Skip to content

Algorithms

ndm_gym.algos

Learning algorithms on the shared pipeline, selected by --algo.

world_model_from_args

world_model_from_args(a: dict)

The (untrained) world model a run with training arguments a (a checkpoint's args) builds.

ndm_gym.algos.common

Machinery shared by the algorithms: world-model fitting on replay windows and imagination start states.

Algo

Algo(
    args,
    kin: ArticulationKinematics,
    motion: MotionLib,
    mdp: MDP,
    dev: str,
)

One learning algorithm on the shared pipeline.

The base class owns the world model, the policy and their optimizers, fits the world model on k-step replay windows, and samples imagination start states. Subclasses define make_world_model, setpoint (policy output -> normalized joint setpoint sent to the simulator), wm_loss, policy_update and checkpoint state.

is_residual classmethod

is_residual(a: dict) -> bool

Whether a run with training arguments a (vars(args); also a checkpoint's args) outputs offsets about the reference pose.

optimizer_kw

optimizer_kw(lr: float) -> dict

Adam's keyword arguments (adam_kwargs; one call per optimizer: with --update_graphs its own learning rate).

optimizer_step

optimizer_step(opt, ok: Tensor)

--no_sync: opt's step gated on the device (gated_step).

ema_update

ema_update()

The policy average's step without a host read (ema_step).

world_model_cls staticmethod

world_model_cls(a: dict) -> nn.Module

The world model for training arguments a (vars(args); also a checkpoint's args).

setpoint

setpoint(a: Tensor, f: Tensor) -> torch.Tensor

Normalized joint setpoint for policy output a at reference frame f (target frame f + 1).

log_lr

log_lr(lr: float) -> float

The learning rate train.py's log reports: its schedule's lr.

wm_loss

wm_loss(
    S_hat, w: dict
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]

(loss, k-step error for logging, per-window error for prioritized sampling) of the predicted windows S_hat against the replay windows w.

policy_update

policy_update(buffer: ReplayBuffer) -> tuple

(policy loss, value loss, imagined reward, grad norm, imagined survival); nan where not defined.

update_pi_avg

update_pi_avg()

--pi_ema: one step of the policy's moving average, after a policy update (a no-op without it).

update_wm_norms

update_wm_norms(S0, S1, a, xi)

Fit the world model's input and output normalizers on simulator transitions (states S0 -> S1, setpoints a, context xi).

update_pi_norms

update_pi_norms(o, g)

Fit the policy's observation and goal normalizers on the observations and goals of collection.

wm_probe

wm_probe(S_hat, s1, mask)

Model-independent k-step prediction error for logging: tracked-body position (m) and joint angle (rad).

wm_update_graphable

wm_update_graphable(buffer: ReplayBuffer)

wm_update for --update_graphs: no host synchronization, so the whole update (sampling, mirror, rollout, loss, backward, clipping, optimizer step) can be captured in a CUDA graph. Returns (loss per step, k-step error).

wm_updates_presampled

wm_updates_presampled(
    buffer: ReplayBuffer, probe: bool = False
)

--wm_presample (XMimic): the iteration's --wm_batches world-model updates on windows drawn, read and mirrored in one pass before the first (ReplayBuffer.sample_windows_multi: the draws of --wm_batches calls of sample_windows in their order, so the same windows as one update at a time while the fit itself draws nothing, i.e. without --wm_input_noise and --wm_smooth_w). No host synchronization: also what --update_graphs captures, as one graph for all the updates. Returns the last update's (loss per step, k-step error), with probe its wm_probe too.

wm_update

wm_update(buffer: ReplayBuffer, probe: bool = False)

One world-model step on a batch of replay windows. Optional (--wm_fail_windows p): a fraction p of the windows ends in the last --wm_fail_window steps before the replay's terminations, while it holds any.

mark_static_tensors

mark_static_tensors()

For CUDA graphs of the imagination (--pi_cudagraphs): the tables it reads from plain objects (motion library, task, kinematics, the algorithm's own) are static inputs, which the graphs would otherwise copy at every replay (module parameters and buffers are static already).

sample_valid_starts

sample_valid_starts(buffer: ReplayBuffer, B: int)

Replay start states (and their observation histories) whose clip has H more frames. Optional trick (--imag_fail_starts p): a fraction p of them comes from the last --imag_fail_window steps before the replay's terminations, while it holds any, so that the policy also rehearses the states it failed from; how many did is kept in self.fail_starts for the training log.

sample_valid_starts_nosync

sample_valid_starts_nosync(buffer: ReplayBuffer, B: int)

sample_valid_starts without reading the valid count on the host (--no_sync; BlinkMimic): 2B candidates, stable-sorted valid first (only starts within H frames of a clip's end are invalid, under 1%), the first B kept.

perturb_start

perturb_start(S)

Optional imagination trick: Gaussian horizontal root-velocity kicks on the start states (m/s), so the policy also learns to recover. Off (exact no-op, no RNG draw) at --imag_start_perturb 0.

imag_noise

imag_noise(o_hist: Tensor) -> torch.Tensor

--imag_hoist: the observation noise of the rollout's steps, (H, B, obs), in one draw (MDP.add_noise's per step) for the start histories o_hist (B, hist, obs).

start_obs_history

start_obs_history(h: dict) -> torch.Tensor

Noisy observation history of the start states, as the deployed policy would see it.

lr_at

lr_at(t: float, lr: float, decay: float) -> float

Cosine decay to 0.03x over decay, then constant (t and decay in iterations or in training hours).

set_lr

set_lr(opt: Optimizer, lr: float)

Every parameter group's learning rate; a tensor one (capturable Adam, --critic_cudagraphs) is written in place, for the CUDA graph that reads it.

reference_setpoints

reference_setpoints(
    motion: MotionLib, default_q: Tensor, alpha: Tensor
) -> torch.Tensor

Reference pose of every frame as a normalized joint setpoint (residual policies add their offsets to it).

adam_kwargs

adam_kwargs(
    lr: float, dev, update_graphs: bool, adam_kw: dict
) -> dict

Adam's keyword arguments: with --update_graphs the capturable fused kernel and a device learning rate, a new tensor at each call. Each optimizer takes its own call: optimizers built with one tensor would share their learning rate, which set_lr writes in place (--wm_lr would set the policy's too).

wm_optimizer

wm_optimizer(
    wm: Module,
    args,
    opt_kw: dict,
    capturable: bool,
    adam_kw: dict,
)

The world model's optimizer (LAFAN1 and muscle training): Adam with opt_kw (adam_kwargs, a call of its own) on all its parameters, or with --wm_opt muon MuonAdam (Adam's betas 0.9, 0.999; capturable: --update_graphs; adam_kw: --fused_adam): Muon on the hidden matrices of the MLP, or on those of the RigidFormer (its network's hidden_matrices, the blocks' weight matrices: RigidFormerNet, the muscle character's MuscleRigidFormerNet), Adam on the rest.

gated_step

gated_step(opt, ok: Tensor)

--no_sync: opt's step where the 0-dim bool ok holds, skipped on the device elsewhere (parameters and all optimizer state unchanged): the fused Adam's found_inf, MuonAdam's gate. The gradients must be finite.

zero_nonfinite_grads

zero_nonfinite_grads(params, finite: Tensor)

--no_sync: every gradient of params set to zero where the 0-dim bool finite is false (a gated step needs finite gradients), without a host read.

ema_step

ema_step(pi_avg, pi: Module, decay: float)

The policy average's step (AveragedModel.update_parameters, the same lerp) without its host-side test of the first call; the training loop advances the host-side counter n_averaged (--update_graphs).

survival

survival(d: Tensor) -> torch.Tensor

cumprod(1 - d, 0) as a loop of products (the graphable updates': cumprod's backward tests for zeros on the host).

update_in_place

update_in_place(norm, x)

norm.update(x) for CUDA graphs, which read the normalizer's statistics where they were captured: RunningNorm.update replaces its variance and count tensors, so the new values are written into the old ones.

cap_rollout_grads

cap_rollout_grads(S: tuple, k: float) -> tuple

Optional imagination trick (--bptt_clip_k k), applied to the state after every imagined step: identity in the forward pass; in the policy's BPTT, each rollout's gradient on each state component is scaled down to at most k times the median over the batch, so that a few rollouts whose gradients grow through the world model cannot dominate the policy gradient. The other rollouts' gradients are unchanged.

clip_rollout_policy_grads

clip_rollout_policy_grads(
    pi: TrackingPolicy, taps: list, k: float
) -> int

Optional trick (--pi_rollout_clip k), after the BPTT's backward pass: each rollout's part of the policy gradient, sum_t J_tb^T abar_tb over the horizon (rollout_grads), is scaled down to at most k times the median over the rollouts, so that a few rollouts whose gradients grow through the world model (up to 100 times the median on the study's checkpoints) cannot dominate the update. A rollout's size is measured in the policy's output: the norm over the horizon of its adjoints abar_tb, the gradients that reached the output (taps: per imagined step, the policy's inputs (obs history, goals) and a zero tensor added to its output, whose .grad is abar), which ranks the rollouts as the parameter-space norm does (log correlation 0.84-0.85; 3 of 4 of the largest 1% the same). The backward pass has accumulated all rollouts' parts in the parameters' .grad; the policy runs again on the clipped rollouts' inputs and adds (w_b - 1) times their parts, w_b = k median / size_b < 1. Rollouts without a gradient do not count in the median. Returns the number of clipped rollouts.

clip_rollout_output_grads

clip_rollout_output_grads(
    rerun, outs: list, k: float
) -> int

clip_rollout_policy_grads for a policy of any inputs: outs per imagined step the zero tensor (B, J) added to the policy's output, whose .grad is the output's adjoint, and rerun(idx) the policy's output again on the steps' inputs of the rollouts idx, steps outer ((H * len(idx), J), detached inputs). Returns the number of clipped rollouts.

smoothness_penalty

smoothness_penalty(
    net: Module,
    x: Tensor,
    eps: float,
    n: int,
    keep: Tensor | None = None,
) -> torch.Tensor

--wm_smooth_w's penalty of a world model's network net (normalized inputs to normalized outputs) at its normalized inputs x (N, D): the mean over the rows (those where keep (N,) holds, if given) and n random unit directions u of ||net(x + eps u) - net(x)||^2 / eps^2, both passes in fp32 (Algo._wm_smoothness).

check_smoothness_args

check_smoothness_args(args)

--wm_smooth_w's arguments as Algo checks them; the defaults where an entry point's arguments lack them.

decay_rollout_grads

decay_rollout_grads(S: tuple, lam: float) -> tuple

Optional imagination trick (--bptt_decay lam), applied to the state after every imagined step (after --bptt_clip_k's cap): identity in the forward pass; in the policy's BPTT the state's gradient is multiplied by lam, so that a loss d imagined steps after an action reaches it with weight lam^d (every path back through the states, the world model's and the observations' alike). Gradients that grow through many steps of the world model count less; the losses next to an action keep their relative weights.

ndm_gym.buffer

Fixed-size GPU replay buffer of simulator transitions, laid out as (time, env).

ReplayBuffer

ReplayBuffer(
    T: int,
    N: int,
    device: str,
    fields: dict | None = None,
    priorities: bool = True,
)

fields: name -> (shape, dtype) of a transition, FIELDS (LAFAN1 tracking) by default; window_keys: the fields a k-step window returns; priorities: keep the window priorities of sample_windows_prioritized (without them, add skips their upkeep, a reduction over the whole buffer at every step).

add_device

add_device(tr: dict)

add at the device-side write head (train.py --collect_graph: capturable): advances ptr_t and size_t on the device; advance_host advances the host's ptr and size after each replay.

sample_windows

sample_windows(B: int, k: int)

k-step windows; returns dict of (B, k, ...) tensors and a validity mask (B, k).

sample_windows_multi

sample_windows_multi(n: int, B: int, k: int)

n batches of sample_windows(B, k) in one pass (train.py --wm_presample; XMimic): the same draws in the same order (each batch's start times, then its environments), one read of the replay for all of them. Returns a dict of (n, B, k, ...) tensors and the masks (n, B, k); batch i is what the i-th of n calls of sample_windows returns while nothing else draws random numbers in between.

sample_windows_prioritized

sample_windows_prioritized(B: int, k: int, alpha: float)

Like sample_windows but with start probability proportional to priority^alpha (no importance weighting: emphasizing hard transitions is the point). Also returns the starts for update_priorities.

sample_start_points

sample_start_points(B: int)

B start points drawn uniformly: their age (0 = oldest) and env.

sample_starts

sample_starts(B: int, hist: int)

Start points for imagination plus the indices of their observation history (oldest first).

at

at(key: str, age: Tensor, env: Tensor) -> torch.Tensor

Field key at age (0 = oldest) of env.

terminations

terminations(failed)

Age (0 = oldest) and env of every stored termination, and the age of its episode's first stored state.

failed(s1, f) -> bool: which of the given done transitions are terminations rather than time-outs.

pre_failure_points

pre_failure_points(B: int, window: int, failed)

B start points (age, env) from the last window steps before the replay's terminations: a termination drawn uniformly, then a state among the window up to and including its last one, inside its episode and the buffer. None while the replay holds no termination (failed as in terminations).

pre_failure_starts

pre_failure_starts(B: int, hist: int, window: int, failed)

B start points like sample_starts from pre_failure_points; None while the replay holds no termination.

pre_failure_windows

pre_failure_windows(
    B: int,
    k: int,
    window: int,
    failed,
    generator: Generator | None = None,
)

Up to B k-step windows like sample_windows whose last step lies in the last window steps up to and including a termination: a termination drawn uniformly, then the window's end, inside its episode and the buffer (terminations with a shorter episode are skipped). None while the replay holds none that fits.

windows_at

windows_at(t0: Tensor, env: Tensor, k: int)

The k-step windows starting at age t0 of env, as sample_windows returns them.

starts_at

starts_at(age: Tensor, env: Tensor, hist: int)

The states at age (0 = oldest) of env, with the indices of their observation history.

ndm_gym.algos.supertrack

SuperTrack (Fussell, Bergamin, Holden, TOG 2021) on the shared pipeline.

Only the algorithm differs from SuperMimic. The world model predicts accelerations that are integrated with semi-implicit Euler (paper ยง3.4, Eq. 8-12; :mod:ndm_gym.worldmodels.accel) and is fit with an L1 window loss on world-space body states (Alg. 1). The policy outputs PD offsets about the reference pose and is trained by BPTT through the frozen world model on an L1 tracking loss in root-local space (ยง3.3, ยง3.5, Alg. 2), plus world-space root position and rotation terms as in the paper's ยง4.2 extension for tasks that score global drift. There is no reward, no survival weight and no critic. Added on top of the paper (each with an ablation flag): the task's own action-rate and joint-limit penalties, at the reward's ratio to its full tracking score. Optional tricks behind flags (off by default) include a failure penalty on imagined steps past the task's termination thresholds (--st_fail_w).

ReferenceLocal

ReferenceLocal(
    motion: MotionLib,
    kin: ArticulationKinematics,
    chunk: int = 65536,
)

Local(K) of every reference frame over all bodies, precomputed once, plus the reference root pose and the reference center-of-mass features.

LossBalancer

LossBalancer(n: int)

Bases: Module

Fixed term weights, set once so that every term contributes 1 at the start of training (paper ยง3.4-3.5).

calibrated property

calibrated: bool

ready, read from the device only until it is set: it never changes back (a loaded state is read again), so the check at every update does not synchronize with the GPU.

SuperTrack

SuperTrack(args, kin, motion, mdp, dev)

Bases: Algo

imag_action_noise

imag_action_noise(B: int) -> torch.Tensor

--imag_hoist: the exploration noise of the rollout's steps, (H, B, J), in one draw (_st_imag_step's per step).

policy_update_graphable

policy_update_graphable(buffer: ReplayBuffer)

policy_update for --update_graphs: the same update without host synchronization, so that all of it (start sampling, imagination, losses, backward, clipping, the optimizer step skipped on the device for a non-finite gradient, the policy average's step) can be captured in one CUDA graph. The loss balancer is calibrated by the first, eager update; the survival products of --st_fail_w are a loop (cumprod's backward tests for zeros on the host).

local_features

local_features(bp, bR, bv, bw)

Local(X) of SuperTrack Eq. 1-7 for world-space body states (..., B, ...) whose body 0 is the root: root-frame positions, velocities, 6D rotations, angular velocities, body heights, and the up vector.

com_features

com_features(kin: ArticulationKinematics, body, p, R)

Whole-body center of mass relative to the root and its velocity, both in the root's heading frame: (N, 6).

body_errors

body_errors(
    body, S, ref: tuple, f: Tensor
) -> list[torch.Tensor]

Per-element absolute tracking errors of every term in TRACK_TERMS, (N, n_term) each, from all-body FK of S.

track_terms

track_terms(
    kin: ArticulationKinematics, S, ref: tuple, f: Tensor
) -> torch.Tensor

L1 tracking errors of states S against reference frames f, summed within each term: (N, len(TRACK_TERMS)).

wm_window_terms

wm_window_terms(
    kin: ArticulationKinematics,
    S_hat,
    S,
    squared: bool = False,
) -> torch.Tensor

L1 (or, with squared, L2) errors of world-space body positions, velocities, rotations (log) and angular velocities: (N, 4).

ndm_gym.algos.supermimic

SuperMimic (Liao et al., CoRL 2026; arXiv 2610.28480): BPTT of the imagined tracking return through the frozen world model, with a soft survival weight and a critic bootstrap beyond the horizon (paper ยง3, Eq. 1-3).

SuperMimic

SuperMimic(args, kin, motion, mdp, dev)

Bases: Algo

policy_update_graphable

policy_update_graphable(buffer: ReplayBuffer)

policy_update for --update_graphs (BlinkMimic's --cuda_graph): the same update without host synchronization, so that all of it (start sampling, imagination, objective, backward, clipping, the optimizer step skipped on the device for a non-finite gradient, the policy average's step, the critic's targets and minibatch steps) can be captured in one CUDA graph. The survival products are a loop of multiplications (cumprod's backward tests for zeros on the host). Returns (policy loss, value loss, imagined reward, gradient norm, imagined survival).

ndm_gym.algos.blinkmimic

BlinkMimic (F. Chen, 2026; https://github.com/fuyichen0725/blinkmimic): SuperMimic's objective with InstantTrack's and its own training changes.

--algo blinkmimic is --algo supermimic with BlinkMimic's released recipe (PRESET, their PRESET[main] in this library's options); it is not a separate algorithm. Every change is an option of its own, off by default. The policy average, Muon, mirror augmentation, failure-focused and evaluation-guided resets (algos/eprobe.py) and the policy's learning-rate multiplier apply to any algorithm; the semi-implicit world model and the contact reward to SuperMimic. docs/blinkmimic.md maps BlinkMimic's changes to the options and lists what is not ported.

Mirror

Mirror(device: str)

--wm_mirror (BlinkMimic): left-right mirror images of the G1's states, setpoints and sim context. The reflection M = diag(1, -1, 1) of the world's y axis maps positions and linear velocities to M x, rotations to M R M, angular velocities (pseudo-vectors) to -M w, and every joint to its left/right partner, the sign flipped for roll and yaw joints (and the waist's roll and yaw). In xi the joint offsets are mirrored as joints and the torso's lateral center-of-mass offset changes sign. Setpoints mirror as joints since the default pose and the action scales are symmetric.

windows

windows(w: dict, n: int, stacked: bool = False) -> dict

Replay windows (ReplayBuffer.sample_windows) with the first n replaced by their mirror images. stacked: several batches of windows (ReplayBuffer.sample_windows_multi), the first n of each.

Graphed

Graphed(fn, ready, name: str, warmup: int = 3, stream=None)

--update_graphs (BlinkMimic's --cuda_graph): fn runs eagerly until ready(); then eagerly on a side stream for warmup calls, is captured as a CUDA graph on the next call and replayed from then on. Each call is one update; its outputs are cloned out of the graph's memory. stream (train.py --layout, algos.layouts): the capture's stream, one of the update's own device where that is not the first to capture (None: torch's default capture stream).

PolicyLR

PolicyLR(args: Namespace)

--pi_lr_mult with --lr_decay_ret, --lr_decay_len, --lr_decay_by (BlinkMimic): the policy's learning rate is the schedule's times a multiplier. From the log row where the logged training return first reaches --lr_decay_ret (or at --lr_decay_by), the multiplier ramps linearly to 1 over --lr_decay_len iterations. train_muscles, whose log has no normalized return, ramps at the deadline --lr_decay_by alone.

at

at(it: int) -> float

The multiplier at iteration it.

observe

observe(it: int, ret: float | None) -> str | None

At a log row, it iterations done and the logged training return ret (None: no return, the deadline alone): the trigger's message when it fires (once), else None.

state_dict

state_dict() -> dict

The trigger's iteration for a checkpoint (nothing without a trigger).

add_blinkmimic_args

add_blinkmimic_args(parser: ArgumentParser)

BlinkMimic's options (off by default). Tools that rebuild a run's arguments add them after add_speed_args, as ndm_gym.train.parse_args does.

expand_preset

expand_preset(argv: list[str]) -> list[str]

argv with --algo blinkmimic (or --algo=blinkmimic) replaced by --algo supermimic --preset blinkmimic and PRESET, before the other arguments, which take precedence (the preset's switches cannot be turned off); other command lines are returned unchanged.

check_args

check_args(args: Namespace)

The BlinkMimic options' constraints on a run's arguments (ndm_gym.train); raises ValueError.

check_resume

check_resume(ck_args: dict, args: Namespace)

A resumed run must have the checkpoint's optimizers, policy average and world model; raises ValueError.

reset_kwargs

reset_kwargs(args: Namespace) -> dict

The simulator's arguments for --fail_reset and --bin_fix (none while both are off).

policy_average

policy_average(
    pi: Module, decay: float
) -> torch.optim.swa_utils.AveragedModel

--pi_ema (InstantTrack, BlinkMimic): an exponential moving average of the policy's weights and normalizers.

ndm_gym.algos.xmimic

XMimic's machinery as options of ndm_gym.train (docs/algorithms/xmimic.md).

XMimic (N. Bohlinger and J. Peters, 2026; https://github.com/nico-bohlinger/xmimic, MIT) is BlinkMimic's trainer rebuilt in JAX: the same algorithm and hyperparameters (here --algo blinkmimic), with an iteration turned into a shorter chain of larger GPU operations and its steps run at the same time on up to four GPUs. The changes that carry over to this library's PyTorch pipeline are options here, off by default:

  • --eprobe_gpu i: the probe worker of the evaluation-guided resets (algos.eprobe) on the i-th GPU the trainer sees instead of the trainer's own, as XMimic's prober GPU (its layouts FP, ALP and AWLP). The sweeps and what they set are the same; they no longer take the trainer's GPU while they run.
  • --njmax n: MuJoCo Warp's constraint rows per world in the training simulator (XMimic: 256, against the scene's 500). A world that needs more loses the extra rows for that step, so this option changes results. The evaluation and the probe worker keep the scene's.
  • --gc_freeze: Python's garbage collector frozen once the run is set up (gc.freeze): a full collection then scans only what the loop allocates. Host time only.

and its learner's restructuring (xmimic/fast.py), for SuperTrack's and SuperMimic's updates with the MLP world model on the one-robot scene; the values are the default's up to rounding unless stated:

  • --pi_encode_once (train.py's option, SuperTrack's before) now also in SuperMimic's imagination: the policy's goal encoder once over every imagined step's goal, the steps its decoder (the policy's alone: with either world model).
  • --imag_hoist (with --pi_encode_once): the imagined steps compute only what depends on the imagined state. Before the rollout: the reference's terms of all its frames, the noise of all its steps (one draw per kind instead of one per step: another random stream) and the start history's normalization; each new observation is normalized once, when it is produced, instead of with its history at every step.
  • --pi_deferred_grads (with --imag_hoist) and --wm_deferred_grads: the weight and bias gradients of the policy decoder's Linear layers in the BPTT update, and of the world model's in its k-step fit, as one matrix product per layer over all steps after the backward pass (core.nets.run_mlp_deferred, deferred_grads), instead of one per step inside it. --deferred_bf16: those products in bf16 under --amp bf16 (their results rounded to bf16, as each step's is by default) instead of fp32 products of the bf16 operands.
  • --muon_batched: Muon's Newton-Schulz iterations of equally shaped matrices as batched products (core.muon).
  • --wm_presample: the windows of an iteration's --wm_batches world-model updates drawn, read and mirrored in one pass before the updates (ReplayBuffer.sample_windows_multi); with --update_graphs the updates are one CUDA graph. The same windows as one update at a time unless the fit draws random numbers itself (--wm_input_noise, --wm_smooth_w).

and its iteration split across GPUs:

  • --layout AL | AWL: the iteration's steps on two or three GPUs at the same time, each on the others' results of the previous iteration (algos.layouts; XMimic's layouts of those names without their prober, which is --eprobe_gpu). This one changes results: the policy update's batch and world model are one iteration older.

add_xmimic_args

add_xmimic_args(parser: ArgumentParser)

XMimic's options (off by default), in a group of their own.

check_args

check_args(args: Namespace)

The options' constraints; raises ValueError.

probe_device

probe_device(index: int, visible: str | None) -> str

--eprobe_gpu index: the probe worker's CUDA_VISIBLE_DEVICES, entry index of the trainer's visible (the device index itself where the trainer's is unset).

ndm_gym.algos.layouts

XMimic's iteration split across GPUs for ndm_gym.train (--layout; docs/algorithms/xmimic.md, section 2).

On one GPU an iteration takes the sum of its steps: the collection, the world-model updates, the policy update. XMimic (N. Bohlinger and J. Peters, 2026; xmimic/multi_gpu.py) runs them at the same time on separate GPUs, each on the others' results of the previous iteration, so that an iteration takes about its longest step. Here, in one process and one host thread:

  • AL, two GPUs. Actor (the first GPU the trainer sees): the simulator, the collection, the replay buffer, the world model with its updates, the draw of the next imagination batch. Policy learner (the second): the policy update with the policy average and the critic.
  • AWL, three GPUs. The world-model updates move to the second GPU, on a replica of the replay buffer that receives the rows the actor wrote; the policy learner is the third.

Every device has an object of the run's algorithm (Split): the actor's is train.py's own, the others are built from the same arguments and start from its networks. The collection, the world-model update and the policy update stay the functions the one-GPU loop captures as CUDA graphs (--collect_graph, --update_graphs); a graph's replay returns at once, so the host queues the three devices' work back to back and they run side by side.

What iteration i computes (the loop's order: collection, world-model updates, policy update, then exchange):

  • the collection acts with the policy as iteration i - 1's policy update left it, as on one GPU (iteration i - 1's exchange brought it to the actor);
  • AL's world-model updates follow the collection on the actor, as on one GPU; AWL's run on the replica, which holds the rows up to iteration i - 1's collection, with the normalizers as that collection left them;
  • the policy update imagines from the batch the actor drew at the end of iteration i - 1, in the world model as iteration i - 1's updates left it (AWL: iteration i - 1's updates, which saw the rows up to iteration i - 2), with the policy's normalizers of iteration i - 1. On one GPU all three would be iteration i's. The run's first iteration has no batch yet and makes no policy update, so every later one has made one update fewer than on one GPU.

This is XMimic's staleness (its layouts AL and AWL): the actor collects with the policy of the learner's previous iteration, and the learner updates on the actor's batch and world model of the previous iteration.

exchange ends the iteration. The actor draws the next imagination batch; then, as in-place copies into the fixed tensors the other device's captured updates read (Parcel: packed on the source, one device-to-device copy per dtype, unpacked on the destination; PyTorch orders a copy between two GPUs after the work queued on both, so every copy carries what the iteration computed and no step of the next iteration starts before its inputs have arrived):

  • actor -> learner: the batch (start states and their observation histories' states), the policy's normalizers, and in AL the world model (weights and normalizers);
  • AWL, world-model learner -> learner: the world model (weights, and the normalizers its updates used); then actor -> world-model learner: the replay rows of the iteration, the write head and fill level, the world model's normalizers;
  • learner -> actor: the policy's weights.

The copies are exact (float32 as it is, where XMimic sends the weights as bf16), so the actor's policy is the learner's bit for bit. The exchange also runs in the iterations --wm_only_iters keeps for the world model alone.

The split itself waits for the devices once per iteration, and only for the work of the iteration before (RunAhead), so that the host queues an iteration while the previous one runs. The collection schedule, the learning-rate schedule with its --lr_decay_ret trigger, the logging and the checkpoints stay train.py's loop on the host; the failure-focused resets stay in the simulator on the actor; the probe sweeps read the policy average, which lives on the learner (SplitAlgo gives the loop each quantity from the object that holds it).

Parcel

Parcel(pairs: dict)

Tensors of one device copied into their counterparts on another, in place: packed into one flat vector per dtype on the source, one device-to-device copy each, unpacked on the destination. pairs: name -> (source, destination), of equal shape and dtype; all sources on one device, all destinations on one. The tensors are held, not looked up again: they must be written in place (--no_sync's normalizers, the optimizers' steps).

OnDevice

OnDevice(fn, device)

fn called with device as torch's current CUDA device: a CUDA graph's warm-up stream, capture and memory report (algos.blinkmimic.Graphed) are the current device's. As is on the CPU.

RunAhead

RunAhead(devices)

The loop's one synchronization with the devices per iteration: step waits for the events the previous call recorded at the end of every CUDA device's queue, then records new ones. The host so queues an iteration's work while the previous one runs, and no more (XMimic's run-ahead limit). Nothing to wait for on the CPU.

LayoutTimer

LayoutTimer(split, every: int = 20)

LAYOUT_PROFILE=1 (train.py with --layout): every every-th iteration, CUDA events on each device's current stream around the iteration's steps (the collection on the actor, the world-model updates on their owner, the policy update on the learner, the exchange on every device) and at the iteration's start; after the exchange the devices are synchronized and one line is printed: per device, the milliseconds of its steps, its span (from the iteration's start to the end of its part of the exchange, as its stream reached them) and its idle time, the span less its steps. The events add no work; the synchronization stalls the host's run-ahead once every every iterations.

mark

mark(name: str, role: str | None = None)

An event named name on the device of role (None: on every device).

report

report(it: int) -> str

The timed iteration's line (after the exchange's end marks); the events are then dropped.

GivenStarts

GivenStarts(
    buffer: ReplayBuffer,
    B: int,
    hist: int,
    device,
    keys: tuple = START_KEYS,
)

An imagination batch as fixed tensors on device: the start states and their observation histories' states, as ReplayBuffer.starts_at returns them for B starts. starts stands in for the learner's own draw (Algo.sample_valid_starts_nosync), which the policy update calls with what it was given as its replay buffer. keys: the replay's fields a start holds; hist 0: starts without a history (train_hand: the hand agents' draw, hand_algos.START_KEYS).

pairs

pairs(other: GivenStarts) -> dict

The parcel entries that bring this batch into other.

SplitAlgo

SplitAlgo(actor, wmer, learner)

What ndm_gym.train's loop reads of its algorithm, each from the object that holds it under a layout: the world model, its optimizer and SuperTrack's world-model balancer from the world model's owner (AL: the actor's object; AWL: the world-model learner's); the policy, the critic, their optimizers, the policy average, SuperTrack's policy balancer and the count of skipped policy updates from the policy learner's.

optimizers property

optimizers: tuple

The live optimizers, in an algorithm's order: the world model's, then the learner's others.

state_dict

state_dict() -> dict

The run's state with an algorithm's keys: the policy learner's, the world model's parts from its owner.

Split

Split(
    args,
    actor,
    algo_on,
    buffer: ReplayBuffer,
    devices: tuple | None = None,
    start_keys: tuple = START_KEYS,
    hist: int | None = None,
    steps: int | None = None,
)

--layout AL | AWL: the objects of the run's algorithm on the layout's devices and what crosses between them (the module's docstring). actor: train.py's algorithm object on the simulator's device; algo_on(device): a new object of the same arguments on another device, with the task's tables there; buffer: the replay buffer, on the actor's device with its write head and fill level on the device (--graph_early); devices: the layout's, the actor's first (the first GPUs the trainer sees by default). start_keys, hist: the replay's fields of an imagination start and its history's length (GivenStarts; None: --hist); steps: the collection steps of an iteration at most (None: those of --utd), the rows AWL's replica receives per iteration. train_hand passes the hand agents' (algos.hand_layout).

The training loop: update_graphs() once after the warm-up collection; per iteration its collection, the returned world-model update and, once ready, the returned policy update; then exchange(). algo (SplitAlgo) is what the loop reads otherwise.

describe

describe() -> str

The layout's devices and what each does, for the run's output.

update_graphs

update_graphs(graphs: bool = True) -> tuple

train.py's update_graphs under the layout, called once after the warm-up collection (AWL's replica starts as the actor's buffer then): the world-model update on its owner's device and replay, and the policy update on the learner's device, on the batch it was sent. Each is a CUDA graph on its device (algos.blinkmimic.Graphed, with a capture stream of that device: torch's default one belongs to the device that captured first, and work of another device would not be recorded on it); graphs False: the plain functions, as the tests run them on the CPU.

exchange

exchange()

The end of an iteration: the actor draws the next imagination batch, and what the next iteration's steps read crosses the devices (the module's docstring), in this order: AWL's world model to the learner before the actor's normalizers reach the world-model learner, so that the learner gets the normalizers the weights were fit with.

copy_modules

copy_modules(src, dst) -> list[str]

The state of every module of algorithm src into dst's, an object of the same class and arguments on another device: the networks with their normalizers, the policy average, SuperTrack's balancers. The optimizers keep their own state. Returns the modules' names.

ndm_gym.algos.rollout_grads

The policy gradient of a BPTT update taken apart by rollout (and by imagined step), for --pi_rollout_clip and tools/grad_stats.py --anatomy.

The policy gradient of an update is g = sum_{t,b} J_tb^T abar_tb over the imagined steps t and the rollouts b: abar_tb is the gradient that reaches the policy's output at step t of rollout b from all its later uses (the world model, the observations, the losses), the output's adjoint, and J_tb the Jacobian of that output in the policy's parameters. For a policy of linear layers, layer l's part is sum_{t,b} D_tb X_tb^T (weight) and sum_{t,b} D_tb (bias), with X the layer's input and D the gradient of its output when the policy runs again on the steps' inputs with abar as its output's gradient. RolloutGrads does that rerun and keeps X and D, from which come, without forming the per-rollout parts G_b = sum_t J_tb^T abar_tb, their squared norms sum_l sum_{t,t'} (D_tb . D_t'b) (X_tb . X_t'b + 1), their dot products with a vector, and any weighted sum sum_b w_b G_b.

RolloutGrads

RolloutGrads(
    pi: TrackingPolicy,
    Ob: Tensor,
    Gl: Tensor,
    A: Tensor,
    chunk: int = 512,
)

The rerun of pi on the inputs of H imagined steps of B rollouts, obs histories Ob (H, B, hist, obs) and goals Gl (H, B, goal), with the output adjoints A (H, B, J) as the output's gradient, chunk rollouts at a time (as the update ran it: matmuls under the bf16 autocast of run_mlp when it is set). Every parameter of pi must be a linear layer's weight or bias. Gradients are flat, the parameters in pi.parameters()'s order.

rollout_sq_norms

rollout_sq_norms() -> torch.Tensor

|G_b|^2 (B,).

rollout_dots

rollout_dots(v: Tensor) -> torch.Tensor

G_b . v (B,) for a flat vector v.

weighted

weighted(
    weights: dict[str, Tensor],
) -> tuple[dict[str, torch.Tensor], list[torch.Tensor]]

sum_b w_b G_b for every weight vector of weights (name -> (B,)), and each chunk's own sum of G_b.

step_parts

step_parts() -> (
    tuple[list[torch.Tensor], list[torch.Tensor]]
)

Per layer, every step's part summed over the rollouts: weights (H, out, in) and biases (H, out).

flat

flat(part: dict) -> torch.Tensor

A gradient given per parameter (parameter -> tensor) as one flat vector.

ndm_gym.algos.hand_algos

SuperTrack and SuperMimic for hand-object tracking (tasks.hand_tracking). Both fit the world model on k-step windows of simulator transitions and train the policy through imagined rollouts of the frozen world model from replayed states.

SuperTrack (algos/supertrack.py, hoi_algos.HOISuperTrack; HandSuperTrack): the acceleration world model; the policy minimizes L1 errors of the quantities the task tracks over the imagined window, each term weighted once to 1 at calibration or by the task's weights; no reward, no critic.

SuperMimic (algos/supermimic.py; Liao et al., CoRL 2026; HandSuperMimic): the increment world model; the policy maximizes the imagined tracking return with a soft survival weight and a critic beyond the horizon (paper ยง3, Eq. 1-3). --bptt_decay lam scales the gradient through the imagined state by lam at every step.

HandSuperMimic

HandSuperMimic(
    args: Namespace,
    kin: HandKinematics,
    task: HandTask,
    dev: str,
)

pi_avg property

pi_avg: Module | None

The policy average's model (layouts.Split reads its count of steps), or None.

act

act(
    S: HandState,
    a_prev: Tensor,
    f: Tensor,
    noise: float = 0.0,
    z: Tensor | None = None,
) -> torch.Tensor

The policy's action in the simulator, with Gaussian exploration noise; fits the policy's input normalizer. z: the noise's standard normal draw, made before (train_hand --compile_collect); None: drawn here.

wm_update

wm_update(buffer: ReplayBuffer) -> torch.Tensor

--wm_batches steps on k-step windows; returns the last step's loss.

sample_valid_starts_nosync

sample_valid_starts_nosync(
    buffer: ReplayBuffer, B: int
) -> tuple[dict, dict]

The policy update's draw of B imagination starts from the replay, without a host read: each the state, the frame and the action before it (START_KEYS; every replayed state is a start, the reference holding its last frame), without a history. Under --layout the policy learner's draw is the batch the actor drew (layouts.GivenStarts).

wm_update_graphable

wm_update_graphable(buffer: ReplayBuffer) -> tuple

--layout: the iteration's world-model updates (wm_update), the last loss in a tuple (layouts.Split's graph).

policy_update_graphable

policy_update_graphable(buffer: ReplayBuffer) -> tuple

--layout: the policy update and the policy average's step, as hand_fast.update_functions calls them, in one function for the policy learner's CUDA graph; the loop counts the average's steps.

policy_update

policy_update(buffer: ReplayBuffer) -> tuple

One policy step on imagined rollouts from replayed states, then the critic's on their lambda-returns. Returns (policy loss, value loss, imagined reward as a share of the maximum, gradient norm, imagined survival).

HandSuperTrack

HandSuperTrack(
    args: Namespace,
    kin: HandKinematics,
    task: HandTask,
    dev: str,
)

Bases: HandSuperMimic

SuperTrack on the hand-object task. The policy minimizes, over the imagined window, the L1 errors of what the task tracks (TERMS: the keypoints' positions in the world and, for the fingertips, about the palm in the palm's frame; the palm's rotation; the finger joints; the object's position and rotation), each term weighted once to 1 at calibration (LossBalancer); --st_vel_terms adds the velocities' (VEL_TERMS: the joints', the object's linear and angular), calibrated as the others; --st_obj_w then weighs the object's position and rotation terms that many times. --st_unit_scales: terms of one unit share a calibrated weight (UNIT_OF): the fingertips' positions about the palm and the object's position weigh per metre as the keypoints' positions in the world, the object's rotation per radian as the palm's; a clip whose reference pose alone does not move the object starts with a large error of the object and so, calibrated by itself, with a small weight on it. --st_task_weights: no calibration; the terms are the task's five tracked quantities and each weighs, per unit of error and imagined step, the task's reward weight over its kernel's width (tasks.hand_tracking.RewardCfg: an error as large as the width costs the reward's weight), so that the loss trades the hand's pose against the object as the task does; the fingertips about the palm, which the task does not track, weigh nothing. Plus the failure penalty on the task's soft termination (--st_fail_w, as LAFAN1's and HOI's: every imagined step after a failure costs that many steps' worth of loss) and the regularizer on the actions (--st_reg), which are offsets about the reference pose. --st_imag_noise adds Gaussian noise to the imagined actions. With the task's target-rate penalty (--target_rate_w) its cost at every imagined step, summed over the window (--st_cost_mean: its mean). No reward, no critic: policy_update returns NaN for the value loss and the imagined reward of the same rollouts for the log (--st_no_imag_r: not computed, NaN).

policy_update

policy_update(buffer: ReplayBuffer) -> tuple

One policy step on imagined rollouts from replayed states. Returns (policy loss, NaN, imagined reward as a share of the maximum, gradient norm, imagined survival), the layout of SuperMimic's.

replay_fields

replay_fields(task: HandTask) -> dict

A transition: the state, the position targets u, the next state, the action before this step's, the frame.

ndm_gym.algos.hand_fast

Systems options of hand-object tracking's training (ndm_gym.train_hand), for both of its agents (algos.hand_algos). Each is off by default; with all of them off the loop and the agents compute what they do without this module.

--fused_adam Adam's fused CUDA kernel for every optimizer (optimizer). --reset_masked the ended worlds are reset by masked writes of fixed shapes, the random draws made for every world (HandSim.reset_masked): no host read, another random stream. --no_sync an iteration without host-device synchronization: the control step on Warp's stream, where torch's writes, the physics graph and torch's reads follow each other (HandSim.step_nosync, Collector); the normalizers' freeze test on the device and their statistics written in place (RunningNorm.no_sync); the policy's step skipped on the device for a non-finite gradient (finite_step); the survival products as a loop (survive: cumprod's backward reads the device). The device is read at the log's rows, and a checkpoint's tensors are moved to the host in one transfer per dtype (to_host). --collect_graph a collection step (the policy's action and its noise, the control step with MuJoCo-Warp's physics as kernels, the terminations and masked resets, the normalizers, the replay write, the log's sums) as one CUDA graph, captured at the third step and replayed (Collector). --compile_eager the collection step's forward kinematics (of the state for the policy and for the world model's normalizer, of the next state for the termination and for the reward; each hundreds of small kernels when run eagerly) as one compiled function (equal up to rounding). --update_graphs the iteration's world-model updates as one CUDA graph and its policy update (SuperMimic's with the critic's) as another (update_functions; blinkmimic.Graphed), with capturable optimizers. With either graph the replay's write head and fill level are read on the device (ReplayBuffer.use_device_ptr: another random stream for the sampled starts). --pi_opt muon, --wm_opt muon Muon on the hidden matrices of the policy's or the world model's MLP, Adam on the rest (core.muon.MuonAdam). --pi_ema an exponential moving average of the policy, which checkpoints store as 'pi' (PolicyAverage). --pi_lr_mult the policy's learning rate is --lr times this, ramped to 1 from the log row where sim_r reaches --lr_decay_ret (at the latest from --lr_decay_by), over --lr_decay_len iterations (blinkmimic.PolicyLR). --phase_times a measurement, which changes no result: the wall time of an iteration's phases (collection, world-model updates, policy update, critic update, log rows, checkpoints, the host's rest), the device synchronized at every boundary, in phase_times.csv with a summary at the end (PhaseTimes). --compile_updates with --no_sync: the updates' parts that otherwise run eagerly between the compiled ones, compiled (equal up to rounding): the policy's objective from the imagined window (the survival, SuperTrack's weighted terms, failure penalty and action regularizer, SuperMimic's return with the critic's value at the end), SuperTrack's kinematics of the start states (SuperMimic's are compiled already), SuperMimic's critic targets (its normalizer's update, the values and the lambda-returns) and its minibatch loss; the backward passes of these parts with them. --muon_batched with --pi_opt muon or --wm_opt muon: Muon's Newton-Schulz iterations of equally shaped matrices as batched products (core.muon.MuonAdam's batched, train.py's option; the world model's two hidden matrices; equal up to rounding). --elementwise_3x3, --combo_kernels train.py's options: inside compiled functions the products of 3 x 3 matrices and 3-vectors as fused fp32 elementwise products, and independent small kernels launched together (train.elementwise_3x3_products, train.combo_kernels; equal up to rounding). --wm_palm_fk the world model's fit computes the kinematics of the palm alone (HandKinematics.palm), the only part of them the world model reads, instead of every keypoint's (the same values). --sm_reuse_input SuperMimic: an imagined step's policy input is the critic's input the step before computed (the same observation and goal of the same state; the start's from start_features), not computed again (equal up to rounding). --st_no_imag_r SuperTrack: the imagined steps without the task's reward, which SuperTrack's loss does not read (only the log's imag_r did, then NaN): neither the reward nor, in the compiled imagined step, its backward on zero gradients is computed (the same updates; equal up to rounding). --compile_collect with --no_sync: the collection step's torch work before the physics (the state, the policy's action, the position targets written) and after it (the frame, the terminations, the masked resets, the normalizers, the episode lengths, the log's sums) as two compiled functions, which --collect_graph captures with the physics' kernels (Collector.core_compiled); the forward kinematics are compiled in them (--compile_eager's are then not used). The random draws are made before them in the default step's order and the replay write stays outside (equal up to rounding). --compile_rollout the policy update's imagined rollout (the start's kinematics and the --horizon steps) as one compiled function (the agent's _rollout), whose backward is one graph, instead of a compiled function per step: the steps' kernels fuse across their boundaries and the policy's gradients are summed inside the graph. SuperTrack's imagination noise is drawn before it, in the steps' order (equal up to rounding). --mix_order_reductions inductor's mix-order reductions without its size checks (mix_order_reductions): a row reduction and a column reduction that read the same activations fused into one kernel, as in LayerNorm's backward in the world model's fit (the input's gradient per row, the weight's and bias's per column), which inductor fuses by default only from 4,096 rows (the fit has --wm_batch rows; equal up to rounding). --autotune_gemm the compiled functions' matrix products from the fastest of cuBLAS and inductor's Triton templates, timed per shape when they are compiled (autotune_gemm: inductor's max_autotune_gemm, without its CUDA graphs; longer compilations; equal up to rounding).

An agent takes part by building its optimizers with optimizer and by taking its policy step with finite_step on the survival of survive; the collector and the graphs call its act, update_wm_norms, wm_update and policy_update as the loop does. docs/tasks/hand.md lists what each option changes in a run's numbers.

PolicyAverage

PolicyAverage(pi: Module, decay: float)

--pi_ema: an exponential moving average of the policy's weights and normalizer (blinkmimic.policy_average), stepped after every policy update as AveragedModel.update_parameters steps it: the first step copies the policy, the later ones are its lerp (common.ema_step). A step reads only the average's count, which AveragedModel keeps on the host, so it can be captured with the update; the loop counts the steps (count), a graph's replays too. Checkpoints hold the average as 'pi', the policy that evaluate_hand loads, the trained policy as 'pi_live' and the average's own state as 'pi_avg'.

checkpoint

checkpoint(ck: dict) -> dict

The agent's checkpoint ck with the average in the policy's place.

resume

resume(ck: dict) -> dict

Loads the average from the checkpoint ck; returns ck with the trained policy as 'pi', for the agent.

Timed

Timed(fn)

HAND_PROFILE=1 (train_hand): fn with the device synchronized before and after each call, so that the call's time is its own; take returns the mean time of the calls since the last one, in ms.

PhaseTimes

PhaseTimes(
    args,
    algo,
    device,
    resumed: bool,
    clock=time.perf_counter,
    devices: tuple = (),
)

--phase_times (train_hand): the wall time of each phase of an iteration, in <log_dir>/phase_times.csv. The device is synchronized at every phase's boundary, so that a phase's time holds the work it queued there; an iteration then takes at least as long as without the option, where the host queues a phase while the device runs the one before. The phases (PHASES) add up to the iteration:

the policy's action, the control step with its physics, the terminations and resets,

the normalizers, the replay write, the log's sums; with --collect_graph one CUDA graph

wm the iteration's --wm_batches world-model updates; with --update_graphs one CUDA graph policy the policy update with the policy average's step (--pi_ema); with --update_graphs one CUDA graph, which holds SuperMimic's critic update too critic SuperMimic's critic update, timed apart only without --update_graphs: the agent then calls lap where its policy step ends and where its critic's update ends (NaN where it is in policy and without a critic) log a log row: its read of the device, the file's line, the output ckpt a checkpoint host the rest: the loop's host work between the phases (the learning rates, the log's lists, the timing itself) and what it queues on the device

