Skip to content

Training

negative_log_likelihood is the maximum-likelihood loss of any flow (a flowjax distribution, SurVAEFlow or ClassCondFlow), and fit_gaussianization_flow is a small loop around it with early stopping on a validation split. The docs notebooks train the same loss with pipekit-train, which is a docs dependency only.

The NumPyro bridges, a flow as a NumPyro distribution (flow_to_numpyro), a flow-based SVI guide (FlowGuide) and a NumPyro distribution as a flow base (NumpyroBase), live in pyrox-flows since gauss_flows dropped its numpyro dependency.

negative_log_likelihood

negative_log_likelihood(flow: Any, x: Array, *, key: PRNGKeyArray | None = None, condition: ArrayLike | None = None) -> Array

Mean negative log-likelihood of a batch under a flow.

ℒ(θ) = −(1/B) Σ_b [log p(z_L⁽ᵇ⁾) + Σ_ℓ 𝒱_ℓ⁽ᵇ⁾]

Each 𝒱_ℓ is a log-determinant for a bijection and, for a surjection or an injection, a log-density term that may need a draw; the bound is exact for a chain of bijections. The flow is passed through paramax.unwrap first, so constrained and frozen parameters take their values, and a frozen (paramax.NonTrainable) leaf gets no gradient.

Parameters:

Name Type Description Default
flow Any

A flowjax distribution, a SurVAEFlow or a ClassCondFlow.

required
x Array

A batch of samples, shape (B, *event).

required
key PRNGKeyArray | None

PRNG key for a flow with stochastic layers. A flowjax distribution ignores it; SurVAEFlow and ClassCondFlow require it.

None
condition ArrayLike | None

The condition, shape (B, *cond) or cond broadcast to the batch; the class labels, shape (B,), for a ClassCondFlow.

None

Returns:

Type Description
Array

The scalar mean over the batch.

Raises:

Type Description
ValueError

If the flow needs a key and none was given.

Shape

x: (B, *event); condition: (B, *cond), cond or (B,) labels; output: ().

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from flowjax.distributions import Normal
>>> from gauss_flows_models.inference import negative_log_likelihood
>>> float(negative_log_likelihood(Normal(jnp.zeros(2)), jnp.zeros((4, 2))))
1.837877...
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/inference/train.py
def negative_log_likelihood(
    flow: Any,
    x: Array,
    *,
    key: PRNGKeyArray | None = None,
    condition: ArrayLike | None = None,
) -> Array:
    """Mean negative log-likelihood of a batch under a flow.

        ℒ(θ) = −(1/B) Σ_b [log p(z_L⁽ᵇ⁾) + Σ_ℓ 𝒱_ℓ⁽ᵇ⁾]

    Each 𝒱_ℓ is a log-determinant for a bijection and, for a surjection or an
    injection, a log-density term that may need a draw; the bound is exact for
    a chain of bijections. The flow is passed through `paramax.unwrap` first,
    so constrained and frozen parameters take their values, and a frozen
    (`paramax.NonTrainable`) leaf gets no gradient.

    Args:
        flow: A flowjax distribution, a `SurVAEFlow` or a `ClassCondFlow`.
        x: A batch of samples, shape ``(B, *event)``.
        key: PRNG key for a flow with stochastic layers. A flowjax
            distribution ignores it; `SurVAEFlow` and `ClassCondFlow` require it.
        condition: The condition, shape ``(B, *cond)`` or ``cond`` broadcast to
            the batch; the class labels, shape ``(B,)``, for a `ClassCondFlow`.

    Returns:
        The scalar mean over the batch.

    Raises:
        ValueError: If the flow needs a key and none was given.

    Shape:
        ``x``: ``(B, *event)``; ``condition``: ``(B, *cond)``, ``cond`` or
        ``(B,)`` labels; output: ``()``.

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from flowjax.distributions import Normal
        >>> from gauss_flows_models.inference import negative_log_likelihood
        >>> float(negative_log_likelihood(Normal(jnp.zeros(2)), jnp.zeros((4, 2))))
        1.837877...
    """
    flow = paramax.unwrap(flow)
    if isinstance(flow, AbstractDistribution):
        log_p = flow.log_prob(x, condition)
    else:
        if key is None:
            raise ValueError(
                f"{type(flow).__name__}.log_prob draws from its stochastic layers: "
                "pass key=."
            )
        log_p = _keyed_log_prob(flow, jnp.asarray(x), key, condition)
    return -jnp.mean(log_p)

