Skip to content

Tasks

LAFAN1 tracking in SuperMimic's setup: observations, the analytic reward and terminations shared by the simulator and the world models.

ndm_gym.tasks.tracking

Motion-tracking task: analytic observation, reward, termination and critic heads (paper Appendix A).

Shared by the simulator (labels transitions) and the world models (imagined rollouts). The state tuple and sim context are defined in :mod:ndm_gym.state.

MDP

MDP(
    kin: ArticulationKinematics,
    motion: MotionLib,
    default_q: Tensor,
    cfg: RewardCfg = RewardCfg(),
)

obs

obs(
    S, a_prev, xi, f, root_R: Tensor | None = None
) -> torch.Tensor

Noise-free proprioceptive observation (+ reference-relative root orientation). root_R: the reference's root rotation at frame f, read before (train.py --imag_hoist), instead of the frame.

reward

reward(
    S,
    f,
    a,
    a_prev,
    terms: bool = False,
    contact: tuple | None = None,
)

Per-step reward (already multiplied by dt) comparing S with reference frame f. contact (weight, feet, reference contact per frame; SuperMimic's --contact_reward) adds that training-only term (tasks.contact).

soft_termination

soft_termination(
    S,
    f,
    tz: float = 0.02,
    tt: float = 0.04,
    margin: float = 1.0,
) -> torch.Tensor

Differentiable termination probability for imagined rollouts; margin < 1 scales the thresholds down (fails earlier).

critic_features

critic_features(S, f, xi) -> torch.Tensor

Critic input: invariant state, goal, sim context, and robot-vs-reference errors.

ndm_gym.tasks.contact

InstantTrack's contact reward (--contact_reward; --ref_contact_fix is BlinkMimic's): a term of SuperMimic's imagined reward only, which matches a smooth foot-contact indicator to the reference's contact state and rewards low horizontal foot speed while the reference foot is down. Evaluation keeps the task's reward.

foot_bodies

foot_bodies() -> list[int]

The feet's indices among the tracked bodies.

reference_contact

reference_contact(
    motion: MotionLib, feet: list[int], calibrated: bool
) -> torch.Tensor

The reference's foot contact per frame (num_frames, len(feet)): the foot below CONTACT_Z; with calibrated (--ref_contact_fix) below its clip's own floor (the 5th percentile of the foot's height in the clip) + 1.5 cm and slower than 0.5 m/s horizontally, since the retargeted feet of some clips sit about 1 cm higher.

contact_term

contact_term(
    foot_p: Tensor, foot_v: Tensor, c_ref: Tensor
) -> torch.Tensor

Per sample, the mean over the feet (positions and velocities (..., feet, 3), reference contact (..., feet)) of the contact match 1 - (c - c_ref)^2, c = sigmoid((CONTACT_Z - z) / 5 mm), plus c_ref exp(-|v_xy|^2 / (0.3 m/s)^2).

ndm_gym.tasks.hand_tracking

Hand-object motion tracking: a dexterous hand follows a kinematic reference of a hand and the object it handles.

State tuple S = (q, qd, p, R, v, w): the hand's joint positions and velocities (ndm_gym.robots.hands), and the object's position, rotation matrix and world linear and angular velocity. Observation, goal, reward and termination are analytic functions of the state, its forward kinematics fk (HandKinematics.forward of the joint positions, computed once per state) and the reference frame, shared by the simulator's transitions and the world model's imagined rollouts. A step taken at frame f tracks frame f + 1; the reference ends in HOLD frames of its last pose, and imagined rollouts stay on the last frame once they reach it.

HandReference

Bases: NamedTuple

A clip at the control rate, (T, ...) per field: the state's components, the keypoints and the palm's rotation.

RewardCfg dataclass

RewardCfg(
    keypoint_std: float = 0.04,
    finger_std: float = 0.4,
    palm_ori_std: float = 0.4,
    object_pos_std: float = 0.04,
    object_ori_std: float = 0.5,
    w_keypoint: float = 1.0,
    w_finger: float = 0.5,
    w_palm_ori: float = 0.5,
    w_object_pos: float = 2.0,
    w_object_ori: float = 1.0,
    w_action_rate: float = -0.05,
    w_target_rate: float = 0.0,
    term_object: float = 0.15,
    term_palm: float = 0.15,
)

scaled

scaled(k: float) -> RewardCfg

The tracking kernels' widths scaled by k (training's --reward_std_scale).

HandTask

HandTask(
    kin: HandKinematics,
    ref: HandReference,
    cfg: RewardCfg = RewardCfg(),
)

setpoint

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

Position targets for policy output a in [-1, 1] at frame f: offsets about the next frame's pose.

obs

obs(S, fk, a_prev: Tensor) -> torch.Tensor

The hand's joints, and the fingertips and the object about the palm in the palm's frame.

goal

goal(S, f: Tensor, goal_frames: int) -> torch.Tensor

The next goal_frames reference frames about the state: joint offsets, the object's offset and relative rotation.

errors

errors(S, fk, f: Tensor) -> dict[str, torch.Tensor]

Tracking errors against frame f: keypoints (..., num_keypoints) and object position (m), finger joints (rad, RMS), and the squared rotation angles of the palm and the object.