The loop times its three functions through timed, calls lap after a log row and after a checkpoint and end after every iteration; every --log_every-th writes a row (COLUMNS: the iteration, each phase's mean ms per iteration since the last row, the iterations per second; a resumed run continues the file). finish returns the summary: the means over iterations 1,001 to 3,000 of a run from its first iteration, past its compilations and its graphs' captures (the policy update's follows --wm_only_iters); over the second half of the iterations run for a shorter run and for a resumed one, which compiles and captures again. clock: the tests' in time.perf_counter's place. devices (--layout, algos.hand_layout): the layout's, all synchronized at every boundary, and the phases LAYOUT_PHASES: the exchange between them (the draw of the next imagination batch, the copies) is timed apart; algo is then the policy learner's agent.

lap

lap(phase: str)

A boundary: the time since the last one is phase's.

timed

timed(phase: str, fn)

fn with each call's time as phase's and the time from the last boundary to the call as the host's.

end

end(it: int)

The end of iteration it: what is left of its time is the host's; a row with every --log_every-th.

finish

finish() -> str

Closes the file; returns the summary, a line per phase with what it holds.

Collector

Collector(sim, task, algo, buffer, args)

train_hand's collection step for --no_sync: the default step's computations (train_hand.collect) on the loop's state kept in fixed tensors (the previous action, the episode lengths, the log's sums acc), without a host read. The control step is HandSim.step_nosync, the ended episodes' lengths are summed and cleared by mask; with --compile_eager the step's forward kinematics, the agent's too (its fk), are one compiled function. A call runs the step on Warp's stream, where torch's work and the physics graph are ordered, and has the caller's stream wait for it. With --collect_graph the first two calls run so (kernels loaded, workspaces allocated), the third captures the step with the physics as kernels in one CUDA graph (torch's capture on Warp's stream, Warp's registered as external: sim.rigid.isaaclab_mjwarp.capture_step's way), and it is replayed from then on; the transition is written at the replay's device-side head, the host's advanced after each call.

Another task's training (train_quadruped) subclasses it with its own log sums (acc_keys, log_errors) and its state's layout (unflatten); its simulator has HandSim's step_nosync, physics and torch_stream.

log_errors

log_errors(errors: dict)

The task's errors of a step's next states, into the log's sums.

core

core(physics=None)

One collection step on the fixed tensors; physics: the simulator's physics as kernels, inside the capture.

core_compiled

core_compiled(physics=None)

--compile_collect: core's step with its torch work before the physics (_before) and after it (_after) as compiled functions. The random draws are made first, in the default step's order (the action's noise, then the resets'), so that the step draws the same numbers; the replay write and the previous action's update stay outside (the replay's fields are written in place).

