Skip to content

Extensions

An extension adds a research feature to any agent whose loop folds the phases it uses. The user guide shows how to use them and Writing an extension how to add one.

ajax.extensions.base

The Extension framework — composable research features for any agent.

An :class:Extension is a research feature (expert guidance, observation augmentation, online behavioural cloning, target modifiers, exploration schemes, instrumentation, …) that attaches to any agent without bloating the agent's own file. It implements only the lifecycle phases it touches; an agent's training loop folds every extension through each phase, in list order.

Design contract

  • Static. Extensions are plain Python objects passed as static arguments to the jitted training step, so the fold unrolls at trace time (a Python for over a fixed tuple — no dynamic dispatch). Every extension must therefore be hashable: the default id-based hash is fine for a one-off instance; a @dataclass(frozen=True) is preferred for instances carrying config, so the JIT cache is reused across equivalent runs.
  • State lives in the pytree. An extension never stores mutable state on self — only frozen config. Anything that changes during training is a pytree returned by :meth:Extension.init_state and carried in BaseAgentState.ext_state (one entry per extension; the default () means stateless, zero overhead).
  • No-op by default. Every phase method has a default that is the identity / 0.0 / {} / unchanged-state, so an extension is exactly as invasive as the phases it overrides, and an empty :class:ExtensionStack is genuinely zero-cost.
  • Keys by name. In every phase an extension draws on a key of its own, derived from its name and occurrence (extension_key_names), so adding, removing or moving another extension changes none of its keys. Where its pretrain or post_update runs the agent's own steps, the stack lends it a key off the agent's and takes the agent's back after.

Phases

init_state build the extension's pytree state (once, on fresh init) pretrain one-shot, before the training loop (MC/BC pre-training) on_target transform the TD / value target critic_loss extra additive critic-loss term (summed over extensions) actor_loss extra additive actor-loss term (summed over extensions) action override the collection-time action (None = defer; the last non-None proposal in the stack wins) eval_action override the evaluation-time action (same rule) transform_action make the executed action a function of the policy's and the expert's (residual RL), in collection, the losses and evaluation; the replay stores the executed one actuate execute the chosen action through the expert (gain mode: it sets the expert's gains); the replay stores the chosen post_update hook after the update step (φ-refresh, schedules, …) eval_metrics extra metrics, merged into the eval log observe columns appended to every observation (an expert's action, the training progress), stored with it choose_warmup_action the actions of a warm-up step (ExpertWarmup's expert mix), uniform by default choose_replay_action the action a replay row stores (StorePolicyAction: the policy's), the executed one by default track_memory the agent's expert's memory after a step that executed another's action (BumplessTracking); its own step by default

on_target, critic_loss and actor_loss may return (value, metrics) instead of their value: metrics, a dict of scalars named <extension>/<metric>, is logged with the update's own metrics (the last update's, or the mean over the update's epochs and minibatches, as the agent logs its own). Two extensions logging one name raise. on_target may also return (target, metrics, ext_state): the extension's state after the update's target, which it learns from (ValueCentering's offset, ResetCost's reset critic); the others keep theirs.

Phase batches

The batch dict of a phase holds the keys :data:COMMON_BATCH_KEYS lists, on every agent that folds it, and those the agent declares in its phase_batch_keys (on the shared steps: their sets in ajax.agents.loop, TARGET_KEYS and the others). An extension raises on a key it needs and does not find, rather than return a no-op. gamma is None for an average-reward agent, dones is where the target cut the bootstrap and targets the target, held constant; the critic (DQN's and PQN's q_state) and the actor come at the differentiated parameters. The replay agents' raw_observations is None in a run without an expert, whose replay does not keep them. a_expert is the agent's expert_policy's action at each row, stored at collection from the expert's state along the trajectory; None without one.

ExtensionContext

Shared context handed to every extension phase.

step and rng are traced; total_steps is static so it can drive Python-level decisions (e.g. schedule lengths) at trace time. The pretrain phase of a run on ajax.agents.loop.TrainLoop also gets its static env_args and, off-policy, its update(agent_state, experience) -> (agent_state, aux) and replay buffer, so an extension can run the agent's own update; each is None where the run has none. seed_index (traced) is the seed's place among those trained together, for what names a file per seed.

Extension

Base class for a composable research feature.

Subclass and override only the phases the feature touches. Keep subclasses hashable (@dataclass(frozen=True) is the recommended form) and stateless on self — see the module docstring.

observation_width

observation_width(env_args)

The columns :meth:observe appends to every observation.

init_observer

init_observer(n_envs)

Its per-env state at an episode start ((): none).

observe

observe(inputs, state)

The (n_envs, observation_width) columns it appends to the observation inputs describes (:class:ajax.controller.ObserveInputs) and its state after that observation. It runs whenever an observation arrives, in collection and evaluation alike, and its columns are stored with the observation (ajax.controller). The default appends none.

init_state

init_state(agent_state, rng)

Return this extension's initial pytree state.

Called once, on fresh initialisation only (skipped on resume). The default () marks a stateless extension — no pytree overhead in BaseAgentState.ext_state.

pretrain

pretrain(agent_state, ext_state, context)

One-shot step before the training loop (e.g. MC/BC pre-train).

Returns the (possibly updated) (agent_state, ext_state).

replay_rows

replay_rows(n_envs)

The rows its pretrain writes into a replay of n_envs envs (ExpertPrefill, PriorData); none by default.

pretrain_updates

pretrain_updates()

The agent updates its pretrain runs before any env step (ExpertPrefill's and PriorData's offline_updates); none by default.

on_target

on_target(agent_state, ext_state, batch, target, context)

Transform the TD / value target; or return (target, metrics), or (target, metrics, ext_state) to update its own state (the module docstring).

critic_loss

critic_loss(agent_state, ext_state, batch, context)

Extra additive critic-loss term (summed across extensions); or (term, metrics).

actor_loss

actor_loss(agent_state, ext_state, batch, context)

Extra additive actor-loss term (summed across extensions); or (term, metrics).

action

action(agent_state, ext_state, obs, rng, context)

Override the collection-time action; None defers.

eval_action

eval_action(agent_state, ext_state, obs, rng, context)

Override the evaluation-time action; None defers. obs is the shared evaluation's dict (ajax.evaluate.step_environment): executed_action, expert_action (the agent's expert's, None without one), observations (the critics' input) and raw_obs; expert_mask, written into it, marks where the expert's action was taken. rng is the extension's own key.

transform_action

transform_action(actions, inputs)

The executed action from the policy's actions and the expert's (:class:ajax.controller.TransformInputs), before the action is chosen: the warm-up and the acting modes act on executed actions, and the critics score them; the policy's by default.

actuate

actuate(actions, inputs)

The env's action from the chosen actions (warm-up draws included), executed through the expert of inputs (:class:ajax.controller.TransformInputs), and the expert's state after it. The replay stores the chosen actions; the default executes them as they are.

policy_action_dim

policy_action_dim(env_args, expert)

The dimension of the actions the policy chooses, where it is not the env's (gain mode: the expert's learnable gains); None: the env's.

choose_warmup_action

choose_warmup_action(uniform_actions, inputs)

The actions a warm-up step takes instead of uniform_actions, and whether the expert took them, one boolean for the step (ajax.controller.WarmupInputs); by default the uniform ones.

choose_replay_action

choose_replay_action(executed_actions, policy_actions)

The actions a replay row stores for a step: by default the ones executed (residual, warm-up or expert actions included), which generated the step's reward and next observation.

track_memory

track_memory(expert, memory, obs, command, applied)

The agent's expert's memory after a step from memory at obs, once the env has stepped: command is the action sent, applied the action the actuator made of it, both in agent units. The expert's own step by default.

policy_action_for_expert

policy_action_for_expert(policy_actions)

For an action transform: the policy action, shaped like policy_actions, at which it executes its expert's own action. The rows the expert acts in (its prefill) store it as the policy's.

reward

reward(agent_state, ext_state, batch, rewards, context)

Replace a rollout's rewards before the agent's targets read them. Returns (rewards, ext_state, metrics).

post_update

post_update(agent_state, ext_state, context)

Hook after the update step. Returns (agent_state, ext_state).

eval_metrics

eval_metrics(agent_state, ext_state, rng, context)

Extra metrics, merged into the eval log.

experts

experts()

The experts this extension calls itself, on the observations it is given (without a state); none by default.

uses_expert_actions_as_policy_actions

uses_expert_actions_as_policy_actions()

Whether it puts an expert's actions where the policy's actions go: as the actor's target, or as an action its critics score. Gain mode refuses it, since there the expert's actions are env actions and the policy's are gains. None does by default.

needs

needs()

The capabilities it needs: those its phases imply and those it requires.

reads

reads()

Per phase, the batch keys it reads (batch_keys).

implemented_phases

implemented_phases()

The phases this extension actually overrides (vs the no-op base).

check_stack

check_stack(stack)

Raise when the stack it runs in cannot hold it (another extension's place or the keys it reads; ValueCentering, ResetCost), checked as the stack binds to its agent. Any stack by default.

bind_to_agent

bind_to_agent(**agent_context)

Return self, optionally populating closed-over agent context.

The default is the identity: an extension ignores every kwarg it does not need. One that closes over values the agent factory resolves (env_args, buffer, …; e.g. :class:MCPretrain, :class:PhiRefresh) overrides this to return a new frozen instance with them filled in, so a whole stack binds without per-extension type checks (:meth:ExtensionStack.bind_to_agent).

ExtensionStack

ExtensionStack(extensions=())

A folded, immutable collection of extensions.

Holds the static tuple of :class:Extension objects and folds them through each phase in list order. An empty stack is a true no-op. Hashable (so it can be a JIT static argument) iff its extensions are.

sets_temperature property

sets_temperature

Whether an extension of the stack sets the temperature (Extension.sets_temperature).

continues_through_terminations property

continues_through_terminations

Whether an extension of the stack has the target go on through a termination (Extension.continues_through_terminations).

implemented_phases

implemented_phases()

The phases at least one extension of the stack implements.

buffer_fields

buffer_fields()

The replay-buffer fields the stack's extensions declare they read.

apply_init

apply_init(agent_state, rng, total_steps, **run_fields)

A fresh run's extension setup: every extension's initial state, then its one-shot pretrain at step 0 (rng split between the two; run_fields: :meth:apply_pretrain's). Skipped on resume, where the state already carries both.

apply_init_states

apply_init_states(agent_state, rng)

agent_state with every extension's initial state (one key each) in its ext_state.

apply_pretrain

apply_pretrain(
    agent_state, step, rng, total_steps, **run_fields
)

The one-shot pretrain; returns the updated agent_state. run_fields: the run's :class:ExtensionContext fields (env_args, update, buffer, seed_index).

apply_post_update

apply_post_update(agent_state, step, rng, total_steps)

Every extension's post_update; returns the updated agent_state.

apply_reward

apply_reward(
    agent_state, batch, rewards, step, rng, total_steps
)

Every extension's reward, in list order, each seeing the previous rewards; returns the state (the extensions' states updated), the rewards and the metrics.

apply_on_target

apply_on_target(
    agent_state, batch, target, step, rng, total_steps
)

Every extension's on_target; returns the (possibly reshaped) target, the extensions' metrics and their states, those that returned one updated.

compute_extensions_critic_loss

compute_extensions_critic_loss(
    agent_state, batch, step, rng, total_steps
)

Every extension's critic_loss; returns the summed additive critic-loss term and the extensions' metrics.

compute_extensions_actor_loss

compute_extensions_actor_loss(
    agent_state, batch, step, rng, total_steps
)

Every extension's actor_loss; returns the summed additive actor-loss term and the extensions' metrics.

apply_eval_metrics

apply_eval_metrics(agent_state, step, rng, total_steps)

The extensions' evaluation metrics, merged (each extension gets its own key, which its context carries too).

bind_to_agent

bind_to_agent(**agent_context)

Return a new stack with every extension bound to agent_context (each :meth:Extension.bind_to_agent picks the kwargs it needs); each agent factory passes the context it owns. An empty stack returns self.

with_experts

with_experts(convert)

The stack with convert applied to every expert its extensions hold (their expert_fields; one still None is left). A convert memoised by identity keeps one expert one object, which :func:ajax.extensions.expert.reads_stored_expert_actions compares.

check_extensions

check_extensions(
    agent_name,
    stack,
    capabilities,
    phases,
    *,
    context=(),
    pretrain_context=(),
    buffer_fields=(),
    batch_keys={},
    agent_expert=None,
    takes_expert_policy=False,
    stores_expert_actions=False,
)

Reject the extensions of stack that cannot run on agent_name, whose run has capabilities and whose code folds phases, binds the context keys, fills the pretrain_context fields, stores the buffer_fields and passes, per phase, the batch_keys beyond the common ones (:func:~ajax.extensions.capabilities.check_capabilities), or that call a stateful expert without its state (:func:check_extension_experts).

Raises a ValueError naming every offending extension: one whose phase an agent never folds would otherwise be silently ignored. Agents call it at construction (ActorCritic.__init__).

holds_expert

holds_expert(agent_expert, stack)

Whether a run has an expert: the agent's expert_policy, or one an extension holds (its expert_fields). Replay keeps the raw observations and the expert flags, which only experts read, for such a run (init_buffer's include_raw_obs, include_is_expert).

check_extension_experts

check_extension_experts(
    agent_name,
    stack,
    agent_expert=None,
    stores_expert_actions=False,
)

Reject an extension calling a stateful expert (one with init_state, called expert(state, obs)) without its state.

