Skip to content

Agents

Every agent but TDMPC2MultiTask subclasses ActorCritic. Its constructor takes the environment, the algorithm's own hyperparameters and extensions=(); train runs one or more seeds at once. TDMPC2MultiTask learns offline from a dataset and keeps its own train, with the same seeds-at-once call.

Each agent's reference, with every constructor argument, is at the end of its algorithm page, next to the paper it follows and the notes on using it:

Agent Class Reference
SAC ajax.agents.SAC.SAC.SAC SAC
ASAC ajax.agents.ASAC.ASAC.ASAC ASAC
RVISAC ajax.agents.RVISAC.RVISAC.RVISAC RVI-SAC
REDQ ajax.agents.REDQ.REDQ.REDQ REDQ
CrossQ ajax.agents.CrossQ.CrossQ.CrossQ CrossQ
TD3 ajax.agents.TD3.TD3.TD3 TD3
TQC ajax.agents.TQC.TQC.TQC TQC
IQL ajax.agents.IQL.IQL.IQL IQL
AVG ajax.agents.AVG.AVG.AVG AVG
DQN ajax.agents.DQN.DQN.DQN DQN
PQN ajax.agents.PQN.PQN.PQN PQN
PPO ajax.agents.PPO.PPO.PPO PPO
APO ajax.agents.APO.APO.APO APO
REINFORCE ajax.agents.REINFORCE.REINFORCE.REINFORCE REINFORCE
UDRL ajax.agents.UDRL.UDRL.UDRL UDRL
DAgger ajax.agents.DAgger.DAgger.DAgger DAgger
APG ajax.agents.APG.APG.APG APG
DreamerV3 ajax.agents.DreamerV3.DreamerV3.DreamerV3 DreamerV3
TDMPC2 ajax.agents.TDMPC2.TDMPC2.TDMPC2 TD-MPC2
TDMPC2MultiTask ajax.agents.TDMPC2.TDMPC2MultiTask.TDMPC2MultiTask TD-MPC2

Every agent is also exported from ajax itself (from ajax import SAC).

Every agent but DreamerV3 and TD-MPC2 is a declared agent: its hyperparameters are the fields of a dataclass on a family of ajax.agents.families, which builds its constructor (keyword-only after env_id), run config and train function: a replay (SAC, TQC, REDQ, ASAC, RVISAC, CrossQ, TD3, IQL, DQN, DAgger: ReplayAgent), each step as it comes (AVG: IncrementalAgent), rollouts (PPO, APO, REINFORCE, PQN: OnPolicyAgent) or an iteration of its own (UDRL, APG: OwnIterationAgent); Agent families lists them. Its fields are fixed once built: dataclasses.replace(agent, gamma=0.9) builds another.

ajax.agents.base.ActorCritic

ActorCritic(
    env_id,
    n_envs=4,
    actor_learning_rate=0.0003,
    critic_learning_rate=0.0003,
    actor_architecture=("128", "tanh", "128", "tanh"),
    critic_architecture=("128", "tanh", "128", "tanh"),
    env_params=None,
    max_grad_norm=None,
    weight_decay=0.0,
    memory=None,
    normalize_observations=False,
    observation_clip=None,
    normalize_rewards=False,
    reward_normalization_gamma=None,
    actor_bias_init=None,
    critic_bias_init=None,
    encoder_kernel_init=None,
    cnn_image_shape=None,
    cnn_extra_obs_dim=0,
    cnn_spec=None,
    log_std_state_independent=False,
    log_std_init=-1.0,
    log_std_bounds=LOG_STD_BOUNDS,
    mean_kernel_init=None,
    logits_kernel_init=None,
    log_std_kernel_init=None,
    value_kernel_init=None,
    tanh_mean=False,
    encoder_layer_norm=False,
    squash=False,
    episode_length=None,
    action_repeat=1,
    extensions=(),
)

Initialize the agent.

Parameters:

Name Type Description Default
actor_learning_rate float | Callable[[int], float]

Learning rate for the actor's optimizer, or its schedule.

0.0003
critic_learning_rate float | Callable[[int], float]

Learning rate for the critic's optimizer, or its schedule.

0.0003
weight_decay float

decoupled weight decay of the actor's and the critic's optimizers (OptimizerConfig.weight_decay): on top of the Adam step, each step multiplies their parameters by 1 - lr * weight_decay. It reaches the networks only: a scalar dual variable (SAC's temperature) keeps its own plain Adam. 0 keeps plain Adam.

0.0
memory Optional[Union[MemoryConfig, dict]]

Pluggable memory block (MemoryConfig or its dict form); None keeps the networks feedforward.

None
normalize_rewards bool

divide the rewards the agent learns from by the running standard deviation of the discounted return and clip them to +-10, as SB3's VecNormalize does (logged returns stay in the env's units).

False
reward_normalization_gamma Optional[float]

with normalize_rewards, that return's discount: the agent's gamma if None (0.99 for an agent without one), 0 for the single-step reward's standard deviation.

None
action_repeat int

simulator steps per agent step on brax / playground envs (episode_length then counts simulator steps); stored on env_args. gymnax envs and prebuilt envs support only 1.

1

run_capabilities

run_capabilities()

The capabilities of this run (:func:~ajax.extensions.capabilities.run_capabilities).

resume_iteration_offset

resume_iteration_offset(initial_state)

Absolute index of the first scan iteration when resuming.

train feeds it to the inner train function so a resumed run sees absolute iteration indices (see build_resumable_train). The default 0 restarts the indices at every train call (every existing agent; APG's per-stage cadence relies on it). Agents whose schedules are functions of the absolute tick override this to return their tick counter -- a host-side int, equal across seeds.

resume_offset_kwargs

resume_offset_kwargs(initial_state)

:meth:resume_iteration_offset as the train function's keyword. Only passed when non-zero: the default (0) keeps the call -- and the train functions that predate the offset -- unchanged.

resumed_state

resumed_state(state, n_timesteps, train_options)

The state a resumed call of n_timesteps, with train's other options, continues from: state itself, but for a replay agent's replay, which grows to the uninterrupted run's.

sweepable_fields

sweepable_fields()

The fields this agent's sweep may vary: :attr:sweepable, less those this configuration captures when built.

member

member(values)

This agent as one member of a sweep: the fields named in values set to them, traced numbers, and what construction built from them rebuilt (derived_at_construction: the optimiser configs, from the learning rates; ajax.agents.sweep).

The copy is not constructed again: a sweepable field is one no construction check reads, and a traced value could not be checked. Its fields are set past the rule that fixes them once built, which keeps what trains what the run config logs: a sweep logs each member's values in its own run config.

use_precision

use_precision(precision, devices=None)

Set this call's compute dtype from train's precision (None: :attr:default_precision) on devices, record it in the run config, and return it: "float32" or "bfloat16" (:func:ajax.precision.resolve_precision).

use_devices

use_devices(
    devices,
    n_members,
    in_python,
    logging_config,
    runs_at_once=None,
)

This call's devices: those given, else every CPU device of a CPU run that JAX shows as several (:func:cpu_devices_to_split), else None. Members that share JAX's one CPU device hear how to split them (:func:cpu_split_hint), once per line that calls train. The run config records how many devices train the members.

set_compute_dtype

set_compute_dtype(dtype)

Build the networks of the next call to compute in dtype: the shared networks read it from :attr:network_args; an agent with networks of its own overrides this.

get_make_train

get_make_train()

:attr:make_train with the agent's own arguments (:attr:train_kwargs) and its extensions; :meth:train passes the rest.

smallest_evaluation_spacing

smallest_evaluation_spacing()

The environment steps of one iteration, between two of which a run can evaluate: one step in each env.

train

train(
    seed=42,
    n_timesteps=int(1000000.0),
    num_episode_test=10,
    logging_config="default",
    on_ids_ready=None,
    initial_state=None,
    total_timesteps=None,
    sweep=None,
    devices=None,
    precision=None,
    runs_at_once=None,
    unroll_ticks=False,
    **kwargs,
)

Train the agent, every seed at once (or runs_at_once at a time).

Parameters:

Name Type Description Default
seed int | Sequence[int]

One seed, or several: each trains a run of its own, all in the same compiled program.

42
n_timesteps int

Timesteps this call trains for. An agent that trains in iterations (an on-policy rollout of n_envs x n_steps steps) trains the whole iterations it holds, at least one, and warns when it is not a whole number of them.

int(1000000.0)
num_episode_test int

Number of episodes for evaluation during training.

10
logging_config Union[LoggingConfig, None, str]

the evaluation and logging (ajax.logging.LoggingConfig): the policy is evaluated every log_frequency steps on num_episode_test episodes, each run logs to the config's backends, and out holds the evaluations. Not given ("default"): about ten evaluations over the call, a printed line for each, no backend. None: no evaluation, no log and nothing printed.

'default'
on_ids_ready Optional[Callable]

Called once before training with the runs' identifiers, one per member, in order (an empty list without a logging_config): the ids its backends file each run under.

None
initial_state Optional[BaseAgentState]

a state (or (state, out)) train returned, to resume from: the run continues from its timestep.

None
total_timesteps Optional[int]

the whole run's horizon, which every schedule (training fraction, extensions, exploration, the logging's end) runs over; None: this call's end, its start (0, or the resumed timestep) plus n_timesteps. Pass the same horizon to every call of a run split into calls of whole iterations to follow the schedules of one call and end where it ends.