check_hand_fast_args

check_hand_fast_args(args: Namespace)

The options' constraints on a run's arguments; raises ValueError.

check_resume

check_resume(ck_args: dict, args: Namespace)

A resumed run must have its checkpoint's algorithm, SuperTrack's terms, optimizers and policy average; raises ValueError.

mix_order_reductions

mix_order_reductions()

--mix_order_reductions: inductor fuses a reduction over rows and one over columns that read the same tensor into one kernel (torch._inductor.config.triton.mix_order_reduction, on by default), here without its checks of size (mix_order_reduction_non_strict_mode), which leave it out below 4,096 rows: the world model's fit at --wm_batch 2,048 runs LayerNorm's backward as one kernel per layer that reads the activations once, instead of a row kernel for the input's gradient and a split column kernel for the weight's and bias's that reads them again.

autotune_gemm

autotune_gemm()

--autotune_gemm: inductor times each matrix product of a compiled function, per shape, between cuBLAS and its Triton templates and takes the fastest (torch._inductor.config.max_autotune_gemm; the products' tiles, so their rounding, may change). Not its max-autotune mode: no CUDA graphs of its own, the loop's graphs capture the kernels.

optimizer

optimizer(args, dev, module: Module, kind: str)

The optimizer of an agent's kind ("wm", "pi" or "critic") network: Adam at --lr, the policy's with betas (0.9, 0.95). --fused_adam: its fused kernel; --update_graphs: the capturable fused kernel with a device learning rate (common.adam_kwargs, set_lr); --pi_opt muon, --wm_opt muon: MuonAdam on the network's MLP (--muon_batched: its batched Newton-Schulz iterations). args without these options (a checkpoint's from before them) builds Adam as before.

