Quest 02 / 02 · CapstoneTier 03 · Monthly

Bounty boards / Monthly · December 2026

Build a robot trajectory replay and audit studio with MuJoCo, LeRobot and Rerun

  • MuJoCo simulation
  • Rerun visualization
  • LeRobot datasets
  • PyTorch modeling
  • IMU anomaly detection
  • DVC pipelines
  • robot kinematics
  • Time34 hours
  • Stages11
  • BoardDecember 2026

Overview

You finish with a DVC-tracked local robotics audit studio that scores ABB IRB 120 kinematics, detects UR3e CASPER IMU anomalies, replays 20 deterministic MuJoCo contact rollouts, and evaluates a LeRobot PushT baseline. Every signal and trajectory exports to compact Rerun archives that play back in a self-hosted Rerun 0.44 web viewer with usage analytics disabled. A pytest suite and versioned JSON metrics prove full reproducibility on a tagged Git commit.

  • A Git and DVC repository whose preprocessing stages build leak-free Parquet splits and identical SHA-256 checksums on repeated runs.
  • Trained PyTorch checkpoints reporting held-out IRB 120 Euclidean pose RMSE and 95th-percentile millimeter error alongside CASPER IMU anomaly F1 with false alarms capped at 2 percent.
  • A compact MuJoCo MJCF planar pushing arm scene and runner producing bit-identical state and contact-force logs across 20 seeded episodes.
  • A LeRobot PushT v3.0 loader and PyTorch behavioral-cloning baseline reporting held-out action MSE across unseen episodes.
  • Synchronized Rerun .rrd archives, a telemetry-disabled Rerun 0.44 web viewer launcher, a passing pytest audit suite, and a README linking metrics to five exported failure recordings.
01SETUP30 minutesSet up the workspace...02DATA2 hoursPull raw datasets an...03DATA3 hoursBuild deterministic...04BUILD4 hoursTrain the IRB 120 ki...05BUILD4 hours 30 minutesTrain the CASPER IMU...06BUILD4 hoursSimulate 20 seeded M...07BUILD4 hoursLoad lerobot/pusht a...08BUILD2 hoursExport CASPER IMU au...09BUILD2 hours 30 minutesExport synchronized...10SHIP3 hoursServe the Rerun 0.44...11TEST4 hours 30 minutesWire the DVC metrics...
DATAKaggle IRB120,CASPER, PushTSTOREDVC ingest andParquet splitsMODELPyTorch MLP, 1D-CNN,PushT BCTOOLMuJoCo 20 seededcontact runsCODERerun 0.44 PythonloggerOUTLocal Web Viewer(analytics off)TESTpytest suite andaudit JSONraw CSVs and v3.0 videosseeded Parquet splitsposes, scores, actionsMJCF joints, forcescompact .rrd archivesheld-out metricsdeterminism digestszero-beacon check
End-to-end audit studio: DVC stages version raw datasets, train PyTorch models, run MuJoCo rollouts, export Rerun archives and verify metrics.

Tools

  • MuJoCo

    MuJoCo uses Apache-2.0 and supplies free local binaries and Python bindings. Compute and separately sourced model assets remain outside the engine license.

  • LeRobot

    The LeRobot library is Apache-2.0 software with free local installation. Hardware, compute, and any separately obtained models or datasets have their own costs and terms.

  • Rerun

    The SDK is free under Apache-2.0/MIT; managed Hub has separate contact-based pricing. The native agent panel documents using an installed Codex client with its subscription and no extra API key. A direct provider API connection requires its own key and billing.

  • PyTorch

    PyTorch source is free under its BSD-style license. Hardware, cloud compute and third-party components can have separate costs or terms.

  • DVC

    DVC is free Apache 2.0 software. Remote storage and any separate hosting service require their own accounts and may incur charges.

Datasets

  • Robot Kinematics Dataset Kaggle

    Provides IRB 120 joint angles and tool-space coordinates for training and checking a PyTorch kinematics predictor against simulated poses.

    Attribution 4.0 International (CC BY 4.0) · 1.3 MB · updated 2021-09-14

  • Industrial Robotic Arm - IMU Data (CASPER 1 & 2) Kaggle

    Supplies industrial robotic arm IMU streams for training a PyTorch window classifier that flags movement anomalies on a synchronized timeline.

    MIT · 3.1 GB · updated 2024-09-01

  • lerobot/pusht Hugging Face

    Provides planar pushing demonstrations in LeRobot format for loading episodes alongside Rerun trajectory replay and baseline policy scoring.

    mit · 185.8 MB · updated 2025-09-27

Before you begin

Python 3.12 or newer

PyTorch, MuJoCo, LeRobot 0.6+, Rerun 0.44 and DVC run in a free virtual environment. Verify your version with python --version or py -3.12 --version on Windows.

Node.js 20 LTS and npm

Required to bundle the local @rerun-io/web-viewer 0.44 web app with usage analytics disabled. Both tools are free; check with node --version and npm --version.

16 GB of RAM and 15 GB of free disk space

The CASPER IMU download on Kaggle is roughly 959 MB compressed and expands to about 3.1 GB of extracted CSVs, sharing space with Parquet splits, PushT videos, checkpoints and Rerun archives.

A free Kaggle account and API token

Needed for the IRB 120 kinematics and CASPER IMU datasets via the free kaggle CLI. Keep credentials outside the repository.

Git, a terminal and a modern browser

Use Bash or zsh on macOS and Linux, PowerShell on Windows, and Chromium or Firefox with DevTools to inspect outbound viewer requests. Every listed shell and browser is free to install.

Working Python and introductory PyTorch

You should read NumPy, pandas and torch.nn modules comfortably and know basic train, validation and test split hygiene.

An NVIDIA or Apple Silicon GPU, optional

Every stage runs on CPU. A local GPU speeds up CASPER 1D-CNN and PushT image policy epochs without adding cloud billing.

Stage 01 · setup30 minutes

Set up the workspace, environment and DVC repo

Create a clean Git and DVC repository, install all five open-source robotics tools, and disable Rerun CLI telemetry before logging any data.

Start with an empty project folder tracked by both Git and DVC. Keeping raw datasets, checkpoints and .rrd recordings under DVC keeps Git commits small while tying every number to one commit hash.

LayoutProject tree
robot-audit-studio/
  data/  # DVC-tracked raw and processed tables
    raw/
    interim/
    processed/
  models/  # Saved PyTorch checkpoints
  scenes/  # MuJoCo MJCF XML scene files
  src/
    audit/  # Python pipeline modules
  exports/  # Exported Rerun .rrd archives
  viewer/  # Local Rerun 0.44 web viewer app
  reports/  # Versioned audit_summary.json
  tests/  # pytest verification suite
  dvc.yaml  # Reproducible DVC pipeline stages
  params.yaml  # Seeds, splits and model settings
bashCreate the repository and Python virtual environment on macOS or Linux.
mkdir -p robot-audit-studio/{data/raw,data/interim,data/processed,models,scenes,src/audit,exports,viewer,reports,tests}
cd robot-audit-studio
touch src/__init__.py src/audit/__init__.py
git init
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
powershellInitialize the workspace folders and virtual environment in Windows PowerShell.
New-Item -ItemType Directory -Force robot-audit-studio | Out-Null
Set-Location robot-audit-studio
foreach ($d in @('data/raw','data/interim','data/processed','models','scenes','src/audit','exports','viewer','reports','tests')) {
  New-Item -ItemType Directory -Force $d | Out-Null
}
New-Item -ItemType File -Force src/__init__.py, src/audit/__init__.py | Out-Null
git init
py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip

Install the Python packages from PyPI inside your active Python 3.12+ environment, then initialize DVC and disable Rerun analytics. Pinning lerobot[dataset]>=0.6 and rerun-sdk>=0.44 avoids older Rerun pins, installs the dataset extras for LeRobotDataset, and enables MJCF import plus 0.44 telemetry controls.

bashInstall Python packages, start DVC tracking, and turn off Rerun CLI analytics.
pip install "torch>=2.5" "mujoco>=3.2" "lerobot[dataset]>=0.6" "rerun-sdk>=0.44" dvc pandas pyarrow scikit-learn numpy pyyaml kaggle pytest av
dvc init
rerun analytics disable
rerun analytics config
text.gitignoreIgnore virtual environments, secrets and local caches while letting DVC manage data pointers.
.venv/
__pycache__/
*.pyc
.pytest_cache/
.env
kaggle.json
access_token
viewer/node_modules/
viewer/dist/
bashVerify every required library imports without errors inside the virtual environment.
python -c "import torch, mujoco, lerobot, rerun, dvc; print('torch', torch.__version__, 'mujoco', mujoco.__version__, 'rerun', rerun.__version__)"
Output
torch <torch_version> mujoco <mujoco_version> rerun <rerun_version>
Stage 01 Checkpoint

The version check prints installed releases for torch, mujoco and rerun, dvc status runs without errors, and rerun analytics config confirms analytics is disabled.

Stage 02 · data2 hours

Pull raw datasets and inspect schemas

Download both Kaggle arm datasets and the LeRobot PushT corpus, register raw folders with DVC, and audit every column header and sampling interval before writing loaders.

Each dataset carries its own license and file layout, so inspect the downloaded files directly before hard-coding column names or physical units. The IRB 120 file uses CC BY 4.0 and asks you to cite one of the authors' papers, while CASPER and PushT use the MIT license.

bashAuthenticate Kaggle if needed and download both Kaggle robotics datasets.
kaggle auth login
kaggle datasets download sandibaressiegota/robot-kinematics-dataset -p data/raw/irb120 --unzip
kaggle datasets download hkayan/industrial-robotic-arm-imu-data-casper-1-and-2 -p data/raw/casper --unzip

Pull lerobot/pusht into data/raw/pusht using the LeRobotDataset Python API so the local cache matches the current LeRobot v3.0 layout. That dataset contains 206 episodes and 25,650 frames recorded at 10 Hz.

pythonsrc/audit/inspect_raw.pyInspect exact CSV columns, value ranges, sampling intervals and PushT episode keys.
from pathlib import Path
import json
import numpy as np
import pandas as pd
from lerobot.datasets import LeRobotDataset


def inspect_csv(path: Path) -> dict:
    df = pd.read_csv(path, nrows=5000)
    numeric = df.select_dtypes(include=[np.number])
    summary = {
        'file': path.name,
        'sample_rows': int(len(df)),
        'columns': list(df.columns),
        'dtypes': {c: str(t) for c, t in df.dtypes.items()},
        'nulls_in_sample': {c: int(df[c].isna().sum()) for c in df.columns},
        'min_max': {
            c: [float(numeric[c].min()), float(numeric[c].max())]
            for c in numeric.columns
        },
    }
    time_cols = [c for c in df.columns if 'time' in c.lower()]
    if time_cols and pd.api.types.is_numeric_dtype(df[time_cols[0]]):
        diffs = df[time_cols[0]].diff().dropna()
        positive = diffs[diffs > 0]
        if len(positive) > 0:
            summary['median_dt'] = float(positive.median())
    return summary