fit_gaussianization_flow

fit_gaussianization_flow(key: PRNGKeyArray, dist: Any, data: ArrayLike, *, condition: ArrayLike | None = None, optimizer: GradientTransformation | None = None, learning_rate: float = 0.0005, max_epochs: int = 100, max_patience: int = 5, batch_size: int = 256, val_prop: float = 0.1, show_progress: bool = True) -> tuple[Any, dict[str, list[float]]]

Fit a flow to samples by maximum likelihood, with early stopping.

The samples are shuffled once and split into a training set and a validation set. Each epoch reshuffles the training set, drops the last short batch, and takes one optimiser step per batch on negative_log_likelihood; the validation loss is then taken over the whole validation set. Training stops after max_patience epochs without a lower validation loss, and the parameters of the best epoch are returned.

Only the floating-point arrays are trained. A paramax.NonTrainable leaf gets no optimiser state, so it stays fixed under any optimiser (AdamW's weight decay included), and key or integer leaves (FFJORD's trace_key) are left alone.

Parameters:

Name Type Description Default
key PRNGKeyArray

PRNG key for the split, the shuffles and the stochastic layers.

required
dist Any

The flow to fit: a flowjax distribution, a SurVAEFlow or a ClassCondFlow.

required
data ArrayLike

The samples, shape (N, *event).

required
condition ArrayLike | None

The condition of each sample, shape (N, *cond), or the class labels, shape (N,), for a ClassCondFlow.

None
optimizer GradientTransformation | None

An optax optimiser. Defaults to Adam at learning_rate.

None
learning_rate float

Adam's step size when optimizer is not given.

0.0005
max_epochs int

Maximum number of epochs.

100
max_patience int

Epochs without a lower validation loss before stopping.

5
batch_size int

Samples per step, capped at the size of the training set.

256
val_prop float

Fraction of the samples held out for validation.

0.1
show_progress bool

Whether to show a progress bar over the epochs.

True

Returns:

Type Description
Any

(flow, losses): the flow at the epoch with the lowest validation

dict[str, list[float]]

loss, and {"train": [...], "val": [...]} with one mean loss per

tuple[Any, dict[str, list[float]]]

epoch run.

Raises:

Type Description
ValueError

If data and condition disagree on N, or the split leaves the training or the validation set empty.

Shape

data: (N, *event); condition: (N, *cond) or (N,) labels. Each step sees (B, *event) with B = min(batch_size, N_train).

Examples:

