Evaluating policies¶
Comparing policies and assessing their performance — see the
policy comparison guide for usage;
the exact solver has its own page.
Everything on this page is imported from the top-level dynaplex
package.
PolicyComparer ¶
PolicyComparer(mdp: Any, *, number_of_trajectories: int | None = None, warmup_time: int | None = None, horizon: int | None = None, seed: int = 0, workers: int = 0, max_steps: int = 1 << 20, backend: str = 'engine', jit: bool | None = None, checks: "bool | Literal['rehearsal'] | None" = None, nn_batch: int = 1024, verbose: bool = False)
Bases: Generic[_S]
Evaluate policies on an MDP over common-random-number trajectories.
Generic over the MDP's statistics holder: PolicyComparer(mdp) is a
PolicyComparer[MyStats] when the MDP's context names Stats = MyStats,
a PolicyComparer[TrajectoryStats] for an MDP without a custom context,
and untyped (Any) for a custom context that leaves Stats derived — so
assess(...).stats is typed wherever it can be.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mdp
|
Any
|
the MDP instance; dispatches on |
required |
number_of_trajectories
|
int | None
|
default 4096 (infinite) / 16384 (finite), as legacy. |
None
|
warmup_time
|
int | None
|
INFINITE only (error if set on a finite-horizon MDP);
default 128. Time units of |
None
|
horizon
|
int | None
|
INFINITE only (error if set on a finite-horizon MDP); default 1024. Length of the measurement window in time units. |
None
|
seed
|
int
|
global experiment seed (eval seed space — disjoint from training). |
0
|
workers
|
int
|
worker worlds per engine (compiled backend). 0 = auto (cpu_count - 2, capped at number_of_trajectories). Pure throughput knob: seeds key on the GLOBAL trajectory index, so results are worker-count-invariant bit-for-bit. The Python backend runs serially regardless. |
0
|
max_steps
|
int
|
per-trajectory raw-step safety cap. Guards finite-horizon
MDPs that never reach FINAL and infinite-horizon MDPs that forget
to advance |
1 << 20
|
backend
|
str
|
"engine" (default) compiles an engine kernel per policy; a
build failure (a compile error, a promise violation) PROPAGATES.
"python" runs the pure-Python kernel. "auto" is the explicit opt-in
to a fallback: engine, and on a build failure the Python kernel
with a warning — never silently. The backends are bit-identical,
so mixing them inside one compare preserves exact CRN pairing.
A trained agent ( |
'engine'
|
jit
|
bool | None
|
passed through to Engine (None = auto, True = require, False = interpreter). Engine-backend only. |
None
|
checks
|
"bool | Literal['rehearsal'] | None"
|
runtime checks in the compiled kernels (roadmap/checks_mode.md). "rehearsal" (the default): every policy is first evaluated on a short seeded pass (32 trajectories) through CHECKED kernels, then the real evaluation runs FAST (asserts and list bounds compiled out). True = the whole run checked; False = fast, no rehearsal. None takes the DYNAPLEX_CHECKS=0|1 environment override if set, else "rehearsal". Engine-backend only (CPython is always checked). |
None
|
nn_batch
|
int
|
NNAgent policies only — the episode-slot WORKING SET of the NN round-trip harness (dcl_gen1_api.md section 5): bounds live states/ memory and sets the network's forward batch; the trajectories STREAM through min(nn_batch, number_of_trajectories) slots. Execution detail: per-episode seeds key on the global episode index, so results are invariant to it (exactly, modulo forward-precision argmax near-ties — torch ULPs can differ across batch shapes). |
1024
|
assess ¶
assess(policy, *, name: str | None = None) -> PolicyAssessment[_S]
Evaluate one policy; delta_* fields stay None (no benchmark).
compare ¶
compare(*policies, benchmark: int | str = 0) -> Comparison[_S]
Evaluate several policies on common random numbers.
Accepts policies as positional args, a single list/tuple, or a single
dict {name: policy} (dict keys become the result names). benchmark
selects the benchmark policy by index (default 0 = the first) or by
name (e.g. benchmark="S=28" with dict input); deltas are always
computed as policy - benchmark, paired per trajectory.
PolicyAssessment
dataclass
¶
PolicyAssessment(name: str, policy: object, mean: float, error: float, returns: NDArray[np.float64], stats: _S_co, delta_mean: float | None = None, delta_error: float | None = None, is_benchmark: bool = False, backend: str = 'python')
Bases: Generic[_S_co]
Result of evaluating one policy. mean/error are ALWAYS the absolute
metric (cost per unit time for infinite horizon, episode cost for finite);
the paired difference vs the benchmark lives in the separate
delta_mean/delta_error fields (set by compare, None from assess,
0.0 for the benchmark itself). stats is the MDP's context statistics
holder: the context's collected fields — cumulative_cost, time_elapsed
and every statistic a custom context declares — under the same names, each
with a leading trajectory axis. Its type is the holder the context names
(a context with Stats = MyStats gives stats: MyStats;
TrajectoryStats for MDPs without a custom context). Raw window totals, no
normalization; row i is trajectory i under common random numbers for every
policy and backend.
to_dict ¶
Old-style plain-dict view (policy object and per-trajectory returns not included).
Comparison ¶
Comparison(assessments: list[PolicyAssessment[_S_co]])
Bases: Sequence[PolicyAssessment[_S_co]], Generic[_S_co]
List-like result of PolicyComparer.compare: one PolicyAssessment per
policy, in input order. Indexable by int/slice AND by name (results["zipkin"]).
Renders as a table; .to_dicts() for old-script ports.
Model check¶
Runs the MDP under a policy in plain Python — no compile — and fails with a
hint naming the method when the decision structure is degenerate (a category
that never changes, time that never advances, an unwritten validity mask, no
real choice at any decision, hidden state outside the State object). Run it
before rehearse. See Promises → Checking the model dynamically.
check_mdp ¶
dynaplex.check_mdp — the dynamic model exerciser (roadmap/mdp_validation_improvements.md).
The legacy Tester::ExecuteTest role: run the MDP under a policy in plain CPython, no
Engine, no compile, and report degenerate decision structure with a hint that names the
user's method. It complements dynaplex.rehearse (checked compiled kernels + CPython
parity): run check_mdp first — seconds, precise messages — then rehearse.
Per seed the driver runs one trajectory until time_elapsed >= periods (infinite
horizon) or FINAL (finite), counting events, decisions and valid actions, and fails on:
- category incoherence — an initial or transitioned state that is FINAL on an
infinite-horizon MDP, an initial state that is already FINAL, a category that is not
a
StateCategory; - program flow (opt-out
relax_program_flow) — an action-only loop, transitions that never advancetime_elapsed(infinite horizon), the raw-step cap, substantially fewer decisions than periods; - no real decisions (opt-out
skip_no_decisions_check) — over the whole run every decision state offered exactly one valid action (or none was ever reached): the model would hang DCL before round one (roadmap/dcl_robustness.md 16.1); - validity-mask discipline —
write_action_validityleft an entry unwritten (the driver poisons the mask before every call), no valid action, or the policy chose an action the mask marks invalid; - non-determinism — seed 0 run twice must produce the same transition trace (module globals, unseeded numpy, mutable class attributes);
- with
features=: the featurizer's declaration is validated against the MDP (assert_featurizer_for_mdp), thenwrite_featuresruns in CPython on every decision state of seed 0 through a one-row holder, and any non-finite value (NaN, inf) in a written row fails — a bug nothing else catches before training diverges.
The legacy representation checks (serialization roundtrip, equality reflexivity) have
no counterpart: store, clone, == and deep_hash are derived from the dataclass
fields by reflection, so a field cannot be forgotten. Static rules (cost/time accumulate-only, rng-bind-once, event-stream-only) are promises
checked before any compile (roadmap/mdp_contract_validation.md); they are NOT
re-derived here.
MdpCheckReport
dataclass
¶
MdpCheckReport(seeds: int, periods: int, policy: str, horizon_type: HorizonType, events: int, decisions: int, valid_actions: int, episodes_without_decision: int, finals: int, max_steps: int, feature_rows: int)
What check_mdp ran and counted (a raise, not a field, reports a failure).
check_mdp ¶
check_mdp(mdp: Any, policy: Any = None, *, features: type | None = None, seeds: int = 64, periods: int = 128, relax_program_flow: bool = False, skip_no_decisions_check: bool = False, seed: int = 0) -> MdpCheckReport
Exercise mdp under policy (default: dynaplex.RandomPolicy) for seeds
trajectories of periods time units each, in plain CPython; with features=
(a featurizer class) also featurize every decision state of seed 0 and fail on a
non-finite feature value. See the module docstring for the checks. Raises
DynaPlexError with a hint naming the offending method; returns the counters
otherwise.
MdpCheckReport
dataclass
¶
MdpCheckReport(seeds: int, periods: int, policy: str, horizon_type: HorizonType, events: int, decisions: int, valid_actions: int, episodes_without_decision: int, finals: int, max_steps: int, feature_rows: int)
What check_mdp ran and counted (a raise, not a field, reports a failure).
Rehearsal¶
The model checker: the checked pass every algorithm runs by default
(checks="rehearsal"), as a standalone call. See Language reference →
Runtime checks and fast mode.
rehearse ¶
dynaplex.rehearse — the standalone model checker (roadmap/checks_mode.md §4).
The harnesses (PolicyComparer, VectorEnv, DCL) rehearse on their own: with
checks="rehearsal" (the default) they run a short seeded pass through
CHECKED kernels before compiling the fast ones. rehearse is that step as a
callable you can run first, on any (mdp, policy[, featurizer]) triple:
- structural checks — the policy shape, and the featurizer's declaration
against the MDP (
assert_featurizer_for_mdp: field walk, spec, one-row dress rehearsal); - a CHECKED, compiled simulation of the policy on
trajectoriesseeded trajectories through the comparer kernel — everyassertand list bound in the model is live, so a violation raisesDynaPlexErrorhere; - CPython-vs-compiled parity: the same trajectories through the comparer's pure-Python kernel must give bytewise identical returns (a compiler divergence is the other class of problem a user cannot see);
- with a featurizer and the optional
gymnasiumdependency installed: a CHECKED pass of the gym kernel driven by random valid actions, compared bytewise against its CPython execution.
Deterministic misuse (a feature-count mismatch, an always-violated assert) is
caught on the first state; rare-state index errors are probabilistic — for a
run that misbehaves in fast mode, DYNAPLEX_CHECKS=1 reruns it fully checked
without a code change.
RehearsalReport
dataclass
¶
What a rehearsal ran and found (a raise, not a field, reports a failure).
rehearse ¶
rehearse(mdp: Any, policy: Any, *, features: type | None = None, trajectories: int = 32, seed: int = 0, workers: int = 1, warmup_time: int | None = None, horizon: int | None = None, jit: bool | None = None) -> RehearsalReport
Check (mdp, policy[, features]) with every runtime check live; see the module
docstring. Raises DynaPlexError on a violated model assert/list bound,
RuntimeError on a compiled-vs-CPython divergence, and the structural
validators' own errors. warmup_time/horizon apply to infinite-horizon
MDPs only (PolicyComparer's defaults otherwise).
RehearsalReport
dataclass
¶
What a rehearsal ran and found (a raise, not a field, reports a failure).