reward

reward(
    S, fk, f: Tensor, a: Tensor, a_prev: Tensor
) -> torch.Tensor

The tracking reward of reaching S at frame f with action a after a_prev.

smooth_cost

smooth_cost(
    S, a: Tensor, a_prev: Tensor
) -> torch.Tensor | None

The target-rate penalty of reaching S with action a after a_prev (per step, before CONTROL_DT), or None when it is off: w_target_rate times the mean over the joints of the policy's part of the targets' change over the joint's kernel width, squared (a change of the width costs the weight). A target that jumps back and forth from one step to the next costs its jumps; one that follows the reference costs nothing, since the reference's own motion is not the policy's part.

soft_termination

soft_termination(
    S, fk, f: Tensor, width: float = 0.015
) -> torch.Tensor

The termination's probability with the thresholds as sigmoids, differentiable in the state.

build_reference

build_reference(
    clip: dict[str, Tensor],
    kin: HandKinematics,
    device: str,
) -> HandReference

The reference of a clip (motion.sources.spider.load_reference, sampled every CONTROL_DT), its last pose held for HOLD frames; velocities by central differences.

HDMI's human-object interaction tasks and MuscleVAE's muscle-actuated tracking.

ndm_gym.tasks.hdmi

HDMI's human-object interaction task (LeCAR-Lab/HDMI @ 32282f6): observation groups, reward groups and terminations as functions of explicit tensors, shared by the simulator (labels transitions) and the world models (imagined rollouts). The per-task data is in :mod:ndm_gym.tasks.hdmi_tasks.

Every formula follows docs/hdmi_task_spec.md (§ below), which cites HDMI's source lines. Conventions:

  • Orientations are rotation matrices (v_world = R v_body), as elsewhere in ndm_gym. HDMI's quaternion formulas are evaluated in matrix form: quat_apply_inverse(q, v) = R^T v, q_a* (x) q_b = R_a^T R_b, yaw_quat(q) = the heading rotation of R (yaw = atan2(R10, R00)), |axis_angle_from_quat(q_a* (x) q_b)| = the rotation angle of R_a^T R_b.
  • Joints follow HDMI's simulator order (JOINT_NAMES, §3.3); its first 23 are the action and tracking joints. Keypoints are HDMI's 16 tracking bodies in simulator order (KEYPOINT_NAMES, §3.4); keypoint 0, the pelvis, is the root.
  • Robot, object and reference positions share one frame (HDMI shifts the reference by the env origin, CMD:171).
  • Timing (§0): step n runs the physics, HDMI's update hooks, the rewards, the command update CU(n), the observations and the terminations. Rewards and terminations compare the state after the step (time n) with the reference of the previous command update CU(n-1), whose index 0 is frame f_{n-1} = s + n - 1, while several terms read CU(n-1)'s snapshots of the state at time n-1; contact flags lead the poses by one frame. HDMIInput therefore holds both states and both reference windows. After a reset HDMI returns all-zero observations and, at n = 1, still holds the previous episode's command buffers (its PPO drops those transitions, §0): what to pass then is the caller's choice.
  • Not here: truncation (clip end t >= L or the episode length, §0), HDMI's running observation normalizer (§4), the ref_joint_pos_ group (the teacher's residual base, §4.5) and the always-zero debug reward group (§5.6).

HDMIState

Bases: NamedTuple

Robot and object at one instant, read from the simulator or predicted by a world model; world frame.

HDMIRef

Bases: NamedTuple

The reference one command update loads (reference_window): index k of the second axis is frame t + F[k] for poses and joints and frame t + 1 + F[k] for the contact flags, t being the frame counter before the update.

HDMIInput

Bases: NamedTuple

Everything step n needs (§0). From prev (CU(n-1)'s snapshots) the terms read the root pose, the keypoints (priv observations), the object's pose and hinge angle (rewards), the contact points and forces; from now the keypoints and joints (rewards, terminations, observations), the object (terminations, observations) and its hinge (observations). now's contact points and forces become the next step's prev.

HDMIClip

Bases: NamedTuple

One clip's reference at 50 fps in HDMI's orders (§1), T frames.

FeetContact

Bases: NamedTuple

The feet's contact-sensor state the feet terms read [IL], kept by HDMITask.advance_feet.

HDMIOutput

Bases: NamedTuple

One step's observations, rewards and terminations (HDMITask.step).

HDMITask

HDMITask(
    cfg: HDMITaskCfg,
    num_envs: int,
    joint_limits: Tensor,
    robot_mass: float,
    noise: bool = True,
    device: str | device = "cpu",
    dtype: dtype = torch.float32,
)

HDMI's heads for one task and the per-env state HDMI keeps across steps: observation histories, the episodic observation noise, the termination counters and the feet's air and contact timers.

joint_limits (29, 2): the robot's hard joint position limits in JOINT_NAMES order, which HDMI reads from its USD (§5.4). robot_mass: total link mass (kg) that normalizes the impact force; HDMI uses env 0's after the startup mass randomization (§5.5). noise: HDMI's observation noise (§4). State updates are out of place, so the rewards, terminations' errors and observations are differentiable through imagined rollouts.

reset

reset(env_ids: Tensor, state: HDMIState)

Episode start for env_ids with state the post-reset state of all envs (§0 reset): the histories are filled with it (OC:24-29, 51-57, 104-108), the contact-target noise is redrawn, the counters and timers cleared.

refill

refill(mask: Tensor, state: HDMIState)

reset's histories for the envs where mask (N,) holds, by selection (no host synchronization, as a compiled caller needs): filled with state, the policy's angular velocity with its reset noise, the termination counters cleared. The contact-target noise and the feet's timers are kept (algos.hoi_algos' --st_ref_replay).

