A Coding Guide to Google Research’s Kauldron: Configs That Are Plain Data, Components Wired by String, and a JAX Trainer You Can Read End to End
In this tutorial, we implement Kauldron, the JAX training library from Google Research that describes itself as optimized for research velocity and modularity, and we take those two words literally by testing what they actually buy us. We install it, then spend the first half of the notebook on the three mechanisms that make Kauldron different from a stack of Flax and Optax: konfig, which turns an experiment into a tree of plain dictionaries that round-trip through JSON; kontext, which wires components together with string key paths so a loss never imports the model it scores; and the runtime shape checker, whose named axes bind across arguments and report what they were bound to when something does not match. We then write a custom loss and a custom metric in the shape the framework expects, train a real Trainer on synthetic in-memory data with no download and no accelerator, and monitor an inner layer of the model without editing the model. We finish by running a five-variant sweep in which every experiment differs by one config line, and by letting a training run checkpoint itself and resume where it stopped. Copy CodeCopiedUse a different Browser import os import sys import json import textwrap import traceback import subprocess RESULTS = {} def banner(title): print(“n” + “=” * 78) print(title) print(“=” * 78) def section(name): def wrap(fn): def run(*a, **kw): banner(name) try: out = fn(*a, **kw) RESULTS[name] = out if isinstance(out, str) else “ok” return out except Exception as e: RESULTS[name] = f”SKIPPED / FAILED -> {type(e).__name__}: {e}” print(f”n[!] {name} did not complete: {type(e).__name__}: {e}”) traceback.print_exc(limit=3) return None return run return wrap banner(“0. Install Kauldron, and the one compatibility patch you need today”) subprocess.run([sys.executable, “-m”, “pip”, “install”, “-q”, “kauldron==1.4.2”], check=True) import jax from etils.enp import array_spec as _array_spec # jax >= 0.10.1 moved `jax._src.prng`, but etils <= 1.14.0 still reaches for it whenever it # inspects an array’s dtype. Kauldron calls that code on every batch, so without this two-line # patch a Trainer raises AttributeError before it finishes a single step. The replacement uses # jax’s own public dtype API and is a no-op on older jax. if not hasattr(jax._src, “prng”): _array_spec._is_jax_random_dtype = lambda dt: jax.dtypes.issubdtype(dt, jax.dtypes.prng_key) import numpy as np import optax import flax from flax import linen as nn import kauldron from kauldron import kd, konfig, kontext from kauldron.typing import Float, typechecked print(f” kauldron {kauldron.__version__} | jax {jax.__version__} | flax {flax.__version__}” f” | optax {optax.__version__}”) print(f” devices: {jax.devices()}”) print(“n Kauldron’s pitch is modularity: it is the glue, not the framework. Four pieces do the work:”) print(” konfig -> your experiment IS a Python call tree, and that tree is a plain dict”) print(” kontext -> parts are wired by string key paths, so they never import each other”) print(” ktyping -> Float[‘*b h w c’] checked at runtime, with named axes bound across args”) print(” kd.train -> Trainer: model + data + losses + metrics + optimizer, and nothing else”) print(“n Everything below runs on a CPU runtime with no dataset download: the data is synthetic.”) We install Kauldron and apply the one compatibility patch the current release combination needs. jax 0.10.1 moved the private module jax._src.prng, and etils up to 1.14.0 still reaches for it whenever it inspects an array’s dtype, which is a code path Kauldron runs on every batch. Without the two-line replacement below, which uses jax’s own public dtype API and is a no-op on older versions, a Trainer raises AttributeError before it completes a single step. With it in place we import the four pieces that do the work: konfig for the config system, kontext for the wiring, the typing module for runtime shape checks, and kd.train for the Trainer itself. Everything afterwards runs on a CPU runtime, because the only dataset in this notebook is one we generate. Copy CodeCopiedUse a different Browser @section(“1. A config is a call tree, and a call tree is a dict”) def config_is_a_dict(): with konfig.imports(): import optax as coptax # looks like optax, builds ConfigDict instead cfg = coptax.adam(learning_rate=0.003) print(f” cfg = {cfg}”) print(f” type = {type(cfg).__name__}”) print(f” __qualname__ = {cfg.__qualname__!r} <- the call, stored as data”) cfg.learning_rate = 1e-4 # configs are mutable optimizer = konfig.resolve(cfg) # …until you resolve them print(f” after cfg.learning_rate = 1e-4 -> resolve() gives {type(optimizer).__name__}”) print(“n An arbitrarily complex optimizer is still just nested dicts:”) chain = coptax.chain( coptax.clip_by_global_norm(1.0), coptax.scale_by_adam(b2=0.99), coptax.scale_by_learning_rate(0.003), ) as_json = json.dumps(json.loads(chain.to_json()), indent=2) print(textwrap.indent(as_json, ” “)) rebuilt = konfig.resolve(konfig.ConfigDict(json.loads(chain.to_json()))) print(f” JSON -> ConfigDict -> resolve() -> {type(rebuilt).__name__}”) print(” optax has no idea konfig exists. No base class, no registry, no decorator.”) return f”optax.chain -> JSON -> {type(rebuilt).__name__}” config_is_a_dict() We start with konfig, because it is the piece the rest of the library is built on. Inside a konfig.imports() block, importing optax gives us something that looks and autocompletes like optax but builds configuration instead of objects, so optax.adam(learning_rate=0.003) returns a ConfigDict holding the qualified name of the call and its arguments rather than an optimizer. That config is mutable until konfig.resolve turns it into the real thing, and because it is only nested dictionaries, an arbitrarily complex optax.chain serialises to JSON and comes back as a working optimizer. The important part is what optax had to do to support this: nothing. There is no base class, no registry, and no decorator anywhere in optax, and the same applies to any library we configure this way. Copy CodeCopiedUse a different Browser @section(“2. cfg.ref: change one number, everything downstream follows”) def config_references(): with konfig.imports(): import optax as coptax from kauldron import kd as ckd cfg = ckd.train.Trainer() cfg.num_train_steps = 1000 cfg.schedules = { “lr”: coptax.warmup_cosine_decay_schedule( init_value=0.0, peak_value=1e-3, warmup_steps=100, decay_steps=cfg.ref.num_train_steps, # <- a reference, not the value 1000 ) } at_1000 = konfig.resolve(cfg.schedules[“lr”]) cfg.num_train_steps = 200 # one edit… at_200 = konfig.resolve(cfg.schedules[“lr”]) # …and the schedule already knows print(f” {‘progress’:>10s} {‘lr @ 1000 steps’:>18s} {‘lr @ 200 steps’:>16s}”) for frac in (0.1, 0.5, 0.9): print(f” {frac:>9.0%} {float(at_1000(int(1000*frac))):>18.6f}” f” {float(at_200(int(200*frac))):>16.6f}”) print(“n Without .ref the schedule would have frozen 1000 into itself,

