Skip to content

Programs

The programs module executes what the rest of the package builds. Training and inference are both stages in a program that organizes them in list.

Note

Nothing in programs imports hydra, but every constructor is fully keyword-constructible so a program can be written as a config file and instantiated from one.

The pipelining concepts

  1. A Program is a list of stages.
  2. A stage is either a one-shot StageBlock or an iterative StageLoop — Train, Eval, Predict.
  3. A Phase is a stage that contains stages, so sub-stages can nest, repeat, or conditionally trigger.
  4. Runner runs the program, handing each stage a Context carrying its position, its randomness and the shared objects.
  5. Everything that happens is a run Event signal; Hooks watch events and can checkpoint, log, or stop the run.

Minimal example

Runner takes any stage, and a single stage needs no wrapper. Defaults fill in the rest: optim="adamw", lr=1e-4 and hooks=[Console()]. A step with non-finite gradients stops the run; Train(nonfinite=...) chooses otherwise.

Runner(Train(model=unet, data=train_ds, loss=nn.MSELoss(), epochs=10)).run()

Denoising Diffusion Training

examples/programs_diffusion.py refines a coarse image into a fine one with a DDPM. It is the reference for conditional sampling: the model never sees the target directly, only the condition.

The data is paired, and return_as gives each half the name every stage reads it by — "x" for the samples, "c" for the condition. Those names are what inputs=, targets= and condition= refer to later.

import sys
import tempfile
from pathlib import Path
import torch
from torch import nn
from chuchichaestli.data import ConditionalDensityDataset, HalfMoonsDataset
from chuchichaestli.data.split import split_dataset
from chuchichaestli.diffusion.processes import DDPM
from chuchichaestli.metrics import FID, PSNR, SSIM
from chuchichaestli.models.unet import UNet
from chuchichaestli.programs import (
    Checkpointer,
    Console,
    Eval,
    EventType,
    Every,
    Diffusion,
    FromProcess,
    ImageExport,
    Predict,
    Program,
    ProgressBar,
    Timer,
    Runner,
    Jsonl,
    Phase,
    Train,
)
from chuchichaestli.training import OptimSpec, Term

STORE = Path(tempfile.mkdtemp()) / "store"
torch.manual_seed(42)

# Create an image dataset of half moons, each paired with a coarse copy
pairs = ConditionalDensityDataset(
    source=HalfMoonsDataset,
    n_images=64,
    side=32,
    points=16384,
    noise=0.05,
    return_as={"x": 0, "c": 1},
)
dataset, validation = split_dataset(pairs, (0.8, 0.2))

The process is a separate object from the model. The U-Net takes in_channels=2 because sample and condition arrive concatenated, and time_embedding=True because a denoiser is timestep-conditioned; DDPM owns the noise schedule and the reverse loop.

# Build a U-Net denoising diffusion model...
model = UNet(
    dimensions=2,
    in_channels=2,
    out_channels=1,
    n_channels=16,
    down_block_types=("DownBlock", "DownBlock"),
    up_block_types=("UpBlock", "UpBlock"),
    block_out_channel_mults=(1, 2),
    res_groups=8,
    time_embedding=True,
)
# ...using a standard DDPM sampler
process = DDPM(num_timesteps=200, device="cpu")

Four stages, each handing the next one something by name.

Train fits on two Diffusion terms sharing one process at different weights; Diffusion(process, condition="c") scores a noise prediction.

Predict samples. draw=FromProcess(process) replaces the plain single noise prediction step with the iterative reverse loop (sampling costs 200 model calls, training one), and weights="ema" reads the averaged shadow weights (Train(ema=0.99) publishes as "model/ema") rather than the live parameters. It publishes what it generated beside the ground truths as "sample/pairs".

Eval scores those pairs. model=None because the predictions already exist — it reads them instead of running anything — and each metric is published as "score/<name>", which a later When could branch on.