advance_feet

advance_feet(feet_force: Tensor) -> FeetContact

The feet's contact sensor over one control step's physics substeps (Isaac Lab's ContactSensor, §5.5): a foot is in contact when its net force exceeds 1 N; on touchdown the last air time becomes the air time so far plus the touchdown substep; counted in substeps, so the 0.02 s comparisons are exact.

draw_noise

draw_noise(
    push: bool = True,
) -> dict[str, torch.Tensor] | None

The standard normal draws of one step (or, without push, of one observations), in the order they are drawn: the pushed histories' angular velocity, joint positions and gravity, then the object group's position, heading and contact targets (two draws); None without noise. Passed to step or observations they give the same values as drawing inside, which a compiled caller needs to keep eager's random stream.

contact_points

contact_points(
    body_pos, body_rot, obj_body_pos, obj_body_rot, scale
) -> tuple[torch.Tensor, torch.Tensor]

The task's end-effector points and contact targets (N, E, 3) from the keypoints, the object's contact-body pose and the env's per-axis object scale scale (N, 3), 1 in env 0 (§5.3, §7).

rewards

rewards(
    x: HDMIInput, feet: FeetContact
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]

(N, 4) group rewards, each the sum of its enabled terms' weight x value times dt (ENV:406-416, 620-647), and every term's weight x value.

termination_errors

termination_errors(x: HDMIInput) -> torch.Tensor

(N, terms) errors in the order of term_names; a term exceeds when its error >= its threshold (TRM:24).

observations

observations(
    x: HDMIInput, noise: dict[str, Tensor] | None = None
) -> dict[str, torch.Tensor]

The four groups from the current histories; noise as HDMI draws it (OBS:286-300, 342-349, 372-380), from noise (draw_noise) if given.

step

step(
    x: HDMIInput, noise: dict[str, Tensor] | None = None
) -> HDMIOutput

One control step in HDMI's order (§0): the feet's sensor ticks through the physics substeps, the update hooks push the observation histories and count the terminations, then rewards, observations and termination flags. The observation noise comes from noise (draw_noise) if given.

action_pipeline

action_pipeline(
    action: Tensor,
    action_buf: Tensor,
    a_filt: Tensor,
    delay: Tensor,
    alpha: Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]

HDMI's action delay and filter over one control step (§3.1). action (N, 23) enters the buffer (N, 23, 3) of raw actions; at physics substep i the action delayed by delay (N,) substeps drives ã <- ã + alpha (a_used - ã), alpha (N, 1). Returns the filtered action after each substep (N, 4, 23) and the buffer and ã after the step. It does not depend on the physics, so imagination reproduces the simulator's PD targets exactly.

reference_window

reference_window(
    clip: HDMIClip, t: Tensor, steps: Tensor | None = None
) -> HDMIRef

The reference a command update with frame counter t (N,) loads before incrementing it (CMD:247, 290, 565-568): poses and joints at frames t + F, contact flags at t + 1 + F (one frame ahead, §0), frames past the clip's end held at its last frame (MOT:333-338), and the phase (t + 1) / L that ref_motion_phase reads after the update. steps: FUTURE_STEPS as a tensor on t's device, which hot loops pass so that it is not copied to the device every call.

relative_rot

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

Ra^T Rb for (..., 3, 3) with broadcast batch dims (HDMI's q_a* (x) q_b).

rot_angle

rot_angle(R: Tensor) -> torch.Tensor

Rotation angle in [0, pi] of R, i.e. |axis_angle_from_quat(q)|; atan2 keeps it accurate near 0 and pi.

heading_pos

heading_pos(
    pos: Tensor, root_pos: Tensor, root_rot: Tensor
) -> torch.Tensor

Positions (..., B, 3) in the root's heading frame, R(yaw q_root)^T (p - p_root) with the root's height set to 0 (REW:62-89, OBS:95-115); the root's batch dims are those of pos without the body axis.

heading_rot

heading_rot(rot: Tensor, root_rot: Tensor) -> torch.Tensor

Orientations (..., B, 3, 3) relative to the root's heading, yaw(q_root)* (x) q (REW:186-208).

contact_points

contact_points(
    eef_pos,
    eef_rot,
    eef_offset,
    obj_body_pos,
    obj_body_rot,
    target_offset,
) -> tuple[torch.Tensor, torch.Tensor]

End-effector points e_e = p_eef + R_eef d_e (N, E, 3) and contact targets c_e = p_ob + R_ob o_e (N, E, 3) on the object's contact body (CMD:571-577); target_offset (N, E, 3) already multiplied by the env's object scale (CMD:427-439), eef_offset (E, 3) or (N, E, 3).

object_frame_force

object_frame_force(
    obj_body_rot: Tensor, force_w: Tensor
) -> torch.Tensor

End-effector contact forces (N, E, 3) from the world frame to the object contact body's frame (CMD:584).

eef_contact_exp

eef_contact_exp(
    x: HDMIInput,
    pos_sigma,
    pos_tolerance,
    frc_sigma,
    frc_thres,
    per_axis,
    gain,
) -> torch.Tensor

mean_e [g_e gain r_e + 1 - g_e]: exactly 1 outside the annotated contact (REW:399-408).

eef_contact_exp_max

eef_contact_exp_max(
    x: HDMIInput,
    pos_sigma,
    pos_tolerance,
    frc_sigma,
    frc_thres,
    per_axis,
) -> torch.Tensor

max_e r_e while any end effector's flag is on, else 0 (REW:441-449; roll_ball).

contact_reward

contact_reward(cfg) -> tuple[str, dict]

The task's enabled contact reward (eef_contact_exp, or roll_ball's eef_contact_exp_max) and its factor's parameters.

contact_error

contact_error(
    s: HDMIState,
    flag: Tensor,
    kind: str,
    pos_sigma,
    pos_tolerance,
    frc_sigma,
    frc_thres,
    per_axis,
) -> torch.Tensor

HDMI's contact reward as an error (N,): -log of its factor per end effector, d_e / pos_sigma plus the force's shortfall below frc_thres over frc_sigma, from the state s; the mean over the end effectors of the flagged ones' (eef_contact_exp; flag (N, C), one column broadcasts) or the best end effector's while any flag is on (eef_contact_exp_max).

feet_stumble

feet_stumble(x: HDMIInput) -> torch.Tensor

-mean over the feet of 1[|F_xy| > 0.5 N] on the latest substep's net force (RF:71-80; truman's loco group).

