pipekit-train¶
Training pipelines for emulators and amortized inference. A thin
orchestration layer over existing training tools (Equinox+Optax
ships as the v0.1 reference; Lightning and Keras adapter modules
are scaffolded for v0.2 / v0.3). Trained models are first-class
pipekit.Operators — they drop into inference pipelines (e.g.
pipekit_cycle.NeuralForward for emulator handoff). Master plan
reference: Report 11.
The full multi-file design lives in the package:
packages/pipekit-train/docs/design/.
Datasets¶
pipekit_train.dataset
¶
Layer 0 — training datasets.
Carrier-agnostic dataset operators that yield (input, target)
pairs and provide a stable content hash.
Classes in this module:
TrainingDataset— abstractOperatorbase. Defines the__iter__+content_hash+with_splitcontract.IterableDataset— generic escape hatch wrapping any iterable with an explicit content hash. Streaming, no random access.SimulationDataset— wraps apipekit_cycle.ForwardModel+ a prior operator to generate(params, simulator_output)pairs. Supports both single-step emulation and trajectory rollouts.CachedDataset— disk/fsspec-backed cache (zarr in v0.1).
See docs/design/api/datasets.md.
CachedDataset
¶
Bases: TrainingDataset
Disk- or cloud-backed cache around any TrainingDataset.
First epoch hits the source and writes to cache_dir. Subsequent
epochs read from the cache. Cache is keyed on source.content_hash()
so cache files are reused across runs (and across machines when
cache_dir is an fsspec URI) as long as the source's config and
seed haven't changed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
TrainingDataset
|
The wrapped |
required |
cache_dir
|
str | PathLike[str]
|
Either a local filesystem directory or an
fsspec URI ( |
required |
format
|
Literal['zarr', 'parquet', 'tfrecord']
|
Storage format. v0.2 ships |
'zarr'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
NotImplementedError
|
if |
ImportError
|
lazily, if |
Notes
- The cache writes raw NumPy-compatible arrays. Non-array
carriers (objects, ragged structures) must be converted
upfront —
CachedDatasetis for array-shaped pairs. - The cache is content-addressed, not split-addressed. Calling
cached.with_split("val")returns aCachedDatasetwrappingsource.with_split("val"); the cache for that split lives at a different path because its content hash differs. - To force re-cache, delete the cache directory or change a source-config field.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | |
invalidate()
¶
Delete the cache for the current content hash.
After calling this, the next iteration re-materialises from the source. Useful when the cache becomes corrupt or when you want to force a re-bake without changing source config. Works for both local paths and fsspec URIs.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
IterableDataset
¶
Bases: TrainingDataset
Generic escape hatch — wrap any iterable as a TrainingDataset.
Useful when the data source doesn't fit the catalog / simulation patterns: an existing PyTorch dataset, a generator over remote files, a user-built sequence of synthetic batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Iterable[tuple[Any, Any]] | Callable[[], Iterable[tuple[Any, Any]]]
|
Either an iterable of |
required |
content_hash
|
str
|
User-supplied content hash. Required, because we
can't introspect |
required |
seed
|
int
|
PRNG seed (unused by the base wrapper; surfaced for consistency with sampling subclasses). |
0
|
split
|
Split
|
|
'train'
|
Because the source is an opaque user closure, this class sets
forbid_in_yaml = True — the YAML round-trip is debug-only.
Equinox-adapter note: IterableDatasets aren't indexable, so the
adapter falls back from Grain's MapDataset (indexed) to plain
Python iteration with manual batching.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
SimulationDataset
¶
Bases: TrainingDataset
Yields (parameters, simulator_output) pairs.
Used for emulator training and amortized inference. The dataset samples a prior, evaluates the forward model (single step or trajectory), and optionally pushes the output through an observation operator (for SBI where the network learns to invert observations, not raw model states).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forward_model
|
Any
|
Anything satisfying
|
required |
prior
|
Operator
|
Zero-arg |
required |
n_samples
|
int
|
Total samples per epoch. |
required |
cycle
|
Operator | None
|
Optional |
None
|
obs_op
|
Any | None
|
Optional |
None
|
seed
|
int
|
PRNG seed for the prior. Each sample uses
|
0
|
split
|
Split
|
|
'train'
|
The content hash includes the forward-model state_signature
(when available) and dt, the prior config, n_samples,
seed, and split — anything that affects the data.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
TrainingDataset
¶
Bases: Operator
Abstract base — yields (input, target) pairs.
Subclasses implement __iter__ and content_hash. The base
provides:
pipekit.Operatorsemantics — get_config / dumps / loads.with_splitfor deterministic train/val/test split derivation.- A default
content_hashover(type, get_config())that subclasses can extend or override.
The training surface is the iterator, not _apply. Calling
a TrainingDataset like dataset() is undefined and raises
TypeError — datasets compose into TrainingLoop via the
dataset= constructor argument, not via Sequential.
Attributes:
| Name | Type | Description |
|---|---|---|
seed |
PRNG seed used by sampling subclasses. Default |
|
split |
|
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
content_hash()
¶
Stable identifier for this dataset's contents.
Default folds (type, get_config()) into a sha256. Subclasses
with external state (catalog URIs, forward-model signatures)
override to fold those in as well.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
with_split(split)
¶
Return a shallow clone of this dataset with a different split.
Same seed; only the split label changes. Subclasses that
carry mutable state should override.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
hash_config(*parts)
¶
sha256 over parts, each stable-JSON-encoded and NUL-terminated.
The shared content-hash framing for TrainingDataset.content_hash
implementations (used by SimulationDataset, CachedDataset, and
geotoolz-patcher's geopatcher.integrations.train.XarrayWindowDataset).
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
Losses¶
pipekit_train.loss
¶
Loss protocol + common loss operators.
The carrier-agnostic loss surface from the v0.1 design.
Loss(Protocol) — runtime-checkable; signature(predicted, target) -> float | tuple[float, dict].MSE— mean squared error. Carrier-agnostic via duck typing on-,**,.mean; works for both numpy and JAX arrays.NLL— assumespredictedhas.log_prob(target). Distribution- shaped outputs (Equinox distributions, numpyro distributions, custom density heads). For Gaussian-NLL on raw (mean, log_var) tuples, wrap them in a small density head that exposes.log_prob.KL— Kullback-Leibler divergence. Preferspredicted.kl_divergence (target)if available; otherwise falls back to-(target.log_prob(samples) - predicted.log_prob(samples)).mean()with samples drawn frompredicted.Composite— weighted sum ofLosscomponents, emitting the per-component values as auxiliary metrics.
See docs/design/api/primitives.md.
Composite
¶
Bases: Operator
Weighted sum of Loss components.
The aggregate loss is sum(w_i * L_i(predicted, target)). Each
component's scalar value is surfaced as an auxiliary metric so
the adapter logs them individually.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
tuple[tuple[float, Loss], ...]
|
Tuple of |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Returns from __call__:
(total, {"<name>_<i>": value, ..., "total": total}).
Source code in packages/pipekit-train/src/pipekit_train/loss.py
KL
¶
Bases: Operator
Kullback-Leibler divergence between two distributions.
Contract
predicted and target must both expose either
.kl_divergence(other) (fast analytic path) or
.log_prob(samples) + .sample(key) (sample-based
fallback). The fast path is tried first.
Returns from __call__:
(loss, {"kl": loss}).
Note
The sample-based fallback requires a PRNG key. v0.1 ships the analytic path only; sample-based KL lands in v0.1.1 when the Equinox adapter exposes the per-batch RNG.
Source code in packages/pipekit-train/src/pipekit_train/loss.py
Loss
¶
Bases: Protocol
Loss function — per-batch scalar called by the adapter.
Implementations may return either a scalar loss directly, or a
(scalar, aux_metrics_dict) tuple. The adapter distinguishes
by introspection.
See docs/design/api/primitives.md and ADR D4 in
docs/design/decisions.md.
Source code in packages/pipekit-train/src/pipekit_train/loss.py
MSE
¶
Bases: Operator
Mean squared error loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reduction
|
str
|
|
'mean'
|
Returns from __call__:
(loss, {"mse": loss}) so adapters see a consistent
(scalar, aux) shape.
Source code in packages/pipekit-train/src/pipekit_train/loss.py
NLL
¶
Bases: Operator
Negative log-likelihood for distribution-shaped predictions.
Contract: predicted must expose .log_prob(target) returning
a per-sample log-probability array. The loss reduces over the
leading batch axis with reduction.
Typical wrappers — your model emits a distribution-shaped output:
- For amortized inference: a
pyrox/distrax/numpyrodistribution whose.log_probis differentiable through the model parameters. - For Gaussian regression: a tiny head operator that wraps
(mean, log_var)model outputs into aNormal-like object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reduction
|
str
|
|
'mean'
|
Returns from __call__:
(loss, {"nll": loss}).
Source code in packages/pipekit-train/src/pipekit_train/loss.py
Callbacks¶
pipekit_train.callbacks
¶
Callback protocol + bundled callbacks.
The five-hook callback surface and three bundled callbacks
(EarlyStopping, Checkpoint, LogToExperiment) per
docs/design/api/components.md.
The Callback Protocol is intentionally not @runtime_checkable:
structural isinstance would reject partial implementations (a
metric-logger that only cares about on_step_end), which
contradicts the design's optional-hook model. Adapters dispatch via
getattr(cb, hook, None). See ADR D9.
Callback
¶
Bases: Protocol
Per-step / per-epoch / per-eval hooks.
Each of the five hooks is optional at runtime. Adapters
dispatch via getattr(cb, hook_name, None) so a callback that
only cares about one hook (say, on_step_end for a metric
logger) implements just that method.
This Protocol is intentionally not @runtime_checkable:
structural isinstance would require every callback to
implement all five methods, which contradicts the
partial-implementation model documented in
docs/design/api/components.md. The Protocol exists as the
type-checker contract describing the full hook surface; the
runtime contract is "ducks with the methods you actually use".
See ADR D9 in docs/design/decisions.md.
Source code in packages/pipekit-train/src/pipekit_train/callbacks.py
Checkpoint
¶
Bases: Operator
Save (model_op, optimizer_state) every N steps; final to a registry.
On each on_step_end, when state.step is a multiple of
every_n_steps, the adapter is expected to save its native
checkpoint into save_dir. (The actual save call lives in the
adapter; this callback just signals when to fire.)
When registry is set, on_train_end stores the final model
operator in the registry by content hash, and the URI is recorded
on last_uri / last_hash for the loop to fold into its
TrainingArtifact.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
every_n_steps
|
int
|
Cadence for on-disk snapshots. |
1000
|
keep_last
|
int
|
Number of recent checkpoints to retain on disk.
Honored by the adapter's native checkpoint manager
(Orbax |
3
|
save_dir
|
str
|
Local directory or fsspec URI. |
'./ckpts'
|
registry
|
Any | None
|
Optional anything satisfying
|
None
|
Attributes (runtime state):
last_uri: Set after on_train_end if a registry was provided.
last_hash: Set after on_train_end if a registry was provided.
Source code in packages/pipekit-train/src/pipekit_train/callbacks.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
on_train_end(loop, state)
¶
Persist the final model to the registry, if one is configured.
Source code in packages/pipekit-train/src/pipekit_train/callbacks.py
should_snapshot(step)
¶
EarlyStopping
¶
Bases: Operator
Signal stop when a monitored metric hasn't improved for N evals.
The callback only triggers on on_eval_end. It updates internal
"best so far" state and sets should_stop to True once
patience consecutive eval rounds pass without a meaningful
improvement (min_delta).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
str
|
Metric name as it appears in the on_eval_end dict. |
required |
patience
|
int
|
Number of consecutive evals without improvement before signalling stop. |
10
|
mode
|
Literal['min', 'max']
|
|
'min'
|
min_delta
|
float
|
Minimum change to count as improvement. |
0.0
|
Attributes (runtime state, not part of the operator config): should_stop: Read by the adapter's outer loop on each on_eval_end to decide whether to break early. best: Current best value of the monitored metric. wait: Consecutive eval rounds since last improvement.
Source code in packages/pipekit-train/src/pipekit_train/callbacks.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
reset()
¶
LogToExperiment
¶
Bases: Operator
Forward metrics / params / artifacts to a pipekit-experiment tracker.
On on_train_begin, calls tracker.start_run with the loop's
config (plus any user-supplied extra config). On on_step_end /
on_eval_end, forwards metrics to tracker.log_metrics. On
on_train_end, calls tracker.end_run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracker
|
Any
|
Anything satisfying
|
required |
run_name
|
str
|
Name passed to |
required |
config
|
dict[str, Any] | None
|
Extra config dict merged into the run start. The
tracker also sees the TrainingLoop's |
None
|
Attributes (runtime state):
run: The Run object returned by tracker.start_run,
available after on_train_begin.
Source code in packages/pipekit-train/src/pipekit_train/callbacks.py
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | |
Metric writers¶
pipekit_train.writer
¶
Metric writer protocol + default JSON Lines implementation.
MetricWriter is the carrier-agnostic seam where per-step metrics
land when no ExperimentTracker is attached. JSONLWriter is the
default; W&B, TensorBoard, and other writers are user-supplied per
docs/design/examples/integration.md.
JSONLWriter
dataclass
¶
Append-only JSON Lines metric writer.
Each write appends one line of the form::
{"step": int, "metrics": {name: float, ...}, "timestamp": iso8601}
The file is opened lazily on the first write. Records are
written into Python's text-IO buffer immediately and that buffer
is flushed to the OS every flush_every writes; flushing only
pushes data out of user space, it does not guarantee
durability against a kernel crash or power loss. Set
fsync_on_flush=True to additionally call os.fsync on each
flush — slower, but the data is on stable storage when it returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. Parent directories are created on first write if missing. |
required |
flush_every
|
int
|
Number of writes between explicit |
100
|
fsync_on_flush
|
bool
|
When True, |
False
|
See docs/design/api/components.md.
Source code in packages/pipekit-train/src/pipekit_train/writer.py
close()
¶
write(step, metrics)
¶
Append one record.
Source code in packages/pipekit-train/src/pipekit_train/writer.py
MetricWriter
¶
Bases: Protocol
Where per-step metrics go when no tracker is attached.
Implementations: JSONL (default), in-memory list, W&B,
TensorBoard. The trainer calls write per logged step.
See docs/design/api/components.md.
Source code in packages/pipekit-train/src/pipekit_train/writer.py
Training loop¶
pipekit_train.loop
¶
Layer 3 — TrainingLoop.
The headline composable. TrainingLoop is a
pipekit.StatefulOperator carrying (model, opt_state, step, epoch,
metrics, rng); running it produces (trained_model_op, artifact).
This module also ships the supporting TrainerCarryState (subclass of
pipekit.CarryState) and ValidationStep (an Operator that
evaluates a trained model against a held-out dataset).
See docs/design/api/models.md.
TrainerCarryState
¶
Bases: CarryState
Carry-state for TrainingLoop.
The optimizer state and RNG are backend-specific opaque types
(an optax.OptState and a jax.Array PRNG key for the Equinox
adapter; a torch.optim.Optimizer.state_dict() + tuple for
Lightning). The pipekit-train side carries them as Any and
delegates serialisation to the adapter's native checkpoint
machinery.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Current model operator (possibly partially trained). |
|
opt_state |
Backend-specific optimizer state. |
|
step |
Global step counter. |
|
epoch |
Derived from step // steps_per_epoch (0 if not set). |
|
metrics |
Latest per-step metric snapshot (cleared on epoch end). |
|
rng |
Backend-specific PRNG state. |
Source code in packages/pipekit-train/src/pipekit_train/loop.py
to_dict()
¶
JSON-safe snapshot.
Backend-specific fields (model, opt_state, rng)
are stored as repr strings — the adapter's native checkpoint
is the round-trip path for those.
Source code in packages/pipekit-train/src/pipekit_train/loop.py
TrainingLoop
¶
Bases: StatefulOperator
Train a model_op on a dataset, producing a trained model_op.
The headline composable. Delegates the actual training to a
backend adapter (pipekit_train.adapters.<backend>.run). The
adapter sees the full loop config and is responsible for the
per-step gradient update and the per-eval validation pass. The
TrainingLoop itself owns the artifact assembly and the callback
threading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_op
|
Operator
|
Untrained model Operator. Backend-specific (an equinox/lightning/keras module wrapped in a pipekit.Operator). |
required |
dataset
|
TrainingDataset
|
A |
required |
val_dataset
|
TrainingDataset | None
|
Optional held-out |
None
|
loss
|
Loss | None
|
A |
None
|
task
|
Any | None
|
Optional backend-native task interface. Lets power users
bypass the auto-synthesised |
None
|
optimizer_config
|
dict[str, Any] | None
|
Flat dict, e.g.
|
None
|
max_steps
|
int
|
Total optimisation steps. (Per-step is the unit; see ADR D10.) |
10000
|
steps_per_epoch
|
int | None
|
Optional. Controls when on_epoch_end fires. |
None
|
batch_size
|
int
|
Per-step minibatch size. |
32
|
backend
|
Literal['equinox', 'lightning', 'keras', 'numpyro-svi', 'numpyro-mcmc', 'blackjax']
|
One of |
'equinox'
|
callbacks
|
tuple[Any, ...]
|
Tuple of |
()
|
metric_writer
|
MetricWriter | None
|
Optional |
None
|
eval_every_n_steps
|
int
|
Validation cadence. |
500
|
log_every_n_steps
|
int
|
Metric logging cadence. |
100
|
checkpoint_dir
|
str | None
|
Optional. When set, the adapter wires up its native checkpoint machinery here. |
None
|
sharding
|
Any | None
|
Optional backend-specific sharding configuration for
multi-device / multi-host training. For the Equinox backend
this is a |
None
|
seed
|
int
|
Master PRNG seed. |
0
|
Raises (at run-time):
ValueError: if neither loss nor task is supplied.
ValueError: if backend isn't recognised.
Source code in packages/pipekit-train/src/pipekit_train/loop.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 | |
run()
¶
Run training end-to-end and return (trained_model_op, artifact).
Equivalent to self._apply(None, None) followed by an
artifact build. The artifact is a
pipekit_experiment.TrainingArtifact when that package is
installed; otherwise a local _LocalArtifact dataclass with
the same field names.
Source code in packages/pipekit-train/src/pipekit_train/loop.py
ValidationStep
¶
Bases: Operator
Compute validation metrics on a held-out dataset.
Iterates dataset, calls model_op on each input, applies
each metric Operator to (predicted, target), and returns
the mean-over-batches metric values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_op
|
Operator
|
The model |
required |
dataset
|
TrainingDataset
|
The held-out |
required |
metrics
|
tuple[Operator, ...]
|
Tuple of |
required |
Returns from __call__:
dict[str, float] with one entry per metric (plus any aux
keys), each averaged over the dataset.
Source code in packages/pipekit-train/src/pipekit_train/loop.py
Hyperparameter sweeps¶
pipekit_train.sweep
¶
Hyperparameter sweep orchestration.
Two operators:
ParameterGrid— Cartesian-product iterator over named parameter axes. Yields{name: value, ...}dicts.HyperSweep— orchestrates N independentTrainingLoopruns by calling a user-suppliedloop_template(params) -> TrainingLoopfor each point in the search space, then returns the trial results ranked by a configured metric.
v0.2 ships grid + sequential execution. Optuna / Ray Tune sampler
adapters land in v0.2.1; parallel execution lands in v0.3. The
StatefulOperator wrapping means a sweep composes into Sequential
just like a TrainingLoop (carry-state is the current best trial).
See issue #14 and design boundaries.md Q5.
HyperSweep
¶
Bases: StatefulOperator
Orchestrate N independent TrainingLoop runs.
For each params dict yielded by search_space, builds a
TrainingLoop via loop_template(params) and runs it.
Captures the trained model and artifact per trial. Returns a list
of SweepResult sorted by select_metric in select_mode
order.
v0.2 runs trials sequentially. Parallel execution (multiprocessing)
lands in v0.3. Optuna / Ray Tune samplers land in v0.2.1 — for now
any iterable of param dicts works as search_space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loop_template
|
Callable[[dict[str, Any]], TrainingLoop]
|
Callable |
required |
search_space
|
Iterable[dict[str, Any]]
|
A |
required |
select_metric
|
str
|
Key to look up in
|
'loss'
|
select_mode
|
Literal['min', 'max']
|
|
'min'
|
n_trials
|
int | None
|
Optional cap on trials drawn from |
None
|
sweep_id
|
str | None
|
Stable identifier for this sweep; default uuid4 hex.
Surfaced on every |
None
|
on_trial
|
Callable[[SweepResult, SweepCarryState], None] | None
|
Optional callback |
None
|
Returns from run():
list[SweepResult] sorted by select_metric. Best result
is results[0].
Raises:
| Type | Description |
|---|---|
ValueError
|
if the search space is empty, or if a trial's
artifact doesn't include |
TypeError
|
if |
Source code in packages/pipekit-train/src/pipekit_train/sweep.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
ParameterGrid
¶
Bases: Operator
Cartesian product over named parameter axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
dict[str, list[Any]]
|
Mapping |
required |
Iteration yields one {axis_name: value, ...} dict per cell.
len(grid) is the product of axis lengths for non-empty
grids; 0 for the empty grid per the convention above.
Example
list(ParameterGrid({"lr": [1e-3, 1e-2], "width": [8, 16]})) [{'lr': 0.001, 'width': 8}, {'lr': 0.001, 'width': 16}, {'lr': 0.01, 'width': 8}, {'lr': 0.01, 'width': 16}]
Source code in packages/pipekit-train/src/pipekit_train/sweep.py
SweepCarryState
¶
Bases: CarryState
Carry-state for HyperSweep.
Threaded across trials inside _apply so the sweep composes
into Sequential (e.g. coarse-then-fine sweep stages share
best-so-far progress).
Attributes:
| Name | Type | Description |
|---|---|---|
completed |
Cumulative number of trials run across all
|
|
best_metric |
Best metric value observed (None until the first trial completes). |
|
best_trial_index |
Global index (in the same coordinate
system as |
Source code in packages/pipekit-train/src/pipekit_train/sweep.py
SweepResult
dataclass
¶
One trial's result inside a sweep.
Attributes:
| Name | Type | Description |
|---|---|---|
params |
dict[str, Any]
|
The parameter dict that produced this trial. |
trained_model_op |
Operator
|
The trained |
artifact |
Any
|
The trial's |
final_metric |
float
|
The value of |
sweep_id |
str
|
Stable identifier shared by every trial in this sweep (defaults to a uuid4 hex string). |
trial_index |
int
|
Global 0-based index across the cumulative
trial stream represented by the carry-state. For a fresh
sweep it starts at 0; when a |
Source code in packages/pipekit-train/src/pipekit_train/sweep.py
Backend adapters¶
The Equinox+Optax+Orbax adapter is the v0.1 reference. Lightning and
Keras adapter modules ship as scaffolds that raise NotImplementedError
on run() until v0.2 / v0.3 land — see
adapters.md
for the planned designs.
Equinox (v0.1 reference)¶
pipekit_train.adapters.equinox
¶
Equinox + Optax + Orbax adapter — the v0.1 reference.
Concrete JAX-native stack as described in
docs/design/api/adapters.md (Equinox section). The adapter
synthesises a TrainTask from a pipekit_train.Loss if the user
doesn't supply one, builds the optimiser from optimizer_config,
runs an eqx.filter_jit'd train step, and threads the user's
callbacks through the loop.
Module surface:
ShardingSpec— optional multi-device / multi-host sharding config (mesh,model_pspec,data_pspec); threaded throughTrainState, the data iterator, and the Orbax restore path. See issue #15, ADR D12.TrainState(eqx.Module)— model + opt_state + step.TrainTask(Protocol) — user-defined training target, ported from the eqx_trainer design.train_step— pure function,@eqx.filter_jitwrapped.save_state/restore_state— Orbax bridge viaeqx.partition.EquinoxModelOp(Operator)— wraps a trainedeqx.Moduleas apipekit.Operator. Deliberate in-package twin ofpipekit_jax.JaxModelOp(kept separate so pipekit-train depends only on pipekit core); unlikeJaxModelOpit has no weight-blob round-trip — wrap the trained module in aJaxModelOpwhen you needserialize_weights/from_registry.run(loop)— full end-to-end training entry point.
See ADRs D8, D9, D10 in docs/design/decisions.md.
EquinoxModelOp
¶
Bases: Operator
Wrap an eqx.Module as a pipekit.Operator.
Public surface used in notebooks and downstream packages. Same
constructor signature and _apply shape as
pipekit_jax.JaxModelOp — swap the import when you need the
registry weight round-trip (serialize_weights /
with_weights / from_registry), which this in-package twin
deliberately omits so pipekit-train depends only on pipekit core.
The wrapper is marked forbid_in_yaml = True because an
eqx.Module is a JAX PyTree of arrays — the round-trip path is
the model registry's weights blob plus the module's
structural config, not JSON of the operator itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
An |
required |
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
ShardingSpec
dataclass
¶
Sharding configuration for the Equinox adapter.
Threaded through TrainState (model + optimiser leaves placed per
model_pspec), the data iterator (each batch placed per
data_pspec, with multi-host process sharding), and the Orbax
restore path (sharding-aware). See ADR D12.
The common case is data parallelism: model_pspec =
PartitionSpec() (the model is replicated on every device) and
data_pspec = PartitionSpec("data") (each batch is split along its
leading axis across the mesh's "data" dimension). A uniform
model-parallel model_pspec is also honoured when every sharded
array leaf has a compatible rank.
Attributes:
| Name | Type | Description |
|---|---|---|
mesh |
Mesh
|
The device mesh. |
model_pspec |
PartitionSpec
|
PartitionSpec applied to every model / optimiser
array leaf. |
data_pspec |
PartitionSpec
|
PartitionSpec applied to each batch (the leading axis is the batch axis). |
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
TrainState
¶
Bases: Module
Equinox-side training state.
A PyTree-clean container holding the bare eqx.Module
(without the EquinoxModelOp wrapper), the Optax optimizer
state, and the global step counter.
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
create(model, optimizer, sharding=None)
staticmethod
¶
Build the initial training state, optionally placed on a mesh.
When sharding is given, the model and optimiser array leaves are
placed on sharding.model_sharding and the step counter is
replicated, so the very first train_step already runs sharded.
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
TrainTask
¶
Bases: Protocol
User-defined Equinox training target.
Provide loss_fn (required); optionally provide eval_fn.
The adapter synthesises a TrainTask from loop.loss when no
explicit task is supplied.
Signatures
loss_fn(model, batch, key) -> (scalar_loss, aux_metrics_dict) eval_fn(model, batch, key) -> metrics_dict (optional)
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
restore_state(mngr, template, step)
¶
Restore array leaves into the static skeleton of template.
Returns:
| Type | Description |
|---|---|
TrainState
|
|
Any | None
|
|
tuple[TrainState, Any | None]
|
(e.g. a checkpoint written by an earlier pipekit-train |
tuple[TrainState, Any | None]
|
without the iterator-state extension). When non- |
tuple[TrainState, Any | None]
|
caller passes it to |
tuple[TrainState, Any | None]
|
resume the data stream byte-identically. See #17. |
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
run(loop)
¶
Train loop end-to-end. The entry point for the Equinox backend.
Returns:
| Type | Description |
|---|---|
Operator
|
A pair |
dict[str, Any]
|
is a |
tuple[Operator, dict[str, Any]]
|
|
tuple[Operator, dict[str, Any]]
|
|
tuple[Operator, dict[str, Any]]
|
|
tuple[Operator, dict[str, Any]]
|
|
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 | |
save_state(mngr, state, step, *, data_iter_state=None)
¶
Persist the array leaves of state at step.
Static (non-array) leaves are reconstructed on restore from the
in-memory template; see restore_state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mngr
|
CheckpointManager
|
Orbax checkpoint manager. |
required |
state
|
TrainState
|
Current |
required |
step
|
int
|
Step number. |
required |
data_iter_state
|
Any
|
Optional state dict from
|
None
|
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
shard_train_state(state, spec)
¶
Return state with its model + optimiser leaves placed on spec.
The model and optimiser arrays go to spec.model_sharding; the scalar
step is replicated across the mesh.
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
train_step(state, batch, key, task, optimizer)
¶
One Equinox optimisation step. Pure function.
Differentiates only array leaves (eqx.filter_grad); passes
task and optimizer as static arguments so structural
changes recompile.