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:
objectExponential moving average of a module’s parameters.
Only floating-point parameters are averaged; buffers are left untouched.
- Parameters:
Example:
ema = EMA(flow, 0.999) ...; opt.step(); ema.update() with ema.swap(): # evaluate with averaged weights val = evaluate_nll(flow, x_val)
- class cjd_flows.train.NoiseAugmentation[source]¶
Bases:
objectNoise 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(requiresflow.context_dim >= 1; at test timeflow.default_context = 0selects the clean distribution)."gaussian"(TarFlow-style): fixedx ← x + sigma εwithout context. Usetweedie_denoise()on samples afterwards."curriculum":x ← x + σ(t) εwithσdecaying fromsigma_maxto0over the firstdecay_fracof training (schedule"linear"or"cosine"), no context.
- Parameters:
mode (
str) – see above.sigma (
Optional[float]) – noise level for"gaussian"; also the defaultsigma_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.
- class cjd_flows.train.TrainResult[source]¶
Bases:
objectOutcome of
fit().- train_losses¶
mean training NLL (nats/sample) per epoch (on the noisy data if noise augmentation is used; without the prior term).
- 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), orNonewithout validation data.
- 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_detislog|det ∂y/∂x̃|from the raw (dequantized) datax̃ ∈ [0, n_bins)^Dto model spacey;Noneassumesy = x̃ / n_bins. Seecjd_flows.data.bits_per_dim().
- __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
flowondata.- 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 is0for clean data.flow (Module)
data (Tensor | Dataset | DataLoader)
batch_size (int)
context (Tensor | None)
batch_context (bool)
- Return type:
- 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
flowby maximum likelihood (or MAP).- Parameters:
flow (
Module) – acjd_flows.core.Flow(anything withlog_prob(x[, context])).train_data (
Union[Tensor,Dataset,DataLoader]) – tensor(N, *event),TensorDataset, anyDatasetreturning a tensor or an(x, label, ...)tuple, or aDataLoader.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 withdim >= 2.weight_decay (
float) – optimizer settings. Weight decay only applies to parameters withdim >= 2.betas (
Tuple[float,float]) – optimizer settings. Weight decay only applies to parameters withdim >= 2.optimizer (
Union[str,Callable[[Sequence[Parameter]],Optimizer]]) –"adamw","adam","sgd"orcallable(params) -> Optimizer.warmup_steps (
Optional[int]) – linear warmup steps (overrideswarmup_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 oflr(cosine/linear).grad_clip (
Optional[float]) – max gradient norm (Nonedisables 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 thatgrad_clipdoes not depend on the data dimension.ema_decay (
Optional[float]) – EMA decay (Nonedisables EMA). Validation uses the EMA weights.early_stopping_patience (
Optional[int]) – stop after this many epochs without validation improvement (requiresval_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"(orTrue) or"fp16"autocast.compile (
bool) – wrap the flow withtorch.compilefor the training forward pass.noise (
Optional[NoiseAugmentation]) – aNoiseAugmentation(soft training / noise augmentation).batch_context (
bool) – pass the second element of(x, c)batches as context.prior_weight (
Optional[float]) – weight oflog_prior()terms exposed by the flow’s (sub)modules; the prior is scaled by1/N_trainso that the objective is the per-sample MAP objective.None= 1.0 if such modules exist;0disables.max_nonfinite (
int) – abort after this many consecutive non-finite steps.val_batch_size (
Optional[int]) – batch size for validation (defaultmax(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); returningTruestops training.
- Return type:
- 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()(Nonemeans the model data isx̃ / n_bins ∈ [0, 1)^D).