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 |
5000
|
m
|
int
|
Rollout replications per candidate action (any value; need not
divide |
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
|
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'
|
gen0
|
'Shape | None'
|
A |
None
|
trained
|
'Shape | None'
|
The same overlay for the shape generations >= 1 run,
where the trained policy forwards on |
None
|
device
|
str | None
|
Where generation >= 1 rollout agents forward
( |
None
|
policy_binding
|
str | None
|
|
None
|
policy_precision
|
str | None
|
precision of the agent's forward on a device
binding ( |
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
|
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 |
None
|
restart_after
|
int
|
Labels (samples) a main trajectory contributes
before it is retired and its slot restarted on a fresh warm
state (legacy |
0
|
sample_info
|
bool
|
Record every sample's provenance (controller, arms,
warm-start origin, label index, time, rounds, row) as the
SampleSet's |
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 |
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 |
5
|
root
|
str | None
|
The directory runs are stored under. |
None
|
gen0_label
|
str | None
|
A readable label for the collection's directory:
|
None
|
workdir
|
str | None
|
The collection's directory. |
None
|
keep_samples
|
str
|
Retention of an experiment's LATER generations, applied
after each generation trains: |
'all'
|
verbose
|
bool
|
Print per-generation progress. |
True
|
jit
|
bool | None
|
|
None
|
checks
|
bool | Literal['rehearsal'] | None
|
Runtime checks in the compiled kernels, applied to the
GENERATION-0 collection only. |
None
|
gc_threshold_bytes
|
int
|
Auto-GC trigger threshold for the worker worlds. |
16 << 20
|
torch_threads
|
int | None
|
If set, |
None
|
compile_agent
|
bool
|
|
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 ¶
The resolved split generation generation runs: gen0 for 0, trained after.
records ¶
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 |
required |
network
|
'Net | None'
|
A constructible network spec ( |
None
|
train
|
dict | None
|
Keyword arguments for |
None
|
training_label
|
str | None
|
A readable last part for the experiment's directory,
|
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
¶
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 ¶
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 ¶
The trained NNAgent of generation (>= 1; agent_gen{g} rolled out
generation g's collection). -1 = the latest trained generation.
train_policy ¶
The generation-1 agent: trained on generation 0 (collected first if it is not there), or loaded if it was trained before.
run ¶
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 ( |
None
|
critic_network
|
Net | None
|
optional constructible spec for the CRITIC. Built as
|
None
|
config
|
PPOConfig
|
|
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 |
None
|
mdp_label
|
str | None
|
a readable label for the model's directory,
|
None
|
training_label
|
str | None
|
a readable last part for this run's directory,
|
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 (required); the number of minibatches per update batch is derived from it.
num_envs
class-attribute
instance-attribute
¶
Parallel environments (kernel slots) collecting rollouts.
num_steps
class-attribute
instance-attribute
¶
Steps per env between updates; one batch = num_envs * num_steps.
max_episode_steps
class-attribute
instance-attribute
¶
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
¶
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
¶
Worker worlds of the engine env (0 = auto).
jit
class-attribute
instance-attribute
¶
JIT setting for the engine env (None = auto).
total_timesteps
class-attribute
instance-attribute
¶
Total env steps to train on (>= one batch).
update_epochs
class-attribute
instance-attribute
¶
Optimization epochs over each rollout batch.
anneal_lr
class-attribute
instance-attribute
¶
Linearly anneal the learning rate to zero over training.
eps_clip
class-attribute
instance-attribute
¶
PPO clipping coefficient (policy ratio and value clip).
max_grad_norm
class-attribute
instance-attribute
¶
Gradient-norm clipping threshold.
norm_adv
class-attribute
instance-attribute
¶
Normalize advantages per minibatch.
clip_vloss
class-attribute
instance-attribute
¶
Clip the value loss (original-PPO style).
target_kl
class-attribute
instance-attribute
¶
Early-stop an update when approximate KL exceeds this (None = off).
critic_hidden
class-attribute
instance-attribute
¶
Hidden widths of the private value head (the actor comes from network).
eval_interval
class-attribute
instance-attribute
¶
Evaluate every this many iterations (0 = only the final evaluation).
eval_trajectories
class-attribute
instance-attribute
¶
Trajectories per evaluation (common random numbers across evaluations).
device
class-attribute
instance-attribute
¶
Torch device for training, e.g. "cpu", "cuda", "mps".
compile_agent
class-attribute
instance-attribute
¶
Opt-in torch.compile on actor and critic.
seed
class-attribute
instance-attribute
¶
Training seed (numpy / torch / env streams).
SampleSet ¶
Five aligned numpy slabs + manifest; see the module docstring.
num_features
property
¶
Width of the SINGLE feature slab — raises on multi-tensor sets (only the v2-compat path and single-tensor conveniences may ask).
with_features ¶
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 ¶
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 ¶
The legacy-format one-line quality report (SampleData::PrintStatistics).
save ¶
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 a saved set; mmap=True memory-maps the slabs read-only (training
can slice minibatches without materializing the whole set).
merge
classmethod
¶
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.
RecordReader
dataclass
¶
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 ¶
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 ¶
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).
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 ¶
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).
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 ¶
The counted field's TensorSpec: one flat float32 vector of count values.
finish ¶
No-op: nothing to check while counting (protocol parity with FeatureWriter).
probe_state ¶
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 ¶
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 ¶
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 ¶
feature bundle (dict keyed by tensor name) -> activations [B, A].
act ¶
(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 ¶
Directory of weights.pt + agent.json; atomic tmp+rename, refuses an existing path (artifacts are immutable).
Net ¶
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 ¶
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 ¶
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.