survive

survive(d: Tensor, no_sync: bool) -> torch.Tensor

The survival after each imagined step from the termination probabilities d (H, B): cumprod(1 - d, 0), with --no_sync as a loop of products (common.survival; equal up to rounding).

finite_step

finite_step(opt, params, grad_norm: Tensor, no_sync: bool)

opt's step unless the gradient's norm is non-finite: tested on the host, or with --no_sync on the device (the gradients of params zeroed and the step skipped there, parameters and optimizer state unchanged: common.gated_step).

update_functions

update_functions(
    algo, buffer, args, average: PolicyAverage | None = None
)

The loop's two updates as functions without arguments: the iteration's world-model updates (returns the last loss) and its policy update with the policy average's step (returns the agent's values for the log). With --update_graphs each is a CUDA graph (blinkmimic.Graphed: three calls run eagerly on a side stream, the fourth is captured, later ones replay it), its values copied out of the graph's memory.

to_host

to_host(tree)

tree (a checkpoint: nested dicts, lists and tuples) with its tensors on the host, moved in one transfer per dtype and device: the tensors are flattened into one tensor, copied, and split again into tensors of their own. On some GPUs a small transfer takes as long as a large one, and a checkpoint is a hundred of them (train_hand --no_sync).

The human-object interaction's and the muscle-actuated character's algorithms; hoi_algos imports the simulator (Installation).