None
sweep Optional[Sweep]

hyperparameter configurations trained with every seed, all in this one program (ajax.agents.sweep): a dict of value lists, whose grid is trained, or a list of configurations, over the agent's sweepable fields (:meth:sweepable_fields). A sweep resumes with the same seed and sweep.

None
devices Optional[Sequence[Any]]

JAX devices (jax.devices()) to split the members over, each training a slice of them at the same time; the results come back on the first. A member trains as it does on one device, but for rounding. None: the default device trains them all, except on a CPU that JAX shows as several devices (JAX_NUM_CPU_DEVICES, set before JAX starts): several members then split over all of them, but for a Gymnasium environment, an evaluation_device or runs_at_once. The run config records how many devices trained (devices).

None
precision Optional[str]

what the networks compute in (ajax.precision): "float32"; "bfloat16", mixed precision (parameters, optimiser, heads, losses and targets stay float32); or "auto", bfloat16 where every device has bfloat16 units (NVIDIA compute capability 8.0 or more, TPU), else float32. None: the agent's original code's precision (:attr:default_precision). The run config records the result; a run may resume in another precision.

None
runs_at_once Optional[int]

the runs (the members) train in consecutive groups of this many, one group after another, each as it would with all of them at once, but for rounding: on a GPU, a group can fit a cache that all the runs overflow. None: every run at once. Takes no devices.

None
unroll_ticks bool

for an agent updating every few steps (DQN's train_frequency), the steps between two updates are compiled one after another instead of as a loop: on a GPU they then run in one CUDA graph, about 1.2 times as fast for DQN on CartPole, but each call compiles longer (about 16 s on bob's L40S). For long runs on a GPU; nothing changes on a CPU or on other agents.

False

Returns (state, out), each leaf with a leading axis over the members: the seeds, or the sweep's configurations, each over the seeds, as :attr:members lists them. On the shared loop (ajax.agents.loop) out is None with logging_config=None, else the evaluations (ajax.logging.progress.Evaluations: the dict of every logged name, with returns and timesteps).

by_configuration

by_configuration(values)

The last train call's values, a row per member (such as evaluations.returns), as (configuration, rows) pairs in the sweep's order, each configuration's rows one per seed.

__repr__

__repr__()

The agent as the call that builds it: its class and the arguments that differ from their defaults. An object (a prebuilt environment, an extension) shows as its class.

save

save(state, path)

Write state and this agent's class and plain constructor arguments to path, for :meth:load to build both again (ajax.checkpoint).

load classmethod

load(path, train_options=None, **arguments)

(agent, state) from a file :meth:save wrote for an agent of this class. arguments: the constructor arguments the file could not store (objects: a prebuilt environment, extensions, an expert policy), passed again, and any to replace (:func:ajax.checkpoint.load).

train_offline

train_offline(
    dataset,
    n_updates,
    seed=42,
    num_episode_test=10,
    logging_config=None,
    on_ids_ready=None,
    precision=None,
)

Train on a transition dataset alone, with no environment step.

n_updates of the agent's own update on a replay holding dataset's rows (:meth:ajax.agents.loop.TrainLoop.offline), evaluating every logging_config.log_frequency updates. Returns (state, out) as :meth:train does, with the state's timestep and evaluation count back at 0, so that train(initial_state=state, ...) fine-tunes online from it, its replay keeping the dataset's rows (with learning_starts=0, from the first step). precision is :meth:train's.

Raises ValueError on an agent without a transition replay.

ajax.agents.families

The agents' families. An agent declares its hyperparameters once, as the fields of a dataclass, and writes what its paper defines: its networks, its init (on its own key layout), its update and its equations. Its family builds everything else from those fields, the same for every member: the constructor, the logged run config, the optimisers, the replay, the extensions' binding, the collector's storage, the training loop's shape and the evaluation's value estimate::

@dataclass(kw_only=True, eq=False, repr=False)
class IQL(ObservationNormalization, ExpertGuided, ReplayAgent):
    expectile: float = 0.7
    ...

    def init(self, key, context): ...
    def update(self, agent_state, context): ...

