cjd_flows.train

Maximum-likelihood training of CJD flows.

fit() is a compact but complete trainer: AdamW with linear warmup and cosine decay, gradient clipping, EMA weights, validation with early stopping, non-finite step protection, optional AMP / torch.compile, MAP priors and noise augmentation (SoftFlow-style “soft training”, fixed Gaussian noise as in TarFlow, or a decaying noise curriculum).

Losses are reported as mean negative log-likelihood in nats per sample; use TrainResult.bits_per_dim() or nats_to_bits_per_dim() to convert.

class cjd_flows.train.EMA[source]

Bases: object

Exponential moving average of a module’s parameters.

Only floating-point parameters are averaged; buffers are left untouched.

Parameters:
  • module (Module) – the module whose parameters are tracked.

  • decay (float) – EMA decay β (shadow ← β·shadow + (1−β)·param).

  • warmup (bool) – use the effective decay min(β, (1+n)/(10+n)) for the first updates so that early (random) weights are forgotten quickly.

Example:

ema = EMA(flow, 0.999)
...; opt.step(); ema.update()
with ema.swap():          # evaluate with averaged weights
    val = evaluate_nll(flow, x_val)
__init__(module, decay=0.999, warmup=True)[source]
Parameters:
update()[source]

Updates the shadow parameters from the current module parameters.

Return type:

None

copy_to(module=None)[source]

Writes the averaged parameters into module (default: the tracked module).

Return type:

None

Parameters:

module (Module | None)

swap()[source]

Context manager that temporarily loads the EMA weights into the module.

class cjd_flows.train.NoiseAugmentation[source]

Bases: object

Noise augmentation / soft training of flows.

Modes:
  • "soft" (SoftFlow, Kim et al. 2020): per-sample σ ~ U(0, sigma_max), x ← x + σ ε and the flow is conditioned on σ / sigma_max (requires flow.context_dim >= 1; at test time flow.default_context = 0 selects the clean distribution).

  • "gaussian" (TarFlow-style): fixed x ← x + sigma ε without context. Use tweedie_denoise() on samples afterwards.

  • "curriculum": x ← x + σ(t) ε with σ decaying from sigma_max to 0 over the first decay_frac of training (schedule "linear" or "cosine"), no context.

Parameters:
  • mode (str) – see above.

  • sigma (Optional[float]) – noise level for "gaussian"; also the default sigma_max.

  • sigma_max (Optional[float]) – maximal noise level for "soft" / "curriculum".

  • decay_frac (float) – fraction of the total steps over which the curriculum decays.

  • schedule (str) – curriculum shape.

__init__(mode='soft', sigma=None, sigma_max=None, decay_frac=0.5, schedule='cosine')[source]
Parameters:
current_sigma(step, total_steps)[source]

Noise level of the "gaussian"/"curriculum" modes at step.

Return type:

float

Parameters:
  • step (int)

  • total_steps (int)

class cjd_flows.train.TrainResult[source]

Bases: object

Outcome of fit().

train_losses

mean training NLL (nats/sample) per epoch (on the noisy data if noise augmentation is used; without the prior term).

Type:

List[float]

val_losses

mean validation NLL per evaluation (clean data).

Type:

List[float]

best_val_loss, best_epoch

best validation loss and its epoch (1-based).

best_state

state_dict (on CPU) of the best weights (EMA weights if EMA is enabled), or None without validation data.

Type:

Optional[Dict[str, Tensor]]

steps

number of optimizer steps taken.

Type:

int

epochs

number of (partial) epochs run.

Type:

int

wall_time

seconds.

Type:

float

skipped_steps

steps skipped because of non-finite loss/gradients.

Type:

int

stopped_early

early stopping triggered.

Type:

bool

aborted

training stopped after too many consecutive non-finite steps.

Type:

bool

restored

which weights the flow holds after training.

Type:

str

step_losses

(step, loss) pairs logged every log_every steps.

Type:

List[Tuple[int, float]]

bits_per_dim(dim, preprocessing_log_det=None, which='val', n_bins=256)[source]

Converts the recorded losses (which = "val" or "train") to bits/dim.

preprocessing_log_det is log|det ∂y/∂x̃| from the raw (dequantized) data x̃ ∈ [0, n_bins)^D to model space y; None assumes y = x̃ / n_bins. See cjd_flows.data.bits_per_dim().

Return type:

List[float]

Parameters:
  • dim (int)

  • preprocessing_log_det (float | None)

  • which (str)

  • n_bins (int)

__init__(train_losses=<factory>, val_losses=<factory>, best_val_loss=None, best_epoch=None, best_state=None, steps=0, epochs=0, wall_time=0.0, skipped_steps=0, stopped_early=False, aborted=False, restored='last', step_losses=<factory>)
Parameters:
Return type:

None

cjd_flows.train.evaluate_nll(flow, data, batch_size=1024, device=None, context=None, batch_context=False, amp=False, pad_context=0)[source]

Mean negative log-likelihood (nats per sample) of flow on data.

Parameters:
  • pad_context (int) – number of zero columns appended to contexts taken from the batches (batch_context=True). Soft-trained conditional flows use one extra column for the noise level, which is 0 for clean data.

  • flow (Module)

  • data (Tensor | Dataset | DataLoader)

  • batch_size (int)

  • device (str | device | None)

  • context (Tensor | None)

  • batch_context (bool)

  • amp (bool | str)