ImageExport writes the same pairs out, one file per image, numbered by the epoch the run had reached.

EPOCHS = 128

# Training stage using a custom objective (MSE + 0.1 x MAE)
training = Train(
    "train_denoising",
    model="model",
    data=dataset,
    batch_size=16,
    epochs=EPOCHS,
    objective=[
        Term("mse", Diffusion(process, condition="c")),
        Term("mae", Diffusion(process, condition="c", loss=nn.L1Loss()), weight=0.1),
    ],
    optim=OptimSpec.adamw(lr=1e-3).with_cosine_schedule(t_max=EPOCHS),
    ema=0.99,
)

# Samples the diffusion model from the ema weights that `Train` published,
# rather than the live ones, and publishes sample/pairs (predictions with GTs);
# `weights="model"` (default) would read the live parameters instead
sampling = Predict(
    "sample",
    model="model",
    weights="ema",
    draw=FromProcess(process),
    data=validation,
    batch_size=len(validation),
    inputs="c",
    targets="x",
)

# Runs evaluation on published (predictions with GTs)
scoring = Eval(
    "score",
    model=None,
    data="sample/pairs",
    batch_size=len(validation),
    metrics=[PSNR(), SSIM(), FID()],
)

# Plots the same published pairs, one file per image, per epoch via `{epoch}`
preview = ImageExport(
    "preview",
    path=STORE / "samples_ema_{epoch:02d}.png",
    source="sample/pairs",
    labels=("sampled", "gt"),
    limit=4,
    cmap="magma",
    normalize="shared",
)

Phase.each_pass slots the other stages between the training passes (epochs), and Every(n, ...) runs them on every nth epoch.

# Compose a program with training and validation stage...
program = Program(
    provide={"model": model},
    stages=[
        Phase.each_pass(
            EPOCHS,
            training,
            Every(32, Phase("score", [sampling, scoring, preview])),
        )
    ],
)

Runner runs the program with a set of hooks.

# ...and run it with multiple hooks
Runner(
    program,
    hooks=[
        Console(every=1, timing=True),
        Timer(stream=sys.stdout, depth=1),
        ProgressBar(unit="epoch"),
        Jsonl("trace.jsonl"),
        Checkpointer(every=32, unit="epoch", keep=2),
    ],
    store=STORE,
    device="cpu",
).run()

The hooks are reporting on the stages. Console prints a line each step/pass, Timer measures how long each stage took and reports once at the end, and ProgressBar pins a bar for the epochs to the bottom line. Jsonl appends every event to a trace (Jsonl.read gets them back as Events), and Checkpointer writes the run's state every nth epoch, keeping the last keep. All of them are optional, hooks=[] would run the same program in silence.

Checkpointer(monitor="mse", mode="min") also writes a checkpoint whenever the monitored value improves, reading it as EarlyStop does, e.g. the metric an Eval stage reports as it ends. Each checkpoint records the value it was measured at, the best one is never pruned, and resume="best" or CheckpointStore(root).load("best") reads it back.

Adversarial Training

examples/programs_gan.py fits the same task with a Pix2Pix GAN. It is the reference for two models trained against each other in one stage. It reads the same data, scores and previews its samples the same way and runs with the same hooks as the diffusion example, so only what differs is shown here, starting with the imports.

from chuchichaestli.models.adversarial.discriminator import PatchDiscriminator
from chuchichaestli.programs import (
    Alternating,
    Criterion,
    DiscriminatorAdv,
    GeneratorAdv,
)
from chuchichaestli.training import AdaptiveWeight

Two models, so the program binds two names. The generator maps one channel to one; the discriminator takes in_channels=2 because it scores the condition joined to a sample.

