Skip to content

Core

Rotations, differentiable forward kinematics of a floating-base articulation, MLPs, running normalizers and Muon.

ndm_gym.core.rotations

Batched rotation utilities (quaternions are wxyz, rotation matrices act on column vectors).

mat_to_quat

mat_to_quat(m: Tensor) -> torch.Tensor

Robust matrix -> quaternion (wxyz, w >= 0).

axis_angle_to_mat

axis_angle_to_mat(
    axis: Tensor, angle: Tensor
) -> torch.Tensor

Rodrigues for a fixed unit axis (..., 3) and angle (...).

so3_exp

so3_exp(
    v: Tensor, elementwise: bool = False
) -> torch.Tensor

Rotation vector (..., 3) -> matrix, smooth at zero. elementwise: K @ K written out as products and sums, which torch.compile fuses with the rest instead of launching a batched matmul (equal up to float rounding).

so3_log

so3_log(R: Tensor) -> torch.Tensor

Matrix -> rotation vector via the quaternion (stable near 0 and pi).

rot_angle_sq

rot_angle_sq(Ra: Tensor, Rb: Tensor) -> torch.Tensor

Squared geodesic angle between rotations, differentiable (via acos of trace, clamped).

yaw_mat

yaw_mat(R: Tensor) -> torch.Tensor

Heading (yaw-only) rotation of R, from the projected x axis.

mat_to_6d

mat_to_6d(R: Tensor) -> torch.Tensor

First two columns, flattened (6D continuous rotation representation).

ndm_gym.core.kinematics

Differentiable forward kinematics of a floating-base articulation in torch, built from its compiled MJCF.

The same FK computes tracked-body poses and velocities for the reference motion, for logged simulator states, and for world-model predictions, so the analytic reward head matches the reward the simulator transitions are labeled with.

ArticulationKinematics

ArticulationKinematics(
    mjcf_path: str,
    joint_names: list[str],
    tracked: list[str],
    device: str,
    fused: bool = False,
)

visual_vertices

visual_vertices() -> list[np.ndarray]

Every moving body's visual-mesh vertices (mesh geoms of group 1), with those of the fixed bodies attached to it, in its link frame: one (n_b, 3) float32 array per body, its vertex set for the anchors.

anchors

anchors(k: int) -> torch.Tensor

k anchor points of every moving body in its link frame, (num_bodies, k, 3) float32: RigidFormer's deterministic farthest point sampling (farthest_point_sample) over the body's visual-mesh vertices (visual_vertices), as the official code's pregen_cf_anchors.py:15 builds an object's anchors from its float32 vertices; they are the first k of the body's full sampling order (pregen_fps_order.py).

forward

forward(p, R, v, w, q, qd, all_bodies: bool = False)

Tracked-body world positions, rotations, linear (link-origin) and angular velocities.

Parameters:

Name Type Description Default
p, R, v, w

root position (B,3), rotation (B,3,3), world lin/ang velocity (B,3).

required
q, qd

joint positions/velocities (B,J) in joint_names order.

required

forward_fused

forward_fused(
    p: Tensor,
    R: Tensor,
    v: Tensor,
    w: Tensor,
    q: Tensor,
    qd: Tensor,
    all_bodies: bool = False,
) -> tuple[
    torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
]

forward by two Triton kernels with a hand-written backward pass (kernels/fk.py; fused): fp32 CUDA tensors of one batch shape, differentiable in all six, equal to forward up to float rounding; anything else raises.

com

com(bp, bR, bv, bw)

Whole-body center of mass position and velocity from all-body FK (forward(..., all_bodies=True)).

mat_vec

mat_vec(M: Tensor, x: Tensor) -> torch.Tensor

M @ x for (..., 3, 3) and (..., 3), written as an elementwise product: torch.compile fuses it with its neighbours, whereas a batched 3x3 @ stays a separate small matmul (3.6x faster fwd+bwd FK on an A100).

mat_mat

mat_mat(A: Tensor, B: Tensor) -> torch.Tensor

A @ B for (..., 3, 3) matrices as an elementwise product (see mat_vec).

farthest_point_sample

farthest_point_sample(
    vertices: ndarray, k: int
) -> np.ndarray

Indices (k,) of RigidFormer's deterministic farthest point sampling of vertices (n, 3) with its rule 'centroid_farthest': MultiObjectDynamics._farthest_point_sample_np in the official code (github.com/Frank-ZY-Dou/ Dynamics-Modeling, RigidFormer/src/data/multi_dataloader.py:997-1042). Start at the vertex farthest from the centroid, then repeatedly take the vertex farthest from those taken; ties within a relative 1e-9 go to the lexicographically smallest coordinates, so the result depends on the vertex set only, not on its order; a taken vertex is never taken again (coincident duplicates come last). In float64.

ndm_gym.core.nets

MLP building blocks shared by world models, policies and critics (paper Table A.4).

run_mlp

run_mlp(
    net: Module, x: Tensor, amp: bool = True
) -> torch.Tensor

net(x), under bf16 autocast when the entry point set AMP_DTYPE, unless amp is False.

linears

linears(net: Sequential) -> list[nn.Linear]

The MLP's Linear layers, in order.

deferred_dtype

