Skip to content

Training loop

The agents share one loop, TrainLoop: it collects experience, waits for learning_starts, folds the extensions, evaluates, logs and resumes the same way for every agent. An agent supplies only its init and update. Architecture explains how the pieces fit.

ajax.agents.loop

The training loop the agents share.

An agent's make_train builds a :class:TrainLoop and hands it what makes the agent its algorithm: how to initialise its state and how to update it. The loop owns everything else, the same for every agent::

fresh run:  state = init(key), then every extension's initial state
            and one-shot pretraining
resumed:    state = the checkpointed state
iterate:    collect one step per env (off-policy) or a rollout (on-policy)
            if timestep >= learning_starts (on-policy: always):
                state, aux = update(state, experience)
                apply the extensions' post_update
            else:
                aux = the update's metrics, filled with NaN
            evaluate and log every log_frequency steps

An off-policy agent that acts, trains and evaluates its own way (the world models: a planner or a filtered latent acts through the row collector, a train ratio schedules the updates) supplies those steps too, and the loop runs them in the same order (:meth:TrainLoop.off_policy)::

iterate:    state, experience = collect(state, tick)
            repeat n_updates(tick, state) times:
                state, _ = update(state, experience)
                apply the extensions' post_update
            evaluate and log every evaluation.every ticks

A replay agent given a dataset trains offline instead (:meth:TrainLoop.offline)::

fresh run:  the replay and the normalisers start from the dataset
iterate:    state, aux = update(state, None)   # no environment step
            apply the extensions' post_update
            evaluate and log every log_frequency updates

The result is train(key, index, initial_state, resume_from_state), which :meth:ajax.agents.base.ActorCritic.train vmaps over seeds. Without a logging config it is :func:ajax.perf_utils.build_resumable_train's one jitted scan and returns (state, None), the evaluation not even traced (tracing alone rebuilds the evaluation env). With one it evaluates every log_frequency steps, whether or not a backend (W&B, TensorBoard) records the logs, and returns (state, evaluations): every logged key's values at the evaluations, in order, padded to the most a call makes with -1 (integer leaves, the timestep) and NaN. It then trains in chunks, the ticks up to the next evaluation, each a jitted scan, and evaluates between them in a program of its own (:func:ajax.perf_utils.build_chunked_train), as Brax does: an evaluation inside the training program slows every tick of it. The ticks that evaluate are known before the run, from the steps each tick takes, so the evaluations come on the ticks and states they would in one scan.

Evaluation dataclass

Evaluation(
    metrics,
    every,
    evaluate=None,
    after_log=None,
    steps_before=None,
)

An agent's own evaluation, every every ticks (None: never), or, given steps_before(tick) (the env steps, summed over envs, of the absolute ticks before tick), on each tick whose steps reach a multiple of every env steps: an agent whose ticks are not all env steps (TD-MPC2's held ticks) cannot keep a step cadence in ticks. The gate reads the unbatched tick, not the per-seed timestep, so that its lax.cond stays a real cond under the seed vmap.

metrics(agent_state, aux) are its training metrics (timestep included), updated with its policy's evaluate(agent_state, key) when it has one and the extensions' eval_metrics; after_log(agent_state, logged) runs on every tick after the gate.

due

due(tick)

Whether tick tick evaluates; None when none does.

ticks

ticks(ticks)

:meth:due over a NumPy array of absolute ticks.

count

count(n_ticks)

The most evaluations n_ticks consecutive ticks make.

TrainLoop dataclass

TrainLoop(
    env_args,
    total_timesteps,
    num_episode_test,
    extensions,
    log,
    log_fn,
    log_frequency,
    start_timestep=0,
    end_timestep=None,
    expert_policy=None,
    offline_data=None,
    evaluate_last_fifth_only=False,
    evaluator=None,
    progress=None,
    unroll_ticks=False,
    plans_ticks=None,
)

One call's environment, budget, extensions and logging (compared and hashed by identity: the environment's parameters are arrays).