# Build a U-Net generator mapping a coarse image to a fine one...
model = UNet(
    dimensions=2,
    in_channels=1,
    out_channels=1,
    n_channels=16,
    down_block_types=("DownBlock", "DownBlock"),
    up_block_types=("UpBlock", "UpBlock"),
    block_out_channel_mults=(1, 2),
    res_groups=8,
)
# ...and a PatchGAN discriminator for adversarial scoring
disc = PatchDiscriminator(
    dimensions=2,
    in_channels=2,
    n_channels=16,
    n_hidden=2,
)

A GAN is one Train stage with two update groups. Each Term names the groups it feeds, Alternating steps them in turn, and each optimizer owns the parameters its params= names — which is how one stage trains two models without either optimizer touching the other's weights. Predict runs the generator once per batch, so it needs no draw=.

EPOCHS = 32

# Training stage using the Pix2Pix objective (weighted L1 + adversarial), the
# adversarial term weighed against L1's gradient at the generator's last layer.
# Both take the same `variant` ("bce", "hinge", "least_squares", "wasserstein").
training = Train(
    "train_pix2pix",
    model="model",
    data=dataset,
    batch_size=16,
    epochs=EPOCHS,
    objective=[
        Term(
            "l1",
            Criterion(nn.L1Loss(), inputs="c", targets="x"),
            weight=10.0,
            groups=("gen",),
        ),
        # Only the discriminator half scores a real sample, so only it takes
        # targets=; the generator half scores what it produced and nothing else
        Term(
            "gen",
            GeneratorAdv(inputs="c", condition="c", variant="bce"),
            weight=AdaptiveWeight(ref="l1", layer="out_block.conv.weight"),
            groups=("gen",),
        ),
        Term(
            "disc",
            DiscriminatorAdv(inputs="c", targets="x", condition="c", variant="bce"),
            groups=("disc",),
        ),
    ],
    optim={
        "gen": OptimSpec.adam(lr=2e-4, params="model", betas=(0.5, 0.999)),
        "disc": OptimSpec.adam(lr=2e-4, params="disc", betas=(0.5, 0.999)),
    },
    update=Alternating(("disc", "gen")),
    ema=0.99,
)

# Runs the generator and publishes sample/pairs (predictions with GTs)
sampling = Predict(
    "sample",
    model="model",
    weights="model",
    data=validation,
    batch_size=len(validation),
    inputs="c",
    targets="x",
)

Adversarial and its two halves read the batch the way the rest of the objectives do: inputs= is what the generator is given, targets= is what counts as a real sample, and condition= is joined channel-wise to every sample so the discriminator scores the pair.

variant= picks which pair of losses the two halves minimize: "bce" (the default, in its non-saturating form), "hinge", "least_squares" or "wasserstein". The two halves are separate terms, each with its own variant= (so give both the same one). Note that "wasserstein" only estimates a distance while its critic stays Lipschitz, which nothing here enforces: no weight clipping, no gradient penalty.

The adversarial term carries an AdaptiveWeight instead of a number, the other feature unique to this example. It balances its own gradient against the reference term's at a named parameter, so the ratio tracks training instead of being guessed once: over this run it moves from about 5 to 0.005 as the L1 term converges and the adversarial one grows.

The program provides both models by name; the phases are the diffusion example's.

# Compose a program with training and validation stage...
program = Program(
    provide={"model": model, "disc": disc},
    stages=[
        Phase.each_pass(
            EPOCHS,
            training,
            Every(8, Phase("score", [sampling, scoring, preview])),
        )
    ],
)

Context bindings

model=, data= and friends accept the object or a str naming a Context binding. That is what lets several stages share models, and what enables configuration through frameworks like hydra.

program = Program(
    provide={"model": unet},
    stages=[
        Train("pretrain", data=train_ds, loss=mse, epochs=20, ema=0.9999),
        Repeat(3, Phase("cycle", [
            Finetune("refine", data=ft_ds, epochs=1, lr=1e-5),
            Eval("validate", data=val_ds, metrics=[PSNR(), SSIM()]),
        ])),
        When(lambda ctx: ctx["validate/psnr"] > 30,
             Predict("sample", data=test_ds, weights="ema", archive="out/preds.h5")),
    ],
)