An extension calls the experts it declares (:meth:Extension.experts) on the observations it is given, where no state of the expert exists: a stateful one is allowed only as the agent's expert_policy of an agent that stores that expert's actions from its state (stores_expert_actions), for an extension that reads them (reads_agent_expert_actions). Stateless experts are always allowed.

phase_output

phase_output(out)

A training phase's value and metrics: it returns its value, or (value, metrics) (the module docstring).

merge_metrics

merge_metrics(*metrics)

The extensions' training metrics in one dict; a name two of them log raises (two extensions of one class report the same names).

extension_key_names

extension_key_names(extensions)

Each extension's key name, "name#occurrence": its name (its class's qualified name where it keeps the base's) and how many extensions of that name come before it in the stack, so two of one class get keys of their own.

ajax.extensions.expert

Expert-guidance research features as composable :class:Extensions.

  • :class:OnlineBC — value-weighted decaying BC loss term.
  • :class:ImitationLoss — plain BC loss term towards the expert.
  • :class:ResidualPolicy — execute clip(a_expert + scale·a_pi).
  • :class:ExpertGains — the action sets the expert's gains (gain mode).
  • ExpertWarmup — the expert acts on a share of the warm-up steps.
  • :class:JSRLCurriculum — jump-start RL: the expert rolls in, the learner takes over.
  • :class:ExpertValueMetrics — the critic at the expert's actions, logged.

Each extension carries only frozen config on self; the maths are the functions below. The expert is SAC's expert_policy: OnlineBC, ResidualPolicy and JSRLCurriculum read the expert action SAC computes. ImitationLoss holds its own expert, and reads the actions the agent stored when that expert is the agent's.

OnlineBC dataclass

OnlineBC(
    bc_coef=1.0, critic_warmup_frac=0.15, name="online_bc"
)

Bases: Extension

Online, value-weighted, warmup-decaying behavioural-cloning term.

A bc_coef · w(s) · ||μ_θ(s) - a_expert||² penalty (:func:compute_online_bc_loss) that decays to zero once the training fraction exceeds critic_warmup_frac. It reads the actor's mean action (pi_mean), the expert's action (a_expert, which SAC puts in its actor-loss batch) and the observations from the batch, and the frozen expert critic phi with its value range (expert_critic_params, expert_v_min, expert_v_max) and the critic phi is applied with from the agent's state, which :class:MCPretrain fits (refused without it). The expert's action is the agent's expert_policy's, so an agent without one refuses it (requires agent_expert); it raises on a batch without a_expert (an agent other than SAC). Until phi* exists the term is 0.

ImitationLoss dataclass

ImitationLoss(
    expert_policy,
    coef=1.0,
    q_filter=False,
    anneal_frac=None,
    target="expert",
    alpha=None,
    reads_stored_expert=False,
    buffer=None,
    action_scale=None,
    name="imitation_loss",
)

Bases: Extension

Behavioural-cloning regulariser: coef · mean((μ(s) - a_E(s))²) / 4.

Same form as the actor-side BC term of TD3+BC (Fujimoto & Gu, 2021), with a frozen expert's action as the target: μ(s) is the actor's mean action (pi.mean(), which is TD3's deterministic action), a_E(s) the expert's action, held constant: its call on the raw observation, or, when it is the agent's expert_policy, the action collection stored from its tracked state (which a stateful expert, a PID with its integral, needs). The mean runs over batch and action dims; / 4 maps the squared distance of two actions in [-1, 1] to [0, 1]. Unlike :class:OnlineBC the term is unweighted and needs no pre-trained expert critic.

q_filter=True counts only the rows where the critic rates the expert's action above the policy's (:func:q_filter_weight, at μ(s)) and still divides by every row, as the paper's fixed λ2 = 1/N_D does: the Q-filtered BC of Nair, McGrew, Andrychowicz, Zaremba and Abbeel (ICRA 2018, Sec. IV-C, eq. 8). Deviations: replay rows labelled with the expert's action, not a demonstration buffer (the replay's expert flags would restore it); coef on the BC term, not the paper's λ1 = 1e-3 on the RL term and λ2; the policy's mean action and the minimum over the agent's critics (TD3's actor reads its first, REDQ's the mean of its ensemble), not DDPG's one critic. The filter needs a Q critic, which the off-policy actor-critics (SAC, TD3, REDQ, CrossQ, TQC, ASAC, RVI-SAC, AVG and IQL) put in their actor-loss batch (critic_state); a state-value critic (PPO, APO) cannot rate an action. It refuses :class:ResidualPolicy, whose critic reads the executed action. imitation/q_filter_frac logs, at each evaluation, the share of a replay batch the filter keeps (every agent but AVG, which keeps no replay).

With anneal_frac the term is multiplied by a weight falling linearly from 1 to 0 at that fraction of training (:func:anneal_weight), as in kickstarting (Schmitt et al., 2018, Kickstarting Deep Reinforcement Learning, arXiv:1803.03835, eqs. 2-3), whose distillation weight on the teacher decays so the student ends on its own RL loss. Deviations from kickstarting: a squared error on the mean action instead of the cross-entropy between the teacher's and the student's policies (the expert is deterministic: it gives an action, not a distribution); a linear schedule set by anneal_frac instead of the weights population-based training tunes. None keeps the weight at 1.

target="replay" clones the replayed rows' own actions (actions, which the replay actor-critics, SAC, TD3, REDQ, CrossQ, TQC, ASAC, RVI-SAC and IQL, put in their actor-loss batch) instead of an expert's: logged data needs no expert, and expert_policy may be None. alpha makes the actor loss TD3+BC's (Fujimoto and Gu, 2021), λ · (the agent's own) + coef · mean((μ(s) - a)²) with λ = alpha / mean|Q_1(s, μ(s))| (:func:td3bc_lambda), the actions compared in the env's units and without the / 4: the term adds (λ - 1) times the agent's own loss (agent_loss in its actor batch), already counted. On TD3, whose own loss is -mean Q_1, that is the paper's -λ mean Q + mean((π(s) - a)²); anneal_frac and the filter act on the cloning part only. With both, on TD3, a transition dataset trained offline (train_offline) and normalize_observations=True (the dataset's statistics, sqrt(var + 1e-8) in place of the reference's std + 1e-3), it is TD3+BC.

The agents it runs on, with continuous actions (the off-policy actor-critics, APO, DAgger, PPO, APG and UDRL), put pi_mean and raw_observations in their actor-loss batch, and those storing their expert's actions (stores_expert_actions) the stored a_expert, which the term reads when its expert is the agent's. An agent whose batch has no pi_mean (a discrete-action policy) raises at trace time.

needs

needs()

The filter and alpha also read the Q critic; the replayed target needs a replay.

reads

reads()

The filter and alpha also read the critic from the actor-loss batch, the replayed target its rows' actions.

bind_to_agent

bind_to_agent(**agent_context)

Read the expert's stored actions when it is the agent's; with alpha, the env's action half-ranges (TD3+BC compares env actions); with the filter, bind the agent's replay buffer (its logged share samples it) and SAC's observation augmentation.

eval_metrics

eval_metrics(agent_state, ext_state, rng, context)

imitation/q_filter_frac, the share of a replay batch the Q-filter keeps (an agent with a replay, which it binds).

ResidualPolicy dataclass

ResidualPolicy(
    scale=1.0,
    zero_start=False,
    critic_reads_residual=False,
    name="residual_policy",
)

Bases: Extension

Residual RL (Johannink et al. 2019; Silver et al. 2018).

The executed action is clip(a_expert + scale·a_pi, -1, 1), from the agent's tracked expert, at every step: the warm-up draws uniform residuals, not uniform executed actions. The replay stores the executed action, the critics score it (the TD-target bootstrap at next_a_expert and the actor's policy gradient flow through the same transform, :func:ajax.controller.executed_actions), and evaluation acts through it. Its presence alone turns residual RL on, with the agent's expert policy.

zero_start puts the actor's output head at 0, so that the policy starts as the expert: its mean residual is 0 at every observation. It is Silver et al.'s (Sec. IV-A), not Johannink et al.'s.

critic_reads_residual is both papers' critic: the replay stores the residual and the critics read it (Johannink et al.'s Algorithm 1 stores u_t; Silver et al.'s residual MDP holds the expert in its transitions). The default, the critics scoring the executed action, is neither's. It needs a Q critic, and refuses what puts an expert's action where a residual goes (uses_expert_actions_as_policy_actions, rows seeded in the replay).

implemented_phases

implemented_phases()

Its pretraining only with a zero start.

transform_action

transform_action(actions, inputs)

clip(a_expert + scale·a_pi, -1, 1) — the residual mix.

ExpertGains dataclass

ExpertGains(max_factor=10.0, name='expert_gains')

Bases: Extension

Gain mode: the policy's action sets the agent's expert's learnable gains, anchor_gains · max_factor**a per gain, and the expert acts with them (its step_with_gains, which advances its state). The replay and the critics hold the policy's action, the gains: the agent acts in a space as wide as the expert's learnable gains, and the warm-up draws uniform gains. The expert needs learnable_fields and anchor_gains (register_learnable_gains, or a GainScheduledLaw, whose gains are multipliers).

ExpertWarmup dataclass

ExpertWarmup(fraction, name='expert_warmup')

Bases: Extension

During the warm-up, the agent's expert acts on a share fraction of the steps and uniform random actions on the others (SAC's former expert_fraction). One draw decides each step for every env, as SAC drew it. It acts in the controller only: no state and no key in the learner. The replay flags the steps the expert took, where it keeps is_expert.

StorePolicyAction dataclass

StorePolicyAction(name='store_policy_action')

Bases: Extension