ndm_gym.algos.hoi

Imagination for HDMI's human-object interaction tasks (docs/hoi_design.md ยง3): HDMI's step input (HDMIInput) rebuilt from a neural dynamics model's prediction, so that ndm_gym.tasks.hdmi's own rewards, observations and terminations run on imagined rollouts.

From the predicted robot state (G1 order), object state, contact forces and the per-env context: the 16 keypoints by our forward kinematics, their linear velocities as centre-of-mass velocities (HDMI's), joints in HDMI's order, a hinged object's contact body through its joint frames, the end-effector points and contact targets. Approximations, as stated in the design: the joints after the third physics substep are interpolated at 3/4 of the step; the actuators' torque is the PD law at that interpolated state with the last substep's target, and the hinge torque HDMI's friction and damping law at the interpolated rate (both are computed before the last substep).

HOIImagination

HOIImagination(
    cfg: HDMITaskCfg,
    clip: HDMIClip,
    constants: dict,
    hinge: dict | None,
    layout: ContextLayout,
    device,
)

constants: the task's ndm_gym.sim.rigid.hdmi_sim.ndm_constants; hinge: its HDMISim.hinge_frames for a hinged object, else None; layout: the context's layout.

contact_body

contact_body(So, ctx)

World pose of the object's contact body: a free object's root; a hinge's child, base X_p Rot(axis, q) X_c^-1.

state

state(S, So, f_eef, ctx, kp_com_b, obj_scale) -> HDMIState

HDMIState of a robot state S (G1 order), object state So, end-effector forces (N, E, 3) in the contact body's frame, contexts (N, C), keypoint centres of mass (N, 16, 3) in their link frames and object scales (N, 3).

step_input

step_input(
    now: HDMIState,
    prev: HDMIState,
    t_prev,
    u_sub,
    action_buf,
    ctx,
    f_feet,
) -> HDMIInput

HDMIInput of an imagined control step from the state prev to now (HDMIState), with the frame counter before the step t_prev (N,), the substeps' filtered actions u_sub (N, 4, 23), the raw-action buffer after the step (N, 23, 3) and the feet's forces (N, 4, 2, 3).

ndm_gym.algos.hoi_algos

SuperTrack and SuperMimic on HDMI's human-object interaction tasks (docs/hoi_design.md ยง3), each with the settings selected on LAFAN1: a neural dynamics model of the scene (worldmodels.hoi) fit on replay windows, and a policy (policies.hoi_policy) trained by backpropagation through imagined rollouts, on which HDMI's own terms run (algos.hoi.HOIImagination and an HDMITask of the imagination batch).

Imagination starts are replay states with HDMI's full per-env task state rebuilt: the action delay buffer and filter, the observation histories (slot j: what the end of step t-1-j pushed; before the episode, the reset state's fill; the policy's copies with fresh noise, as HDMI draws it, if the task has noise), the termination counters and the feet's timers (recorded), a fresh episodic contact-target noise. A start's observations are those of the step that ended at it, or at an episode's first row those after the reset (HDMISim.reset_input). Terminations are HDMI's (a term fires after its run of consecutive steps over the threshold), with a gradient in imagination: a step's exceedance is HDMI's 1[e >= thr] in the forward pass and has the gradient of sigmoid((e - thr) / (0.1 thr)) (a straight-through estimator), the run length counts on as exceed (count + 1) from the recorded count, so it is HDMI's counter exactly, and a term fires by sigmoid((count - min_steps + 0.5) / 0.05), within 5e-5 of HDMI's 0 or 1 at every whole count.

Replay rows of a step the guard flagged (hoi_guard; bad) hold finite stand-ins (sanitize_transition) and are left out of the model's windows and normalizers; model and policy updates with a non-finite gradient are skipped and counted (wm_skips, pi_skips).

HOIAgent

HOIAgent(args, env, dev: str)

One HDMI task's learner; kind is the dynamics model's parameterization (SuperTrack: "accel", SuperMimic: "increment"). Built from the training environment (HDMISim) for its task constants.

state_dict

state_dict() -> dict

Everything a resumed run continues from: the networks with their normalizers and the optimizers' states.

base_action

base_action(t: Tensor) -> torch.Tensor

HDMI's residual base at frame t: the reference's tracking joints as an action, (q_ref - q0) / scale.

update_wm_norms

update_wm_norms(tr: dict)

The model's normalizers updated from a step's transitions (sanitize_transition), without the flagged ones.

wm_update

wm_update(buffer) -> torch.Tensor | None

One model update; skipped (and counted) if its gradient is not finite. Returns the loss per window step (the fit loss, without --wm_smooth_w's penalty), None when skipped.

starts

starts(buffer) -> dict

B replay states whose clip covers the horizon, with HDMI's task state rebuilt (module docstring); the task of the imagination batch is set to it.

imagine

imagine(st: dict, taps: list | None = None)

H imagined steps from the starts: the observations at the start, and per step what the policy loss reads (_record). The dynamics model is frozen; gradients reach the policy through every step. taps (a list, for --pi_rollout_clip): per step the policy's observations and a zero tensor added to its output are appended.

clip_rollout_grads

clip_rollout_grads(taps: list) -> int

--pi_rollout_clip after the policy loss's backward pass (algos.common.clip_rollout_output_grads): the policy run again on the taps' observations.

reference_state

reference_state(t: Tensor, kp: Tensor) -> tuple

--st_ref_replay's state of the reference frame t (B,) (the frame a step from counter t is measured against), as HDMI's reset sets it (ยง2, HDMISim.reset) without its noise: the pelvis's pose and angular velocity, its reference centre-of-mass velocity turned into the root link's with the env's centre of mass kp (B, 16, 3), every joint's reference clamped as the reset clamps it (G1 order), the object's reference pose at rest, or the hinge's reference angle (clamped to its limits) and rate.

HOISuperMimic

HOISuperMimic(args, env, dev)

Bases: HOIAgent

SuperMimic: the policy maximizes HDMI's imagined return (the sum of its four reward groups, each times dt) with a critic on HDMI's privileged observations at the horizon; the critic regresses GAE(lambda) targets.

HOISuperTrack

HOISuperTrack(args, env, dev)

Bases: HOIAgent

SuperTrack: the policy minimizes L1 errors of HDMI's tracked quantities over the imagined window (keypoint positions in the world and the root's heading frame, keypoint orientations, the tracking joints, the object's position and orientation or the hinge angle, and the end effectors' distance to their contact targets where the reference is in contact; with --st_contact_force, HDMI's contact reward as an error instead, which adds the predicted force's shortfall), each term weighted once to 1 at calibration (LossBalancer; --st_obj_w then weighs the object's three terms k times), plus the LAFAN1 failure penalty on HDMI's soft terminations; no reward, no critic. --st_obj_imag_noise perturbs the imagined object's velocities after every imagined step. --st_vel_terms adds three terms, calibrated as the others: the L1 errors of the velocities HDMI's tracking group tracks (its keypoints' linear and angular velocities, its tracked joints' velocities; VEL_TERMS). --st_task_penalties adds HDMI's own penalties (its loco and feet terms but survival; the tracking groups' kernels stay out) as a cost at the reward's ratio to its full tracking score, as LAFAN1's SuperTrack: their mean per imagined step times n / full score, n the number of tracking terms. --st_late_w weighs the tracking terms of later imagined steps more (LAFAN1's linear ramp, before the calibration). --st_ref_replay tau replays the demonstration inside the imagined window (_replay): a rollout whose keypoints are on average more than tau metres from the reference continues from the reference's state.

policy_groups

policy_groups(priv_obs: bool) -> tuple[str, ...]

The observation groups the policy reads: POLICY_OBS, and with train_hoi's --priv_obs HDMI's privileged group too (as HDMI's PPO teacher reads it).

task_fields

task_fields(n_terms: int) -> dict

Replay fields of HDMITask's counters before each step, which imagination starts need.

task_record

task_record(task: HDMITask) -> dict

The counters before a step; HDMITask.step and reset replace them rather than write into them, so no copy is needed.

sanitize_transition

sanitize_transition(
    tr: dict, bad: Tensor, q_prev: Tensor
) -> dict

A step's transition with the rows the guard flagged (bad (N,)) made finite for the replay: the robot's and the object's state after the step set to those before it, the contact forces to zero and the pushed joint observation to the previous one (q_prev, the history's newest slot before the step); by selection, since NaN x 0 is NaN. The flag is stored as bad, which keeps the rows out of the model's windows and normalizers.

masked_update

masked_update(norm, x: Tensor, keep: Tensor)

norm.update(x) (a core.normalizer.RunningNorm) from the rows where keep (N,) holds, written into the normalizer's buffers (a CUDA graph reading them sees the update) and without a host synchronization: the rows left out are replaced by zeros rather than multiplied by them (NaN x 0 is NaN); without rows, or once the normalizer is frozen at max_count, nothing changes.

mix_states

mix_states(hit: Tensor, now, ref)

--st_ref_replay's HDMIState of a step's end: the reference's ref where hit (B,), else the rollout's now; a field the reference leaves out (None: the contact forces) is the rollout's. imagine mixes the next step's prev with it outside the compiled step: with that mix an output of the step's graph, Inductor's backward returned non-finite gradients from the first policy update (move_stool-climb, and every task with --priv_obs; on the CPU too, where it also crashed), while the same graph on eager kernels (aot_eager, aot_eager_decomp_partition) and the eager step were finite.

soft_terminations

soft_terminations(
    errors,
    thresholds,
    min_steps,
    count,
    rel_tau: float = 0.1,
)

HDMI's terminations for imagined rollouts (module docstring): the step's termination probability (N,) and the new run lengths (N, terms), HDMI's counts in the forward pass.

ndm_gym.algos.ppo_hoi

HDMI's model-free learner for its human-object interaction tasks, PPO with a privileged teacher and an adaptation module ("PPO-ROA", LeCAR-Lab/HDMI @ 32282f6, active_adaptation/learning/ppo/ppo_roa.py), re-implemented from its behaviour on our simulator and task (HDMISim + HDMITask): the model-free baseline of the wall-clock comparison with the model-based algorithms (docs/hoi_design.md). No HDMI code is copied. References are ALIAS:line as in docs/hdmi_task_spec.md, with PPO = learning/ppo/ppo_roa.py, PC = learning/ppo/common.py, DIST = learning/modules/distributions.py, TRN = scripts/train.py, HLP = scripts/helpers.py and VN = the VecNorm of torchrl 0.7.0 (the version HDMI pins, setup.py:27), torchrl/envs/transforms/transforms.py:6082-6330.

HDMI's README trains a teacher (algo=ppo_roa_train) and then a student from its checkpoint (algo=ppo_roa_finetune; cfg/train_sequential.yaml chains the two); the student, which observes no privileged group, is the policy HDMI deploys. An iteration of either phase (TRN:143-188, PPO:441-465):

  • Rollout: train_every = 32 steps of every env (PPO:43; 4096 envs, Y:13). Actions are drawn from a diagonal Gaussian whose std is a parameter, 1 at initialization (PC:145-164), neither squashed nor clipped (DIST:139-158). The command, policy, object and priv groups are normalized by torchrl's VecNorm (VecNorm), ref_joint_pos_ is not.
  • Values: the critic, one value per reward group (PPO:267-272), of the stored observations and of the observation after the last step; a done step's next value is its own value (TRN:153-159), not bootstrapped at all after a termination.
  • GAE per group, gamma 0.99, lambda 0.95 (PC:195-225), over HDMI's five reward groups (the fifth, debug, is identically zero, ยง5.6); the groups' advantages are scaled by 1/5, summed and normalized over the batch (PPO:624-639). The value targets are the groups' returns; there is no value normalization (PPO:74, 173-177).
  • PPO: 3 epochs of 8 minibatches (PPO:44-45, PC:99-117). The loss is the clipped surrogate (0.2), an entropy bonus of 0.001 and the mean over the groups of the squared value errors, over the transitions with step_count > 1 (teacher) or > 5 (student) (PPO:653-693): HDMI's first observation of an episode is all zeros and its second one partly stale (ยง0). The actor's, the critic's and the encoder's gradients are clipped to norm 1 separately (PPO:698-701). Adam at 3e-4; after every minibatch the policy's learning rate is divided by 1.5 if the KL exceeded 0.02 and multiplied by 1.5 if it was in (0, 0.005), within [1e-5, 1e-2] (PPO:483-491); the critic's stays 3e-4.
  • Adaptation (PPO:507-564): 2 epochs of 8 minibatches of envs. The adaptation module (policy, command and object groups -> 256) regresses the teacher's privileged features except at reset observations; in the teacher phase the student's action mean is also distilled from the teacher's, the student given the teacher's features ("residual distillation"). An EMA (0.04 per iteration) of the module drives the student's rollouts.

Teacher ("train"): the actor's input is cat[command, policy, encoder(cat[priv, object])] and its mean the reference's joints as an action, (q_ref - q0) / scale (OBS:37-50), plus the MLP's output (PPO:223-236); the encoder is trained with the actor; the normalizer is updated (HLP:152-154). Student ("finetune"): loaded from the teacher's checkpoint with both actors' std set to 0.5 (PC:166-171) and the policy's learning rate where the teacher's ended (PPO:769-774); its input is cat[command, policy, the adaptation EMA's prediction], its mean the MLP's output alone; the normalizer is frozen (HLP:155-157).

Implementation choices with the same values: time-major storage, preallocated on the device; masked means as masked sums, the learning rate a device tensor and the normalizer's reset rows conditional on a device flag, so that neither the rollout nor the update needs a host synchronization; a minibatch's rows gathered inside the compiled losses; with graphs, every minibatch step (forward, backward, clipping, both optimizers, the learning rate) replayed as one CUDA graph. Deviations from HDMI's trainer (all outside the losses) are listed in ndm_gym/train_ppo_hoi.py.

PPOConfig dataclass

PPOConfig(
    phase: str = "train",
    train_every: int = 32,
    ppo_epochs: int = 3,
    num_minibatches: int = 8,
    clip_param: float = 0.2,
    gamma: float = 0.99,
    lmbda: float = 0.95,
    lr: float = 0.0003,
    desired_kl: float = 0.01,
    entropy_coef: float = 0.001,
    init_noise_scale: float = 1.0,
    load_noise_scale: float = 0.5,
    latent_dim: int = 256,
    max_grad_norm: float = 1.0,
    adapt_epochs: int = 2,
    ema_tau: float = 0.04,
    vecnorm_decay: float = 0.9999,
    vecnorm_eps: float = 0.0001,
)

HDMI's PPO-ROA settings (PPOConfig, PPO:39-86) as its two stages set them (PPO:89-91).

min_step_count property

min_step_count: int

A transition enters the PPO losses when its step_count exceeds this (PPO:670-674).

GaussianActor

GaussianActor(inp: int, init_std: float)

Bases: Module

HDMI's actor (PPO:238-254, PC:145-164): MLP [512, 256, 256], a linear mean of the 23 actions, and the std a free parameter (no exponential), clamped at 1e-6 by the distribution (DIST:143-146).

VecNorm

VecNorm(
    dim: int, decay: float = 0.9999, eps: float = 0.0001
)

Bases: Module

torchrl 0.7.0's VecNorm as HDMI uses it (HLP:138-160, VN:6210-6249): per feature, decayed sums of x and x^2 and a decayed count; each update first decays them by decay and then adds a batch, and the batch is normalized with the statistics that include it: (x - mean) / std, std = sqrt(max(E[x^2] - mean^2, eps)).

HDMI's environment returns all-zero observations for every env at a reset (ENV:385-386), and the transform updates its statistics with them before the partial reset keeps the reset envs' rows (VN:6210-6216, common.py:2672-2676): every step with a reset also adds N zero rows (absorb_zeros). The statistics start with one batch of zeros, the environment's fake tensordict (HLP:146-147).

update

update(x: Tensor) -> torch.Tensor

Add the batch x (N, dim) and return it normalized.

absorb_zeros

absorb_zeros(n: int, when: Tensor | None = None)

Add n zero rows: the sums only decay. when (a device bool): only if true, without a host synchronization (otherwise every statistic is multiplied by 1 and gets 0 added, unchanged).

Rollout

Rollout(
    T: int,
    N: int,
    obs_dim: int,
    latent: int,
    student: bool,
    device,
)

One iteration's transitions, time-major (T, N, ...) and preallocated on the device (TRN:129-134): the normalized observation groups concatenated (OBS_GROUPS), the teacher's residual base (ref_joint_pos_, zero at reset observations), the student's latent (the adaptation EMA's prediction), the action, its log-probability and the distribution's mean, the group rewards (debug's column zero), the termination and done flags and HDMI's step_count (steps since the reset when the action was taken); the actor's std during the rollout (state independent).