Eval publishes each metric as f"{stage}/{key}", which is what ctx["validate/psnr"] resolves against. Train(ema=...) publishes its shadow weights as f"{binding}/ema", so weights="ema" reads them in a later stage and restores the live parameters afterwards.

Resuming

A run resumed from a checkpoint behaves identically to one that was never interrupted: the same weights to the bit, the same optimizer and schedule state, and the same trace.

Runner(
    program,
    store=STORE,
    resume="last~2",
    hooks=[Jsonl("second.jsonl")],
    device="cpu",
).run()

resume= takes "last", "last~N" for N checkpoints earlier, "first", an index, "best" for the best-scored one, or a path to one. A run that finished records no stage state — a Phase saves only the child it is in the middle of — so resuming its last checkpoint does nothing. To carry on training from finished weights, Load them into a Finetune stage instead, which starts an optimizer of its own.

A run is stopped without losing work by GracefulStop(), which turns a scancel, a job time limit or a Ctrl-C into a stop, and by CancelAfter(steps=, epochs=, seconds=), which stops once a budget is spent. Both finish the program step in progress and raise C3liRunCancelled, so a Checkpointer writes a whole final state and resuming it carries on exactly there. CancelAfter counts from the start of each run, so a resumed job gets a budget of its own: a long run split across jobs that each stay within a time limit is hooks=[GracefulStop(), CancelAfter(seconds=3.5 * 3600), Checkpointer()], resumed with resume="last" until it finishes.

Randomness is derived from (seed, stage path) rather than replayed, so the result does not depend on where a run was interrupted, how many dataloader workers it used, or how many processes it ran across. Each batch is loaded under a seed of its own, derived from the epoch and its samples' indices, so a transform drawing from torch's, numpy's or python's global generator augments it the same way whichever worker loads it. SeededBatches does the same for a plain DataLoader.

Bitwise on CPU, and on GPU only under backends="strict"

Derived randomness guarantees identical inputs on resume. It cannot guarantee identical outputs on a GPU, where cuDNN autotuning and atomic accumulation in some backward kernels vary between runs.

Running across several processes

torchrun --nproc_per_node=4 train.py needs no code change: Runner picks Ddp when RANK and WORLD_SIZE are set and Local otherwise.

Every control decision is agreed across ranks before it takes effect, so a hook that stops the run on one rank stops it on all of them rather than leaving the others blocked. Metrics are combined before an Eval publishes them, only the main rank writes checkpoints, and a Predict writes one shard per rank and joins them when the run ends.

Compiling

Runner(program, compile=True) compiles every module the run holds with torch.compile, and compile=("model",) only the bindings named; compile_kwargs reaches torch.compile (mode, backend, fullgraph). A module is compiled after the topology wraps it, so under torchrun it becomes torch.compile(DDP(model)), which lets torch split the graph at DDP's gradient buckets. Checkpoints and exports name a compiled module's weights as a plain one's, so a run compiled for training resumes, evaluates or exports uncompiled, and the other way round.

Archives

Predict(archive=...) picks its writer from the suffix. Formats that can be appended to stream as the batches arrive; the rest are held until the file is written.

suffix written by streams
.h5, .hdf, .hdf5, .he5 Hdf5Archive yes
.npy NpyArchive yes
.safetensors SafetensorsArchive yes
.npz BufferedArchive no

Exports and previews

Exporter is the shared half of writing something out: the binding it reads, the path, the rank-0 guard and the atomic write. What the concrete stages do with the file is all that separates them.

stage writes kind suffix picks
WeightsExport a binding's state_dict, with its model spec when it records one, atomically weights .safetensors, .pt, .pth
ImageExport one file per image image .png, .jpg, .jpeg, .webp, .tif, .tiff, .pdf, .svg
ArchiveExport samples, and their truths beside them tensor any suffix under Archives