A call trains from start_timestep (a resumed run's timestep, else 0) to end_timestep (None: the horizon); total_timesteps is the run's horizon: every schedule (the extensions' total_steps, the training fraction, the logging's end) runs over the whole run, so a run split into calls follows the schedules of one call; the call's own iterations come from its :attr:budget.

budget property

budget

The timesteps this call trains for.

n_evaluations property

n_evaluations

The most evaluations one call ending at its budget makes (:meth:evaluations_until).

create classmethod

create(
    env_args,
    total_timesteps,
    num_episode_test,
    run_ids=None,
    logging_config=None,
    extensions=(),
    start_timestep=0,
    end_timestep=None,
    expert_policy=None,
    offline_data=None,
    unroll_ticks=False,
)

The loop of one make_train call; starts the logging worker when logging_config names a backend.

replay_rows_per_env

replay_rows_per_env()

The rows per env a fresh run of this call writes to its replay: those its extensions write before training (ExpertPrefill, PriorData), an offline dataset's, then one per tick, none offline.

warn_if_partial

warn_if_partial(per_iteration, unit)

Warn when the budget is not a whole number of iterations of per_iteration env steps (unit names them): the iterations stop at a multiple of it, not at the call's end, so the run trains another number of steps than asked and an evaluation due at that end never happens: the evaluations returned hold no column for it.

warn_if_inside_warmup

warn_if_inside_warmup(learning_starts)

Warn when the call ends before the first update, at learning_starts steps collected: the run collects random steps and its evaluations score a policy that never trained, which a short test run met in silence.

n_rollouts

n_rollouts(n_steps, timesteps=None)

The iterations of :meth:on_policy for n_steps rollouts over timesteps (None: the budget, warning when it is not whole rollouts): the whole rollouts it holds, as purejaxrl, ppo2, CleanRL and purejaxql train, and one when it holds none (as UDRL and APG).

evaluations_until

evaluations_until(timestep)

The most evaluations one call reaching timestep makes: ajax.log's gate counts each one as a log point, so the k-th of the run comes at timestep k * log_frequency or later, and none comes past the horizon.

logging_ticks

logging_ticks(steps_per_tick)

Which ticks of this call (a NumPy array) evaluate_and_log's gate opens after, each tick taking steps_per_tick steps from the call's start_timestep: those whose steps reach a multiple of log_frequency. The gate itself still decides (the horizon, the last fifth alone). The ticks count from the call's first, as the families planning with it number them (their resume_iteration_offset is 0).

collect_kwargs

collect_kwargs(recurrent, **kwargs)

collect_experience's arguments for this run. With the agent's expert, its action pipeline also stores the expert's actions from the expert's tracked state, the run's action extensions act on its result, gain mode actuates the chosen action through the expert, and the default pipeline runs the run's warm-up chooser (expert_collect_kwargs); without it, the action extensions acting with an expert of their own (IBRL).

post_update

post_update(agent_state)

:func:apply_post_update at the collector's timestep, then the actor's copy of a shared encoder taken from the critic the update stepped (mirror_shared_encoder).

maybe_update

maybe_update(
    agent_state,
    learning_starts,
    update,
    timestep=None,
    trains=True,
    planned=None,
)

update and apply post_update on a tick that trains (trains, by default every one) once timestep, by default the steps collected, reaches learning_starts; otherwise the metrics have the update's structure, filled with NaN (which the logger drops), or, on a state keeping them (last_update_metrics) in a run that logs, those of the last update. planned, the Python True or False, is that decision taken before the run (off_policy's plan): no gate is traced.

planned_ticks

planned_ticks(
    iteration,
    learning_starts,
    update_every,
    before_collection,
)

off_policy's ticks with their updates planned before the run. Each tick collects n_envs steps from start_timestep on, so where maybe_update's gate holds is known for every tick of the call: the same rules (reached, reaches_multiple) on the same counts, the steps collected before the tick (before_collection: an update learning from its own step) or after it. The ticks then run with no gate traced: on a GPU a lax.cond in a tick is a conditional node of its CUDA graph, about 18 µs a tick on DQN's (PERFORMANCE_REPORT.md, "Ticks in groups"). train runs them so where plans_ticks says (on accelerators, by default). iteration(agent_state, index, tick, planned) is a tick, planned the update's decision.

used_plan

used_plan(planned)

planned where plans_ticks runs it (None: on accelerators), else None: the ticks gate their updates.

repeat_update

repeat_update(agent_state, n, update)

n times update then post_update; the updates keep what they log on the state. An n derived from unbatched values (the tick, static hyperparameters) keeps the loop one while under the seed vmap; one read from the per-seed state runs it to the largest count, each seed's state frozen after its own.

evaluate_and_log

evaluate_and_log(
    agent_state,
    aux,
    index,
    recurrent=False,
    agent_metrics=None,
    **kwargs,
)

Evaluate and log every log_frequency steps (ajax.log.evaluate_and_log), the agent's family's agent_metrics and the extensions' eval metrics included; returns the state and the metrics (None without logging), only in the last fifth of training when the logging configuration says so. An agent storing normalised observations evaluates with them normalised by its running statistics, unless its own controller says how it acts.

evaluate_every

evaluate_every(agent_state, aux, index, tick, evaluation)

An agent's own evaluation and logs on the ticks :meth:Evaluation.due picks (:func:ajax.log.maybe_eval_and_log, the extensions' eval metrics included); returns the state and the metrics (None without logging).

continued

continued(agent_state)

A resumed state, its training progress measured against the run's horizon (a fresh state is built with it).

train

train(
    init,
    iteration,
    num_updates,
    last_rollout=None,
    evaluations=None,
    update=None,
    buffer=None,
    one_update=None,
    update_metrics=None,
    resume=None,
    returns_iterations=False,
    log=None,
    due=None,
    planned=None,
)

The resumable train function: init (fresh runs only), then num_updates ticks iteration(agent_state, index, tick) -> (agent_state, aux). Logging, log(agent_state, aux, index, tick) evaluates after each tick due(ticks) marks (a NumPy array of absolute ticks to bools), between chunks of ticks (build_chunked_train), and the evaluations are recorded (see the module docstring): n_evaluations rows, or evaluations.