PPOROA

PPOROA(
    cfg: PPOConfig,
    dims: dict[str, int],
    device,
    compile: bool = False,
    graphs: bool = False,
)

HDMI's PPO-ROA for one task. dims: HDMITask.obs_dims. compile: torch.compile the rollout's forward pass, the values and advantages, and the losses with their backward passes (the same computations). graphs (CUDA): each PPO and adaptation minibatch step replayed as one CUDA graph (the same kernels on the same tensors); its optimizers are then capturable, and the update is bound to the first rollout buffer it is given.

observe

observe(obs: dict[str, Tensor]) -> torch.Tensor

A step's observation groups, normalized: the teacher's normalizer adds them first (HLP:152-154), the student's is frozen (HLP:155-157).

reset_observation

reset_observation(
    num_envs: int, when: Tensor | None = None
) -> torch.Tensor

The normalized observation HDMI's reset returns (all groups zero, ENV:385-386), (1, D); the teacher's normalizer first adds the reset's num_envs zero rows (VecNorm), if when (a device bool: whether any env is reset) is true or not given.

features

features(obs: Tensor) -> torch.Tensor

The teacher's privileged features, encoder(cat[priv, object]).

predicted_features

predicted_features(obs: Tensor, ema: bool) -> torch.Tensor

The adaptation module's (or its EMA's) prediction of the features from cat[policy, command, object].

