Skip to content

World models

ndm_gym.worldmodels

Learned differentiable dynamics s_{t+1} = f(s_t, a_t, xi) over the state layout of :mod:ndm_gym.state.

Every world model exposes inputs(S, a, xi_n), targets(S, S1) (regression targets, used to fit the output normalizer), step(S, a, xi_n), and the running normalizers in_norm / out_norm.

ndm_gym.worldmodels.accel

SuperTrack world model: predicts accelerations and integrates them (Fussell et al. 2021, §3.4, Eq. 8-12).

AccelWorldModel

AccelWorldModel(
    hidden=(2048, 2048, 2048),
    substeps: int = 1,
    act: str = "silu",
    layer_norm: bool = True,
    rigidformer: dict | None = None,
)

Bases: Module

Deterministic dynamics s_{t+1} = f(s_t, a_t, xi) predicting the root's linear/angular accelerations in its own frame and the joint accelerations, integrated over one control step with semi-implicit Euler.

substeps n integrates the (constant) predicted acceleration as n semi-implicit Euler substeps of dt / n, in closed form: velocities gain dt * a, positions dt * (v + (n + 1) / (2 n) * dt * a). n = 1 is the paper's single step (Eq. 9-12); n = 4 matches the simulator's four 5 ms substeps.

targets staticmethod

targets(S, S1)

Mean accelerations from S to S1 over one control step (the regression targets).

step

step(S, a, xi_n, input_noise: float = 0.0, taps=None)

input_noise: std of Gaussian noise on the normalized inputs (only while fitting, as a regularizer). taps (--wm_deferred_grads, the MLP only: one application's slices of nets.mlp_taps): the network through nets.run_mlp_deferred; returns (the next state, the Linear layers' inputs).

ndm_gym.worldmodels.increment

SuperMimic world model: predicts frame-local increments of every state component (paper §3.2, Table A.4).

IncrementWorldModel

IncrementWorldModel(
    hidden=(2048, 2048, 2048),
    act: str = "silu",
    layer_norm: bool = True,
    rigidformer: dict | None = None,
)

Bases: Module

Deterministic dynamics s_{t+1} = f(s_t, a_t, xi) predicting frame-local state increments.

targets staticmethod

targets(S, S1)

Frame-local increments from S to S1 (the regression targets).

net_out

net_out(x, taps=None)

The network's output for its normalized inputs; with taps (--wm_deferred_grads, the MLP only: one application's slices of nets.mlp_taps) from nets.run_mlp_deferred, with each Linear layer's input.

step

step(S, a, xi_n, input_noise: float = 0.0, taps=None)