impact_force_l2

impact_force_l2(
    x: HDMIInput, feet: FeetContact, robot_weight: float
) -> torch.Tensor

-sum_f min((F_f / W)^2 1[first contact], 10); F_f is the mean net force magnitude over the sensor's history, the last 3 physics substeps (RF:95-103, LOC:113-117).

feet_slip

feet_slip(
    x: HDMIInput, feet: FeetContact, tolerance: float
) -> torch.Tensor

-sum_f 1[contact time > 0.02 s] clamp(|v_f,xy| - tol, 0, 1), centre-of-mass velocities (RF:25-32).

feet_air_time

feet_air_time(
    feet: FeetContact, thres: float
) -> torch.Tensor

sum_f min(t_air - thres, 0) 1[first contact]: a penalty on touchdowns after short swings (RF:143-154).

reward_selection

reward_selection(cfg, kind: str) -> list[int]

The keypoints (a keypoint reward) or tracking joints (a joint reward) that the task's one enabled reward of HDMI's class kind reads, as HDMITask selects them.

penalty_terms

penalty_terms(cfg) -> list[str]

The task's enabled loco and feet terms but survival, as HDMITask.rewards keys them ("group/name"): HDMI's penalties, each a class of PENALTIES with a positive weight, so every term is <= 0; anything else is an error.

full_tracking_score

full_tracking_score(cfg) -> float

HDMI's full per-step tracking score of the task in HDMITask.rewards' term units (weight x value, before dt): the sum of weight x largest value over its enabled tracking and object-group terms, survival left out.

lost_contact

lost_contact(
    x: HDMIInput, pos_thres: float, frc_thres: float
) -> torch.Tensor

2 if an end effector flagged for contact at f_n is farther than pos_thres from its target or pressed with less than frc_thres, else 0, from CU(n-1)'s snapshots (TRM:177-190).

command_obs

command_obs(x: HDMIInput) -> torch.Tensor

