Skip to content

Agents

gympn.agents.Agent

Base class for policy gradient agents.

All functionality for policy gradient is implemented in this class. Derived classes must define the property policy_loss which is used to train the policy.

Parameters:

Name Type Description Default
policy_network network

The network for the policy model.

required
policy_lr float

The learning rate for the policy model.

0.0001
policy_updates int

The number of policy updates per epoch of training.

1
value_network network, None, or string

The network for the value model.

required
value_lr float

The learning rate for the value model.

0.001
value_updates int

The number of value updates per epoch of training.

25
gam float

The discount rate.

0.99
lam float

The parameter for generalized advantage estimation.

0.97
normalize_advantages bool

Whether to apply per-batch advantage normalization (zero-mean, unit-variance). Default is True (the standard PPO choice). Normalization is needed to learn LOW-headroom tasks: when the optimal-vs-suboptimal margin is small the raw advantages are tiny, and without rescaling the gradient is too weak to reach the optimum (empirically, env b peaks at 8/9 with it off vs 9/9 with it on). Its downside — the step size not decaying at convergence → post-peak drift — is cosmetic given best-checkpoint restore (the deployed policy is the peak, not the drifted tail). Turn it off only for ablations. See INSTABILITY_ANALYSIS.md.

True
normalize_returns bool

Whether to normalize returns (discounted cumulative rewards) for value training. Default is False (IMPORTANT for correctness).

⚠️ CRITICAL: If normalize_returns=True, the value network will be trained on normalized targets (mean=0, std=1). However, value predictions from rollout time will be in the normalized scale, while GAE calculations use raw rewards/credits. This creates a scale mismatch in delta = reward + gamma * v_{t+1} - v_t.

RECOMMENDATION: Keep normalize_returns=False (default) to avoid this mismatch. If you need stable value training, prefer advantage normalization (normalize_advantages=True) — but note it can reintroduce post-peak drift.

False
kld_limit float or None

Early-stopping limit on the mean per-state KL(pi_old || pi_new), checked after each inner policy epoch. Default is None (disabled).

The KL is computed EXACTLY per state, over that state's own (variable size) action set: KL_s = sum_a p_old(a|s) (log p_old − log p_new), then averaged over states — the standard PPO target_kl quantity, valid for variable |A(s)| because old and new always share a state's support. (Historical note: before 2026-07-09 this metric was the SIGNED chosen-action log-ratio — cancellation-prone, high-variance and |A(s)|-dependent — and early stopping was rightly discouraged. That no longer applies.) PPO's clip bounds each surrogate term but NOT the realized policy shift after multiple inner epochs; the KL brake is the guard against the rare catastrophic update that collapses a near-deterministic policy (observed as post-convergence drift).

None
ent_bonus float

Bonus factor for sampled policy entropy.

0.0

act

act(state, return_logprob=False, deterministic=False)

Return an action for the given state using the policy model.

Parameters:

Name Type Description Default
state array

The state of the environment.

required
return_logprob bool

Whether to return the log probability of choosing the chosen action.

False
deterministic bool

Whether to use a deterministic policy.

False

value

value(state)

Return the predicted value for the given state using the value model.

Parameters:

Name Type Description Default
state array

The state of the environment.

required

train

train(env, episodes=10, epochs=1, max_episode_length=None, verbose=0, save_freq=1, logdir=None, batch_size=64, sort_states=False, test_env=None, test_freq=5, test_episodes=10, wandb_logger=None, num_workers=1, eval_seed=None)

Train the agent on env with optional testing during training.

Parameters:

Name Type Description Default
env environment

The environment to train on.

required
test_env environment

The test environment for evaluation during training.

None
test_freq int

Frequency (in epochs) to run testing during training.

5
eval_seed int

Base seed pinning the evaluation scenarios (common random numbers). See :meth:test_in_train. None keeps the historical behaviour of drawing fresh eval scenarios from the live RNG stream.

None
wandb_logger WandBLogger

Logger for Weights & Biases integration.

None

Returns:

Name Type Description
history dict

Dictionary with statistics from training and testing.

run_episode

run_episode(env, max_episode_length=None, buffer=None)

Run an episode and return total reward and episode length.

Values are predicted in batches of states (every 8 steps and at the end of the episode) rather than one forward pass per step.

Parameters:

Name Type Description Default
env environment

The environment to interact with.

required
max_episode_length int

The maximum number of interactions before the episode ends.

None
buffer TrajectoryBuffer object

If included, it will store the whole rollout in the given buffer.

None

Returns:

Type Description
(total_reward, episode_length) : (float, int)