input_noise: std of Gaussian noise on the normalized inputs (only while fitting, as a regularizer). taps (--wm_deferred_grads; net_out): returns (the next state, the Linear layers' inputs).

state_error staticmethod

state_error(S_hat, S)

Frame-local state error components (same layout as targets).

ndm_gym.worldmodels.semi_implicit

BlinkMimic's semi-implicit world model (--wm_structured): velocity increments are predicted, positions integrated.

The network predicts the velocity increments and, for the positions, corrections on top of the semi-implicit drift: the position change that the old and new velocities imply over the control step, dt ((1 - c) v + c v'). c = (n + 1) / (2 n) = 0.625 for the simulator's n = 4 substeps. This is the idea of SuperTrack's acceleration world model (Fussell et al. 2021, §3.4; accel.py): velocities from the network, positions by semi-implicit integration. With zero corrections a step equals AccelWorldModel's with --st_substeps 4 (tests/test_blinkmimic.py). SuperMimic's world model (increment.py) predicts every increment, positions included, directly.

SemiImplicitIncrementWorldModel

SemiImplicitIncrementWorldModel(
    hidden=(2048, 2048, 2048),
    act: str = "silu",
    layer_norm: bool = True,
    rigidformer: dict | None = None,
)

Bases: IncrementWorldModel

IncrementWorldModel whose network outputs (the targets layout) are the velocity increments and the position corrections on top of the drift. The fit's loss is normalized by the plain increments' scale (inc_norm).

drift

drift(S, v1, w1, qd1)

The semi-implicit position change from S with the new velocities, in the increments' frames: the heading frame for the root position, the body frame for the rotation vector.

targets

targets(S, S1, inc=None)

The velocity increments and the position corrections on top of the drift from S to S1; inc: the plain increments increments(S, S1) where the caller has them (train.py --compile_norms).

integrate

integrate(S, d)

The next state from denormalized network outputs d (the targets layout).

step

step(S, a, xi_n, input_noise: float = 0.0, taps=None)

input_noise: std of Gaussian noise on the normalized inputs (only while fitting, as a regularizer). taps (--wm_deferred_grads; net_out): returns (the next state, the Linear layers' inputs).

ndm_gym.worldmodels.rigidformer

RigidFormer-style body-token Transformer backbone for the world models of :mod:ndm_gym.worldmodels.

Structure after RigidFormer (Z. Dou et al., "RigidFormer: Learning Rigid Dynamics using Transformers", arXiv 2605.09196), re-implemented for an articulated body rather than copied: one token per rigid body instead of one per free object, analytic forward kinematics instead of the point-cloud encoder, 3-D rotary attention on the body positions, pre-norm blocks with RMS and QK normalization, gated attention and SwiGLU, register tokens, FiLM conditioning on the global sim context, and per-body read-out heads in reduced coordinates (exact joint constraints, the articulated counterpart of RigidFormer's Kabsch projection). Design and measurements: docs/rigidformer_backbone.md.

Shapes (N rollouts, B = 30 bodies in kinematic-tree order, J = 29 joints in G1 order, F = token width): net.inputs(S, a [N,J], xi_n [N,XI_DIM], f=None) -> x [N, D], D = BF + GLOBAL_DIM raw features, fit by in_norm in_norm(x) (TokenInputNorm) -> [N, D + 3B] normalized x, then body positions / POS_SCALE net(in_norm(x)) -> y [N, root_out + Jjoint_out] normalized outputs With K > 1 anchors per body (anchors, RigidFormer's anchor RoPE), x also holds P rotary points of every body after the global context, which in_norm passes through instead of the body positions (D + 3BP and D + 6BP): with anchor_mode="mean" (ARoPE, the mean of the anchors' rotary angles) P = 1, the anchors' centroid, whose angles that mean is, the angles being linear in the position; with "concat" (every anchor coordinate its own channels) P = K, the anchors; see Rope3d. The rotary positions are those of the inputs (heading frame, origin at the pelvis's ground projection, where the registers sit), or with rope_center relative to their centroid over all bodies (and anchors). The world models' step is unchanged: its optional input noise (normalized units) also jitters the rotary positions, by input_noise * POS_SCALE metres (each rotary point independently). y holds the root components first, then each joint component over the J joints: (6, 29 x 1) is ACC_OUT of the acceleration model, (12, 29 x 2) is WM_OUT of the increment model.

Token features of body b (F = TOKEN_DIM, + WRENCH_DIM with ext_wrench), in the root's heading (yaw) frame with the origin at the pelvis's ground projection: [0:3] position (height kept absolute) [3:9] 6-D rotation [9:12] linear velocity [12:15] angular velocity [15:21] the body's parent joint: q, qd, setpoint u, PD error q0 + offset + alpha u - q, PD torque / effort limit (clipped), calibration offset (normalized xi); zeros on the pelvis [21:27] optional external wrench [F; tau about the link origin] (f.wrench_h[:, b] of inputs) followed by the global context (friction and torso center-of-mass offset, normalized xi) that conditions every block.

TreeKinematics

TreeKinematics(kin: ArticulationKinematics)

Bases: Module

ArticulationKinematics.forward(..., all_bodies=True) with its constants as non-persistent buffers, so they follow the module's device (tests/test_rigidformer_backbone.py).

forward

forward(p, R, v, w, q, qd)

World positions (N,B,3), rotations (N,B,3,3), link-origin linear and angular velocities (N,B,3).

Rope3d

Rope3d(dim: int, max_freq: float, points: int = 1)

Bases: Module

3-D rotary position embedding (RigidFormer's anchor RoPE). Channel pairs (2m, 2m+1) of the first dim channels of every head turn by x_c * omega_f, for the three coordinates c and dim / 6 log-spaced frequencies omega_f in [1, max_freq] rad/m, so query-key products depend on relative positions only.

RigidFormer's PhysFormerRoPE (official code, github.com/Frank-ZY-Dou/Dynamics-Modeling, RigidFormer/src/models/ physformer_rope.py) gives a token of K anchor points its angles in one of two ways: ARoPE (paper Sec. 3.3; _forward_sa_rope, physformer_rope.py:414-460): every anchor's angles as above, mean-pooled over the anchors. The angles are linear in the position, so this is the one point above at the anchors' centroid, as that file says (lines 289-294 and 423-430); RigidFormerNet passes that centroid. points P > 1 (forward_multi_point with use_set_aggregation=False, physformer_rope.py:338-400): pos (N, T, P, 3), whose 3P coordinates, point by point (p0x, p0y, p0z, p1x, ...), each turn their own dim / 3P channels by dim / 6P log-spaced frequencies in [1, max_freq] rad/m. dim must be a multiple of 6P; other settings are refused, as there (lines 349-372), not truncated. Both channels of a pair turn by the same angle, as there with INTERLEAVED_PAIRING (physformer_rope.py:106-120); its default half-split layout gives them different angles when a coordinate has more than one frequency.

forward

forward(pos: Tensor)

pos (N, T, 3), or (N, T, P, 3) with P = points > 1 -> cos, sin (N, 1, T, dim / 2) in fp32.

Block

Block(
    dim: int,
    heads: int,
    ffn_mult: float,
    ctx_dim: int,
    fused_rope: bool = False,
)

Bases: Module

Pre-norm Transformer block of RigidFormer's decoder over a token set (any tokens: bodies, particles): x + W_o(sigmoid(gate) * Attn(RMSNorm(x))) with QK-RMSNorm, rotary positions and an optional additive bias, then FiLM x * (1 + gamma(c)) + beta(c) (zero-initialized), then x + SwiGLU(RMSNorm(x)). Attention runs through F.scaled_dot_product_attention (flash kernel without a bias, memory-efficient kernel with one), or with attention = "token" through ndm_gym.core.token_attention (inference only: no backward pass).

x (N, T, D) fp32 residual stream; cos, sin (N, 1, T, r) or None; bias (1 or N, H, T, T) or None; c (N, C) or None. fused_rope: rope_rotate_fused instead of rope_rotate (equal up to float rounding, faster when compiled).

TokenInputNorm

TokenInputNorm(dim: int, pos_index: Tensor)

Bases: RunningNorm

RunningNorm of the flat token features whose forward also passes the body positions through, unnormalized up to the fixed POS_SCALE, for the rotary attention: x (N, D) -> (N, D + 3B). update and the state dict are RunningNorm's.

RigidFormerNet

RigidFormerNet(
    kin: ArticulationKinematics,
    root_out: int,
    joint_out: int,
    dim: int = 128,
    layers: int = 3,
    heads: int = 4,
    ffn_mult: float = 2.5,
    registers: int = 2,
    rope: bool = True,
    rope_max_freq: float = 10.0,
    rope_detach: bool = False,
    tree_bias: bool = True,
    film: bool = True,
    head_layers: tuple[int, ...] | None = None,
    ext_wrench: bool = False,
    checkpoint: str = "frozen",
    fused_rope: bool = False,
    fused_train: bool = False,
    anchors: int = 1,
    anchor_mode: str = "mean",
    rope_center: bool = False,
    keep_ops: bool = False,
    merge: str = "none",
)

Bases: Module

Body-token Transformer: per-body features -> shared token embedding + learned body embedding (+ registers) -> layers blocks with rotary positions, a kinematic-tree attention bias and FiLM on the global context -> a SwiGLU fusion of the token features of head_layers (0 = embedding) -> root head on the pelvis token, shared joint head on the other tokens. Both heads start at zero, like the MLP's last layer.

Parameters:

Name Type Description Default
kin ArticulationKinematics

kinematics of the articulation (body 0 the floating root; body b >= 1 owns one joint).

required
root_out, joint_out

outputs per root (6 accel / 12 increment) and per joint (1 / 2).

required
dim, layers, heads, ffn_mult, registers

Transformer size; registers extra learned tokens at the origin.

required
rope, rope_max_freq

rotary attention on the body positions (frequencies 1..max_freq rad/m).

required
rope_detach bool

no gradient through the rotary positions while the parameters do not require gradients (the policy's BPTT, as checkpoint="frozen"); the positions still reach the token features, so only the attention pattern's dependence on them is held fixed in the backward pass. Off by default.

False
tree_bias bool

learned per-head bias on the number of joints between two bodies (registers: one extra class).

True
film bool

global context by FiLM in every block (True) or appended to every token (False).

True
ext_wrench bool

reserve the per-body external-wrench channel (f.wrench_h of inputs, then required there).

False
checkpoint str

activation checkpointing of the trunk (recomputed in the backward pass): "never", "always", or "frozen" = only while the parameters do not require gradients, i.e. in the policy's BPTT through the frozen world model, where H steps of activations would not fit (docs/rigidformer_backbone.md, measurements); "frozen_readout" = while frozen, only the read-out (the blocks' activations are kept, which fused_train makes small: two (N, T, dim) tensors per block).

'frozen'
fused_rope bool

the blocks' rotary embedding as one elementwise expression (rope_rotate_fused): the same function up to float rounding, faster under torch.compile. Off by default, which keeps the numerics of the runs trained before the flag.

False
fused_train bool

the blocks' passes under bf16 autocast (the world-model fit, the policy's BPTT) as the fused Triton kernels of ndm_gym.kernels.rf_train (CUDA; bf16 products with fp32 accumulation, everything else fp32): the same function up to float rounding. Passes without autocast (fp32: --wm_bptt_fp32, the penalty of --wm_smooth_w) run the blocks as without the option. Off by default.

False
keep_ops bool

with fused_train, the fused forward passes whose parameters train (the world-model fit) also keep the bf16 operands their backward passes would recompute (rf_block_train(keep_ops=True); about 100 MB more per block at 2048 windows); the same function up to float rounding. Off by default.

False
anchors int

K anchor points per body for the rotary attention (RigidFormer's ARoPE): K > 1 places them by RigidFormer's farthest point sampling over the body's visual meshes (ArticulationKinematics.anchors) and moves them with the body; 1 (default) keeps one point per body, its link origin (either mode).

1
anchor_mode str

how the K anchors give the rotary angles (Rope3d): "mean" (default) mean-pools their angles (ARoPE), which are the angles of their centroid: the inputs carry that body-fixed point, and the blocks see one rotary point per body as with K = 1; "concat" gives each of their 3K coordinates its own channels. The rotary channels per head are 6 * floor(head width / 8), 24 at the head width 32 of RF-S and RF-M; "concat" needs a multiple of 6K of them: K = 4 fits 24 (one frequency, 1 rad/m, per coordinate), K = 8 needs 48 (head width 64). Either mode changes only the rotary tables the blocks take, so it runs with fused_train.

'mean'
rope_center bool

the rotary positions relative to their centroid over all bodies (and anchors) of the sample, as RigidFormer's model.rope_center_positions, so that the zero-angle registers sit at that centroid instead of the pelvis's ground projection; the body tokens' query-key products do not change (rotary products depend on differences), so only the registers' attention does. Off by default.

False
merge str

bodies that share a token (token_groups: "none", the default, one token per body; "distal", "coincident" or "joints"), for fewer tokens. A token's input is its members' token features side by side, proximal to distal, zero-padded to the largest group (one shared embedding over that width, then a learned embedding per token); its rotary position is its last (distal) member's link origin; the tree bias counts the joints between tokens in the tree of tokens (a group's inner joints not counted). The read-out gives every body the features of its token plus a learned embedding of the body (bodies sharing a token only), then the SwiGLU fusion and heads as without merging. The inputs, the step and the outputs are unchanged.

'none'

hidden_matrices

hidden_matrices() -> list[nn.Parameter]

Muon's parameters with --wm_opt muon (core.muon.MuonAdam): every block's weight matrices as stored (block_matrices). Adam keeps the rest: the token embedding and the context network, the body, register and read-out embeddings, the tree bias, the norms, the biases, FiLM, and the read-out's SwiGLU fusion and heads.

inputs

inputs(S, a, xi_n, f=None)

Flat raw features (N, in_dim) of states S, normalized setpoints a (N, J) and normalized sim context xi_n.

f: the external forces, whose wrench_h (N, B, 6) holds every body's force and torque about its link origin in the root's heading frame; required with ext_wrench, must be None without.

forward

forward(x)

x (N, in_dim + 3B), or (N, in_dim + 3BP) with P rotary points per body, from TokenInputNorm -> y (N, out_dim).

token_groups

token_groups(
    kin: ArticulationKinematics,
    mode: str = "none",
    gap: float = MERGE_GAP,
) -> list[list[int]]

The bodies each token holds (RigidFormerNet(merge=...)), tokens in tree order, members proximal to distal. A link only ever joins its parent's token, and only when the parent is not the root and has no other child (a serial chain).

"none": one token per body. "coincident": a link joins when its origin lies within gap of its parent's (kin.off_p): serial hinges whose axes nearly meet. "distal": only those of the "coincident" chains that end at a leaf. "joints": one token per anatomical joint, the hinges named <joint>_{pitch,roll,yaw}_joint along a chain. On the G1 (kinematics; 30 bodies): "distal" merges each wrist's roll, pitch and yaw links (origins 3.8 and 4.6 cm apart) and each ankle's pitch and roll links (1.8 cm), 24 tokens; "coincident" also the waist's yaw and roll links with the torso (4.4 and 0 cm) and each shoulder's pitch and roll links (4.0 cm), 20 tokens (the next closest pair, a hip's pitch and roll links, is 6.0 cm apart); "joints" merges every hip's, shoulder's and wrist's three links, every ankle's two and the waist's two with the torso, 14 tokens: the pelvis, the waist, and per side the hip, knee, ankle, shoulder, elbow and wrist.

tree_hops

tree_hops(parent: list[int]) -> torch.Tensor

Number of joints on the path between every pair of bodies of a kinematic tree: (B, B) long.

rope_rotate

rope_rotate(
    x: Tensor, cos: Tensor, sin: Tensor
) -> torch.Tensor

Rotate the leading 2 * cos.shape[-1] channels of x (N, H, T, hd) in fp32; the other channels pass.

rope_rotate_fused

rope_rotate_fused(
    x: Tensor, cos: Tensor, sin: Tensor
) -> torch.Tensor

rope_rotate as one elementwise expression over all channels, x * c + (x with the two channels of every pair swapped) * s, with c = (cos, cos) and s = (-sin, sin) on a pair and c = 1, s = 0 on the channels that pass. Without the stack and cat of rope_rotate, torch.compile fuses the QK normalization, the rotation and the cast into one kernel per block instead of nine (A100, 4096 x 33 tokens, 4 heads: 0.18 instead of 0.78 ms per block). Equal to rope_rotate up to float rounding (the compiled kernels contract the products and sums differently).

It also avoids a miscompilation of rope_rotate by torch 2.11's Inductor: with 33 tokens, the last of them at zero positions concatenated in the graph, RMS-normalized queries (keys) and the angles computed in the same graph, the kernel that stacks the rotated halves reads its permuted, padded input (strides [1600, 12, 48, 1] for 4 heads) in logical order and scrambles heads and tokens (HOIRigidFormerNet: 31 tokens and 2 registers). The G1's 32 tokens are not affected (checked at the study's shapes).

block_matrices

block_matrices(blocks: ModuleList) -> list[nn.Parameter]

Muon's parameters of a RigidFormer's blocks (Block) with --wm_opt muon (core.muon.MuonAdam; the hidden_matrices of RigidFormerNet and of the muscle character's MuscleRigidFormerNet): every block's weight matrices as stored, the q/k/v/gate projection (4 dim x dim, one matrix), the attention's output projection, the SwiGLU's value and gate projection (2 hidden x dim, one matrix) and its output projection.

rigidformer_kwargs

rigidformer_kwargs(a: dict) -> dict | None

RigidFormerNet keyword arguments for training arguments a (--wm_backbone, --rf_*), None for the MLP. The MLP's own flags must stay at their defaults with this backbone (they would otherwise be silently ignored).

ndm_gym.worldmodels.g1_infer

Inference copies of the G1 world models (AccelWorldModel, IncrementWorldModel) for simulation throughput, as HOIWorldModel.inference_copy for HDMI's scenes: the LAFAN1 tracking and the two-G1 boxing scene's NDMs.

inference_copy(wm, dtype, attention, fused) returns a G1InferenceModel (no parameter requires gradients) whose step(S, a, xi_n) is the world model's: dtype bf16: the network's parameters in bf16 and the step without autocast, so the network runs in bf16 end to end (the RigidFormer's token features, residual stream, norms, attention and heads: InferenceRigidFormerNet; the MLP's layers); the input features, kinematics, normalizers and integration stay fp32. None keeps the fp32 parameters under the step's bf16 autocast, as the model as trained. attention the RigidFormer's attention: "token" (ndm_gym.core.token_attention) or "sdpa"; its relation bias is gathered once. The MLP takes None. fused the features (the RigidFormer's forward kinematics and token features, the MLP's invariant features) and the integration as two Triton kernels (g1_fused), the normalizers fused with the network's casts; CUDA only. The semi-implicit MLP world model (--wm_structured) integrates with its own drift there. The RigidFormer's blocks or its whole network can then run as fused Triton kernels (kernels.rf_block.fused_copy of an fp32 copy, dtype None; a bf16 copy is refused there).

Every copy is compared with the model it was made from on the device before use (check) and refused on a mismatch: the fused features and integration against the model's own inputs and step in fp32 (float rounding), the network against the model's in fp32: its distance may not exceed that of the model under bf16 autocast (the as-trained path) by more than 2x on average and 4x at the largest. Forward only: the copies refuse to run with gradients enabled.

InferenceRigidFormerNet

InferenceRigidFormerNet(
    kin: ArticulationKinematics,
    root_out: int,
    joint_out: int,
    dim: int = 128,
    layers: int = 3,
    heads: int = 4,
    ffn_mult: float = 2.5,
    registers: int = 2,
    rope: bool = True,
    rope_max_freq: float = 10.0,
    rope_detach: bool = False,
    tree_bias: bool = True,
    film: bool = True,
    head_layers: tuple[int, ...] | None = None,
    ext_wrench: bool = False,
    checkpoint: str = "frozen",
    fused_rope: bool = False,
    fused_train: bool = False,
    anchors: int = 1,
    anchor_mode: str = "mean",
    rope_center: bool = False,
    keep_ops: bool = False,
    merge: str = "none",
)

Bases: RigidFormerNet

RigidFormerNet of an inference copy: its forward in the parameters' precision (bf16 end to end; fp32 parameters run under the caller's autocast as the model as trained, the residual stream fp32), the relation bias gathered once (bias_table), the blocks' attention by attention, fp32 outputs. Made by from_net (a copy). The blocks run as Blocks or as the fused kernels' FusedBlock (fused_copy), never as the training kernels of fused_train.

CastNet

CastNet(net: Module, dtype: dtype)

Bases: Module

An MLP of an inference copy with dtype parameters: its input cast to them, its output to fp32.

G1InferenceModel

G1InferenceModel(wm: Module, fused: bool)

Bases: Module

An inference copy of a G1 world model (inference_copy): wm, a copy of it with its network made for inference, and step(S, a, xi_n): wm.step, or with fused the step's features and integration as Triton kernels around the same network.

features

features(S, a, xi_n) -> torch.Tensor

The network's normalized input as wm.in_norm(wm.inputs(S, a, xi_n)), from the fused kernel (fused).

integrate

integrate(y, S)

The next state from the network's normalized outputs y, by the fused kernel (fused).

inference_copy

inference_copy(
    wm: Module,
    dtype: dtype | None = torch.bfloat16,
    attention: str | None = "token",
    fused: bool = False,
    check: bool = True,
) -> G1InferenceModel

An inference copy of the G1 world model wm (module docstring); with check, compared with wm on the device first (check_copy).

random_inputs

random_inputs(n: int, device, seed: int = 0) -> tuple

States S, setpoints a and normalized contexts xi_n of n robots for the checks: the root near standing height, random rotations and velocities, joints within about +-0.5 rad.

network_errors

network_errors(
    ref_net: Module, net: Module, x: Tensor, amp: bool
) -> tuple[tuple[float, float], tuple[float, float]]

(max, mean) |net(x) - ref_net(x) in fp32| for net as a copy runs it (under bf16 autocast with amp) and for ref_net under bf16 autocast (the model as trained).

check_copy

check_copy(wm: Module, m: G1InferenceModel, n: int = 64)

Raise unless the inference copy m matches the world model wm it was made from on its device: the fused features and integration within float rounding of wm.inputs / wm.step in fp32, the network within the bf16-autocast reference's error (module docstring).

ndm_gym.worldmodels.hoi

Neural dynamics models of HDMI's human-object interaction scenes (docs/hoi_design.md §3): one 20 ms control step of the robot and the tracked object, and the contact forces, from the state, the four physics substeps' filtered actions and the per-env context (HDMISim.context).

Two parameterizations of the step, as the LAFAN1 world models: "accel" (SuperTrack's, accel.py: accelerations in the bodies' frames, integrated with semi-implicit Euler) and "increment" (SuperMimic's, increment.py: frame-local increments). A free object is integrated like the robot's root; a hinged object's base is fixed, so only its hinge angle and rate change. Both are fit with the same loss, window_loss: SuperMimic's normalized frame-local state error over a k-step rollout, with the object's and the forces' errors appended. The frame-local targets, increments and errors are those of accel.py and increment.py with the 3 x 3 products written elementwise, so they stay fp32 where TF32 matmuls are allowed.

Shapes (N rollouts): S robot state (ndm_gym.state), So object state (p, R, v, w) or (angle (N, 1), rate (N, 1)), u (N, 4, 23) filtered actions, ctx (N, C); forces F = (end effectors (N, E, 3) in the contact body's frame, feet (N, 4, 2, 3) world frame after each substep). The inputs are invariant to a yaw of the scene, so the network predicts the feet's forces in the heading frame of the step's start state (feet_heading) and step turns them to the world frame; the contact body's frame turns with the scene.

ContextLayout

Bases: NamedTuple

Layout of HDMISim.context: the startup part, the reset part (29 joint offsets, delay, filter constant, hinge friction and damping), then 12 numbers (position, rotation matrix) per pose: a fixed base's, then each prop's.

scalars property

scalars: int

Length of the leading part without poses.

HOIWorldModel

HOIWorldModel(
    kind: str,
    hinged: bool,
    num_eefs: int,
    layout: ContextLayout,
    hidden=(2048, 2048, 2048),
    act: str = "silu",
    layer_norm: bool = True,
    rigidformer: dict | None = None,
)

Bases: Module

Deterministic one-step model (S, So, u, ctx) -> (S', So', F') of one HDMI task's scene.

inference_copy

inference_copy(
    dtype: dtype | None = torch.bfloat16,
    attention: str | None = "token",
    fused: bool = False,
) -> HOIWorldModel

A copy for inference only (simulation throughput; no parameter requires gradients). dtype: the network's parameters in that precision and step without autocast, so the network runs in it end to end (bf16: the residual stream, norms, attention and heads; the input features, kinematics, normalizers and integration stay fp32); None keeps the fp32 parameters under step's autocast. A RigidFormer's attention by attention ("token": ndm_gym.core.token_attention, "sdpa"), its read-out heads merged into one product and its relation bias gathered once (HOIRigidFormerNet.freeze_tables); the MLP takes attention=None. fused: the features (the forward kinematics and token features) and the integration as two Triton kernels (worldmodels/hoi_fused.py), the normalizers fused with the network's casts, CUDA only; equal to the unfused step up to float rounding (A100, bf16, token attention: RigidFormer 0.75 -> 0.58 ms GPU time per step at N=256 and 1.80 -> 1.59 ms at 1024, MLP 0.17 -> 0.13 and 0.31 -> 0.26 ms). On a trained RigidFormer, the network output deviates from its fp32 eager value by 1.4e-4 on average and 7.4e-3 at most (in normalized units; step under bf16 autocast: 1.1e-4 and 1.7e-2).

inputs

inputs(S, So, u, ctx)

Raw features, invariant to a shift and yaw of the whole scene: the robot's invariant features, the object and the fixed poses in the robot's heading frame, the filtered actions and the context's scalars.

targets

targets(S, So, S1, So1, F1) -> torch.Tensor

The output that maps (S, So) exactly to (S1, So1), then the forces F1 (the feet's in the heading frame of S): what out_norm normalizes.

errors

errors(pred: tuple, true: tuple) -> torch.Tensor

Frame-local error components of a prediction (S, So, F) against the truth, in err_norm's layout: in the true state's frames, as IncrementWorldModel.state_error; the feet's forces in its heading frame (the step's end; the start state is not passed, and the heading turns by one step in between).

increments

increments(S, So, S1, So1, F1) -> torch.Tensor

One true step's frame-local increments, then its forces (the feet's in the heading frame of S): the data err_norm is fit on.

step

step(S, So, u, ctx, input_noise: float = 0.0)

input_noise: std of Gaussian noise on the normalized inputs (fitting only, as a regularizer: train_hoi's --wm_input_noise); for the RigidFormer it also jitters the rotary positions, by input_noise * POS_SCALE metres.

rollout

rollout(
    S, So, u, ctx, input_noise: float = 0.0
) -> list[tuple]

Open-loop k-step prediction from (S, So) with u (N, k, 4, 23) and ctx (N, k, C): k tuples (S, So, F); input_noise as step's.

window_loss

window_loss(
    preds: list[tuple], trues: list[tuple], mask: Tensor
)

SuperMimic's world-model loss over a window: squared errors normalized by the per-component scale of one true step (with floors), averaged over components, summed over the valid steps (mask (N, k)), averaged over windows. Also returns each window's last-step error and its sum (for prioritized sampling).

HOIRigidFormerNet

HOIRigidFormerNet(
    kind: str,
    hinged: bool,
    layout: ContextLayout,
    eef_bodies: list[str],
    q0: Tensor,
    act_scale: Tensor,
    act_of_joint: Tensor,
    dim: int = 128,
    layers: int = 3,
    heads: int = 4,
    ffn_mult: float = 2.5,
    registers: int = 2,
    rope_max_freq: float = 10.0,
    checkpoint: str = "frozen",
)

Bases: Module

RigidFormer for HDMI's scenes: one token per robot body (G1 kinematic-tree order, as RigidFormerNet), one for the object, one per static prop, and register tokens; 3-D rotary attention on the tokens' positions, a learned per-head bias by relation (the kinematic-tree hop count between two bodies; one class each for body-object, body-prop, object/prop pairs and register pairs), FiLM on the context's scalars, and read-out heads on the pelvis (root), the joint tokens, the object token, the end effectors' and the ankles' tokens (contact forces).

Token features, in the robot's heading frame with the origin at the pelvis's ground projection (height absolute): body = position, 6-D rotation, linear and angular velocity, and its parent joint's angle, rate, offset, the four substeps' PD-target offsets from the default pose and PD errors (zeros on the pelvis); object = position, 6-D rotation, velocities, or for a hinge its base's position and 6-D rotation, angle, rate, Coulomb friction and damping; prop = position and 6-D rotation. inputs returns them flat with the context's scalars, forward takes them through TokenInputNorm (positions passed on for the rotary attention) and returns the flat output in HOIWorldModel's layout.

checkpoint: activation checkpointing of everything after the input split (recomputed in the backward pass), as RigidFormerNet's: "never", "always", or "frozen" = only while the parameters do not require gradients, i.e. in the policy's BPTT through the frozen world model, where the horizon's activations dominate the memory.

freeze_tables

freeze_tables()

For inference copies (parameters frozen): the relation bias gathered once, and the five read-out heads as one linear layer over the read tokens followed by a gather with an index table built here (one product instead of five; the same outputs up to rounding).

object_increment

object_increment(So, So1) -> torch.Tensor

Frame-local increments of a free body (p, R, v, w), the object or the robot's root, as the root's in IncrementWorldModel.targets: the displacement in the heading frame of R, the rotation and the velocity changes in R's frame. The 3 x 3 products are elementwise (mat_mat, mat_vec), so they stay fp32 where TF32 is allowed (train_hoi), where the batched product R^T R1 leaves rotation errors of about 5e-4.

robot_increment

robot_increment(S, S1) -> torch.Tensor

IncrementWorldModel.targets(S, S1), also its state_error(S1, S), with the products elementwise.

robot_accel

robot_accel(S, S1) -> torch.Tensor

AccelWorldModel.targets(S, S1), the mean accelerations over one control step, with the products elementwise.

feet_heading

feet_heading(R, F) -> torch.Tensor

The feet's forces F (..., 4, 2, 3) in the heading frame of the root's rotation R (..., 3, 3): H^T F, H = yaw_mat(R).

invariant_features

invariant_features(S) -> torch.Tensor

ndm_gym.state.invariant_features with the 3 x 3 products written out elementwise (mat_mat, mat_vec): torch.compile fuses them with the rest of the step instead of launching batched matmuls, which also run in TF32 when it is allowed. Equal up to float rounding.

rigidformer_args

rigidformer_args(
    constants: dict,
    dim: int = 128,
    layers: int = 3,
    heads: int = 4,
    registers: int = 2,
) -> dict

HOIRigidFormerNet's keyword arguments from a task's ndm_gym.sim.rigid.hdmi_sim.ndm_constants and a size.

ndm_gym.worldmodels.muscle

World models of MuscleVAE's muscle-actuated character (docs/musclevae_design.md §4), in maximal coordinates: the next state of the 23 bodies and the muscle state (ndm_gym.tasks.muscle_tracking) from the state, the muscle state and the action (the 284 muscle targets). The character's 14 ball joints have no single-angle coordinates, so the model works on the bodies, as SuperTrack's and MuscleVAE's do.

Inputs, in the root's heading frame H (the yaw of the pelvis's rotation): the root's height, and per body its position relative to the root, its rotation (6-D), velocity and rotation rate; the muscle state (15); the action (284): 645 values.

Outputs, per body in the same frame (kind): * "accel" (SuperTrack, Fussell et al. 2021 §3.4, Eq. 8-12; MuscleVAE's world model predicts the same, each body's change of velocity and angular velocity): the linear and angular accelerations over the control step, integrated by semi-implicit Euler, v' = v + dt H a_v, w' = w + dt H a_w, p' = p + dt v', R' = exp(dt w') R, which is exact for the state's backward-difference velocities; and the muscle state's rate of change, F' = F + dt dF/dt. * "increment" (SuperMimic §3.2): the increments of position, rotation (R' = exp(H dth) R), velocity and rotation rate, and of the muscle state.

The network is the G1 world models' MLP (core.nets, zero-initialized output) between running normalizers (core.normalizer), or with rigidformer the token Transformer MuscleRigidFormerNet, one token per body and one per muscle, or one per body that also carries the muscles' analytic wrench (docs/musclevae_design.md §5); the outputs' normalizer floor is the G1 models' 1e-4 per step (per second for the accelerations and rates). All 3 x 3 products are written elementwise (core.kinematics.mat_vec, mat_mat), so no TF32 matmul rounds them.

MuscleRigidFormerNet

MuscleRigidFormerNet(
    kind: str,
    muscle_model: str = "released",
    dim: int = 128,
    layers: int = 3,
    heads: int = 4,
    ffn_mult: float = 2.5,
    registers: int = 2,
    rope: bool = True,
    rope_max_freq: float = 10.0,
    tree_bias: bool = True,
    checkpoint: str | None = None,
    tokens: str = "all",
    muscle_dim: int | None = None,
    fused_train: bool = False,
    fused_features: bool = False,
)

Bases: Module

RigidFormer for MuscleVAE's character (docs/musclevae_design.md §5), with one of two token sets (tokens):

"all": one token per body (23, the tree's order), one per muscle (284) and register tokens; 3-D rotary attention on the tokens' positions (a body's center of mass, a muscle's path midpoint; registers at the origin), a learned per-head bias by relation (relation_classes), FiLM on the muscle state (the 15 part fatigue values), and read-out heads on the body tokens (each body's accelerations or increments of MuscleWorldModel) and on each body part's muscle tokens, pooled with the part fatigue's f0 weights (the part's three fatigue rates or increments).

"body": the body tokens and the registers only. Each body token also carries the force and the torque about its origin that the muscles' forces (the clipped PD force below) exert on it through the muscle model's anchors (robots.muscles.MuscleModel.body_wrench), and the mean, over the muscles attached to it (muscle_bodies), of the muscle encodings SiLU(Linear(the muscle's MUSCLE_SCALARS features) + a learned per-muscle embedding), each muscle_dim wide (default 32), mapped linearly to the token width. The attention bias classes are the joints between two bodies, and one more for any pair with a register. The fatigue read-out has one token per body part: the f0-weighted mean of its muscles' encodings, mapped linearly, plus the mean of the body tokens over the bodies its muscles attach to (f0-weighted, each muscle's weight shared equally by its bodies); the part tokens go through the body tokens' read-out to the fatigue head.

The blocks are RigidFormerNet's (rigidformer.Block); the heads start at zero, like the MLP's last layer. With fused_train (body tokens, 23 bodies and registers a power of two: registers=9), the blocks' passes under bf16 autocast run as kernels.rf_train's fused kernels, as RigidFormerNet's fused_train (the same function up to float rounding; passes without autocast run the blocks). With fused_features (body tokens), the muscles' lengths, length rates and wrench on CUDA in fp32 come from kernels.muscle_geometry's fused kernels (the same functions up to float rounding; elsewhere from robots.muscles).

Token features, in the root's heading frame H with the origin at the pelvis's ground projection (heights absolute): body (BODY_TOK): position, 6-D rotation, velocity, rotation rate, and relative to its parent its rotation (6-D) and rotation rate in the parent's frame (zeros on the pelvis); with "body", then the muscle wrench (WRENCH); muscle (MUSCLE_TOK), from the bodies by robots.muscles (muscle_model's parameters): length over rest length, normalized length, length rate over rest length (1/s), action, PD error over rest length, and what the first substep's muscle step gives with the muscle's part fatigue standing in for its own (the world model's state has no per-muscle fatigue): the clipped PD force over f0max, the activation, the force-length, force-velocity and passive factors; then its part's fatigue (MA, MR, MF), its path midpoint and the unit directions of its first and last segments. With "body", the first MUSCLE_SCALARS of them (up to the part's fatigue). inputs returns them flat with the muscle state; forward takes them through TokenInputNorm (positions passed on for the rotary attention) and returns the flat output in MuscleWorldModel's layout.

checkpoint: activation checkpointing of the world model's whole step, the features included, recomputed in the backward pass (MuscleWorldModel.step): "never", "always", or "frozen" = only while the parameters do not require gradients (the policy's BPTT). Default (None): "always" for the muscle tokens (with 309 tokens the activations of a window fit or of the policy's BPTT do not fit otherwise), "frozen" for the body tokens (a window fit's activations fit; the BPTT's 32 steps at 4096 rollouts do not).

muscles

muscles(device, dtype=torch.float32) -> mu.MuscleModel

The muscle model on device in dtype (built once for each, outside any compiled graph).

geometry_tables

geometry_tables(device) -> list[torch.Tensor]

The fused geometry kernels' tables on device (built once, outside any compiled graph).

hidden_matrices

hidden_matrices() -> list[nn.Parameter]

Muon's parameters with --wm_opt muon (core.muon.MuonAdam), as the G1 RigidFormer's: every block's weight matrices as stored (rigidformer.block_matrices). Adam keeps the rest: the token embeddings and the context network, the per-token and register embeddings, with "body" the muscle encoder and its maps to the token and read-out widths, the relation bias, the norms, the biases, FiLM, and the read-out's SwiGLU fusion and heads.

recompute

recompute() -> bool

Whether a step with gradients is recomputed in the backward pass (checkpoint).

MuscleWorldModel

MuscleWorldModel(
    kind: str,
    hidden=(2048, 2048, 2048),
    act: str = "silu",
    layer_norm: bool = True,
    rigidformer: dict | None = None,
)

Bases: Module

Deterministic dynamics (S', F') = f(S, F, a) of the muscle character's bodies and muscle state (module docstring). rigidformer: keyword arguments of MuscleRigidFormerNet for the token Transformer instead of the MLP (None).

targets

targets(S, F, S1, F1) -> torch.Tensor

The regression targets from (S, F) to (S1, F1): the outputs that :meth:integrate turns into (S1, F1).

integrate

integrate(S, F, y: Tensor)

The next state and muscle state from the outputs y (denormalized).

step

step(S, F, a, input_noise: float = 0.0)

One control step; input_noise: std of Gaussian noise on the normalized inputs (fitting only).

heading

heading(S) -> torch.Tensor

The root's heading rotation H (..., 1, 3, 3), broadcast over the bodies.

increments

increments(S, F, S1, F1) -> torch.Tensor

From (S, F) to (S1, F1), per body in S's heading frame: position, rotation (log of R1 R^T), velocity and rotation rate increments, then the muscle state's: (..., 291).

body_hops

body_hops() -> np.ndarray

Number of joints between every pair of the character's bodies: (NB, NB).

relation_classes

relation_classes(
    muscle_bodies: list[set[int]], registers: int
) -> tuple[torch.Tensor, int]

The attention bias's class of every token pair (bodies, then muscles, then registers): (T, T) long, and the number of classes. Two bodies: the joints between them, h; a muscle and a body: h + K from the nearest body the muscle's anchors move with; two muscles: h + 2 K between their nearest bodies; any pair with a register: 3 K, with K = the largest h + 1.

rigidformer_kwargs

rigidformer_kwargs(args) -> dict | None

MuscleRigidFormerNet's keyword arguments for training arguments args (--wm_backbone, --rf_*, --muscle_model; ndm_gym.train_muscles), None for the MLP. Runs from before --rf_muscle_tokens have "all".

ndm_gym.worldmodels.hand

World model of a hand and the object it handles, on the hand-object state (tasks.hand_tracking), in the two parameterizations of the LAFAN1 world models. increment (SuperMimic's, worldmodels.increment): an MLP predicts the increments of every state component. accel (SuperTrack's, worldmodels.accel): it predicts the accelerations of the joints and of the object (linear and angular, world frame), integrated with semi-implicit Euler over one control step. Both read the hand's joints, the object about the palm and in the world (its height and tilt decide the contact with the floor), and the position targets' offsets from the joints, and both are fit with the same error: the next state's, in units of the spread of one true step's increments.

HandWorldModel

HandWorldModel(
    num_joints: int,
    hidden: Sequence[int] = (1024, 1024, 1024),
    act: str = "silu",
    layer_norm: bool = True,
    kind: str = "increment",
)

Bases: Module

Deterministic dynamics s_{t+1} = f(s_t, u_t), u_t the joints' position targets.

increments staticmethod

increments(S: HandState, S1: HandState) -> torch.Tensor

The increments from S to S1: the object's rotation in its own frame.

targets

targets(S: HandState, S1: HandState) -> torch.Tensor

The regression targets, what out_norm normalizes: the increments from S to S1, or (accel) the mean accelerations over the step of the joints and of the object.

step

step(
    S: HandState, fk: tuple[Tensor, Tensor], u: Tensor
) -> HandState

The next state from S, its forward kinematics fk (HandKinematics.forward, or its palm: only the palm's pose is read) and the targets u.

error

error(S_hat: HandState, S: HandState) -> torch.Tensor

The prediction's error in the increments' layout, in units of the increments' spread.

ndm_gym.worldmodels.piano

The Wuji piano task's own world model (benchmarks/wuji_piano): differentiable contact dynamics for two Wuji hands and an 88-key piano. It is task-specific, not the library's acceleration or increment model (worldmodels.accel, worldmodels.increment). PianoDynamics steps what the policy observes, 192 numbers (the 52 actuator positions, their last changes and the 88 key depths), not the physics state: the actuators take a first-order step plus a residual network; TipGeometry, a polynomial fit of each fingertip to the hand model's kinematics, places the ten fingertips; hand-set contact constants turn their distances to the keys into key depths, which a second residual network corrects. FingerDynamics is the five-finger exercise's model.

TipGeometry

TipGeometry(coeff, origin, scales, centers, sizes)

Bases: Module

Evaluate per-digit quadratic fits and rotate each fingertip into the keyboard frame.

The coefficient tensor is indexed by hand, digit, polynomial term and xyz (2 × 5 × 15 × 3). Origins, key centers and key half-sizes use meters. The six wrist scales convert normalized translation and rotation commands to meters and radians.

PianoDynamics

PianoDynamics(geometry: TipGeometry)

Bases: Module

Predict one 20 Hz control step from the measured state and 52 normalized actuator targets.

The 192 state values are actuator positions, their changes since the preceding step and the 88 key depths as fractions of full travel. Both hands share the key surface geometry.

FingerDynamics

FingerDynamics(digits: int)

Bases: Module

Shared acceleration MLP conditioned on digit identity. Units are normalized to one control step.

ndm_gym.worldmodels.quadrotor

World model of a quadrotor on the tracking task's state (tasks.quadrotor_tracking), in the two parameterizations of the LAFAN1 world models. accel (SuperTrack's, worldmodels.accel): an MLP predicts the linear acceleration in the body's frame and the body rates' derivative, integrated over one control step with semi-implicit Euler in closed form for the simulator's substeps (velocities gain dt a, positions dt (v + (n + 1) / (2 n) dt a)). increment (SuperMimic's, worldmodels.increment): it predicts the increments of every state component, in the body's frame.

A rigid body in free flight: its dynamics do not depend on the position or the heading, so the network reads the world's up axis and the linear velocity in the body's frame, the body rates and the command (13 numbers). Both parameterizations are fit with the same error, the next state's in units of the spread of one true step's increments.

QuadWorldModel

QuadWorldModel(
    hidden=(512, 512, 512),
    act: str = "silu",
    layer_norm: bool = True,
    kind: str = "increment",
    substeps: int = 4,
)

Bases: Module

Deterministic dynamics s_{t+1} = f(s_t, u_t), u_t the command (thrust, body rates).

increments staticmethod

increments(S, S1) -> torch.Tensor

The increments from S to S1 in S's body frame.

targets

targets(S, S1) -> torch.Tensor

The regression targets, what out_norm normalizes: the increments from S to S1, or (accel) the mean accelerations over the step.

step

step(S, u: Tensor)

The next state from S and the command u.

error

error(S_hat, S) -> torch.Tensor

The prediction's error in the increments' layout (the true state's body frame), in units of the increments' spread.

ndm_gym.worldmodels.mjcf

A world model of a MuJoCo model in its generalized coordinates, for models without actuator activation: qpos and qvel are the whole state, so the model reads any MJCF that passes MjcfLayout's checks.

The layout is read once from the MjModel: its joints (free, ball, slide, hinge), the anchor (the free joint at the root of the actuated tree, if there is one), the other free joints (objects), the actuators (joint or fixed-tendon transmissions with a fixed gain and an affine or no bias, the position and velocity servos of most robot models) and the joint equalities (a joint held at a polynomial of another, as hands couple their finger joints), which each step then satisfies exactly: the coupled joint's position and velocity are set from the other's. The inputs do not depend on the anchor's heading and horizontal position: vectors in the world frame are read in the anchor's heading frame, heights stay absolute (the floor). A planar model's root has no anchor but slides: with planar_root its horizontal slides' positions (rootx) are left out of the inputs in the same way, their velocities kept. Two parameterizations: SuperTrack's (kind="accel", worldmodels.accel, the default): an MLP predicts the generalized accelerations, with the free joints' linear parts in the heading frame, and one step integrates them in MuJoCo's own convention (mj_integratePos: the velocity first, then positions add and free and ball quaternions turn by the body-frame angular velocity), so qpos and qvel round-trip through MuJoCo unchanged; SuperMimic's (kind="increment", worldmodels.increment): the MLP predicts the step's increments directly, the tangent from qpos to the next qpos and the velocity's change, the free joints' linear parts again in the heading frame, and the step applies them (mj_integratePos with dt = 1). The error of a prediction is taken in the tangent space (mj_differentiatePos), in units of the spread of one true step's increments, as the hand's world model takes it (worldmodels.hand). With geometry=True the inputs also hold the contact geometry: forward kinematics in MuJoCo's convention (mj_kinematics) places the robot's collision geoms, and each one's centre is read in each object's frame, with its signed distance to the object's primitive collision geoms. With contacts (contact_spheres' result) they hold the contact inputs: the robot's collision geoms as spheres, and per geom and object its gap, the nearest point, the normal there and the relative velocity (contact_inputs); the objects are the free objects and, where the spheres name them, bodies that ride on slides or hinges and static geoms of the world (a floor). With backbone="rigidformer" a body-token Transformer (MjcfRigidFormerNet, after worldmodels.rigidformer) takes the MLP's place: one token per body, with its pose, velocity and joints in the inputs' frame, and per body the outputs of its own degrees of freedom in the MLP's output layout, so that the targets, the integration and the error are the same.

MjcfLayout dataclass

MjcfLayout(
    nq: int,
    nv: int,
    nu: int,
    dt: float,
    anchor: tuple[int, int] | None,
    objects: tuple[tuple[int, int], ...],
    balls: tuple[tuple[int, int], ...],
    scalars: tuple[tuple[int, int, bool], ...],
    slides: tuple[int, ...],
    act_q: tuple[int, ...],
    act_d: tuple[int, ...],
    gear: tuple[float, ...],
    gain: tuple[float, ...],
    bias: tuple[tuple[float, float, float], ...],
    ctrl_range: tuple[tuple[float, float] | None, ...],
    force_range: tuple[tuple[float, float] | None, ...],
    tendons: tuple[
        tuple[int, tuple[tuple[int, int, float], ...]], ...
    ] = (),
    couplings: tuple[
        tuple[
            int,
            int,
            int,
            int,
            float,
            float,
            tuple[float, ...],
        ],
        ...,
    ] = (),
    tree: tuple = (),
    robot_geoms: tuple = (),
    object_geoms: tuple = (),
    object_unread: tuple = (),
    ipos: tuple = (),
    planar: tuple[int, ...] = (),
)

What the world model reads of an MjModel. Index tuples address qpos (q) and qvel (d).

free property

free: tuple[tuple[int, int], ...]

Every free joint, the anchor first.

from_model staticmethod

from_model(
    m, anchor: str | None = None, planar_root: bool = False
) -> MjcfLayout

The layout of m (mujoco.MjModel). anchor: the name of the anchor's free joint; by default the free joint at the root of the actuated joints' tree, or none (a fixed base) if that root has none. Features the model does not support are an error: actuator activation (na > 0); equality constraints other than joint equalities active from the start, and chains of them; flexes; mocap bodies with geoms; actuators other than joint or fixed-tendon transmissions (to hinges and slides) with a fixed gain and an affine or no bias. planar_root: the inputs leave out the positions of the slides that move the actuated tree's root horizontally (planar_slides).

floors

floors() -> np.ndarray

(2 nv,) the error floors of the tangent position and the velocity, in qvel's layout.

MjcfWorldModel

MjcfWorldModel(
    lay: MjcfLayout,
    hidden=HIDDEN,
    act: str = "silu",
    layer_norm: bool = True,
    amp: bool = True,
    kind: str = "accel",
    geometry: bool = False,
    backbone: str = "mlp",
    rf: dict | None = None,
    contacts: dict | None = None,
    pos_lead: float = 1.0,
)

Bases: Module

Deterministic dynamics (qpos', qvel') = f(qpos, qvel, ctrl) over one step of dt (the model's timestep by default). backbone: the network, "mlp" (hidden, act, layer_norm) or "rigidformer" (MjcfRigidFormerNet on the token features of token_inputs; rf: its options, RF_DEFAULTS' where not given). Each backbone's options stay at their defaults with the other, and the contact geometry (geometry) is the MLP's: the tokens hold every body's pose.

pos_lead (the accelerations' only): the next position is the position advanced by dt times v + pos_lead (v' - v). At 1, the default, that is the next velocity, one semi-implicit Euler step of dt (SuperTrack's integration). A control step of several physics steps, or of RK4, advances the position with the mean of the velocities it passes through, which an exact v' does not give at 1 (mean_velocity_lead); the value is kept in the model's state (pos_lead) when it is not 1, and the step is then the model's own dt only.

heading

heading(qpos: Tensor) -> tuple[torch.Tensor, torch.Tensor]

The anchor's heading frame H (..., 3, 3) and horizontal position (..., 3); the world's with no anchor.

servo

servo(
    qpos: Tensor, qvel: Tensor, ctrl: Tensor
) -> tuple[torch.Tensor, torch.Tensor]

Each actuator's force (MuJoCo's: gain ctrl + b0 + b1 length + b2 velocity, ctrl and force clipped to their ranges) and the clipped control's offset from the actuator's length, gear times the joint's position.

inputs

inputs(
    qpos: Tensor, qvel: Tensor, ctrl: Tensor
) -> torch.Tensor

The features of a state and its controls, invariant to the anchor's heading and horizontal position (the RigidFormer's: token_inputs).

body_poses

body_poses(
    qpos: Tensor, qvel: Tensor | None = None
) -> tuple[torch.Tensor, ...]

Every body's world position (..., nbody, 3) and rotation (..., nbody, 3, 3), the world's first, as mj_kinematics computes them from qpos (a mocap body at its model pose), one level of the tree at a time. With qvel, also every body's linear velocity at its origin and angular velocity (..., nbody, 3), in the world frame, as mj_objectVelocity gives them for mjOBJ_XBODY: a free joint's linear velocity is qvel's and its angular one qvel's turned from the body's frame; on a body's way out from its parent's frame, each joint in turn adds its own, about its anchor: a hinge its axis times its rate, a ball its velocity in the frame after its rotation, a slide its axis times its rate as a linear velocity.

token_inputs

token_inputs(
    qpos: Tensor, qvel: Tensor, ctrl: Tensor
) -> torch.Tensor

The RigidFormer's raw features (..., B F): B tokens, one per body after the world, of F = tok_dim features each, in the frame of inputs (the anchor's heading frame about its ground projection, heights absolute): the body's position (its centre of mass; with the option point="origin" its frame's origin), its 6-D rotation, its linear velocity there and its angular velocity, and the angular velocity in the body's own frame (the free and ball joints' velocities' frame); then per slot the joint's position features as the MLP takes them (q, or sin q and cos q for a hinge without limits, the other columns zero), its velocity, and per actuator on it the offset and the force of servo; empty slots are zeros.

contact_geometry

contact_geometry(qpos: Tensor) -> torch.Tensor

Per object: each robot collision geom's centre in the object's frame (3) and its signed distance to the nearest of the object's primitive collision geoms (1).

contact_gaps

contact_gaps(
    qpos: Tensor, qvel: Tensor | None = None
) -> tuple[torch.Tensor, ...]

Per object (..., O, G): each robot collision geom's smallest gap to the object's primitive collision geoms (negative: they overlap), the smallest over the geom's own spheres of the centre's signed distance less the radius; the object's surface point nearest to that sphere and the unit normal there, in the object's frame (..., O, G, 3); and with qvel the velocity of the geom's body at that point less the object's own there, in the object's frame. After the objects, one entry per static geom the spheres name: the gap to it; its surface point nearest to the geom's nearest sphere, from the origin of the geom's own body; the normal there; and the velocity of that body at the point: these three in the frame of the geom's body (a floor does not move with the robot: its own frame would hold the robot's place in the world).

contact_inputs

contact_inputs(qpos: Tensor, qvel: Tensor) -> torch.Tensor

Per object and robot collision geom, 13 values of order one (the input normalizer leaves them as they are, unless update_norms was given contact_scale): the gap beyond the contact margin, clipped to -2 .. 20 mm, in units of 5 mm; exp(-gap / 0.5 mm), 1 in contact; the overlap in units of 0.1 mm, at most 20; and, each times exp(-gap / 2 mm), the object's nearest point in its frame in units of 3 cm, the normal there, and the geom's velocity relative to the object at that point in units of 0.2 m/s, with its normal part. No gradient passes through them. With the spheres' basis set, 12 more per object (see below). The objects are the free objects, then the bodies the spheres name as objects, then the static geoms they name, whose point, normal and velocity are in the frame of the robot geom's body (contact_gaps) and which have no 12 more.

contact_features

contact_features(
    qpos: Tensor, qvel: Tensor
) -> tuple[torch.Tensor, torch.Tensor | None]

contact_inputs' values per object and geom (..., O, G, 13), and with the spheres' basis the 12 summed terms per object (..., O, 12), else None.

targets

targets(
    qpos: Tensor,
    qvel: Tensor,
    qpos1: Tensor,
    qvel1: Tensor,
    dt: float | None = None,
) -> torch.Tensor

The regression targets, what out_norm normalizes, the free joints' linear parts in the heading frame: the mean generalized accelerations over the step (accel), or the step's increments (increment: increments).

increments

increments(
    qpos: Tensor, qvel: Tensor, qpos1: Tensor, qvel1: Tensor
) -> torch.Tensor

One step's increments in the error's layout: the tangent from qpos to qpos1, then qvel1 - qvel.

step

step(
    qpos: Tensor,
    qvel: Tensor,
    ctrl: Tensor,
    dt: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor]

The next state: the predicted accelerations integrated as MuJoCo's semi-implicit Euler integrates them (with pos_lead, the position advanced with the velocity that far from the present one to the next), or the predicted increments applied (increment); with pos_lead or the increments the step is the model's timestep only.

couple

couple(
    qpos: Tensor, qvel: Tensor
) -> tuple[torch.Tensor, torch.Tensor]

The joint equalities satisfied exactly: each coupled joint's position set to the polynomial of the other's and its velocity to the polynomial's slope times the other's velocity (the state unchanged in a model without them).

error

error(
    qpos_hat: Tensor,
    qvel_hat: Tensor,
    qpos: Tensor,
    qvel: Tensor,
) -> torch.Tensor

The prediction's error in the increments' layout, in units of the increments' spread (with floors).

update_norms

update_norms(
    qpos: Tensor,
    qvel: Tensor,
    ctrl: Tensor,
    qpos1: Tensor,
    qvel1: Tensor,
    contact_scale: bool = False,
)

The normalizers from transitions (..., dims): the inputs, the targets and the increments' spread. The contact inputs keep their units, made for order one (a hand at its object). With contact_scale each of their columns is divided by its spread over the transitions of every such call so far where that exceeds one, and stays as it is where not (a foot on a floor: points and velocities of tens of units); the scales sit in the input normalizer, so that a saved fit holds them.

window_loss

window_loss(
    qpos: Tensor,
    qvel: Tensor,
    ctrl: Tensor,
    valid: Tensor | None = None,
    weights: Tensor | None = None,
    loss: str = "l1",
) -> torch.Tensor

The open-loop loss of windows: qpos (T + 1, B, nq), qvel (T + 1, B, nv), ctrl (T, B, nu); valid (T, B) bool, False from a step whose next state does not follow (a reset) on. The mean L1 error over the valid steps; with weights (2 nv,), each step's error components averaged with those weights instead of equally; loss: "l1", "l2" (squared) or "huber" (squared within one step's spread, absolute beyond).

MjcfRigidFormerNet

MjcfRigidFormerNet(
    lay: MjcfLayout,
    kind: str,
    tok_dim: int,
    *,
    dim: int,
    layers: int,
    heads: int,
    registers: int,
    rope_max_freq: float,
    ffn_mult: float = 2.5,
)

Bases: Module

The RigidFormer backbone of MjcfWorldModel (backbone="rigidformer"), worldmodels.rigidformer's design for any MJCF. One token per body after the world (in the tree's order): its features (MjcfWorldModel.token_inputs) through a shared embedding, plus a learned embedding of the body; registers learned tokens at the origin. layers pre-norm blocks (rigidformer.Block: gated attention with QK-RMSNorm and 3-D rotary positions, then SwiGLU; no FiLM, as there is no global context) with a learned per-head bias by relation: the number of links between two bodies of one tree (each body that hangs from the world starts a tree), one class for two bodies of different trees, one for pairs with a register. The rotary positions are the token positions, rotated by frequencies from 1 to rope_max_freq rad/m. The read-out fuses each token's features after the embedding and after the last block (SwiGLU), and every body with degrees of freedom gives the outputs of its own, with one head per joint type (a free joint 6, a ball 3, a hinge or slide 1; once for the accelerations, twice for the increments: the tangent's and the velocity's), gathered into the MLP's output layout (qvel's, twice for the increments). The heads start at zero, as the MLP's last layer.

x (..., B F + 3 B) from make_input_norm (the normalized features, then the token positions over POS_SCALE) -> (..., nv) or (..., 2 nv), fp32. The features run in the parameters' dtype (bf16 in a bf16 inference copy; fp32 parameters under the caller's autocast, with an fp32 residual stream), the rotary positions in fp32.

make_input_norm

make_input_norm()

The normalizer of the token features (rigidformer.TokenInputNorm), which also passes the token positions on.

describe

describe() -> str

Width x blocks, heads and tokens, for the logs.

heads

heads(z: Tensor) -> torch.Tensor

The outputs (N, nv) or (N, 2 nv) from the read tokens' fused features z (N, R, dim): each joint type's head on its bodies' tokens, gathered into the MLP's layout.

planar_slides

planar_slides(
    m, anchor_joint, tendon_joints, couplings
) -> tuple[int, ...]

The qpos addresses of the slides that move the actuated tree's root body horizontally (a planar model's rootx): on a plane its dynamics do not depend on their positions. An error unless the model has no anchor, gravity points down z, the actuated joints hang from one root body and it has such a slide, unlimited, not driven, not in a joint equality and not turned by a hinge before it on that body.

quat_exp

quat_exp(v: Tensor) -> torch.Tensor

The unit quaternion of the rotation vector v.

quat_log

quat_log(q: Tensor) -> torch.Tensor

The rotation vector of the unit quaternion q, the short way round.

integrate_pos

integrate_pos(
    lay: MjcfLayout,
    qpos: Tensor,
    qvel: Tensor,
    dt: float,
    index=None,
) -> torch.Tensor

mj_integratePos: positions add the velocity times dt; free and ball quaternions turn by the body-frame angular velocity (right multiplication), then are normalized; hinges and slides add. index: the hinges' and slides' qpos and qvel addresses as tensors on qpos's device (a world model's own, which torch.compile reads as buffers), else built once.

differentiate_pos

differentiate_pos(
    lay: MjcfLayout,
    qpos1: Tensor,
    qpos2: Tensor,
    index=None,
) -> torch.Tensor

mj_differentiatePos with dt = 1: the tangent from qpos1 to qpos2 in qvel's layout (rotations in qpos1's body frame); index as integrate_pos's.

signed_distance

signed_distance(
    kind: int, x: Tensor, size: Tensor
) -> torch.Tensor

The signed distance (..., ) of points x (..., 3), in a geom's frame, to its surface (negative inside): a sphere of radius size[0], a capsule or cylinder of radius size[0] and half length size[1] along z, a box of half sizes size, or a plane (the frame's z = 0, unbounded; negative below it).

distance_normal

distance_normal(
    kind: int, x: Tensor, size: Tensor
) -> tuple[torch.Tensor, torch.Tensor]

The signed distance (...,) of points x (..., 3), in a geom's frame, to its surface (negative inside) and the surface's unit normal (..., 3) at its point nearest to them (outwards): a sphere, a capsule or a cylinder along z, a box or a plane, with signed_distance's sizes.

contact_spheres

contact_spheres(
    m,
    lay: MjcfLayout,
    spacing: float = 0.0025,
    rmax: float = 0.02,
    cap: int = 384,
    seed: int = 0,
    tol: float = 2e-05,
    objects: tuple = (),
    static: tuple | None = None,
    pair_margin: bool = False,
) -> dict

The robot's collision geoms as spheres, for the contact inputs (MjcfWorldModel(contacts=...)): a mesh's convex hull (as MuJoCo collides it), a box, a cylinder or an ellipsoid through _hull_spheres, a capsule as spheres along its axis, a sphere as itself. Returns center (G, K, 3) in each geom's body's frame and radius (G, K), a geom's unused places a point 10 m off along every axis with radius 0 (the mark by which a model, or a saved fit, keeps them out of every gap); body (G,), each geom's body; count (G,); geom (G,), the geoms' ids in the model, in lay.robot_geoms' order; and margin, the largest contact margin among the objects' and the robot's collision geoms; with pair_margin the largest margin of a contact between one of the robot's collision geoms and one of the objects' or the static geoms, as the installed MuJoCo sets it from the two geoms' margins (_pair_margin): the margin of the simulator's contacts.

objects: names of bodies that are objects too although no free joint carries them (one that rides on slides or hinges): their subtrees' geoms are not the robot's, and the result holds tb, their body ids, and tg (rows of 12: the body's place in tb, then the type, position (3), quaternion (4) and size (3) of each of its collision geoms, a sphere, a capsule, a cylinder or a box). static: names of collision geoms of the world body the robot's geoms' gaps are also read to (an empty tuple: every one of them): the result holds sg (rows of 11: type, position, quaternion, size in the world's frame; a plane, a sphere, a capsule, a cylinder or a box). By default neither: the layout's free objects alone.

check_gaps_revision

check_gaps_revision(ck: dict, path: str)

Refuse a saved fit (ck: a fit_mjcf --save file's contents) whose contact inputs read static geoms and whose mark of the gaps' revision (contact_gaps, beside layout and args) is not GAPS_REVISION. A fit without the mark was fitted on the gaps before 9418a03d, where a geom's unused sphere places stood for its nearest point to a floor: it must be made again. A fit without static geoms, whose gaps are the same in both revisions, is not concerned, marked or not.

mean_velocity_lead

mean_velocity_lead(m, substeps: int) -> float

MjcfWorldModel(pos_lead=...) for a control step of substeps physics steps of the model m: where between the velocities before and after the step, v and v', the mean velocity of its position update lies under a constant acceleration. The integrators that advance the position with each physics step's new velocity (Euler, implicit, implicitfast) add up k velocities, v + i (v' - v) / k: (k + 1) / (2 k), which is 1 for one step. RK4 advances it with the mean of v and v': 1 / 2.

inference_copy

inference_copy(
    wm: MjcfWorldModel, dtype: dtype | None = torch.bfloat16
) -> MjcfWorldModel

A forward-only copy for simulation throughput: the network's parameters in dtype (bf16 or fp16: the network runs in that type end to end; the features, normalizers and integration stay fp32, and so do the RigidFormer's rotary positions), the MLP with its input cast to them, the RigidFormer casting its token features itself; or the fp32 model (None). On a GPU the copy's network is compared with the model's in fp32 and refused if it differs by more than twice the model's own bf16-autocast error on average or four times at the largest (worldmodels.g1_infer's rule).

fused_compile

fused_compile(wm)

Around the first calls of a torch.compile'd step of wm (the calls that compile it): on the fused path the compiler runs a graph's independent kernels as one launch (torch._inductor.config.combo_kernels, the trainers' --combo_kernels): the path's step is a few dozen small kernels, and a planner's step at a few hundred worlds is paid by the launch. The kernels' code is the same. Off the fused path nothing is set.

backbone_kwargs

backbone_kwargs(a: dict) -> dict

MjcfWorldModel's backbone and rf from fit_mjcf's arguments a (--backbone, --rf_*), or from a fit's saved args (a fit from before --backbone is an MLP's). Each backbone's options must stay at their defaults with the other, which would otherwise ignore them: the RigidFormer's --rf_* with the MLP; the MLP's --hidden, --act and --no_ln, and the contact geometry inputs (--geometry), with the RigidFormer.