def main() -> None:
    irb_files = sorted(Path('data/raw/irb120').glob('*.csv'))
    casper_files = sorted(Path('data/raw/casper').glob('*.csv'))
    pusht = LeRobotDataset(
        'lerobot/pusht',
        root=Path('data/raw/pusht'),
        video_backend='pyav',
    )
    sample = pusht[0]
    report = {
        'irb120': [inspect_csv(p) for p in irb_files],
        'casper': [inspect_csv(p) for p in casper_files],
        'pusht': {
            'num_episodes': int(pusht.num_episodes),
            'num_frames': int(len(pusht)),
            'fps': int(pusht.fps),
            'sample_keys': {k: list(v.shape) if hasattr(v, 'shape') else str(type(v)) for k, v in sample.items()},
        },
    }
    out = Path('data/interim/schema_report.json')
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
    print('Wrote', out)
    print('IRB 120 files:', [r['file'] for r in report['irb120']])
    print('CASPER CSV count:', len(report['casper']))
    print('PushT episodes:', report['pusht']['num_episodes'], 'frames:', report['pusht']['num_frames'])


if __name__ == '__main__':
    main()
bashRun the schema inspection script and register raw data folders in DVC.
python src/audit/inspect_raw.py
dvc add data/raw/irb120 data/raw/casper data/raw/pusht
git add data/raw/.gitignore data/raw/irb120.dvc data/raw/casper.dvc data/raw/pusht.dvc .gitignore src/audit/inspect_raw.py
Verified raw files and licenses before writing loaders.
DatasetExpected raw contentsLicenseUnit and schema check
IRB 120 Kinematicsrobot_inverse_kinematics_dataset.csv (15,000 rows)CC BY 4.0Confirm 6 joint columns in radians and 3 tool coordinates (x, y, z) scale in meters or mm.
CASPER 1 and 2 IMUNormal streams (IMU_20Hz_freq_drop.csv, IMU_Acc_Gyro_20Hz.csv) and five fault files including IMU_extra_weigth.csvMITConfirm exact accelerometer, gyroscope and timestamp headers and median sampling interval in schema_report.json.
LeRobot PushT206 episodes, 25,650 frames, 10 Hz Parquet + AV1 MP4 videosMITConfirm observation.image ([3, 96, 96]), observation.state ([2]) and action ([2]).
Stage 02 Checkpoint

data/interim/schema_report.json lists every CSV column header, numeric range, median sampling interval and PushT tensor shape, and three .dvc pointer files exist under data/raw/.

Stage 03 · data3 hours

Build deterministic splits and DVC preprocessing

Create leak-free Parquet splits for IRB 120 kinematics and non-overlapping CASPER IMU windows, then verify that running dvc repro twice yields identical split checksums.

Randomly shuffling sliding windows across a time series leaks neighboring samples into both training and test sets. Slice each CASPER CSV into contiguous time blocks first, then cut non-overlapping windows inside each block so training, tuning and test windows never touch.

DATAIRB 120 CSV (15,000rows)DATACASPER normal andfault CSVsCODESeeded 70/15/15 rowsplitCODEContiguous blocksplit per CSVCODENon-overlapping64-step windowsSTOREParquet tables andSHA manifestfixed seed 42train, val, testper-file orderingstride equals lengthzero window overlap
Leak-free data splitting: IRB 120 uses seeded row partitions while CASPER slices contiguous blocks per CSV before non-overlapping windowing.

Record every column mapping, unit conversion factor and random seed inside params.yaml. Confirm the casper.normal_files, casper.anomaly_files and irb120 keys match the filenames and headers printed in data/interim/schema_report.json; prepare_data.py automatically intersects shared numeric IMU columns across the selected CASPER CSVs.

yamlparams.yamlCentral pipeline parameters tracked by DVC for reproducible preprocessing, training and simulation.
seed: 42
splits:
  train: 0.70
  val: 0.15
  test: 0.15
irb120:
  csv_name: robot_inverse_kinematics_dataset.csv
  joint_columns: [q1, q2, q3, q4, q5, q6]
  target_columns: [x, y, z]
  target_to_mm: 1000.0
  epochs: 80
  batch_size: 256
  lr: 0.001
casper:
  normal_files:
    - IMU_Acc_Gyro_20Hz.csv
  anomaly_files:
    - IMU_earthquake.csv
    - IMU_extra_weigth.csv
    - IMU_hitting_arm.csv
    - IMU_hitting_platform.csv
    - IMU_magnet.csv
  window_size: 64
  sample_rate_hz: 20.0
  max_normal_rows: 120000
  epochs: 35
  batch_size: 128
  lr: 0.001
  max_false_alarm_rate: 0.02
mujoco:
  num_episodes: 20
  steps_per_episode: 200
  base_seed: 1000
pusht:
  train_episodes: 165
  val_episodes: 20
  epochs: 15
  batch_size: 64
  lr: 0.0005
pythonsrc/audit/prepare_data.pyNormalize IRB 120 rows and non-overlapping CASPER windows into Parquet files with SHA-256 digests.
from pathlib import Path
import hashlib
import json
import numpy as np
import pandas as pd
import yaml


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open('rb') as handle:
        for chunk in iter(lambda: handle.read(65536), b''):
            digest.update(chunk)
    return digest.hexdigest()


def prepare_irb120(cfg: dict, out_dir: Path) -> dict:
    raw_path = Path('data/raw/irb120') / cfg['irb120']['csv_name']
    df = pd.read_csv(raw_path)
    joint_cols = cfg['irb120']['joint_columns']
    target_cols = cfg['irb120']['target_columns']
    if not set(joint_cols + target_cols).issubset(df.columns):
        numeric_cols = list(df.select_dtypes(include=[np.number]).columns)
        joint_cols, target_cols = numeric_cols[:6], numeric_cols[6:9]
    clean = df[joint_cols + target_cols].dropna().reset_index(drop=True)
    clean['row_id'] = np.arange(len(clean), dtype=np.int64)
    rng = np.random.default_rng(cfg['seed'])
    perm = rng.permutation(len(clean))
    n_train = int(len(clean) * cfg['splits']['train'])
    n_val = int(len(clean) * cfg['splits']['val'])
    parts = {
        'train': clean.iloc[perm[:n_train]].sort_values('row_id').reset_index(drop=True),
        'val': clean.iloc[perm[n_train:n_train + n_val]].sort_values('row_id').reset_index(drop=True),
        'test': clean.iloc[perm[n_train + n_val:]].sort_values('row_id').reset_index(drop=True),
    }
    meta = {'joint_columns': joint_cols, 'target_columns': target_cols, 'files': {}}
    for name, frame in parts.items():
        target = out_dir / f'irb120_{name}.parquet'
        frame.to_parquet(target, index=False)
        meta['files'][name] = {'rows': int(len(frame)), 'sha256': sha256_file(target)}
    return meta


def load_casper_numeric(path: Path, max_rows: int | None = None) -> pd.DataFrame:
    df = pd.read_csv(path, nrows=max_rows)
    keep = [
        c for c in df.select_dtypes(include=[np.number]).columns
        if 'time' not in c.lower() and 'index' not in c.lower() and 'label' not in c.lower()
    ]
    return df[keep].dropna().reset_index(drop=True)