An off-policy correctness ablation (SAC's former store_policy_action): the replay stores the action the policy chose, not the one executed, so the rows an expert, a warm-up or a residual acted in no longer hold the action that produced their reward and next observation. It acts in the controller only: no state and no key in the learner. An agent learning from an expert's labels alone (DAgger) learns from no stored action: there is nothing to ablate (reward_learning).

JSRLState

JSRLCurriculum's state: the run's root of JSRL-Random's per-episode draws, the curriculum's stage, the best moving average of its evaluations, the latest evaluations, newest first, and how many it has run.

JSRLCurriculum dataclass

JSRLCurriculum(
    episode_length=None,
    decay_frac=None,
    schedule="performance",
    n_stages=10,
    tolerance=0.05,
    threshold=None,
    moving_average=5,
    eval_every=10000,
    eval_episodes=1,
    env_args=None,
    expert_policy=None,
    name="jsrl_curriculum",
)

Bases: Extension

Jump-start RL (Uchendu et al. 2023, arXiv 2204.02372).

The agent's expert (the guide) acts each episode's first h steps, the learner the others, and the guide's share falls as the learner takes over. h runs through H, H - H / n_stages, ..., 0. schedule chooses it:

  • "performance", the paper's JSRL-Curriculum (its Algorithm 1): h moves on when an evaluation of the combined policy passes (:func:next_stage, :func:combined_policy_return). Its defaults are the paper's for D4RL: an evaluation every 10,000 steps, a moving average of 5 (A.4), n_stages 10 and tolerance 5% (Table 11). Evaluations run on envs of their own, eval_episodes episodes each, and they are steps on the plant: ajax.ledger charges them to the run's budget. So eval_episodes defaults to 1, Ajax's own value and not the paper's, which leaves the moving average to steady the gate: at the defaults a run of 1M steps spends 2% of them on evaluations on 200-step episodes and 14% on 1,600-step ones. The paper leaves open whether the average restarts at a new stage; here it runs on.
  • "random", the paper's JSRL-Random: h drawn uniformly from that sequence at each episode's start, without a curriculum.
  • "time", Ajax's own and not the paper's: h falls linearly from H to 0 at decay_frac (default 0.5) of training, whatever the performance.

episode_length is H, in agent steps: None reads the task's, the paper's H_1 on a task whose episodes all run to the horizon.

The action phase owns the per-episode substitution, in the action stage's pre-warm-up slot (ajax.environments.action_stage). It reads post_warmup_action and expert_action off the stage's dict and each env's step_in_episode off agent_state.collector_state, which collect_experience counts for an extension that reads it. It writes expert_mask back, which flags the steps the expert took.

Evaluations log the guide horizon (jsrl/horizon) and the share of envs the expert drove on the last collection step (jsrl/expert_frac), and with "performance" the stage (jsrl/stage) and the best moving average (jsrl/best).

evaluates property

evaluates

Whether the schedule evaluates on the plant during the run.

task_horizon property

task_horizon

H, which bind_to_agent reads off the task.

evaluation_due

evaluation_due(step, n_envs)

Whether an update at step evaluates: the first of each eval_every steps, steps moving n_envs at a time.

evaluation_steps

evaluation_steps(env_args)

The env steps of one evaluation (combined_policy_return): each episode runs to the task's length, in the steps n_timesteps counts, whether or not it ends early.

bind_to_agent

bind_to_agent(**agent_context)

Read H off the task and keep the expert and the env that "performance" evaluates. Raises ValueError on an agent that does not give them.

action

action(agent_state, ext_state, obs, rng, context)

Substitute the expert action while step_in_episode < h.

guide_steps

guide_steps(agent_state, ext_state, total_steps)

h: one value, or JSRL-Random's one per env.

stage_horizon

stage_horizon(stage)

H at stage 0, falling by H / n_stages a stage to 0 at n_stages.

episode_horizons

episode_horizons(collector, key)

JSRL-Random's h of each env's episode, a stage's drawn uniformly, on a key of its env and its episode's first tick, which holds through the episode: nothing to store at the episode's start.

horizon

horizon(timestep, total_steps)

The "time" schedule's h: episode_length at the start, falling linearly to 0 at decay_frac of the run.

post_update

post_update(agent_state, ext_state, context)

Every eval_every steps, evaluate the combined policy and move to the next stage where it passes.

ExpertValueMetrics dataclass

ExpertValueMetrics(
    buffer=None,
    expert_policy=None,
    discrete=False,
    name="expert_value_metrics",
)

Bases: Extension

The critic at the expert's actions, logged at each evaluation, on a replay batch: value/q_expert_mean, the mean of min_k Q_k(s, a_E); value/q_gap, that minus the same at the batch's actions (above 0: the critic rates the expert above what was done); and, once :class:~ajax.extensions.pretrain.MCPretrain has fitted φ*, value/phi_star_q_gap_ood, the mean |min_k Q_φ*(s, a_E) - min_k Q(s, a_E)|.

One replay batch per evaluation pays for them, not a critic pass (two with φ*) per update for three logged numbers. a_E is the expert's action stored at collection. A replay agent with an expert_policy (SAC, TD3, REDQ, CrossQ, TQC, ASAC, RVI-SAC, IQL and DQN) binds its replay buffer, its expert and whether its actions are discrete: a discrete agent's Q-network gives every action's value, read at the stored index (q_network_value), one network, no ensemble to take the minimum of.

residual_action_transform

residual_action_transform(actions, a_expert, scale=1.0)

Residual RL: executed action is clip(a_expert + scale * a_pi, -1, 1).

The critic was trained on (s, executed_action) tuples, so the policy gradient must flow through Q(s, executed_action), not Q(s, a_pi). scale follows Johannink et al. 2019; values < 1 keep the initial behaviour close to the expert when the policy is randomly initialised.

online_bc_weight

online_bc_weight(train_frac, critic_warmup_frac)

The online BC term's schedule: 1 at the start, falling linearly to 0 at critic_warmup_frac of training.

compute_online_bc_loss

compute_online_bc_loss(
    pi_mean,
    a_expert,
    critic_state,
    expert_critic_params,
    observations,
    train_frac,
    critic_warmup_frac,
    expert_v_min,
    expert_v_max,
    bc_coef,
)

Online decaying BC term — value-weighted, warmup-decaying.

Decays to zero after train_frac exceeds critic_warmup_frac. Value-weighting ensures BC is strongest in high-value states.

reads_stored_expert_actions

reads_stored_expert_actions(ext, agent_context)

Whether an extension that carries an expert of its own (IBRL, LCBGatedBootstrap, CriticBlend, PhiRefresh) reads that expert's actions as collection stored them (next_a_expert): when it is the agent's expert_policy, whose state collection tracks along each trajectory. Another expert is called on the raw observations the extension is given, without a state (a stateful one is refused at construction, check_extension_experts).

extension_expert_actions

extension_expert_actions(ext, raw_observations, stored)

The extension's expert's actions at raw_observations (a replayed batch's s', or the step collection acts on): the stored ones (reads_stored_expert_actions), else its call on the raw observations.

anneal_weight

anneal_weight(step, total_steps, anneal_frac)

1 at the start of training, falling linearly to 0 at anneal_frac of total_steps, 0 after.

q_filter_weight

q_filter_weight(
    critic_state, observations, a_expert, a_policy
)

The Q-filter of Nair et al. 2018 (eq. 8), (batch, 1): 1 where the critic's ensemble minimum rates the expert's action above the policy's, min_k Q_k(s, a_E) > min_k Q_k(s, π(s)), else 0; held constant.

td3bc_lambda

td3bc_lambda(critic_state, observations, pi_mean, alpha)

TD3+BC's lambda = alpha / mean|Q_1(s, pi(s))|, held constant, with Q_1 the first critic, the one TD3's actor follows (sfujim/TD3_BC@8791ad7, TD3_BC.py:141-143: lmbda = alpha / Q.abs().mean().detach(), actor loss -lmbda * Q.mean() + mse_loss(pi, action)).

next_stage

next_stage(
    state, value, n_stages, tolerance, threshold=None
)

state after an evaluation of the combined policy reading value. The next stage comes where the moving average of the latest evaluations clears threshold or, without one, the paper's rule (Uchendu et al. 2023, A.4): it is within tolerance, a share of its size, of the best previous moving average. The first evaluation has no best to fall short of.

combined_policy_return

combined_policy_return(
    env_args,
    expert,
    agent_state,
    guide_steps,
    n_episodes,
    key,
)

The mean return in the env's units of the combined policy over n_episodes: the expert acts each episode's first guide_steps steps, the agent's deterministic policy the others, as evaluate acts it. The rollout has envs of its own, which it steps once per episode.

ajax.extensions.pretrain

One-shot pre-training research features as composable :class:Extensions.

CloningPretrain, MCPretrain and BellmanPretrain run once, before the training loop (the pretrain phase, skipped on resume); PhiRefresh refreshes MCPretrain's critic during training.

  • :class:CloningPretrain — behaviour cloning of the actor on an expert's rollouts.
  • :class:MCPretrain — regress a frozen expert critic on Monte-Carlo returns, then (optionally) lightly nudge the online critic toward it.
  • :class:BellmanPretrain — Bellman-bootstrapped critic pre-training on the expert buffer.
  • :class:PhiRefresh — periodic self-consistent refresh of the frozen expert critic during training (the post_update phase).
  • :class:PriorData — a transition dataset in the replay, and the agent's own updates on it before acting.
  • ExpertPrefill — the agent's expert's transitions in the replay before training.

MCPretrainAux

Diagnostics logged after MC critic pretraining.

PretrainLosses

A pretraining fit's first and last loss, kept in its extension's state for the evaluations' log. NaN before the fit, when it takes no step, and in a run resumed from a checkpoint saved before they were kept (added_fields, :func:ajax.checkpoint.restore_into).

unknown classmethod

unknown()

Every field NaN.

MCPretrainResults

Bases: PretrainLosses

MCPretrain's fit: its first and last regression loss, and the mean over the fit's rows of φ*'s value at the expert's action (the smallest of its critics').

CloningPretrain dataclass

CloningPretrain(
    expert_policy,
    n_steps=100000,
    epochs=10,
    batch_size=64,
    skip_actor=False,
    reset_log_std=False,
    reset_actor_head=False,
    env_args=None,
    actor_optimizer_args=None,
    name="cloning_pretrain",
)

Bases: Extension

Behaviour cloning of the actor on an expert's rollouts, before training.

Rolls expert_policy out for n_steps steps per env, observing as the agent does, then fits the actor to its actions on observations standardised with the dataset's statistics (:func:ajax.agents.cloning.pre_train: epochs passes in batches of batch_size, at the actor's learning rate). The agent's observation statistics start from the dataset's. skip_actor leaves the actor as initialised; after cloning, reset_log_std puts its log-std (head or parameter) back at its initial values and reset_actor_head also its output head (the mean layer, or a PID actor's gains). Evaluations log the mean loss of cloning's first and last epoch (cloning/first_loss, cloning/last_loss).

The fields after reset_actor_head are the agent's context, filled by :meth:bind_to_agent (the off-policy actor-critics, APO and DAgger do).

bind_to_agent

bind_to_agent(**agent_context)

Copy the agent's env_args (its observation features included) and actor_optimizer_args. Raises ValueError when a feature reads the agent's expert and expert_policy is another expert, or when another pretrain-phase extension comes before it in the stack.

pretrain

pretrain(agent_state, ext_state, context)

Clone the actor on context.rng (:meth:clone) and keep its losses.

clone

clone(agent_state, key)

agent_state with its actor cloned on rollouts drawn with key and its observation statistics seeded, and the mean loss of cloning's first and last epoch (NaN with skip_actor); raises ValueError when the agent did not bind its context.

MCPretrain dataclass

MCPretrain(
    expert_policy,
    n_mc_steps=10000,
    n_mc_episodes=100,
    n_steps=5000,
    use_online_light=True,
    online_light_steps=500,
    online_light_lr_scale=0.1,
    env_args=None,
    network_args=None,
    critic_optimizer_args=None,
    num_critics=2,
    gamma=None,
    reward_scale=None,
    use_phi_refresh=False,
    name="mc_pretrain",
)

Bases: Extension

Monte-Carlo critic pre-training.

Regresses a frozen expert critic φ* on unbiased MC returns from expert rollouts, persists φ* + the value range v_min/v_max on the agent state, and — when use_online_light is set — applies a weak supervised nudge of the online critic toward φ* to reduce seed-to-seed variance at initialisation.

Building φ* needs the agent's env, critic network and optimiser config, gamma and reward_scale: the fields after the hyperparameters, which the agent fills through :meth:bind_to_agent (only SAC does). φ* trains with that optimiser config as it is, so the agent's weight_decay (like its gradient clipping and learning- rate schedule) also decays φ* while it fits the MC returns. use_phi_refresh keeps φ*'s optimiser state for a :class:PhiRefresh in the same stack. Evaluations log the value range (mc_pretrain/v_min, mc_pretrain/v_max) and the fit (mc_pretrain/first_loss, mc_pretrain/last_loss, mc_pretrain/q_expert_mean: :class:MCPretrainResults).

bind_to_agent

bind_to_agent(**agent_context)

Copy the agent's context (env_args, network_args, critic_optimizer_args, num_critics, gamma, reward_scale) onto a new instance, and keep φ*'s optimiser when the stack (extensions) holds a :class:PhiRefresh.

pretrain

pretrain(agent_state, ext_state, context)

Build the frozen expert critic φ* and persist it on agent_state: a fresh critic regressed on unbiased MC returns sets expert_critic_params / expert_v_min / expert_v_max, then (use_online_light) the online critic is nudged toward it. The fit's results are the extension's state.

Raises ValueError when the agent did not bind its context.

BellmanPretrain dataclass

BellmanPretrain(
    n_steps=5000,
    buffer=None,
    gamma=None,
    reward_scale=None,
    recurrent=False,
    update_value_fn=None,
    update_target_fn=None,
    name="bellman_pretrain",
)

Bases: Extension

Bellman-bootstrapped critic pre-training.

n_steps critic updates on the replay buffer before training, which a seeder fills first (ExpertPrefill or PriorData, which pretrain before it). Bootstraps from an untrained critic, so the pre-trained values are biased (:class:MCPretrain regresses unbiased returns instead); kept for ablation parity. Evaluations log the critic loss of its first and last update (bellman_pretrain/first_loss, bellman_pretrain/last_loss).

The fields after n_steps are the agent's context, filled by :meth:bind_to_agent: a replay agent with a discounted Q critic and target critics gives its critic step (ajax.agents.families.ReplayAgent.extension_values). It needs the target critics, which each step's Polyak update moves.

bind_to_agent

bind_to_agent(**agent_context)

Copy the agent's buffer, gamma, reward_scale, recurrent and critic updates (update_value_fn, update_target_fn). It requires a seeded replay: without a seeder the replay is empty when it runs.

pretrain

pretrain(agent_state, ext_state, context)

Pre-train the critic and keep its losses; raises ValueError when unbound.

PhiRefresh dataclass

PhiRefresh(
    expert_policy,
    interval=500,
    steps=20,
    buffer=None,
    gamma=None,
    reward_scale=None,
    reads_stored_expert=False,
    name="phi_refresh",
)

Bases: Extension

Periodic self-consistent refresh of the frozen expert critic.

Every interval steps, run steps self-consistent Bellman updates on expert-flagged buffer transitions, keeping φ* aligned with the live data distribution. Requires :class:MCPretrain (which creates the refreshable φ*; refused without it).

buffer, gamma and reward_scale come from the agent through :meth:bind_to_agent (only SAC binds them); unbound, post_update raises ValueError.

bind_to_agent

bind_to_agent(**agent_context)

Copy the agent's buffer, gamma and reward_scale, and whether its expert is the agent's (:func:reads_stored_expert_actions).

ExpertPrefill dataclass

ExpertPrefill(
    n_steps,
    expert=None,
    offline_updates=0,
    name="expert_prefill",
)

Bases: Extension

An expert acts n_steps steps in every env before training, and its transitions go to the replay as collection writes its own (store_expert_transitions): with the agent's features at training progress 0, is_expert 1, and under an action transform the policy action that executes the expert's own. The rows count once in the observation and reward normalisers, as PriorData's and collection's own do (count_in_normalisers), and in no timestep, so learning_starts counts live steps.

Then offline_updates of the agent's update run on the replay, as PriorData's do: they need no env step, and they do not wait for policy_update_start or alpha_update_start. They are how an offline phase reads the agent's observation features, which a dataset does not hold.

The expert is the agent's, unless expert names one for the prefill alone: an agent's expert_policy is called on every step collected, and this one on the prefill's alone.

It needs an expert, a replay and an update that stays correct on actions the policy did not choose: SAC, TD3, REDQ, CrossQ, TQC, ASAC, RVI-SAC, IQL and DQN take it. It runs before the other pretraining, which may read its rows (ExtensionStack.apply_pretrain).

needs

needs()

The agent's expert, unless it has its own.

PriorData dataclass

PriorData(dataset, offline_updates=0, name='prior_data')

Bases: Extension

Prior data in the replay, and the agent's own updates on it before acting (offline-to-online RL).

Adds the dataset's rows to the agent's replay, where they stay (ajax.buffers.dataset.fill_replay), and to its observation and reward normalisers, each row counted once as collection counts its own; then runs offline_updates of the agent's update on that replay: its critic, actor, temperature and target steps and its extensions' loss terms, but no post_update between them. These updates come before any env step, so they do not wait for policy_update_start or alpha_update_start, which still count the env steps collected online. offline_updates=0 is RLPD's prior data in the replay (Ball et al. 2023) without its symmetric sampling. Ajax's warm-up acts uniformly: pair it with learning_starts=0.

Needs the replay and update an off-policy loop hands the pretrain phase (pretrain_context): SAC, TD3, REDQ, CrossQ, TQC, ASAC, RVI-SAC, IQL and DQN take it, every other agent refuses it when built.

pretrain_critic_mc

pretrain_critic_mc(
    agent_state,
    expert_critic_state,
    expert_policy,
    mode,
    env_args,
    gamma,
    reward_scale,
    n_mc_steps=10000,
    n_mc_episodes=500,
    n_steps=5000,
    batch_size=256,
)

Pre-train critic using Monte Carlo returns from expert trajectories.

Unlike Bellman pretraining (bootstraps from an untrained critic → biased), MC returns G_t = Σ γ^k r_{t+k} are unbiased estimates of V^expert(s). The critic starts with accurate Q(s, a_expert) near the target from step 1.

Collection strategy: single call with n_mc_steps * n_mc_episodes // n_envs timesteps. The n_envs parallel environments reset to different initial states on each episode boundary, giving the same state-space coverage as separate per-seed rollouts — without any mapping over traced keys (which fails inside the outer vmap over seeds). Total transitions ≈ n_mc_steps * n_mc_episodes regardless of n_envs.

(agent_state, frozen_expert_params, obs_batched, action_batched,

Type Description
Tuple[Any, FrozenDict, Array, Array, MCPretrainAux, LoadedTrainState]

MCPretrainAux, expert_critic_state_trained)

pretrain_critic_online_light

pretrain_critic_online_light(
    agent_state,
    obs_batched,
    action_batched,
    n_steps=500,
    lr_scale=0.1,
)

Weak supervised nudge of the online critic toward φ*.

Goal: reduce seed-to-seed variance at initialization. NOT a full MC pretrain — just reduces starting point spread. Target network stays random and untouched.

refresh_phi_star

refresh_phi_star(
    agent_state,
    buffer,
    phi_refresh_steps,
    gamma,
    reward_scale,
    ext,
)

Periodic self-consistent φ* refresh using expert-flagged buffer transitions. ext's expert gives the action at s' (extension_expert_actions).

Target: r + γ * min_k Q_φ(s′, π(s′)) — φ* supervises its own bootstraps. Non-expert transitions are masked out, so the gradient comes only from (s, a_expert, r, s') rows where EDGE fired the expert action.

pretrain_critic_bellman

pretrain_critic_bellman(
    agent_state,
    recurrent,
    gamma,
    reward_scale,
    buffer,
    n_steps,
    update_value_fn,
    update_target_fn,
)

n_steps Bellman critic updates (the agent's update_value_fn) on replay batches, each followed by a target update at tau 5e-4. Returns the agent state and each update's critic loss.

collect_and_store_expert_transitions

collect_and_store_expert_transitions(
    expert_policy,
    env_args,
    buffer,
    buffer_state,
    rng,
    n_steps,
)

Collect n_steps expert steps per env (collect_prefill_transitions) and store them in the replay (store_expert_transitions).

collect_prefill_transitions

collect_prefill_transitions(
    expert_policy, env_args, rng, n_steps
)

n_steps expert steps per env, as the replay keeps them: with the observations' features (the training progress holds 0 before training).

store_expert_transitions

store_expert_transitions(
    transitions, env_args, buffer, buffer_state
)

Store the expert's transitions, time along their first axis, in the replay row by row as the live collector does (replay_row): one step of every env per add (the buffer's add batch is the env axis), with the expert's actions at s and s' as a_expert and next_a_expert, and is_expert 1, the last row a seam (init_buffer's include_seam).

run_offline_updates

run_offline_updates(agent_state, agent_update, n_updates)

agent_state after n_updates of the agent's update on its replay, with no post_update between them.

ajax.extensions.target_mods

TD-target modifier research features as composable Extensions.

These reshape the Bellman target before it enters the critic loss (the on_target phase):

  • IBRL: add gamma (1 - d) (Q_expert - Q_policy) where the expert's next action is selected, so the value function matches an argmax action-selection policy.
  • LCBGatedBootstrap: soft-blend the policy and expert TD targets by an LCB-scored sigmoid gate.
  • CriticBlend: a warmup-decaying blend of the Bellman target with the frozen expert critic's.
  • MCVarianceCorrection: replace high-ensemble-variance Bellman targets with the MC-pretrained oracle.
  • ValueBox: a value-threshold expert action override during collection (the action phase).

The batch on_target reads is the dict the shared critic step builds (update_steps.apply_on_target): observations, actions, next_observations, rewards (unscaled), reward_scale, dones, gamma, raw_next_observations (the environment's own next observations, which an extension's expert reads: an agent keeps them when an extension carries an expert), next_a_expert, next_actions (the next actions the target scored) and critic_subset (the target critics it took its minimum over, where a random subset: REDQ's).

IBRL dataclass

IBRL(
    expert_policy,
    hybrid_acting=True,
    soft_choice=False,
    soft_choice_beta=10.0,
    reads_stored_expert=False,
    critic_subset_size=None,
    name="ibrl",
)

Bases: Extension

IBRL bootstrap (Hu, Mirchandani and Sadigh, Imitation Bootstrapped Reinforcement Learning, 2023), as its authors' code computes it (hengyuan-hu/ibrl 3c457da, rl/q_agent.py update_critic and _act_ibrl).

The target bootstraps on the better of the expert's next action a_E and the policy's a', the next action the agent's target scored (score_next_actions): it gains gamma (1 - d) [a_E selected] (min Q_target(s', a_E) - min Q_target(s', a')), the minima over the critics the base target took its minimum over. With all of them, the bonus is max(min Q(s', a_E) - min Q(s', a'), 0). With a random subset of them (REDQ's), a_E is selected on a fresh subset of the same size (draw_selection_critics), as the authors select on one random pair and value on another, so the bonus can be negative.

Selection is hard by default, the authors' "ibrl". With soft_choice it is their "ibrl_soft", in acting and in the bootstrap alike, as their act_method sets both: the expert's action is chosen with probability sigmoid(soft_choice_beta (min Q(a_E) - min Q(a'))), their softmax over the two candidates (beta 10 in their configurations), and sampled, in evaluation too (choose_expert).

With hybrid_acting (the default) it also acts as their act_method "ibrl", as every IBRL configuration of theirs does: it executes the better of the agent's action and the expert's (choose_action), in collection (the action stage, past the warm-up) and in evaluation (eval_action). The agent's is the one it would execute (TD3's noisy action, a sample; in evaluation its mean); each is scored by the target critics' minimum, over a fresh random subset where the target takes one (REDQ's), as the authors' forward_k draws a random pair per call. The replay flags the steps the expert's action took. The actor's loss ignores the choice, as theirs; their epsilon-greedy choice (ibrl_eps_greedy, 1 in every configuration) is left out.

No original form exists for the rest, kept as Ajax's: SAC's, REDQ's and TQC's entropy term stays at a' when the expert is selected; TQC's bonus reads its quantiles' means, while its target pools truncated quantiles; a target without next actions (IQL's V(s')) scores a sample of the online actor instead.

implemented_phases

implemented_phases()

Its acting phases only where it acts hybrid.

bind_to_agent

bind_to_agent(**agent_context)

Read the expert's stored actions when it is the agent's, and act on the target's subset size (REDQ's; None: every critic).

action

action(agent_state, ext_state, obs, rng, context)

Collection's choice, from the action the step would execute.

eval_action

eval_action(agent_state, ext_state, obs, rng, context)

Evaluation's choice, from the action the agent evaluates with.

choose_action

choose_action(agent_state, step, action, key)

The expert's action where its minimum over the target critics tops action's, else action (hengyuan-hu/ibrl rl/q_agent.py _act_ibrl), or chosen as choose_expert chooses. Reads step (the stage's dict, or evaluation's) and writes into it where the expert's won (expert_mask). The subset and the soft choice draw on keys derived from key by name, so either option leaves the other's draw.

choose_expert

choose_expert(expert_values, policy_values, key)

Where the expert's action is chosen over the policy's, from their values: where the expert's is higher (a tie keeps the policy's, as the authors' argmax does); with soft_choice, on a draw on key with probability sigmoid(soft_choice_beta (expert - policy)), the softmax over the two of their _act_ibrl_soft, which samples it in evaluation too (UPSTREAM_BUGS 4).

eval_metrics

eval_metrics(agent_state, ext_state, rng, context)

Where it acts hybrid, the share of envs whose last collection step executed an expert's action (ibrl/expert_frac).

LCBGatedBootstrap dataclass

LCBGatedBootstrap(
    expert_policy,
    lcb_beta_init=1.0,
    lcb_beta_decay_k=2.0,
    lcb_temperature=1.0,
    reads_stored_expert=False,
    name="lcb_gated_bootstrap",
)

Bases: Extension

LCB-gated bootstrap.

Scores the policy and expert next-actions by an LCB rule and soft-blends the two TD targets with p_expert = σ((score_e - score_p)/lcb_temperature). β anneals over training; evaluations log it (lcb_bootstrap/beta). The policy's next action is the one the agent's target scored, as IBRL's, and the two values blended are minima over the critics the base target took its minimum over (all of them, or REDQ's subset), so the blend moves the target from what it valued; the LCB scores read the whole ensemble.

bind_to_agent

bind_to_agent(**agent_context)

Read the expert's stored actions when it is the agent's.

beta

beta(timestep, total_steps)

The LCB pessimism β at timestep (:func:lcb_beta).

CriticBlend dataclass

CriticBlend(
    expert_policy,
    critic_warmup_frac=0.15,
    reads_stored_expert=False,
    name="critic_blend",
)

Bases: Extension

Warmup-decaying blend of the Bellman target with the expert's.

(1-α)·y_bellman + α·y_expert with y_expert = r + γ(1-d)·V_E(s'), the one-step target on the frozen expert critic V_E(s') = φ*(s', a_E(s')), so the blend stays a Bellman target (V_E(s') alone has no reward, discount or terminal mask). α decays linearly to 0 over critic_warmup_frac of training; evaluations log it (critic_blend/expert_weight). Requires the frozen expert critic :class:MCPretrain fits (refused without it).

bind_to_agent

bind_to_agent(**agent_context)

Read the expert's stored actions when it is the agent's.

expert_weight

expert_weight(timestep, total_steps)

α: 1 at the start, falling linearly to 0 at critic_warmup_frac of the run.

MCVarianceCorrection dataclass

MCVarianceCorrection(
    threshold, name="mc_variance_correction"
)

Bases: Extension

Replace high-variance Bellman targets with the MC oracle.

Where the inter-critic variance exceeds threshold the Bellman target is swapped for the MC-pretrained expert critic's estimate. Requires :class:MCPretrain (refused without it).

ValueBox dataclass

ValueBox(name='value_box')

Bases: Extension

Value-threshold expert-action override.

During collection, override the policy action with the expert's whenever the frozen-expert value V_expert(s) exceeds a curriculum threshold that ramps from v_min to v_max over training. Requires MCPretrain (which supplies phi*, v_min and v_max; refused without it).

The action phase, in the action stage's post-warm-up slot (ajax.environments.action_stage), reads the stage's dict (env_action; expert_action, the action of the agent's expert_policy, at which it also measures the expert's value; observations, the critics' input, augmented when it is) and the box bounds off the agent state (so a resumed run keeps them), and writes in_value_box, entry_bonus and box_entry back into the dict for the collector to record on the transition, and expert_mask, where the expert drove. An entry ends the agent's episode: the expert's value, paid as the bonus, replaces the bootstrap, whatever its sign. The override (box_action_override) comes after the warm-up's choice.

Evaluations log the threshold (value_box/threshold), the share of envs inside the box and the share the expert drove on the last collection step (value_box/in_box_frac, value_box/expert_frac); the bounds are MCPretrain's (mc_pretrain/v_min, mc_pretrain/v_max).

action

action(agent_state, ext_state, obs, rng, context)

Override with a_expert inside the value box, its bounds MCPretrain's v_min and v_max on the agent's state; writes in_value_box, entry_bonus, box_entry and expert_mask into obs for the collector's bookkeeping (reward shaping, the entry's termination, is_expert_flag).

threshold

threshold(agent_state, step, total_steps)

The box's threshold at step: MCPretrain's v_min rising linearly to its v_max over the run.

blend_modify_target

blend_modify_target(target_q, expert_target, alpha_blend)

Blended Bellman: (1-alpha)y_bellman + alphay_expert.

mc_correction_modify_target

mc_correction_modify_target(
    target_q,
    critic_state,
    critic_params_mc,
    observations,
    actions,
    q_var,
    mc_variance_threshold,
)

Replace high-variance Bellman targets with MC-pretrained oracle estimate.

box_compute_threshold

box_compute_threshold(v_min, v_max, train_frac)

Curriculum threshold: v_min + (v_max - v_min) * train_frac.

box_entered

box_entered(in_box, last_in_box)

Where the step enters the value box: inside it now, not before.

box_compute_state

box_compute_state(
    obs,
    a_exp,
    critic_state,
    expert_critic_params,
    threshold,
    last_in_box,
)

Compute box membership and entry bonus, the expert's value V(s) = min Q_phi*(s, a_exp) at its action a_exp.

Returns (in_box, entry_bonus, v_box).

box_action_override

box_action_override(action, expert_action, in_box)

Override with expert action inside the value box.

discounted

discounted(name, gamma)

The target's discount gamma, which a bootstrap bonus scales; refused on an average-reward agent (ASAC, RVI-SAC, APO: gamma None), whose target has no discount and for which the bonus has no form.

score_next_actions

score_next_actions(ext, agent_state, batch, key)

The target critics' ensemble at s' for the expert's action and for the policy's, (Q_target(s', a_E), Q_target(s', a')): a' is the next action the agent's target scored (TD3's smoothed target action, the sample SAC's, REDQ's and TQC's targets valued), as the authors' IBRL compares the expert with the action its target values (hengyuan-hu/ibrl rl/q_agent.py:_act_ibrl). A target without next actions (IQL's V(s')) has no original form: a sample of the online actor on key stands in.

take_minimum

take_minimum(values, critics)

The minimum of values over its ensemble axis, over the critics indexed by critics (None: all of them).

draw_selection_critics

draw_selection_critics(size, num_critics, key)

The critics IBRL selects the expert's or the policy's action on: a fresh random subset of size critics, the size of the subset the base target takes its minimum over, drawn on key; None (all critics) where the target takes all of them (size None). The authors' state critic draws a random pair on each call, one to select and one to value (hengyuan-hu/ibrl rl/critic.py forward_k, rl/q_agent.py:288, :442), a quirk Ajax copies (UPSTREAM_BUGS 1); with no subset both are every critic, as in their two-critic pixel runs.

ajax.extensions.adversarial

Adversarial imitation as a composable :class:Extension.

  • :class:AdversarialReward — GAIL's discriminator reward.

Discriminator

Bases: Module

Logits of "an expert's" for an (observation, action) row.

AdversarialReward dataclass

AdversarialReward(
    demonstrations,
    n_updates=2,
    learning_rate=0.001,
    architecture=("32", "relu", "32", "relu"),
    name="gail",
)

Bases: Extension

GAIL (Ho and Ermon, NeurIPS 2016): the policy learns from a reward a discriminator gives, trained to tell its rollouts from the expert's demonstrations. Following HumanCompatibleAI/imitation@e5ef188 (algorithms/adversarial/gail.py and common.py): each rollout's rewards become -log(1 - D(s, a)) from the current discriminator (- logsigmoid(-logits)), then the discriminator takes n_updates steps of binary cross-entropy, the demonstrations labelled 1, on the rollout's rows and as many demonstration rows drawn uniformly. The environment's own reward is not used. The discriminator reads the action the env executes, clipped to [-1, 1] in agent units (:func:~ajax.environments.utils.agent_action_to_env), as the reference records it (its BufferingWrapper sees the action SB3 steps the env with, clipped to the box). Its 32-32 ReLU network starts as torch's nn.Linear and steps by torch's Adam (learning rate 1e-3), the reference's BasicRewardNet and optimiser. Deviations: the discriminator reads (s, a) unnormalised, without the reference examples' running normalisation; its generator batch is the whole rollout, the reference's demo_batch_size rows of its last one; PPO stands in for the paper's TRPO, as in the reference. Logs gail/reward, gail/disc_loss and the shares of expert and rollout rows it classifies right, gail/expert_acc and gail/policy_acc.

rows

rows()

The demonstrations' (observation, executed action) rows.

ajax.extensions.offline

Offline-RL critic regularisers as composable :class:Extensions.

  • :class:ConservativeQ — CQL(H)'s conservative critic term.
  • :class:CalQL — the same term, its policy-action values floored at the data's Monte-Carlo returns (Cal-QL).
  • :class:TargetBC — ReBRAC's penalty on the target's next actions.

ConservativeQ dataclass

ConservativeQ(
    alpha=5.0, n_actions=10, name="conservative_q"
)

Bases: Extension

CQL(H)'s critic term (Kumar, Zhou, Tucker and Levine, NeurIPS 2020, eq. 4), in the importance-sampled form of the authors' code (aviralkumar2907/CQL@d67dbe9, d4rl/rlkit/torch/sac/cql.py:234-264, min_q_version 3)::

alpha * mean( logsumexp_j [Q(s, a_j) - log density(a_j)] - Q(s, a) )

over the critics and the batch, with a the row's action and the a_j n_actions uniform actions in [-1, 1]^A and n_actions of the policy at s and at s', all scored at s. It pushes the critic down on actions away from the data's and up on the data's. The reference sums each critic's Bellman loss and term; Ajax's critics share one mean squared error, so the term is the mean over them, at the same ratio. It needs a policy with a density: a deterministic one (TD3's) is a point mass, whose samples are copies of one action and whose density is undefined. Deviations from the reference's SAC: its target keeps SAC's entropy term (the reference's deterministic_backup drops it), and there is no policy_eval_start warm start, during which the reference's actor maximises the data actions' log-likelihood in place of the critics' value (cql.py:184-191; 0 steps by default, :36, and 40,000 in its examples, d4rl/examples/cql_mujoco_new.py:140). Logs cql/term and cql/gap, the logsumexp minus the data's value.

floor

floor(q, batch)

The policy actions' values as the term reads them (CalQL floors them); no metrics.

CalQL dataclass

CalQL(alpha=5.0, n_actions=10, name='cal_ql')

Bases: ConservativeQ

Cal-QL (Nakamoto, Zhai, Singh, Mark, Ma, Finn, Kumar and Levine, NeurIPS 2023): :class:ConservativeQ's term with the policy actions' values floored at the row's Monte-Carlo return to go before the logsumexp (nakamotoo/Cal-QL@ac6eafe, JaxCQL/conservative_sac.py:227-240), so the critic is pushed down no further than the data's own return. The return to go is the transition dataset's (return_to_go), at its gamma, in the env's reward units: the agent's gamma and a reward_scale of 1 match it. Deviation: the reference computes a collected episode's returns when it ends; collected rows here keep -inf, no floor. Also logs calql/bound_frac, the share of policy actions at s whose value the floor raised.

TargetBC dataclass

TargetBC(beta=1.0, name='target_bc')

Bases: Extension

ReBRAC's critic penalty (Tarasov, Kurenkov, Nikulin and Kolesnikov, NeurIPS 2023; tinkoff-ai/ReBRAC@694385b, src/algorithms/rebrac.py: 134-144): the bootstrap less beta times the squared distance from the next actions the target scored (TD3's smoothed next_actions) to the dataset's next action a' (next_action)::

y -= gamma (1 - d) beta sum_i (next_actions_i - a'_i)^2

A row whose a' is unknown (an episode's last row, a collected one: NaN) keeps its target. Logs target_bc/penalty, the mean penalty, and target_bc/known_frac, the share of rows with an a'.

policy_samples

policy_samples(actor_state, observations, key, n)

n actions of the actor at each observation, (n, B, A), and their log-densities, (n, B, 1), held constant.

sampled_q

sampled_q(critic_state, params, observations, actions)

Every critic at each observation and each of its (n, B, A) actions: (critics, n, B, 1).

ajax.extensions.retained

Rows a replay keeps for the whole run, in a ring of their own beside the one collection writes (ajax.buffers.utils.TwoBufferState), so no later step evicts them.

  • :class:RetainedDemonstrations -- DDPGfD's demonstrations, kept forever.
  • :class:RLPD -- RLPD's offline buffer, half of each batch.

The update ratio, the critics and their architecture stay the agent's own (num_critic_updates, num_critics, critic_architecture), so these modules run on any backbone. RLPD's original configuration, ten LayerNorm critics, a subset of two and 20 critic steps per env step on fresh batches, is REDQ's defaults with critic_architecture=("256", "layernorm", "relu", "256", "layernorm", "relu") and extensions=(RLPD(...),).

RetainedDemonstrations dataclass

RetainedDemonstrations(
    n_steps,
    dataset=None,
    share=None,
    expert=None,
    name="retained_demonstrations",
)

Bases: Extension

Demonstrations in a ring of their own, sampled for the whole run.

DDPGfD (Vecerik et al. 2017, sec. 3) "loads the demonstration transitions into the replay buffer before the training begins and keeps all transitions forever". The rows are an expert's, n_steps per env (ExpertPrefill's: with the run's observation features), the agent's or, so that no online step calls one, expert's; or those of dataset (n_steps 0), whose observations hold no features. They count once in the normalisers, in no timestep, and the replay's capacity leaves them out.

share is the part of each batch they fill. None draws each row over all the rows held, so they fade as the agent's own rows arrive, as in a replay that evicts nothing of theirs. 0.5 is Rainbow-DemoRL's prefill (Bhatt et al. 2026), which with CloningPretrain before it in the stack is their BC start plus prefill.

Departures from DDPGfD: the sampling is uniform in each ring, without its prioritised replay (its priorities for demonstrations set the share itself); no n-step loss and no L2 penalty, which stay the backbone's.

needs

needs()

The agent's expert, unless a dataset or its own gives the rows.

pretrain

pretrain(agent_state, ext_state, context)

The kept rows written to a ring of their own, as a replay's seeders write theirs, which then joins the replay.

RLPD dataclass

RLPD(
    n_steps,
    dataset=None,
    share=0.5,
    expert=None,
    name="rlpd",
    critic_subset=None,
    critic_layer_norm=True,
)

Bases: RetainedDemonstrations

Online RL with offline data (Ball, Smith, Kostrikov and Levine, ICML 2023; ikostrikov/rlpd@c90fd4b): an offline ring of logged rows, half of every batch from it, on critics with LayerNorm.

The logged rows keep their rewards, and the agent's reward normaliser divides them as it divides its own. critic_subset is their random subset Z: each target's bootstrap takes the minimum of that many target critics, drawn once per target (Algorithm 1, line 15; None: all of them). critic_layer_norm refuses critics without LayerNorm; set it to False to run the ablation (their figure 7, value divergence on narrow data).

Departures, all kept for the shared backbone, and all gone on REDQ (the module docstring): SAC's actor loss reads the critics' minimum, RLPD's their mean; SAC's critic steps of one update share one batch, RLPD's each draw theirs (rlpd/agents/sac/sac_learner.py update); and its target entropy is -dim(A), RLPD's -dim(A)/2. Ajax's warm-up acts uniformly up to learning_starts, as their code's start_training does and their Algorithm 1 does not. The offline rows are not interleaved with the online ones: the batch's first half is theirs, which a mean over rows does not see.

implemented_phases

implemented_phases()

on_target only where it subsamples: otherwise the target is the agent's own, on any critic.

reads

reads()

Only a subsampling target reads its batch.

needs

needs()

Subsampling needs a next action's values, one per target critic.

bind_to_agent

bind_to_agent(**agent_context)

Check the critics the agent builds, where it hands them over.

on_target

on_target(agent_state, ext_state, batch, target, context)

The target, bootstrapping on a random subset of the target critics.

bootstrap_on_subset

bootstrap_on_subset(
    target, next_values, subset, gamma, dones
)

target, whose bootstrap took the minimum of the target critics' next_values (their axis first), as if it took the minimum over subset.

ajax.extensions.cheq

Contextualized Hybrid Ensemble Q-learning (Cramer, Frauenknecht, Sabirov and Trimpe, RLC 2024; Data-Science-in-Mechanical-Engineering/cheq@adedba2): the executed action blends the expert's and the RL agent's, with a weight that falls as the critics disagree, and the actor and the critics read the weight::

a_mix = (1 - lambda_t) a_prior + lambda_t a_RL                       eq. 2
u_t = std_e Q_e(s_t, a_RL, lambda_t)                                 eq. 4
lambda_{t+1} = lambda_min + clip((u_t - u_max) / (u_min - u_max), 0, 1)
               * (lambda_max - lambda_min)                           eq. 5

:func:blend, :func:disagreement and :func:adapted_weight are those three.

HeldWeight

The weight each env acts on, and whether its episode has started.

CHEQ dataclass

CHEQ(
    lambda_min=0.2,
    lambda_max=1.0,
    u_low=0.005,
    u_high=0.025,
    warmup_lambda_max=0.3,
    adaptation_start=5000,
    mask_rate=0.8,
    scale_rate=0.01,
    weight_column=-1,
    observer_index=-1,
    name="cheq",
)

Bases: Extension

The weight's column on every observation, the blend executed, the RL action stored.

The agent's expert is the control prior. Each observation carries lambda_t, raw, so the actor and the critics read it. A row stores the RL action a_RL, the uniform draw in the warm-up and the actor's sample after, and its next observation holds the row's lambda_t (Algorithm 2), so training sees a_RL in the hybrid MDP, not a_mix. Before adaptation_start each episode runs on one weight of the warm-up's band, up to warmup_lambda_max (their [0.2, 0.3] for 5e3 steps). From it, lambda_t starts each episode at lambda_min and follows eq. 5 after every update.

Thresholds. u_low and u_high are shares of the value spread, the interquartile range of the values the targets bootstrap, tracked at scale_rate, not Q units: the paper's 0.03 and 0.15 are Q units of one task, and these tasks' rewards span 1e-4 to 6e4 per step. Scaling or shifting the rewards leaves u / spread as it is, and one trip's cost in a batch does not inflate it. The defaults are the paper's numbers over a spread of 6, an estimate from its rewards (0.08 to 0.28 per step at gamma 0.99), not a measurement: a starting point to tune per task.

The prior's memory. The paper assumes a prior "time-invariant and without an internal state". A PID with an integrator breaks that: a_prior then depends on the error history, so (s, a_RL, lambda) is not Markov. So a stateful expert needs PIDTermsInput or ExpertStateInput in the stack: its memory joins the observation the actor and the critics read, and the hybrid MDP is Markov again. ExpertStateInput holds the memory itself. PIDTermsInput holds the error's plain integral, which parts from it where the expert's anti-windup holds its integrator (four_tank's PI, while its pumps saturate). The expert's memory goes on advancing on the observed error under the blend, and restarts with each episode.

Departures from the paper. Evaluation has no state to carry lambda in: its observation holds lambda_max, which is the actor's input if evaluated alone; eval_action reads eq. 4 and 5 there, at the current state rather than the last, then the actor again at that weight, in place of lambda carried along the episode. Masks seed on a row's bits (row_masks), not a stored mask, and each critic's loss keeps the batch's size as its divisor. The warm-up's band is walked per episode, not per step. Inherited from the shared backbone, and gone on REDQ: SAC's actor loss reads the critics' minimum (theirs, the mean), its target every critic (theirs, a random pair), and its critic steps share a batch. eq. 4 is the population deviation; their code's torch.std is the sample's (a factor sqrt(E / (E - 1)), which the thresholds absorb). Their configs run 3 critics for the paper's E = 5.

bind_to_agent

bind_to_agent(**agent_context)

Find the weight's column; refuse an expert whose memory the observations do not hold (the class docstring).

observe

observe(inputs, state)

The weight the env acts on next: its episode's, chosen at the episode's first observation. Evaluation holds the actor's own column (the class docstring). The run's first observation and an expert prefill's rows, at progress 0, hold lambda_min.

action

action(agent_state, ext_state, obs, rng, context)

The blend of the chosen action and the expert's, the chosen one (uniform in the warm-up) going to the replay.

eval_action

eval_action(agent_state, ext_state, obs, rng, context)

The blend at the weight eq. 4 and 5 give at this state, with the actor's action at that weight (the class docstring).

on_target

on_target(agent_state, ext_state, batch, target, context)

The target unchanged, the spread of what it bootstraps tracked.

critic_loss

critic_loss(agent_state, ext_state, batch, context)

The masked rows taken back out of the agent's mean squared error.

post_update

post_update(agent_state, ext_state, context)

lambda_{t+1} from the newest row (s_t, a_RL, lambda_t), written to the next observation and its env's held weight; a new episode keeps its start.

eval_metrics

eval_metrics(agent_state, ext_state, rng, context)

The weight the envs have been acting on, the disagreement behind it, and the spread that scales it.

blend

blend(prior, rl_action, weight)

Eq. 2: the regularised mix, the RL action in full at weight 1.

disagreement

disagreement(critic_state, observations, actions)

Eq. 4: the critics' standard deviation at (s, a), one per row.

adapted_weight

adapted_weight(
    uncertainty, u_low, u_high, lambda_min, lambda_max
)

Eq. 5: lambda_max below u_low, lambda_min above u_high, linear between.

track

track(tracked, value, rate)

tracked, moved by rate towards value: a running average.

interquartile_range

interquartile_range(values)

The spread of the middle half of values, which one trip's cost among a batch's rows leaves as it is, as it would not a standard deviation.

row_masks

row_masks(key, rows, critics, rate)

Per critic and row, whether the critic trains on the row, (critics, B, 1): Bernoulli(rate), drawn from the row's own bits and key, so a row keeps its masks every time it is sampled.

relative_uncertainty

relative_uncertainty(
    critic_state, ext_state, observations, actions
)

Eq. 4 as a share of the value spread; past u_high before any target.

ajax.extensions.porl

PORL (Xiao et al. 2025, arXiv 2505.16856): online fine-tuning of a pre-trained policy, with no dataset and no pre-trained critic.

Algorithm 1 runs two stages on one replay, empty at the start. For T steps the policy stays frozen and acts epsilon-greedily while a fresh critic takes M updates per step; from step T + 1 it is plain SAC. :class:EpsilonGreedyPresample is the first stage's behaviour, and :func:porl gives the rest as the agent's own settings, CloningPretrain standing for the pre-trained policy.

M, the critics and their architecture stay the agent's (num_critic_updates, num_critics, critic_architecture), so the arm runs on any backbone. The paper's Table 1 is num_critic_updates=16, num_critics=10, actor_learning_rate=1e-4, alpha_learning_rate=1e-4, batch_size=512 (1024 on Kitchen and RLBench), LayerNorm critics of four layers of 256 (three of 512 on Adroit and Kitchen) and presample_steps=20_000 (5_000 on Adroit).

A stateful expert's clone needs the expert's memory in its observations, through features: ExpertStateInput.for_expert(expert), exact, with the agent's expert_policy and so one expert query per step; or PIDTermsInput, which needs no expert but holds the error's plain integral, so it parts from a PI whose anti-windup holds its integrator (four_tank's, while its pumps saturate).

Departures from the paper:

  • The policy is a clone of an expert. Its rollouts are plant steps the paper does not count (ajax.ledger charges them) and they stay out of the replay.
  • The paper's networks read no observation statistics; the clone's do, so holding its weights would not hold the policy (see :class:EpsilonGreedyPresample). The stage's rows never count in them.
  • SAC's critic steps of one update share one batch, and its actor step reads the same batch. The paper draws M batches and steps the actor on their union. REDQ draws one per critic step, and steps its actor on the last.
  • The paper does not say how its target reads ten critics. SAC takes the minimum of all of them; REDQ takes it over a random subset_size of them.
  • The paper gives no starting temperature: the stage holds the agent's alpha_init, and fine-tuning starts from it.
  • The exploiting action is the clone's mean, a reading rather than the paper's words ("actions from the pre-trained policy"): it calls the stage greedy, and its figure 9 compares it with deterministic sampling.

EpsilonGreedyPresample dataclass

EpsilonGreedyPresample(
    presample_steps=20000,
    epsilon=0.1,
    name="epsilon_greedy_presample",
)

Bases: Extension

For the first presample_steps env steps each env takes a uniform action with probability epsilon and the actor's mean otherwise; then the agent's own action. A uniform warm-up keeps its actions. The replay stores the action taken.

The observation statistics hold where pretraining left them through those steps, to the one row each step counts before it acts. Frozen weights alone are no frozen policy: the random actions reach states the clone's rollouts did not, and those rows would move the statistics the weights read.

check_stack

check_stack(stack)

The actor's mean is the executed action only without an action transform.

pretrain

pretrain(agent_state, ext_state, context)

Keep the statistics as the pretraining before it left them.

post_update

post_update(agent_state, ext_state, context)

Put the kept statistics back, up to the stage's last update.

porl

porl(
    cloning, presample_steps=20000, epsilon=0.1, features=()
)

The agent's keyword arguments for PORL: clone, then a critic warm-up on presample_steps env steps (a multiple of n_envs), then fine-tuning. Its critic updates start with the first step. Only they run in the warm-up: Algorithm 1 has no actor or temperature step before the one following step T + 1, which the start gates count in steps collected.

ajax.extensions.structure

What RL can change around a controller it keeps.

  • OuterLoopReference: the policy moves the target the expert reads.
  • GainScheduledLaw, under ExpertGains: the policy sets multipliers on its gains.
  • BumplessTracking: the expert's memory follows the action applied.

Each asks only what it uses of a stateful expert, expert(memory, obs) -> (action, memory): the first and the last which columns to move, the second its gains through step_with_gains. TargetGym's batched controllers have that form, and its envs name the columns (obs_target_index, obs_value_index). ExpertLaw gives gains to a law that form does not cover.

ExpertLaw dataclass

ExpertLaw(step, params, memory, gain_names=())

An expert with step_with_gains, from its law: step(params, memory, obs) -> (action, memory) for one env, with params and memory pytrees, as TargetGym's Controller holds it, and gain_names the dotted leaves of params that are gains.

TargetGym's batched form has step_with_gains too, for a law whose flat gains are registered. Most are not, TECS nests its gains, and that form makes every param an array, which wind_turbine's law cannot take to numpy.

of classmethod

of(controller, gain_names)

The law of a controller with step, params and init_state.

step_with_gains

step_with_gains(state, obs, gains)

A step at gains, (n_envs, n_gains), the other params left as they are.

GainLayerState

A gain-scheduled law's state per env: the law's memory now and at the last step, the last observation and executed action, the multipliers' logarithms, and whether the episode has had a step.

GainScheduledLaw dataclass

GainScheduledLaw(
    expert,
    obs_width,
    max_log_rate=0.05,
    bias_retention=0.99,
    action_limits=(-1.0, 1.0),
)

A law whose gains take multipliers each step, through a velocity form (Bloor et al., arXiv 2408.13566, eq. 10): for ExpertGains, which bounds the multipliers (max_factor), and an agent's expert_policy. expert is any with step_with_gains, learnable_fields, anchor_gains and init_state.

The paper's layer is a PID. These laws are not all PIDs, so the form is theirs, held at the step's gains: the change in the action is the law's change from the last step to this one, both at this step's gains::

u_t = u_(t-1) + f(g_t; x_t) - f(g_t; x_(t-1))

On a PID that is eq. 10, and a new gain alone moves nothing. At constant gains it is the law itself, with its limits and anti-windup. It is written u_t = f(g_t; x_t) + bias, so at unit multipliers bias is 0 and the action is the law's, to float32 rounding where it divides by a gain (XLA divides by one number through its reciprocal, not by one per env). bias_retention scales the bias each step: at 1 this is eq. 10, below it a law at its own limit, or holding an inner integrator, cannot stay held off that limit by an old bias. Near a law's own limit the difference is of limited outputs, so a higher gain can move the action less, where eq. 10 on a PID would not.

Beyond the paper, whose gains jump each step: log multipliers move at most max_log_rate a step. The memory they hold joins the state, so the policy reads what its action will move from through ExpertStateInput. The paper trains by particle swarm; Ajax's SAC here has no published result.

anchor_gains property

anchor_gains

Ones: the gains ExpertGains sets here are the multipliers.

__call__

__call__(state, obs)

The law at the multipliers it holds.

step_with_gains

step_with_gains(state, obs, factors)

One step at the multipliers factors, (n_envs, n_gains), as far as the rate limit lets them move.

OuterLoopReference dataclass

OuterLoopReference(
    target_channels, max_change, name="outer_loop_reference"
)

Bases: Extension

Outer-loop control (Arroyo and Giraldo, arXiv 2008.13732): the policy moves the target the agent's expert reads, and the unchanged expert acts. The actions are one per column of target_channels, each scaled by its max_change, in the target's units. The replay and the critics hold the policy's actions, and a warm-up draws uniform changes.

Departures from the paper: the policy outputs a change, not the reference itself, so a change of 0 is the expert to the bit and the policy starts near it; and the reward stays the task's, without the paper's penalties on fast references (eq. 7).

BumplessTracking dataclass

BumplessTracking(
    reading_channels, name="bumpless_tracking"
)

Bases: Extension

The agent's expert's memory follows the action applied: without it the memory advances on the error whoever acts, so its integral winds up while a learner holds the plant. It changes nothing the arm chooses, so it stacks on any switching or blending arm, and leaving it out is the ablation.

reading_channels are the columns the expert's errors read, TargetGym's obs_value_index. What it follows is the actuator's report, the env's info["applied_action"], or the commanded action where the env gives none or no env is stepped (a deployed policy). A step the expert chose itself stays its own, its anti-windup with it, whatever the actuator made of it: that is the expert the study scores, and its discrepancy is not a takeover.

conditioned_memory

conditioned_memory(expert, memory, obs, action, channels)

The batched expert's memory after a step that executed action: Hanus, Kinnaert and Henrotte (Automatica 1987), for a controller x+ = A x + B e, u = C x + D e, with the state fed the realisable error, the one at which the controller would have output the executed action::

realisable error = e + inverse(D) (u_executed - u)

The paper is paywalled: the equations are as MERL TR2019-054 restates them.

D is the expert's derivative in the readings it compares with its targets, so a cascade's is the whole cascade's. The error moves through the reading, not the target as the paper has it: a law biasing on its target (four_tank's steady voltages, cstr's steady temperature) has that bias stay put, and may not be defined at a moved one. D's pseudo-inverse leaves a law sitting at its own limit, D = 0, to its own anti-windup. One Newton step, exact for a law affine in its readings.

path_name

path_name(path)

A pytree leaf's dotted name, "tecs.time_const".

batched

batched(tree, n_envs)

tree repeated along a new leading axis, one entry per env.

ajax.extensions.exploration

Exploration research features as composable Extensions.

EDGE (Expert Decayed Guided Exploration) substitutes the expert action for the policy action during collection, gated by a value comparison that decays over training. EDGEExploration selects one of six gates with gate: "fixed", "argmax" and "boltzmann" (value-gap gates) or "lcb", "argmax_lcb" and "thompson" (quality-aware gates); the gate maths are the functions below.

The action stage (ajax.environments.action_stage) hands the gate the step's quantities (post_warmup_action, expert_action, observations, ...) as a dict through the obs argument, as the batch dict of the on_target and actor_loss phases. The extension picks an action (or returns None to defer); the stage owns the bookkeeping (is_expert_flag, the stored action). A gate draws on the extension's own key, which the stage derives from the collection's.

EDGEExploration dataclass

EDGEExploration(
    gate="fixed",
    decay_frac=0.3,
    tau=1.0,
    fixed_prob=0.5,
    lcb_beta_init=1.0,
    lcb_beta_decay_k=2.0,
    lcb_temperature=1.0,
    lcb_asymmetric=False,
    epsilon_floor=0.0,
    name="edge_exploration",
)

Bases: Extension

Expert Decayed Guided Exploration during collection.

gate selects the substitution rule (see the module docstring). The other fields:

  • decay_frac: the value-gap gates decay to 0 over this fraction.
  • tau: the Boltzmann temperature on the value gap.
  • fixed_prob: the substitution probability of the fixed gate.
  • lcb_beta_init, lcb_beta_decay_k: the LCB pessimism schedule.
  • lcb_temperature: the softmax temperature of the LCB and Thompson gates.
  • lcb_asymmetric: LCB on the expert arm, UCB on the policy arm.
  • epsilon_floor: the minimum policy-pick probability (Thompson).

The expert is the agent's expert_policy: the gate compares the action collection called it for with the one the step would execute. Evaluations log the share of envs the expert drove on the last collection step (edge/live_expert_frac) and the gate's schedule: edge/beta for the LCB gates, edge/decay for the fixed, argmax and Boltzmann gates (the Thompson gate has none).

needs

needs()

The value gates compare the critic's values of the two actions; the LCB and Thompson gates read its ensemble.

action

action(agent_state, ext_state, obs, rng, context)

Apply the configured EDGE gate to substitute the policy action.

obs is the action stage's dict (the module docstring): expert_action, observations (the critics' input, its features included) and post_warmup_action (the action the step would execute). The gate draws on rng, the extension's own key.

Side effects: writes expert_mask back into obs, which flags the steps the expert took (is_expert_flag).

choose_by_score

choose_by_score(agent_state, obs, rng, context)

Where a scoring gate (every gate but the fixed one) hands the expert the step, drawing on rng, the extension's key. It scores with the frozen expert critic phi* where MCPretrain fitted one, else with the agent's live critic.

eval_metrics

eval_metrics(agent_state, ext_state, rng, context)

The fraction of envs an expert drove on the last collection step, and the gate's schedule at the collector's timestep.

score_action_pair

score_action_pair(
    obs,
    policy_action,
    expert_action,
    critic_state,
    critic_params,
)

The critic ensemble's Q(s, a_expert) and Q(s, a_policy) at critic_params (the live critic's, phi*, or the target's), obs the critic's input.

lcb_beta

lcb_beta(step, total_steps, init, decay_k)

The LCB pessimism init (1 - t / T)^decay_k, annealed over the run (t / T clipped to [0, 1], T at least 1).

lcb_score

lcb_score(q, beta)

min Q - beta (max Q - min Q) over the ensemble axis: the critics' disagreement as epistemic uncertainty, penalised.

edge_compute_value_gap

edge_compute_value_gap(
    obs,
    policy_action,
    expert_action,
    critic_state,
    critic_params,
)

Compute Q(s,pi*) - Q(s,pi). Positive means expert is still better.

Returns (gap, q_policy) — q_policy is reused by the Boltzmann gate.

edge_compute_decay

edge_compute_decay(timestep, total_timesteps, decay_frac)

Linear decay: 1 -> 0 over decay_frac of training.

decay_frac=0.0 means never decay (gate stays active for full training).

edge_argmax_gate

edge_argmax_gate(gap, decay)

Deterministic: use expert whenever gap > 0 and decay > 0.

edge_boltzmann_gate

edge_boltzmann_gate(gap, decay, rng, q_policy, tau)

Adaptive: p = decay * sigmoid(gap / (tau * |Q|)), drawn on rng.

edge_fixed_gate

edge_fixed_gate(decay, rng, fixed_prob)

Fixed probability: p = decay * fixed_prob, whatever the critic's values (it scores no action), drawn on rng.

edge_lcb_scores

edge_lcb_scores(
    obs,
    policy_action,
    expert_action,
    critic_state,
    critic_params,
    beta,
    asymmetric=False,
)

Each candidate's score (score_expert, score_policy): its :func:lcb_score, the critics' disagreement penalising uncertain (OOD) candidates; the gate then compares the two.

asymmetric scores the policy arm optimistically instead (UCB, max Q + beta (max Q - min Q)), so the gate hands control to the policy where its critic is uncertain, which is where fresh on-policy Bellman anchors help most; the expert arm keeps its LCB, staying conservative about following an unreliable expert. Symmetric LCB over-penalises the policy exactly where it explores beyond the expert's tube.

edge_lcb_argmax_gate

edge_lcb_argmax_gate(score_expert, score_policy)

Deterministic argmax gate over LCB scores.

use_expert = score_e > score_p.

Compared to edge_lcb_gate (softmax), this collapses the gate to a hard threshold while preserving the LCB scoring (mu - beta*sigma) so the (gating form, scoring rule) ablation can vary one axis at a time. Used by the argmax_lcb corner of the 2x2.

edge_lcb_gate

edge_lcb_gate(score_expert, score_policy, rng, temperature)

Stochastic Boltzmann gate over LCB scores, drawn on rng.

p(use_expert) = sigmoid((score_e - score_p) / temperature).

Hard threshold (argmax) creates a self-fulfilling expert preference: expert always wins → buffer all expert → critic never learns Q for policy actions → expert keeps winning. The stochastic version ensures policy occasionally gets sampled, breaking the inertia.

Temperature → 0 recovers argmax; → ∞ recovers uniform mixing.

edge_compute_thompson_stats

edge_compute_thompson_stats(
    obs,
    policy_action,
    expert_action,
    critic_state,
    critic_params,
)

Per-action Q mean / std across critic ensemble: (mu_e, sigma_e, mu_p, sigma_p).

edge_thompson_gate

edge_thompson_gate(
    mu_e,
    sigma_e,
    mu_p,
    sigma_p,
    rng,
    temperature=1.0,
    epsilon_floor=0.0,
)

Thompson-sampling gate, with optional epsilon floor on policy picks, drawn on rng.

Treat each candidate's Q as Gaussian(mu, (temperature * sigma)^2), draw one sample per side, pick whichever is larger. Equivalent to p(use_expert) = Phi((mu_e - mu_p) / (T * sqrt(sigma_e^2 + sigma_p^2))) in expectation, but stochastic per-step (which is what we want for exploration: the gate itself injects noise rather than deferring to a fixed rule).

Symmetric: high uncertainty on either side widens the gate, never biasing it. Confident estimates dominate. With both sigmas → 0 we recover deterministic argmax.

epsilon_floor: with this probability, force the policy regardless of the Thompson outcome. Required when the expert dominates by many sigmas (Phi -> 1 -> Thompson never picks the policy -> the critic never sees policy actions in its updates -> Q for policy actions stays stale -> the gate can never flip even if the policy improves). Set carefully on brittle envs: too high crashes the agent, too low starves the policy of evaluation data. ~0.001-0.05 is a sane range.

ajax.extensions.ensemble

Critic-ensemble research features as composable :class:Extensions.

  • :class:KernelRepulsion — SVGD-style function-space repulsion between the critics of an ensemble (the critic_loss phase).

KernelRepulsion dataclass

KernelRepulsion(coef=0.1, name='kernel_repulsion')

Bases: Extension

coef times :func:q_kernel_repulsion of the critics on the critic-loss batch, added to the critic loss (REDQ's SVGD variant).

It reads the batch every replay agent's critic step passes (observations, actions, critic_params, critic_state), so it costs one more ensemble forward. Feedforward critics only: agents with memory reject extensions, so repulsion with recurrent memory is unsupported.

q_kernel_repulsion

q_kernel_repulsion(q_preds)

The mean RBF kernel between the critics' Q-functions on a batch.

q_preds is (num_critics, batch, ...); each critic's outputs form one feature vector. The bandwidth follows the median heuristic (Liu & Wang 2016, SVGD), held constant so the kernel adapts to the current spread without a confounding gradient; minimising the mean kernel pushes the critics apart in function space.

ajax.extensions.annealing

MEW, Minimum Excess Work (Adamczyk, Rojas and Kulkarni, "Thermodynamics of Reinforcement Learning Curricula", SciForDL 2026, arXiv 2603.12324; JacobHA/MEW@8f180eb): the temperature of a maximum-entropy agent annealed towards zero at a constant thermodynamic speed, in place of its own rule::

zeta(beta) = beta sum_k Cov(r_t, r_t+k)          eq. 4, eq. 8 (friction)
beta <- beta + speed / sqrt(zeta)                       Algorithm 1
alpha = 1 / beta

The covariance is that of the agent's last history rewards per env, read from its replay (or, on an agent without one, kept by MEW itself), so the temperature falls slowly while the rewards fluctuate and fast once they settle. As the authors' code (annealed_asac_temporal.py), :func:friction uses the unbiased autocovariance of each env's centred rewards summed over every lag, floored at 1e-3, and MEW steps once the agent has collected more than history steps per env. The paper's Algorithm 1 writes the step as speed / (beta sqrt(zeta) + eps) with zeta without beta; the code's form is kept. MEW steps after each update (post_update), where the authors' code steps before it: the agent's next update reads the new temperature.

MEWState

Bases: Replaceable

friction: the last step's (NaN before the first). rewards: the last rewards, (history, n_envs), on an agent without a replay, and stored: how many it has received; None on a replay agent.

MEW dataclass

MEW(speed=1e-06, history=50000)

Bases: Extension

Anneal the temperature by Minimum Excess Work (the module's docstring), in place of the agent's own temperature step. Logs mew/friction.

Parameters:

Name Type Description Default
speed float

The thermodynamic speed eta, the authors' 1e-6 (Figure 3 finds 1e-7 to 1e-4 alike on Humanoid).

1e-06
history int

The recent rewards per env the friction reads, the authors' 50,000 (HISTORY_STEPS; the paper's text says 5,000); more than 100, as the authors' update needs. A smaller replay gives all it holds.

50000

recent_rewards

recent_rewards(agent_state, state)

The last rewards, (n_envs, n), how many each env has held, and the state, the agent's last step stored on one without a replay.

post_update

post_update(agent_state, ext_state, context)

One annealing step, once more than history steps per env are collected and the history is full.

integrated_autocovariance

integrated_autocovariance(rewards)

sum_k Cov(r_t, r_t+k) over every lag k of each env's rewards (n_envs, n), each lag's mean over its n - k pairs, averaged over the envs. As the authors', by FFT of the centred rewards zero-padded to 2n (no wrap).

friction

friction(rewards, beta)

Eq. 4's friction for the inverse temperature beta, from eq. 8's reward autocovariance, floored at MIN_FRICTION.

anneal

anneal(alpha, rewards, speed)

Algorithm 1's step: the next temperature, and the friction it read.

ajax.extensions.centering

Centering any discounted agent's values as a composable :class:Extension.

  • :class:ValueCentering — its TD target minus an offset learned as the reward rate (ajax.agents.centering's rules).

ValueCentering dataclass

ValueCentering(rule=RVIBatchMean(), name='centering')

Bases: Extension

Reward centering (Naik, Wan, Tomar & Sutton, RLC 2024): the agent's TD target minus an offset that learns the reward rate, so that its values lose the constant r(pi) / (1 - gamma) and stay small as gamma nears 1. The rule is one of relative value iteration's reference functions (ajax.agents.centering): the batch mean of the next values, followed at rate 0.005 (Hisaki & Ono, ICML 2024; RVI-SAC's, the default), the mean TD error at step_size (Naik et al.'s value-based centering, step_size = eta times the critic's step size), or the target critics' value at a reference state-action pair (ASAC's Q(0, 0)). The offset starts at 0 and moves once an update, after the target has read it.

It shifts a one-step target (r + gamma V(s')); a lambda-return sums rewards over many steps, which a constant shift does not centre (PPO, APO, PQN). An average-reward agent (ASAC, APO, RVI-SAC) centres its values itself: it is not discounted, and this module refuses it. It comes last of the extensions shaping the target, so that it centres the target the critic fits. Naik et al. centre continuing tasks: on a task whose episodes terminate, every step's offset also prices an episode's length (a shorter one pays fewer), unless the target goes on through terminations (ResetCost, before it in the stack). Logs centering/offset.

check_stack

check_stack(stack)

Refuse a stack where another extension shapes the target after it: the critic would fit a target it did not centre.

reference_scorer

reference_scorer(batch)

The batch's target_value_at at one row given as tuples (None: zeros, as wide as the batch's observations and actions), or None where the batch has none.

ajax.extensions.reset_cost

The automatic reset cost as a composable :class:Extension.

  • :class:ResetCost — terminations become steps into the reset state, charged a cost learned to hold the termination rate at most at a target (ajax.agents.reset_cost).

ResetCost dataclass

ResetCost(
    target_rate=0.001,
    rate_tau=0.005,
    gain=1.0,
    architecture=("64", "relu", "64", "relu"),
    learning_rate=0.0003,
    tau=0.005,
    name="reset_cost",
    env_args=None,
)

Bases: ResetCostSettings, Extension

Hisaki & Ono's automatic reset cost (ICML 2024, Section 3.3), which their code gives SAC and ARO-DDPG as well as RVI-SAC: the agent's target no longer stops at a termination but bootstraps on the reset observation the replay stores there, and a terminated row's reward is charged c, a Lagrange multiplier that a reset critic's estimate of the termination rate drives towards keeping it at most target_rate (the settings, ResetCostSettings, are the authors'). Each update, before the agent's critics step: the charge from the current c, then one step of the reset critic (scored at the agent's next actions, one-hot for discrete ones), its rate, one Adam step of c and the reset critic's Polyak update at tau, the authors' SAC-with-reset's order.

It needs a replay, whose next observation after a termination is the reset one (an on-policy rollout keeps the final one), and a target scored at the policy's next action, where the reset critic is scored too. An average-reward agent prices terminations itself (ASAC's penalty, RVI-SAC's own reset cost): it is not discounted, and this module refuses it. Logs reset_cost/cost, reset_cost/rate and reset_cost/critic_loss.

check_stack

check_stack(stack)

Refuse a stack that reads, past a termination, what belongs to the episode that ended: an expert's next action and observation (IBRL, CriticBlend, LCBGatedBootstrap score them where the target now reads the reset observation) or an episode's return to go (Cal-QL's floor).

bind_to_agent

bind_to_agent(**agent_context)

Copy the agent's env_args, which size the reset critic.

action_count

action_count()

The number of actions a discrete agent chooses from (None for continuous ones).

ajax.extensions.instrumentation

EVarEst measurement / instrumentation as composable :class:Extensions.

The measurement code of EVAREST's evarest/rl/, foldable into any Ajax agent with a critic (the Compatibility page says which module runs where): extensions=[CriticDiagnostics(), BiasVoreDecomposition(...), ...].

Coverage

  • :class:CriticDiagnostics — eval_metrics phase, plasticity diagnostics (srank, dormant fraction, feat / weight L2 norms). Reads the agent's replay buffer (off-policy) OR agent_state.last_rollout (on-policy and incremental agents keep it for an extension reading it), auto-detected.
  • :class:BiasVoreDecomposition — eval_metrics phase, EVarEst bias^2 / Var(residual) / MSE / |bias| decomposition of the critic objective. Mirrors the math in EVAREST's loss.py / mechanism.py.
  • :class:BiasVorePenalty — critic_loss phase, the EVarEst critic objective itself. penalty(alpha) = ((1-2alpha)/alpha) * Var(q_preds - target_q) added on top of the agent's vanilla MSE.

Without a measurement batch (no replay buffer, no last_rollout yet) the eval-metric extensions emit no metrics rather than wrong numbers. The maths are intentionally kept identical to the EVAREST sources.

CriticDiagnostics dataclass

CriticDiagnostics(
    buffer=None,
    on_policy_batch=256,
    critic_loc="auto",
    concat_action="auto",
    name="conditioning_metrics",
)

Bases: Extension

At each evaluation, logs whether the critic's features are degrading: their effective rank, the fraction of dormant units, and the feature and weight norms.

These plasticity diagnostics are measured on a state batch sampled from the agent's visited-state distribution.

Reads the critic's encoder features: * critic_loc='critic' + concat_action=True ⇒ Q(obs,act) ensemble critic on critic_state. * critic_loc='critic' + concat_action=False ⇒ V(obs) ensemble critic on critic_state. * critic_loc='actor' ⇒ Q-network on actor_state (DQN, PQN), penultimate features read via the encoder_features sow.

'auto' (the default for both) reads them from the networks, never from the agent's name or the batch source: the critic branch when critic_state's network is an ensemble critic (it exposes apply_encoder_ensemble), the actor branch otherwise; on the critic branch, the action is concatenated when the critic's parameters were built on the observation and action (:func:critic_takes_action).

A replay agent's measurements sample its own replay, unless buffer names another; on-policy and incremental agents keep their last rollout for them.

bind_to_agent

bind_to_agent(**agent_context)

The agent's own replay, when no buffer is given: a replay agent passes it, and an on-policy agent has none (it keeps its rollout).

BiasVoreDecomposition dataclass

BiasVoreDecomposition(
    buffer=None,
    on_policy_batch=256,
    gamma=0.99,
    reward_scale=1.0,
    value_target_fn=None,
    name="bias_vore_decomposition",
)

Bases: Extension

EVarEst bias^2 / Var(residual) / MSE / |bias| decomposition.

Ports the math from EVAREST loss.py / mechanism.make_evarest_decomposition_metrics. The residual is reconstructed from the agent's current critic on a measurement batch sampled the same way :class:CriticDiagnostics samples (replay buffer for off-policy, last_rollout for on-policy and incremental agents).

By default it is the critic's one-step TD residual under the current policy, prediction - (reward_scale * r + gamma (1 - d) next), with the critic read from the networks (:func:_critic_kind):

  • Q(s, a) ensemble: next = min_i Q_i(s', a') - alpha log pi(a'|s'), a' ~ pi(s'), alpha the agent's temperature if it has one, else 0;
  • V(s) ensemble: next = min_i V_i(s');
  • Q-network: next = max_a' Q(s', a').

The bootstrap uses the critic's current parameters: whether and how an agent keeps a target network (SAC does, AVG and PQN do not) is its own business, as are GAE, Q(lambda) and average-reward targets. Pass value_target_fn to measure against an agent's exact target.

bind_to_agent

bind_to_agent(**agent_context)

The agent's own replay, when no buffer is given: a replay agent passes it, and an on-policy agent has none (it keeps its rollout).

BiasVorePenalty dataclass

BiasVorePenalty(
    alpha=0.5,
    coeff_override=None,
    loss_scale=1.0,
    name="bias_vore_penalty",
)

Bases: Extension

EVarEst critic objective as a critic_loss extension.

Ports the additive form of EVAREST's :func:make_evarest_loss / :func:make_evarest_ppo_loss / :func:make_evarest_td_loss. The agent's vanilla critic loss already contains MSE = bias^2 + Var(residual); this extension adds the eq. (6) extra penalty term:

penalty(alpha) = ((1 - 2 alpha) / alpha) * Var(q_preds - target_q)

so the total objective becomes MSE + ((1-2 alpha)/alpha) * Var(residual). alpha=0.5 ⇒ coeff 0 ⇒ identical to vanilla; alpha->0 is the AVEC limit (use a small alpha rather than zero). coeff_override lets callers fix the coefficient directly (e.g. to disable the extra penalty entirely without recomputing alpha). It rebuilds the residual the agent's MSE term sees from the critic_loss batch: observations, targets and the critic (critic_params and critic_state, with actions for a Q-critic; DQN's and PQN's q_state and actions), and raises on a batch without them rather than add 0.

srank

srank(feats, delta=0.01)

Kumar et al. (2021) effective rank.

Smallest k whose top-k singular values capture >= 1-delta of the total spectral mass. feats is the (batch, d) feature matrix.

dormant_fraction

dormant_fraction(feats, tau=0.025)

Sokar et al. (2023) dormant-unit fraction.

A unit is dormant when its mean-|activation| score, normalised by the layer mean, is <= tau. feats is the (batch, d) post- activation feature matrix.

critic_takes_action

critic_takes_action(critic_state, obs, act, rng)

Whether an ensemble critic reads the observation and action (an action-value critic) or the observation alone (a state-value one).

The answer is the input its parameters were built on: each candidate goes through the critic's init abstractly (shapes only, nothing is computed) and the one that rebuilds the critic's parameter shapes wins. A candidate the critic refuses is not it: a CNN encoder checks its input's width (ValueError) where an MLP builds other shapes. Where the batch comes from does not say it: AVG learns an action-value critic from its rollout, without a replay buffer.

evarest_coeff

evarest_coeff(alpha)

The eq. (6) coefficient (1 - 2 alpha) / alpha.

ajax.extensions.observe

Observation features: columns an agent appends to every observation.

Each is an :class:~ajax.extensions.base.Extension implementing the observe phase (:mod:ajax.controller): its columns join the observation whenever one arrives, in collection and evaluation alike, and are stored with it, so the actor, the critics and the replay all read them.

ExpertActionInput dataclass

ExpertActionInput(name='expert_action')

Bases: Extension

The agent's expert's action at the observation, called from the state it holds there, in agent units: raw, since it is an action. An agent learning from the expert's labels alone (DAgger) would read the label it learns: it refuses it (reward_learning). A discrete expert's index enters one-hot, over the env's action count.

ExpertStateInput dataclass

ExpertStateInput(width=0, name='expert_state')

Bases: Extension

The agent's stateful expert's state before its call at the observation (a PID's integrator), flattened to width columns (:meth:for_expert reads it off the expert).

for_expert classmethod

for_expert(expert)

The input for expert's state, as wide as it flattens.

PIDMemory

A PID's memory per env: the last error and integral, and whether the episode has had an observation (its first starts the terms afresh).

PIDTermsInput dataclass

PIDTermsInput(
    current_idx,
    target_idx,
    dt=1.0,
    integral_limit=None,
    name="pid_terms",
)

Bases: Extension

A PID controller's terms (e, I, D) for the tracking errors e = obs[target_idx] - obs[current_idx] of the env's flat observation, with sampling period dt and clamping anti-windup integral_limit (:mod:ajax.environments.pid_terms gives the discrete-time terms). Raw, so gains acting on them are a PID's; a :class:PIDPolicy actor reads them where the observation holds them (:func:pid_terms_at). Every episode starts afresh: no term carries over.

PreviousAction dataclass

PreviousAction(name='previous_action')

Bases: Extension

The action executed just before the observation, in agent units: zero at an episode's first observation, a discrete action one-hot (:func:ajax.controller.previous_action_input). Raw, since it is an action.

An agent whose memory reads it acts on its own past commands, which a deployed controller has. Ni et al. (2022)'s recurrent actor reads the previous action with the observation (twni2016/pomdp-baselines at e7c19c3, policies/models/policy_rnn.py:23-91), as their critic does (ajax.agents.recurrent).

PreviousReward dataclass

PreviousReward(name='previous_reward')

Bases: Extension

The reward the environment paid for the action executed just before the observation, raw: zero at an episode's first observation (:func:ajax.controller.previous_reward_input).

Ni et al. (2022)'s recurrent actor and critic read it beside the observation and the previous action, r[0] = 0 at an episode's start (twni2016/pomdp-baselines at e7c19c3, policies/models/policy_rnn.py:126- 131, recurrent_actor.py:101-109, recurrent_critic.py:129-135). A deployed policy then needs each reward: agent.policy's act reads it.

TrainingProgressInput dataclass

TrainingProgressInput(name='training_progress')

Bases: Extension

The share of the run done (:func:ajax.schedule.progress), the same for every env: evaluation holds the collector's, as the deployed policy holds the value at the end of training.

pid_terms_at

pid_terms_at(env_args, n_errors)

The first column of the n_errors PID terms a PID actor reads: a PIDTermsInput's among the observation features, else the observation's first (an env that puts them there).

ajax.extensions.representation

Recording how an agent's internal representations change during training.

Neuroscience embeds a population's activity into a low-dimensional manifold; the ML analogue tracks a network's hidden activations on a fixed set of states across training. :class:RepresentationProbe does the part that belongs in the compiled loop, reading the networks at chosen steps; embedding what it wrote takes minutes on a CPU, offline.

ProbeState

Bases: Replaceable

The probe set, carried rather than closed over: it stays out of the compiled program. A resumed run compares its first probe with the last.

RepresentationProbe dataclass

RepresentationProbe(
    run_directory,
    probe_interval,
    n_states=2048,
    probe_seed=0,
    layers=(),
    float16=False,
    replay_states=0,
    probe_set=None,
    env_args=None,
    buffer=None,
    name="representation_probe",
)

Bases: Extension

Reads the networks on a fixed probe set during training.

At step 0 and then at the first update on or past each multiple of probe_interval env steps, it writes one file per seed to run_directory, and logs at each evaluation the metrics of the latest probe as Representation/<layer>/<metric>. The file seed000_probe00001.npz holds step, metrics/<name>, parameters/<network>/..., layers/<layer> ((n_states, n_units), an ensemble's with a leading member axis) and values, the critic's ensemble mean, when the agent has one.

The probe set is the run directory's probe_set.npz, made there from the seed probe_seed unless it exists: runs pointed at one directory read the same states. Give probe_set to bring your own.

replay_states also keeps that many observations of a training batch at each probe after the first (replay/observations), on an agent with a replay, to set what it learns from against the probe set later.

layers keeps the layers whose name (actor/encoder/network/layers_1) holds one of the strings; empty, every one. float16 halves the activations' size, and turns values above 65504 infinite. Parameters stay float32: rounding them would swamp the small steps between two probes.

A resumed run goes on from its last probe, but the state it resumes from has each seed's own counters, so the probe's work runs at every update.

bind_to_agent

bind_to_agent(**agent_context)

Copies the agent's env_args and fetches the probe set.

Raises ValueError on observation columns or actions the env's own random rollouts cannot give the networks, and on replay_states without a replay.

read_networks

read_networks(agent_state, observations, actions, rng)

The chosen layers' activations, the critic's values and the parameters of each network read.

measure

measure(
    agent_state, state, step, rng, due, replay_filled=True
)

Reads the networks, writes the file and keeps the metrics.

pretrain

pretrain(agent_state, ext_state, context)

Takes the seed's place in the batch and the untrained network's probe: off-policy, the first update comes after the warm-up.

write

write(record, seed_index)

One probe's file, whole or not at all: a run stopped while writing leaves no file an analysis would stumble on.

probe_metrics

probe_metrics(layer, previous)

One network member's layer on the probe set, (n_states, n_units), against its activations at the previous probe.

layer_metrics

layer_metrics(layer, previous)

:func:probe_metrics, averaged over an ensemble's members (its layers have a leading member axis). An ensemble's members are not a batch of one representation: each is compared with its own past.

named_metrics

named_metrics(layers, previous)

Every layer's metrics, by the name the logger shows them under.

read_activations

read_activations(train_state, x)

The network's output at x as it reads it, and each of its activation layers' outputs by path. A network without such a layer (a CNN encoder's activations are plain functions) reports none.