ref_body_pos_future_local (CU(n-1)'s keypoints in its frame-f_{n-1} root heading frame), ref_joint_pos_future and ref_motion_phase (CU(n)), (N, 356).

policy_obs

policy_obs(
    x: HDMIInput,
    ang_vel_hist: Tensor,
    gravity_hist: Tensor,
    joint_pos_hist: Tensor,
    hist_idx: Tensor | None = None,
) -> torch.Tensor

Root angular velocity and projected gravity (newest), joint positions minus the offsets at POLICY_JOINT_HISTORY (slot 0 newest; OC:117-121), previous actions flattened as j * 3 + k (OC:131-136), (N, 249).

object_obs

object_obs(
    x: HDMIInput,
    xy_noise=None,
    heading_noise=None,
    contact_noise=None,
) -> torch.Tensor

object_xy_b, object_heading_b and ref_contact_pos_b, (N, 4 + 3E): the object at time n and the contact targets at n-1 in the heading frame of CU(n-1)'s root snapshot, whose height is kept (OBS:285-352, 371-384).

priv_obs

priv_obs(
    x: HDMIInput,
    ang_vel_hist: Tensor,
    gravity_hist: Tensor,
    joint_pos_hist: Tensor,
    hinged: bool,
    height_idx: Tensor | None = None,
) -> torch.Tensor

The critic's and teacher's group in HDMI's order (Y:137-164, plus the hinge terms of doors and the chair), (N, 1703 + 5C + 3E (+3)).

ndm_gym.tasks.hdmi_tasks

HDMI's 13 human-object interaction tasks (LeCAR-Lab/HDMI @ 32282f6, cfg/task/G1/hdmi/*.yaml) as plain data.

The base tables are HDMI's cfg/task/base/hdmi-base.yaml (Y below). Each task adds its objects and contact geometry and overrides rewards, terminations, reset ranges and randomization the way Hydra merges its YAML onto the base: a changed entry keeps its place, a new one is appended. § numbers refer to docs/hdmi_task_spec.md. :mod:ndm_gym.tasks.hdmi evaluates the rewards, terminations and observations; the reset ranges and the randomization are for the simulator.

Term dataclass

Term(
    kind: str,
    weight: float,
    enabled: bool = True,
    params: dict = dict(),
)

A reward term as HDMI's YAML declares it: kind is HDMI's reward class, the term adds weight x its value to its group; a disabled term is still evaluated (and logged) but not added (§5.1).

Termination dataclass

Termination(
    threshold: float, min_steps: int, params: dict = dict()
)

A consecutive-step counter (TRM:12-32): fires once the term's error has been >= threshold for min_steps steps in a row; params are the term's other arguments. Keyed by HDMI's termination class.

ResetCfg dataclass

ResetCfg(
    pose_range: dict = (lambda: dict(BASE_POSE_RANGE))(),
    velocity_range: dict = (
        lambda: dict(BASE_VELOCITY_RANGE)
    )(),
    joint_pos_noise: float = 0.1,
    joint_vel_noise: float = 0.1,
    object_pose_range: dict = (
        lambda: dict(BASE_OBJECT_POSE_RANGE)
    )(),
    object_joint_pos_noise: float = 0.1,
    object_joint_vel_noise: float = 0.1,
)

Reset noise (§2): uniform ranges keyed by POSE_KEYS (Y:74-88, 100-106; a missing key is (0, 0), CMD:95-98) and half-widths of the joint noise; HDMI zeroes the robot's pose and velocity noise in evaluation, not the object's.

ObjectRandomization dataclass

ObjectRandomization(
    mass_range: tuple[float, float],
    dynamic_friction_range: tuple[float, float] = (
        0.3,
        0.8,
    ),
    static_dynamic_friction_ratio_range: tuple[
        float, float
    ] = (1.0, 2.0),
    restitution_range: tuple[float, float] = (0.0, 0.2),
    scale_range: tuple[float, float] = (0.9, 1.1),
    homogeneous_scale: bool = False,
    hinge_armature_range: tuple[float, float] | None = None,
    hinge_friction_range: tuple[float, float] | None = None,
    hinge_damping_range: tuple[float, float] | None = None,
)

The tracked object's randomization (§7): mass, dynamic friction, static/dynamic friction ratio and restitution at startup (HRN:12-83); a per-env per-axis scale of the whole asset at spawn, one scalar with homogeneous_scale, the contact targets scaled alike (SPN:292-311, CMD:427-439); a hinge's armature at startup and its Coulomb friction and viscous damping at every reset (HRN:85-112).

reward_table

reward_table(
    disable: tuple[str, ...] = (),
    add: dict[str, dict[str, Term]] | None = None,
) -> dict[str, dict[str, Term]]

The base reward table with terms disabled in place (HDMI's enabled: false) and new terms appended to a group.

termination_table

termination_table(
    add: dict[str, Termination] | None = None,
    **change: dict,
) -> dict[str, Termination]

The base termination table with a term's threshold, min_steps or params changed in place and new terms appended.

ndm_gym.tasks.muscle_tracking

Motion tracking with MuscleVAE's muscle-actuated character (docs/musclevae_design.md §4): the state its world models predict, the reference tables, SuperMimic's tracking reward on its 23 bodies, and MuscleVAE's termination rule with its form for imagined rollouts.

State: per body (body 0 the pelvis, the root) the center of mass p and the rotation R, and the velocities MuscleVAE's environment records, backward differences over the 50 ms control step (CFG env_recompute_velocity, MU:39-50): v = (p - p_prev) / dt and the rotation rate w = log(R R_prev^T) / dt. Positions then follow from the velocities exactly, p' = p + dt v' and R' = exp(dt w') R, the semi-implicit Euler step of SuperTrack's and MuscleVAE's world models. At an episode's first state the velocities are the simulator's (ENV:296), the angular one stored as the rate whose observation (their_angular_velocity) is the simulator's. With it the muscle state: MuscleVAE's fatigue observation, the body parts' f0-weighted MA, MR and MF (15). Body states are (p, R, v, w) tuples of (..., 23, 3) and (..., 23, 3, 3) tensors, stored flat as (..., 23, 13): p, the quaternion wxyz, v, w.

Reference (build_reference): each frame's bodies by our forward kinematics of the clip's joint positions, raised as a reset raises them (MuscleSim's Reference.lift), so that a reset starts on the reference; velocities by backward differences at 20 Hz of the clip's own (unraised) motion, a clip's first frame taking its second's, as the reset's. Not their dataset's placement of the bodies, which the character's hinges cannot reach (the lower legs, feet and hands 1 to 11 cm from our forward kinematics on average, up to 17.5 cm). The termination's head height is their placement's, as MuscleSim's (within 1.2 mm of ours).

Reward (SuperMimic's, tasks.tracking.MDP.reward, on all 23 bodies): the sum of exp(-e / std^2) of the mean squared body position, geodesic rotation, linear and angular velocity errors, plus the G1 task's action-rate penalty, times dt; the reference re-anchored to the character's root (its horizontal position and heading; the velocities rotated with it), since MuscleVAE's reference switches to a random frame of a random clip. The widths are SuperMimic's (tasks.tracking.RewardCfg) times --reward_std_scale. The action rate (action_rate) is the G1's in its action units: the muscle targets over ACTION_UNIT, their squared changes summed and scaled from the 284 muscles to the G1's 29 actuators. Unlike the G1's, no world-space root terms (after a switch the reference's global pose is unrelated to the character's, and the task scores no drift) and no joint-limit penalty (the simulator's Euler hinges enforce the limits; docs/musclevae_design.md §4).

Termination (ENV:193-218 with CFG, as ndm_gym.sim.rigid.muscle_sim.done_flags): a step is off track when the head's height differs from the reference's by more than 0.5 m; an off count rises by one per step off track and falls by one (not below 0) per step on track; terminated once it reaches 20 after 26 steps, or when the observation exceeds 50 in magnitude. In imagination (soft_termination) each comparison is MuscleVAE's 1[x > threshold] in the forward pass with the gradient of sigmoid((x - threshold) / (0.1 threshold)) (a straight-through estimator), so the count is theirs exactly, and the count's rule fires by sigmoid((count - 19.5) / 0.05), within 5e-5 of 0 or 1 at every whole count.

References as in ndm_gym.sim.rigid.muscle_sim: MU = MuscleVAECore/Utils/motion_utils.py, ENV = MuscleVAECore/Env/ muscle_env.py, CFG = Data/NNModel/config.yml of wangchek/MuscleVAE_ @ 54c001c, which has no license: nothing is copied.

MuscleReference

Bases: NamedTuple

Per-frame reference tables (F frames, MuscleSim's Reference order), on one device.

MuscleRewardCfg dataclass

MuscleRewardCfg(
    body_pos_std: float = RewardCfg.body_pos_std,
    body_ori_std: float = RewardCfg.body_ori_std,
    body_linvel_std: float = RewardCfg.body_linvel_std,
    body_angvel_std: float = RewardCfg.body_angvel_std,
    w_action_rate: float = RewardCfg.w_action_rate,
)

SuperMimic's tracking-kernel widths and the G1 task's action-rate weight (tasks.tracking.RewardCfg).

scaled

scaled(k: float) -> MuscleRewardCfg

The widths times k (--reward_std_scale, training only).

flatten_bodies

flatten_bodies(S) -> torch.Tensor

(p, R, v, w) -> (..., 23, 13).

unflatten_bodies

unflatten_bodies(x: Tensor)

(..., 23, 13) -> (p, R, v, w).

their_angular_velocity

their_angular_velocity(w: Tensor) -> torch.Tensor

The rotation rates w (..., 3) of the state as MuscleVAE's backward-difference angular velocity, the vector part of 2 (q' q^* - 1) / dt (MU:40-50) for q' = exp(dt w) q: (2 sin(|w| dt / 2) / (|w| dt)) w.

rate_from_their

rate_from_their(w_obs: Tensor) -> torch.Tensor

The inverse of :func:their_angular_velocity (for data only: at |w_obs| dt = 2, a half turn, its slope is infinite): the rate whose MuscleVAE angular velocity is w_obs, rotation angles clipped at pi.

body_states

body_states(
    body_q: Tensor,
    body_qd: Tensor,
    before: Tensor,
    fresh: Tensor,
) -> torch.Tensor

The state (N, 23, 13) of MuscleSim's bodies: their poses body_q (N, 23, 7, quaternions xyzw) with backward differences from the poses before the last step, or where fresh (N,) (reset since that step) the simulator's velocities body_qd (N, 23, 6).

head_height_error

head_height_error(S, head_z: Tensor) -> torch.Tensor

|head height - the reference's| (...).

observation_max

observation_max(S) -> torch.Tensor

The largest magnitude in MuscleVAE's termination check of the observation (MU:204-234, as MuscleSim's done_flags): positions relative to the root, velocities and angular velocities (theirs) in the root's frame, and the heights.

straight_through

straight_through(
    x: Tensor, threshold: float
) -> torch.Tensor

1[x > threshold] with the gradient of sigmoid((x - threshold) / (SOFT_REL_TAU threshold)).

off_count_step

off_count_step(off: Tensor, count: Tensor) -> torch.Tensor

MuscleVAE's off-track count after a step: +1 off track, else -1 and at least 0 (off 0 or 1, or soft).

soft_termination

soft_termination(
    S, head_z: Tensor, count: Tensor, ep_step: Tensor
) -> tuple[torch.Tensor, torch.Tensor]

MuscleVAE's termination of an imagined step (module docstring) from the state after it, the reference's head heights (B,), the off counts before it (B,) and the episode steps before it (B,): the step's termination probability (B,) and the new off counts (B,), MuscleVAE's in the forward pass.

termination

termination(
    S, head_z: Tensor, count: Tensor, ep_step: Tensor
) -> tuple[torch.Tensor, torch.Tensor]

The hard rule (bool (B,), integer counts (B,)), for checks: MuscleSim's done_flags on a state.

build_reference

build_reference(
    names: tuple[str, ...],
    lift: Tensor,
    head_z: Tensor,
    length: Tensor,
    rest_length: Tensor,
    char: dict | None = None,
    device: str | device = "cpu",
) -> MuscleReference

The tables of the named clips (module docstring) from MuscleSim's Reference: lift, head_z and the muscle lengths length (F, 284) of every frame; forward kinematics in double precision on the CPU.

reference_from_sim

reference_from_sim(sim) -> MuscleReference

:func:build_reference for a MuscleSim's clips.

action_rate

action_rate(a: Tensor, a_prev: Tensor) -> torch.Tensor

The G1 task's action rate (tasks.tracking.MDP.reward: the squared setpoint changes summed over its 29 actuators) of muscle targets (..., 284) in G1 action units: sum((da / ACTION_UNIT)^2) x 29 / 284.

anchored_reference

anchored_reference(S, ref: MuscleReference, f: Tensor)

The reference bodies of frames f (B,) re-anchored to the states' roots: the reference turned by the heading difference dR = yaw(R_root R_ref_root^T) about its root, which is placed at the character's horizontal position and the reference's height (tasks.tracking.MDP.reward); its velocities turned by dR.

reward

reward(
    S,
    ref: MuscleReference,
    f: Tensor,
    cfg: MuscleRewardCfg,
    rate: Tensor | None = None,
    terms: bool = False,
)

SuperMimic's reward (module docstring) of states S against reference frames f, with the action-rate penalty of rate (action_rate) if given, times dt: (B,), and with terms the mean squared errors.

root_frame_mpjpe

root_frame_mpjpe(
    S, ref: MuscleReference, f: Tensor
) -> torch.Tensor

Mean body position error (B,) in the root's frame, relative to the root (tools/replay_musclevae.py's).

ndm_gym.tasks.quadrotor_tracking

Quadrotor trajectory tracking: a racing quadrotor (ndm_gym.robots.quadrotor) follows flown trajectories.

State tuple S = (p, R, v, w): the position, the rotation matrix, the world linear velocity and the angular velocity in the body's frame (the body rates); flat, MuJoCo's qpos and qvel of the free joint. Observation, goal, reward and termination are analytic functions of the state and the reference frame, shared by the simulator's transitions and the world model's imagined rollouts. The policy's inputs are in the body's frame, so they do not depend on the position or the heading.

The reference is one or more flights, one after the other; a step taken at frame f tracks frame f + 1 of the same flight, and imagined rollouts stay on a flight's last frame once they reach it (QuadReference.end). The action is an offset about the reference's feedforward command (thrust: the thrust along the reference's body z that gives its acceleration against gravity and drag; its body rates).

QuadReference

Bases: NamedTuple

Flights at the control rate, (T, ...) per field: the state's components, the feedforward thrust, and the first and the last frame of each frame's flight.

ahead

ahead(f: Tensor, k: int) -> torch.Tensor

The frame k steps after f, at most its flight's last.

RewardCfg dataclass

RewardCfg(
    pos_std: float = 0.3,
    rot_std: float = 0.5,
    vel_std: float = 2.0,
    ang_std: float = 4.0,
    w_pos: float = 2.0,
    w_rot: float = 1.0,
    w_vel: float = 0.5,
    w_ang: float = 0.25,
    w_action_rate: float = -0.05,
    term_pos: float = 1.0,
)

scaled

scaled(k: float) -> RewardCfg

The tracking kernels' widths scaled by k (training's --reward_std_scale).

QuadTask

QuadTask(
    ref: QuadReference,
    spec: QuadrotorSpec = QuadrotorSpec(),
    cfg: RewardCfg = RewardCfg(),
    goal_stride: int = 5,
)

goal_stride: the goal's frames are 1, 1 + stride, 1 + 2 stride, ... control steps ahead.

setpoint

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

The command (thrust, body rates) for policy output a in [-1, 1] at frame f: offsets about the reference's.

obs

obs(S, a_prev: Tensor) -> torch.Tensor

The world's up axis and the linear velocity in the body's frame, the body rates, the previous action.

goal

goal(S, f: Tensor, goal_frames: int) -> torch.Tensor

goal_frames reference frames ahead, about the state in the body's frame: the position's offset, the relative rotation, the reference's velocity.

errors

errors(S, f: Tensor) -> dict[str, torch.Tensor]

Tracking errors against frame f: position (m), squared rotation angle, linear (m/s) and angular velocity (rad/s).

reward

reward(
    S, f: Tensor, a: Tensor, a_prev: Tensor
) -> torch.Tensor

The tracking reward of reaching S at frame f with action a after a_prev.

soft_termination

soft_termination(
    S, f: Tensor, width: float = 0.1
) -> torch.Tensor

The termination's probability with the threshold as a sigmoid, differentiable in the state.

build_reference

build_reference(
    flights: list[dict[str, Tensor]],
    spec: QuadrotorSpec,
    device: str,
) -> QuadReference

The reference of flights (motion.sources.drone_racing.load_flight, sampled every CONTROL_DT), one after the other; velocities by central differences within each flight.

ndm_gym.tasks.quadruped_tracking

Quadruped motion tracking: the Go2 follows retargeted dog motion capture (motion.sources.lifelike), one or many clips.

State tuple S = (qpos, qvel), MuJoCo's generalized coordinates of the Go2 (robots.go2): the trunk's position and quaternion and the joints, the trunk's world linear and body-frame angular velocity and the joints'. Observation, goal, reward and termination are analytic functions of the state, its forward kinematics fk (Go2Kinematics.forward of qpos, computed once per state: the trunk and the feet, and the trunk's rotation) and the reference frame, shared by the simulator's transitions and the world model's imagined rollouts.

The clips are concatenated into one reference; a frame index addresses a frame of one clip, and last holds the index of its clip's last frame. A step taken at frame f tracks frame f + 1; imagined rollouts and goals stay on a clip's last frame once they reach it. The observation does not depend on the trunk's heading and horizontal position; the goal reads the reference in the trunk's heading frame; the reward and the termination compare the trunk with the reference in the world (the clip's own frame), so that drift costs.

QuadrupedReference

Bases: NamedTuple

The clips at the control rate, concatenated, (F, ...) per field: the state, the keypoints and the trunk's rotation (Go2Kinematics.forward), the planted feet, each frame's clip and its clip's last frame; per clip its first and last frame (C,).

ahead

ahead(f: Tensor, k: int) -> torch.Tensor

The frame k steps after f, at most its clip's last.

RewardCfg dataclass

RewardCfg(
    feet_std: float = 0.06,
    joint_std: float = 0.3,
    trunk_pos_std: float = 0.15,
    trunk_ori_std: float = 0.3,
    lin_vel_std: float = 0.5,
    ang_vel_std: float = 1.5,
    w_feet: float = 1.0,
    w_joint: float = 0.5,
    w_trunk_pos: float = 1.0,
    w_trunk_ori: float = 1.0,
    w_lin_vel: float = 0.5,
    w_ang_vel: float = 0.25,
    w_action_rate: float = -0.05,
    term_height: float = 0.12,
    term_ori: float = 1.0,
    term_pos: float = 0.5,
)

scaled

scaled(k: float) -> RewardCfg

The tracking kernels' widths scaled by k (training's --reward_std_scale).

QuadrupedTask

QuadrupedTask(
    kin: Go2Kinematics,
    ref: QuadrupedReference,
    cfg: RewardCfg = RewardCfg(),
)

setpoint

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

Joint position targets for policy output a in [-1, 1] at frame f: offsets about the next frame's pose.

obs

obs(S, fk, a_prev: Tensor) -> torch.Tensor

The trunk's height, tilt (its rotation in its heading frame) and body-frame velocities, the joints, the feet about the trunk in the trunk's frame and the previous action.

goal

goal(S, fk, f: Tensor, goal_frames: int) -> torch.Tensor

The next goal_frames reference frames in the trunk's heading frame: the trunk's offset, rotation and velocities (the angular one in the reference trunk's frame), and the joints' offsets.

errors

errors(S, fk, f: Tensor) -> dict[str, torch.Tensor]

Tracking errors against frame f: the feet about the trunk (..., NUM_FEET) and in the world (m), the trunk's position and height (m), its squared rotation angle, the joints (rad, RMS) and the trunk's velocities.

reward

reward(
    S, fk, f: Tensor, a: Tensor, a_prev: Tensor
) -> torch.Tensor

The tracking reward of reaching S at frame f with action a after a_prev.

termination

termination(S, fk, f: Tensor) -> torch.Tensor

The trunk too low or too high, turned too far or too far away from the reference (a fall ends there too).

soft_termination

soft_termination(
    S,
    fk,
    f: Tensor,
    widths: tuple[float, float, float] = (
        0.012,
        0.08,
        0.03,
    ),
) -> torch.Tensor

The termination's probability with the thresholds as sigmoids of widths (the height's, the rotation's and the position's), differentiable in the state.

heading_local

heading_local(H: Tensor, x: Tensor) -> torch.Tensor

World vectors x (..., 3) in the heading frame H (..., 3, 3).

feet_local

feet_local(fk) -> torch.Tensor

The feet about the trunk in the trunk's heading frame (..., NUM_FEET, 3).

build_reference

build_reference(
    clips: list[dict], kin: Go2Kinematics, device: str
) -> QuadrupedReference

The reference of clips (motion.sources.lifelike.load_clip, sampled every CONTROL_DT); velocities by central differences within each clip, the trunk's angular velocity in its body frame as MuJoCo's free joint keeps it.