The environment's accumulated reward (info['pn_reward']) and the episode length.

run_episodes

run_episodes(env, episodes=100, tot_steps=None, max_episode_length=None, store=False, num_workers=None)

Run several episodes, store interaction in buffer, and return history.

OPTIMIZATION: Supports parallel episode collection using multiprocessing. With num_workers > 1, episodes are collected in parallel across multiple CPU cores. This provides 4-8x speedup on episode collection (2-4x overall).

Parameters:

Name Type Description Default
env environment

The environment to interact with.

required
episodes int

The number of episodes to perform.

100
tot_steps int

The total number of steps to perform across all episodes, if episodes is None.

None
max_episode_length int

The maximum number of steps before the episode is terminated.

None
store bool

Whether or not to store the rollout in self.buffer.

False
num_workers int

Number of parallel workers. If None, defaults to sequential. If > 1, uses multiprocessing.Pool for parallel collection.

None

Returns:

Name Type Description
history dict

Dictionary which contains information from the runs.

check_gradient_norms

check_gradient_norms(model)

Check and print the gradient norms for each parameter in the model.

Parameters:

Name Type Description Default
model Module

The PyTorch model to check gradients for.

required

load_policy_weights

load_policy_weights(filename)

Load weights from filename into the policy model.

Parameters:

Name Type Description Default
filename str

The path to the file from which the model weights will be loaded.

required

save_policy_weights

save_policy_weights(filename)

Save the current weights in the policy model to filename.

Parameters:

Name Type Description Default
filename str

The path to the file where the model weights will be saved.

required

test_in_train

test_in_train(env, episodes=100, max_episode_length=None, deterministic=True, logdir=None, eval_seed=None)

Evaluate the agent on a test environment during training.

Parameters:

Name Type Description Default
env environment

The test environment to evaluate on.

required
episodes int

The number of episodes to run for evaluation.

100
max_episode_length int

The maximum number of steps in an episode.

None
deterministic bool

Whether to use a deterministic policy during testing.

True
logdir str

Directory to save the best policy.

None
eval_seed int

Base seed for COMMON RANDOM NUMBERS across evaluations. When set, episode i runs under seed eval_seed + i, so every eval point -- across epochs, across runs, and across methods -- scores the policy on the SAME fixed set of scenarios.

Without it (the default, and the historical behaviour) each eval draws fresh scenarios from wherever training left the global RNG: unbiased, but two arms are compared on different sample paths. Measured on s1, one 20-episode eval point carries +-0.231 SD of pure scenario noise, so a paired single-point difference carries +-0.327 -- and greedy_drift, a max over ~15 such points, is inflated by ~0.40 for a policy that is genuinely flat.

The env's stochasticity comes from the global random / NumPy streams, so this reseeds those per episode and RESTORES the prior state afterwards. Training's stream therefore continues across the eval as if it had not run -- verified directly in suite/_test_eval_crn.py (T2).

That does NOT make a CRN run step-identical to a non-CRN run of the same seed, and it cannot: without eval_seed the eval CONSUMES the training stream (20 episodes' worth of draws per eval point), so the two configurations' rollouts diverge from the first eval onward -- measured on a 4-epoch s1 cell, epoch 4's sampled return was 9.65 with CRN vs 9.40 without. Results produced with eval_seed set are a new baseline, not a re-scoring of existing cells.

env.reset(seed=...) is deliberately NOT used: it routes to seed_everything, which would also reseed torch and re-apply the deterministic-kernel switches on every eval episode.

None

Returns:

Name Type Description
test_metrics dict

Dictionary containing evaluation metrics (mean, min, max, std returns and lengths).

load_value_weights

load_value_weights(filename)

Load weights from filename into the value model.

save_value_weights

save_value_weights(filename)

Save the current weights in the value model to filename.

save_policy_network

save_policy_network(filename)

Save the current policy to file.

Parameters:

Name Type Description Default
filename str

The path to the file where the model will be saved.

required

load_policy_network

load_policy_network(filename)

Load the current policy from file.

Parameters:

Name Type Description Default
filename str

The path to the file from which the model will be loaded.

required

gympn.agents.PPOAgent

Bases: Agent

Proximal Policy Optimization agent.

Parameters:

Name Type Description Default
policy_network network

The network for the policy model.

required
method (clip, penalty)

The loss type for PPO.

'clip'
eps float

The clip ratio if using 'clip'.

0.2
c float

The fixed KLD weight if using 'penalty'.

0.01

gympn.agents.PGAgent

Bases: Agent

A policy gradient agent.

Parameters:

Name Type Description Default
policy_network network

The network for the policy model.

required