A model spec is every argument the model was constructed with, so anyone holding the weights file, or a checkpoint, can read them: paths, tensors and device names included.

Every export is announced with an EXPORTED event carrying the files written, their kind and the source binding, identical on every rank. A Predict(archive=...) announces its archive the same way as it ends, with kind tensor, and a Checkpointer each checkpoint it writes, with kind checkpoint, so hooks such as Jsonl see every file a run leaves.

A path with an {epoch}, {step}, {advance} or {name} field numbers the exports by where the run had got to, so a stage entered every few epochs leaves its own files rather than overwriting the last ones. An inference pass is not an epoch: Predict and Eval loops report trains=False, so only a loop that updates the model moves the epoch and step counters. Checkpointer(unit=...) counts the same way. A checkpoint records the counters, so a resumed run carries on numbering where it stopped.

ImageExport(
    "preview",
    path=STORE / "samples_{epoch:02d}.png",
    source="sample/pairs",
    labels=("sampled", "gt"),
    limit=4,
    cmap="magma",
    normalize="shared",
)

ImageExport reads whatever save_images accepts, which includes the "<stage>/pairs" a Predict publishes: one row per batch, predictions in one, their truths in the next. Each image becomes its own file, named after the target's stem, its row and its place in that row, so preview_{epoch:02d}.png with two labelled rows writes preview_08_sampled_0.png, preview_08_ground-truth_0.png, and so on. The {epoch} field is the exporter's; the rest of the name is save_images'.

Single-channel, RGB and RGBA are all written. Raw pixels go through torchvision alone, and matplotlib takes over as soon as a colormap, a label, a title, a vector format or a draw closure asks for more than pixels.

draw is handed the axes and the image in [0, 1], and owns both: ticks, spines, axis labels, a legend and a colorbar are all its to set, and ax.get_figure() reaches the figure.

def contours(ax, image):
    shown = ax.contourf(image[0].numpy(), levels=8, cmap="magma")
    ax.set_xlabel("x [px]")
    ax.get_figure().colorbar(shown, ax=ax).set_label("density")

ImageExport("preview", path="runs/preview_{epoch}.pdf", source="sample/pairs",
            draw=contours, labels=("sampled", "ground truth"))

Each canvas takes its aspect from the image on it, so a 3:1 image is written 3:1 rather than adrift in a square. size sets the inches along the longer side — mixed aspects still share a bounding box — and pad the margin around it.

Everything past path and source is handed straight to save_images, the way OptimSpec.kwargs reaches the optimizer: limit chooses what is written, normalize scales it, labels and title name it, size and pad shape the canvas, and draw hands the drawing itself back to you.

Experiment trackers

A tracker is a hook like any other: adding one to hooks=[...] logs an existing program as it is, with no change to its stages. The diffusion example above, sent to TensorBoard as well:

Runner(
    program,
    hooks=[
        Console(every=1, timing=True),
        Timer(stream=sys.stdout, depth=1),
        ProgressBar(unit="epoch"),
        Jsonl("trace.jsonl"),
        Checkpointer(every=32, unit="epoch", keep=2),
        TensorBoard(),
    ],
    store=STORE,
    device="cpu",
).run()

Three backends ship with the package, each behind its own extra:

tracker install where runs go by default
TensorBoard() chuchichaestli[tensorboard] <store>/tensorboard/<project>/<experiment>/<run_name>
Wandb(entity=..., mode=...) chuchichaestli[wandb] your W&B account; mode="offline" keeps it local
MLflow(tracking_uri=...) chuchichaestli[mlflow] one SQLite file, <store>/mlflow.db

examples/programs_tensorboard.py, programs_wandb.py and programs_mlflow.py each log a run entirely locally. They read the diffusion example's data, but train a small convolutional upsampler, which takes well under a minute on a CPU.

EPOCHS = 16
BATCH = 4
STEPS_PER_PASS = math.ceil(len(dataset) / BATCH)

