Skip to content

Buffers

Off-policy agents store transitions in a flashbax replay buffer. With memory=, they store per-environment trajectories and replay sequences R2D2-style. The world models keep their own replay (DreamerV3, TD-MPC2).

ajax.buffers.utils

TwoBufferState

Bases: TrajectoryBufferState

A replay's ring, which collection writes and evicts from, beside a ring of rows that stay for the whole run (RLPD's offline buffer, DDPGfD's demonstrations). The readers of a replay see the first ring; sampling reads both (:func:sample_two_buffers).

Attributes:

Name Type Description
retained Any

The ring of kept rows, with the first ring's fields.

share Optional[float]

The share of each batch drawn from it, exact in every batch; None: each row of a batch is drawn over the rows of both rings alike, so the share falls as the first ring fills.

ReplayBatch

Bases: NamedTuple

One replay sample: its rows' fields, the optional ones None where the buffer does not store them (:func:init_buffer).

written_rows

written_rows(buffer_state)

The rows per env a ring holds: those written, up to its length.

empty_ring_like

empty_ring_like(buffer_state, rows_per_env)

An empty ring of rows_per_env rows, with buffer_state's fields.

with_retained_rows

with_retained_rows(buffer_state, retained, share)

buffer_state, its next batches also drawing from the ring retained.

sample_two_buffers

sample_two_buffers(sample, state, key)