last_rollout, a (length, collect_kwargs) pair, pre-allocates agent_state.last_rollout for an agent exposing its rollouts. The extensions' pretraining gets the env, update and the replay buffer (ajax.extensions.base.ExtensionContext). one_update, a state to the state after one update, is given by an update keeping its actor's last metrics: a fresh or resumed state gets their slot (with_actor_metrics_slot). update_metrics, a state to its update's metrics, is given by an update that runs every few steps: a fresh or resumed state gets the slot of its last metrics (with_update_metrics_slot). resume transforms a resumed state after continued (APG rebuilds its optimiser). With returns_iterations, iteration evaluates itself and the train function returns every iteration's output, stacked, logging or not, instead of the rows. planned (planned_ticks) runs the ticks with their updates decided before the run, where plans_ticks says.

off_policy

off_policy(
    init,
    update,
    learning_starts=0,
    *,
    uniform_steps=None,
    recurrent=False,
    expose_rollout=False,
    after_collect=None,
    collect_kwargs=None,
    eval_kwargs=None,
    collect=None,
    n_updates=None,
    evaluation=None,
    num_ticks=None,
    keeps_actor_metrics=False,
    pretrain_update=None,
    update_every=1,
)

Train on one environment step per env per iteration (a tick).

Each tick collects a step (uniform actions before uniform_steps, by default learning_starts; 0: the policy's from the first step, as TQC's authors act), applies after_collect(agent_state, transition) when given, then from learning_starts runs update(agent_state, transition) (without a replay, from the step collected at learning_starts) on the ticks whose steps collected reach a multiple of update_every (:func:reaches_multiple), then evaluates the actor (:meth:evaluate_and_log). expose_rollout keeps the step on agent_state.last_rollout as a T = 1 rollout. The budget is :attr:budget // n_envs ticks.

An agent acting, training and evaluating its own way (the module docstring) supplies those steps: collect replaces the collection and the arguments configuring it; n_updates(tick, agent_state) updates (of the absolute, unbatched tick: a train ratio, a burst; or of the collected state: the env steps the tick took) replace the learning_starts and update_every gate (:meth:repeat_update); evaluation replaces the actor's evaluation (:meth:evaluate_every); num_ticks the budget.

keeps_actor_metrics: the update keeps its actor's last metrics on the state (update_steps.run_actor_if), which then gets their slot. pretrain_update, by default update, is the update the extensions' pretraining runs, before any env step. With :attr:offline_data it trains offline instead (:meth:offline).

offline

offline(
    init,
    update,
    buffer,
    recurrent=False,
    eval_kwargs=None,
    keeps_actor_metrics=False,
    pretrain_update=None,
)

Train on :attr:offline_data alone, with no environment step.

A fresh run's replay and normalisers start from the dataset's rows (:func:seed_replay). Each tick runs update(agent_state, None) on that replay, applies post_update and counts the update in the collector's timestep: the schedules run over the updates, and the evaluations (:meth:evaluate_and_log) come every log_frequency updates and log the updates done as their timestep. The budget is :attr:budget updates.

forced_reset

forced_reset(
    agent_state, n_steps, resets_per_eval, num_evals
)

brax's num_resets_per_eval: every env reset (:func:ajax.environments.interaction.force_reset) every reset_every updates, resets_per_eval times per evaluation after the first of num_evals.

Playground envs draw a fresh initial state at every episode end by default (build_env_from_id(fresh_reset=True)); with fresh_reset=False their auto-reset replays the first reset state, and without these resets a run sees only n_envs initial conditions.

on_policy

on_policy(
    init,
    update,
    n_steps,
    *,
    recurrent=False,
    expose_rollout=False,
    forced_resets=(0, 1),
    collect_kwargs=None,
    eval_kwargs=None,
)

Train on an n_steps rollout per env per iteration.

Each iteration collects the rollout from the agent state agent_state_at_rollout_start (collect_experience with collect_kwargs), then runs update(agent_state, rollout, agent_state_at_rollout_start), resets every env on brax's cadence when forced_resets, (resets_per_eval, num_evals), asks for any (forced_reset), and applies post_update; expose_rollout keeps the rollout on agent_state.last_rollout. The budget is n_rollouts; a budget under one rollout trains one, which reaches past the call's end and evaluates there when the horizon is further.

record

record(rows, count, metrics)

Write metrics into row count of rows when they are an evaluation (their timestep is not the -1 sentinel), else nothing.

Returns the rows and the count of evaluations written.

fresh_state

fresh_state(init, extensions, total_steps, key, **context)