# A small convolutional upsampler
model = nn.Sequential(
    nn.Conv2d(1, 16, 5, padding=2),
    nn.ReLU(),
    nn.Conv2d(16, 16, 5, padding=2),
    nn.ReLU(),
    nn.Conv2d(16, 1, 5, padding=2),
)

# Train a pass, score it, and preview a few upsampled images
train = Train(
    "train",
    data=dataset,
    batch_size=BATCH,
    objective=Criterion(nn.MSELoss(), inputs="c", targets="x"),
    optim=OptimSpec.adamw(lr=3e-3).with_cosine_schedule(t_max=EPOCHS),
)
evaluate = Eval(
    "eval",
    data=validation,
    batch_size=BATCH,
    inputs="c",
    targets="x",
    metrics=[MSE()],
)
sample = Predict(
    "sample",
    data=Subset(validation, range(4)),
    batch_size=4,
    inputs="c",
    targets="x",
)
preview = ImageExport(
    "preview",
    path=STORE / "previews" / "upsampled_{epoch:02d}.png",
    source="sample/pairs",
    labels=("upsampled", "fine"),
)
program = Program(
    provide={"model": model},
    stages=[Phase.each_pass(EPOCHS, train, evaluate, sample, preview)],
)

The run is stopped halfway by CancelAfter and resumed, so the backend shows how a resumed run carries on.

# Stop halfway, as a job's time limit would, then resume where it stopped
halfway = CancelAfter(steps=STEPS_PER_PASS * EPOCHS // 2)
for resume, budget in ((None, [halfway]), ("last", [])):
    try:
        Runner(
            program,
            hooks=[
                Console(every=STEPS_PER_PASS),
                Checkpointer(every=1, unit="epoch", monitor="mse"),
                TensorBoard(),
                *budget,
            ],
            store=STORE,
            device="cpu",
            project="chuchichaestli-examples",
            experiment="upsample",
            run_name="tensorboard",
            resume=resume,
        ).run()
    except C3liRunCancelled as stopped:
        print(f"\n{stopped}; resuming from where it stopped\n")

The three scripts differ only in the tracker, and each prints how to look at the result.

from chuchichaestli.programs import TensorBoard

TensorBoard(),
from chuchichaestli.programs import Wandb

Wandb(mode="offline", artifacts=("image", "checkpoint")),
from chuchichaestli.programs import MLflow

MLflow(
    artifacts=("image", "checkpoint"),
    checkpoint_uploads="last",
    config={"lr": 3e-3, "epochs": EPOCHS},
),

The runner names the run once (project=, experiment=, run_name=; a run_name is drawn when you give none) and every tracker files it under those names, so switching backends renames nothing. A run resumed from a checkpoint continues the same backend run, on the same step axis.

What is logged is a TrackingPolicy. By default that is each training step's losses, rate and gradient norm, each pass's duration, throughput and peak memory, each stage's closing scores (eval/mse), a config of the run (its seed, every stage's settings, the models' specs and sizes, versions, device and the repository's commit, with a dirty repository's diff as git.patch), a record of each checkpoint, and the images and archives the exporters write. Weights and checkpoints are uploaded only when asked for. Any field can be changed in place, a preset named, or one policy shared:

TensorBoard(every=10, memory=False)           # fields changed in place
Wandb(log="full")                             # everything, checkpoints included
MLflow(log="minimal", config={"lr": 1e-3})    # the curves, the outcome, your config
policy = TrackingPolicy(artifacts=("image", "checkpoint"), checkpoint_uploads="best")
hooks = [TensorBoard(log=policy), MLflow(log=policy)]

Only the main process logs. A tracker whose backend fails is dropped with a warning rather than ending the run, and how a run ended (finished, failed or cancelled) is the last thing each one records. The repository's commit is read without GitPython too; whether it is dirty, and its diff, need chuchichaestli[git].