def slice_windows(
    df: pd.DataFrame, window_size: int, label: int, source: str, train_frac: float, val_frac: float
) -> dict[str, list[dict]]:
    total = (len(df) // window_size) * window_size
    df = df.iloc[:total]
    n_win = total // window_size
    n_train = int(n_win * train_frac)
    n_val = int(n_win * val_frac)
    buckets = {'train': range(0, n_train), 'val': range(n_train, n_train + n_val), 'test': range(n_train + n_val, n_win)}
    rows = {'train': [], 'val': [], 'test': []}
    values = df.to_numpy(dtype=np.float32)
    for split_name, indices in buckets.items():
        for idx in indices:
            start = idx * window_size
            end = start + window_size
            rows[split_name].append({
                'window_id': f'{source}:{start}:{end}',
                'source_file': source,
                'start_row': int(start),
                'end_row': int(end),
                'label': int(label),
                'values': values[start:end].reshape(-1).tolist(),
            })
    return rows


def prepare_casper(cfg: dict, out_dir: Path) -> dict:
    raw_dir = Path('data/raw/casper')
    w = int(cfg['casper']['window_size'])
    train_frac = float(cfg['splits']['train'])
    val_frac = float(cfg['splits']['val'])
    frames = []
    for name in cfg['casper']['normal_files']:
        frames.append((name, 0, load_casper_numeric(raw_dir / name, cfg['casper']['max_normal_rows'])))
    for name in cfg['casper']['anomaly_files']:
        frames.append((name, 1, load_casper_numeric(raw_dir / name)))
    common_cols = sorted(set.intersection(*(set(f.columns) for _, _, f in frames)))
    if not common_cols:
        raise ValueError('No shared numeric IMU columns across selected CASPER CSV files.')
    merged = {'train': [], 'val': [], 'test': []}
    for name, label, frame in frames:
        split_rows = slice_windows(frame[common_cols], w, label, name, train_frac, val_frac)
        for key in merged:
            merged[key].extend(split_rows[key])
    meta = {'feature_columns': common_cols, 'window_size': w, 'files': {}}
    for name, rows in merged.items():
        frame = pd.DataFrame(rows).sort_values('window_id').reset_index(drop=True)
        target = out_dir / f'casper_windows_{name}.parquet'
        frame.to_parquet(target, index=False)
        meta['files'][name] = {
            'windows': int(len(frame)),
            'anomalies': int(frame['label'].sum()),
            'sha256': sha256_file(target),
        }
    return meta


def main() -> None:
    cfg = yaml.safe_load(Path('params.yaml').read_text(encoding='utf-8'))
    out_dir = Path('data/processed')
    out_dir.mkdir(parents=True, exist_ok=True)
    manifest = {
        'seed': int(cfg['seed']),
        'irb120': prepare_irb120(cfg, out_dir),
        'casper': prepare_casper(cfg, out_dir),
    }
    manifest_path = out_dir / 'split_checksums.json'
    manifest_path.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
    print('Wrote', manifest_path)


if __name__ == '__main__':
    main()

Create the initial dvc.yaml with the prepare_data stage, then run dvc repro twice in a row. On the second run, DVC should detect unchanged inputs and skip recomputation while preserving every split checksum.

yamldvc.yamlInitial DVC stage definition for deterministic preprocessing.
stages:
  prepare_data:
    cmd: python src/audit/prepare_data.py
    deps:
      - data/raw/irb120
      - data/raw/casper
      - src/audit/prepare_data.py
    params:
      - seed
      - splits
      - irb120
      - casper.normal_files
      - casper.anomaly_files
      - casper.window_size
      - casper.max_normal_rows
    outs:
      - data/processed/irb120_train.parquet
      - data/processed/irb120_val.parquet
      - data/processed/irb120_test.parquet
      - data/processed/casper_windows_train.parquet
      - data/processed/casper_windows_val.parquet
      - data/processed/casper_windows_test.parquet
      - data/processed/split_checksums.json
bashExecute dvc repro twice and confirm the second run uses the DVC cache.
dvc repro
dvc repro
Output
Stage 'prepare_data' didn't change, skipping
Data and pipelines are up to date.
Stage 03 Checkpoint

The second dvc repro reports that prepare_data did not change, and data/processed/split_checksums.json lists non-zero row counts, window counts and SHA-256 hashes for every split.

Stage 04 · build4 hours

Train the IRB 120 kinematics MLP in PyTorch

Train a seeded PyTorch multilayer perceptron to predict ABB IRB 120 tool coordinates from joint angles and measure Euclidean RMSE, 95th-percentile millimeter error and worst-case workspace regions.

Predicting tool-space (x, y, z) coordinates from six joint angles gives your studio a fast learned kinematics reference beside physical simulations. Standardize inputs using training-split statistics only, and store those scaling tensors inside the checkpoint so evaluation stays self-contained.

pythonsrc/audit/train_kinematics.pyTrain the seeded IRB 120 PyTorch MLP and export millimeter pose error metrics plus the five worst test poses.
from pathlib import Path
import json
import numpy as np
import pandas as pd
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
import yaml


class KinematicsMLP(nn.Module):
    def __init__(self, in_dim: int = 6, hidden: int = 128, out_dim: int = 3) -> None:
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, hidden),
            nn.LayerNorm(hidden),
            nn.SiLU(),
            nn.Linear(hidden, hidden),
            nn.LayerNorm(hidden),
            nn.SiLU(),
            nn.Linear(hidden, hidden // 2),
            nn.SiLU(),
            nn.Linear(hidden // 2, out_dim),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x)


def set_seed(seed: int) -> None:
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.use_deterministic_algorithms(True, warn_only=True)


def workspace_region(coords_mm: np.ndarray) -> list[str]:
    labels = []
    for x, y, z in coords_mm:
        sx = 'X+' if x >= 0 else 'X-'
        sy = 'Y+' if y >= 0 else 'Y-'
        sz = 'Z+' if z >= 0 else 'Z-'
        labels.append(f'{sx}_{sy}_{sz}')
    return labels


def main() -> None:
    cfg = yaml.safe_load(Path('params.yaml').read_text(encoding='utf-8'))
    manifest = json.loads(Path('data/processed/split_checksums.json').read_text(encoding='utf-8'))
    joint_cols = manifest['irb120']['joint_columns']
    target_cols = manifest['irb120']['target_columns']
    scale_mm = float(cfg['irb120']['target_to_mm'])
    set_seed(int(cfg['seed']))

    train_df = pd.read_parquet('data/processed/irb120_train.parquet')
    val_df = pd.read_parquet('data/processed/irb120_val.parquet')
    test_df = pd.read_parquet('data/processed/irb120_test.parquet')

    x_train = train_df[joint_cols].to_numpy(dtype=np.float32)
    y_train = train_df[target_cols].to_numpy(dtype=np.float32) * scale_mm
    x_val = val_df[joint_cols].to_numpy(dtype=np.float32)
    y_val = val_df[target_cols].to_numpy(dtype=np.float32) * scale_mm
    x_test = test_df[joint_cols].to_numpy(dtype=np.float32)
    y_test = test_df[target_cols].to_numpy(dtype=np.float32) * scale_mm

    x_mean, x_std = x_train.mean(axis=0), x_train.std(axis=0) + 1e-6
    y_mean, y_std = y_train.mean(axis=0), y_train.std(axis=0) + 1e-6

    def norm_x(arr: np.ndarray) -> torch.Tensor:
        return torch.from_numpy((arr - x_mean) / x_std)

    def norm_y(arr: np.ndarray) -> torch.Tensor:
        return torch.from_numpy((arr - y_mean) / y_std)

    gen = torch.Generator().manual_seed(int(cfg['seed']))
    train_loader = DataLoader(
        TensorDataset(norm_x(x_train), norm_y(y_train)),
        batch_size=int(cfg['irb120']['batch_size']),
        shuffle=True,
        generator=gen,
    )
    model = KinematicsMLP(in_dim=len(joint_cols), out_dim=len(target_cols))
    opt = torch.optim.AdamW(model.parameters(), lr=float(cfg['irb120']['lr']), weight_decay=1e-4)
    loss_fn = nn.MSELoss()
    best_val = float('inf')
    best_state = None

    for _ in range(int(cfg['irb120']['epochs'])):
        model.train()
        for bx, by in train_loader:
            opt.zero_grad()
            loss = loss_fn(model(bx), by)
            loss.backward()
            opt.step()
        model.eval()
        with torch.no_grad():
            val_pred = model(norm_x(x_val)).numpy() * y_std + y_mean
            val_rmse = float(np.sqrt(np.mean(np.sum((val_pred - y_val) ** 2, axis=1))))
            if val_rmse < best_val:
                best_val = val_rmse
                best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}

    model.load_state_dict(best_state)
    model.eval()
    with torch.no_grad():
        test_pred = model(norm_x(x_test)).numpy() * y_std + y_mean

    err_mm = np.linalg.norm(test_pred - y_test, axis=1)
    rmse_mm = float(np.sqrt(np.mean(err_mm ** 2)))
    p95_mm = float(np.percentile(err_mm, 95))

    eval_df = test_df[['row_id'] + joint_cols].copy()
    for i, axis in enumerate(['x', 'y', 'z']):
        eval_df[f'true_{axis}_mm'] = y_test[:, i]
        eval_df[f'pred_{axis}_mm'] = test_pred[:, i]
    eval_df['error_mm'] = err_mm
    eval_df['region'] = workspace_region(y_test)
    region_stats = (
        eval_df.groupby('region')['error_mm']
        .agg(['count', 'mean', 'max'])
        .reset_index()
        .to_dict(orient='records')
    )
    worst5 = eval_df.nlargest(5, 'error_mm').reset_index(drop=True)

    Path('models').mkdir(exist_ok=True)
    Path('reports').mkdir(exist_ok=True)
    torch.save(
        {
            'state_dict': best_state,
            'x_mean': x_mean,
            'x_std': x_std,
            'y_mean': y_mean,
            'y_std': y_std,
            'joint_columns': joint_cols,
            'target_columns': target_cols,
        },
        'models/irb120_mlp.pt',
    )
    eval_df.to_parquet('reports/kinematics_test_preds.parquet', index=False)
    worst5.to_parquet('reports/kinematics_worst5.parquet', index=False)
    summary = {
        'val_rmse_mm': round(best_val, 3),
        'test_rmse_mm': round(rmse_mm, 3),
        'test_p95_mm': round(p95_mm, 3),
        'test_max_mm': round(float(err_mm.max()), 3),
        'regions': region_stats,
    }
    Path('reports/kinematics_eval.json').write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
    print(json.dumps({'test_rmse_mm': summary['test_rmse_mm'], 'test_p95_mm': summary['test_p95_mm']}))


if __name__ == '__main__':
    main()
bashRun kinematics training and inspect the millimeter pose error metrics.
python src/audit/train_kinematics.py
Output
{"test_rmse_mm": <your_rmse_mm>, "test_p95_mm": <your_p95_mm>}
Stage 04 Checkpoint

models/irb120_mlp.pt, reports/kinematics_eval.json and reports/kinematics_worst5.parquet exist, and the JSON report records test RMSE, p95 error in millimeters and per-octant peaks.

Stage 05 · build4 hours 30 minutes

Train the CASPER IMU 1D-CNN fault detector

Train a PyTorch 1D convolutional classifier on disjoint CASPER IMU windows, tune its threshold on the tuning split for at most 2 percent false alarms, and evaluate on unseen test windows.

Industrial fault detectors fail on factory floors when they cry wolf too often. Searching candidate probability cutoffs strictly on the validation split and locking the highest-F1 threshold whose validation false-alarm rate stays at or below 2 percent keeps the test split unbiased.

pythonsrc/audit/imu_model.pyDefine the 1D-CNN model, tensor reshaping helper and false-alarm-constrained threshold search.
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score
import torch
from torch import nn


class ImuCNN1D(nn.Module):
    def __init__(self, in_channels: int) -> None:
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv1d(in_channels, 32, kernel_size=5, padding=2),
            nn.BatchNorm1d(32),
            nn.ReLU(),
            nn.Conv1d(32, 64, kernel_size=5, padding=2),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            nn.Conv1d(64, 64, kernel_size=3, padding=1),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            nn.AdaptiveAvgPool1d(1),
        )
        self.head = nn.Linear(64, 1)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.head(self.features(x).squeeze(-1)).squeeze(-1)


def to_tensor_array(df: pd.DataFrame, window_size: int, n_channels: int) -> tuple[np.ndarray, np.ndarray]:
    x = np.stack(df['values'].to_numpy()).astype(np.float32)
    x = x.reshape(-1, window_size, n_channels).transpose(0, 2, 1)
    y = df['label'].to_numpy(dtype=np.float32)
    return x, y