A fresh run's state: init(init_key) on split(key), then the extensions' initial states and one-shot pretraining on extension_key (:meth:ExtensionStack.apply_init; context: the pretraining's static context fields).

with_actor_metrics_slot

with_actor_metrics_slot(agent_state, one_update)

agent_state with the slot its update keeps the actor's last metrics in (BaseAgentState.last_actor_metrics, update_steps.run_actor_if): their structure, read from the trace of one_update (a state to the state after one update), NaN until the actor's first step, so the scan carry keeps one structure from the first update. A state that has the slot keeps it.

with_update_metrics_slot

with_update_metrics_slot(agent_state, first_metrics)

agent_state with the slot a run updating every few steps keeps its last update's metrics in (BaseAgentState.last_update_metrics, TrainLoop.maybe_update): their structure, read from the trace of first_metrics (a state to the metrics of an update), NaN until the first update. A state that has the slot keeps it.

with_horizon

with_horizon(agent_state, env_args, total_steps)

A state whose collector keeps the run's horizon total_steps, which a feature reading the training progress needs (:func:ajax.controller.reads_progress); a resumed run measures its progress against its own call's.

with_obs_norm

with_obs_norm(agent_state, env_args=None)

An agent normalising its own observations (the collector's obs_norm_info) with those statistics mirrored on its networks, which apply them; collection refreshes the mirror at every step, and setting it at init keeps the scan carry's structure fixed. An agent storing normalised observations (env_args.store_normalized_obs) gets no mirror: its networks read them as stored.

seed_replay

seed_replay(agent_state, data, env_args)

agent_state with data's rows in its replay, where they stay (:func:ajax.buffers.dataset.fill_replay), and in the normalisers it has (count_in_normalisers).

count_in_normalisers

count_in_normalisers(
    agent_state,
    obs,
    rewards,
    terminated,
    truncated,
    env_args,
)

The agent state with rows written to its replay before training counted in the normalisers it has, each row once, as collection counts its own: their observations in its own observation statistics, mirrored on its networks, and in the env's reward statistics the reward or, with the normaliser's gamma, the discounted return of the episode so far (its running return left as it is). Time runs along the first axis of the rewards and the episode ends, the envs along the others; the observations keep their columns last. A normaliser the agent lacks costs nothing.

whole_call

whole_call(planned, num_updates)

A call's num_updates ticks as planned (build_resumable_train's run_ticks), keeping no aux; None without a plan, or where it leaves the ticks to gate their updates.

The steps an agent's update is written in:

ajax.agents.update_steps

The steps an agent's update is written in: a loss's gradients (compute_gradients), gradient steps with the extensions' loss terms added (critic_step, which hands the extensions the Q critics' value readers, critic_value_readers; actor_step; apply_gradients_clipped_together for two networks clipped together), the extensions' target and post-update phases, the gates (run_if, run_actor_if) and keys (derive_extensions_key) around them, which ajax.agents.loop re-exports, and the target critics' Polyak update (update_target_networks).

apply_post_update

apply_post_update(
    extensions, agent_state, step, total_steps
)

Apply the extensions' post_update at step on a key derived from the updates' stream, which it leaves as it was: a run with extensions draws every other key as the run without them.

derive_actor_key

derive_actor_key(agent_state)

The key of an actor step that counts on some updates only (a policy delay, policy_update_start), derived from the updates' stream without advancing it: the stream's next keys are the same whether the step ran, or ran and was dropped, and a dropped step's keys are never drawn again.

scan_on_indexed_keys

scan_on_indexed_keys(step, agent_state, length)

length steps of step(agent_state, None) -> (agent_state, aux) and the last one's aux, the i-th step on the updates' stream restarted from one of its keys folded with i; then the stream goes on after that one key. It advances once whatever the length, so a count of steps (SAC's and REDQ's critic updates, DQN's gradient steps) moves no later draw.

run_if

run_if(condition, update, state)

update(state) where condition holds, else state unchanged: a policy delay, a target refresh, a warm-up. state is any tree: an agent's state, or one network's (DQN's target refresh).

update returns the new state, or the new state and its metrics. Skipped, the metrics have update's structure, read from its trace (with the names the extensions log): NaN, -1 in integer leaves (ajax.log.unevaluated), which the logger drops; an actor's step keeps its last metrics instead (run_actor_if). A condition that is the Python True runs update with no gate, the Python False (planned before the run) skips it with none. Under the seed vmap a condition read from per-seed state runs update every time and selects; one from unbatched counters runs it only where it holds.

reached

reached(start, timestep)

Whether timestep has reached start, the env steps an update step waits for (policy_update_start): the Python True, with nothing traced, when start is 0 or less, so an agent without the wait runs the program it ran before it had one.

reaches_multiple

reaches_multiple(every, before, count)

Whether a tick taking the env steps collected from before to before + count reaches a multiple of every, the rule of Ajax's other step schedules (log_frequency, JSRLCurriculum's gate): the Python True, with nothing traced, when every tick does (every <= count). before may be an int, a NumPy or a JAX array.

all_of

all_of(*conditions)

Whether every condition holds; the Python Trues among them (no gate) add nothing to the program, and with nothing else left it is True.

run_actor_if

run_actor_if(condition, update, agent_state, keep=False)

update(agent_state) -> (agent_state, metrics), an actor's step, where condition holds (a policy delay, policy_update_start). Skipped, agent_state is unchanged and the metrics are those of the actor's last step that ran, which the state keeps (last_actor_metrics, whose slot the training loop gives it): a skipped update logs the last real step, not NaN or zeros (owner, 2026-10-24), and NaN, which the logger drops, before the first. Without a gate (condition the Python True) update runs as it is, its metrics kept only with keep: an agent that keeps them (keeps_actor_metrics) and whose gate is open at every update (ReplayAgent.from_update_start) keeps the state's slot, so its state, and a checkpoint of it, has the gated run's structure.

derive_extensions_key

derive_extensions_key(key)

The extensions' key of a step on key, which the step's own draws (on key and the keys it splits off it) never get.

compute_gradients

compute_gradients(loss, params)

The gradients of loss at params, and what loss returns beside its value.

loss takes the parameters alone and returns (value, aux): the number to minimise and what to keep from computing it (its metrics). An agent fixes the loss's other inputs first, in a small local function. params is one network's parameters, or a tuple of several networks' (APO's summed loss), and the gradients have the same structure. A caller that logs the loss's value puts it in aux.

