Skip to content

Training policies

Sample collection, training algorithms, featurizers, and the trained agents and networks they produce. Everything on this page is imported from the top-level dynaplex package, except the observation-spec vocabulary (TensorSpec, Dtype, and friends), which lives in dynaplex.modelling. For assessing the resulting policies, see evaluating policies.

Sample collection and training

DCL

DCL(mdp: MDPProtocol, policy: PolicyProtocol | ContextPolicyProtocol, *, n: int = 5000, m: int = 1000, h: int | None = None, gen0: 'Shape | None' = None, trained: 'Shape | None' = None, seed: int = 0, reduction_factor: int = 4, final_field: int = 5, root: str | None = None, gen0_label: str | None = None, workdir: str | None = None, keep_samples: str = 'all', verbose: bool = True, jit: bool | None = None, gc_threshold_bytes: int = 16 << 20, torch_threads: int | None = None, compile_agent: bool = False, steps_per_round: int = 0, machine: 'str | DclPlan | None' = 'auto', device: str | None = None, policy_binding: str | None = None, policy_precision: str | None = None, allow_mismatch: bool = False, checks: bool | Literal['rehearsal'] | None = None, warmup_time: int | None = None, restart_after: int = 0, sample_info: bool = False)

The Deep Controlled Learning generation loop; see the module docstring.

Construct around an (mdp, heuristic policy) pair, then collect_gen0(), and train_policy(features=, network=) or run(generations, features=, network=). Collection and training internals are collect_samples, dynaplex.featurize and train_network, which stay public for ad-hoc use.

Parameterize a DCL collection. Construction is cheap and torch-free; it creates the workdir and its dcl.json record, but collects and trains nothing. The featurizer, the network and the training settings are NOT given here: they belong to train_policy / run / experiment.

Parameters:

Name Type Description Default
mdp MDPProtocol

The MDP instance to solve.

required
policy PolicyProtocol | ContextPolicyProtocol

The generation-0 rollout policy (e.g. a heuristic benchmark policy). Generations >= 1 roll out the previously trained agent instead; the heuristic labels only generation 0.

required
n int

Number of labeled samples to collect per generation (default 5000, the legacy N).

5000
m int

Rollout replications per candidate action (any value; need not divide workers; default 1000, the legacy M).

1000
h int | None

Rollout horizon. On finite-horizon MDPs a rollout ends at the horizon or at a FINAL state, whichever comes first. None (default) = the legacy H: 40 on a finite-horizon MDP, 256 on an infinite-horizon one.

None
machine 'str | DclPlan | None'

The execution plan: two shapes (processes, engines, workers, slots — one for generation 0, one for the trained policy), the trained policy's device and policy binding, hand-engineered for a machine. "auto" (default) recognizes which plan this allocation IS — "laptop" (derived from this machine's cores and accelerator) on macOS and Windows; on Linux one of "gpu_h100" / "gpu_a100" and their _half / _quarter units or "genoa" — and never invents one: an unrecognized allocation raises MachineMismatchError up front rather than run slowly on a shape nobody tuned. Pass a plan name, a dynaplex.machine.DclPlan, or None = no plan, both shapes Shape.TRIVIAL (1 process, 1 engine, 1 worker, 512 slots, cpu) unless gen0 / trained say otherwise. At collection time the plan is VERIFIED against the allocation (allowed CPUs, visible GPUs) and refuses to run on less — "always get a full node". The shapes are NOT part of the run's identity: a run that moves to another machine finds its directory and goes on, and says so when it uses samples collected under another shape.

'auto'
gen0 'Shape | None'

A dynaplex.Shape overlaid on the plan's generation-0 shape: every field set here replaces the plan's, every field left None keeps it (Shape(workers=8) changes the workers only). Generation 0 rolls out the heuristic in-machine, so its shape has no forward to place.

None
trained 'Shape | None'

The same overlay for the shape generations >= 1 run, where the trained policy forwards on device.

None
device str | None

Where generation >= 1 rollout agents forward ("cpu"/"cuda"/"mps"); default from the plan, else cpu. Training runs on the plan's training device (cluster GPU plans: the GPU; laptop: the cpu, faster for small nets at batch 64), or on device when that is given explicitly; train=dict(device=...) overrides either.

None
policy_binding str | None

collect_samples policy binding for the agent ("auto"/"blocking"/"device"/"graph"); default from the plan, else auto.

None
policy_precision str | None

precision of the agent's forward on a device binding ("fp32"/"tf32"/"fp16"/"bf16"); default from the plan, else fp32. Lower precision is faster for attention-sized networks and may change near-tie actions.

None
steps_per_round int

Generation-0 schedule: decisions a worker takes on one rollout slot before moving to the next within a round (0, the default: run each rollout to its cutoff, depth-first; 1 = the pre-2026-09 breadth-first sweep). A throughput knob like workers/slots: same sample distribution, different concrete draw.

0
warmup_time int | None