sample(state, key) on a plain ring. On a TwoBufferState, one draw from each ring, kept row by row: the first rows of the batch from the retained ring where a share is fixed (RLPD's N/2 from each), else each row with the retained ring's share of the rows held.

n_step_rows

n_step_rows(window, gamma, reward_stats=None)

One row per window of consecutive steps (batch, n, ...): the first step's state and action, the discounted sum of the rewards from there, and the state n steps ahead or at the episode's end, whichever comes first, as the row's next state and flags. A seam ends a window as an episode's end does. bootstrap_discount is gamma to the power of the steps summed, which the target's bootstrap takes in place of gamma. With reward_stats, a reward normaliser's statistics, each reward is divided by them and clipped before the sum, as collection clips each one (SB3's NStepReplayBuffer normalises its rewards before summing them).

get_buffer

get_buffer(
    buffer_size,
    batch_size,
    n_envs=1,
    sequence_length=None,
    n_step=1,
    gamma=1.0,
)

Replay buffer factory: a trajectory buffer of buffer_size // n_envs rows per env, whose add takes the single-step (n_envs, ...) transitions the collector writes. A run's state may hold fewer, the rows it writes (init_buffer's rows_per_env): add and sample read the ring's length from the state.

sequence_length=None (default) samples rows alone, uniformly over every stored one: a row holds its next observation, so it needs no successor (flashbax's flat buffer samples a row with its successor, which leaves each env's newest row out). When set (recurrent agents), sample yields contiguous per-env sequences of that length, shaped (batch_size, sequence_length, ...). Rows alone, a TwoBufferState also draws from its retained ring (:func:sample_two_buffers); no window reads one, as a run with memory refuses the extensions that write it.

n_step above 1 samples rows as well, each one n_step steps long (:func:n_step_rows, at gamma), both rings' alike: a window never crosses a ring's write position, so a ring needs n_step rows per env first.

stored_observation_dtype

stored_observation_dtype(env_args)

The dtype a replay keeps its observations in: bool where the env's observation space is boolean (MinAtar's images) and the replay keeps the env's own observations, a quarter of float32's memory for the same values, 0.0 and 1.0 (as_read reads them back); float32 otherwise, for observations normalised or extended with feature columns and every other space.

as_read

as_read(experience)

Replayed fields as the agent reads them: observations kept as bool (stored_observation_dtype) in float32, 0.0 and 1.0.

min_replay_rows

min_replay_rows(batch_size, n_envs, sequence_length=None)

The rows per env a replay (get_buffer) holds before it can sample: a sample's own, plus one.

count_replay_rows

count_replay_rows(buffer_state)

The rows per env a replay's ring holds, and those written to it (the most over the seeds): the rows before its write position, plus the ring's once it has filled. The ring axis follows the env axis, after the seed axes of current_index.

grow_replay

grow_replay(buffer_state, rows)

A replay that has overwritten none of its rows, its ring lengthened to rows per env: row a stays at slot a, so it is the ring a replay of rows per env holds after the same rows; a ring filled exactly writes its next row past its old end. Host-side, before a resumed run.

init_buffer

init_buffer(
    buffer,
    env_args,
    include_expert_fields=False,
    actor_carry_dim=0,
    include_raw_next_obs=False,
    include_raw_obs=False,
    include_is_expert=False,
    include_return_to_go=False,
    include_next_action=False,
    include_policy_action=False,
    include_seam=False,
    rows_per_env=None,
)

Initialize the flashbax buffer state with correctly shaped dummy transitions.

Observations are flat (build_env_from_id flattens gymnax ones).

The observations are as wide as the agent's, their features (env_args.observers) included, in stored_observation_dtype: bool for a boolean space, which sampling reads back as float32. include_raw_obs, include_raw_next_obs: also keep the environment's own observation, raw_obs, and next observation (the final one where an episode ended), raw_next_obs, for an expert to read. include_is_expert: also keep whether an expert acted, is_expert. include_return_to_go: also keep a dataset row's return to its episode's end, return_to_go (a collected row's is -inf: unknown). include_next_action: also keep a dataset row's next action, its episode's next row's, next_action (NaN where unknown). include_policy_action: also keep the action the policy chose, policy_action, where it differs from the executed one (a residual policy's, for an actor fitting its own actions: IQL's). include_seam: also keep seam, set on a row the next one written does not follow in time: the last row a prefill or a dataset writes, which the first step collected comes after. For a replay reading a row's successors (:func:n_step_rows). rows_per_env: the ring's length, the rows a run writes to it (ajax.buffers.ring); None: the buffer's capacity.

A field is stored only for a reader: a row is about 40% raw observation, which a run without an expert never reads.

mean_of_written_rows

mean_of_written_rows(buffer_state, field)

The mean of a replay field over the rows written so far, every env's (all of them once the replay is full): for a 0/1 field (is_expert), the share of the rows where it is set. 0 before any row is written.

normalized_rewards

normalized_rewards(reward, stats)

The env's own reward divided by a reward normaliser's statistics, which it leaves as they are, and clipped as collection clips it; while they are empty (no step yet), the reward as it is.

get_batch_from_buffer

get_batch_from_buffer(
    buffer, buffer_state, key, reward_stats=None
)

A replay batch. The replay keeps the env's own rewards; with reward_stats, a reward normaliser's current statistics (:func:ajax.environments.interaction.reward_statistics), they come divided by them, as SB3's replay buffer does under VecNormalize.

as_replay_batch

as_replay_batch(rows, reward_stats=None)

rows, a replay's fields as an agent reads them (as_read), as a ReplayBatch: a sample's, or the rows an agent picks itself (DAgger's passes over the whole replay); their rewards as get_batch_from_buffer's.

get_sequence_batch_from_buffer

get_sequence_batch_from_buffer(buffer, buffer_state, key)

Sample contiguous sequences from a trajectory buffer (see get_buffer(sequence_length=...)) and return them time-major.

Returns a dict of arrays shaped (sequence_length, batch_size, ...), ready for the recurrent (scan-based) network path.

ajax.buffers.dataset

Transition datasets: logged or recorded transitions, kept on disk and added to a replay.

A :class:TransitionDataset holds whole episodes as flat rows in time order, each episode contiguous (the replay agents read single transitions; TD-MPC2's offline datasets, :mod:ajax.agents.TDMPC2.dataset, hold [N, L, ...] episodes for its sequence sampler):

================ ========== =============================================== field shape content ================ ========== =============================================== obs [N, O] f32 the env's own observation (not normalised) action [N, A] f32 the action taken, in agent units ([-1, 1]) reward [N] f32 the env's own reward terminated [N] bool a true terminal (no bootstrap) truncated [N] bool a time limit (bootstrap on next_obs) next_obs [N, O] f32 the next observation, the final one at an end is_expert [N] bool whether the expert chose action a_expert [N, A] f32 the expert's action at obs (NaN: unknown) return_to_go [N] f32 sum_k gamma^k r_{t+k} to the episode's end episode [N] i32 the episode's index ================ ========== ===============================================

return_to_go and episode follow from the others. return_to_go is Cal-QL's Monte-Carlo return (Nakamoto et al. 2023), cut at a time limit.

:func:record rolls an expert out, :func:export reads a run's replay, :func:fill_replay adds a dataset to one. :func:save and :func:load follow TD-MPC2's file conventions: an uncompressed .npz of plain arrays and a JSON meta string, no pickle.

TransitionDataset dataclass

TransitionDataset(
    obs,
    action,
    reward,
    terminated,
    truncated,
    next_obs,
    is_expert=None,
    a_expert=None,
    gamma=0.99,
    env="env",
)

Whole episodes of transitions (the module docstring's schema).

is_expert defaults to False and a_expert to NaN (logged data); gamma discounts return_to_go; env names the environment.

returns_to_go

returns_to_go(reward, ends, gamma)

sum_k gamma^k reward[t + k] to the end of t's episode.

record

record(
    expert_policy,
    env_args,
    key,
    n_steps,
    gamma=0.99,
    env="env",
)

The whole episodes of n_steps steps per env of expert_policy (Ajax's expert collector, so its state is kept for a stateful one): the actions in agent units, as a replay keeps them. Each env's last episode, cut by the end of the recording, is left out.

export

export(state, gamma=0.99, env='env', seed_index=None)

The whole episodes in a replay agent's replay (state as its train returned it; seed_index picks a seed), oldest first, env after env. A ring that wrapped has lost its oldest episode's start: that episode is left out. The observations are the replay's raw_obs and raw_next_obs where it keeps them (else, after a termination, next_obs is the reset observation it stores).

next_actions

next_actions(data)

Each row's next action, its episode's next row's; NaN on an episode's last row (a terminal one needs none; a time limit's is unknown).

fill_replay

fill_replay(buffer_state, data)

buffer_state with data's rows added where adding them one row per env at a time, as collection adds its own, would put them: each env's replay row gets a contiguous run of data, so a sequence replay reads its episodes whole, and its last row is a seam (init_buffer's include_seam). A replay already holding rows drops its oldest when full, as collection does.

The rows go in with one call of flashbax's trajectory add, the add a replay's add makes one row at a time, given each env's whole run: a loop of one add per row cost about 20 us per row on a GPU (20 s for a million rows).

Raises ValueError when the replay keeps fields data does not hold or of another width, when data's rows do not divide among its envs (flashbax advances every env's row together), or when they outnumber its capacity.

save

save(data, path)

Write data to path, through a temporary file renamed, so an interrupted save leaves no partial file there.

load

load(path)

The dataset :func:save wrote to path; raises ValueError on another format or version. return_to_go and episode are recomputed from the rows.

ajax.agents.recurrent

Shared machinery for agents whose networks have memory (a GRU, LSTM, transformer or Mamba; a network's memory is also called its carry).

Two kinds of agent use it: - The off-policy agents with a Q-critic (families.RecurrentReplayAgent) train on windows of consecutive steps from one environment, as Ni et al. (2022) do, with R2D2's burn-in and stored state as options (Kapturowski et al. 2019): sample_and_burnin_sequences draws the windows, and actor_dist and q_values run the networks over them. Their networks are Ni et al.'s (the section below). - PPO computes its values on a rollout with compute_rollout_values, and its losses run its networks with get_policy_on_minibatch and predict_values_on_minibatch, each for a network with or without memory (the on-policy section).

How an off-policy agent trains its memory: 1. Sample, for each environment, a window of burn_in + sequence_length + 1 consecutive steps from the replay. 2. Warm up ("burn in") each network's memory: start it from zero and run the network over the first burn_in steps with the current parameters. Training does not change these warmed-up memories (no gradient flows back into them). Ni et al. burn in nothing (burn_in 0, the default): the trained steps start from a zero memory, at a first row that reads no previous action or reward, as an episode's first does. 3. Train on the next sequence_length steps, backpropagating through time. The window's last step is never trained on: each row already stores the next observation its target looks ahead to (interaction.bootstrap_obs).

A TD target adds to the reward the estimated value of the next state: the bootstrap. With memory, that value must come from the memory that has read the rows up to the current one. Where a time limit cut an episode, that needs the time-limit section below.

A critic's memory reads each row's observation together with the action taken before it and the reward it earned, which the PreviousAction and PreviousReward features put in the observation (a run with memory adds them; without PreviousAction, the replay appends the action). The action a loss asks about (the taken one, or one the policy samples) enters after the memory, at a head between the memory and the output layer, so asking about another action never changes the memory (Critic.query_dim), as in Ni et al. (2022)'s recurrent critic (twni2016/pomdp-baselines at e7c19c3, policies/models/recurrent_critic.py:129-139 and 165-186).

RecurrentCarries

What one update needs to replay a window of S trained rows in B environments (R2D2-style): each network's warmed-up memory at the first trained row, and the rows themselves.

The memories were warmed up with the current parameters, and no gradient flows back into them: only the trained rows backpropagate through time. The rows' observations, actions and episode starts are kept because the targets replay the networks over them (the time-limit section).

with_features

with_features(extensions, features)

extensions with each of features appended where none of its kind is there.

ni_initialisation

ni_initialisation(deterministic=False)

Ni et al.'s initialisation of the layers after the memory, as an agent's ActorCritic arguments: rlkit's Mlp, hidden layers uniform in +-1/sqrt(fan_out) with biases 0.1 (torchkit/networks.py:53-57), output layers uniform in +-3e-3, kernel and bias (:66-68), the actor's in +-1e-3 (policies/models/actor.py:22, :103), its log-std layer's too (:118-121). deterministic: TD3's actor, which has no log-std layer.

previous_actions

previous_actions(actions, resets)

Each step's previous action in its episode, (T, B, A): zero at an episode start (resets) and at the sequence's first step.

zero_columns

zero_columns(x, ranges)

x with its columns in ranges set to zero.

sample_and_burnin_sequences

sample_and_burnin_sequences(
    agent_state,
    buffer,
    sample_key,
    burn_in,
    burn_target_actor=False,
    stored_state=False,
)

Sample windows and warm up every network's memory (steps 1 and 2 of the module docstring).

With stored_state (R2D2's stored state), the actor's memory is not warmed up from zero: the memory the actor had when it collected the data is read back from the replay (the actor_carry field, written by collect_experience with store_hidden). Kapturowski et al. 2019 show it goes stale less than a zero start with a warm-up. The critics are still warmed up from zero: they never run during collection, so nothing is stored for them.

Returns the trained rows as a Transition whose arrays have time as their first axis, (sequence_length, batch, ...), and the matching RecurrentCarries, which no gradient flows back into.

sample_replay

sample_replay(
    agent_state,
    buffer,
    key,
    recurrent=False,
    burn_in=0,
    stored_state=False,
    burn_target_actor=False,
)

One replay batch: transitions, or burned-in sequences when recurrent.

Returns (batch, carries). A feedforward batch keeps its pre-normalisation observations in batch.raw_obs and has no carries (None); sequences are time-major, with the carries of sample_and_burnin_sequences and no raw observations.

stored_actor_carry_dim

stored_actor_carry_dim(memory, stored_state)

Width of the actor carry a stored-state replay buffer keeps per step (R2D2 stored state), 0 when nothing is stored.

make_replay_buffer

make_replay_buffer(
    agent, n_envs, memory, buffer_size, batch_size
)

The replay buffer of an off-policy agent: transitions, or per-env trajectories sampled as windows when memory is set. The agent's fields burn_in, sequence_length, stored_state and learning_starts set it.

replayed_window

replayed_window(agent, memory)

The steps a replayed window spans, for agent's burn_in and sequence_length: the burn-in prefix, the trained segment and the bootstrap step. None without memory: the replay samples rows alone.

actor_dist

actor_dist(
    actor_state,
    params,
    obs,
    carries=None,
    *,
    bootstrap=False,
    target_actor=False,
)

The actor's action distribution at obs.

Without carries (an actor without memory), one batch of observations. With carries (an actor with memory), over a replayed window, starting from the warmed-up memory: - bootstrap False: at the rows themselves (obs are their observations), for the actor's own loss; - bootstrap True: at each row's next observation (obs are those next observations), for the critic's target (see the time-limit section). target_actor starts from the target actor's memory instead of the online actor's: TD3's target asks its target actor for the next action.

q_values

q_values(
    critic_state,
    params,
    obs,
    actions,
    carries=None,
    *,
    bootstrap=False,
    quantiles=False,
)

Every critic's Q(obs, actions), with the critics of the ensemble on the first axis (quantiles: a distributional critic's quantiles, on the last axis).

With carries (critics with memory), over a replayed window: - bootstrap False: the online critic, from its warmed-up memory, at the rows (obs are their observations, actions the ones the loss asks about); - bootstrap True: the target critic, from its warmed-up memory, at each row's next observation (obs are those next observations, actions the next actions the target asks about), see the time-limit section. The memory reads each observation with the action taken before it, appended from carries.prev_actions or, where those are None, in the observation (PreviousAction, in agent units); the asked-about action enters at the output layer. Every appended action reaches the critic in its own units (in_critic_units; predict_value converts a critic without memory's).

row_positions_with_final_observations

row_positions_with_final_observations(cut_by_time_limit)

Each row's position once a final observation is inserted after every row a time limit cut.

cut_by_time_limit (S, B) is True where a time limit, not a real termination, ended the episode at that row. Each insertion moves every later row one position further, so a row's position is its own index plus the number of final observations inserted before it.

compute_rollout_values

compute_rollout_values(
    agent_state,
    rollout,
    agent_state_at_rollout_start,
    sequence_length,
)

Before an on-policy update: the critic's values V(s_t) on the rollout and its next values V(s_{t+1}), which GAE reads.

A critic without memory values each observation on its own. A critic with memory reads the rollout in order (compute_values_from_rollout_sequence), which also moves its memory to the rollout's end and gives what the minibatches replay both networks from: the episode starts (resets, one per step) and each network's memory at the start of every sequence of sequence_length steps (actor_hidden and critic_hidden).

Returns the agent state, the values, the next values and those memories (None without memory).

compute_values_from_rollout_sequence

compute_values_from_rollout_sequence(
    agent_state,
    rollout,
    agent_state_at_rollout_start,
    length,
)

Before a recurrent PPO update: the critic's values on the rollout, its next values, the episode-start flags, and each network's memory at the start of each training sequence of length steps.

While collecting, only the actor runs, so its memory is up to date and the critic's is not. This pass runs the critic over the rollout one step at a time, from its memory at the rollout's start, which gives: - the value V(s_t) at every step; - the next value V(s_{t+1}): after reading step t, the critic is asked about step t's next observation, which is the episode's final observation where the episode ended. So a step cut by a time limit is valued with its own episode's memory, as sb3-contrib's RecurrentPPO does, not with a fresh memory on the next episode's first observation (GAE ignores the next value where the episode really terminated); - the critic's memory at the start of every training sequence, which the loss replays the critic from; - the critic's memory at the rollout's end, kept as the next rollout's starting memory. It runs step by step, as acting does, because each next value needs the memory right after its own step.

The actor's memory at the start of each training sequence is recomputed with the current parameters by one more pass (skipped when one sequence is the whole rollout, whose start memory is the stored one exactly). So no sequence starts from a zero memory in the middle of an episode, which makes truncated backpropagation through time worse than none.

Returns the agent state with the critic's memory moved to the rollout's end, the values, the next values, the episode-start flags (resets[t]: obs[t] starts an episode) and the (actor, critic) start memories.

get_policy_on_minibatch

get_policy_on_minibatch(
    actor_state, actor_params, minibatch
)

The actor's action distribution at the minibatch's observations (obs), for an on-policy loss.

An actor without memory reads each observation on its own. An actor with memory replays each of the minibatch's sequences from its memory at the sequence's start (actor_hidden, from compute_rollout_values: the live memory on actor_state has moved past this rollout), resets flagging the observations that start an episode.

predict_values_on_minibatch

predict_values_on_minibatch(
    critic_state, critic_params, minibatch
)

The critic's value predictions at the minibatch's observations (obs), for an on-policy loss: one critic, so without the ensemble's axis.

A critic with memory replays the minibatch's sequences from critic_hidden, as get_policy_on_minibatch replays the actor's.

unsupported_recurrent_options

unsupported_recurrent_options(agent_name, **options)

Raise if any expert-guidance style option is combined with memory.