compute_actor_critic_gradients

compute_actor_critic_gradients(
    policy_loss, value_loss, actor, critic
)

Each network's gradient of the summed loss policy_loss + value_loss at their parameters, then what each loss returns beside its value.

value_loss takes the critic's parameters; policy_loss the actor's, then the critic's, from which an actor sharing the critic's encoder reads it (sharing.with_critic_encoder). Without a shared encoder the networks share no parameter, so each network's gradient is that of its own loss. With one, the encoder is the critic's: its gradient is the value loss's plus the policy loss's, as in ppo2's one network (ppo2/model.py:75-107).

gradient_step

gradient_step(train_state, loss_fn)

One optimiser step down loss_fn(params) -> (loss, aux).

Returns the stepped train state, the loss's aux and the global norm of the gradients, before any clipping the optimiser does (a caller that does not log it leaves it to dead-code elimination).

apply_on_target

apply_on_target(
    extensions,
    agent_state,
    batch,
    target_q,
    key,
    total_timesteps,
    *,
    rewards,
    dones,
    gamma,
    reward_scale,
    next_actions=None,
    critic_subset=None,
    next_values=None,
    predictions=None,
    target_value_at=None,
)

target_q with the extensions' on_target applied, no gradient flowing back through it (stop_gradient), their metrics and agent_state with the extensions' states as on_target left them: critic_step's first half, which an agent whose target comes out of its own critic pass (CrossQ) calls inside its loss.