Periods each main trajectory runs under the generation's own rollout policy (the heuristic at generation 0, the trained agent after) before its first labeled state, so samples describe the policy's stationary behaviour rather than the modeller's startup transient (legacy L). None (default) = the legacy default: 100 on an infinite-horizon MDP, off on a finite one; 0 = off. Infinite-horizon MDPs only. Warm states are produced up front per controller — a short prologue of batched forwards on generations >= 1 — and every worker keeps a copy of that supply.

None
restart_after int

Labels (samples) a main trajectory contributes before it is retired and its slot restarted on a fresh warm state (legacy reinitiate_counter; 0 = never, the default). A sample-diversity knob for slow-mixing systems. Counted in labels, not periods. Both knobs are part of the experiment identity when active.

0
sample_info bool

Record every sample's provenance (controller, arms, warm-start origin, label index, time, rounds, row) as the SampleSet's info slab, for scripts/dcl_audit.py. Free when off (a static flag in the machine); not identity.

False
seed int

Global experiment seed, covering collection and training.

0
reduction_factor int

Cap on the per-round reduction factor of the sequential-halving tournament: the candidate field shrinks from |A| to final_field in the fewest rounds whose steady per-round factor stays <= reduction_factor.

4
final_field int

Number of candidate actions in the tournament's final round. These finalists all receive the (equal, largest) per-action rollout budget, so their cost estimates carry full evidence; the best of them is the label. States with fewer than final_field admissible actions run a single full-budget round over all of them.

5
root str | None

The directory runs are stored under. None (default) = the environment variable DYNAPLEX_RUNS_DIR when it is set, else dynaplex_runs. A relative path is relative to the current working directory of the Python process, not to the script. PPO follows the same rule.

None
gen0_label str | None

A readable label for the collection's directory: {root}/{MDPClass}_dcl_{gen0_label} instead of the hash-derived one. A label already taken by a collection with other settings (or other model code) is refused (WorkdirMismatchError).

None
workdir str | None

The collection's directory. None (default, recommended) derives {root}/{MDPClass}_dcl_{hash8} from a structural hash of the MDP, the policy and the collection settings, so every distinct collection gets its own directory by construction (gen0_label puts a readable label in place of the hash). Passing a directory uses exactly that path — you then own uniqueness: a directory that holds another collection is refused unless allow_mismatch. Experiments live in their own directories below it. The directory is printed when verbose.

None
keep_samples str

Retention of an experiment's LATER generations, applied after each generation trains: "all" keeps every generation's gen{g} directory (records and samples), "last" keeps only the most recent generation's, "none" deletes each generation's as soon as it has been trained on. Generation 0 is never deleted: it is the collection every experiment shares. Deleted samples make samples(g) unavailable for those generations; agents are always kept.

'all'
verbose bool

Print per-generation progress.

True
jit bool | None

None (default) uses the JIT when available, True requires it, False always interprets.

None
checks bool | Literal['rehearsal'] | None

Runtime checks in the compiled kernels, applied to the GENERATION-0 collection only. "rehearsal" (the default) runs that collection once CHECKED at a tiny budget before the fast collection; True = the generation-0 collection fully checked; False = fast, no rehearsal; None = the DYNAPLEX_CHECKS=0|1 environment override if set, else "rehearsal". Generations >= 1 always collect fast: the rehearsal exists to catch an unchecked model or featurizer fault, and one that the generation-0 rehearsal does not surface is unlikely to surface under a later policy either, while checking every generation would cost speed. A resumed run that skips generation 0 therefore never rehearses.

None
gc_threshold_bytes int

Auto-GC trigger threshold for the worker worlds.

16 << 20
torch_threads int | None

