code: pipeline check, set_norm_stats, explicit optimizer hook
Browse filesFiles changed (4)
94 unmodified lines959697989910010194 unmodified linesoutcome = ("toppled" if tilt > 45 else "held" if rise > 0.015 and tilt < 20 else "not lifted")return dict(job=job, piece=w.kind[name], outcome=outcome, neighbour_moved=moved > 0.002,pushed_before_close=pushed > 0.002, rise_mm=round(1000 * rise, 1), tilt_deg=round(tilt, 1),open_width_mm=round(1000 * (grasp.open_q - lo), 1))def main():94 unmodified lines959697989910010194 unmodified linesoutcome = ("toppled" if tilt > 45 else "held" if rise > 0.015 and tilt < 20 else "not lifted")return dict(job=job, piece=w.kind[name], outcome=outcome, neighbour_moved=moved > 0.002,pushed_before_close=pushed > 0.002, rise_mm=round(1000 * rise, 1), tilt_deg=round(tilt, 1),open_q_rad=round(float(grasp.open_q), 4)) # gripper joint angle, not a widthdef main():
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Zero-training check of the fine-tuning pipeline: same weights, compare predictions.
Checkpoints made by `lerobot-train` with --steps=1 and --policy.optimizer_lr=0.0 keepthe original weights but carry the processors the training pipeline built, inparticular the state/action normalization it takes from the training dataset(lerobot_train.py overrides the saved statistics when fine-tuning from a checkpoint).
1. Weights: every tensor of each variant against the reference (max abs difference).2. Normalization: the saved state/action statistics of each variant against the reference.3. Predictions: identical observations (the settings profile's scenes from --seed; the first frame and frames along the reference policy's own approach) and identical sampling noise (torch seed per observation). For each observation the whole 50-step action chunk is read (50 calls on a fresh queue) and compared with the reference: joint differences in degrees and the shift of the `gripperframe` site (forward kinematics of the commanded joints) in mm.
Writes pipeline_check.md and pipeline_check.json to --out.
Run: MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/pipeline_check.py \ --reference models/baseline --variant P0=ckpt/p0 --variant M0=ckpt/m0 --out sim/reports/pipeline_check"""from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))
def weight_diff(ref: Path, other: Path) -> dict: from safetensors.torch import load_file
a, b = load_file(str(ref / "model.safetensors")), load_file(str(other / "model.safetensors")) diffs = {k: float((a[k].float() - b[k].float()).abs().max()) for k in a if k in b} return dict(tensors=len(a), missing=len(set(a) ^ set(b)), max_abs=max(diffs.values(), default=None), differing=sum(v > 0 for v in diffs.values()))
def norm_stats(path: Path) -> dict: from safetensors.torch import load_file
out = {} for f in sorted(path.glob("policy_*processor*normalizer*.safetensors")): for k, v in load_file(str(f)).items(): if k.startswith(("observation.state", "action")): out[f"{f.name.split('_step')[0]}:{k}"] = v.float().numpy().tolist() return out
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--reference", required=True) ap.add_argument("--variant", action="append", default=[], help="NAME=path, repeatable") ap.add_argument("--seed", type=int, default=1_000_003) ap.add_argument("--scenes", type=int, default=8) ap.add_argument("--frames", default="0,20,40,60,80", help="frames along the reference rollout to sample") ap.add_argument("--out", required=True) args = ap.parse_args() import mujoco import numpy as np import torch from lerobot.utils.control_utils import predict_action
from camera_effects import training_look from episode import EpisodeRunner, load_config from eval_policy import load_policy from lerobot_export import Recorder, video_settings from piece_sets import sample_piece_set
out = Path(args.out) out.mkdir(parents=True, exist_ok=True) cfg = load_config() crf, pix_fmt = video_settings(cfg) ref = Path(args.reference) variants = dict(v.split("=", 1) for v in args.variant) report = dict(reference=str(ref), variants=variants, seed=args.seed) report["weights"] = {n: weight_diff(ref, Path(p)) for n, p in variants.items()} ref_stats = norm_stats(ref) report["normalization"] = {} for n, p in variants.items(): st = norm_stats(Path(p)) report["normalization"][n] = {k: float(np.max(np.abs(np.array(st[k]) - np.array(v)))) if k in st else None for k, v in ref_stats.items()}
# Observations: frames of the reference policy's own rollouts. runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9]), cfg, "check"), render=True) policy, pre, post, device = load_policy(str(ref)) frames = [int(x) for x in args.frames.split(",")] obs_list = [] lo, hi = runner.grip_range for i in range(args.scenes): erng = np.random.default_rng([args.seed, i]) ep_seed = int(erng.integers(2**62)) task = runner.setup(np.random.default_rng(ep_seed)) rec = Recorder(cfg, None) rec.begin(runner, task, np.random.default_rng(ep_seed ^ 0x5EED)) policy.reset() torch.manual_seed(int(erng.integers(2**31))) d = runner.d for f in range(max(frames) + 1): obs = {"observation.images.overhead": training_look(rec.observe(runner, "overhead"), crf, pix_fmt), "observation.images.wrist": training_look(rec.observe(runner, "wrist"), crf, pix_fmt), "observation.state": runner.to_lerobot(d.qpos[runner.qadr])} if f in frames: obs_list.append(dict(scene=i, frame=f, move=f"{task.source}-{task.dest.square}", obs={k: np.array(v, copy=True) for k, v in obs.items()})) a = predict_action(obs, policy, device, pre, post, use_amp=False, task=cfg["dataset"]["instruction"], robot_type="so101_follower").squeeze().float().cpu().numpy() d.ctrl[:5] = np.radians(a[:5]) d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo) for _ in range(runner.n_sub): mujoco.mj_step(runner.m, d) del policy torch.cuda.empty_cache()
m = runner.m dk = mujoco.MjData(m) site = m.site("gripperframe").id arm = runner.expert.kin.qadr
def fingertips(chunk): pts = [] for a in chunk: dk.qpos[arm] = np.radians(a[:5]) mujoco.mj_kinematics(m, dk) pts.append(dk.site_xpos[site].copy()) return np.array(pts)
def chunks(path): pol, pre_, post_, dev = load_policy(path) res = [] for j, o in enumerate(obs_list): pol.reset() torch.manual_seed(12345 + j) # identical sampling noise for every model res.append(np.array([predict_action(dict(o["obs"]), pol, dev, pre_, post_, use_amp=False, task=cfg["dataset"]["instruction"], robot_type="so101_follower") .squeeze().float().cpu().numpy() for _ in range(50)])) del pol torch.cuda.empty_cache() return res
ref_chunks = chunks(str(ref)) again = chunks(str(ref)) # the reference against itself: determinism floor report["predictions"] = {} for name, path in [("reference_again", str(ref))] + list(variants.items()): ch = again if name == "reference_again" else chunks(path) dj = np.array([np.abs(c - r) for c, r in zip(ch, ref_chunks)]) # obs x 50 x 6 tip = np.array([np.linalg.norm(fingertips(c) - fingertips(r), axis=1) for c, r in zip(ch, ref_chunks)]) report["predictions"][name] = dict( joint_deg_max=round(float(dj[..., :5].max()), 4), joint_deg_median=round(float(np.median(dj[..., :5])), 4), first_action_joint_deg_median=round(float(np.median(dj[:, 0, :5])), 4), gripper_cmd_max=round(float(dj[..., 5].max()), 3), fingertip_mm_median=round(1000 * float(np.median(tip)), 3), fingertip_mm_p95=round(1000 * float(np.percentile(tip, 95)), 3), fingertip_mm_max=round(1000 * float(tip.max()), 3), per_joint_deg_median=[round(float(np.median(dj[..., k])), 3) for k in range(6)]) report["observations"] = [dict(scene=o["scene"], frame=o["frame"], move=o["move"]) for o in obs_list] (out / "pipeline_check.json").write_text(json.dumps(report, indent=1)) lines = ["# Fine-tuning pipeline check (zero updates)", "", f"Reference `{ref}`. Variants: " + ", ".join(f"{n} = `{p}`" for n, p in variants.items()) + ".", f"{len(obs_list)} observations ({args.scenes} scenes from seed {args.seed}, frames {args.frames} of the " "reference policy's own rollout), each with identical sampling noise; the whole 50-step chunk compared.", "", "## Weights", "", "| variant | tensors | differing | max abs difference |", "|---|---|---|---|"] lines += [f"| {n} | {w['tensors']} | {w['differing']} | {w['max_abs']} |" for n, w in report["weights"].items()] lines += ["", "## Saved state/action normalization (max abs difference from the reference)", "", "| variant | " + " | ".join(report["normalization"][next(iter(variants))].keys()) + " |" if variants else "", "|---|" + "---|" * len(ref_stats)] lines += [f"| {n} | " + " | ".join(f"{v:.3g}" if v is not None else "-" for v in d.values()) + " |" for n, d in report["normalization"].items()] lines += ["", "## Predictions against the reference", "", "| model | joint deg median | joint deg max | first action deg median | gripper cmd max | " "fingertip mm median | fingertip mm p95 | fingertip mm max |", "|---|---|---|---|---|---|---|---|"] lines += [f"| {n} | {p['joint_deg_median']} | {p['joint_deg_max']} | {p['first_action_joint_deg_median']} | " f"{p['gripper_cmd_max']} | {p['fingertip_mm_median']} | {p['fingertip_mm_p95']} | {p['fingertip_mm_max']} |" for n, p in report["predictions"].items()] lines += ["", "`reference_again` is the reference model loaded a second time: the numerical floor (GPU " "non-determinism) any difference must be judged against."] (out / "pipeline_check.md").write_text("\n".join(lines) + "\n") print("\n".join(lines))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Make a fine-tune keep a checkpoint's normalization.
When `lerobot-train` fine-tunes from a checkpoint it replaces the checkpoint's savedstate/action normalization with the training dataset's statistics(lerobot_train.py passes them as processor overrides, and those take precedence).Merging correction data into a dataset changes those statistics, which by itselfshifts the policy's commands by millimetres at the grasp (sim/reports/pipeline_check).
This writes the checkpoint's saved statistics for `observation.state` and `action`into the dataset's meta/stats.json (the original is kept as meta/stats_original.json),so the override hands the checkpoint its own normalization back. Image statistics areleft alone (SmolVLA does not normalize images).
Run: .venv/bin/python sim/set_norm_stats.py data/merged_v2 models/baseline"""from __future__ import annotations
import argparseimport jsonimport osimport shutilfrom pathlib import Path
def saved_stats(checkpoint: Path) -> dict: from safetensors.torch import load_file
f = next(checkpoint.glob("policy_preprocessor_step_*_normalizer_processor.safetensors")) out: dict = {} for key, tensor in load_file(str(f)).items(): feature, stat = key.rsplit(".", 1) out.setdefault(feature, {})[stat] = tensor.float().numpy().tolist() return out
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("dataset") ap.add_argument("checkpoint") args = ap.parse_args() meta = Path(args.dataset) / "meta" stats_path = meta / "stats.json" backup = meta / "stats_original.json" if not backup.exists(): shutil.copyfile(stats_path, backup) stats = json.loads(backup.read_text()) saved = saved_stats(Path(args.checkpoint)) for feature in ("observation.state", "action"): for stat, value in saved[feature].items(): if stat in stats[feature]: stats[feature][stat] = value tmp = meta / "stats.json.tmp" # a new file, not an in-place edit: hard-linked copies stay intact tmp.write_text(json.dumps(stats, indent=2)) os.replace(tmp, stats_path) for feature in ("observation.state", "action"): print(feature, {s: [round(x, 3) for x in stats[feature][s]] for s in ("mean", "std")})
if __name__ == "__main__": main()10 unmodified lines11121314151614 unmodified lines3132333410 unmodified lines# Baseline (overhead and wrist only already, no train view needed):# ROOT=data/so101_chess_baseline REPO=Machanize/chess_phase_smolvla_baseline \# JOB=chess_phase_smolvla_baseline STEPS=10000 bash sim/train_policy.shset -euo pipefailcd "$(dirname "$0")/.."ROOT=${ROOT:-data/so101_chess_sim_train}14 unmodified lines--wandb.enable=false \--policy.push_to_hub="${PUSH:-true}" \--policy.repo_id="$REPO" \--policy.private=false10 unmodified lines11121314151617181914 unmodified lines343536373810 unmodified lines# Baseline (overhead and wrist only already, no train view needed):# ROOT=data/so101_chess_baseline REPO=Machanize/chess_phase_smolvla_baseline \# JOB=chess_phase_smolvla_baseline STEPS=10000 bash sim/train_policy.sh# EXTRA_ARGS adds lerobot-train options (for example --policy.optimizer_lr=0.0).# Note: when BASE is a trained checkpoint, lerobot-train replaces its saved state/action# normalization with the statistics of the dataset at ROOT (lerobot_train.py, overrides).set -euo pipefailcd "$(dirname "$0")/.."ROOT=${ROOT:-data/so101_chess_sim_train}14 unmodified lines--wandb.enable=false \--policy.push_to_hub="${PUSH:-true}" \--policy.repo_id="$REPO" \--policy.private=false \${EXTRA_ARGS:-}
chess-sim/code/sim/jaw_tolerance.py+1-1
chess-sim/code/sim/pipeline_check.pyAdded+185
chess-sim/code/sim/set_norm_stats.pyAdded+60
chess-sim/code/sim/train_policy.sh+5-1