>>> import jax.random as jr
>>> from gauss_flows_models.flows import gaussianization_flow
>>> from gauss_flows_models.inference import fit_gaussianization_flow
>>> x = jr.normal(jr.key(0), (512, 2))
>>> flow = gaussianization_flow(jr.key(1), n_dims=2, n_layers=2)
>>> trained, losses = fit_gaussianization_flow(
...     jr.key(2), flow, x, max_epochs=3, show_progress=False
... )
>>> len(losses["train"]) == len(losses["val"]) == 3
True
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/inference/train.py
def fit_gaussianization_flow(
    key: PRNGKeyArray,
    dist: Any,
    data: ArrayLike,
    *,
    condition: ArrayLike | None = None,
    optimizer: optax.GradientTransformation | None = None,
    learning_rate: float = 5e-4,
    max_epochs: int = 100,
    max_patience: int = 5,
    batch_size: int = 256,
    val_prop: float = 0.1,
    show_progress: bool = True,
) -> tuple[Any, dict[str, list[float]]]:
    """Fit a flow to samples by maximum likelihood, with early stopping.

    The samples are shuffled once and split into a training set and a
    validation set. Each epoch reshuffles the training set, drops the last
    short batch, and takes one optimiser step per batch on
    `negative_log_likelihood`; the validation loss is then taken over the
    whole validation set. Training stops after ``max_patience`` epochs without
    a lower validation loss, and the parameters of the best epoch are returned.

    Only the floating-point arrays are trained. A `paramax.NonTrainable` leaf
    gets no optimiser state, so it stays fixed under any optimiser (AdamW's
    weight decay included), and key or integer leaves (FFJORD's ``trace_key``)
    are left alone.

    Args:
        key: PRNG key for the split, the shuffles and the stochastic layers.
        dist: The flow to fit: a flowjax distribution, a `SurVAEFlow` or a
            `ClassCondFlow`.
        data: The samples, shape ``(N, *event)``.
        condition: The condition of each sample, shape ``(N, *cond)``, or the
            class labels, shape ``(N,)``, for a `ClassCondFlow`.
        optimizer: An optax optimiser. Defaults to Adam at ``learning_rate``.
        learning_rate: Adam's step size when ``optimizer`` is not given.
        max_epochs: Maximum number of epochs.
        max_patience: Epochs without a lower validation loss before stopping.
        batch_size: Samples per step, capped at the size of the training set.
        val_prop: Fraction of the samples held out for validation.
        show_progress: Whether to show a progress bar over the epochs.

    Returns:
        ``(flow, losses)``: the flow at the epoch with the lowest validation
        loss, and ``{"train": [...], "val": [...]}`` with one mean loss per
        epoch run.

    Raises:
        ValueError: If ``data`` and ``condition`` disagree on N, or the split
            leaves the training or the validation set empty.

    Shape:
        ``data``: ``(N, *event)``; ``condition``: ``(N, *cond)`` or ``(N,)``
        labels. Each step sees ``(B, *event)`` with ``B = min(batch_size,
        N_train)``.

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows_models.flows import gaussianization_flow
        >>> from gauss_flows_models.inference import fit_gaussianization_flow
        >>> x = jr.normal(jr.key(0), (512, 2))
        >>> flow = gaussianization_flow(jr.key(1), n_dims=2, n_layers=2)
        >>> trained, losses = fit_gaussianization_flow(
        ...     jr.key(2), flow, x, max_epochs=3, show_progress=False
        ... )
        >>> len(losses["train"]) == len(losses["val"]) == 3
        True
    """
    x = jnp.asarray(data)
    n = x.shape[0]
    cond = None if condition is None else jnp.asarray(condition)
    if cond is not None and cond.shape[0] != n:
        raise ValueError(
            f"x has {n} samples but condition has {cond.shape[0]}; they must match."
        )
    n_val = round(val_prop * n)
    n_train = n - n_val
    if n_val < 1 or n_train < 1:
        raise ValueError(
            f"val_prop={val_prop} splits {n} samples into {n_train} for training "
            f"and {n_val} for validation; both need at least one."
        )
    batch_size = min(batch_size, n_train)
    n_batches = n_train // batch_size

    key, split_key = jr.split(key)
    order = jr.permutation(split_key, n)
    x_train, x_val = x[order[:n_train]], x[order[n_train:]]
    c_train = None if cond is None else cond[order[:n_train]]
    c_val = None if cond is None else cond[order[n_train:]]

    if optimizer is None:
        optimizer = optax.adam(learning_rate)
    params, static = eqx.partition(dist, eqx.is_inexact_array, is_leaf=_is_frozen)
    opt_state = optimizer.init(params)

    def batched(a, idx):
        if a is None:
            return None
        return a[idx].reshape(n_batches, batch_size, *a.shape[1:])

    best_params, best_val = params, np.inf
    losses: dict[str, list[float]] = {"train": [], "val": []}
    epochs = tqdm(range(max_epochs), disable=not show_progress)
    for _ in epochs:
        key, perm_key, step_key, val_key = jr.split(key, 4)
        idx = jr.permutation(perm_key, n_train)[: n_batches * batch_size]
        params, opt_state, train_loss = _train_epoch(
            params,
            static,
            opt_state,
            optimizer,
            batched(x_train, idx),
            batched(c_train, idx),
            jr.split(step_key, n_batches),
        )
        val_loss = float(_val_loss(params, static, x_val, c_val, val_key))
        losses["train"].append(float(train_loss))
        losses["val"].append(val_loss)
        epochs.set_postfix({"train": losses["train"][-1], "val": val_loss})
        if val_loss < best_val:
            best_params, best_val = params, val_loss
        elif len(losses["val"]) - 1 - int(np.argmin(losses["val"])) >= max_patience:
            break
    return eqx.combine(best_params, static), losses