If set, torch.set_num_threads(torch_threads) before training and collection. Torch's default (all cores) measurably HURTS the per-round inference batches of generation >= 1 collection on big multi-socket machines — one socket's worth of threads is a good starting point (measured on 2x96-core Genoa: 96 threads beat 192 by 2.6x). With processes > 1 every child process applies it too (spawned children would otherwise default to torch's all-cores pool).

None
compile_agent bool

torch.compile the rollout agent's forward before each generation >= 1 collection (one-time warmup of tens of seconds, then a measurably faster forward).

False

allow_mismatch: an existing workdir whose dcl.json describes a DIFFERENT collection (other MDP, policy, parameters) is refused with a WorkdirMismatchError listing the differences — resuming there would mix artifacts of two collections. True proceeds anyway (deliberate reuse, e.g. timing a new plan on stored generation-0 samples); the record is left as written.

torch_threads and compile_agent are PERFORMANCE knobs and are deliberately EXCLUDED from the experiment hash and dcl.json — the same experiment resumes under different perf settings. Compiled and eager forwards are bitwise-equal on CPU (measured); thread count is part of torch's per-(machine, build, device) reproducibility caveat (see NNAgent.to) — in principle a different thread count could flip a near-tie forward, exactly like moving devices.

shape

shape(generation: int) -> 'Shape'

The resolved split generation generation runs: gen0 for 0, trained after.

records

records() -> str

The directory generation 0's collection writes: states and statistics, two blocks of records in which record k belongs to sample row k (see collect_samples). dynaplex.featurize(mdp, records() + "/states", F) gives the features of any featurizer F for these samples.

collect_gen0

collect_gen0() -> SampleSet

Collect generation 0: n samples under the heuristic policy, no featurizer. The state and the statistics of every sample go to records(); the returned SampleSet (labels, statistics, manifest; no features) is also stored. Done ONCE: a later call, in this process or another, loads what is there.

One run collects at a time. While it does, gen0.collecting in the directory names its process; a second run on the same machine that also finds no generation 0 stops with CollectionInProgressError (and loads the result when it is run again later). So collect first, then start the runs that train on it.

samples

samples() -> SampleSet

The stored SampleSet of generation 0 (collect_gen0() first). The samples of an experiment's later generations: experiment(...).samples(g).

experiment

experiment(*, features: type[Featurizer], network: 'Net | None' = None, train: dict | None = None, training_label: str | None = None) -> 'DCLExperiment'

The experiment of one (featurizer, network, training settings) on this collection: its agents, and the collections of its later generations.

Parameters:

Name Type Description Default
features type[Featurizer]

The featurizer class defining the state representation (written with @featurizer) — e.g. LostSalesFeaturizer.

required
network 'Net | None'

A constructible network spec (dynaplex.MLP(...) / dynaplex.Net); None = dynaplex.MLP().

None
train dict | None

Keyword arguments for dynaplex.nn.train_network (epochs, batch_size, lr, loss, ...).

None
training_label str | None

A readable last part for the experiment's directory, {Featurizer}_{network}_{training_label}, in place of the short hash of the network's parameters and the training settings (LostSalesFeaturizer_mlp_128x128_c46a1f). A label already taken by an experiment with other settings is refused (WorkdirMismatchError) when the directory is first used.

None

The experiment's directory is not made here but on first use: see DCLExperiment.workdir.

train_policy

train_policy(*, features: type[Featurizer], network: 'Net | None' = None, train: dict | None = None, training_label: str | None = None) -> 'NNAgent'

The generation-1 agent of this (featurizer, network, training settings), trained on generation 0 (collected first if it is not there). Calling it with another featurizer or network trains another agent on the SAME samples.

run

run(generations: int, *, features: type[Featurizer], network: 'Net | None' = None, train: dict | None = None, training_label: str | None = None) -> list

Run the loop up to generations TOTAL trained generations for this (featurizer, network, training settings) and return the trained agents. Idempotent: existing artifacts are loaded, not redone.

DCLExperiment

DCLExperiment(dcl: DCL, features: type[Featurizer], network: 'Net | None', train: dict | None, training_label: str | None = None)

One (featurizer, network, training settings) on a DCL collection: a line of agents. Made by DCL.experiment(...); DCL.train_policy and DCL.run are shorthands for its methods. See the module docstring for the directory.

workdir property

workdir: str

The experiment's directory, {Featurizer}_{network}_{training_label or hash6} below the collection's. Made on FIRST USE, not when the experiment is created: the network's part of the name comes from its factory (Net.label), and importing a factory imports torch, which generation 0 does not need. run() and train_policy() first use it after generation 0 is there. A directory that holds an experiment with other settings is refused here (WorkdirMismatchError).

records

records(generation: int) -> str

The directory generation generation's collection writes (states, statistics): the collection's own for generation 0, this experiment's after.

samples

samples(generation: int) -> SampleSet

The stored SampleSet of generation (labels, statistics, manifest; no features). Unavailable if housekeeping deleted it — keep_samples.

featurized

featurized(generation: int) -> SampleSet

The samples of generation WITH this experiment's features, made now from the stored states (dynaplex.featurize): what its agent is trained on.

agent

agent(generation: int = -1) -> 'NNAgent'

The trained NNAgent of generation (>= 1; agent_gen{g} rolled out generation g's collection). -1 = the latest trained generation.

agents

agents() -> list

All trained agents, ascending generation.

train_policy

train_policy() -> 'NNAgent'

The generation-1 agent: trained on generation 0 (collected first if it is not there), or loaded if it was trained before.

run

run(generations: int) -> list

Run the loop up to generations TOTAL trained generations (idempotent — existing artifacts are loaded, not redone) and return the trained agents.

WorkdirMismatchError

Bases: ValueError

An explicit workdir already records a different experiment (see DCL).

CollectionInProgressError

Bases: RuntimeError

Another run on this machine is collecting generation 0 in this directory.

featurize

featurize — the features of stored states.

x = dynaplex.featurize(mdp, records + "/states", MyFeaturizer)   # {tensor name: [N, ...] array}

states is a block of states of mdp (what collect_samples(..., records=dir) leaves at dir/states; dynaplex.RecordWriter(path, <state class>, mdp) in general). Row k of every returned array is what features.write_features writes for the state in record k: the same bytes a collection would have written for that sample, because it is the same compiled featurizer on the same state.

So a featurizer is no longer part of collecting: collect once, and try as many featurizers (and networks) on those states as you like. The states are read one at a time and never exist as Python objects; what is held in memory is the result.

Design: roadmap/state_store_and_featurize.md sections 4 and 22.

featurize

featurize(mdp, states: str | os.PathLike, features: type[Featurizer], *, checks: bool | Literal['rehearsal'] | None = None, jit: bool | None = None) -> dict[str, np.ndarray]

The features of the states in the block at states, as written by the featurizer class features: one array per tensor of its spec, row k for record k. See the module docstring.

checks: as for collect_samples. "rehearsal" (the default) first featurizes a few states with every check on, so a mistake in the featurizer is reported with a source line, and then runs all of them fast; True = all of them checked; False = fast only; None = DYNAPLEX_CHECKS if set, else "rehearsal".

PPO

PPO(mdp: MDPProtocol, *, features: type[Featurizer], config: PPOConfig, network: Net | None = None, critic_network: Net | None = None, root: str | None = None, mdp_label: str | None = None, training_label: str | None = None, workdir: str | None = None, verbose: bool = True)

Masked PPO on a DynaPlex MDP; train() returns an NNAgent.

Parameters:

Name Type Description Default
mdp MDPProtocol

the MDP instance.

required
features type[Featurizer]

the featurizer CLASS. Must be importable by dotted path (it is recorded in the agent artifact — same constraint as DCL).

required
network Net | None

constructible actor spec (dynaplex.Net / dynaplex.MLP(...)); default MLP(). Built over the featurizer's declared spec, dict-forward, exactly like DCL's actor. Live torch modules are rejected.

None
critic_network Net | None

optional constructible spec for the CRITIC. Built as factory(spec, 1, **kwargs) — same dict-forward contract as the actor, one value per sample ([B, 1]). Default None = the built-in flat value head, which requires a SINGLE-tensor observation spec; multi-tensor featurizers (object-token bundles) must pass one. The critic is training machinery: it lives in checkpoint.pt and never enters the agent artifact.

None
config PPOConfig

PPOConfig (required — minibatch_size has no default).

required
root str | None

the directory runs are stored under (see the module docstring for what is made below it). None (default) = the environment variable DYNAPLEX_RUNS_DIR when it is set, else dynaplex_runs (the rule DCL follows, utilities/runs_dir.py). A relative path is relative to the current working directory.

None
mdp_label str | None

a readable label for the model's directory, {root}/{MDPClass}_ppo_{mdp_label}, in place of the hash of the model. A label taken by another model (other parameters, or other code) is refused (WorkdirMismatchError).

None
training_label str | None

a readable last part for this run's directory, {Featurizer}_{network}_{training_label}, in place of the hash of the network's parameters and the settings. A label taken by other settings is refused.

None
workdir str | None

this run's directory itself, in place of all of the above (no labels with it). A directory that holds a run with other settings is refused.

None
verbose bool

per-iteration progress lines.

True

train

train() -> NNAgent

Run the training loop; returns the BEST-evaluating agent (the final one when evaluation is unavailable). Artifacts land in self.workdir: best_agent/, final_agent/, checkpoint.pt, tensorboard/.

A completed workdir (existing final_agent/) is NOT retrained: the stored agent is loaded and returned.

PPOConfig dataclass

PPOConfig(minibatch_size: int, num_envs: int = 256, num_steps: int = 128, max_episode_steps: int | None = None, backend: str = 'engine', workers: int = 0, jit: bool | None = None, total_timesteps: int = 500000, update_epochs: int = 4, anneal_lr: bool = True, lr: float = 0.00025, gamma: float = 0.99, gae_lambda: float = 0.95, eps_clip: float = 0.2, vf_coef: float = 0.5, ent_coef: float = 0.01, max_grad_norm: float = 0.5, norm_adv: bool = True, clip_vloss: bool = True, target_kl: float | None = None, critic_hidden: tuple = (128, 128), eval_interval: int = 10, eval_trajectories: int = 256, device: str = 'cpu', compile_agent: bool = False, seed: int = 42)

Configuration for dynaplex.PPO. Only minibatch_size is required.

Batch sizing: one update batch is num_envs * num_steps (defaults: 256 * 128 = 32768). The engine env makes envs nearly free — per policy step the cost is one kernel round plus one batched forward, so hundreds to thousands of envs is the intended regime (the old num_envs=8 default was an artifact of the serial CPython adapter).

GAE horizon: don't shrink num_steps to compensate for env count — with gamma=0.99 the effective horizon is ~100 steps, so num_steps of 64-128 is the floor for dense-reward MDPs.

Large batches: at fixed total_timesteps, more envs means FEWER update iterations. Compensate with a higher lr and/or fewer update_epochs (measured on lost_sales: epochs 4 -> 1 more than doubles end-to-end steps/s), and raise total_timesteps rather than starving the update count.

minibatch_size instance-attribute

minibatch_size: int

Minibatch size (required); the number of minibatches per update batch is derived from it.

num_envs class-attribute instance-attribute

num_envs: int = 256

Parallel environments (kernel slots) collecting rollouts.

num_steps class-attribute instance-attribute

num_steps: int = 128

Steps per env between updates; one batch = num_envs * num_steps.

max_episode_steps class-attribute instance-attribute

max_episode_steps: int | None = None

Time-based truncation cap, passed to the env (None = env default: 2048 for infinite-horizon MDPs, never for finite-horizon ones).

backend class-attribute instance-attribute

backend: str = 'engine'

Env backend: "engine" (default; the compiled kernel, and a model that does not compile is an error), "python" (the CPython kernel, about ten times slower), or "auto" (the explicit request to fall back to "python", with a warning, when the engine build fails).

workers class-attribute instance-attribute

workers: int = 0

Worker worlds of the engine env (0 = auto).

jit class-attribute instance-attribute

jit: bool | None = None

JIT setting for the engine env (None = auto).

total_timesteps class-attribute instance-attribute

total_timesteps: int = 500000

Total env steps to train on (>= one batch).

update_epochs class-attribute instance-attribute

update_epochs: int = 4

Optimization epochs over each rollout batch.

anneal_lr class-attribute instance-attribute

anneal_lr: bool = True

Linearly anneal the learning rate to zero over training.

lr class-attribute instance-attribute

lr: float = 0.00025

Adam learning rate.

gamma class-attribute instance-attribute

gamma: float = 0.99

Discount factor.

gae_lambda class-attribute instance-attribute

gae_lambda: float = 0.95

GAE lambda.

eps_clip class-attribute instance-attribute

eps_clip: float = 0.2

PPO clipping coefficient (policy ratio and value clip).

vf_coef class-attribute instance-attribute

vf_coef: float = 0.5

Value-loss weight.

ent_coef class-attribute instance-attribute

ent_coef: float = 0.01

Entropy-bonus weight.

max_grad_norm class-attribute instance-attribute

max_grad_norm: float = 0.5

Gradient-norm clipping threshold.

norm_adv class-attribute instance-attribute

norm_adv: bool = True

Normalize advantages per minibatch.

clip_vloss class-attribute instance-attribute

clip_vloss: bool = True

Clip the value loss (original-PPO style).

target_kl class-attribute instance-attribute

target_kl: float | None = None

Early-stop an update when approximate KL exceeds this (None = off).

critic_hidden class-attribute instance-attribute

critic_hidden: tuple = (128, 128)

Hidden widths of the private value head (the actor comes from network).

eval_interval class-attribute instance-attribute

eval_interval: int = 10

Evaluate every this many iterations (0 = only the final evaluation).

eval_trajectories class-attribute instance-attribute

eval_trajectories: int = 256

Trajectories per evaluation (common random numbers across evaluations).

device class-attribute instance-attribute

device: str = 'cpu'

Torch device for training, e.g. "cpu", "cuda", "mps".

compile_agent class-attribute instance-attribute

compile_agent: bool = False

Opt-in torch.compile on actor and critic.

seed class-attribute instance-attribute

seed: int = 42

Training seed (numpy / torch / env streams).

SampleSet

SampleSet(features: dict, mask, y, q_sum, z, q_count, manifest: dict, info=None)

Five aligned numpy slabs + manifest; see the module docstring.

num_features property

num_features: int

Width of the SINGLE feature slab — raises on multi-tensor sets (only the v2-compat path and single-tensor conveniences may ask).

with_features

with_features(features: dict, featurizer: type, spec: dict) -> 'SampleSet'

This set with the feature slabs features (row k = sample k), as written by the featurizer class featurizer whose observation spec is spec:

x = dynaplex.featurize(mdp, records + "/states", MyFeaturizer)
train_set = samples.with_features(x, MyFeaturizer, dynaplex.modelling.feature_spec(MyFeaturizer, mdp))

A collection returns a set WITHOUT features: the states of its samples are on disk and any featurizer can be applied to them. The labels and statistics are shared with this set, not copied; the manifest records the featurizer and spec.

quality

quality(levels: tuple = (0.5, 1.0, 1.5, 2.0, 2.5, 3.0)) -> dict

Fraction of samples whose label separates from its closest rival at each z level. High fractions = statistically solid labels; fractions near zero = the labels are noise-picks among near-ties and a trained policy cannot be expected to improve on the rollout policy.

quality_line

quality_line() -> str

The legacy-format one-line quality report (SampleData::PrintStatistics).

save

save(path: str) -> None

Write the set as a directory of .npy slabs + manifest.json.

Atomic publish: everything is written to path + ".tmp" and renamed into place, so a reader never observes a half-written set. Refuses an existing path (artifacts are immutable — callers decide about replacement); a leftover .tmp from a crashed writer is silently discarded.

load classmethod

load(path: str, mmap: bool = False) -> 'SampleSet'

Load a saved set; mmap=True memory-maps the slabs read-only (training can slice minibatches without materializing the whole set).

merge classmethod

merge(sets: list['SampleSet']) -> 'SampleSet'

Concatenate shards IN THE GIVEN ORDER (the caller supplies ascending rank order; no shuffle — shuffling is training's job). Refuses shards whose manifests disagree on anything but row count / shard identity.

Records on disk

DCL writes the state and the statistics of every sample to disk while it collects, as records: objects of one class, appended one after the other from compiled model code. The same writers and readers are available to your own model code and harnesses.

RecordWriter dataclass

RecordWriter(path: str | os.PathLike, cls: type, mdp=None, *, chunk_values: int = DEFAULT_CHUNK_VALUES)

Writes objects of class cls to a new block at path. mdp is the model their const references belong to; a class that refers to nothing const needs none. See the module docstring.

close

close() -> int

Complete the block: the rest of the numbers, the offsets, the manifest. Returns the number of records written. Closing again does nothing.

discard

discard() -> None

Close without leaving a block.

RecordReader dataclass

RecordReader(path: str | os.PathLike, cls: type, mdp=None)

Reads the records of the block at path, which must have been written for the same class cls and the same mdp (or none). count is the number of records in it.

append_record

append_record(obj, writer: RecordWriter) -> int

Append obj to the writer's block; returns its record number.

read_record

read_record(obj, reader: RecordReader, record: int) -> None

Read record number record INTO obj, which keeps its identity.

read_record_into

read_record_into(objs: list, reader: RecordReader, record: int) -> None

Read record number record as a NEW object and append it to the list objs. (In CPython a list does not say what it holds; the reader's class is used.)

reserve

reserve(xs: list, n: int) -> None

Make room in the list xs for n elements in total. See the module docstring.

Built-in policies

RandomPolicy

Pick uniformly among the actions the MDP marks valid in the current state.

Works for ANY MDP unchanged: each decision it obtains the action-validity mask from mdp.write_action_validity (via the context's reusable scratch, context.valid — no per-call allocation) and draws one of the valid actions uniformly from the trajectory's policy stream (context.policy_rng). Under the built-in algorithms the results are reproducible, worker-count-invariant, and safe for common-random-number comparisons.

Typical use: a zero-knowledge generation-0 rollout policy for DCL when no domain heuristic is available (a sensible heuristic, when you have one, remains the better starting point), or a baseline in PolicyComparer runs.

Example:

```python
from dynaplex.models import RandomPolicy

d = dp.DCL(mdp, RandomPolicy(mdp), ...)
agents = d.run(2, features=MyFeaturizer)
```

Construct with the MDP whose valid actions are to be sampled — only its num_actions attribute and write_action_validity method are used.

Featurizers

A featurizer turns a decision state into the tensors a network consumes. Its writer fields declare the representation and write_features fills one batch row through them; spec() declares the observation spec — a plain dict[str, TensorSpec], one named tensor per writer field, batch axis implicit. An observation batch is the matching dict of batched arrays (everything downstream — network factories, SampleSet slabs, gym observations — is keyed the same way). spec() is optional on the class: when omitted, @featurizer synthesizes one that sizes by counting on a probe state.

Featurizer

Base class of every featurizer — subclass it, apply @featurizer above @dataclass(slots=True), declare mdp plus writer fields (all Final — a featurizer is bound once), and write write_features::

@featurizer
@dataclass(slots=True)
class MyFeaturizer(Featurizer):
    mdp: Final[MyMDP]
    v: Final[GlobalStateWriter]

    def write_features(self, state: MyState) -> None:
        self.v.append(float(state.on_hand))

The base carries no fields: it exists so type checkers know a featurizer class up front (the features= argument of DCL, PPO, VectorEnv and PolicyComparer is type[Featurizer]) and see the methods @featurizer synthesizes onto the subclass (bind/reset/finish/spec and the derived Holder). The stubs here are never compiled: the decorator always overrides them on the concrete class, and they raise if reached (a featurizer used without the decorator). Same shape as TrajectoryContext / @trajectory_context.

bind

bind(h: Any) -> 'Featurizer'

A NEW featurizer of this class whose writers write into holder h's arrays (this instance is the factory: same mdp, fresh writers). Replaces the old in-place install(h): writer fields are Final, so binding to a holder is construction, not mutation — fz = fz.bind(h).

featurizer

featurizer(cls: type[_T] | None = None, /, *, probe_steps: int | None = None) -> type[_T] | Callable[[type[_T]], type[_T]]

Class decorator (apply ABOVE @dataclass): derive the FeatureHolder class and synthesize the absent methods — the field-walk trio install/reset/finish (engine-compiled) plus spec (CPython-only, declaration-by-counting).

@featurizer(probe_steps=N) sets how many events probe_state may walk from the initial state to reach the first decision (default PROBE_STEPS_DEFAULT, 1000); it is the one knob, read by the synthesized spec(), the dress rehearsal (assert_featurizer_for_mdp, hence check_mdp, rehearse and DCL) alike.

Defined by its expansion: the result is exactly the equivalent hand-written desugared form. Hand-written methods are left untouched (the escape hatch); a hand-written install also takes over holder selection — its parameter annotation IS the holder (holder_from_featurizer reads it), so nothing is derived or attached in that case. Otherwise the derived holder is attached as cls.Holder (user convenience; dcl itself deduces via install's annotation).

GlobalStateWriter module-attribute

GlobalStateWriter = FeatureWriter

The observation spec

TensorSpec dataclass

TensorSpec(dtype: Dtype, sample_shape: tuple)

One named featurizer output tensor: element dtype + PER-SAMPLE shape. The batch axis is deliberately NOT part of the shape — it belongs to the bundle, not the tensors (one spec serves n_target, slot capacity and minibatch size alike; the allocator prepends it: slab = [B, *sample_shape]).

Dtype

Bases: _enum.Enum

Element type of a spec tensor — a CLOSED vocabulary (what the writers can produce), deliberately in the engine-registrable enum shape (direct Enum subclass, consecutive int values from 1 — ONNX TensorProto precedent) even though nothing engine-side reads it today. Serialize by NAME, never by value: values renumber when members are inserted; names are the format. Names match numpy's (np.dtype(d.name) works).

feature_spec

feature_spec(features_cls, mdp) -> dict[str, TensorSpec]

THE observation spec for (featurizer, mdp): what features_cls.spec() declares, keyed by writer field name. A spec is a plain dict — the same shape a network factory receives, the agent sidecar stores and the SampleSet manifest carries. Note num_actions is NOT part of it: input representation and action space are different concerns (factories take both, separately).

GlobalStateCounter

GlobalStateCounter()

Bases: FeatureWriter

The counting twin of GlobalStateWriter — same write surface, but it only tracks how many values were written, never storing them. CPython-only (never compiled). It subclasses FeatureWriter purely so a counter can be assigned to a GlobalStateWriter field under a type checker (the written-out spec() idiom); it has no array, and the engine never sees one (writer kinds are matched by class identity, not isinstance).

Writer/counter pairing is the auto-sizing mechanism: construct the featurizer with a counter in a writer field, run write_features on a probe state, and ask the counter for the field's TensorSpec via spec(). Later writer kinds add their own counters (ObjectWriter <-> ObjectCounter), each reporting its own spec, so spec synthesis never needs to know writer kinds.

Usage

counter = GlobalStateCounter() twin = FeaturizerCls(mdp=mdp, v=counter) # a counter stands in for the writer field twin.write_features(await_action_state) ts = counter.spec() # TensorSpec(Dtype.float32, (count,))

Create a feature counter initialized to zero (no backing array).

append

append(x: float) -> None

Count one scalar value.

append_many

append_many(*xs: float) -> None

Count multiple scalar values.

extend

extend(xs: list[float] | list[int] | list[bool] | NDArray[np.float64] | NDArray[np.int64] | NDArray[np.bool_]) -> None

Count values from a list or numpy array.

spec

spec() -> 'TensorSpec'

The counted field's TensorSpec: one flat float32 vector of count values.

reset

reset(row: int) -> None

No-op: a counter has no row (protocol parity with FeatureWriter).

finish

finish() -> None

No-op: nothing to check while counting (protocol parity with FeatureWriter).

probe_state

probe_state(mdp, seed: int = 42, max_steps: int = PROBE_STEPS_DEFAULT)

A representative decision state: the initial state advanced to its first AWAIT_ACTION. Pure CPython. This is the state handed to synthesized spec() bodies (declaration-by-counting) and to the dress-rehearsal verifier; also handy in tests and for poking at an MDP interactively.

The walk is seeded (42), so an MDP that reaches no decision within max_steps events does so deterministically: that is a property of the model and its initial state, not bad luck.

Agents and networks

NNAgent

NNAgent(module: _tnn.Module, spec: dict, num_actions: int, featurizer: str, network: Net, info: dict | None = None)

The trained bundle: featurizer reference + network + selection + frozen spec.

Callable at three cuts
  • agent(states, mdp=mdp) — pure-CPython convenience: featurize + forward + masked argmax on ordinary state objects (the cheapest way to test an agent).
  • agent.activations(features) — training/diagnostics cut.
  • agent.act(features, mask) — the engine-loop cut (what the DCL gen>=1 loop and the comparer NN path call).

to

to(device) -> 'NNAgent'

Move the FORWARD to device ("mps"/"cuda"/"cpu") and return self. This is the lever for gen>=1 collection and comparer evaluation throughput — their per-round minibatched forwards run wherever the agent lives (inputs are moved per call; outputs come back as numpy). Note the reproducibility caveat: results are bit-reproducible per (machine, torch build, DEVICE) — a cpu run and an mps run of the same collection may differ in near-tie argmaxes.

compile

compile(**kwargs) -> 'NNAgent'

Wrap the forward in torch.compile and return self (chainable, like to). Opt-in: one-time warmup of tens of seconds buys a measurably faster CPU forward on big per-round batches (the gen>=1 collection regime), and the compiled forward is bitwise-equal to eager on CPU — the action stream does not change. Serialization is untouched (save stores the plain module); compiling is a process-local property, never part of the agent's identity. Idempotent: a second call (any kwargs) is a no-op.

activations

activations(features: dict) -> np.ndarray

feature bundle (dict keyed by tensor name) -> activations [B, A].

act

act(features: dict, mask: np.ndarray) -> np.ndarray

(features, mask) -> actions [B] — the boundary cut of both engine loops. Torch-side end to end (forward, masking, argmax): only the [B] action vector crosses back to numpy, never the [B, A] activations. Same selection rule as masked_argmax, guaranteed by construction (measured on the DVRP example: the numpy round-trip was a third of gen>=1 act() time).

save

save(path: str) -> None

Directory of weights.pt + agent.json; atomic tmp+rename, refuses an existing path (artifacts are immutable).

MLP

MLP(hidden=(128, 128)) -> Net

The default network: Net sugar for the built-in MLP factory.

Net

Net(factory: str, **kwargs)

Constructible network spec: importable factory path + JSON-able kwargs. The ONLY way to specify a network (live modules are rejected by design — agent files must rebuild on cold nodes from importable code).

label

label() -> str

The readable name of this network, as a DCL experiment's directory uses it: what the factory's net_factory(label=...) says for these parameters, else the factory's function name without a trailing _factory. Imports the factory.

net_factory

net_factory(*, label)

Decorator for a network factory: how its networks are called in a run directory.

@dynaplex.net_factory(label=lambda d_model, n_layers: f"gin_{n_layers}x{d_model}")
def gin_factory(spec, num_actions, d_model=64, n_layers=6): ...

label is a function of the factory's own parameters (the ones it names, or all of them when it takes **kwargs); it is called with the values a Net gives, and the factory's defaults for the rest, and returns a short name of letters, digits, ., _ and -. A plain string is a fixed name. A factory without this decorator is called by its function name, without a trailing _factory, whatever its parameters are. See Net.label.

train_network

train_network(samples: SampleSet, *, network: Net | None = None, loss: str = 'soft_ce', epochs: int = 1000, batch_size: int = 64, lr: float = 0.0001, patience: int = 10, val_fraction: float = 0.05, val_every: int = 5, seed: int = 0, device: str = 'cpu', features=None, verbose: bool = False, step: str = 'auto') -> NNAgent

Train a network on a stored SampleSet; returns the NNAgent bundle.

Standalone and engine-free: never touches states or MDPs. The featurizer identity comes from the SampleSet manifest (or pass features= to override with the class itself). Targets per loss are computed once in numpy (see the module docstring; the default "soft_ce" puts the label mass on the final-round survivors by their cost gaps, "ce" is the hard one-hot on the winner, "count_ce" the visit-count form); the optimization is masked cross-entropy with Adam, deterministic in seed (per torch's per-build determinism caveats).

Training regimen (the legacy PolicyTrainer recipe + the DCL paper's Table 1 — with ONE deliberate deviation: default lr is 1e-4 where legacy hardcoded 1e-3. 1e-3 diverged outright on the DVRP example while 1e-4 matched the Akkerman paper's own tuned value; the safe rate is the right default, easy problems just take a few more epochs under the same early stopping): one seeded shuffle, then a validation split of max(1, val_fractionn) samples; the TRAINING set is RESHUFFLED EVERY EPOCH (measured to matter); validation loss every val_every epochs (legacy: 5), the best-validation weights are checkpointed and RESTORED at the end; early stopping once the epochs since the last validation improvement EXCEED patience — legacy's rule, so with the defaults training stops after the third failed check, 15 epochs without improvement (epochs is the maximum). val_fraction=0 disables the split, best-weight tracking and early stopping (fixed epochs on all data). verbose prints a line at every validation — losses with the legacy 100exp(-loss) percentage — plus the estimated validation cost REGRET per period (mean of qbar[predicted] - qbar[best] from the SH-honest q record; partial-budget means for eliminated actions make it an estimate). step: "auto" (default: graph on cuda, eager elsewhere), "eager", or "graph" (cuda only): the whole minibatch step — gather into static buffers, forward, masked loss, backward, Adam — is captured ONCE as a CUDA graph and replayed per minibatch (one launch instead of ~30; at batch 64 the eager step is launch-bound at ~1 ms on an A100). Same regimen: same minibatches in the same order, the last partial batch of an epoch runs eagerly, the capture warm-up is undone in place so the first replay is the first Adam step from the initial weights. Measured on an A100 (150k samples, batch 64): 2.9 -> 0.46 s/epoch (128x128), 3.9 -> 0.62 (256x256); the weights are reproducible run to run but differ from eager's at rounding level (the captured kernels and the capturable optimizer round differently); validation losses agree to 3 decimals.