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; a Keras adapter module is
scaffolded for v0.3). Trained models are first-class
pipekit_ops.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'
|
in_memory
|
bool
|
Load the whole cache into NumPy arrays on first read and serve items from them. A zarr read costs about 1 ms per array, so turn this on when the cache fits in memory and the dataset is read item by item, as in training. |
False
|
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.
- The store is opened once per instance and process, and reopened
after
invalidateor a change of content hash. Delete the cache throughinvalidate: an instance holding the arrays does not see a directory removed behind its back.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
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 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 | |
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
|
|
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'
|
cycle_state
|
CarryState | None
|
Initial carry state for a stateful |
None
|
simulator_version
|
str | None
|
Label for the simulator's behaviour, such as
|
None
|
invert
|
bool
|
|
False
|
The content hash covers the class and get_config() of the forward
model, cycle and observation operator, the forward model's
state_signature and dt, the prior config, n_samples, seed,
split, cycle_state and simulator_version. Code changes that
none of these show aren't detected. content_hash warns once per dataset
when the forward model is a wrapped function or has no get_config, and
no simulator_version is set.
Source code in packages/pipekit-train/src/pipekit_train/dataset.py
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 | |
TrainingDataset
¶
Bases: Operator
Abstract base — yields (input, target) pairs.
Subclasses implement __iter__ and content_hash. The base
provides:
pipekit_ops.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 estimates it with samples drawn frompredicted, which needs a PRNGkey.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. A component that takes a key gets
its own, split from the one passed in.
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.
KL(q ‖ p) = E_q[log q(z) - log p(z)], where q is predicted and p is
target. The analytic path is used when predicted has
.kl_divergence(target). Otherwise it is estimated by Monte Carlo:
(1 / S) Σ_s [log q(z_s) - log p(z_s)], with S draws z_s from q.
Algorithm
- Use
predicted.kl_divergence(target)if it exists. - Otherwise draw
n_samplesfrompredictedwithkey. - Average
log_probdifferences over draws and any batch dims.
Gradients flow through the draws only if predicted samples by
reparameterisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Monte Carlo draws S for the estimate. Its error falls as 1 / √S. |
32
|
Returns from __call__:
(loss, {"kl": loss}).
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If the estimate is needed and no |
Examples:
>>> class Point:
... def kl_divergence(self, other):
... import numpy as np
...
... return np.array([0.5, 1.5])
>>> KL()(Point(), None)[0].item()
1.0
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. A loss that needs randomness may also take a keyword
key, which the adapter supplies per batch; see call_loss.
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
call_loss(loss, predicted, target, key=None)
¶
Call loss, passing key only if it takes one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
Any
|
Any |
required |
predicted
|
Any
|
The model's prediction. |
required |
target
|
Any
|
The target. |
required |
key
|
Any
|
Optional PRNG key. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Whatever |
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.
The Equinox adapter saves into TrainingLoop.checkpoint_dir or
save_dir on this cadence, and always saves the final step. (The
actual save call lives in the adapter; this callback only configures it.)
Only the Equinox backend writes on-disk snapshots.
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 | PathLike[str] | None
|
Local directory for snapshots, used when
|
None
|
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
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 273 274 275 276 | |
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
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 168 | |
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
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 | |
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_ops.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_ops.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). 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/keras module wrapped in a pipekit_ops.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', '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
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 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 | |
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.
Trials rank on validation metrics when they have them: the backend's
final_eval_metrics, scored on the final state. Without a
val_dataset they rank on the last training batch, with a warning.
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 the chosen split's metrics. Default
|
'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
|
select_split
|
Literal['auto', 'train', 'eval']
|
Which metrics to rank on. |
'auto'
|
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 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 | |
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. The Keras
adapter module ships as a scaffold that raises NotImplementedError
on run() until v0.3 lands — 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_ops.Operator. Deliberate in-package twin ofpipekit_jax.JaxModelOp(kept separate so pipekit-train depends only on pipekit core). It can write its weights withserialize_weights, but it can't reload them; pass aJaxModelOptoTrainingLoopfor that, andrunreturns the trained model in the same wrapper.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_ops.Operator.
Public surface used in notebooks and downstream packages. Same
constructor signature and _apply shape as
pipekit_jax.JaxModelOp. It writes its array leaves with
serialize_weights, so a registry can store them and two trained
models get different hashes. Swap the import when you need to reload
them (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
serialize_weights()
¶
Return the module's leaves as tree_serialise_leaves bytes.
Unfiltered, so that Python scalar fields are written too.
pipekit_jax.JaxModelOp.with_weights reads these bytes against an
unfiltered skeleton of the same structure.
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. The adapter synthesises a TrainTask from
loop.loss when no explicit task is supplied.
By default evaluation also calls loss_fn, compiled, on ragged batches,
and averages its aux metrics per sample across the validation set.
A task may also define eval_fn, which switches evaluation to padded
batches. Every batch then has batch_size rows, padded with copies of the
last real row, and compiles once. valid is (batch_size,) bool, True
for a real row, and the task must leave the other rows out of its metrics.
Each batch's metrics are weighted by valid.sum(), so a masked per-sample
mean is exact across the set; a metric such as a quantile is not.
Signatures
loss_fn(model, batch, key) -> (scalar_loss, aux_metrics_dict) eval_fn(model, batch, key, valid) -> 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]]
|
(the last training batch), and |
tuple[Operator, dict[str, Any]]
|
set on the final state, empty without a |
tuple[Operator, dict[str, Any]]
|
in the TrainingArtifact. |
Source code in packages/pipekit-train/src/pipekit_train/adapters/equinox.py
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 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 | |
save_state(mngr, state, step, *, data_iter_state=None, force=False)
¶
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
|
force
|
bool
|
Save even if |
False
|
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.