update

update(
    buf: Rollout, last_obs: Tensor, section=None
) -> dict[str, torch.Tensor]

One iteration's learning from the rollout buf and the observation after its last step (N, D): HDMI's train_op (PPO:441-465). Returns the minibatches' mean diagnostics as device tensors. section(name): a context manager around each part (the trainer's profiling), none by default.

state_dict

state_dict() -> dict

HDMI's state_dict (PPO:736-754): in the teacher phase the student's std is set to the teacher's and the EMA to the adaptation module first, side effects that HDMI's training also has at every checkpoint.

load_teacher

load_teacher(sd: dict)

Start the student phase from a teacher's checkpoint (PPO:756-776, HLP:132-160): every network, both actors' std set to load_noise_scale, the policy's learning rate where the teacher's ended, the normalizer's statistics (frozen in this phase); fresh optimizer states, as HDMI's (it saves none).

load_state_dict

load_state_dict(sd: dict)

Resume a run of the same phase.

make_mlp

make_mlp(inp: int, units: tuple[int, ...]) -> nn.Sequential

HDMI's MLP: Linear, LayerNorm, Mish per layer (PC:56-71 with layer_norm="before", PPO:73).

hdmi_init

hdmi_init(module: Module)

Every linear layer orthogonal with gain 0.01, zero bias (PPO:336-344); LayerNorms and stds keep theirs.

gaussian_log_prob

gaussian_log_prob(
    a: Tensor, loc: Tensor, std: Tensor
) -> torch.Tensor