Return type:

float

cjd_flows.train.fit(flow, train_data, val_data=None, *, epochs=10, batch_size=128, lr=1e-3, weight_decay=0.0, optimizer='adamw', betas=(0.9, 0.95), warmup_steps=None, warmup_frac=0.02, schedule='cosine', min_lr_ratio=0.0, grad_clip=1.0, scale_lr_mult=10.0, normalize_loss=True, ema_decay=None, early_stopping_patience=None, max_steps=None, restore='best', device=None, num_workers=0, amp=False, compile=False, noise=None, batch_context=False, prior_weight=None, max_nonfinite=20, val_batch_size=None, log_every=None, verbose=False, callback=None, seed=None)[source]

Trains flow by maximum likelihood (or MAP).

Parameters:
  • flow (Module) – a cjd_flows.core.Flow (anything with log_prob(x[, context])).

  • train_data (Union[Tensor, Dataset, DataLoader]) – tensor (N, *event), TensorDataset, any Dataset returning a tensor or an (x, label, ...) tuple, or a DataLoader.

  • val_data (Union[Tensor, Dataset, DataLoader, None]) – same types; evaluated after every epoch (clean data, no noise).

  • epochs (int) – number of epochs.

  • batch_size (int) – batch size (ignored for DataLoaders).

  • lr (float) – optimizer settings. Weight decay only applies to parameters with dim >= 2.

  • weight_decay (float) – optimizer settings. Weight decay only applies to parameters with dim >= 2.

  • betas (Tuple[float, float]) – optimizer settings. Weight decay only applies to parameters with dim >= 2.

  • optimizer (Union[str, Callable[[Sequence[Parameter]], Optimizer]]) – "adamw", "adam", "sgd" or callable(params) -> Optimizer.

  • warmup_steps (Optional[int]) – linear warmup steps (overrides warmup_frac).

  • warmup_frac (float) – warmup as a fraction of the total number of steps.

  • schedule (str) – "cosine", "linear" or "constant" after warmup.

  • min_lr_ratio (float) – final lr as a fraction of lr (cosine/linear).

  • grad_clip (Optional[float]) – max gradient norm (None disables clipping).

  • scale_lr_mult (float) – learning-rate multiplier for scalar parameters (e.g. the flow’s global scale) and the base-distribution parameters. These have to follow the latent variance as the couplings learn; with a plain Adam step size they throttle training for thousands of steps.

  • normalize_loss (bool) – backpropagate the NLL in nats per dimension, so that grad_clip does not depend on the data dimension.

  • ema_decay (Optional[float]) – EMA decay (None disables EMA). Validation uses the EMA weights.

  • early_stopping_patience (Optional[int]) – stop after this many epochs without validation improvement (requires val_data).

  • max_steps (Optional[int]) – hard limit on optimizer steps (also sets the schedule length).

  • restore (str) – weights to keep at the end: "best" (best validation; falls back to "ema"/"last" without validation data), "last" or "ema".

  • device (Union[str, device, None]) – training device (default: the flow’s device). The flow is moved there.

  • num_workers (int) – DataLoader workers for generic datasets.

  • amp (Union[bool, str]) – False, "bf16" (or True) or "fp16" autocast.

  • compile (bool) – wrap the flow with torch.compile for the training forward pass.

  • noise (Optional[NoiseAugmentation]) – a NoiseAugmentation (soft training / noise augmentation).

  • batch_context (bool) – pass the second element of (x, c) batches as context.

  • prior_weight (Optional[float]) – weight of log_prior() terms exposed by the flow’s (sub)modules; the prior is scaled by 1/N_train so that the objective is the per-sample MAP objective. None = 1.0 if such modules exist; 0 disables.

  • max_nonfinite (int) – abort after this many consecutive non-finite steps.

  • val_batch_size (Optional[int]) – batch size for validation (default max(batch_size, 1024)).

  • log_every (Optional[int]) – log the running training loss every this many steps.

  • verbose (bool) – print one line per epoch.

  • callback (Optional[Callable[[Dict[str, Any]], Optional[bool]]]) – called after every epoch with a dict (epoch, step, train_loss, val_loss, lr, flow); returning True stops training.

  • seed (Optional[int]) – random seed.

Return type:

TrainResult

Returns:

A TrainResult.

cjd_flows.train.nats_to_bits_per_dim(nll_nats, dim, preprocessing_log_det=None, n_bins=256)[source]

(nll − log|det ∂y/∂x̃|) / (D ln 2) (nll in nats per sample).

Same convention as cjd_flows.data.bits_per_dim() (None means the model data is x̃ / n_bins ∈ [0, 1)^D).

Parameters:
cjd_flows.train.tweedie_denoise(flow, x, sigma, context=None)[source]

Tweedie / score-based denoising x + σ² ∇_x log p(x).

Needs one backward pass. For CJD flows the log-det term has zero gradient w.r.t. x, so the score is J_f(x)^T ∇ log p_Z(f(x)).

Parameters:
  • flow (Module) – a flow with log_prob(x, context), trained on σ-noisy data.

  • x (Tensor) – noisy samples.

  • sigma (float) – noise level (for soft-trained flows pass the matching context = σ / σ_max).

  • context (Optional[Tensor]) – optional context.

Return type:

Tensor