def false_alarm_rate(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    neg = (y_true == 0)
    if neg.sum() == 0:
        return 0.0
    return float(((y_pred == 1) & neg).sum() / neg.sum())


def choose_threshold(y_val: np.ndarray, probs: np.ndarray, max_far: float) -> float:
    best_t, best_f1 = 0.5, -1.0
    for t in np.linspace(0.05, 0.99, 189):
        pred = (probs >= t).astype(np.int64)
        if false_alarm_rate(y_val, pred) <= max_far:
            score = float(f1_score(y_val, pred, zero_division=0))
            if score > best_f1:
                best_f1 = score
                best_t = float(t)
    return best_t

Keep the training driver separate so tests and inference tools can import ImuCNN1D without re-running training. Standardize every IMU channel with training-split statistics only, weight positive windows to handle class imbalance, and save the locked threshold inside models/casper_cnn.pt.

pythonsrc/audit/train_imu_cnn.pyFit the 1D-CNN on CASPER windows, lock the validation cutoff, and write held-out scores with top misses.
from pathlib import Path
import json
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score, precision_score, recall_score
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
import yaml
from src.audit.imu_model import ImuCNN1D, choose_threshold, false_alarm_rate, to_tensor_array


def main() -> None:
    cfg = yaml.safe_load(Path('params.yaml').read_text(encoding='utf-8'))
    manifest = json.loads(Path('data/processed/split_checksums.json').read_text(encoding='utf-8'))
    w = int(manifest['casper']['window_size'])
    c = len(manifest['casper']['feature_columns'])
    seed = int(cfg['seed'])
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.use_deterministic_algorithms(True, warn_only=True)

    train_df = pd.read_parquet('data/processed/casper_windows_train.parquet')
    val_df = pd.read_parquet('data/processed/casper_windows_val.parquet')
    test_df = pd.read_parquet('data/processed/casper_windows_test.parquet')

    x_tr, y_tr = to_tensor_array(train_df, w, c)
    x_va, y_va = to_tensor_array(val_df, w, c)
    x_te, y_te = to_tensor_array(test_df, w, c)

    mean = x_tr.mean(axis=(0, 2), keepdims=True)
    std = x_tr.std(axis=(0, 2), keepdims=True) + 1e-6
    x_tr_n = (x_tr - mean) / std
    x_va_n = (x_va - mean) / std
    x_te_n = (x_te - mean) / std

    pos = max(float(y_tr.sum()), 1.0)
    neg = max(float((y_tr == 0).sum()), 1.0)
    pos_weight = torch.tensor([neg / pos], dtype=torch.float32)

    gen = torch.Generator().manual_seed(seed)
    loader = DataLoader(
        TensorDataset(torch.from_numpy(x_tr_n), torch.from_numpy(y_tr)),
        batch_size=int(cfg['casper']['batch_size']),
        shuffle=True,
        generator=gen,
    )
    model = ImuCNN1D(in_channels=c)
    opt = torch.optim.AdamW(model.parameters(), lr=float(cfg['casper']['lr']), weight_decay=1e-4)
    loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
    max_far = float(cfg['casper']['max_false_alarm_rate'])

    best_val_f1, best_state = -1.0, None
    for _ in range(int(cfg['casper']['epochs'])):
        model.train()
        for bx, by in loader:
            opt.zero_grad()
            loss = loss_fn(model(bx), by)
            loss.backward()
            opt.step()
        model.eval()
        with torch.no_grad():
            val_probs = torch.sigmoid(model(torch.from_numpy(x_va_n))).numpy()
            t = choose_threshold(y_va, val_probs, max_far)
            val_f1 = float(f1_score(y_va, (val_probs >= t).astype(np.int64), zero_division=0))
            if val_f1 > best_val_f1:
                best_val_f1 = val_f1
                best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}

    model.load_state_dict(best_state)
    model.eval()
    with torch.no_grad():
        val_probs = torch.sigmoid(model(torch.from_numpy(x_va_n))).numpy()
        test_probs = torch.sigmoid(model(torch.from_numpy(x_te_n))).numpy()

    threshold = choose_threshold(y_va, val_probs, max_far)
    test_pred = (test_probs >= threshold).astype(np.int64)
    metrics = {
        'threshold': round(threshold, 4),
        'val_f1': round(best_val_f1, 4),
        'test_f1': round(float(f1_score(y_te, test_pred, zero_division=0)), 4),
        'test_precision': round(float(precision_score(y_te, test_pred, zero_division=0)), 4),
        'test_recall': round(float(recall_score(y_te, test_pred, zero_division=0)), 4),
        'test_false_alarm_rate': round(false_alarm_rate(y_te, test_pred), 4),
    }

    pred_df = test_df[['window_id', 'source_file', 'start_row', 'end_row', 'label']].copy()
    pred_df['prob'] = test_probs
    pred_df['pred'] = test_pred
    pred_df['abs_error'] = np.abs(pred_df['label'] - pred_df['prob'])
    misses = pred_df[pred_df['pred'] != pred_df['label']].nlargest(5, 'abs_error')
    if len(misses) < 5:
        misses = pred_df.nlargest(5, 'abs_error')

    torch.save(
        {
            'state_dict': best_state,
            'mean': mean,
            'std': std,
            'threshold': threshold,
            'feature_columns': manifest['casper']['feature_columns'],
            'window_size': w,
        },
        'models/casper_cnn.pt',
    )
    pred_df.to_parquet('reports/imu_test_preds.parquet', index=False)
    misses.reset_index(drop=True).to_parquet('reports/imu_worst5.parquet', index=False)
    Path('reports/imu_eval.json').write_text(json.dumps(metrics, indent=2) + '\n', encoding='utf-8')
    print(json.dumps(metrics))


if __name__ == '__main__':
    main()
bashRun the fault-detector training script and inspect held-out F1 alongside false alarms.
python -m src.audit.train_imu_cnn
Output
{"threshold": <your_threshold>, "val_f1": <your_val_f1>, "test_f1": <your_test_f1>, "test_precision": <your_precision>, "test_recall": <your_recall>, "test_false_alarm_rate": <your_far>}
Stage 05 Checkpoint

models/casper_cnn.pt, reports/imu_eval.json and reports/imu_worst5.parquet exist, with held-out anomaly F1 reaching at least 0.90 and false alarms no higher than 2 percent.

Stage 06 · build4 hours

Simulate 20 seeded MuJoCo contact rollouts

Author a compact planar pushing articulated-arm MJCF scene and confirm that twenty seeded episodes yield identical joint and contact logs across repeated runs.

MuJoCo's native Python bindings run the C physics engine deterministically on a single CPU thread when you reset MjData before each episode. Build a compact MJCF scene with explicit friction, fixed RK4 integration and named joints so Rerun 0.44 can also load the same XML directly.

textscenes/planar_push_arm.xmlCompact two-link planar pushing arm and sliding target block in MJCF XML.
<mujoco model="planar_push_arm">
  <option timestep="0.005" integrator="RK4" gravity="0 0 -9.81"/>
  <default>
    <geom condim="3" friction="0.6 0.005 0.0001"/>
    <joint damping="0.2"/>
  </default>
  <worldbody>
    <light pos="0 0 2.0" dir="0 0 -1"/>
    <geom name="table" type="plane" size="1.5 1.5 0.1" rgba="0.2 0.22 0.26 1"/>
    <body name="base_link" pos="0 0 0.06">
      <geom name="base_geom" type="cylinder" size="0.05 0.06" rgba="0.35 0.4 0.48 1"/>
      <body name="upper_arm" pos="0 0 0.02">
        <joint name="shoulder" type="hinge" axis="0 0 1" range="-2.4 2.4"/>
        <geom name="upper_geom" type="capsule" fromto="0 0 0 0.28 0 0" size="0.022" rgba="0.15 0.65 0.85 1"/>
        <body name="forearm" pos="0.28 0 0">
          <joint name="elbow" type="hinge" axis="0 0 1" range="-2.4 2.4"/>
          <geom name="forearm_geom" type="capsule" fromto="0 0 0 0.24 0 0" size="0.02" rgba="0.2 0.85 0.65 1"/>
          <site name="ee_tip" pos="0.24 0 0" size="0.015" rgba="1 0.3 0.3 1"/>
        </body>
      </body>
    </body>
    <body name="target_block" pos="0.34 0.08 0.04">
      <joint name="block_x" type="slide" axis="1 0 0" damping="0.05"/>
      <joint name="block_y" type="slide" axis="0 1 0" damping="0.05"/>
      <joint name="block_yaw" type="hinge" axis="0 0 1" damping="0.02"/>
      <geom name="block_geom" type="box" size="0.04 0.04 0.04" mass="0.35" rgba="0.95 0.55 0.15 1"/>
    </body>
  </worldbody>
  <actuator>
    <position name="act_shoulder" joint="shoulder" kp="35"/>
    <position name="act_elbow" joint="elbow" kp="25"/>
  </actuator>
</mujoco>

Write a runner that executes 20 seeded episodes, calls mujoco.mj_contactForce on every active contact pair, and records joint angles, end-effector coordinates and contact forces per timestep. Running a second pass across the same seeds lets you assert zero floating-point drift on your machine.

pythonsrc/audit/sim_mujoco.pyRun twenty seeded contact episodes in MuJoCo and assert zero drift across repeated passes.
from pathlib import Path
import hashlib
import json
import mujoco
import numpy as np
import pandas as pd
import yaml


def run_rollouts(xml_path: Path, num_episodes: int, steps: int, base_seed: int) -> tuple[pd.DataFrame, dict[str, str]]:
    model = mujoco.MjModel.from_xml_path(str(xml_path))
    data = mujoco.MjData(model)
    ee_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, 'ee_tip')
    rows = []
    digests = {}
    force6 = np.zeros(6, dtype=np.float64)

    for ep in range(num_episodes):
        seed = base_seed + ep
        rng = np.random.default_rng(seed)
        mujoco.mj_resetData(model, data)
        data.qpos[2] = float(rng.uniform(-0.04, 0.04))
        data.qpos[3] = float(rng.uniform(-0.05, 0.05))
        amp_s = float(rng.uniform(0.35, 0.75))
        amp_e = float(rng.uniform(-0.85, -0.35))
        phase = float(rng.uniform(0.0, 0.8))
        mujoco.mj_forward(model, data)

        ep_buf = []
        for step in range(steps):
            t = step * model.opt.timestep
            data.ctrl[0] = amp_s * np.sin(2.5 * t + phase)
            data.ctrl[1] = amp_e * np.cos(2.0 * t + phase)
            mujoco.mj_step(model, data)
            normal_sum = 0.0
            tangent_sum = 0.0
            for cid in range(data.ncon):
                mujoco.mj_contactForce(model, data, cid, force6)
                normal_sum += float(abs(force6[0]))
                tangent_sum += float(np.hypot(force6[1], force6[2]))
            ee = data.site_xpos[ee_id]
            rec = [
                float(data.time),
                float(data.qpos[0]),
                float(data.qpos[1]),
                float(data.qpos[2]),
                float(data.qpos[3]),
                float(data.qpos[4]),
                float(ee[0]),
                float(ee[1]),
                float(ee[2]),
                normal_sum,
                tangent_sum,
            ]
            ep_buf.append(rec)
            rows.append({
                'episode': ep,
                'seed': seed,
                'step': step,
                'time_s': rec[0],
                'q_shoulder': rec[1],
                'q_elbow': rec[2],
                'block_x': rec[3],
                'block_y': rec[4],
                'block_yaw': rec[5],
                'ee_x': rec[6],
                'ee_y': rec[7],
                'ee_z': rec[8],
                'contact_normal_n': rec[9],
                'contact_tangent_n': rec[10],
                'ncon': int(data.ncon),
            })
        arr = np.asarray(ep_buf, dtype=np.float64)
        digests[str(seed)] = hashlib.sha256(arr.tobytes()).hexdigest()
    return pd.DataFrame(rows), digests


