ACG icon indicating copy to clipboard operation
ACG copied to clipboard

Implementation of ATV/JerkRMS metrics

Open ducido opened this issue 7 months ago • 1 comments

Hi, thank you for the great work!

I have a question regarding the evaluation metrics reported in the paper.

In Table II, you report Action Total Variation (ATV) and JerkRMS for measuring action coherence. I checked the repository but could not find where these metrics are implemented.

Could you please point me to the file or script where ATV and JerkRMS are computed?

Thanks in advance!

ducido avatar Apr 06 '26 03:04 ducido

Hi @ducido, sorry for the late reply — and thanks for your interest in the work!

You're right that the metric code wasn't in the repo. We computed ATV and JerkRMS in a small standalone script for the real-robot (SO-101) evaluation rather than as part of the training pipeline, which is why it didn't make it in. Here's the implementation we used:

import os
from typing import Tuple, Union

import numpy as np
import torch


def read_history(file_path: str) -> np.ndarray:
    """Parse a per-line dict log into a (T, D) numpy array.

    Each line is a Python-style repr of {joint_name: np.array([v], dtype=float32)}.
    Joint order is fixed by the first line.
    """
    rows, keys = [], None
    with open(file_path, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            entry = eval(
                line.replace("array", "np.array").replace("dtype=float32", "dtype=np.float32")
            )
            if keys is None:
                keys = list(entry.keys())
            rows.append([float(entry[k]) for k in keys])
    return np.asarray(rows, dtype=np.float32)


def calc_atv(
    actions: torch.Tensor,
    dt: float = 1 / 30,
    get_max: bool = False,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
    """Mean (and optionally peak) speed per trajectory.

    Args:
        actions: (B, T, D) joint positions in radians.
        dt:      timestep in seconds.
    Returns:
        atv:     (B,)  mean speed.
        atv_max: (B,)  peak speed, only if `get_max`.
    """
    assert actions.dim() == 3, actions.shape
    vel = (actions[:, 1:] - actions[:, :-1]) / dt        # (B, T-1, D)
    speed = torch.norm(vel, dim=-1)                      # (B, T-1)
    atv = speed.mean(dim=-1)                             # (B,)
    if get_max:
        return atv, speed.max(dim=-1).values
    return atv


def calc_jerk_rms(
    states: torch.Tensor,
    dt: float = 1 / 30,
    get_max: bool = False,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
    """RMS (and optionally peak) jerk magnitude per trajectory.

    Args:
        states: (B, T, D) joint positions in radians.
        dt:     timestep in seconds.
    Returns:
        rms:     (B,) RMS jerk magnitude.
        rms_max: (B,) peak jerk magnitude, only if `get_max`.
    """
    assert states.dim() == 3, states.shape
    vel = (states[:, 1:] - states[:, :-1]) / dt
    acc = (vel[:, 1:] - vel[:, :-1]) / dt
    jerk = (acc[:, 1:] - acc[:, :-1]) / dt               # (B, T-3, D)
    jerk_mag = torch.norm(jerk, dim=-1)                  # (B, T-3)
    rms = torch.sqrt((jerk_mag ** 2).mean(dim=-1))       # (B,)
    if get_max:
        return rms, jerk_mag.max(dim=-1).values
    return rms


def _load_trajectory(path: str) -> torch.Tensor:
    """Load a history .txt (degrees) and return (1, T, D) tensor in radians."""
    arr = read_history(path)                             # (T, D), degrees
    return (torch.from_numpy(arr) * (np.pi / 180.0)).unsqueeze(0)


def calc_atv_jerk(path: str, *args, **kwargs):
    actions = _load_trajectory(os.path.join(path, "action_history.txt"))
    states = _load_trajectory(os.path.join(path, "state_history.txt"))
    atv = calc_atv(actions, *args, **kwargs)
    jerk_rms = calc_jerk_rms(states, *args, **kwargs)
    return atv, jerk_rms

A few notes on the assumptions baked in:

  • Inputs: per-rollout action_history.txt (commanded actions) and state_history.txt (observed joint states), one dict per line. ATV is computed on actions, JerkRMS on states — same convention as the paper.
  • Units: the .txt logs are in degrees, so _load_trajectory converts to radians before differencing.
  • Timestep: dt = 1/30 for our 30 Hz control loop. Adjust if your setup differs.
  • Per-trajectory: returns (B,) so you can average across rollouts however you prefer.

For the simulated benchmarks (RoboCasa / DexMimicGen) the same formulas apply — you just need to feed in the action/state sequences from the rollout in (B, T, D) shape (radians) and pick the appropriate dt.

I'll add this to the repo as well so it's easier to find. Let me know if anything is unclear!

pmh9960 avatar Apr 27 '26 04:04 pmh9960