An agent learning from a replay of transitions is a ReplayAgent, one learning from each rollout of its current policy an OnPolicyAgent, one whose iteration is its own (a differentiable rollout, a replay of segments) an OwnIterationAgent, and one storing rows in a replay of its own, sized per call (a world model's), an OwnReplayAgent. The shared knobs an algorithm may take beyond the ones every agent takes (gradient clipping, normalisation, an expert, image observations) are field mixins. The family reads some fields by name (DeclaredAgent, ReplayAgent, OnPolicyAgent). Every agent, family and mixin carries the literal @dataclass decorator, which the API docs read the constructor from; the contract an agent declares for the extensions and the loop (name, capabilities, ...) stays unannotated, so it is no field.

TrainContext dataclass

TrainContext(
    env_args,
    network_args,
    actor_optimizer_args,
    critic_optimizer_args,
    extensions,
    total_timesteps,
    make_collector,
    buffer=None,
    recurrent=False,
    executed=None,
    offline=False,
)

What one train() call gives the agent's init and update, beyond its hyperparameters.

It holds:

  • the run's environment config (env_args);
  • the network and optimiser configs (network_args, actor_optimizer_args, critic_optimizer_args);
  • the extensions, bound to this run;
  • the replay: a replay agent's buffer, an own-replay agent's own (None on-policy);
  • how to build the collector (make_collector);
  • the run's horizon (total_timesteps);
  • whether the run is recurrent (its networks have memory);
  • the residual-action hook (executed), None without a residual policy.

Why it exists: an agent's hyperparameters are its fields, fixed once it is built. Everything that depends on one train() call (the env and the configs it may override, the extensions bound to them, the horizon) is passed explicitly to init and update, where SB3 keeps it as attributes of the agent and PureJaxRL in closures inside its make_train. One agent then trains any number of runs, and a test calls init or update alone on agent.make_context(total_timesteps) (CLAUDE.md rule 7: passed in, never global).

make_scored_actions

make_scored_actions(batch)

The maps to the actions the critics score at batch's rows, at s and at s' (controller.make_scored_actions).

make_actor_critic

make_actor_critic(
    key,
    build=get_initialized_actor_critic,
    critic_optimizer_args=None,
    **options,
)

build's actor and critic train states on this run's configs (another critic optimiser's with critic_optimizer_args).

GradientClipping dataclass

GradientClipping(*, max_grad_norm=None)

Gradient clipping of both networks' optimisers.

Parameters:

Name Type Description Default
max_grad_norm Optional[float]

Clip each network's gradients to this global norm (OptimizerConfig); None leaves them unclipped.

None

ObservationNormalization dataclass

ObservationNormalization(
    *, normalize_observations=False, observation_clip=None
)

Observations normalised inside the agent.

Parameters:

Name Type Description Default
normalize_observations bool

Normalise the observations the networks read by running statistics.

False
observation_clip Optional[float]

With normalize_observations, clip the normalised observations to +-observation_clip, as baselines' VecNormalize does (clipob=10). An on-policy agent's, stored normalised at collection; a replay agent normalises inside its networks, which do not clip, so it refuses one.

None

RewardNormalization dataclass

RewardNormalization(
    *,
    normalize_rewards=False,
    reward_normalization_gamma=None,
)

Rewards normalised before the agent learns from them.

Parameters:

Name Type Description Default
normalize_rewards bool

Divide the rewards learned from by the running standard deviation of the discounted return and clip them to +-10, as SB3's VecNormalize does (the logged returns stay in the env's units).

False
reward_normalization_gamma Optional[float]

With normalize_rewards, that return's discount: the agent's gamma if None (0.99 for an agent without one), 0 for the single-step reward's standard deviation.

None

ExpertGuided dataclass

ExpertGuided(
    *, expert_policy=None, eval_expert_policy=None
)

An expert the agent tracks.

Parameters:

Name Type Description Default
expert_policy Optional[Callable]

An expert the collector tracks: its actions, from its state along each trajectory, feed the observation features, a residual policy and the extensions reading them; each evaluation logs its return. It speaks the env's units; the agent reads it in its own (agent.expert).

None
eval_expert_policy Optional[Callable]

The expert whose return each evaluation logs instead, which takes no other part in the run.

None

ImageObservations dataclass

ImageObservations(
    *,
    cnn_image_shape=None,
    cnn_extra_obs_dim=0,
    cnn_spec=None,
)

Observations holding an image, which the networks read through a CNN encoder (NetworkConfig).

Parameters:

Name Type Description Default
cnn_image_shape Optional[tuple[int, int, int]]

The image's (height, width, channels), flattened first in each observation; None reads the observations with the MLP encoder.

None
cnn_extra_obs_dim int

The features after the image, read beside the encoder's output.

0
cnn_spec Optional[CNNSpec]

The encoder's layers (CNNSpec); None: CNNEncoder's default.

None

EncoderSharing dataclass

EncoderSharing(*, share_encoder=None)

An actor and a critic that may read their observations through one encoder.

Parameters:

Name Type Description Default
share_encoder Optional[bool]

One encoder (the MLP or CNN, and the memory block) for the actor and the critic (NetworkConfig.share_encoder): the critic owns it and the critic's optimiser steps it, at critic_learning_rate. PPO and APO train it with both losses (one step down their sum); an agent with a Q-critic with the critic's loss alone, its actor reading it detached. False: each network has its own. None: what the agent's reference code does (reference_share_encoder).

None

reference_share_encoder

reference_share_encoder()

Whether the agent's reference code gives the actor and the critic one encoder, for the networks this agent builds. The model-free references keep them apart (sfujim/TD3@34770cc TD3.py:81, :85; xtma/rlpyt@e28bb20 models/pg/mujoco_ff_model.py:34-55; Ni et al. 2022's recurrent ones, twni2016/pomdp-baselines@e7c19c3 policies/learner.py:213); an agent whose reference shares overrides this, citing it.

EntropyTemperature dataclass

EntropyTemperature(
    *,
    alpha_learning_rate=0.0003,
    alpha_init=1.0,
    target_entropy_per_dim=-1.0,
    alpha_update_start=0,
)

The entropy temperature alpha of a soft actor-critic, learned towards a target entropy (Haarnoja et al., 2018b) unless the agent fixes it (ajax.agents.temperature).

Parameters:

Name Type Description Default
alpha_learning_rate Optional[float]

The temperature's Adam learning rate; None: the actor's (CrossQ's authors step every network at one rate).

0.0003
alpha_init float

The temperature's initial value.

1.0
target_entropy_per_dim Schedule

The target entropy per dimension of the policy's actions (gain mode's gains): a constant, or a function of the timestep (ajax.schedule).

-1.0
alpha_update_start int

The env steps collected before the temperature's steps are kept (0: from the first update).

0

alpha_args property

alpha_args

The temperature's learning rate and initial value.

target_entropy property

target_entropy

target_entropy_per_dim times the policy's action width (gain mode's gains), at each timestep for a schedule.

target_entropy_at

target_entropy_at(timestep)

The target entropy at timestep.

temperature_update_due

temperature_update_due(timestep, extensions)

Whether the temperature's step counts at timestep: from alpha_update_start on (update_steps.reached), never while an extension sets the temperature itself (MEW).

PolicyUpdateStart dataclass

PolicyUpdateStart(*, policy_update_start=0)