def main() -> None:
    cfg = yaml.safe_load(Path('params.yaml').read_text(encoding='utf-8'))
    xml_path = Path('scenes/planar_push_arm.xml')
    n_ep = int(cfg['mujoco']['num_episodes'])
    steps = int(cfg['mujoco']['steps_per_episode'])
    base_seed = int(cfg['mujoco']['base_seed'])

    df_a, digests_a = run_rollouts(xml_path, n_ep, steps, base_seed)
    df_b, digests_b = run_rollouts(xml_path, n_ep, steps, base_seed)
    numeric_cols = ['time_s', 'q_shoulder', 'q_elbow', 'block_x', 'block_y', 'ee_x', 'ee_y', 'ee_z', 'contact_normal_n', 'contact_tangent_n']
    max_diff = float(np.max(np.abs(df_a[numeric_cols].to_numpy() - df_b[numeric_cols].to_numpy())))
    bit_identical = (digests_a == digests_b) and (max_diff == 0.0)

    Path('reports').mkdir(exist_ok=True)
    df_a.to_parquet('reports/mujoco_rollouts.parquet', index=False)
    report = {
        'num_episodes': n_ep,
        'steps_per_episode': steps,
        'bit_identical': bit_identical,
        'max_abs_diff': max_diff,
        'seed_digests': digests_a,
    }
    Path('reports/mujoco_determinism.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
    print(json.dumps({'bit_identical': bit_identical, 'max_abs_diff': max_diff}))


if __name__ == '__main__':
    main()
bashRun the MuJoCo simulation and determinism verification.
python src/audit/sim_mujoco.py
Output
{"bit_identical": true, "max_abs_diff": 0.0}
Stage 06 Checkpoint

reports/mujoco_rollouts.parquet holds all 20 episodes, and reports/mujoco_determinism.json confirms bit_identical: true with max_abs_diff: 0.0.

Stage 07 · build4 hours

Load lerobot/pusht and score a baseline policy

Load lerobot/pusht through the LeRobot v3.0 Python API, partition episodes strictly by episode_index, and train a compact PyTorch behavioral-cloning baseline to score held-out action MSE.

The lerobot/pusht repository on Hugging Face ships in LeRobot v3.0 format with 206 planar pushing episodes, 96x96 RGB frames (observation.image), 2D proprioceptive states (observation.state) and 2D target actions (action). Splitting by episode index keeps consecutive frames from the same demonstration out of both training and evaluation.

pythonsrc/audit/train_pusht.pyFit a compact CNN and state behavioral-cloning baseline on lerobot/pusht and evaluate unseen episode error.
from pathlib import Path
import json
import numpy as np
import pandas as pd
import torch
from torch import nn
from torch.utils.data import DataLoader, Subset
import yaml
from lerobot.datasets import LeRobotDataset


class PushTBaselinePolicy(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.vision = nn.Sequential(
            nn.Conv2d(3, 16, kernel_size=5, stride=2, padding=2),
            nn.ReLU(),
            nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1),
            nn.ReLU(),
            nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d((1, 1)),
        )
        self.head = nn.Sequential(
            nn.Linear(64 + 2, 64),
            nn.ReLU(),
            nn.Linear(64, 2),
        )

    def forward(self, image: torch.Tensor, state: torch.Tensor) -> torch.Tensor:
        vis = self.vision(image).flatten(1)
        return self.head(torch.cat([vis, state], dim=1))


def episode_frame_indices(ds: LeRobotDataset, train_eps: int, val_eps: int) -> tuple[list[int], list[int], list[int]]:
    ep_col = ds.hf_dataset['episode_index']
    ep_arr = np.asarray(ep_col, dtype=np.int64)
    train_idx = np.where(ep_arr < train_eps)[0].tolist()
    val_idx = np.where((ep_arr >= train_eps) & (ep_arr < train_eps + val_eps))[0].tolist()
    test_idx = np.where(ep_arr >= train_eps + val_eps)[0].tolist()
    return train_idx, val_idx, test_idx


def main() -> None:
    cfg = yaml.safe_load(Path('params.yaml').read_text(encoding='utf-8'))
    seed = int(cfg['seed'])
    np.random.seed(seed)
    torch.manual_seed(seed)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    ds = LeRobotDataset('lerobot/pusht', root=Path('data/raw/pusht'), video_backend='pyav')
    tr_idx, va_idx, te_idx = episode_frame_indices(
        ds, int(cfg['pusht']['train_episodes']), int(cfg['pusht']['val_episodes'])
    )
    stats = ds.meta.stats
    s_mean = torch.as_tensor(stats['observation.state']['mean'], dtype=torch.float32, device=device)
    s_std = torch.as_tensor(stats['observation.state']['std'], dtype=torch.float32, device=device) + 1e-6
    a_mean = torch.as_tensor(stats['action']['mean'], dtype=torch.float32, device=device)
    a_std = torch.as_tensor(stats['action']['std'], dtype=torch.float32, device=device) + 1e-6

    gen = torch.Generator().manual_seed(seed)
    train_loader = DataLoader(Subset(ds, tr_idx), batch_size=int(cfg['pusht']['batch_size']), shuffle=True, generator=gen, num_workers=0)
    val_loader = DataLoader(Subset(ds, va_idx), batch_size=int(cfg['pusht']['batch_size']), shuffle=False, num_workers=0)
    test_loader = DataLoader(Subset(ds, te_idx), batch_size=int(cfg['pusht']['batch_size']), shuffle=False, num_workers=0)

    model = PushTBaselinePolicy().to(device)
    opt = torch.optim.AdamW(model.parameters(), lr=float(cfg['pusht']['lr']), weight_decay=1e-4)
    loss_fn = nn.MSELoss()
    best_val, best_state = float('inf'), None

    def eval_loader(loader: DataLoader) -> tuple[float, list[dict]]:
        model.eval()
        sq_errs = []
        records = []
        with torch.no_grad():
            for batch in loader:
                img = batch['observation.image'].to(device, dtype=torch.float32)
                st = (batch['observation.state'].to(device, dtype=torch.float32) - s_mean) / s_std
                act = batch['action'].to(device, dtype=torch.float32)
                pred = model(img, st) * a_std + a_mean
                diff = (pred - act).cpu().numpy()
                sq_errs.append(np.mean(diff ** 2, axis=1))
                ep_ids = batch['episode_index'].cpu().numpy().reshape(-1)
                fr_ids = batch['frame_index'].cpu().numpy().reshape(-1)
                ts = batch['timestamp'].cpu().numpy().reshape(-1)
                p_np, a_np = pred.cpu().numpy(), act.cpu().numpy()
                for i in range(len(ep_ids)):
                    records.append({
                        'episode_index': int(ep_ids[i]),
                        'frame_index': int(fr_ids[i]),
                        'timestamp': float(ts[i]),
                        'true_a0': float(a_np[i, 0]),
                        'true_a1': float(a_np[i, 1]),
                        'pred_a0': float(p_np[i, 0]),
                        'pred_a1': float(p_np[i, 1]),
                    })
        return float(np.mean(np.concatenate(sq_errs))), records

    for _ in range(int(cfg['pusht']['epochs'])):
        model.train()
        for batch in train_loader:
            img = batch['observation.image'].to(device, dtype=torch.float32)
            st = (batch['observation.state'].to(device, dtype=torch.float32) - s_mean) / s_std
            act_n = (batch['action'].to(device, dtype=torch.float32) - a_mean) / a_std
            opt.zero_grad()
            loss = loss_fn(model(img, st), act_n)
            loss.backward()
            opt.step()
        val_mse, _ = eval_loader(val_loader)
        if val_mse < best_val:
            best_val = val_mse
            best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}

    model.load_state_dict({k: v.to(device) for k, v in best_state.items()})
    test_mse, test_records = eval_loader(test_loader)

    torch.save({'state_dict': best_state, 'stats': stats}, 'models/pusht_bc.pt')
    pd.DataFrame(test_records).to_parquet('reports/pusht_test_preds.parquet', index=False)
    summary = {
        'num_episodes': int(ds.num_episodes),
        'train_frames': len(tr_idx),
        'val_frames': len(va_idx),
        'test_frames': len(te_idx),
        'val_action_mse': round(best_val, 4),
        'test_action_mse': round(test_mse, 4),
    }
    Path('reports/pusht_eval.json').write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
    print(json.dumps({'val_action_mse': summary['val_action_mse'], 'test_action_mse': summary['test_action_mse']}))


if __name__ == '__main__':
    main()
bashTrain the PushT behavioral-cloning baseline and log held-out action MSE.
python src/audit/train_pusht.py
Output
{"val_action_mse": <your_val_mse>, "test_action_mse": <your_test_mse>}
Stage 07 Checkpoint

models/pusht_bc.pt, reports/pusht_eval.json and reports/pusht_test_preds.parquet exist, and held-out action MSE is computed strictly on unseen PushT episodes.

Stage 08 · build2 hours

Export CASPER IMU audit recordings to Rerun

Stream CASPER IMU sensor channels, 1D-CNN anomaly probabilities, decision thresholds and the five worst misses into compact Rerun 0.44 .rrd archives.

Rerun 0.44 separates entity paths from timelines so sensor waveforms, model probabilities and event logs scrub in lockstep. Using rr.RecordingStream, rr.set_time("elapsed", duration=...) and rr.Scalars(...) lets you write one overview stream alongside five focused miss recordings.

pythonsrc/audit/log_imu_rerun.pyExport CASPER IMU sensor channels, anomaly scores and five worst-miss archives as Rerun .rrd files.
from pathlib import Path
import json
import numpy as np
import pandas as pd
import rerun as rr
import yaml


def log_imu_recording(
    out_path: Path,
    windows_df: pd.DataFrame,
    preds_df: pd.DataFrame,
    feature_cols: list[str],
    threshold: float,
    sample_rate_hz: float,
) -> None:
    rec = rr.RecordingStream('casper_imu_audit')
    rec.save(str(out_path))
    rec.log('imu/threshold', rr.SeriesLines(colors=[255, 180, 0], names='threshold'), static=True)
    rec.log('imu/anomaly_prob', rr.SeriesLines(colors=[230, 60, 60], names='anomaly_prob'), static=True)
    rec.log('imu/ground_truth', rr.SeriesLines(colors=[60, 200, 120], names='label'), static=True)

    merged = windows_df.merge(preds_df[['window_id', 'prob', 'pred']], on='window_id', how='inner')
    n_ch = len(feature_cols)
    dt = 1.0 / sample_rate_hz
    t = 0.0
    for row in merged.itertuples(index=False):
        arr = np.asarray(row.values, dtype=np.float32).reshape(-1, n_ch)
        for sample in arr:
            rec.set_time('elapsed', duration=t)
            for ch_idx, col_name in enumerate(feature_cols[:6]):
                rec.log(f'imu/channels/{col_name}', rr.Scalars(float(sample[ch_idx])))
            rec.log('imu/anomaly_prob', rr.Scalars(float(row.prob)))
            rec.log('imu/threshold', rr.Scalars(float(threshold)))
            rec.log('imu/ground_truth', rr.Scalars(float(row.label)))
            t += dt
        rec.log('imu/events', rr.TextLog(f'{row.window_id} label={row.label} prob={row.prob:.3f} pred={row.pred}'))
    rec.flush()


