Logging, evaluation and checkpoints¶
See Logging and Checkpoints and resuming.
ajax.logging.backends ¶
Where a run's logs go: backends behind one small protocol.
Every evaluation a run logs reaches each of its backends in the logging worker, a process of its own, so that training never waits on a disk or a network. The worker is spawned (CUDA is never forked), so a backend is built in the caller's process and copied into the worker: it must be picklable, and it learns about runs only through the calls below. One backend object serves every run of a train call (one run per seed).
RunInfo
dataclass
¶
What a backend is told when a run opens.
run_id: 8 base-36 characters, unique to the run (W&B's id format).
name: the LoggingConfig's run_name and the id, "
LoggingBackend ¶
Bases: Protocol
A sink for the evaluations runs log: any picklable object with these three methods, all called in the logging worker.
A backend may also have start(run), called in the caller's process for each run before training starts, for what must happen at once (W&B creates its run there, so a missing account fails before training and the run shows in the W&B UI at once). What a backend gathers in the worker stays there: to get it back, write it to a file.
A backend of your own, here one printing each step:
class PrintBackend:
def open(self, run):
print("run", run.name, "seed", run.seed)
def log(self, run_id, step, metrics):
print(run_id, step, {k: v.tolist() for k, v in metrics.items()})
def close(self):
pass
LoggingConfig(backends=(PrintBackend(), TensorBoardBackend("runs")))
It reaches the worker by pickling, so its class must be importable there: defined in a module or a script, not in a notebook cell.
log ¶
One evaluation of a run: its metrics at environment step step, each a numpy array. Metrics that are NaN (not computed at this step) are left out.
TensorBoardBackend
dataclass
¶
TensorBoard event files, a folder per run: folder/tensorboard/
WandbBackend
dataclass
¶
Weights & Biases: the wandb extra (pip install ajax-rl[wandb]) and an account. wandb keeps one open run per process, so a run's steps are sent in batches of batch_size, each batch in one init, log, finish cycle; the run is created when training starts so it shows in the W&B UI at once. With steps=False the run is created and gets no evaluation, as a W&B sweep's runs did with use_wandb and sweep=True.
ajax.logging.wandb_logging ¶
LoggingConfig and the logging worker, which passes every run's evaluations to its backends (ajax.logging.backends).
LoggingConfig ¶
Evaluation and logging for a train call: every log_frequency environment steps the agent is evaluated, train returns the evaluations, and each run (one per seed) logs them to the backends.
the LoggingBackend objects every run logs to, such as
TensorBoardBackend(folder) and WandbBackend(project, group), or one of your own (see LoggingBackend); backends=() logs nowhere, and train still returns the evaluations. Not given, use_wandb (on unless set False) and use_tensorboard (off unless set True) name them, as before; given, setting either flag as well is refused.
config: stored with each run, with the agent's run configuration merged in.
project_name, group_name: the W&B project and group of use_wandb.
run_name: the prefix of each run's name, "
run_backends
property
¶
The backends every run logs to: backends, else those the flags
name, else TensorBoard's (folder/tensorboard/
backend
property
¶
Whether a run writes anywhere, so needs the logging worker; without a backend it still evaluates (train returns the evaluations).
with_agent_config ¶
The copy a train call logs with: the agent's run configuration merged into config, and the backends named, so the flags are read (and warned about) once. A copy, so one LoggingConfig can serve several agents' runs.
new_run_id ¶
A fresh run id in W&B's format (wandb.sdk.lib.runid.generate_id:
8 random base-36 digits), without importing wandb.
start_async_logging ¶
Spawn the logging process (once; no-op if already running).
stop_logging_worker ¶
Stop the logging worker running in process and reading log_queue: the poison pill, then up to 300 s for the process to end, after which it is terminated. A worker that exited non-zero is reported.
The worker ends once it has taken the pill, after every earlier message, so its end is the end of the drain. The wait is on the process, not the queue: a worker that dies first, such as one importing a script that trains at its top level, never takes the pill, and a wait for the queue to empty never ended.
init_logging ¶
Register a run with the logging config's backends: each backend's start, if it has one, runs here, before training (W&B creates the run, so it appears in the W&B UI immediately); the worker then opens the run.
When run_seed is given (one call per seed), it is recorded alongside the
config so every run is reproducible and can be paired across conditions by
seed (see the per-run config.json written for TensorBoard runs).
iter_tfrecord ¶
Iterate raw record data from a TFRecord-style TensorBoard event file.
(Each record = [length][crc_len][data][crc_data])
load_scalars_from_tfevents ¶
Reads all scalar summaries from TensorBoard event files using only tensorboardX (no TensorFlow, no tensorboard).
ajax.evaluate ¶
ValueEstimate
dataclass
¶
An agent's critic, read for the value bias :func:evaluate returns:
value(agent_state, obs, action) is its estimate (one per env) of the
return from obs taking action, of the rewards times
reward_scale discounted by gamma, as its targets are.
The value function is part of the evaluation's program; gamma and
reward_scale are its arguments, since a sweep member's are traced
numbers (ActorCritic.train's sweep).
EpisodeRecord ¶
Bases: NamedTuple
Each episode of a rollout, one entry per episode, to its first done. cost_per_step: the mean of minus the reward over the episode's steps, every one of them. trips: the steps the plant tripped on, as the env reports them (info["tripped"]); NaN from an env reporting none, whose count is unknown, not zero.
evaluation_physics ¶
The physics engine the evaluation of env's task steps: the training
env's, but MJX's pure-JAX physics in place of MuJoCo Warp on a device
that is not a GPU (an asynchronous evaluator on the CPU,
LoggingConfig.evaluation_device), where Warp cannot run. Both step
the same model; tasks with contacts drift apart over an episode.
setup_environment ¶
setup_environment(
env,
env_params,
num_episodes,
norm_info,
*,
action_repeat=1,
episode_length=None,
)
The training env's stack, rebuilt for evaluation (gymnax or brax).
Ajax's own layers come off (:func:~ajax.environments.create.strip_ajax_wrappers)
and go back on as training composed them
(:func:~ajax.environments.create.add_ajax_wrappers): the clip to a
continuous action space's bounds, the observation normaliser frozen at
norm_info (None: no normaliser) and applied to the observations
only where training applied it, rewards never normalised. The task
under them -- the user's wrappers, the flattening -- is kept as trained
on (gymnax).
brax / playground tasks are rebuilt from their id with num_episodes
parallel envs, and the wrappers over the stack the builder returned go
back over the rebuilt one (_rebuild_for_evaluation, on the physics of
evaluation_physics). episode_length (simulator steps) and
action_repeat are the training env's; the defaults are None ->
the env's native episode length, falling back to 1000, and repeat 1.
gymnax envs do not support action_repeat > 1.
step_environment ¶
step_environment(
mode,
env,
env_params,
recurrent,
actor_state,
continuous,
expert_policy=None,
agent_state=None,
controller=None,
value_estimate=None,
command=None,
norm_info=None,
)
Return a pure function stepping the evaluation (an :class:_EvalCarry).
Each step acts as the evaluated policy acts (ajax.policy.make_act: the
controller, the actor, the expert in agent units and the choosers, on
keys derived from the carry's), then steps the env on the executed
action mapped onto its bounds (:func:agent_action_to_env), as in
collection. The expert's state is tracked statefully, as collection
tracks it, and restarts with each episode.
value_estimate: the critic's estimate at the actor's input and the action collection stores, each step: the executed action in agent units, the actor's (the gains') under gain mode.
command: a command-conditioned actor's (see :func:evaluate): the
actor reads command.actor_input(obs, c), and each step's reward, in
the agent's units (norm_info, :func:normalised_reward), and end
update c.
step_environment_expert ¶
Step function for the expert's own rollout, called as the agent's
rollout calls it (:func:step_environment): a stateful expert (one with
init_state) as expert_policy(state, obs) -> (action, state), a
stateless one as expert_policy(obs) -> action, in agent units and
mapped onto the env's bounds. A discrete expert's action index comes as
an (n, 1) column, as a replay keeps it; the env takes (n,).
evaluate ¶
evaluate(
env,
actor_state,
num_episodes,
rng,
env_params,
recurrent=False,
gamma=0.99,
norm_info=None,
avg_reward_mode=False,
expert_policy=None,
max_eval_steps=None,
agent_state=None,
controller=None,
eval_expert_policy=None,
value_estimate=None,
command=None,
)
Evaluate the actor's deterministic policy on num_episodes
episodes; with expert_policy (the training expert, which builds the
actor's input) the expert's return too, that of eval_expert_policy
when given, on the same episodes (the same reset and key). The experts
speak env units: they are read in agent units here
(:class:ExpertInAgentUnits; an agent's are already).
command evaluates a command-conditioned actor (UDRL's desired
return and horizon): command.initial(agent_state, num_episodes) is
each episode's first command, the actor reads command.actor_input(obs,
c), and command.update(c, reward, done) follows each step, the
reward in the agent's units, normalised as in training: the units of
its targets.
Returns the mean return, entropy, average reward (avg_reward_mode),
value bias (value_estimate), episode length and expert's return,
each NaN without what it needs. The average reward is APO's reference's
(:func:_reward_rate), on 10 envs of 1,000 steps whatever
num_episodes is: these envs when there are 10, at no step more past
their time limit, 10 more otherwise. The value bias is the mean over the
evaluated steps of the critic's estimate (:class:ValueEstimate) minus
the discounted return realised from the step, in the critic's units:
the rewards normalised as in training (:func:normalised_reward) and
scaled. A recurrent critic's memory is not run here: NaN then. A
controller with choosers (step_environment) adds a seventh: the share of
the evaluated steps they handed the expert.
policy_episodes ¶
policy_episodes(
env,
actor_state,
num_episodes,
rng,
env_params,
recurrent=False,
norm_info=None,
expert_policy=None,
agent_state=None,
controller=None,
)
The record of each of num_episodes episodes, one per env, of the
policy :func:evaluate runs on rng. A diverged episode, whose
rewards went NaN, costs inf: what the policy did, where a NaN cost means
a broken measurement.
The env's draws come from rng alone: the rollout splits its own key
before it acts, and an action's draws derive from that key by name
(:func:ajax.policy.make_act), so a policy sampling its action moves
none of them.
expert_episodes ¶
:func:policy_episodes of the expert alone, on the same reset and the
same steps for the same rng; it speaks env units
(:class:ExpertInAgentUnits). Its NaN costs stay NaN: a reference that
diverged is a broken baseline, which the score refuses.
evaluate_policy ¶
Mean return and mean length of one episode in each of num_episodes envs.
The evaluation protocol of the agents that own their collection (the
world-model agents, DESIGN ยง5.4), for a stateful policy with the row
collector's protocol policy_fn(carry, obs, is_first, key) -> (action,
carry, extras) (extras ignored):
- the env is rebuilt through :func:
setup_environmentwithnum_episodesparallel envs and the trainingaction_repeatand episode length; actions go through :func:ajax.environments.utils.agent_action_to_env, as in the row collector, so train and eval act on the env identically (the env's clip to its bounds is then a no-op); - the envs are reset with
key(the same reset-key derivation as :func:evaluate, so both see the same initial states for one key); - the policy starts from
init_carry_fn(num_episodes)(a zero carry) withis_firstset on the first step only; - every env runs exactly one episode: a scan over the episode length in
agent steps (:func:
ajax.environments.utils.agent_episode_length) with rewards and lengths masked after each env's first done; - every observation carries its features (env_args.observers) at the progress the collector of agent_state holds, frozen as evaluate holds it.
Preconditions (they raise): the training env does not normalise
observations or rewards (the rebuild is the raw env, see
:func:ajax.environments.row_collector.check_unnormalized_env), and
env_params describes one system (per-env, batched params cannot be
rebuilt with num_episodes envs; evaluate a nominal system instead).
policy_episode ¶
One episode under a trained policy's parts, kept step by step for
drawing: the env it ran on (:func:policy_returns' rebuilt one, a
single copy), that env's state at the reset and after every step but
the one ending the episode (whose state is already the next episode's),
each with its leading axis of one env, and every step's reward. It
stops at the episode's end, or after max_steps steps. The steps run
one by one from Python, each compiled: the states are kept, which a
compiled loop would have to hold for the longest episode possible.
snapshot(env, state) replaces each kept state by what it returns,
taken when the env stands there: a Gymnasium env's state lives in its
simulator, which the next step moves.
policy_returns ¶
The return and the length of one episode in each of num_episodes
envs, under a trained policy's parts (ajax.policy.PolicyParts,
from agent.policy_parts() on one seed's state): what
agent.evaluate runs.
The env is rebuilt raw (no normalisation: the parts normalise as the
agent does) with the training action repeat and episode length, and
reset from key. The parts act in the env's units from the env's own
observations, starting an episode on the first step; every env runs one
episode, its rewards and steps counted until its first end.
Evaluating on another device¶
See Evaluating on another device.
ajax.async_evaluation ¶
Evaluation in a thread of its own, on a device of its own, while training
goes on: LoggingConfig(evaluation_device=...).
A logged run evaluates between chunks of training
(:func:ajax.perf_utils.build_chunked_train). With an evaluation device, the
evaluation program still computes what it reads of training (the update's
metrics, the extensions' metrics, the evaluation count) and hands the host
the rest: the state without its replay, the key of its timestep
(:func:ajax.log.evaluation_keys) and those metrics. Training continues at
once. A thread scores every seed's policy of that timestep together on the
device, then sends each seed's row to the logging worker under its own
timestep. The train call waits for the last one and writes the scores into
the rows it returns. They are the inline evaluation's: the same policy at the
same step, on the same keys, up to floating-point rounding.
On a GPU, two programs of one process run one after the other, so the device
is another GPU or the CPU. On the CPU, a MuJoCo Warp run is evaluated on MJX's
pure-JAX physics (:func:ajax.evaluate.evaluation_physics).
AsyncEvaluator ¶
Scores the evaluations of one train call of n_seeds seeds on
device, in a thread, and logs each seed's row through log_fn(row,
seed index). An evaluation is scored once every seed's has come.
hand_over ¶
In the evaluation program, in place of logging metrics: when
flag is set, hand the host what scores(agent_state, key,
*also) reads, and the metrics to log with its scores. Under the
seed vmap the seeds share one call to the host, which hands over each
seed's (:func:ajax.perf_utils.callback_per_member).
score ¶
Score one evaluation of every seed together, then log each row.
wait ¶
Wait for every evaluation handed over (after the programs that
hand them over have run: :func:jax.effects_barrier), then return
their scores, each (seeds, evaluations), and start afresh.
without_replay ¶
agent_state with its replay and stored rollouts set to None, on
the state and on its collector: an evaluation reading one fails as it
traces instead of scoring on a stand-in.
ajax.checkpoint ¶
Checkpoint save/restore for Ajax agents.
Serializes the pytree data of a BaseAgentState (arrays, counters,
and other leaves) while discarding non-data fields such as optax
GradientTransformation closures and flax apply_fn callables.
Those closures are rebuilt at load time by re-initializing a skeleton
state from the same agent config; the loaded data is then grafted onto
the skeleton via flax.serialization.from_state_dict.
Typical resume flow (resume in tests/probing/runs.py runs it):
skeleton = agent.train(seed=seeds, n_timesteps=0) # init only
if checkpoint_exists(path):
skeleton = restore_into(skeleton, path)
final = agent.train(..., initial_state=skeleton, ...)
save_checkpoint(final, path)
load_checkpoint(agent, path) builds that skeleton itself, for as many seeds as the file holds. agent.save(state, path) also writes the agent's class and its plain constructor arguments, from which load(path) builds the agent.
agent_record ¶
What agent.save records of agent: each constructor argument as
the agent was given it (its run config), when it is plain; the others
(a prebuilt environment, extensions, an expert policy) by name only.
save_checkpoint ¶
Save the pytree data of state to path. Atomic write. With
agent, its record too (:func:agent_record), which :func:load
builds the agent from.
restore_into ¶
Load path and graft its data onto skeleton.
skeleton is a freshly-initialized agent state with the same
structure as the saved one. The optimizer transformations and apply
functions come from skeleton; only the pytree data (params,
optimizer mu/nu/count, buffer arrays, rngs, counters) is replaced.
load_checkpoint ¶
The state saved at path (save_checkpoint(state, path)), restored into agent, an agent built with the same arguments: restore_into on a 0-step train of as many seeds as the file holds, which rebuilds what the file does not keep (the optimisers' update rules, the networks' functions). It refuses what restore_into refuses. train_options go to that train call: a run whose options shape its update rule (APG's learning-rate schedule over total_timesteps, its optimiser kept on resume) passes them, so the loaded state resumes as the run would have gone on.
load ¶
The agent and the state that agent.save(state, path) wrote, as
(agent, state).
The agent is built from the recorded arguments, then the state is
restored into it (:func:load_checkpoint, given train_options).
arguments are constructor arguments: those the file could not store
(objects: a prebuilt environment, extensions, an expert policy) must be
passed again, and any other given here replaces the recorded one.
agent_class: the class to build, which must be the one saved
(PPO.load(path)); None: the class of that name exported by ajax.
Raises ValueError on a file save_checkpoint wrote without an
agent, on another class's file, and on an argument to pass again that
is missing.