log N(a; loc, diag std^2), summed over the actions (torch's Normal under Independent).

gaussian_entropy

gaussian_entropy(std: Tensor) -> torch.Tensor

Entropy of the diagonal Gaussian; the std does not depend on the state, so it is the batch's mean too.

gaussian_kl

gaussian_kl(
    loc0: Tensor, std0: Tensor, loc1: Tensor, std1: Tensor
) -> torch.Tensor

KL(N(loc0, std0) || N(loc1, std1)) summed over the actions (torch's kl_divergence for Normal, PPO:717-718).

next_values

next_values(
    value: Tensor, last_value: Tensor, done: Tensor
) -> torch.Tensor

The next state's values (T, N, G) of a rollout's values (T, N, G), the values of the observation after its last step (N, G) and its done flags (T, N): a done step takes its own value, as HDMI stores no terminal observation (TRN:153-159); after a termination GAE drops it.

gae

gae(
    reward,
    terminated,
    done,
    value,
    next_value,
    gamma: float,
    lmbda: float,
) -> tuple[torch.Tensor, torch.Tensor]

HDMI's GAE (PC:195-225) per reward group, time-major: reward, value, next_value (T, N, G), terminated and done (T, N) bool. A termination drops the next value, any done step cuts the trace. HDMI's discount is 1: it is set every step (ENV:488) and only feet_air_time could change it, by its soft_discount, which is 1 in every task (RF:152-153). Returns the advantages and the returns, advantages + values.

combine_advantages

combine_advantages(adv: Tensor) -> torch.Tensor

The groups' advantages (T, N, G) scaled by 1/G (the reward scales, PPO:171-172), summed and normalized over the batch, its unbiased std plus 1e-8 (PPO:633-639): (T, N).

residual_base

residual_base(
    clip_joint_pos: Tensor,
    q0: Tensor,
    scale: Tensor,
    t: Tensor,
) -> torch.Tensor

HDMI's ref_joint_pos_ (OBS:37-50): the reference's action joints at frame t (the command update's index 0, held at the clip's last frame, MOT:333-338) as an action, (q_ref - q0) / scale, (N, 23).

ndm_gym.algos.muscle_algos

SuperTrack and SuperMimic on MuscleVAE's muscle-actuated character (docs/musclevae_design.md ยง4), each with the settings selected on LAFAN1: a world model of the bodies and the muscle state (worldmodels.muscle) fit on replay windows, and a policy (policies.muscle_policy) trained by backpropagation through imagined rollouts on the task's terms (tasks.muscle_tracking). The world model is frozen in the policy's update; gradients reach the policy through every imagined step.

Imagination starts are replay states that the guard did not flag and whose clip holds the horizon, with the reference frame their recorded step tracked, the episode step and MuscleVAE's off count before it; the reference then advances one frame per step (the simulator's random switches are not imagined; a state after one is a replay state like any other). --imag_start_perturb kicks every body of a start by one horizontal velocity N(0, s^2) m/s: the G1's root kick with the joints unchanged. Terminations are MuscleVAE's, straight-through (tasks.muscle_tracking.soft_termination).

Settings in action units (the G1's normalized setpoints there, the muscle targets' a here) are mapped by tasks.muscle_tracking.ACTION_UNIT, MuscleVAE's own collection noise (0.05 on a, MV:72) over SuperMimic's default (0.1): --action_noise and --st_imag_noise times 0.5, and the task's action rate in the G1's units. Everything else keeps its LAFAN1 value.

  • SuperTrack: muscle targets about the reference action, the PD offset about the reference pose (the action l_ref / l_Tpose - 1 of the tracked frame); the world model fit by the L1 window loss on world-space body positions, velocities, rotations (log) and rotation rates, plus the muscle state; the policy by SuperTrack's L1 terms in the root's frame (algos.supertrack.LOCAL_TERMS: positions, velocities, rotations, rotation rates, heights, up direction, on all 23 bodies; no world-space root terms, tasks.muscle_tracking), each weighted once to 1 at calibration (LossBalancer) and the heights and up direction by --st_balance_w on top, the regularizer --st_reg on the offsets, the task's action-rate penalty at the reward's ratio to its full tracking score (as on LAFAN1), the failure penalty --st_fail_w on the soft terminations, and noise --st_imag_noise on the imagined offsets. The action rate is that of the executed targets without the noise, the first step's against the replay's previous action. Options: LAFAN1's --st_late_w, and --st_ref_replay, DiffMimic's demonstration replay in the imagined window (MuscleAgent._replay).
  • SuperMimic: muscle targets about the T-pose (a = 0), the setpoint about the default pose; the world model fit by the normalized squared increment error; the policy maximizes the imagined return of the tracking reward (widths times --reward_std_scale) with the soft survival weight and a critic bootstrap at the horizon; the critic regresses GAE(lambda) targets.

Both algorithms take LAFAN1's --wm_input_noise and --wm_smooth_w for the world model's fit and --pi_rollout_clip for the policy's gradient (algos.common), and BlinkMimic's options: the policy average (--pi_ema), Muon (--pi_opt, --wm_opt; --wm_opt also with the RigidFormer, on its blocks' matrices as in LAFAN1 training), the updates written without host synchronization (--no_sync: wm_update_graphable, policy_update_graphable), which --update_graphs captures as CUDA graphs.

MV = MuscleVAECore/Model/musclevae.py of wangchek/MuscleVAE_ @ 54c001c (no license: nothing is copied from it).

MuscleAgent

MuscleAgent(args, ref: MuscleReference, dev)

One learner on the muscle character; kind is the world model's parameterization (SuperTrack "accel", SuperMimic "increment"); residual: targets about the reference action.

state_dict

state_dict() -> dict

Everything a resumed run continues from: the networks with their normalizers and the optimizers' states.

update_pi_avg

update_pi_avg()

--pi_ema: one step of the policy's moving average, after a policy update (a no-op without it).

average_graphable

average_graphable()

--pi_ema in the graphable policy updates: the average's step without a host read (algos.common.ema_step); its first step, which copies the policy, runs eagerly before any capture.

act

act(
    obs: Tensor, f: Tensor, tap: Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor]

The action (muscle targets a) of a step that tracks reference frame f, and the policy's output; tap (--pi_rollout_clip): a zero tensor added to the output, whose gradient is the output's adjoint.

update_pi_norms

update_pi_norms(obs: Tensor, f: Tensor)

The policy's normalizers from the observations it acts on and the goals of the frames f.

update_wm_norms

update_wm_norms(tr: dict)

The world model's normalizers from a step's transitions, without those the guard flagged.

wm_update

wm_update(buffer) -> torch.Tensor | None

One world-model update on a batch of replay windows; skipped (and counted) if its gradient is not finite. Returns the loss per window step (the fit loss, without --wm_smooth_w's penalty), None when skipped.

wm_update_graphable

wm_update_graphable(buffer) -> tuple

wm_update for --no_sync and --update_graphs: no host synchronization, the optimizer step skipped on the device for a non-finite gradient (counted in wm_skips). Returns the loss per window step and whether the update stepped (0-dim bool). SuperTrack's model loss balancer is calibrated by the first, eager update.

starts

starts(buffer) -> dict

B replay states (module docstring): the bodies (kicked with --imag_start_perturb), the muscle state, the frame the recorded step tracked, the episode step and the off count before it, the previous step's action if the episode and the replay have one.

starts_nosync

starts_nosync(buffer) -> dict

starts without reading the valid count on the host (--no_sync): 2B candidates (the default's first draw), stable-sorted valid first, the first B kept: the default's starts whenever that draw holds B valid ones; a draw with fewer is counted in short_starts, which train_muscles checks at every log row.

imagine

imagine(st: dict, taps: list | None = None)

H imagined steps from the starts; per step the state, muscle state, off count, termination probability and record, and the frame the next step would track. taps (a list, for --pi_rollout_clip): per step the policy's observation and goal and a zero tensor added to its output are appended.

MuscleSuperTrack

MuscleSuperTrack(args, ref, dev)

Bases: MuscleAgent

SuperTrack on the muscle character (module docstring).

graph_keys property

graph_keys: tuple

policy_update_graphable's outputs before ok.

policy_update_graphable

policy_update_graphable(buffer) -> tuple

policy_update for --no_sync and --update_graphs: the starts selected on the device, the survival products a loop of products, the step gated on the device, the policy average's step. Returns the default update's values (graph_keys) and whether it stepped (0-dim bool).

MuscleSuperMimic

MuscleSuperMimic(args, ref, dev)

Bases: MuscleAgent

SuperMimic on the muscle character (module docstring).

critic_input

critic_input(
    S, F, f: Tensor, count: Tensor
) -> torch.Tensor

The critic's input for a state that should match reference frame f (the next step tracks f + 1): the policy's observation and goal, the re-anchored body position errors in the root's heading frame, the off count.

policy_update_graphable

policy_update_graphable(buffer) -> tuple

policy_update for --no_sync and --update_graphs: the starts selected on the device, the survival products a loop of products, the actor's and the critic's steps (and the critic normalizer's update) skipped on the device where the gradient or the imagined rollout is not finite, the policy average's step. Returns the default update's values (graph_keys) and whether it stepped (0-dim bool).

replay_fields

replay_fields() -> dict

A transition in the replay (ndm_gym.buffer.ReplayBuffer): the states before and after the step (tasks.muscle_tracking), the muscle states, the action, the reference frame the step tracked, the episode step and MuscleVAE's off count before it, the flags, and whether the guard flagged it.

local_terms

local_terms(S) -> tuple

SuperTrack's Local(X) (algos.supertrack.local_features, Eq. 1-7) with the 3 x 3 products written elementwise: positions, velocities, 6-D rotations and rotation rates in the root's frame, the heights and the up direction.

wm_terms

wm_terms(S_hat, F_hat, S, F) -> torch.Tensor

L1 errors (..., 5) of world-space body positions, velocities, rotations (log), rotation rates and the muscle state.

ndm_gym.algos.quadrotor_algos

SuperTrack and SuperMimic for quadrotor trajectory tracking (tasks.quadrotor_tracking), as hand-object tracking has them (algos.hand_algos): both fit the world model on k-step windows of simulator transitions and train the policy through imagined rollouts of the frozen world model from replayed states. The systems options are the hand task's (algos.hand_fast), with a collection step of this task's (QuadCollector).

SuperTrack (QuadSuperTrack): the acceleration world model; the policy minimizes, over the imagined window, the L1 errors of what the task tracks (TERMS: position, rotation, linear velocity, body rates), each term weighted once to 1 at calibration (supertrack.LossBalancer) or, with --st_task_weights, by the task's reward weight over its kernel's width; plus the failure penalty on the task's soft termination (--st_fail_w) and the regularizer on the actions (--st_reg), which are offsets about the reference's command. --st_imag_noise adds Gaussian noise to the imagined actions. No reward, no critic.

SuperMimic (QuadSuperMimic; Liao et al., CoRL 2026): the increment world model; the policy maximizes the imagined tracking return with a soft survival weight and a critic beyond the horizon. --bptt_decay lam scales the gradient through the imagined state by lam at every step.

QuadSuperMimic

QuadSuperMimic(
    args, task: QuadTask, dev: str, substeps: int = 4
)

act

act(
    S, a_prev: Tensor, f: Tensor, noise: float = 0.0
) -> torch.Tensor

The policy's action in the simulator, with Gaussian exploration noise; fits the policy's input normalizer.

wm_update

wm_update(buffer: ReplayBuffer) -> torch.Tensor

--wm_batches steps on k-step windows; returns the last step's loss.

policy_update

policy_update(buffer: ReplayBuffer) -> tuple

One policy step on imagined rollouts from replayed states, then the critic's on their lambda-returns. Returns (policy loss, value loss, imagined reward as a share of the maximum, gradient norm, imagined survival).

QuadSuperTrack

QuadSuperTrack(
    args, task: QuadTask, dev: str, substeps: int = 4
)

Bases: QuadSuperMimic

policy_update

policy_update(buffer: ReplayBuffer) -> tuple

One policy step on imagined rollouts from replayed states. Returns (policy loss, NaN, imagined reward as a share of the maximum, gradient norm, imagined survival), the layout of SuperMimic's.

QuadCollector

QuadCollector(sim, task, algo, buffer, args)

Bases: Collector

The collection step for --no_sync and --collect_graph: hand_fast.Collector's streams and capture around this task's step (collect_step with QuadSim.step_nosync).

replay_fields

replay_fields() -> dict

A transition: the state, the command u, the next state, the action before this step's, the frame.

collect_step

collect_step(
    sim,
    task,
    algo,
    buffer,
    args,
    a_prev: Tensor,
    ep_len: Tensor,
    acc: dict,
    step,
    add,
)

One collection step on the loop's state kept in fixed tensors (the previous action, the episode lengths, the log's sums acc), without a host read: step(u) the simulator's control step with its resets, add(transition) the replay's write.

ndm_gym.algos.quadruped_algos

SuperTrack and SuperMimic for quadruped motion tracking (tasks.quadruped_tracking), after the hand-object task's (algos.hand_algos). Both fit the world model on k-step windows of simulator transitions and train the policy through imagined rollouts of the frozen world model from replayed states.

The world model is worldmodels.mjcf's model of the Go2's generalized coordinates (world_model): the inputs do not depend on the trunk's heading and horizontal position, the free joint integrates as MuJoCo's, and the position servos' forces (robots.go2.load_scene) are among its inputs; its step is one control step. SuperTrack's predicts accelerations, SuperMimic's increments.

SuperTrack (QuadrupedSuperTrack): the policy minimizes L1 errors of the quantities the task tracks over the imagined window, each term weighted once to 1 at calibration (or by the task's weights, --st_task_weights); no reward, no critic.

SuperMimic (QuadrupedSuperMimic): the policy maximizes the imagined tracking return with a soft survival weight and a critic beyond the horizon. --bptt_decay lam scales the gradient through the imagined state by lam at every step.

The systems options are the hand-object task's (algos.hand_fast, train_quadruped): the agents build their optimizers with its optimizer and take the policy's step with its finite_step on the survival of survive; QuadrupedCollector is its collection step without host synchronization with this task's log sums.

QuadrupedSuperMimic

QuadrupedSuperMimic(
    args,
    model: MjModel,
    kin: Go2Kinematics,
    task: QuadrupedTask,
    dev: str,
)

act

act(
    S, a_prev: Tensor, f: Tensor, noise: float = 0.0
) -> torch.Tensor

The policy's action in the simulator, with Gaussian exploration noise; fits the policy's input normalizer.

wm_update

wm_update(buffer: ReplayBuffer) -> torch.Tensor

--wm_batches steps on k-step windows; returns the last step's loss.

policy_update

policy_update(buffer: ReplayBuffer) -> tuple

One policy step on imagined rollouts from replayed states, then the critic's on their lambda-returns. Returns (policy loss, value loss, imagined reward as a share of the maximum, gradient norm, imagined survival).

QuadrupedSuperTrack

QuadrupedSuperTrack(
    args,
    model: MjModel,
    kin: Go2Kinematics,
    task: QuadrupedTask,
    dev: str,
)

Bases: QuadrupedSuperMimic

SuperTrack on the quadruped task. The policy minimizes, over the imagined window, the L1 errors of TERMS: the feet about the trunk in its heading frame and in the world, the trunk's position, height and rotation, the joints, the trunk's linear and angular velocity and the joints' velocities, each term weighted once to 1 at calibration (LossBalancer). --st_task_weights: no calibration; the task's six tracked quantities each weigh, per unit of error and imagined step, the task's reward weight over its kernel's width (tasks.quadruped_tracking.RewardCfg), the other terms nothing. Plus the failure penalty on the task's soft termination (--st_fail_w: every imagined step after a failure costs that many steps' worth of loss) and the regularizer on the actions (--st_reg), which are offsets about the reference pose. --st_imag_noise adds Gaussian noise to the imagined actions. No reward, no critic: policy_update returns NaN for the value loss and the imagined reward of the same rollouts for the log.

policy_update

policy_update(buffer: ReplayBuffer) -> tuple

One policy step on imagined rollouts from replayed states. Returns (policy loss, NaN, imagined reward as a share of the maximum, gradient norm, imagined survival), the layout of SuperMimic's.

QuadrupedCollector

QuadrupedCollector(sim, task, algo, buffer, args)

Bases: Collector

train_quadruped's collection step for --no_sync (hand_fast.Collector) with the quadruped task's state and log sums.

replay_fields

replay_fields() -> dict

A transition: the state, the position targets u, the next state, the action before this step's, the frame.

world_model

world_model(
    model: MjModel,
    kind: str,
    hidden=(1024, 1024, 1024),
    act: str = "silu",
    layer_norm: bool = True,
) -> MjcfWorldModel

The world model of the Go2 scene model over one control step.