def main() -> None:
    cfg = yaml.safe_load(Path('params.yaml').read_text(encoding='utf-8'))
    manifest = json.loads(Path('data/processed/split_checksums.json').read_text(encoding='utf-8'))
    imu_eval = json.loads(Path('reports/imu_eval.json').read_text(encoding='utf-8'))
    out_dir = Path('exports')
    out_dir.mkdir(exist_ok=True)

    imu_test_win = pd.read_parquet('data/processed/casper_windows_test.parquet')
    imu_preds = pd.read_parquet('reports/imu_test_preds.parquet')
    imu_worst5 = pd.read_parquet('reports/imu_worst5.parquet')

    fcols = manifest['casper']['feature_columns']
    hz = float(cfg['casper']['sample_rate_hz'])
    thr = float(imu_eval['threshold'])

    normal_slice = imu_test_win[imu_test_win['label'] == 0].head(20)
    anomaly_slice = imu_test_win[imu_test_win['label'] == 1].head(20)
    audit_slice = pd.concat([normal_slice, anomaly_slice], ignore_index=True)
    log_imu_recording(out_dir / 'imu_audit.rrd', audit_slice, imu_preds, fcols, thr, hz)
    for idx, row in imu_worst5.iterrows():
        one_win = imu_test_win[imu_test_win['window_id'] == row['window_id']]
        log_imu_recording(out_dir / f'imu_miss_{idx + 1:02d}.rrd', one_win, imu_preds, fcols, thr, hz)
    print('Exported IMU Rerun archives to exports/')


if __name__ == '__main__':
    main()
bashGenerate the CASPER IMU Rerun archives and verify the chunk summary.
python src/audit/log_imu_rerun.py
rerun rrd stats exports/imu_audit.rrd
Output
Exported IMU Rerun archives to exports/
<chunk and entity summary for imu_audit.rrd>
Stage 08 Checkpoint

exports/imu_audit.rrd and exports/imu_miss_01.rrd through 05.rrd exist on disk, and rerun rrd stats exports/imu_audit.rrd exits with code 0.

Stage 09 · build2 hours 30 minutes

Export synchronized MuJoCo, IRB 120 and PushT logs

Combine the MuJoCo MJCF arm model, contact-force arrows, IRB 120 pose errors and PushT camera frames on one Rerun 0.44 timeline alongside five kinematics failure archives.

Loading scenes/planar_push_arm.xml directly through rr.mjcf.MjcfTree.from_file_path draws the MuJoCo arm geometry beside 3D contact vectors without hand-converting meshes. Placing IRB 120 actual-versus-predicted pose markers and PushT RGB camera frames on the same elapsed timeline lets you audit every subsystem in one viewport.

DATACASPER windows andCNN probsTOOLMuJoCo MJCF andcontact forcesMODELIRB 120 actual vspred posesDATAPushT RGB frames andactionsOUTimu_audit.rrd + 5miss .rrdOUTstudio_replay.rrd + 5pose .rrdrr.Scalars on elapsedMjcfTree + Arrows3DPoints3D error pairsImage + action scalars
Synchronized Rerun 0.44 recording streams writing full studio timelines and ten focused failure archives.
pythonsrc/audit/log_studio_rerun.pyWrite the combined studio timeline recording alongside five kinematics outlier archives.
from pathlib import Path
import numpy as np
import pandas as pd
import rerun as rr
from lerobot.datasets import LeRobotDataset


def log_studio_replay(
    out_path: Path,
    mujoco_df: pd.DataFrame,
    kin_df: pd.DataFrame,
    pusht_preds: pd.DataFrame,
    pusht_ds: LeRobotDataset,
) -> None:
    rec = rr.RecordingStream('robotics_audit_studio')
    rec.save(str(out_path))
    mjcf_tree = rr.mjcf.MjcfTree.from_file_path('scenes/planar_push_arm.xml', entity_path_prefix='mujoco')
    mjcf_tree.log_to_recording(recording=rec)

    ep0 = mujoco_df[mujoco_df['episode'] == 0].reset_index(drop=True)
    first_pusht_ep = int(pusht_preds['episode_index'].iloc[0])
    ep_pusht = pusht_preds[pusht_preds['episode_index'] == first_pusht_ep].reset_index(drop=True)
    ep_indices = np.where(np.asarray(pusht_ds.hf_dataset['episode_index']) == first_pusht_ep)[0]
    n_steps = min(len(ep0), len(kin_df), len(ep_pusht))

    for step in range(n_steps):
        sim_row = ep0.iloc[step]
        kin_row = kin_df.iloc[step]
        pt_row = ep_pusht.iloc[step]
        rec.set_time('elapsed', duration=float(sim_row['time_s']))

        ee_pos = np.array([[sim_row['ee_x'], sim_row['ee_y'], sim_row['ee_z']]], dtype=np.float32)
        force_vec = np.array([[sim_row['contact_tangent_n'] * 0.02, 0.0, sim_row['contact_normal_n'] * 0.02]], dtype=np.float32)
        rec.log('mujoco/ee_pose', rr.Points3D(ee_pos, colors=[[0, 220, 180]], radii=0.015))
        rec.log('mujoco/contact_force', rr.Arrows3D(origins=ee_pos, vectors=force_vec, colors=[[255, 90, 60]]))
        rec.log('mujoco/metrics/contact_normal_n', rr.Scalars(float(sim_row['contact_normal_n'])))

        true_m = np.array([[kin_row['true_x_mm'], kin_row['true_y_mm'], kin_row['true_z_mm']]], dtype=np.float32) / 1000.0
        pred_m = np.array([[kin_row['pred_x_mm'], kin_row['pred_y_mm'], kin_row['pred_z_mm']]], dtype=np.float32) / 1000.0
        rec.log('irb120/actual_pose', rr.Points3D(true_m, colors=[[80, 220, 120]], radii=0.015))
        rec.log('irb120/pred_pose', rr.Points3D(pred_m, colors=[[255, 80, 140]], radii=0.015))
        rec.log('irb120/error_vector', rr.Arrows3D(origins=true_m, vectors=(pred_m - true_m), colors=[[255, 210, 60]]))
        rec.log('irb120/error_mm', rr.Scalars(float(kin_row['error_mm'])))

        frame_sample = pusht_ds[int(ep_indices[step])]
        img_chw = frame_sample['observation.image'].numpy()
        img_hwc = np.clip(np.transpose(img_chw, (1, 2, 0)) * 255.0, 0, 255).astype(np.uint8)
        rec.log('pusht/camera', rr.Image(img_hwc))
        rec.log('pusht/action/true_0', rr.Scalars(float(pt_row['true_a0'])))
        rec.log('pusht/action/pred_0', rr.Scalars(float(pt_row['pred_a0'])))
    rec.flush()


def log_kinematics_failure(out_path: Path, row: pd.Series) -> None:
    rec = rr.RecordingStream('irb120_failure_case')
    rec.save(str(out_path))
    rec.set_time('step', sequence=0)
    true_m = np.array([[row['true_x_mm'], row['true_y_mm'], row['true_z_mm']]], dtype=np.float32) / 1000.0
    pred_m = np.array([[row['pred_x_mm'], row['pred_y_mm'], row['pred_z_mm']]], dtype=np.float32) / 1000.0
    rec.log('irb120/actual_pose', rr.Points3D(true_m, colors=[[80, 220, 120]], radii=0.02, labels=['actual']))
    rec.log('irb120/pred_pose', rr.Points3D(pred_m, colors=[[255, 80, 140]], radii=0.02, labels=['predicted']))
    rec.log('irb120/error_vector', rr.Arrows3D(origins=true_m, vectors=(pred_m - true_m), colors=[[255, 210, 60]]))
    rec.log('irb120/notes', rr.TextLog(f"row_id={int(row['row_id'])} region={row['region']} error_mm={row['error_mm']:.2f}"))
    rec.flush()


def main() -> None:
    out_dir = Path('exports')
    out_dir.mkdir(exist_ok=True)
    kin_preds = pd.read_parquet('reports/kinematics_test_preds.parquet')
    kin_worst5 = pd.read_parquet('reports/kinematics_worst5.parquet')
    mujoco_df = pd.read_parquet('reports/mujoco_rollouts.parquet')
    pusht_preds = pd.read_parquet('reports/pusht_test_preds.parquet')
    pusht_ds = LeRobotDataset('lerobot/pusht', root=Path('data/raw/pusht'), video_backend='pyav')

    log_studio_replay(out_dir / 'studio_replay.rrd', mujoco_df, kin_preds.head(200), pusht_preds, pusht_ds)
    for idx, row in kin_worst5.iterrows():
        log_kinematics_failure(out_dir / f'kinematics_err_{idx + 1:02d}.rrd', row)
    print('Exported', len(list(out_dir.glob('*.rrd'))), 'total Rerun archives in exports/')


if __name__ == '__main__':
    main()
bashGenerate the studio replay and kinematics failure recordings, then validate with rerun rrd stats.
python src/audit/log_studio_rerun.py
rerun rrd stats exports/studio_replay.rrd
Output
Exported 12 total Rerun archives in exports/
<chunk and entity summary for studio_replay.rrd>
Stage 09 Checkpoint

exports/ contains all 12 Rerun archives (imu_audit.rrd, studio_replay.rrd, five kinematics_err files and five imu_miss files), and rerun rrd stats validates both main streams.

Stage 10 · ship3 hours

Serve the Rerun 0.44 web viewer with telemetry off

Configure and launch the local Vite viewer bundle with telemetry switched off, then confirm zero outbound analytics beacons in browser developer tools.

Rerun 0.44 enables usage analytics by default in @rerun-io/web-viewer, while documenting three explicit opt-out controls. Embedded web apps pass { analytics: "off" } inside WebViewerOptions, iframe embeds pass analytics=off in the query string, and rerun --serve-web obeys rerun analytics disable.

jsonviewer/package.jsonLocal Vite package manifest pinning @rerun-io/web-viewer 0.44 and WebAssembly plugins.
{
  "name": "robot-audit-viewer",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host 127.0.0.1 --port 4173",
    "build": "vite build"
  },
  "dependencies": {
    "@rerun-io/web-viewer": "^0.44.0"
  },
  "devDependencies": {
    "vite": "^6.0.0",
    "vite-plugin-top-level-await": "^1.4.4",
    "vite-plugin-wasm": "^3.3.0"
  }
}
javascriptviewer/vite.config.jsConfigure Vite Wasm and top-level await plugins required by @rerun-io/web-viewer.
import { defineConfig } from 'vite';
import wasm from 'vite-plugin-wasm';
import topLevelAwait from 'vite-plugin-top-level-await';