batch is a Transition. rewards, dones (where the bootstrap is cut), gamma (None for an average-reward agent), reward_scale and next_actions (the next actions the target scored; None for a target scoring a state value, IQL's V(s')) and critic_subset (the indices of the target critics whose minimum it took, REDQ's random subset; None for a target over all its critics) are what the target used; next_values the value it bootstrapped at s', before gamma, the cut and the reward scale (a distributional target's mean); predictions() the critics' mean prediction at the batch's rows, which the loss regresses, and target_value_at(observations, actions) their mean value at the target's parameters (the step's where there is no target critic), each run only by an extension reading it. The phase draws on a key derived from key, the step's (derive_extensions_key).

compute_extensions_critic_loss

compute_extensions_critic_loss(
    extensions,
    agent_state,
    batch,
    params,
    target_q,
    key,
    total_timesteps,
)

The extensions' critic_loss terms at the critic's params (the differentiated ones) on batch against target_q (no gradient flows back through it), and their metrics: critic_step's second half, on a key derived from key, the step's.

critic_value_readers

critic_value_readers(critic_state, observations, actions)

apply_on_target's predictions and target_value_at for an ensemble of Q critics: their mean prediction at the batch's rows (observations, actions) at the step's parameters, which the loss regresses, and their mean value at given observations and actions at the target's (the step's where there are no target critics). No gradient flows back, and each reads the critics only where an extension calls it.

critic_step

critic_step(
    agent_state,
    batch,
    target_q,
    value_loss,
    extensions,
    key,
    total_timesteps,
    **target_args,
)

A replay agent's critic step on batch (a Transition).

Applies the extensions' on_target to target_q, no gradient flowing back through it (apply_on_target, which target_args reach: what the target used), then steps the critic down value_loss(params, target_q) -> (loss, aux) plus their critic_loss terms (compute_extensions_critic_loss). The value readers on_target may call, predictions and target_value_at, are the Q critics' at the batch's rows (critic_value_readers) unless target_args holds the agent's. The phases draw on keys derived from key, the step's, on which the agent may draw too. Returns agent_state with the stepped critic and the extensions' states as on_target left them, aux, the gradients' norm (gradient_step) and the two phases' metrics.

bootstrap_cuts

bootstrap_cuts(terminated, extensions)

Where a replay target cuts its bootstrap: at the terminations, unless an extension has it go on through them into the reset observation the replay stores there (ResetCost).

actor_step

actor_step(
    agent_state,
    policy_loss,
    extensions,
    key,
    total_timesteps,
    batch,
    critic_state=None,
)

A replay agent's actor step on batch (a Transition).

Steps the actor down policy_loss(params) -> (loss, aux, pi_mean) (pi_mean: the policy's mean action at the rows, None for a discrete policy) plus the extensions' actor_loss terms, on a key derived from key, the step's (derive_extensions_key). Their batch holds the rows' entries (REPLAY_ACTOR_KEYS: their observations, raw observations, actions and the expert's stored actions a_expert, and critic_state, the critics the agent's loss reads, None where it reads none), with the differentiated actor_params, the actor_state, pi_mean and agent_loss. An extension reads only the keys the agent declares (phase_batch_keys), those its rows hold. Returns the stepped actor state, aux, the gradients' norm (gradient_step) and the phase's metrics.

clip_global_norm

clip_global_norm(grads, max_norm, eps=0.0)

grads (any tree) times min(1, max_norm / (norm + eps)), their global norm taken over every leaf at once; None leaves them.

With eps 0 it is tf.clip_by_global_norm, ppo2's (baselines ea25b9e ppo2/model.py:105-107); torch's clip_grad_norm_, which APO's reference code calls, adds 1e-6 to the norm (torch 1.5.1, torch/nn/utils/clip_grad.py:33-37).

apply_gradients_clipped_together

apply_gradients_clipped_together(
    actor,
    critic,
    actor_grads,
    critic_grads,
    max_grad_norm,
    norm_eps=0.0,
)

One Adam step of each network, their gradients first clipped together to one global norm (clip_global_norm), as ppo2's single optimiser and APO's reference code clip every parameter's gradient at once. Adam works per coordinate, so the two Adams act as one over the whole model.

Returns the stepped actor and critic, then each one's gradient norm before the clip.

update_target_networks

update_target_networks(agent_state, tau)

Polyak-average the target critics towards the critics.

ajax.perf_utils

Shared JAX-pure performance helpers for Ajax agents.

Patterns the perf audits found across agents (PERFORMANCE_LOG.md), written once so a fix lands in one place instead of in every agent's train_*.py.

PlannedTicks

Bases: NamedTuple

Ticks whose updates are known before the run (TrainLoop.off_policy): layout(begin, length), on the host, the layout of the call's ticks begin to begin + length - 1, counted from its first (None: tick by tick, gating each update); run(agent_state, index, first_tick, layout, after) those ticks (:func:run_planned).

plan_ticks

plan_ticks(updates, size)

The layout of a run of ticks updating where updates (a bool per tick) says, size the ticks from one update to the next: groups where the updates come every size ticks, runs of ticks that collect only or that all update elsewhere. None where that takes more than :data:MOST_TICK_SEGMENTS segments (updates at uneven intervals, as when n_envs does not divide the update period): the ticks then gate their updates one by one, with a lax.cond each.

run_planned

run_planned(
    collect,
    update,
    agent_state,
    index,
    first_tick,
    layout,
    unroll=False,
    after=None,
    keep_aux=True,
)

The ticks of layout from first_tick on, each segment a scan: collect and update, (agent_state, index, tick) -> (agent_state, aux), for its ticks that collect only and those that also update. Returns the state and the last tick's aux (None without keep_aux). after(tick) runs after each tick (the progress reports).

A group's ticks before its update are an inner scan, or with unroll one after another in its body: on a GPU the inner scan's loop runs from the host, the unrolled ticks in the group's CUDA graph, faster but compiled for longer. PERFORMANCE_REPORT.md, "Ticks in groups".

start_state

start_state(
    init_fn,
    resume_transform,
    key,
    index,
    initial_state,
    resume_from_state,
)

A train call's first state: init_fn(key, index) on a fresh run; on a resumed one, the state passed in, through resume_transform when given.

build_resumable_train

build_resumable_train(
    *,
    init_fn,
    make_scan_fn,
    num_updates,
    resume_transform=None,
    carry_out=None,
    run_ticks=None,
)

Build the canonical init-or-resume + lax.scan inner train fn.

Every Ajax agent shares this skeleton, written once here so it cannot drift between agents: build a fresh agent_state with init_fn (its one-shot initialisation included, so a continued run does not re-run it) or, with resume_from_state=True, reuse the initial_state handed in from a checkpoint; then jax.lax.scan the per-iteration body num_updates times, its input the iteration index. Each agent's make_train keeps its own setup (networks, optimisers, action pipeline, logging) and hands the pieces over.

The returned train function has the signature

train(key, index=None, initial_state=None, resume_from_state=False,
      iteration_offset=0, shared=None)

and is jitted with resume_from_state static (the init-fresh vs load-from-checkpoint branch is dead-code-eliminated) and initial_state donated: XLA reuses the incoming agent-state buffers on the resume path, saving one agent state of peak memory (donating None, the init path, is a no-op).

The scan input is the iteration index iteration_offset + arange(num_updates): a resumed run passes the number of iterations already done so the body sees absolute iteration indices and every schedule computed from them (seed phase, update bursts, static resets, logging cadence) continues instead of restarting. A passed offset is a traced scalar (one compilation serves every offset) and must be unbatched -- pass it through jax.vmap with in_axes=None -- so the index, and every predicate derived from it, stays unbatched under the seed vmap. The default (the Python int 0, not passed) adds nothing to the program.

shared is an optional pytree the body reads but never carries -- an offline dataset, say -- handed to make_scan_fn as the keyword argument shared (only when it is not None, so builders that do not take it are unchanged). Pass it through the seed vmap with in_axes=None: it then enters the compiled program once, as an argument shared by every seed. Closing over it instead would bake it into the program as a constant (HLO bloat, a recompilation per dataset), and a batched argument would copy it per seed.

Parameters:

Name Type Description Default
init_fn Callable[[Any, Any], Any]

(key, index) -> agent_state. Builds a fresh agent state. Called only on the fresh-init path. index is the per-seed index (or None); agents that don't need it simply ignore it.

required
make_scan_fn Callable[..., Callable[..., Tuple[Any, Any]]]

a builder (agent_state, resume_from_state, key, index) -> body of the per-iteration body (carry, x) -> (carry, aux), invoked once at trace time, after init/resume is resolved, so the body can be finished from the resolved state, branch on whether this is a resume, or use the per-call key / per-seed index or the shared input (passed as shared= when given).

required
num_updates int

number of scan iterations (static int).

required
resume_transform Callable[[Any, Any], Any] | None

optional one-shot (agent_state, key) -> agent_state applied on the resume path only (e.g. re-initialising the optimizer for a new curriculum stage while keeping the learned parameters).

None
carry_out Callable[[Any, Any], Any] | None

optional (agent_state, index) -> out, the initial value of an output the body writes into as it goes (in place) instead of stacking one per iteration. The body then maps ((agent_state, out), x) to ((agent_state, out), None) and train returns the final (agent_state, out).

None
run_ticks Callable[[Any, Any, Any], Any] | None

optional (agent_state, index, first_tick) -> agent_state, the call's iterations from first_tick on in place of the scan of make_scan_fn's body: planned ticks (:class:PlannedTicks). train then returns (agent_state, None).

None

build_chunked_train

build_chunked_train(
    *,
    init_fn,
    tick_fn,
    log_fn,
    due,
    num_updates,
    carry_out,
    resume_transform=None,
    progress=None,
    reports_inside=None,
    progress_reports=None,
    loops=None,
    planned=None,
)

:func:build_resumable_train's train with the evaluations between chunks of ticks, as Brax trains: the ticks up to the next one that evaluates are one jitted program of tick_fn's ticks, and log_fn runs on the state the chunk ends with, as a program of its own. The training program then holds no evaluation, which slowed every tick of it (about 4% for SAC on MuJoCo Warp, evaluations aside); the states, and so the evaluations, are those of one scan.

tick_fn(agent_state, index, tick) -> (agent_state, aux) is one tick, tick its absolute, unbatched index. log_fn(agent_state, aux, out, index, tick) -> (agent_state, out) evaluates after tick tick, reading the tick's aux, and writes into out, which starts as carry_out(agent_state, index). due(ticks), of a NumPy array of absolute ticks, marks those after which log_fn runs: it must be known before the run, so the chunks are. A chunk is a scan of its ticks, and each chunk length compiles once; they are one or two when the evaluations come every so many ticks or steps. loops True trains every chunk with one program for any length (:func:ticks_in_a_loop), False with the scans; by default a call on CPU whose chunks have more than one length takes the loop, so that a last chunk shorter than the others compiles no program of its own while the earlier ones train, and every other call takes the scans. The start, every chunk and every evaluation take the state by donation, so a run updates one copy of it in place.

The evaluation compiles once too: the start hands the first chunk its state, and the first evaluation its out, laid out as every later one gets them.

progress(done, index), when given, is called in the training process as training goes on, about progress_reports times a call, with the fraction of the call's ticks done (1.0 after the last) and the member's index (:func:reporting_chunk): after each piece of a chunk, the pieces of one length, the divisor of the chunk's length nearest the call's ticks / progress_reports (the whole chunk when none is near, a prime length). With reports_inside each chunk reports from inside its program, else between its pieces, each piece trained as a chunk is without reports: by default inside on accelerators and between on CPU, where a program that calls the host runs synchronously. Between reports loops then goes by the pieces' lengths. progress_reports defaults to :data:PROGRESS_REPORTS inside and :data:CPU_PROGRESS_REPORTS between. Either way the ticks and the evaluations stay those of the run without reports.

With planned (:class:PlannedTicks), a chunk or a piece of one whose ticks it lays out runs them so, its layout compiled with its length; the loop (:func:ticks_in_a_loop) runs tick_fn's ticks.

The train function has build_resumable_train's signature but shared, and returns (agent_state, out). It is a Python loop over jitted programs: vmap it over the seeds or call it per seed, as ActorCritic.train does. Jitting it whole would put every chunk into one program, and it reads iteration_offset as a number.

ticks_in_a_loop

ticks_in_a_loop(tick_fn)

train_ticks(agent_state, index, first_tick, last_tick) -> (agent_state, aux): ticks first_tick to last_tick of tick_fn as one jitted program for any number of them, the state donated. The ticks but the last run in a fori_loop with traced bounds, keeping no aux, and the last apart, keeping its own, as :func:final_aux_scan lays out a scan.

A scan compiles once per length: a run whose last chunk was shorter than the others compiled it while the earlier chunks trained, Python tracing it and XLA compiling it on the cores they trained on (PQN's chunks at agent_bench's size took 1.3 to 6 times as long then). On CPU the loop trains as fast as a scan of the ticks: its body compiles to the scan's instructions but for the bound it carries. It saves nothing where a run's chunks have one length, and compiles a tick twice where a one-tick chunk's program is the tick alone: APO's and PPO's runs, of one-tick chunks, took 23% and 29% longer in it at agent_bench's size. On a GPU a loop with traced bounds goes back to the host every tick, which a scan does not: on an L40S SAC's chunks of 200 ticks trained 5.7 times slower in one. PERFORMANCE_REPORT.md, "The chunk's scan and the bar's loops".

reporting_chunk

reporting_chunk(
    tick_fn, progress, num_updates, inside, planned=None
)

build_chunked_train's chunk as reporting(agent_state, index, first_tick, last_tick, piece, call_first, train_ticks), calling progress(done / num_updates, index) in the training process each time piece more of its ticks have trained (piece divides the chunk's length), with done the call's ticks so far (from call_first, its first tick). Under the seed vmap the members share each call to the host, then progress is called once per member.

inside: the chunk stays one scan of its ticks, as without reports, and a tick that ends a piece calls the host under a cond, in that tick's loop turn, so in order and up to a tick early. Otherwise each piece is one program, train_ticks(agent_state, first_tick, last_tick) -> (agent_state, aux), the caller's: the chunk's aux is its last piece's. A small program after the chunk, or after each piece, takes a leaf of the state that returns, so it reports once that has trained. Why the two ways, and not barriers or a call per member: "Evaluation and logging" in docs/developer/architecture.md. Inside, a chunk planned lays out (:class:PlannedTicks) runs its ticks so, each still reporting where it ends a piece.

callback_per_member

callback_per_member(callback, *args)

jax.debug.callback(callback, *args), with the leaves of args handed over as NumPy arrays and one call to the host however many members a vmap batches: there callback runs once per member, in their order, on the member's row of each batched leaf and on the other leaves whole, as under JAX's own rule. That rule calls the host once per member, each call on a GPU a sync of the device: at 50 seeds a chunk of SAC on Pendulum and its evaluation took 772 ms, against 732 ms with one call (PERFORMANCE_REPORT.md, 2026-11-29). A vmap around another still calls the host once per member of the outer one.

call_each_member

call_each_member(callback, members, in_batched, *args)

In the host, callback(*args) once per member of members (None: once, unbatched), with the member's row of each leaf in_batched marks and the other leaves whole.

nearest_divisor

nearest_divisor(n, target)

The divisor of n nearest target by ratio, the larger on a tie, among those of at least a quarter of it, so a chunk reports at most about four times as often as it aims to; n when none is.

final_aux_scan

final_aux_scan(body, init_carry, length, xs=None)

length steps of body(carry, x) -> (new_carry, aux), returning the final carry and the last step's aux alone (aux a pytree of arrays, any structure).

It replaces lax.scan and keeping ys[-1], which would stack every step's aux, [seeds, length, *aux_shape] under the seed vmap, to throw all but one away. The steps before the last run in a scan that keeps no aux, so XLA computes none of it there (a training chunk's per-update logs, which only its last tick's evaluation reads); the last step runs once more in the program, keeping its own. The body is traced twice, or once for one step.

Parameters:

Name Type Description Default
xs Any

optional pytree of per-step inputs; if None, the body receives None as x each step (matches scan semantics).

None

Returns:

Type Description

(final_carry, last_aux); with length 0, init_carry and

an aux of zeros.

ajax.schedule

Schedules: hyperparameters that change over training.

progress

progress(timestep, horizon)

The share of a run of horizon steps (at least one) done at timestep, unclipped: what every schedule over training reads.

at

at(schedule, timestep)

schedule's value at timestep.

linear

linear(start, end, steps)

From start at timestep 0 to end at steps (at least one), then end.

warmup_cosine_schedule

warmup_cosine_schedule(
    peak_value,
    warmup_steps,
    total_steps,
    end_value_fraction=0.1,
    init_value_fraction=0.0,
)

Linear warmup to peak_value then cosine decay to end_value.

An optax step schedule (step -> learning_rate) usable as OptimizerConfig.learning_rate. The warmup-cosine profile is the one the in-context controller reference code trains with (Busetto et al. 2024, GPT-style: 5k warmup steps, decay to peak / 10).

warmup_steps=0 gives pure cosine decay from peak_value.

Agent state and configuration

ajax.state.BaseAgentState

Bases: Replaceable

get_keys_and_new_state

get_keys_and_new_state(n=1)

Draw n fresh random keys from the updates' key (rng).

Returns the drawn keys, then a new agent state whose key has moved past them: shuffle_key, agent_state = agent_state.get_keys_and_new_state(). The new key is the carry, taken first (random_keys.split_carry_first), so a step drawing one key more or less leaves the stream's next keys as they were. The state it is called on is untouched (it is frozen), so drawing from it again would hand out the same keys: carry on with the state returned.

ajax.state.NetworkConfig

Bases: Replaceable

ajax.state.OptimizerConfig

Bases: Replaceable

ajax.state.EnvironmentConfig

Bases: Replaceable

mode property

mode

The backend: "gymnax", or "brax" for brax and playground envs.