Policy iteration (DCL)¶
Rollout planner, decision collection and distillation; see the DCL guide.
gympn.policy_iteration.RolloutPlanner ¶
One-step rollout improvement of base (see the module docstring).
rollouts : episodes played out per option.
component : compare only the options of the base choice's component and
score them by that component's return (True), or compare all options
by the whole net's return (False).
beta : SMDP discount of the return-to-go, exp(-beta * (t - now)); 0 = the
undiscounted return (what evaluation measures).
lockstep : with a network base policy, play all rollouts of a decision
side by side with batched forward passes (same returns as one at a
time, much faster).
restrict : with component=True, simulate only the component in the
rollouts (GymProblem.sim_only = its member transitions): no other
component can affect its future (the certificate), so this is exact
for the score and removes the other components' cost and noise; the
network base then reads the component's subgraph only (its logits do
not depend on anything else: no edges leave a component, and the
actor's attention is masked to it).
keyed : common random numbers through keyed streams
(GymProblem.stream_seed): in rollout j of every option, the k-th
firing of each transition draws the same random numbers, however the
options' trajectories differ. With keyed=False the options only share
the start of one global stream, which shifts as soon as they fire
different transitions.
coalesce : with keyed streams, the base choice's rollouts are played
first and record the state fingerprint (GymProblem.state_fingerprint)
at each step; rollout j of another option that reaches a state rollout
j of the base choice has visited stops there and takes the base
rollout's remaining return, which it would have collected identically.
Exact; saves the steps after the trajectories re-merge.
resample : fn(problem) called at the start of every rollout (after the
rollout's seeding) to redraw what the deciding policy cannot know,
e.g. the already-drawn times of future arrivals, which the simulator
state holds but the observation does not show. Without it the
rollouts see that hidden future, and the planner's choices partly
rest on information no policy has. The same draws for every option
(common random numbers).
margin : depart from the base's choice only when the best option's mean
rollout return beats the base's by more than this.
confirm : when > 0, a departure from the base is kept only if a second,
independent scoring (confirm rollouts per option, other seeds)
departs to the same option; else the base's choice stands. Removes
the departures that are rollout noise, at a cost only where the
planner departs.
sh_budget : when > 0, choose() selects by Sequential Halving with common
random numbers, as Deep Controlled Learning does (Temizoz et al.,
EJOR 2025): sh_budget * (number of options) rollouts in total,
spread evenly over ceil(log2 options) rounds; each round plays every
surviving option with the round's rollouts (paired: the same seeds for
all options, fresh seeds each round), returns accumulate over the
rounds, and the better half (by mean accumulated return) survives.
The last survivor is the choice; no margin, no test.
race_eps : when set (permits), choose() selects by racing, an adaptive
alternative to sh_budget: rounds of race_step paired rollouts of every
surviving option (the same seeds for all of them, fresh seeds each
round, so the survivors stay paired over all rounds). From race_min
rollouts on, an option is eliminated when the leader's mean paired
advantage over it exceeds race_z standard errors, and the race stops
when no survivor's upper bound (mean paired difference to the leader
+ race_z standard errors) reaches race_eps, or at race_cap rollouts
per option. The leader is the choice; the survivors are its label set
(last["set"], _record's t_set). A clear winner stops early; a near tie
stops once its gap is shown to be below race_eps. race_z is a
per-look threshold (no correction for repeated looks), so the error
rate is controlled in practice, not guaranteed.
test, min_t : when test > 0, a departure is tested on test fresh
rollouts (other seeds) of only the chosen option and the base's,
paired by rollout: it is kept only if the mean paired advantage
exceeds the margin and its t statistic (mean / standard error) is at
least min_t. Unlike confirm, the test does not redo the choice among
the options, so a near tie between two good departures does not
veto both; and the fresh rollouts remove the selection's optimism.
option_values ¶
option_values(env, tag=(), anchor=None)
Mean rollout return of every option (class of equivalent bindings)
in the component of the binding anchor (default: the base policy's
choice), each option played first and the base policy after, under
common random numbers. Returns (reps, scores, h): one binding index per
option, their scores (None when there is a single option, so no
rollouts), and the base policy's choice. env is left as it was.
choose ¶
choose(env, tag=()) -> int
The planner's action at env's current decision. tag (e.g. the
episode and step) makes the rollout seeds distinct per decision.
gympn.policy_iteration.HeuristicBase ¶
A gympn heuristic as a base policy. The heuristic receives the problem itself when nothing in it is unobservable (cheap), else its heuristic observation.
gympn.policy_iteration.NetworkBase ¶
A policy network as a base policy (greedy, or sampling).
gympn.policy_iteration.collect_decisions ¶
collect_decisions(make_env: Callable, planner_fn: Callable, seeds: Sequence[int], workers: int = 1, log: Optional[Callable] = None) -> List
Play the planner on one episode per seed (Python and NumPy random reseeded, then env.reset(), like the evaluation) and record every decision as the observation graph with t_mask_a / t_mask_p, the class of the planner's choice. make_env() and planner_fn(env) must be picklable (module-level functions) when workers > 1. Returns graphs, in seed order.
gympn.policy_iteration.episode_components ¶
episode_components(make_env: Callable, seed: int = 0) -> List[frozenset]
The net's components by the STATIC certificate (the net structure, before anything fires), each as the set of its member transitions, in a fixed order (by smallest member id). Static, not the marking certificate after a reset: the reset already fires start-of-episode transitions (e.g. a backlog that opens the day), which the marking certificate then drops as dead, and a component simulated alone without them would start from the wrong marking. Static components are independent too, so simulating one alone is exact. (seed is unused; kept for the signature.)
gympn.policy_iteration.collect_component_decisions ¶
collect_component_decisions(make_env: Callable, planner_fn: Callable, tasks: Sequence, workers: int = 1, log: Optional[Callable] = None, dynamic: bool = True) -> List
Component-factored collection: like collect_decisions, but each task (seed, members) simulates ONE net component of the episode alone (GymProblem.sim_only = members, set before the reset, so the restricted run starts from the same initial marking), with the planner choosing at its decisions. By the certificate the component's future depends on its own marking only, so its days have the distribution they have inside the whole net, and its decisions get the labels they would get there; the actor's logits for a component read that component only, so they are the same on the component's subgraph. Each component can get its own number of days, and every rollout simulates one component only. dynamic (default): a component is split further once the MARKING certificate splits it (a coupling dissolves, e.g. a start-of-shift pool runs empty): each sub-component continues alone from the split. Needs GymProblem.marking_certificate; without it, or with dynamic=False, the components stay the ones at the initial marking. Returns graphs, in task order.
gympn.policy_iteration.nf_dcl ¶
nf_dcl(make_env: Callable, planner_fn: Callable, policy, days=40, seed: int = 0, workers: int = 1, dynamic: bool = True, log: Optional[Callable] = None, **distill_kwargs)
One round of net-factored DCL (NF-DCL): the net's components
(episode_components) are simulated and labelled alone
(collect_component_decisions) and policy is trained on their decisions
(distill).
days: the component-days of every component (an int), or one number per
component, in the order of episode_components. Component-day d of a
component is played from seed + d, so the components share their days.
dynamic: see collect_component_decisions. distill_kwargs go to distill
(epochs, tau, lr, evaluate, select, ...).
For a further round, pass a planner_fn whose base is NetworkBase(policy)
and another seed. make_env() and planner_fn(env) must be picklable when
workers > 1. Returns (graphs, history): the labelled decisions and
distill's history.
gympn.policy_iteration.soft_targets ¶
soft_targets(graphs, tau: float = 0.0)
Set each graph's t_q, the target distribution over its option classes: softmax(scores / tau) when the planner compared several options and tau > 0, else all mass on the chosen class.
gympn.policy_iteration.distill ¶
distill(policy, graphs: List, epochs: int = 15, lr: float = 0.001, batch_size: int = 32, device: Optional[str] = None, seed: int = 0, log: Optional[Callable] = None, evaluate: Optional[Callable] = None, eval_every: int = 5, tau: float = 0.0, select: Optional[str] = None, ema: Optional[float] = None, override_weight: float = 1.0, adv_weight: float = 0.0, ce_weight: float = 1.0, set_labels: bool = False, renorm: bool = False)
Train policy on the planner's choices with Adam: the cross-entropy
with soft_targets(graphs, tau) (tau = 0: the chosen class only).
evaluate(policy) -> dict is called every eval_every epochs and at the end
(on the CPU, the policy in eval mode), and a copy of the weights is kept
at each evaluation (history["checkpoints"]). With select = a key of
evaluate's dict, the policy ends with the weights of the evaluation that
maximised it (history["selected_epoch"]); else with the last ones.
With ema = d (e.g. 0.995), an exponential moving average of the
weights (updated after every step: w_ema <- d w_ema + (1-d) w) is what
is evaluated, kept as checkpoints and returned: averaging smooths the
epoch-to-epoch swings of the greedy policy.
override_weight: the loss weight of the decisions where the planner
departed from its base policy (t_chosen != t_base), relative to the
others: they are few, and copying the base already fits the rest.
adv_weight, ce_weight: the loss is ce_weight * the cross-entropy +
adv_weight * advantage_loss (the network's expected advantage over the
base, by the planner's option scores). set_labels: the cross-entropy is
set_class_nll instead (the label is the set t_set; graphs recorded
without one use their chosen class). renorm: the cross-entropy uses class
probabilities renormalized within the deciding component
(soft_class_nll(renorm=True)).
Returns the history.
gympn.policy_iteration.soft_class_nll ¶
soft_class_nll(policy, batch, renorm: bool = False)
Mean over the batch's decisions of the cross-entropy between the target t_q over option classes (soft_targets) and the network's class probabilities (summed over each class's equivalent bindings). renorm: the class probabilities are renormalized over the compared classes (the deciding component's options), as if the decision were observed on the component's subgraph: the label then constrains only how the component's own options compare, not how much probability the other components' actions get.
gympn.policy_iteration.set_class_nll ¶
set_class_nll(policy, batch)
Mean over the batch's decisions of -log of the network's probability of the label SET t_set (the options the planner could not tell apart from its choice, e.g. a race's survivors): a partial-label loss, so a near tie does not force one arbitrary option.
gympn.policy_iteration.advantage_loss ¶
advantage_loss(policy, batch)
Mean over the batch's decisions of -sum_c P(c) (Q(c) - Q(base)): minus the network's expected advantage over the base policy's class, with the planner's mean rollout returns t_scores as Q (unbiased for every class, unlike the chosen class's score). Decisions without scores (a single option) contribute 0. Value-aware: a near tie costs almost nothing whichever way it goes, a costly mistake costs its price.
gympn.policy_iteration.option_key ¶
option_key(b)
Bindings with equal keys are exactly equivalent: same transition and same token values (postpone: same component).