An actor-critic whose actor's steps count from a timestep on, every replay actor-critic's knob (SAC's, kept for its probes and its users).

Parameters:

Name Type Description Default
policy_update_start int

The env steps collected before the actor's steps are kept (0: from the first update).

0

policy_update_due

policy_update_due(timestep)

Whether the actor's step counts at timestep: from policy_update_start on (update_steps.reached); the Python True, with no gate, where every update comes after it.

keeps_actor_metrics

keeps_actor_metrics()

An actor waiting for policy_update_start skips the updates before it, which log its last step's metrics (update_steps.run_actor_if).

DeclaredAgent dataclass

DeclaredAgent(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
)

Bases: ActorCritic

An agent whose constructor is its fields' (keyword-only but env_id): the knobs every agent takes, its family's, its mixins' and its own.

The family reads some fields by name. Every field named like an ActorCritic argument (ACTOR_CRITIC_ARGS: actor_learning_rate, critic_architecture, ...) reaches it; expert_policy is the agent's expert; an agent claiming the discounted capability declares gamma, or construction raises TypeError, and reward_scale if it scales its rewards (DISCOUNT_FIELDS). Its family may read more (ReplayAgent, OnPolicyAgent).

Parameters:

Name Type Description Default
env_id Union[str, EnvType]

The environment's id, or an environment.

required
n_envs int

The environments stepped in parallel.

1
env_params Optional[EnvParams]

The environment's parameters; its defaults if None.

None
weight_decay float

Decoupled weight decay of the networks' optimisers (OptimizerConfig).

0.0
episode_length Optional[int]

Simulator steps per episode (brax / playground).

None
action_repeat int

Simulator steps per agent step (brax / playground).

1
extensions Sequence[Extension]

The extensions applied in the training loop.

()

expert property

expert

The agent's expert in agent units (ActorCritic wraps it), if any; the expert_policy field holds the one passed in.

preset classmethod

preset(name, env_id, **overrides)

The agent with the settings its reference tunes for the task name, from its module's PRESETS table (ajax.agents.presets), the overrides given winning over them. Its run config records the name under "preset".

check

check()

Refuse arguments the algorithm cannot take, before anything is built.

actor_critic_args

actor_critic_args()

ActorCritic arguments the paper fixes (initialisations, heads) or derives from the fields (CrossQ's learning rates and widths). One named like a field only resolves it where the caller left it None (TypeError otherwise).

optimizer_settings

optimizer_settings()

OptimizerConfig settings both networks' optimisers take (the reference's Adam: its eps, its betas).

network_settings

network_settings()

NetworkConfig settings the reference fixes beyond ActorCritic's arguments (REDQ's squash_log_det_eps, TQC's critic_quantiles).

extension_values

extension_values(configs)

Values only the agent has, which its extension_context may name (configs: the run's env_args, network_args and optimisers).

evaluation_options

evaluation_options()

Each evaluation's options beyond the expert and the critic's estimate (ajax.log.evaluate_and_log's: APO's avg_reward_mode).

evaluation_kwargs

evaluation_kwargs()

Each evaluation's arguments: the expert, the critic's estimate, the expert whose return it logs (eval_expert_policy, in agent units) and the agent's evaluation_options.

uniform_steps

uniform_steps()

The steps an off-policy family's collection acts uniformly for: the warm-up, until learning_starts (None), for an agent claiming the warmup capability; none otherwise (TQC's authors act with the policy from the first step).

keeps_actor_metrics

keeps_actor_metrics()

Whether the update keeps its actor's last metrics on the state, for the updates whose actor step it skips to log (update_steps.run_actor_if): the loop gives the state their slot.

setup

setup()

What the agent derives or checks once its env, networks and family are built: IQL's value optimiser, PPO's checks of its rollout split (they need n_envs).

check_recurrent_options

check_recurrent_options(extensions)

Refuse what a run with memory cannot take: an expert or extensions, which the shared collection does not carry through a recurrent policy (APG's rollout does).

value_estimate

value_estimate()

The critic's estimate of the return each evaluation compares, on the agent's discount and reward scale; none without a discounted critic.

policy

policy(agent_state, seed_index=0)

The policy of seed seed_index of agent_state (train's state, or its (state, out)), acting in the environment's units exactly as the agent's evaluation acts (ajax.policy.Policy).

evaluate

evaluate(agent_state, episodes=10, seed=0)

The return of episodes fresh episodes of each member's trained policy: a row per member of agent_state (train's state, or its (state, out)), a column per episode. The policy acts as agent.policy does, exactly as the agent's evaluation acts; seed draws the episodes' starts. On a Gymnasium environment the episodes step in Python, a member after another. Its mean over a row is that member's score::

state, _ = agent.train(seed=[0, 1], n_timesteps=50_000)
agent.evaluate(state).mean(axis=1)

render

render(
    agent_state,
    path,
    seed_index=0,
    seed=0,
    max_steps=None,
    draw=None,
)

Saves one fresh episode of seed seed_index's trained policy as an animation at path, and returns the path. The policy acts as in agent.evaluate; seed draws the episode's start, and max_steps cuts a long episode short. The file is a .gif, or an .html page on Brax (ajax.render.animation_suffix)::

state, _ = agent.train(seed=0, n_timesteps=50_000)
agent.render(state, "cartpole.gif")

draw draws an environment Ajax has no drawing for, such as one of your own: a function from one environment state (its own fields, without a leading axis) to a (height, width, 3) picture, 8-bit or floats in [0, 1]. Given, it is what draws.

policy_parts

policy_parts()

How the agent acts on one seed's state: as the shared evaluation acts (ajax.policy.evaluation_policy), through the run's controller, its extensions bound as in training.

predict

predict(
    agent_state,
    observation,
    seed_index=0,
    deterministic=True,
)

The action at observation (one, or a batch with a row per env) in the environment's units, as agent.policy(agent_state, seed_index) acts at an episode's start; the policy is built once per state and seed. A policy carrying memory from one step to the next refuses: one call cannot carry it, agent.policy does.

make_context

make_context(
    total_timesteps,
    num_episode_test=1,
    *,
    env_args=None,
    actor_optimizer_args=None,
    critic_optimizer_args=None,
    network_args=None,
    extensions=None,
    run_ids=None,
    logging_config=None,
    start_timestep=0,
    end_timestep=None,
    offline_data=None,
)

The loop and the context of one train function, on the agent's own configs and extensions unless others are given: the extensions bound to the keys of its extension_context. Its family's make_train builds the run on them; a test calls agent.make_context(n) to call init or update alone.

make_collector

make_collector(key, loop, network_args, **options)

The collector state (init_collector_state), holding a stateful expert's state and each env's step in its episode for an extension that reads it (JSRLCurriculum), with options an agent's own.

ReplayAgent dataclass

ReplayAgent(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
    buffer_size,
    batch_size,
    learning_starts,
    train_frequency=1,
)

Bases: DeclaredAgent

An off-policy agent on a replay of transitions (TrainLoop.off_policy): one step per env per iteration and, from learning_starts, one update every train_frequency steps; offline (train_offline) one update per iteration on a replay of the dataset.

Beyond DeclaredAgent's names, the family reads buffer_size, batch_size and learning_starts, which every member declares with its paper's values. An agent writes init and update, and may replace collection's action pipeline (choose_behaviour).

Parameters:

Name Type Description Default
buffer_size int

The replay's capacity, in transitions. A run reserves memory for the rows it writes, at most buffer_size // n_envs per env, so a short run's replay is small (ajax.buffers.ring).

required
batch_size int

The rows each update samples.

required
learning_starts int

The env steps collected before the first update (0: none).

required
train_frequency int

The env steps between updates, as SB3's train_freq and CleanRL's (dqn.py:195): from learning_starts, an update on each tick whose steps collected reach a multiple of it (update_steps.reaches_multiple); 1, the default, every tick. An evaluation between two updates logs the last one's metrics.

1

init

init(key, context)

A fresh agent state, on the agent's own key layout.

update

update(agent_state, context)

One update: (agent_state, logged metrics).

update_start

update_start()

The env steps collected before the first update.

choose_behaviour

choose_behaviour(context)

The action pipeline collection runs; None: the policy's, uniform during the warm-up or its chooser's. An agent's own runs the chooser too (context.env_args.warmups).

before_env_steps

before_env_steps()

The agent as it updates on a dataset before acting, where no env step will open its starts (ignores_update_starts). A copy: the agent that trains online keeps them, as its run config logs them.

from_update_start

from_update_start()

The agent as the online loop updates it, from update_start() on: a wait for a timestep at or before it (policy_update_start, alpha_update_start; SAC's 2,000 under its 10,000 learning_starts) is over at every update, so its gate, a lax.cond in every update, goes. A copy, as before_env_steps's.

evaluation_kwargs

evaluation_kwargs()

DeclaredAgent's, and what each evaluation logs of the replay (measure_replay).

replay_window

replay_window()

The rows one replayed sample spans; None: rows alone.

replay_length

replay_length(rows_per_env)

The ring length of the replay of a run writing rows_per_env rows per env (ajax.buffers.ring): one more, so that it never reports full before its capacity, buffer_size // n_envs, at most that, and at least the rows it holds before it can sample.

resumed_state

resumed_state(state, n_timesteps, train_options)

state, its replay grown to the uninterrupted run's ring (replay_length) where it is shorter: the call writes one row per env and tick, none offline. A shorter ring that has overwritten rows is refused (size_ring).

stores_state

stores_state()

Whether the replay keeps the actor's recurrent state (R2D2's stored state).

make_collector

make_collector(key, loop, network_args, **options)

The collector state, its replay storing what the run reads: the expert's data where it is held, the fields the extensions ask for, and options (init_collector_state's), an agent's own.

make_train

make_train(
    env_args,
    actor_optimizer_args,
    critic_optimizer_args,
    network_args,
    total_timesteps,
    num_episode_test,
    run_ids=None,
    logging_config=None,
    start_timestep=0,
    end_timestep=None,
    offline_data=None,
    extensions=(),
)

The train function ActorCritic.train builds: the loop over init and update.

extension_values

extension_values(configs)

A discounted Q critic with targets gives BellmanPretrain its critic step on a replay batch without any extension (update_value_fn, the agent's update_critic) and the targets' Polyak update (update_target_fn): an agent naming them in its extension_context writes update_critic(agent_state, batch, carries, context) -> (agent_state, aux with critic_loss, metrics).

RecurrentReplayAgent dataclass

RecurrentReplayAgent(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
    buffer_size,
    batch_size,
    learning_starts,
    train_frequency=1,
    memory=None,
    burn_in=0,
    sequence_length=NI_WINDOW_STEPS,
    stored_state=False,
)

Bases: ReplayAgent

A replay agent that may have memory: it then trains on replayed windows of burn_in + sequence_length + 1 steps with R2D2's burn-in (ajax.agents.recurrent), and its learning_starts must give each env more steps than a window.

Its networks with memory are Ni et al. (2022)'s (ajax.agents.recurrent: NI_LAYOUT, NI_MEMORY_WIDTH, NI_MEMORY_INITS, ni_initialisation, which the agent's actor_critic_args takes). They read the previous action and the previous reward, so a run with memory observes both: PreviousAction and PreviousReward join its extensions where it has none of them (owner, 2026-11-13: on by default, as Ni et al.'s networks read them). The family names neither: reference_features and reference_layout do, and a subclass overrides the two together.

Its batch_size counts rows without memory, windows with it; None is 256 rows (each agent's reference's) or Ni et al.'s 64 windows. The window defaults are theirs too: 64 trained steps from a zero memory, no burn-in.

Parameters:

Name Type Description Default
memory Optional[Union[MemoryConfig, dict]]

The networks' memory block (MemoryConfig or its dict form); None keeps them feedforward.

None
burn_in int

The steps that rebuild the recurrent state before a replayed window's trained steps.

0
sequence_length int

The trained steps of a replayed window.

NI_WINDOW_STEPS
stored_state bool

R2D2's stored-state replay: replayed windows start from the actor's recurrent state recorded at collection (Kapturowski et al. 2019).

False

reference_features

reference_features()

The observation features a run with memory observes, each added where its extensions have none of the kind: those reference_layout's memory reads (Ni et al.'s previous action and previous reward). A subclass returning none also returns a reference_layout embedding none; a Q-critic's memory then reads the previous action the replay appends (ajax.agents.recurrent.previous_actions).

reference_layout

reference_layout()

The NetworkConfig fields of the networks with memory (Ni et al.'s layout); {} keeps the agent's own.

IncrementalAgent dataclass

IncrementalAgent(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
    learning_starts,
    expose_recent_rollout=False,
)

Bases: DeclaredAgent

An agent learning from each step as it comes, without a replay (TrainLoop.off_policy): one step per env per iteration, then one update on that step alone, for each step collected from learning_starts on, so never on a warm-up step (AVG, Vasan et al., 2024). An agent writes init and update, and may record statistics of every collected step (update_step_statistics).

Parameters:

Name Type Description Default
learning_starts int

The env steps collected before the first step the agent learns from.

required
expose_recent_rollout bool

Keep each step on agent_state.last_rollout, a one-step rollout, even when no extension reads it.

False

init

init(key, context)

A fresh agent state, on the agent's own key layout.

update

update(agent_state, transition, context)

One update on the step just collected: (agent_state, logged metrics).

update_step_statistics

update_step_statistics(agent_state, transition, context)

What the agent records from every collected step, before the update (AVG's TD-error scale).

make_train

make_train(
    env_args,
    actor_optimizer_args,
    critic_optimizer_args,
    network_args,
    total_timesteps,
    num_episode_test,
    run_ids=None,
    logging_config=None,
    start_timestep=0,
    end_timestep=None,
    extensions=(),
)

The train function ActorCritic.train builds: the loop over init, update_step_statistics and update. It takes no dataset: without a replay there is no offline training (train_offline refuses it).

OnPolicyAgent dataclass

OnPolicyAgent(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
    n_steps,
    n_epochs,
    num_minibatches,
    expose_recent_rollout=False,
)

Bases: DeclaredAgent

An on-policy agent (TrainLoop.on_policy): each iteration collects n_steps per env with the current policy, then one update on that rollout, n_epochs passes over its minibatches (ajax.agents.minibatch). The rollout keeps each observation normalised with the statistics of its step (EnvironmentConfig.store_normalized_obs), as SB3's VecNormalize does.

The family reads n_steps, n_epochs and num_minibatches, which every member declares with its paper's values, and brax's num_resets_per_eval and num_evals where an agent declares them. An agent writes init and update, and may replace collection's action pipeline (choose_behaviour) and add to each evaluation (evaluation_options).

Parameters:

Name Type Description Default
n_steps int

The steps each env collects per iteration.

required
n_epochs int

The passes of each update over the rollout.

required
num_minibatches int

The minibatches of each pass (PPO derives them from batch_size at 0).

required
expose_recent_rollout bool

Keep each rollout on agent_state.last_rollout even when no extension reads it.

False

smallest_evaluation_spacing

smallest_evaluation_spacing()

A rollout: n_steps in each env.

init

init(key, context)

A fresh agent state, on the agent's own key layout.

update

update(
    agent_state,
    rollout,
    agent_state_at_rollout_start,
    context,
)

One update on the (n_steps, n_envs) rollout collected from agent_state_at_rollout_start (a recurrent agent replays the rollout from that state's memories): (agent_state, logged metrics).

choose_behaviour

choose_behaviour(context)

The action pipeline collection runs; None: the policy's sample.

make_train

make_train(
    env_args,
    actor_optimizer_args,
    critic_optimizer_args,
    network_args,
    total_timesteps,
    num_episode_test,
    run_ids=None,
    logging_config=None,
    start_timestep=0,
    end_timestep=None,
    extensions=(),
)

The train function ActorCritic.train builds: the loop over init and update. It takes no dataset: an on-policy agent learns from its own rollouts (train_offline refuses it).

OwnIterationAgent dataclass

OwnIterationAgent(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
)

Bases: DeclaredAgent

An agent whose iteration is its own (TrainLoop.train): it acts and learns its way, then the loop evaluates on its cadence, logs and resumes. UDRL collects a segment and fits its replay of segments (Schmidhuber, 2019); APG takes a gradient step through a differentiable rollout.

An agent writes init, iterate (applying the extensions' post_update where its order puts it), report (the training metrics an evaluation logs), evaluation_metrics and count_iteration_steps. It may take options per train call (configure_call), and return every iteration's output instead of the evaluations (returns_iterations, make_iteration_output). It takes no dataset: train_offline refuses it.

init

init(key, context)

A fresh agent state, on the agent's own key layout.

iterate

iterate(agent_state, context)

One iteration, the extensions' post_update applied: (agent_state, aux, which report and make_iteration_output read).

report

report(agent_state, aux)

The training metrics an evaluation logs, timestep included.

evaluation_metrics

evaluation_metrics(
    agent_state, key, context, num_episode_test
)

The policy's evaluation metrics, on num_episode_test episodes.

policy_parts

policy_parts()

How the agent acts: its own, as its evaluation is.

count_iteration_steps

count_iteration_steps(context)

The env steps one iteration takes, and how a warning names them.

configure_call

configure_call(context, n_iterations)

The context of one train call of n_iterations iterations, and how a state it resumes from is transformed (None: as it is). An agent taking options per call declares them as keywords here.

make_iteration_output

make_iteration_output(aux, evaluations)

What an iteration returns: its evaluations, which the loop records (None without logging); with returns_iterations, the agent's own.

make_train

make_train(
    env_args,
    actor_optimizer_args,
    critic_optimizer_args,
    network_args,
    total_timesteps,
    num_episode_test,
    run_ids=None,
    logging_config=None,
    start_timestep=0,
    end_timestep=None,
    extensions=(),
    **call_options,
)

The train function ActorCritic.train builds: the loop over init and iterate, call_options going to configure_call. It takes no dataset (train_offline refuses it).

OwnReplayAgent dataclass

OwnReplayAgent(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
)

Bases: DeclaredAgent

An agent storing rows in a replay of its own (TrainLoop.off_policy's hooks): each tick its row collector acts and stores one row per env, it runs the updates its schedule gives the absolute tick, and the loop evaluates on its cadence, logs and resumes. DreamerV3 trains on windows of the replay at a train ratio (Hafner et al., 2023).

It is no ReplayAgent: its replay holds rows, not transitions, sized for each call (prepare_replay), and it takes no dataset. It assumes the row collector (ajax.environments.row_collector): a resumed run starts at the tick of the rows it counted, and each env copy may carry its own system.

An agent writes prepare_replay, init, collect, count_updates, update, report and evaluation_metrics; it may count its ticks (count_ticks), restart what it logs after each log (make_after_log) and check a call (check_run).

prepare_replay

prepare_replay(start_tick, end_tick, agent_state)

The replay of a call training from tick start_tick, holding the rows the run writes up to tick end_tick (its horizon's, or start_tick for a 0-tick call), and the state it resumes from (None for a fresh run), its replay moved into that replay's shapes. The agent records the sizes.

init

init(key, context)

A fresh agent state, on the agent's own key layout.

collect

collect(agent_state, tick, context)

Act and store one row per env at the absolute tick: (agent_state, what update reads).

count_updates

count_updates(agent_state, tick, context)

The updates run after the tick's rows (an int32 count).

update

update(agent_state, experience, context)

One update on the replay; the loop folds post_update after it.

report

report(agent_state, aux)

The training metrics an evaluation logs, timestep included.

evaluation_metrics

evaluation_metrics(
    agent_state, key, context, num_episode_test
)

The policy's evaluation metrics, on num_episode_test episodes.

policy_parts

policy_parts()

How the agent acts: its own, as its evaluation is.

count_ticks

count_ticks(n_timesteps, start_tick)

The ticks of n_timesteps from start_tick: one row per env each.

steps_before

steps_before(tick)

The timesteps the absolute ticks before tick take: one row per env each.

make_after_log

make_after_log()

What runs on every tick after the logging gate (Evaluation's after_log). None by default: an identity would still trace the gate.

check_run

check_run(agent_state, end_tick)

Check the state a call ended with, at tick end_tick.

value_estimate

value_estimate()

None: the agent evaluates itself (evaluation_metrics), so the shared evaluation's critic estimate is never compared; a world model's critic reads its latent state, not the observation that estimate passes.

resume_iteration_offset

resume_iteration_offset(initial_state)

The absolute tick of a resumed run, equal across seeds (row_collector.resume_tick), so that every schedule of the tick continues instead of restarting.

train

train(
    seed=42,
    n_timesteps=int(1000000.0),
    num_episode_test=10,
    logging_config="default",
    on_ids_ready=None,
    initial_state=None,
    total_timesteps=None,
    sweep=None,
    devices=None,
    precision=None,
    runs_at_once=None,
    unroll_ticks=False,
    **kwargs,
)

ActorCritic.train, then check_run at the tick the call ended at: a run this agent's mode cannot learn is refused once trained (T10). ActorCritic.train does not check, so a caller can still read what such a run learned, as the TD-MPC2 chain probe does.

make_train

make_train(
    env_args,
    actor_optimizer_args,
    critic_optimizer_args,
    network_args,
    total_timesteps,
    num_episode_test,
    run_ids=None,
    logging_config=None,
    start_timestep=0,
    end_timestep=None,
    extensions=(),
    *,
    replay,
    start_tick=0,
)

The train function ActorCritic.train builds: off_policy's ticks of the agent's collect, count_updates and update on the call's replay, evaluating every log_frequency timesteps. It takes no dataset (train_offline refuses it).

acts_with_its_own_state

acts_with_its_own_state(method)

method saying so when the state it is given was trained by another agent or on another environment: its networks then meet inputs of another shape, which flax reports as a parameter of the wrong shape without naming the state.

measure_replay

measure_replay(agent_state)

What each evaluation logs of a replay agent's replay: the share of its rows an expert acted in (replay/expert_share), where the replay keeps the flags (a run with an expert). Read at each evaluation, not each update, over the whole replay, not one batch.

reads_step_in_episode

reads_step_in_episode(extensions)

Whether an extension reads each env's step in its episode, which the collector then counts.

reads_last_rollout

reads_last_rollout(extensions)

Whether an extension reads the agent's last rollout, which the agent then keeps.

Presets and sweeps

Agent.preset(task, env_id) builds an agent from its reference's settings for one task, and train(sweep=...) trains several configurations in one program. See Presets and Hyperparameter sweeps.

ajax.agents.presets

Per-task presets: the settings an agent's reference code tunes for one task, kept apart from the agent's defaults, which are its reference's general config. An agent's module keeps them in a PRESETS table, task name to :class:Preset, and Agent.preset(name, env_id, **overrides) (:meth:ajax.agents.families.DeclaredAgent.preset) builds the agent from one.

A task goes by the name its reference gives it ("Hopper", "AntMaze", "Atari"), not by an env id: one task has ids in gymnasium, brax and playground.

A table may also hold another library's conventions under the library's name (PPO's "SB3"): that library's defaults in Ajax's names, for someone bringing settings from it.

Preset dataclass

Preset(overrides, citation)

A task's settings in an agent's reference.

Parameters:

Name Type Description Default
overrides Mapping[str, Any]

The agent's fields its reference sets for the task. A table gives the presets of one reference the same fields, the ones the reference varies across its tasks, even where a value equals the default: a default that changes later leaves the preset as its reference.

required
citation str

Where the values come from (repo@commit, file:line).

required

presets_of

presets_of(agent_class)

The PRESETS table of the module that defines agent_class, empty when it has none: a subclass defined elsewhere tunes other things.

ajax.agents.sweep

A sweep: hyperparameter configurations trained with every seed, all in one compiled program (ActorCritic.train's sweep).

The seeds already train as one program, vmapped over their keys. A sweep puts its configurations on the same axis: each member, one configuration with one seed, builds its agent with the configuration's values while the program is traced (ActorCritic.member), so they are numbers the program reads, one per member, instead of constants compiled into it. Members run configuration-major: member k * n_seeds + s is configuration k with seed s, and draws the keys a run of that configuration with seed s draws.

Only an agent's sweepable fields (ActorCritic.sweepable) vary: numbers its training reads as numbers. A setting that sets a shape, a loop's length or which code is built needs a program of its own: one train call per value.

configurations

configurations(sweep)

The sweep's configurations in order: a dict's grid (its last field varying fastest, as itertools.product) or the list given; none without a sweep.

check

check(agent_name, sweepable, names, reasons=None)

Refuse the fields outside the agent's sweepable ones, naming them, with the agent's own reason (ActorCritic.unsweepable) where it gives one.

member_row

member_row(configuration, seed)

A member's seed and values, as ActorCritic.members lists them.

configuration_label

configuration_label(configuration)

A configuration on one line, as the progress lines name it.

by_configuration

by_configuration(members, values)

values, a row per member, as (configuration, rows) pairs in the sweep's order: each configuration's rows, one per seed. members is ActorCritic.members; without a sweep there is one pair, of an empty configuration.

member_values

member_values(configurations_by_member)

Each swept field's values, one per member: float32, the precision of the arrays they multiply, as a separate run's Python number takes it.

Acting

A trained agent acts through its policy (agent.policy, agent.predict; Train, evaluate, deploy).

ajax.policy

How a trained agent acts: the part of an evaluation step before the environment steps, which evaluate runs on its rollout (ajax.evaluate), and the policy object a user acts with (agent.policy), which acts as the evaluation does.

Acted

Bases: NamedTuple

One acting step, per env, in agent units.

PolicyCarry

Bases: NamedTuple

What a policy carries from one step to the next, per env; None where it carries nothing.

PolicyParts

Bases: NamedTuple

How an agent acts, on one seed's state: initial(n_envs) is the carry at the start of an episode, step(obs, carry, starts, reward, key) -> (action, carry) acts once in the environment's units, starts True where obs starts an episode. reads_reward: step reads the reward the last action earned.

Policy

Policy(build, agent_state)

A trained agent's policy (agent.policy), acting in the environment's units exactly as the agent's evaluation acts:

carry = policy.reset(n_envs)
action, carry = policy.act(obs, carry, done, reward)

obs is a batch of the environment's own observations, one row per env. done is True where obs starts a new episode, the last action having ended one (None: nowhere); the memory, the expert's state, the observation features and the command restart there. reward is what the last action earned, which a command-conditioned agent (UDRL) and a PreviousReward feature read. key is the step's key for the policy's draws (a chooser's, a world model's sampling); None draws it from the carry's own stream. act is compiled once, its state an argument of the program, not a constant in it.

has_memory property

has_memory

Whether the policy carries anything from one step to the next.

reset

reset(n_envs)

The carry of n_envs envs whose next observation starts an episode.

act

act(obs, carry, done=None, reward=None, key=None)

The action at obs, in the environment's units, and the next carry.

normalised_reward

normalised_reward(x, norm_info)

x, a reward in the env's units, in the agent's: divided by the scale the training env's reward normaliser holds (norm_info.reward, frozen) and clipped, as collection does each reward; unchanged without one.

frozen_progress

frozen_progress(agent_state)

The training progress an evaluation's features hold: the collector's as it stands (None where it keeps no horizon).

get_deterministic_action_and_entropy_fn

get_deterministic_action_and_entropy_fn(
    actor_state, recurrent, continuous
)

Return a function mapping (obs, done, hidden) → (action, entropy, hidden).

In recurrent mode the hidden state is an explicit input/output so the eval loop can thread it through its carry (the live carry on actor_state belongs to the training envs and has the wrong batch size here). Non-recurrent mode passes hidden through untouched.

make_act

make_act(
    actor_state,
    recurrent,
    continuous,
    expert_policy=None,
    agent_state=None,
    controller=None,
    command=None,
)

A pure function acting once, as the evaluation acts: act(obs, done, expert_obs, expert_state, actor_hidden, command_value, rng) -> Acted.

It acts as the agent's controller says, on an ActingState: the actor's input (Controller.observe), its deterministic action, then the executed one (Controller.act). The expert acts in agent units on expert_obs, the environment's own observation. A command-conditioned actor reads command.actor_input(obs, command_value). The controller's choosers (an extension's eval_action phase) may then replace the executed action by the expert's (choose_in_evaluation), on keys derived from rng, so they move no other draw. A tracker then has the expert's memory follow the executed action.

evaluation_policy

evaluation_policy(
    env_args,
    agent_state,
    expert_policy=None,
    controller=None,
    recurrent=False,
    command=None,
    norm_info=None,
)

The policy evaluate runs (make_act), acting on the environment's own observations: it appends the run's features to them, as collection does, and maps the executed action onto the environment's bounds. The expert's state, the features' and the command restart with each episode; the command counts down each reward, in the agent's units (norm_info, normalised_reward).

row_collector_policy

row_collector_policy(
    env_args, agent_state, policy_fn, init_carry_fn
)

The policy evaluate_policy runs, the world models' row collector's: policy_fn(carry, obs, is_first, key) -> (action, carry, extras) on the observation with the run's features, from init_carry_fn(n_envs), is_first where an episode starts; its action mapped onto the environment's bounds.

The policy, collection and evaluation act through one controller: the features, the normaliser, the expert, the carry and the action transforms. An extension author meets it in Writing an extension.

ajax.controller

What a policy acts on, the same in collection and evaluation.

The controller is everything a policy does when it acts, the part that would ship with it: its features, normaliser, expert, carry, choice of action and action transforms. A step acts on an :class:ActingState. Collection builds it from the collector and the actor (:func:acting_state), and evaluation from its own rollout, so the action pipelines read one state whichever runs them.

ActingState

Bases: NamedTuple

What one step acts on, per env: the observation the actor reads (before any normalisation), where the last step ended an episode (the carry and the expert restart there), the global timestep, the tracked expert's state (None: no stateful expert), the actor's carry (None: a feedforward actor), each env's step in its episode (None unless an extension reads it) and the observation normaliser's statistics (None: none). Evaluation acts on neither a timestep nor a step in an episode: None there.

TransformInputs

Bases: NamedTuple

What an action transform reads, per env: the agent's tracked expert (agent units), the state its call this step starts from, the env's own observation and the expert's action there. The learner, scoring stored rows, passes the stored action alone.

ObserveInputs

Bases: NamedTuple

What an observation feature reads, per env: the env's own observation the features are for (raw_obs, before any normalisation), the agent's tracked expert (in agent units; None without one) and the state its call there starts from, the collector's timestep (None in evaluation, which passes its frozen progress), the run's horizon (None where the collector keeps none), in evaluation the training progress it holds, whether the features' gradient flows back to what they read (APG's differentiable rollout; elsewhere they are held constant), the action executed just before the observation (:func:previous_action_input) and the reward the environment paid for it (:func:previous_reward_input), each None unless a feature reads it.

ObservationLayout dataclass

ObservationLayout(env_width, columns=())

The columns of an observation with features: the env's own (env_width), then each feature's in columns order, (name, width, normalised): the normalised ones first, then the raw ones, so the normaliser's statistics cover the leading normalised_width.

slice

slice(name)

The columns of the feature name.

WarmupInputs

Bases: NamedTuple

What a warm-up chooser reads in one step: the expert's action in the space the warm-up draws (find_expert_action_in_choice_space; None in a run without an expert), and the key the step's uniform actions were drawn on.

ScoredActions

Bases: NamedTuple

The maps from the policy's actions at a batch's rows to those the critics score there: at each row's s (map_actions) and at its s' (map_next_actions). Under a residual policy they are the executed actions, from the expert's actions the rows stored at s and s'; without one, the policy's own (leave_unchanged).

Controller dataclass

Controller(
    normalize_obs=False,
    raw_columns=0,
    observers=(),
    transforms=(),
    choosers=(),
    tracker=None,
)

How an agent acts beyond its actor's forward pass, which evaluation runs (collection still runs the agent's pipeline): its observation features (observers, :attr:EnvironmentConfig.observers), the observation normalised (normalize_obs: an agent storing its observations normalised, which collection stores so already; the leading raw_columns stay raw), and the executed action made from the actor's by transforms (:attr:EnvironmentConfig.transforms): residual RL's transform_action, or gain mode's actuate, where the actor's action sets the expert's gains and the expert acts. The default executes the actor's action on its observation. The expert is the caller's, in agent units. Hashable: a static argument.

actuates property

actuates

Whether the critics score the actor's action, not the executed one: one actuated through the expert (gain mode), or a residual they read themselves.

observe

observe(acting)

The actor's input: acting's observation, its features included, normalised with its statistics where the agent stores its observations so.

act

act(actions, acting, expert, expert_obs)

The executed action from the actor's actions, and the expert's state after the step: the transforms' (the expert called for them, its action 0 without one; gain mode's actuation steps the expert itself), else the actor's own. The expert is called every step its state is read, as collection calls it: for a transform, the features or a chooser; otherwise its state is left as it is.

acting_state

acting_state(agent_state)

A collecting agent's acting state, its collector's and its actor's.

observers_of

observers_of(stack)

The extensions of stack that append observation features, in column order: those the normaliser covers first, then the raw ones, each in stack order.

observation_layout

observation_layout(env_width, observers, env_args)

The layout of an env's env_width columns followed by observers' (:func:observers_of).

init_observers

init_observers(observers, n_envs)

Each observer's per-env state at an episode start.

restart_observers

restart_observers(
    started, observers, states, expert, expert_state, n_envs
)

The observers' states and a stateful expert's, fresh in the envs where an episode starts (started) and continuing in the others.

feature_columns

feature_columns(inputs, observers, states)

observers' columns at the observation inputs describes, in column order, and their states after it.

observe_features

observe_features(raw_obs, inputs, observers, states)

raw_obs with observers' columns appended, and their states after this observation; without observers, raw_obs itself.

memory_tracker_of

memory_tracker_of(stack)

The extension of stack with the expert's memory following what was applied (BumplessTracking), or None.

transforms_of

transforms_of(stack)

The extensions of stack that transform the action (residual RL's transform_action, gain mode's actuate).

warmups_of

warmups_of(extensions)

The extensions choosing what the warm-up acts with (ExpertWarmup).

replay_action_choosers_of

replay_action_choosers_of(extensions)

The extensions choosing the action a replay row stores (StorePolicyAction).

choose_warmup_actions

choose_warmup_actions(warmups, uniform_actions, inputs)

The warm-up's actions and whether the expert took them (one boolean for the step): the run's chooser's (an agent takes one), else the uniform ones.

find_expert_action_in_choice_space

find_expert_action_in_choice_space(
    transform, after_choice, expert_action, policy_actions
)

The expert's action in the space the step's action is chosen in, which the warm-up draws and the replay stores: the executed one, unless the transform acts after the choice (gain mode, or a residual applied after it), where it is the policy action that executes the expert's own (policy_action_for_expert).

warmup_expert_flags

warmup_expert_flags(expert_took, policy_actions)

A warm-up step's is_expert column: 1 in every env where the expert took it.

executed_actions

executed_actions(env_args, actions, a_expert)

The actions the critics score: the policy's actions through the run's transform_action (residual RL), from the expert's actions a_expert at the same rows; the policy's own without one. Gain mode stores the policy's actions, so its critics score them as they are.

read_the_residual

read_the_residual(transforms)

Whether a residual policy among transforms has the critics read the residual itself, which the replay then stores as the action (ResidualPolicy.critic_reads_residual).

executed_fn

executed_fn(env_args)

(actions, a_expert) -> actions the critics score, where the run has a residual policy they score through (:func:executed_actions); None otherwise, so the learner traces nothing extra.

leave_unchanged

leave_unchanged(actions)

actions as they are: the actions the critics score without a residual policy (a Python identity, which adds nothing to the traced program).

make_scored_actions

make_scored_actions(executed, batch)

The ScoredActions of batch's rows (a Transition), from executed, executed_fn's map (None without a residual policy).

policy_action_dim

policy_action_dim(env_args)

The dimension of the actions the policy chooses: gain mode's, the expert's learnable gains (env_args.policy_action_dim), else the env's.

critic_action_units

critic_action_units(env_args)

The critic's map of its action input to the env's units (:func:ajax.environments.utils.critic_action_units); none under gain mode, whose critics read the gains.

reads_progress

reads_progress(env_args)

Whether a feature of env_args.observers reads the training progress, whose horizon the collector then keeps (max_timesteps).

reads_previous_action

reads_previous_action(observers)

Whether a feature among observers reads the action executed before each observation (ObserveInputs.previous_action).

previous_action_input

previous_action_input(
    observers, action, n_envs, env, env_params
)

ObserveInputs.previous_action: action, the action the envs executed, in agent units, as an observation's columns: a continuous action clipped to [-1, 1], as the environment and the replay take it, a discrete action one-hot over the env's action count. Zeros where no action was executed yet (action None: a reset). None, and nothing computed, unless a feature among observers reads it.

reads_previous_reward

reads_previous_reward(observers)

Whether a feature among observers reads the reward paid for the action executed before each observation (ObserveInputs.previous_reward).

previous_reward_input

previous_reward_input(observers, reward, n_envs)

ObserveInputs.previous_reward: reward, what the environment paid for the action executed before the observation, as one column, raw as the environment pays it. Zeros where no action was executed yet (reward None: a reset). None, and nothing computed, unless a feature among observers reads it.

reads_agent_expert

reads_agent_expert(env_args)

Whether a feature of env_args.observers reads the agent's expert.

feature_width

feature_width(env_args, normalised=None)

The columns env_args.observers append (those the normaliser covers with normalised True, the raw ones with False).

flatten_expert_state

flatten_expert_state(expert_state)

A stateful expert's state as one (n_envs, D) array (:func:~ajax.networks.memory.flatten_carry): the Markov component an observation augmented with it carries (a PID's integrator). None for a stateless expert (no state, or an empty one).

call_expert

call_expert(expert, state, obs)

(action, state): a stateful expert (one with init_state) called as expert(state, obs), a stateless one as expert(obs), its state kept.

make_run_controller

make_run_controller(
    env_args, controller=None, extensions=()
)

How a run acts in evaluation: controller (None: the actor's action on its observation) with the run's features, transforms, the choosers among its extensions and, where it stores them so, observations normalised by its running statistics.

PPO's update cuts its rollout into minibatches in one of three ways (a rollout split), which also says where the advantages are computed: "flat", ppo2's shuffled single steps, GAE once on the rollout; "time", brax's shuffled fragments of unroll_length steps, GAE in each minibatch from the current critic; "recurrent", sequences of bptt_length steps, GAE once.

ajax.agents.minibatch.RolloutSplit dataclass

RolloutSplit(kind, num_minibatches, length)

How one rollout is cut into minibatches, chosen once per update from the hyperparameters: how many minibatches each epoch has (num_minibatches), how many steps each piece holds (length) and whether the pieces keep time order (kind, the module docstring).

advantages_per_minibatch property

advantages_per_minibatch

Whether GAE is computed again in each minibatch, from the current critic (brax's fragments), rather than once on the rollout.

cut_into_minibatches

cut_into_minibatches(batch, key, memories=None)

One epoch's partition of the rollout batch on key; a recurrent split's sequences take along what they replay their networks from (memories, from recurrent.compute_rollout_values).

ajax.agents.minibatch.choose_rollout_split

choose_rollout_split(
    agent_config, n_steps, n_envs, recurrent
)

The rollout's RolloutSplit.

time only when unroll_length asks for it (n_steps gives whole rollouts per env): with as many minibatches as envs, each minibatch is then one env's trajectory, its advantages normalised within it. It needs fragments that split evenly into more than one minibatch: recomputing GAE on a single minibatch, the whole rollout, with a critic that just stepped only makes the value targets oscillate (the flake of the one-env probing fixture). A recurrent rollout is a pool of sequences of bptt_length steps (by default default_bptt_length) that must split exactly into the minibatches, as Baselines' and CleanRL's recurrent PPO assert: a bptt_length that does not divide the default raises ValueError.