export default defineConfig({
  plugins: [wasm(), topLevelAwait()],
  publicDir: '../exports',
  server: {
    host: '127.0.0.1',
    port: 4173,
  },
});
htmlviewer/index.htmlMinimal local studio shell with an archive picker covering all 12 exported .rrd files.
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Robotics Audit Studio (Rerun 0.44, Analytics Off)</title>
    <style>
      body { margin: 0; font-family: sans-serif; background: #111; color: #eee; }
      header { padding: 10px 16px; display: flex; gap: 12px; align-items: center; background: #1c1c22; }
      #viewer-container { position: relative; width: 100vw; height: calc(100vh - 48px); }
    </style>
  </head>
  <body>
    <header>
      <strong>Robotics Audit Studio</strong>
      <select id="rrd-select">
        <option value="/studio_replay.rrd">studio_replay.rrd</option>
        <option value="/imu_audit.rrd">imu_audit.rrd</option>
        <option value="/kinematics_err_01.rrd">kinematics_err_01.rrd</option>
        <option value="/kinematics_err_02.rrd">kinematics_err_02.rrd</option>
        <option value="/kinematics_err_03.rrd">kinematics_err_03.rrd</option>
        <option value="/kinematics_err_04.rrd">kinematics_err_04.rrd</option>
        <option value="/kinematics_err_05.rrd">kinematics_err_05.rrd</option>
        <option value="/imu_miss_01.rrd">imu_miss_01.rrd</option>
        <option value="/imu_miss_02.rrd">imu_miss_02.rrd</option>
        <option value="/imu_miss_03.rrd">imu_miss_03.rrd</option>
        <option value="/imu_miss_04.rrd">imu_miss_04.rrd</option>
        <option value="/imu_miss_05.rrd">imu_miss_05.rrd</option>
      </select>
    </header>
    <div id="viewer-container"></div>
    <script type="module" src="/main.js"></script>
  </body>
</html>
javascriptviewer/main.jsBoot @rerun-io/web-viewer with analytics: "off" and switch between exported .rrd archives.
import { WebViewer } from '@rerun-io/web-viewer';

const container = document.getElementById('viewer-container');
const selector = document.getElementById('rrd-select');
const viewer = new WebViewer();

function toArchiveUrl(path) {
  return new URL(path, window.location.origin).href;
}

await viewer.start(toArchiveUrl(selector.value), container, {
  analytics: 'off',
  width: '100%',
  height: '100%',
});

selector.addEventListener('change', async () => {
  await viewer.close('all');
  await viewer.open(toArchiveUrl(selector.value));
});
pythonsrc/audit/launch_viewer.pyEnforce rerun analytics disable and launch either the local Vite web viewer or rerun --serve-web.
import argparse
import subprocess
import sys
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser(description='Launch the local Rerun 0.44 web viewer with telemetry disabled.')
    parser.add_argument('--mode', choices=['npm', 'cli'], default='npm')
    parser.add_argument('--rrd', default='exports/studio_replay.rrd')
    args = parser.parse_args()

    subprocess.run(['rerun', 'analytics', 'disable'], check=True)
    if args.mode == 'npm':
        npm_cmd = 'npm.cmd' if sys.platform.startswith('win') else 'npm'
        subprocess.run([npm_cmd, 'run', 'dev'], cwd=Path('viewer'), check=True)
    else:
        subprocess.run(['rerun', '--serve-web', args.rrd], check=True)


if __name__ == '__main__':
    main()
bashInstall viewer packages once and launch the telemetry-disabled local web viewer.
npm --prefix viewer install
python src/audit/launch_viewer.py --mode npm
  1. Open http://127.0.0.1:4173/ in Chromium or Firefox and open browser Developer Tools before switching recordings.
  2. Select the Network tab, check Preserve Log, and clear existing rows.
  3. Scrub the elapsed timeline in studio_replay.rrd to inspect synchronized MuJoCo contact vectors, IRB 120 poses and PushT frames.
  4. Switch the dropdown to imu_audit.rrd and inspect IMU sensor channels beside anomaly probability spikes.
  5. Filter the Network tab by -domain:127.0.0.1 and confirm zero outbound telemetry or analytics requests appear.
Stage 10 Checkpoint

Both studio_replay.rrd and imu_audit.rrd scrub smoothly on 127.0.0.1:4173, and the browser Network tab records zero outbound analytics beacons.

Stage 11 · test4 hours 30 minutes

Wire the DVC metrics summary, pytest suite and README

Aggregate all evaluation metrics into one DVC-tracked JSON file, verify determinism and privacy with pytest, reproduce the pipeline on a tagged commit, and publish the technical README.

Consolidate every model and simulation report into reports/audit_summary.json so dvc metrics show displays the entire studio at a glance. Wiring every Python script into dvc.yaml lets any reviewer rebuild models, rollouts and Rerun archives with a single command.

pythonsrc/audit/build_summary.pyCombine IRB 120, CASPER IMU, PushT, MuJoCo and Rerun checks into one DVC metrics JSON.
from pathlib import Path
import json


def main() -> None:
    kin = json.loads(Path('reports/kinematics_eval.json').read_text(encoding='utf-8'))
    imu = json.loads(Path('reports/imu_eval.json').read_text(encoding='utf-8'))
    sim = json.loads(Path('reports/mujoco_determinism.json').read_text(encoding='utf-8'))
    pusht = json.loads(Path('reports/pusht_eval.json').read_text(encoding='utf-8'))
    rrds = sorted(p.name for p in Path('exports').glob('*.rrd'))

    summary = {
        'irb120_test_rmse_mm': kin['test_rmse_mm'],
        'irb120_test_p95_mm': kin['test_p95_mm'],
        'casper_test_f1': imu['test_f1'],
        'casper_test_recall': imu['test_recall'],
        'casper_test_false_alarm_rate': imu['test_false_alarm_rate'],
        'casper_threshold': imu['threshold'],
        'pusht_test_action_mse': pusht['test_action_mse'],
        'mujoco_bit_identical': sim['bit_identical'],
        'mujoco_max_abs_diff': sim['max_abs_diff'],
        'exported_rrd_count': len(rrds),
    }
    out = Path('reports/audit_summary.json')
    out.write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
    print(json.dumps(summary, indent=2))


if __name__ == '__main__':
    main()
yamldvc.yamlComplete DVC pipeline DAG from raw splits through models, MuJoCo rollouts, Rerun exports and final audit metrics.
stages:
  prepare_data:
    cmd: python src/audit/prepare_data.py
    deps:
      - data/raw/irb120
      - data/raw/casper
      - src/audit/prepare_data.py
    params:
      - seed
      - splits
      - irb120
      - casper.normal_files
      - casper.anomaly_files
      - casper.window_size
      - casper.max_normal_rows
    outs:
      - data/processed/irb120_train.parquet
      - data/processed/irb120_val.parquet
      - data/processed/irb120_test.parquet
      - data/processed/casper_windows_train.parquet
      - data/processed/casper_windows_val.parquet
      - data/processed/casper_windows_test.parquet
      - data/processed/split_checksums.json
  train_kinematics:
    cmd: python src/audit/train_kinematics.py
    deps:
      - data/processed/irb120_train.parquet
      - data/processed/irb120_val.parquet
      - data/processed/irb120_test.parquet
      - data/processed/split_checksums.json
      - src/audit/train_kinematics.py
    params:
      - seed
      - irb120
    outs:
      - models/irb120_mlp.pt
      - reports/kinematics_test_preds.parquet
      - reports/kinematics_worst5.parquet
      - reports/kinematics_eval.json
  train_imu:
    cmd: python -m src.audit.train_imu_cnn
    deps:
      - data/processed/casper_windows_train.parquet
      - data/processed/casper_windows_val.parquet
      - data/processed/casper_windows_test.parquet
      - data/processed/split_checksums.json
      - src/audit/imu_model.py
      - src/audit/train_imu_cnn.py
    params:
      - seed
      - casper
    outs:
      - models/casper_cnn.pt
      - reports/imu_test_preds.parquet
      - reports/imu_worst5.parquet
      - reports/imu_eval.json
  sim_mujoco:
    cmd: python src/audit/sim_mujoco.py
    deps:
      - scenes/planar_push_arm.xml
      - src/audit/sim_mujoco.py
    params:
      - mujoco
    outs:
      - reports/mujoco_rollouts.parquet
      - reports/mujoco_determinism.json
  train_pusht:
    cmd: python src/audit/train_pusht.py
    deps:
      - data/raw/pusht
      - src/audit/train_pusht.py
    params:
      - seed
      - pusht
    outs:
      - models/pusht_bc.pt
      - reports/pusht_test_preds.parquet
      - reports/pusht_eval.json
  export_imu_rerun:
    cmd: python src/audit/log_imu_rerun.py
    deps:
      - data/processed/casper_windows_test.parquet
      - data/processed/split_checksums.json
      - reports/imu_test_preds.parquet
      - reports/imu_worst5.parquet
      - reports/imu_eval.json
      - src/audit/log_imu_rerun.py
    params:
      - casper.sample_rate_hz
    outs:
      - exports/imu_audit.rrd
      - exports/imu_miss_01.rrd
      - exports/imu_miss_02.rrd
      - exports/imu_miss_03.rrd
      - exports/imu_miss_04.rrd
      - exports/imu_miss_05.rrd
  export_studio_rerun:
    cmd: python src/audit/log_studio_rerun.py
    deps:
      - data/raw/pusht
      - scenes/planar_push_arm.xml
      - reports/kinematics_test_preds.parquet
      - reports/kinematics_worst5.parquet
      - reports/mujoco_rollouts.parquet
      - reports/pusht_test_preds.parquet
      - src/audit/log_studio_rerun.py
    outs:
      - exports/studio_replay.rrd
      - exports/kinematics_err_01.rrd
      - exports/kinematics_err_02.rrd
      - exports/kinematics_err_03.rrd
      - exports/kinematics_err_04.rrd
      - exports/kinematics_err_05.rrd
  build_summary:
    cmd: python src/audit/build_summary.py
    deps:
      - reports/kinematics_eval.json
      - reports/imu_eval.json
      - reports/mujoco_determinism.json
      - reports/pusht_eval.json
      - exports/imu_audit.rrd
      - exports/studio_replay.rrd
      - src/audit/build_summary.py
    metrics:
      - reports/audit_summary.json:
          cache: false

Automated checks catch the subtle regressions that break robotics audits silently, including nondeterministic physics rollouts, train-test split leakage and truncated .rrd archives. Add a pytest suite that exercises MuJoCo determinism, Parquet split disjointness, Rerun archive parsing and the telemetry opt-out flag on every commit.

pythontests/test_audit_suite.pyAutomated pytest checks for MuJoCo determinism, zero split leakage, Rerun archive integrity and analytics opt-out.
from pathlib import Path
import json
import subprocess
import pandas as pd
from src.audit.sim_mujoco import run_rollouts


def test_mujoco_seed_determinism() -> None:
    xml_path = Path('scenes/planar_push_arm.xml')
    df1, dig1 = run_rollouts(xml_path, num_episodes=4, steps=40, base_seed=1000)
    df2, dig2 = run_rollouts(xml_path, num_episodes=4, steps=40, base_seed=1000)
    assert dig1 == dig2
    assert df1.equals(df2)


def test_zero_split_leakage() -> None:
    irb_sets = [set(pd.read_parquet(f'data/processed/irb120_{s}.parquet')['row_id']) for s in ('train', 'val', 'test')]
    assert irb_sets[0].isdisjoint(irb_sets[1])
    assert irb_sets[0].isdisjoint(irb_sets[2])
    assert irb_sets[1].isdisjoint(irb_sets[2])

    imu_sets = [set(pd.read_parquet(f'data/processed/casper_windows_{s}.parquet')['window_id']) for s in ('train', 'val', 'test')]
    assert imu_sets[0].isdisjoint(imu_sets[1])
    assert imu_sets[0].isdisjoint(imu_sets[2])
    assert imu_sets[1].isdisjoint(imu_sets[2])

    for split in ('train', 'val', 'test'):
        df = pd.read_parquet(f'data/processed/casper_windows_{split}.parquet')
        for _, grp in df.groupby('source_file'):
            ordered = grp.sort_values('start_row')
            assert (ordered['start_row'].iloc[1:].to_numpy() >= ordered['end_row'].iloc[:-1].to_numpy()).all()


def test_rerun_archive_integrity() -> None:
    expected = [
        'imu_audit.rrd',
        'studio_replay.rrd',
        *[f'kinematics_err_{i:02d}.rrd' for i in range(1, 6)],
        *[f'imu_miss_{i:02d}.rrd' for i in range(1, 6)],
    ]
    for name in expected:
        path = Path('exports') / name
        assert path.is_file() and path.stat().st_size > 64
        res = subprocess.run(['rerun', 'rrd', 'stats', str(path)], capture_output=True, text=True, check=False)
        assert res.returncode == 0, res.stderr


def test_viewer_telemetry_disabled() -> None:
    viewer_js = Path('viewer/main.js').read_text(encoding='utf-8')
    assert "analytics: 'off'" in viewer_js or 'analytics: "off"' in viewer_js
    cfg = subprocess.run(['rerun', 'analytics', 'config'], capture_output=True, text=True, check=True)
    assert 'false' in cfg.stdout.lower() or 'disabled' in cfg.stdout.lower()


def test_audit_summary_thresholds() -> None:
    summary = json.loads(Path('reports/audit_summary.json').read_text(encoding='utf-8'))
    assert summary['mujoco_bit_identical'] is True
    assert summary['mujoco_max_abs_diff'] == 0.0
    assert summary['casper_test_f1'] >= 0.90
    assert summary['casper_test_false_alarm_rate'] <= 0.02
    assert summary['exported_rrd_count'] >= 12

Write a technical README.md that ties your reported numbers in reports/audit_summary.json to five concrete failure recordings exported from Rerun. Include the hardware profile, wall-clock stage timings and proper attribution for all three datasets.

markdownREADME.mdTechnical README template linking versioned metrics, source attributions and five inspected Rerun failure archives.
# Robot Trajectory Replay and Audit Studio

## Environment and Hardware
- Python: `<your Python version>`
- Hardware: `<your CPU / GPU and RAM>`
- Full `dvc repro` wall-clock time: `<minutes>`

## Evaluation Summary (`reports/audit_summary.json`)
| Metric | Value |
| --- | --- |
| IRB 120 held-out Euclidean RMSE (mm) | `<value>` |
| IRB 120 held-out 95th-percentile error (mm) | `<value>` |
| CASPER IMU held-out anomaly F1 | `<value>` |
| CASPER IMU held-out false-alarm rate | `<value>` |
| PushT held-out action MSE | `<value>` |
| MuJoCo 20-seed determinism max abs diff | `0.0` |
| Rerun 0.44 outbound analytics beacons | `0` |

## Five Inspected Failure Recordings
1. `exports/kinematics_err_01.rrd`: `<row_id, workspace octant, error in mm and joint configuration note>`
2. `exports/kinematics_err_02.rrd`: `<row_id, workspace octant, error in mm and joint configuration note>`
3. `exports/imu_miss_01.rrd`: `<window_id, source fault file, predicted probability vs label and waveform cue>`
4. `exports/imu_miss_02.rrd`: `<window_id, source fault file, predicted probability vs label and waveform cue>`
5. `exports/imu_miss_03.rrd`: `<window_id, source fault file, predicted probability vs label and waveform cue>`

## Dataset Credits and Licenses
- Robot Kinematics Dataset (ABB IRB 120), Baressi Segota et al., CC BY 4.0.
- Industrial Robotic Arm IMU Data (CASPER 1 & 2, UR3e), Hakan Kayan, MIT License.
- lerobot/pusht planar pushing demonstrations, Chi et al. / Hugging Face LeRobot, MIT License.
bashCommit the pipeline, tag the release, reproduce from scratch and run the full pytest suite.
dvc repro
dvc metrics show
python -m pytest -v
git add dvc.yaml dvc.lock params.yaml scenes/ src/ viewer/package.json viewer/vite.config.js viewer/index.html viewer/main.js reports/audit_summary.json tests/ README.md
git commit -m "Complete reproducible robotics audit studio"
git tag v1.0-audit
Output
Path                        irb120_test_rmse_mm  casper_test_f1  casper_test_false_alarm_rate  pusht_test_action_mse
reports/audit_summary.json  <your_rmse_mm>       <your_f1>       <your_far>                    <your_mse>
5 passed in <seconds>s
Stage 11 Checkpoint

dvc repro rebuilds from scratch on tag v1.0-audit, dvc metrics show prints the versioned summary, all five pytest checks pass, and README.md documents five exported failure recordings.

Troubleshooting

LeRobotDataset('lerobot/pusht') fails with a missing datasets import, TorchCodec error or ffmpeg shared library error.

Install lerobot[dataset]>=0.6 (pip install "lerobot[dataset]>=0.6" av) and keep video_backend='pyav' in every LeRobotDataset call. On Linux or macOS, you can alternatively install ffmpeg via conda-forge if you want TorchCodec decoding.

prepare_data.py raises ValueError: No shared numeric IMU columns across CASPER CSVs.

Open data/interim/schema_report.json and compare column names across the normal and anomaly CSVs. Remove any incompatible file from casper.normal_files or map matching accelerometer and gyroscope columns explicitly before windowing.

IRB 120 pose RMSE looks 1,000 times too large or too small.

Check min_max for the tool coordinates in data/interim/schema_report.json. Set irb120.target_to_mm in params.yaml to 1000.0 if coordinates are stored in meters, or 1.0 if they are already stored in millimeters.

CASPER IMU test false-alarm rate exceeds 0.02 even though validation passed.

Lower casper.max_false_alarm_rate in params.yaml to 0.015 and re-run dvc repro. Increasing casper.max_normal_rows also gives the 1D-CNN wider normal-motion coverage.

Vite fails to bundle @rerun-io/web-viewer with a WebAssembly or top-level await error.

Confirm both vite-plugin-wasm and vite-plugin-top-level-await are installed in viewer/package.json and enabled inside viewer/vite.config.js, then restart with python src/audit/launch_viewer.py --mode npm.

dvc repro re-runs every stage after a fresh checkout even when nothing changed.

Verify that dvc.lock and all data/raw/*.dvc pointer files are committed to Git, and confirm you are running inside the same commit tag with the local DVC cache populated.

Done when

  • Running dvc repro reproduces identical split checksums and evaluation metrics from a fresh checkout on the same Git commit.
  • The PyTorch IRB 120 model reports held-out Euclidean tool-position RMSE alongside 95th-percentile position error in millimeters.
  • The PyTorch CASPER IMU classifier reaches at least 0.90 anomaly F1 across unseen test rows with false alarms at no more than 2 percent.
  • Twenty seeded MuJoCo contact rollouts produce bit-identical state logs across repeated runs on the same machine.
  • The LeRobot loader and baseline policy report held-out action MSE on lerobot/pusht episodes without breaking under the current LeRobot release.
  • Opening the exported .rrd archives in the local Rerun web viewer shows synchronized signals and trajectories while browser inspection confirms zero analytics beacons.
  • The full pytest verification suite passes on a clean checkout, and the README ties reported metrics to five concrete failure recordings exported from Rerun.

Deliverables

  • A version-controlled repository containing DVC stages, PyTorch training code, MuJoCo MJCF scenes and Rerun logging utilities.
  • A versioned DVC metrics JSON summary covering IRB 120 pose error alongside CASPER IMU anomaly scores and PushT policy action error.
  • Exported Rerun .rrd failure archives plus a local web-viewer launch script configured with usage telemetry disabled.
  • A technical README documenting environment setup, source credits, metric tables and five inspected failure episodes.

How to measure it

Report held-out Euclidean RMSE and 95th-percentile position error for the IRB 120 kinematics model in millimeters. On the held-out CASPER IMU test split, report anomaly F1 and recall alongside the false-alarm rate, targeting at least 0.90 F1 at 2 percent or fewer false alarms. Report held-out PushT action MSE alongside MuJoCo replay determinism error across identical seeds. Confirm zero outbound analytics requests from your self-hosted Rerun browser viewer.

Going further

  • Log real ROS 2 or simulated sensor bags in MCAP format and load them beside your MuJoCo trajectories using Rerun's built-in rerun mcap CLI importer.
  • Train a second IRB 120 model in the inverse direction (tool pose to joint angles) with sine and cosine outputs and compare workspace singularity errors against the forward MLP.
  • Attach rr.GrpcSink() to sim_mujoco.py so live contact rollouts stream into a running local Rerun viewer while still writing an .rrd archive through rr.set_sinks.
  • Export the worst CASPER and PushT failure windows back into a new LeRobot v3.0 dataset via LeRobotDataset.create and finalize() for targeted fine-tuning rounds.

Bounty stretch goals

  • Add an interactive Vuer browser scene that renders live MuJoCo joint poses beside the Rerun recording timeline.
  • Measure domain shift by injecting synthetic sensor noise and time-axis jitter into held-out IMU streams and charting the F1 drop.
  • Swap the LeRobot behavioral-cloning baseline for a diffusion policy checkpoint and compare rollout contact stability in MuJoCo.
  • Package the Rerun replay studio and DVC pipeline inside a container image that runs the full deterministic audit suite in CI.

References

Reporting behind this quest

An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.