deferred_dtype(device, amp: bool = True) -> torch.dtype

The dtype of an MLP's pre-activations on device as run_mlp computes them: the autocast's where it applies (AMP_DTYPE set, amp, a device it acts on), else fp32.

mlp_taps

mlp_taps(
    net: Sequential, lead: tuple, device, amp: bool = True
) -> list[torch.Tensor]

Per Linear layer of net a zero tensor lead + (out,) that requires grad, in the pre-activations' dtype (deferred_dtype): run_mlp_deferred adds a slice of each to the layer's output at every application, so that after a backward pass its .grad holds the gradients at those pre-activations (deferred_grads).

run_mlp_deferred

run_mlp_deferred(
    net: Sequential,
    x: Tensor,
    taps: list[Tensor],
    amp: bool = True,
) -> tuple[torch.Tensor, list[torch.Tensor]]

run_mlp with each Linear layer's weight and bias detached and taps[i] (zeros, the layer's output shape; one application's slice of mlp_taps) added to the i-th Linear's output. The values are run_mlp's; no gradient reaches the Linear layers' parameters, the pre-activations' gradients land in the taps instead. Also returns each Linear's input (detached; under the autocast as the product reads it, in bf16), from which deferred_grads forms the parameters' gradients over all applications at once.

deferred_grads

deferred_grads(
    net: Sequential,
    ins: list[Tensor],
    taps: list[Tensor],
    bf16_product: bool = False,
)

The Linear layers' gradients of run_mlp_deferred's applications, added to their parameters' .grad (set where it is None): for layer i with the stacked inputs ins[i] (..., in) and the taps' gradients taps[i].grad (..., out) over all applications, dW = sum dy^T x as one matrix product and db = sum dy, where backpropagation forms one product per application inside the backward chain (XMimic's deferred_grads). Operands in bf16 (the autocast's) are multiplied in fp32, which holds them exactly, so the result is the fp32 sum (on the GPU a TF32 product under allow_tf32, which also holds bf16 exactly); bf16_product: the bf16 product instead, its result rounded to bf16 as each application's is in backpropagation, without the casts.

ndm_gym.core.normalizer

Running mean/std normalizer for network inputs and outputs.

RunningNorm

RunningNorm(
    dim: int,
    max_count: float = 200000000.0,
    eps: float = 0.01,
)

Bases: Module

Running mean/std normalizer; updated from data without gradients, frozen after max_count.

update

update(x: Tensor, gate: Tensor | None = None)

gate (--no_sync only; train_muscles' graphable updates): a 0-dim bool, the statistics unchanged where it is false.

ndm_gym.core.muon

Muon on the hidden weight matrices of MLPs, Adam on the rest (--pi_opt muon, --wm_opt muon; InstantTrack, BlinkMimic).

Muon (torch.optim.Muon: momentum orthogonalized by Newton-Schulz iterations) updates every Linear layer of the given MLPs except each MLP's first and last, or the weight matrices given instead (the RigidFormer world model's blocks: RigidFormerNet.hidden_matrices). Its step is rescaled to Adam's update RMS (adjust_lr_fn="match_rms_adamw"), so Adam's learning rate and schedule apply unchanged. Input and output layers, biases and norms stay on Adam.

MuonAdam

MuonAdam(
    model: Module,
    mlps: list[Module] | None,
    lr: float,
    betas=(0.9, 0.95),
    capturable: bool = False,
    matrices: list[Parameter] | None = None,
    batched: bool = False,
    **adam_kw,
)

Muon on the hidden matrices of mlps (submodules of model), or on the 2-D parameters matrices of model given instead (mlps None), Adam with betas (and adam_kw, e.g. fused) on the rest of model's parameters; both at the learning rate lr.

capturable (train.py --update_graphs; BlinkMimic's --cuda_graph): the learning rates are 0-dim device tensors (set with set_lr), Adam is the capturable fused kernel, and the Muon step is done here with torch.optim.Muon's arithmetic and the tensor learning rate (torch.optim.Muon reads a tensor learning rate on the host, so a captured step would freeze it).

batched (train.py --muon_batched; XMimic): the Muon step is done here as well, with the Newton-Schulz iterations of equally shaped matrices as batched products (newton_schulz_batched; a matrix alone in its shape keeps the single iteration).

step

step(ok: Tensor | None = None)

ok (train.py --no_sync): a 0-dim bool device tensor; where it is false the whole step is skipped without a host read (parameters, momenta, Adam's moments and step counts unchanged). The gradients must be finite (zeroed first).

hidden_matrices

hidden_matrices(mlps: list[Module]) -> list[nn.Parameter]

The weights of every Linear layer of each MLP except its first and last.

newton_schulz_batched

newton_schulz_batched(
    grads: Tensor,
    ns_coefficients,
    ns_steps: int,
    eps: float,
) -> torch.Tensor

torch.optim.Muon's Newton-Schulz iteration (_zeropower_via_newtonschulz) on a stack (n, rows, cols) of equally shaped matrices, each product a batched one instead of n (XMimic's newton_schulz_batched). Every matrix sees the same arithmetic: bf16 operands, its own norm (computed per matrix, as the single iteration computes it), the same products; a batched product may accumulate in another order than a single one.