File size: 9,892 Bytes
6145c8e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | """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 keep
the original weights but carry the processors the training pipeline built, in
particular 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 argparse
import json
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.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()
|