chess-sim: RL pilot summary and code (rl_env, rl_policy, rl_train, rl_check; eval_policy --fast/--expert-fp32)
Browse filesFiles changed (10)
- chess-sim/code/sim/README.md+5
- chess-sim/code/sim/eval_policy.py+34-13
- chess-sim/code/sim/rl_check.pyAdded+228
- chess-sim/code/sim/rl_env.pyAdded+230
- chess-sim/code/sim/rl_policy.pyAdded+219
- chess-sim/code/sim/rl_train.pyAdded+278
- chess-sim/code/sim/visual_probe.pyAdded+182
- chess-sim/reports/rl/pilot/args.jsonAdded+36
- chess-sim/reports/rl/pilot/log.jsonlAdded+8
- chess-sim/reports/rl/summary.mdAdded+98
43 unmodified lines44454647484943 unmodified lines| `collect_recovery.py` | DAgger-style correction demonstrations: the policy drives, the scripted teacher takes over (before the grasp, at a misaligned close, after a failed lift) and only its part is recorded. `--style v2` lines up from where the arm is; `v1` (first attempt) replanned from the approach height with a pause and made the policy hover. || `phase2_dart.toml` | Perturbed (DART-style) teacher, merged after another profile (`PHASE2_PROFILE=baseline,dart`): in a share of episodes the executed approach drifts 2-10 mm off-centre and returns before the fingertips reach the piece, while the recorded actions stay the clean plan (`Expert.perturb_pick`). || `validate_dart.py` | The perturbed teacher against the plain one on the same scenes, without cameras: success, touches on the target before closing, contacts with neighbours. || `paired_compare.py` | Two `eval_policy.py` runs on the same scenes, paired by episode index: success, discordant scenes with an exact McNemar test, per piece and per move. || `train_policy.sh` / `train_act.sh` | SmolVLA (from the base model, or `BASE=` a checkpoint) and ACT training on the pod. || `reports/grasp_validation.md` | Latest validation report (and `.json` with every trial). |43 unmodified lines444546474849505152535443 unmodified lines| `collect_recovery.py` | DAgger-style correction demonstrations: the policy drives, the scripted teacher takes over (before the grasp, at a misaligned close, after a failed lift) and only its part is recorded. `--style v2` lines up from where the arm is; `v1` (first attempt) replanned from the approach height with a pause and made the policy hover. || `phase2_dart.toml` | Perturbed (DART-style) teacher, merged after another profile (`PHASE2_PROFILE=baseline,dart`): in a share of episodes the executed approach drifts 2-10 mm off-centre and returns before the fingertips reach the piece, while the recorded actions stay the clean plan (`Expert.perturb_pick`). || `validate_dart.py` | The perturbed teacher against the plain one on the same scenes, without cameras: success, touches on the target before closing, contacts with neighbours. || `visual_probe.py` | Does the policy aim from the images? The teacher's hand frozen 40 and 20 mm above the piece, the piece moved 4 mm with the arm unchanged; how far each model's predicted grasp point follows it (1 = fully, 0 = ignores). Not yet run with a model. || `rl_env.py` | The simulator as an RL environment for a chunked policy: one step = one 50-frame chunk, scenes and success as eval_policy; VecChessEnv runs several in worker processes. || `rl_policy.py` | SmolVLA as a stochastic policy (ReinFlow noise at each denoising step), critic, stored prefixes, checkpoint with the baseline's processors. || `rl_train.py` | PPO fine-tuning over parallel simulators (per-element clipped ratios), validation curve, checkpoints. || `rl_check.py` | Checks before RL training: same as eval_policy, noise cost, likelihood, which weights change, save/reload. || `paired_compare.py` | Two `eval_policy.py` runs on the same scenes, paired by episode index: success, discordant scenes with an exact McNemar test, per piece and per move. || `train_policy.sh` / `train_act.sh` | SmolVLA (from the base model, or `BASE=` a checkpoint) and ACT training on the pod. || `reports/grasp_validation.md` | Latest validation report (and `.json` with every trial). |
41 unmodified lines4243444546474849505 unmodified lines56575859606132 unmodified lines9495969798991001 unmodified line10210310410510610710810911025 unmodified lines13613713813914014114214314414514614714841 unmodified lines19019119219319419519656 unmodified lines25325425525625725825927 unmodified lines28728828929029129241 unmodified linessys.path.insert(0, str(HERE))def load_policy(path: str, n_action_steps: int | None = None):"""The policy, its pre/post processors and the torch device. `n_action_steps` overrides howmany steps of each predicted chunk are executed before predicting again."""import torchfrom lerobot.configs.policies import PreTrainedConfigfrom lerobot.policies.factory import get_policy_class, make_pre_post_processors5 unmodified linesif n_action_steps:pcfg.n_action_steps = n_action_stepspolicy = get_policy_class(pcfg.type).from_pretrained(path, config=pcfg)policy.to(device).eval()pre, post = make_pre_post_processors(policy_cfg=pcfg, pretrained_path=path,preprocessor_overrides={"device_processor": {"device": device.type}})32 unmodified linesdef drive(runner, task, policy, pre, post, device, cfg, seconds, rec_rng_seed, video=None, stop_when_done=True,recorder=None, on_frame=None, on_substep=None, replan_near=None, near_height=0.07):"""Let the policy drive from the set-up state. Returns (Result, metrics).`recorder`: an already begun Recorder to render through (its dataset is not written).1 unmodified line`on_substep(f, k)`: called after every physics substep k of frame f.`replan_near`: while the gripper frame is within `near_height` (m) of the board surface,predict a new chunk after this many steps of the current one instead of all of them (therest of the chunk is dropped). A real arm knows this height from its joint angles."""import mujocoimport numpy as npfrom lerobot.utils.control_utils import predict_actionfrom camera_effects import training_look25 unmodified linesqueue.clear() # predict afresh from the current imagesif queue is not None and len(queue) == 0:predictions += 1over, wrist = (training_look(rec.observe(runner, c), crf, pix_fmt) for c in ("overhead", "wrist"))if video is not None:video.append(np.concatenate([over[::2, ::2], wrist[::2, ::2]], axis=1))obs = {"observation.images.overhead": over, "observation.images.wrist": wrist,"observation.state": runner.to_lerobot(d.qpos[runner.qadr])}a = predict_action(obs, policy, device, pre, post, use_amp=False, task=cfg["dataset"]["instruction"],robot_type="so101_follower")a = a.squeeze().float().cpu().numpy()d.ctrl[:5] = np.radians(a[:5])d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo)41 unmodified linestorch.set_num_threads(2) # several workers share the CPU; torch would take every corecfg = load_config()policy, pre, post, device = load_policy(args.policy, args.n_action_steps)runner, block_now = None, None# Each worker takes a contiguous slice, and every episode (its piece set, scene, move and the# policy's sampling noise) comes from (seed, episode index) alone: the same --seed gives the same56 unmodified linestorch.manual_seed(int(erng.integers(2**31))) # the policy's sampling noise, per episodet0 = time.time()r, m = drive(runner, task, policy, pre, post, device, cfg, args.seconds, ep_seed ^ 0x5EED, video,on_frame=on_frame, replan_near=args.replan_near, near_height=args.near_height_mm / 1000)m.pop("path")queue.put(dict(index=i, success=bool(r.success), reason=r.reason, frames=r.frames, seconds=round(time.time() - t0, 1),piece=w.kind[task.target], source=task.source, destination=task.dest.square or "bin",27 unmodified linesap.add_argument("--n-action-steps", type=int, help="replan after this many steps of each chunk (default: as trained)")ap.add_argument("--replan-near", type=int, help="near the board, replan after this many steps of each chunk")ap.add_argument("--near-height-mm", type=float, default=70.0, help="gripper-frame height above the board that counts as near")ap.add_argument("--out", default=str(HERE / "reports" / "policy_eval"))args = ap.parse_args()out = Path(args.out)41 unmodified lines42434445464748495051525 unmodified lines585960616263646566676869707132 unmodified lines1041051061071081091101 unmodified line11211311411511611711811912012112212312425 unmodified lines15015115215315415515615715815916016116216316416516641 unmodified lines20820921021121221321456 unmodified lines27127227327427527627727827 unmodified lines30630730830931031131231341 unmodified linessys.path.insert(0, str(HERE))def load_policy(path: str, n_action_steps: int | None = None, expert_fp32: bool = False):"""The policy, its pre/post processors and the torch device. `n_action_steps` overrides howmany steps of each predicted chunk are executed before predicting again.`expert_fp32`: run SmolVLA's action expert in float32. Loading otherwise rounds it to bfloat16(the checkpoint stores it in float32); its weights are reloaded from the file at full precision."""import torchfrom lerobot.configs.policies import PreTrainedConfigfrom lerobot.policies.factory import get_policy_class, make_pre_post_processors5 unmodified linesif n_action_steps:pcfg.n_action_steps = n_action_stepspolicy = get_policy_class(pcfg.type).from_pretrained(path, config=pcfg)if expert_fp32:from safetensors.torch import load_filepolicy.model.vlm_with_expert.lm_expert.float()weights = load_file(str(Path(path) / "model.safetensors"))expert = {k: v for k, v in weights.items() if ".lm_expert." in k}missing, unexpected = policy.load_state_dict(expert, strict=False)assert expert and not unexpected, "action expert weights not found in model.safetensors"policy.to(device).eval()pre, post = make_pre_post_processors(policy_cfg=pcfg, pretrained_path=path,preprocessor_overrides={"device_processor": {"device": device.type}})32 unmodified linesdef drive(runner, task, policy, pre, post, device, cfg, seconds, rec_rng_seed, video=None, stop_when_done=True,recorder=None, on_frame=None, on_substep=None, replan_near=None, near_height=0.07, fast=False):"""Let the policy drive from the set-up state. Returns (Result, metrics).`recorder`: an already begun Recorder to render through (its dataset is not written).1 unmodified line`on_substep(f, k)`: called after every physics substep k of frame f.`replan_near`: while the gripper frame is within `near_height` (m) of the board surface,predict a new chunk after this many steps of the current one instead of all of them (therest of the chunk is dropped). A real arm knows this height from its joint angles.`fast`: render only the frames where the policy predicts a new chunk (it ignores the images ofthe others); the next action of the current chunk is taken from its queue and postprocessed aspredict_action does. Without camera noise (the baseline profile) the results are identical."""import mujocoimport numpy as npimport torchfrom lerobot.utils.control_utils import predict_actionfrom camera_effects import training_look25 unmodified linesqueue.clear() # predict afresh from the current imagesif queue is not None and len(queue) == 0:predictions += 1if fast and video is None and queue is not None and len(queue) > 0:with torch.inference_mode():a = post(queue.popleft())else:over, wrist = (training_look(rec.observe(runner, c), crf, pix_fmt) for c in ("overhead", "wrist"))if video is not None:video.append(np.concatenate([over[::2, ::2], wrist[::2, ::2]], axis=1))obs = {"observation.images.overhead": over, "observation.images.wrist": wrist,"observation.state": runner.to_lerobot(d.qpos[runner.qadr])}a = predict_action(obs, policy, device, pre, post, use_amp=False, task=cfg["dataset"]["instruction"],robot_type="so101_follower")a = a.squeeze().float().cpu().numpy()d.ctrl[:5] = np.radians(a[:5])d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo)41 unmodified linestorch.set_num_threads(2) # several workers share the CPU; torch would take every corecfg = load_config()policy, pre, post, device = load_policy(args.policy, args.n_action_steps, args.expert_fp32)runner, block_now = None, None# Each worker takes a contiguous slice, and every episode (its piece set, scene, move and the# policy's sampling noise) comes from (seed, episode index) alone: the same --seed gives the same56 unmodified linestorch.manual_seed(int(erng.integers(2**31))) # the policy's sampling noise, per episodet0 = time.time()r, m = drive(runner, task, policy, pre, post, device, cfg, args.seconds, ep_seed ^ 0x5EED, video,on_frame=on_frame, replan_near=args.replan_near, near_height=args.near_height_mm / 1000,fast=args.fast)m.pop("path")queue.put(dict(index=i, success=bool(r.success), reason=r.reason, frames=r.frames, seconds=round(time.time() - t0, 1),piece=w.kind[task.target], source=task.source, destination=task.dest.square or "bin",27 unmodified linesap.add_argument("--n-action-steps", type=int, help="replan after this many steps of each chunk (default: as trained)")ap.add_argument("--replan-near", type=int, help="near the board, replan after this many steps of each chunk")ap.add_argument("--near-height-mm", type=float, default=70.0, help="gripper-frame height above the board that counts as near")ap.add_argument("--fast", action="store_true", help="render only the frames the policy predicts from (see drive)")ap.add_argument("--expert-fp32", action="store_true", help="run the action expert in float32 (see load_policy)")ap.add_argument("--out", default=str(HERE / "reports" / "policy_eval"))args = ap.parse_args()out = Path(args.out)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228"""Checks before an RL training run (sim/rl_policy.py, sim/rl_env.py, eval_policy.py --fast).
1. same_as_eval: with the noise off and one scene at a time, the RL environment and sampler reproduce eval_policy.py exactly on the same scenes (success, frames, closest approach, closing error): a) eval_policy --fast vs normal; b) the RL path with the action expert in bfloat16 (as loaded) vs eval_policy; c) the RL path with the expert in float32 (as trained here) vs eval_policy --expert-fp32.2. noise: success with each candidate noise schedule (sigma at the first and last denoising step) against no noise, on the same scenes (what exploration costs).3. likelihood: log-probabilities recomputed from stored chains and prefixes (other minibatch compositions) equal those at sampling time, so the PPO ratio starts at 1.4. update: after one PPO step only the intended weights changed; the backbone is bit-identical.5. reload: a saved checkpoint keeps the baseline's normalization, loads in eval_policy.load_policy (float32 expert, full precision) and gives the same chunk for the same x_0.Writes <out>/rl_check.md and .json. Needs anti-aliasing off (SIM_OFFSAMPLES=0).
Run (pod): MUJOCO_GL=egl PHASE2_PROFILE=baseline SIM_OFFSAMPLES=0 .venv/bin/python sim/rl_check.py \ --policy models/baseline --out sim/reports/rl/check"""from __future__ import annotations
import argparseimport hashlibimport jsonimport osimport subprocessimport sysimport tempfilefrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))FIELDS = ("success", "frames", "closest_mm", "close_lateral_mm")
def eval_run(policy, n, seed, out, fast, fp32=False): out = Path(out) if not (out / "eval_results.json").exists(): cmd = [sys.executable, str(HERE / "eval_policy.py"), "--policy", policy, "--episodes", str(n), "--workers", "2", "--seed", str(seed), "--video-episodes", "0", "--out", str(out)] cmd += (["--fast"] if fast else []) + (["--expert-fp32"] if fp32 else []) subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=dict(os.environ)) return {e["index"]: e for e in json.loads((out / "eval_results.json").read_text())["episodes"]}
def compare(a: dict, b: dict): diffs = [(i, f, a[i].get(f), b[i].get(f)) for i in sorted(a) for f in FIELDS if a[i].get(f) != b[i].get(f)] return dict(identical=not diffs, differences=diffs[:10], episodes=len(a), success=(sum(bool(x["success"]) for x in a.values()), sum(bool(x["success"]) for x in b.values())))
def digest(t): return hashlib.sha1(t.detach().float().cpu().numpy().tobytes()).hexdigest()
def set_schedule(pol, s0, s1): """Geometric noise schedule from s0 (first denoising step) to s1 (last), as FlowRL builds it.""" import math
import torch
frac = torch.linspace(0.0, 1.0, pol.n_steps, device=pol.device)[:, None] pol.log_sigma.data = (math.log(s0) + frac * (math.log(s1) - math.log(s0))).expand(pol.n_steps, pol.adim).clone() pol.sigma_min, pol.sigma_max = 0.5 * min(s0, s1), 1.5 * max(s0, s1)
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--policy", required=True) ap.add_argument("--out", required=True) ap.add_argument("--same-episodes", type=int, default=8) ap.add_argument("--noise-episodes", type=int, default=60) ap.add_argument("--seed", type=int, default=9_000_003) ap.add_argument("--noise-seed", type=int, default=9_400_003) ap.add_argument("--schedules", default="0.1:0.002,0.2:0.002,0.3:0.003", help="candidate noise schedules, first:last denoising step, comma-separated") args = ap.parse_args() out = Path(args.out) out.mkdir(parents=True, exist_ok=True) report = dict(args=vars(args)) schedules = [tuple(float(x) for x in s.split(":")) for s in args.schedules.split(",")]
# 1a / reference runs of eval_policy.py (before this process takes GPU memory). normal = eval_run(args.policy, args.same_episodes, args.seed, out / "eval_normal", fast=False) fast = eval_run(args.policy, args.same_episodes, args.seed, out / "eval_fast", fast=True) fp32 = eval_run(args.policy, args.same_episodes, args.seed, out / "eval_fast_fp32", fast=True, fp32=True) report["fast_vs_normal"] = compare(fast, normal) report["eval_fp32_vs_bf16"] = compare(fp32, normal) print("fast vs normal:", report["fast_vs_normal"], "| eval fp32 vs bf16 expert:", report["eval_fp32_vs_bf16"], flush=True)
import numpy as np import torch
from episode import load_config from rl_env import VecChessEnv from rl_policy import FlowRL from rl_train import ppo_update, run_episodes, summarize
cfg = load_config() instr = cfg["dataset"]["instruction"]
def same(pol): venv = VecChessEnv(1, cfg) eps = run_episodes(pol, venv, args.seed, list(range(args.same_episodes)), noise=False, early_stop=False, check_expert=True, record=False, eval_noise_seeds=True) venv.close() return {e["info"]["index"]: dict(e["result"], index=e["info"]["index"]) for e in eps}
# 1b. the RL path with the expert in bfloat16, as eval_policy loads it. pol = FlowRL(args.policy, instr, expert_fp32=False) report["rl_bf16_vs_eval"] = compare(same(pol), normal) print("rl bf16 vs eval:", report["rl_bf16_vs_eval"], flush=True) del pol torch.cuda.empty_cache()
# 1c. the RL path with the expert in float32 vs eval_policy --expert-fp32. pol = FlowRL(args.policy, instr, *schedules[0], expert_fp32=True) base_digests = {n: digest(p) for n, p in pol.model.named_parameters()} report["rl_fp32_vs_eval_fp32"] = compare(same(pol), fp32) print("rl fp32 vs eval fp32:", report["rl_fp32_vs_eval_fp32"], flush=True)
# 2. what exploration costs, per candidate schedule (batched, same scenes). venv = VecChessEnv(8, cfg) idx = list(range(args.noise_episodes)) torch.manual_seed(0) report["noise"] = {"off": summarize(run_episodes(pol, venv, args.noise_seed, idx, noise=False, early_stop=False, check_expert=False, record=False))} for s0, s1 in schedules: set_schedule(pol, s0, s1) report["noise"][f"{s0}:{s1}"] = summarize(run_episodes(pol, venv, args.noise_seed, idx, noise=True, early_stop=False, check_expert=False, record=False)) print("noise", f"{s0}:{s1}", report["noise"][f"{s0}:{s1}"], flush=True) print("noise off", report["noise"]["off"], flush=True)
# 3. likelihood of stored chains with their stored prefixes, other minibatch compositions. s0, s1 = schedules[0] set_schedule(pol, s0, s1) eps = run_episodes(pol, venv, args.noise_seed + 1, list(range(8)), noise=True, early_stop=True, check_expert=False, record=True) venv.close() dec = [d for e in eps for d in e["decisions"]][:24] with torch.no_grad(): chain = torch.stack([d["chain"] for d in dec]).to(pol.device) old = torch.stack([d["logp"] for d in dec]).to(pol.device) new_all, _ = pol.evaluate(None, chain, prefix=pol.stack_prefix([d["prefix"] for d in dec])) new_one = torch.cat([pol.evaluate(None, d["chain"][None].to(pol.device), prefix=pol.stack_prefix([d["prefix"]]))[0] for d in dec[:8]]) report["likelihood"] = dict( schedule=f"{s0}:{s1}", decisions=len(dec), logp_scale=round(float(old.abs().mean()), 1), max_abs_diff_batch=float((new_all - old).abs().max()), max_ratio_minus_1_batch=float(((new_all - old).exp() - 1).abs().max()), max_abs_diff_single=float((new_one - old[:8]).abs().max()), max_ratio_minus_1_single=float(((new_one - old[:8]).exp() - 1).abs().max())) print("likelihood:", report["likelihood"], flush=True)
# 4. one PPO step: which weights change. for d in dec: d["adv"], d["ret"] = float(np.random.randn()), float(np.random.rand()) opt = torch.optim.AdamW([dict(params=pol.policy_params(), lr=3e-6), dict(params=list(pol.critic.parameters()), lr=3e-4)]) ns = argparse.Namespace(epochs=1, minibatch=8, clip=0.2, vf_coef=0.5, max_grad_norm=1.0, target_kl=1e9) upd = ppo_update(pol, opt, dec, ns, policy_on=True) changed = [n for n, p in pol.model.named_parameters() if digest(p) != base_digests[n]] groups = {} for n in changed: g = n.split(".")[0] if not n.startswith("vlm_with_expert.") else ".".join(n.split(".")[:2]) groups[g] = groups.get(g, 0) + 1 trained = set(pol.trained_names) with torch.no_grad(): after, _ = pol.evaluate(None, chain, prefix=pol.stack_prefix([d["prefix"] for d in dec])) report["update"] = dict(step=upd, changed_tensors=len(changed), trained_tensors=len(trained), changed_outside_trained=[n for n in changed if n not in trained][:10], trained_unchanged=len(trained - set(changed)), changed_groups=groups, backbone_identical=not any(n.startswith("vlm_with_expert.vlm.") for n in changed), state_proj_identical=not any(n.startswith("state_proj.") for n in changed), logp_change_after_step=float((after - new_all).abs().mean())) print("update:", report["update"], flush=True)
# 5. save, reload (as eval_policy --expert-fp32 loads it), same chunk. with tempfile.TemporaryDirectory() as tmp: pol.save(tmp) from safetensors.torch import load_file
from eval_policy import load_policy norm_same = all( all(torch.equal(a[k], b[k]) for k in a) for f in Path(args.policy).glob("policy_*processor*.safetensors") for a, b in [(load_file(str(f)), load_file(str(Path(tmp) / f.name)))]) loaded, _, _, _ = load_policy(tmp, expert_fp32=True) mine = dict(pol.model.named_parameters()) weights_same = all(torch.equal(p.detach(), mine[n].detach()) for n, p in loaded.model.named_parameters() if n.startswith("vlm_with_expert.lm_expert.")) del loaded re = FlowRL(tmp, instr, *schedules[0], expert_fp32=True) with torch.no_grad(): obs = [d for d in dec[:4]] x0 = pol.x0(4) p1 = pol.stack_prefix([d["prefix"] for d in obs]) c1 = pol.evaluate(None, chain[:4], prefix=p1)[0] c2 = re.evaluate(None, chain[:4], prefix=re.stack_prefix([d["prefix"] for d in obs]))[0] report["reload"] = dict(normalization_identical=bool(norm_same), expert_weights_identical=bool(weights_same), max_logp_diff=float((c1 - c2).abs().max()), files=sorted(p.name for p in Path(tmp).iterdir())) print("reload:", report["reload"], flush=True)
(out / "rl_check.json").write_text(json.dumps(report, indent=1, default=str)) lines = ["# RL checks", "", f"Policy `{args.policy}`.", "", f"1. Same as eval_policy ({args.same_episodes} scenes, seed {args.seed}, noise off, one scene at a time):", f" - eval_policy --fast vs normal: {report['fast_vs_normal']['identical']}", f" - RL path, expert bfloat16 vs eval_policy: {report['rl_bf16_vs_eval']['identical']} " f"{'' if report['rl_bf16_vs_eval']['identical'] else report['rl_bf16_vs_eval']['differences'][:3]}", f" - RL path, expert float32 vs eval_policy --expert-fp32: {report['rl_fp32_vs_eval_fp32']['identical']} " f"{'' if report['rl_fp32_vs_eval_fp32']['identical'] else report['rl_fp32_vs_eval_fp32']['differences'][:3]}", f" - eval_policy, expert float32 vs bfloat16: successes {report['eval_fp32_vs_bf16']['success']}", f"2. Noise schedules ({args.noise_episodes} scenes, seed {args.noise_seed}): success / clean lift / closing error median:", ] + [f" - {k}: {v['success']:.1%} / {v['clean_lift']:.1%} / {v['close_mm_median']} mm" for k, v in report["noise"].items()] + [ f"3. Likelihood ({report['likelihood']['schedule']}), {report['likelihood']['decisions']} stored chains: max |ratio - 1| " f"{report['likelihood']['max_ratio_minus_1_batch']:.2e} (one minibatch), " f"{report['likelihood']['max_ratio_minus_1_single']:.2e} (one at a time); log-prob scale {report['likelihood']['logp_scale']}.", f"4. One PPO step (lr 3e-6): {report['update']['changed_tensors']} tensors changed of {report['update']['trained_tensors']} " f"trained; outside the trained set: {report['update']['changed_outside_trained'] or 'none'}; backbone identical " f"{report['update']['backbone_identical']}; state_proj identical {report['update']['state_proj_identical']}; " f"mean log-prob change {report['update']['logp_change_after_step']:.3g}; KL {report['update']['step'].get('kl')}.", f"5. Save/reload: normalization identical {report['reload']['normalization_identical']}; expert weights identical " f"after eval_policy's float32 load {report['reload']['expert_weights_identical']}; max log-prob difference " f"{report['reload']['max_logp_diff']:.2e}."] (out / "rl_check.md").write_text("\n".join(lines) + "\n") print("\n".join(lines))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230"""The chess simulator as an RL environment for a chunked policy (SmolVLA): one step = one chunk.
Scenes, rendering and the success judgement are those of eval_policy.py: episode (seed, i) is thesame scene, move, camera look and policy noise seed as `eval_policy.py --seed seed`, episode i.Only the frames the policy sees are rendered (the first frame of each chunk); the images do notdepend on the skipped renders in the baseline profile (no camera noise).
Reward (per chunk, summed over its frames): +1.0 the move is complete when the episode ends (eval_policy's success: the piece within 6 mm of the target square, upright, no other piece moved more than 2 mm) +0.2 once, when the marked piece is first lifted cleanly (more than 8 mm, tilted under 20 deg) -0.5 another piece moved more than 2 mm (the move can no longer succeed; the episode ends) -0.3 the marked piece toppled (tilt over 45 deg; the episode ends)Episodes also end as in eval_policy (the move done and the arm back near rest) or at the timelimit. With `early_stop=False` only eval_policy's endings apply, so an episode runs exactly aseval_policy.py runs it.
VecChessEnv runs several environments in worker processes (rendering with EGL there); the policystays in the main process and samples one batch per chunk boundary."""from __future__ import annotations
import multiprocessing as mpimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))
LIFT_M = 0.008 # as eval_policy.LIFT_MCLEAN_LIFT_TILT = 20.0TOPPLED_TILT = 45.0REWARD = dict(success=1.0, clean_lift=0.2, disturbed=-0.5, toppled=-0.3)
class ChessEnv: def __init__(self, cfg: dict, seconds: float = 20.0, per_set: int = 5): import numpy as np
from episode import EpisodeRunner from lerobot_export import video_settings from piece_sets import sample_piece_set
assert cfg["piece_sets"].get("fixed"), "one runner per worker assumes a fixed piece set (baseline profile)" self.cfg, self.per_set = cfg, per_set self.crf, self.pix_fmt = video_settings(cfg) self.fps = cfg["dataset"]["fps"] self.max_frames = int(seconds * self.fps) self.runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng(0), cfg, "rl"), render=True) self.site = self.runner.m.site("gripperframe").id self.home = np.array(cfg["expert"]["home"])
# ------------------------------------------------------------------ episode def reset(self, seed: int, index: int, check_expert: bool = True, early_stop: bool = True, measure: bool = True) -> tuple[dict, dict]: """Episode `index` of `seed`, as eval_policy.py builds it. Returns (observation, info); info["torch_seed"] is eval_policy's per-episode seed for the policy's sampling noise. `check_expert=False` skips eval_policy's check that the teacher can do the move (every move of the baseline profile is doable, so the same first episode seed is kept). `measure=False` skips planning the teacher's grasp, which only serves the closing-error measurement.""" import mujoco import numpy as np
from lerobot_export import Recorder
r = self.runner erng = np.random.default_rng([seed, index]) for _ in range(20 if check_expert else 1): ep_seed = int(erng.integers(2**62)) task = r.setup(np.random.default_rng(ep_seed)) if not check_expert or r.run(task, ep_seed).success: break task = r.setup(np.random.default_rng(ep_seed)) d, w, ex = r.d, r.w, r.expert # The teacher's planned grasp (not executed), as eval_policy measures the closing error against it. saved = (d.qpos.copy(), d.qvel.copy(), d.act.copy(), d.ctrl.copy(), d.time) self.plan = None if measure: try: self.plan = ex.plan_pick(d, task.target, np.random.default_rng(ep_seed)) except Exception: self.plan = None d.qpos[:], d.qvel[:], d.act[:], d.ctrl[:] = saved[:4] d.time = saved[4] mujoco.mj_forward(r.m, d) self.task, self.early_stop = task, early_stop self.rec = Recorder(self.cfg, None) self.rec.begin(r, task, np.random.default_rng(ep_seed ^ 0x5EED)) self.start = {p: w.base_pos(d, p) for p in w.pieces} self.watched = [p for p in task.squares.values() if p != task.target] self.src = w.square_center(task.source) self.f, self.placed_at, self.done = 0, None, False self.lifted, self.clean_lift, self.closest = False, False, np.inf self.close = None self.open_max = 0.0 torch_seed = int(erng.integers(2**31)) info = dict(seed=seed, index=index, ep_seed=ep_seed, torch_seed=torch_seed, piece=w.kind[task.target], source=task.source, destination=task.dest.square or "bin") return self.observe(), info
def observe(self) -> dict: from camera_effects import training_look
r = self.runner over, wrist = (training_look(self.rec.observe(r, c), self.crf, self.pix_fmt) for c in ("overhead", "wrist")) return {"observation.images.overhead": over, "observation.images.wrist": wrist, "observation.state": r.to_lerobot(r.d.qpos[r.qadr])}
def step(self, chunk) -> tuple[dict | None, float, bool, dict]: """Execute an action chunk (n x 6, LeRobot units) frame by frame, as eval_policy's drive() does, until it ends or the episode does.""" import mujoco import numpy as np
from eval_policy import CLOSING, OPEN
r, task = self.runner, self.task d, w = r.d, r.w lo, hi = r.grip_range reward, events = 0.0, [] for a in np.asarray(chunk, dtype=np.float32): # float32 like eval_policy's actions: radians rounded the same way f = self.f d.ctrl[:5] = np.radians(a[:5]) d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo) for _ in range(r.n_sub): mujoco.mj_step(r.m, d) self.f += 1 g = d.site_xpos[self.site] self.closest = min(self.closest, float(np.linalg.norm(g[:2] - self.src[:2]))) rise = w.base_pos(d, task.target)[2] - self.start[task.target][2] tilt = w.tilt_deg(d, task.target) self.lifted |= bool(rise > LIFT_M) if not self.clean_lift and rise > LIFT_M and tilt < CLEAN_LIFT_TILT: self.clean_lift = True reward += REWARD["clean_lift"] events.append("clean_lift") if self.plan is not None and self.close is None: # eval_policy's closing measurement self.open_max = max(self.open_max, float(a[5])) if self.open_max > OPEN and a[5] < CLOSING: pnt, _ = r.expert.kin.pose(d.qpos[r.expert.kin.qadr].copy(), self.plan.offset) self.close = round(1000 * float(np.linalg.norm((pnt - self.plan.grasp_point)[:2])), 1) end = None if self.early_stop: moved = max((float(np.linalg.norm(w.base_pos(d, p) - self.start[p])) for p in self.watched), default=0.0) if moved * 1000 > self.cfg["validation"]["disturb_mm"]: reward += REWARD["disturbed"] end = "disturbed" elif tilt > TOPPLED_TILT: reward += REWARD["toppled"] end = "toppled" if end is None and f % 15 == 0 and f > 60: # eval_policy: done once placed and back near rest res = r._judge(task, self.start, self.watched, {}, self.f, 0.0) near_home = np.abs(d.qpos[r.expert.kin.qadr] - self.home).max() < 0.35 if res.success and self.placed_at is None: self.placed_at = f if self.placed_at is not None and near_home: end = "done" if end is None and self.f >= self.max_frames: end = "time" if end is not None: events.append(end) self.done = True break info = dict(events=events) if self.done: res = r._judge(task, self.start, self.watched, {}, self.f, 0.0) if res.success: reward += REWARD["success"] info.update(success=bool(res.success), reason=res.reason, frames=self.f, lifted=self.lifted, clean_lift=self.clean_lift, disturbed=bool(res.disturbed), closest_mm=round(1000 * self.closest, 1), close_lateral_mm=self.close, end=events[-1]) return None, reward, True, info return self.observe(), reward, False, info
# ---------------------------------------------------------------------- worker processesdef _worker(conn, cfg, seconds): import warnings
warnings.filterwarnings("ignore") env = ChessEnv(cfg, seconds) while True: cmd, arg = conn.recv() if cmd == "reset": conn.send(env.reset(**arg)) elif cmd == "step": conn.send(env.step(arg)) elif cmd == "close": env.runner.close() conn.close() return
class VecChessEnv: """n ChessEnv in worker processes. reset(i, ...) and step(i, chunk) are sent to worker i; step_many sends chunks to several workers and collects their results."""
def __init__(self, n: int, cfg: dict, seconds: float = 20.0): ctx = mp.get_context("spawn") self.conns, self.procs = [], [] for _ in range(n): a, b = ctx.Pipe() p = ctx.Process(target=_worker, args=(b, cfg, seconds), daemon=True) p.start() self.conns.append(a) self.procs.append(p) self.n = n
def reset_many(self, jobs: dict) -> dict: """jobs: {worker: dict(seed=, index=, check_expert=, early_stop=)} -> {worker: (obs, info)}""" for i, arg in jobs.items(): self.conns[i].send(("reset", arg)) return {i: self.conns[i].recv() for i in jobs}
def step_many(self, chunks: dict) -> dict: """chunks: {worker: chunk} -> {worker: (obs or None, reward, done, info)}""" for i, c in chunks.items(): self.conns[i].send(("step", c)) return {i: self.conns[i].recv() for i in chunks}
def close(self): for c in self.conns: try: c.send(("close", None)) except (BrokenPipeError, OSError): pass for p in self.procs: p.join(timeout=10) if p.is_alive(): p.terminate()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""SmolVLA as a stochastic policy for RL (ReinFlow-style noise injection), plus a critic.
SmolVLA turns Gaussian noise x_0 into a 50-step action chunk with 10 Euler steps of a learnedvelocity field (VLAFlowMatching.sample_actions). Here each step adds Gaussian noise of a learnedper-step, per-joint size to the six real action dimensions:
x_{k+1} = x_k + dt * v(x_k, t_k) + sigma_k * eps_k
so the probability of the chain x_1 ... x_10 given x_0 is a product of Gaussians that can becomputed and differentiated (ReinFlow). With the noise off this is exactly SmolVLA's sampling.
Trained: the action expert (`vlm_with_expert.lm_expert`) and the action and time projections(`action_in_proj`, `action_out_proj`, `action_time_mlp_in`, `action_time_mlp_out`), and a critic (anMLP on the frozen backbone's pooled prefix output and the normalized state); optionally the noisesizes. Frozen: the vision-language backbone and `state_proj`, which feeds it, so the prefix (images,instruction, state) is computed without gradients. The noise and the critic are only for training;`save()` writes a plain SmolVLA checkpoint with the baseline's own processors (normalization).
Numerics (sim/reports/rl/check): the backbone runs in bfloat16 and gives batch-size-dependentresults, and small noise sizes turn tiny differences in the mean into large log-probabilitydifferences. So the prefix (KV cache, pad mask, pooled features, state) of every decision is keptfrom sampling time and reused in the update (`split_prefix` / `stack_prefix`), and the actionexpert runs in float32 (`expert_fp32`, also needed for small updates to register at all). Thenoise size falls geometrically from `sigma_start` (first denoising step, where the flow turns itinto a coherent change of the whole chunk) to `sigma_end` (last step, which adds it directly tothe joint targets as frame-to-frame jitter)."""from __future__ import annotations
import mathimport shutilimport sysfrom pathlib import Path
import torchfrom torch import nn
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))
TRAINED = ("vlm_with_expert.lm_expert.", "action_in_proj.", "action_out_proj.", "action_time_mlp_in.", "action_time_mlp_out.")
def gauss_logp(x: torch.Tensor, mean: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor: """Log density of each element of x under N(mean, sigma^2): (B, T, A) -> (B, T, A). Kept per element: PPO clips each element's ratio (as per-token ratios in language-model PPO); the sum over the 300 values of a step is far too sharp with the small noise of the last denoising steps.""" z = (x - mean) / sigma return -0.5 * z * z - torch.log(sigma) - 0.5 * math.log(2 * math.pi)
class Critic(nn.Module): def __init__(self, feat_dim: int, state_dim: int, hidden: int = 256): super().__init__() self.net = nn.Sequential(nn.Linear(feat_dim + state_dim, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(), nn.Linear(hidden, 1))
def forward(self, feat, state): return self.net(torch.cat([feat, state], dim=-1)).squeeze(-1)
class FlowRL(nn.Module): def __init__(self, path: str, instruction: str, sigma_start=0.1, sigma_end=0.002, learn_sigma=False, expert_fp32=True): super().__init__() from eval_policy import load_policy
policy, pre, post, device = load_policy(path, expert_fp32=expert_fp32) self.policy, self.pre, self.post, self.device = policy, pre, post, device self.src_path = Path(path) self.model = policy.model cfg = policy.config self.n_steps, self.chunk, self.adim = cfg.num_steps, cfg.chunk_size, cfg.action_feature.shape[0] self.max_adim = cfg.max_action_dim self.instruction = instruction for p in policy.parameters(): p.requires_grad_(False) self.trained_names = [] for name, p in self.model.named_parameters(): if name.startswith(TRAINED): p.requires_grad_(True) self.trained_names.append(name) frac = torch.linspace(0.0, 1.0, self.n_steps, device=device)[:, None] init = math.log(sigma_start) + frac * (math.log(sigma_end) - math.log(sigma_start)) self.log_sigma = nn.Parameter(init.expand(self.n_steps, self.adim).clone(), requires_grad=learn_sigma) self.sigma_min, self.sigma_max = 0.5 * min(sigma_start, sigma_end), 1.5 * max(sigma_start, sigma_end) hidden = self.model.vlm_with_expert.config.text_config.hidden_size self.critic = Critic(hidden, self.adim).to(device) policy.eval()
# ------------------------------------------------------------------ inputs def sigma(self) -> torch.Tensor: return self.log_sigma.exp().clamp(self.sigma_min, self.sigma_max)
def policy_params(self): return [p for n, p in self.model.named_parameters() if p.requires_grad]
def batch(self, obs_list: list[dict]) -> dict: """Observations (numpy, as eval_policy builds them) through the policy's own preprocessor, stacked.""" from lerobot.policies.utils import prepare_observation_for_inference
items = [] with torch.no_grad(): for o in obs_list: ob = prepare_observation_for_inference(dict(o), self.device, self.instruction, "so101_follower") items.append(self.pre(ob)) return {k: torch.cat([it[k] for it in items]) for k, v in items[0].items() if torch.is_tensor(v)}
@torch.no_grad() def prefix(self, batch: dict): """Images, instruction and state through the frozen backbone: (pad masks, KV cache, pooled features, normalized state).""" from lerobot.policies.smolvla.modeling_smolvla import make_att_2d_masks from lerobot.utils.constants import OBS_LANGUAGE_ATTENTION_MASK, OBS_LANGUAGE_TOKENS
images, img_masks = self.policy.prepare_images(batch) state = self.policy.prepare_state(batch) embs, pad, att = self.model.embed_prefix(images, img_masks, batch[OBS_LANGUAGE_TOKENS], batch[OBS_LANGUAGE_ATTENTION_MASK], state=state) att2d = make_att_2d_masks(pad, att) pos = torch.cumsum(pad, dim=1) - 1 outs, kv = self.model.vlm_with_expert.forward(attention_mask=att2d, position_ids=pos, past_key_values=None, inputs_embeds=[embs, None], use_cache=self.policy.config.use_cache, fill_kv_cache=True) h, m = outs[0].float(), pad.unsqueeze(-1).float() feat = (h * m).sum(1) / m.sum(1).clamp(min=1.0) return pad, kv, feat, state[:, :self.adim].float()
def _times(self, bsize: int): dt = -1.0 / self.n_steps return dt, [torch.tensor(1.0 + k * dt, dtype=torch.float32, device=self.device).expand(bsize) for k in range(self.n_steps)]
# ------------------------------------------------------------------ sampling and likelihood @torch.no_grad() def sample(self, batch: dict, x0: torch.Tensor, noise: bool = True): """The chain x_0..x_n (B, n+1, T, max_adim), its log-probabilities per element (B, n, T, A), the critic's value (B,) and the prefix (pad, kv, feat, state) for the update. With noise=False, x_n is SmolVLA's own action chunk for this x_0.""" prefix = self.prefix(batch) pad, kv, feat, state = prefix bsize = x0.shape[0] dt, times = self._times(bsize) sig = self.sigma() x, chain = x0, [x0] logp = x0.new_zeros(bsize, self.n_steps, self.chunk, self.adim) for k in range(self.n_steps): v = self.model.denoise_step(pad, kv, x, times[k]) mean = x + dt * v if noise: nxt = mean.clone() eps = torch.randn(bsize, self.chunk, self.adim, device=self.device) nxt[..., :self.adim] = mean[..., :self.adim] + sig[k] * eps logp[:, k] = gauss_logp(nxt[..., :self.adim], mean[..., :self.adim], sig[k]) else: nxt = mean x = nxt chain.append(x) return torch.stack(chain, 1), logp, self.critic(feat, state), prefix
@staticmethod def split_prefix(prefix, j: int): """Decision j's prefix, on the CPU.""" pad, kv, feat, state = prefix return (pad[j:j + 1].cpu(), {l: {k: t[j:j + 1].cpu() for k, t in d.items()} for l, d in kv.items()}, feat[j:j + 1].cpu(), state[j:j + 1].cpu())
def stack_prefix(self, items): """Stored prefixes of several decisions as one batch on the device.""" dev = self.device kv = {l: {k: torch.cat([it[1][l][k] for it in items]).to(dev) for k in items[0][1][l]} for l in items[0][1]} return (torch.cat([it[0] for it in items]).to(dev), kv, torch.cat([it[2] for it in items]).to(dev), torch.cat([it[3] for it in items]).to(dev))
def evaluate(self, batch: dict | None, chain: torch.Tensor, prefix=None): """Per-element log-probabilities (B, n, T, A) of a stored chain under the current weights (with gradients through the action expert and the noise sizes) and the critic's value (B,). Pass the stored `prefix` (stack_prefix) to reuse sampling time's; else it is recomputed.""" pad, kv, feat, state = prefix if prefix is not None else self.prefix(batch) bsize = chain.shape[0] dt, times = self._times(bsize) sig = self.sigma() logp = [] for k in range(self.n_steps): v = self.model.denoise_step(pad, kv, chain[:, k], times[k]) mean = chain[:, k] + dt * v logp.append(gauss_logp(chain[:, k + 1, ..., :self.adim], mean[..., :self.adim], sig[k])) return torch.stack(logp, 1), self.critic(feat, state)
@torch.no_grad() def actions(self, chain: torch.Tensor): """The executed chunk in LeRobot units (B, T, 6): the last chain step through the policy's own postprocessor (unnormalization), as eval_policy applies it to every action.""" x = chain[:, -1, :, :self.adim] bsize = x.shape[0] a = self.post(x.reshape(bsize * self.chunk, self.adim)) return a.reshape(bsize, self.chunk, self.adim).float().cpu().numpy()
def x0(self, bsize: int, generators=None) -> torch.Tensor: """Initial noise as SmolVLA draws it (sample_noise); with per-episode CUDA generators seeded like eval_policy's torch.manual_seed, the same draws as eval_policy.py.""" shape = (self.chunk, self.max_adim) if generators is None: return torch.normal(mean=0.0, std=1.0, size=(bsize, *shape), dtype=torch.float32, device=self.device) return torch.cat([torch.normal(mean=0.0, std=1.0, size=(1, *shape), dtype=torch.float32, device=self.device, generator=g) for g in generators])
# ------------------------------------------------------------------ checkpoint def save(self, out: str | Path, extra: dict | None = None): """A plain SmolVLA checkpoint (config + weights) with the baseline's processor files, and the training-only parts (noise sizes, critic) in rl_state.pt.""" out = Path(out) out.mkdir(parents=True, exist_ok=True) self.policy.save_pretrained(out) for f in self.src_path.glob("policy_*processor*"): shutil.copy2(f, out / f.name) torch.save(dict(log_sigma=self.log_sigma.detach().cpu(), critic=self.critic.state_dict(), **(extra or {})), out / "rl_state.pt")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278"""RL fine-tuning of SmolVLA in the chess simulator (PPO over action chunks, ReinFlow-style noise).
One decision = one 50-step action chunk (sim/rl_env.py). Each iteration collects --episodesepisodes from --envs simulators in parallel on training scenes (--train-seed, episodes never usedby any test), computes advantages over the chunks of each episode (GAE), then updates the actionexpert and the critic (sim/rl_policy.py; the noise sizes too with --learn-sigma) with PPO. Everyelement of the denoising chain (step x timestep x joint) has its own clipped likelihood ratio, astokens do in language-model PPO: with the small noise of the last denoising steps, the probabilityof a whole step (300 values) changes by hundreds of nats after a single small update(sim/reports/rl/check). The first --critic-warmup iterations train only the critic.
Every --val-every iterations (and before the first update) the policy runs without noise on afixed set of validation scenes (--val-seed): the learning curve on scenes the updates never saw.Checkpoints: <out>/iter_XXXX, <out>/last and <out>/best (best validation success; a later iterationwins ties). log.jsonl has one line per iteration.
Run (pod): MUJOCO_GL=egl PHASE2_PROFILE=baseline SIM_OFFSAMPLES=0 .venv/bin/python sim/rl_train.py \ --policy models/baseline --out outputs/rl_pilot --iterations 30"""from __future__ import annotations
import argparseimport jsonimport sysimport timefrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))
def run_episodes(pol, venv, seed: int, indices: list[int], noise: bool, early_stop: bool, check_expert: bool, record: bool, eval_noise_seeds: bool = False, measure: bool = True): """Run episodes (seed, index) on the vector env with the current policy. Returns the finished episodes: dict(info, decisions=[...], ret, ...). Each decision keeps what PPO needs when record.""" import numpy as np import torch
todo = list(indices) active, episodes = {}, [] free = list(range(venv.n)) timing = run_episodes.timing = dict(prep=0.0, sample=0.0, env=0.0, reset=0.0, rounds=0)
def start(workers): jobs = {} for w in workers: if todo: jobs[w] = dict(seed=seed, index=todo.pop(0), check_expert=check_expert, early_stop=early_stop, measure=measure) for w, (obs, info) in venv.reset_many(jobs).items(): gen = None if eval_noise_seeds: # the same x_0 draws as eval_policy.py gen = torch.Generator(device=pol.device) gen.manual_seed(info["torch_seed"]) active[w] = dict(obs=obs, info=info, decisions=[], ret=0.0, gen=gen) return [w for w in workers if w not in jobs]
t = time.time() free = start(free) timing["reset"] += time.time() - t while active: ws = sorted(active) t0 = time.time() batch = pol.batch([active[w]["obs"] for w in ws]) gens = [active[w]["gen"] for w in ws] if eval_noise_seeds else None x0 = pol.x0(len(ws), gens) t1 = time.time() chain, logp, value, prefix = pol.sample(batch, x0, noise=noise) acts = pol.actions(chain) t2 = time.time() results = venv.step_many({w: acts[j] for j, w in enumerate(ws)}) t3 = time.time() timing["prep"] += t1 - t0 timing["sample"] += t2 - t1 timing["env"] += t3 - t2 timing["rounds"] += 1 for j, w in enumerate(ws): nxt, rew, done, info = results[w] ep = active[w] if record: ep["decisions"].append(dict(prefix=pol.split_prefix(prefix, j), chain=chain[j].cpu(), logp=logp[j].cpu(), value=float(value[j]), reward=float(rew))) ep["ret"] += float(rew) if done: ep["result"] = info ep.pop("obs") ep.pop("gen") episodes.append(ep) del active[w] free.append(w) else: ep["obs"] = nxt t = time.time() free = start(free) timing["reset"] += time.time() - t return episodes
def gae(episodes, gamma: float, lam: float): for ep in episodes: adv, nxt_v = 0.0, 0.0 # every episode ends (success, failure or time limit) for d in reversed(ep["decisions"]): delta = d["reward"] + gamma * nxt_v - d["value"] adv = delta + gamma * lam * adv d["adv"], d["ret"] = adv, adv + d["value"] nxt_v = d["value"]
def summarize(episodes, prefix=""): import numpy as np
n = len(episodes) r = [e["result"] for e in episodes] out = {f"{prefix}episodes": n, f"{prefix}success": round(sum(x["success"] for x in r) / max(n, 1), 4), f"{prefix}return": round(float(np.mean([e["ret"] for e in episodes])), 4) if n else None, f"{prefix}clean_lift": round(sum(x["clean_lift"] for x in r) / max(n, 1), 4), f"{prefix}disturbed": round(sum(x["end"] == "disturbed" for x in r) / max(n, 1), 4), f"{prefix}toppled": round(sum(x["end"] == "toppled" for x in r) / max(n, 1), 4)} for kind in ("pawn", "knight"): k = [e for e in episodes if e["info"]["piece"] == kind] out[f"{prefix}success_{kind}"] = round(sum(e["result"]["success"] for e in k) / max(len(k), 1), 4) close = [x["close_lateral_mm"] for x in r if x.get("close_lateral_mm") is not None] out[f"{prefix}close_mm_median"] = round(float(np.median(close)), 2) if close else None return out
def ppo_update(pol, opt, decisions, args, policy_on: bool): import numpy as np import torch
adv = torch.tensor([d["adv"] for d in decisions], dtype=torch.float32) adv = (adv - adv.mean()) / (adv.std() + 1e-8) ret = torch.tensor([d["ret"] for d in decisions], dtype=torch.float32) old = torch.stack([d["logp"] for d in decisions]) # (N, n_steps, T, A) stats = dict(kl=[], clipfrac=[], pg_loss=[], v_loss=[], grad_norm=[]) trained = [p for p in pol.parameters() if p.requires_grad] stop = False for epoch in range(args.epochs): perm = np.random.permutation(len(decisions)) for s in range(0, len(perm), args.minibatch): idx = perm[s:s + args.minibatch] prefix = pol.stack_prefix([decisions[i]["prefix"] for i in idx]) # as at sampling time chain = torch.stack([decisions[i]["chain"] for i in idx]).to(pol.device) logp, value = pol.evaluate(None, chain, prefix=prefix) a = adv[idx].to(pol.device)[:, None, None, None] log_ratio = (logp - old[idx].to(pol.device)).clamp(-20, 20) ratio = log_ratio.exp() pg = -torch.min(ratio * a, ratio.clamp(1 - args.clip, 1 + args.clip) * a).mean() v_loss = 0.5 * ((value - ret[idx].to(pol.device)) ** 2).mean() loss = (pg if policy_on else 0.0 * pg) + args.vf_coef * v_loss opt.zero_grad(set_to_none=True) loss.backward() gn = torch.nn.utils.clip_grad_norm_(trained, args.max_grad_norm) if not policy_on: # critic warm-up: leave the policy and noise untouched for p in pol.policy_params() + [pol.log_sigma]: p.grad = None opt.step() with torch.no_grad(): kl = ((ratio - 1) - log_ratio).mean().item() stats["kl"].append(kl) stats["clipfrac"].append(((ratio - 1).abs() > args.clip).float().mean().item()) stats["pg_loss"].append(pg.item()) stats["v_loss"].append(v_loss.item()) stats["grad_norm"].append(float(gn)) if policy_on and np.mean(stats["kl"][-max(1, len(perm) // args.minibatch):]) > args.target_kl: stop = True break out = {k: round(float(np.mean(v)), 5) for k, v in stats.items() if v} out["epochs_done"] = epoch + 1 out["kl_stop"] = stop return out
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--policy", required=True) ap.add_argument("--out", required=True) ap.add_argument("--iterations", type=int, default=30) ap.add_argument("--envs", type=int, default=10) ap.add_argument("--episodes", type=int, default=100, help="episodes per iteration") ap.add_argument("--train-seed", type=int, default=7_700_003) ap.add_argument("--val-seed", type=int, default=9_300_003) ap.add_argument("--val-episodes", type=int, default=60) ap.add_argument("--val-every", type=int, default=5) ap.add_argument("--save-every", type=int, default=5) ap.add_argument("--seconds", type=float, default=20.0) ap.add_argument("--lr", type=float, default=3e-7) ap.add_argument("--sigma-lr", type=float, default=3e-3) ap.add_argument("--critic-lr", type=float, default=3e-4) ap.add_argument("--sigma-start", type=float, default=0.2, help="noise size at the first denoising step") ap.add_argument("--sigma-end", type=float, default=0.002, help="noise size at the last denoising step") ap.add_argument("--learn-sigma", action="store_true", help="train the noise sizes too (default: fixed schedule)") ap.add_argument("--expert-bf16", action="store_true", help="keep the action expert in bfloat16 (default float32)") ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--lam", type=float, default=0.95) ap.add_argument("--clip", type=float, default=0.2) ap.add_argument("--epochs", type=int, default=2) ap.add_argument("--minibatch", type=int, default=16) ap.add_argument("--target-kl", type=float, default=0.02, help="per-element approximate KL") ap.add_argument("--vf-coef", type=float, default=0.5) ap.add_argument("--max-grad-norm", type=float, default=1.0) ap.add_argument("--critic-warmup", type=int, default=1) ap.add_argument("--torch-threads", type=int, default=2, help="CPU threads of this process; its idle thread pool otherwise spins and starves the simulators") args = ap.parse_args()
import numpy as np import torch
torch.set_num_threads(args.torch_threads)
from episode import load_config from rl_env import REWARD, VecChessEnv from rl_policy import FlowRL
out = Path(args.out) out.mkdir(parents=True, exist_ok=True) (out / "args.json").write_text(json.dumps(dict(vars(args), reward=REWARD), indent=1)) cfg = load_config() torch.manual_seed(0) np.random.seed(0) pol = FlowRL(args.policy, cfg["dataset"]["instruction"], args.sigma_start, args.sigma_end, learn_sigma=args.learn_sigma, expert_fp32=not args.expert_bf16) groups = [dict(params=pol.policy_params(), lr=args.lr), dict(params=list(pol.critic.parameters()), lr=args.critic_lr)] if args.learn_sigma: groups.append(dict(params=[pol.log_sigma], lr=args.sigma_lr)) opt = torch.optim.AdamW(groups, weight_decay=0.0) venv = VecChessEnv(args.envs, cfg, args.seconds) log = (out / "log.jsonl").open("a") val_indices = list(range(args.val_episodes)) best = -1.0
def validate(it): nonlocal best t0 = time.time() eps = run_episodes(pol, venv, args.val_seed, val_indices, noise=False, early_stop=False, check_expert=False, record=False) s = summarize(eps, "val_") s["val_seconds"] = round(time.time() - t0, 1) if s["val_success"] >= best and it > 0: best = s["val_success"] pol.save(out / "best", dict(iteration=it, val=s)) return s
try: row = dict(iteration=0, **validate(0)) print(json.dumps(row), flush=True) log.write(json.dumps(row) + "\n") log.flush() next_index = 0 for it in range(1, args.iterations + 1): t0 = time.time() idx = list(range(next_index, next_index + args.episodes)) next_index += args.episodes eps = run_episodes(pol, venv, args.train_seed, idx, noise=True, early_stop=True, check_expert=False, record=True, measure=False) t_roll = time.time() - t0 timing = {k: round(v, 1) for k, v in run_episodes.timing.items()} gae(eps, args.gamma, args.lam) decisions = [d for e in eps for d in e["decisions"]] upd = ppo_update(pol, opt, decisions, args, policy_on=it > args.critic_warmup) row = dict(iteration=it, decisions=len(decisions), rollout_s=round(t_roll, 1), rollout_parts=timing, update_s=round(time.time() - t0 - t_roll, 1), sigma_mean=round(float(pol.sigma().mean()), 5), **summarize(eps, "train_"), **upd) if it % args.val_every == 0 or it == args.iterations: row.update(validate(it)) if it % args.save_every == 0: pol.save(out / f"iter_{it:04d}", dict(iteration=it)) print(json.dumps(row), flush=True) log.write(json.dumps(row) + "\n") log.flush() pol.save(out / "last", dict(iteration=args.iterations)) finally: venv.close()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""Does the policy aim from what it sees? A visual-feedback probe, no training.
The scripted teacher's clean pick is executed until its pinch point is `--heights` mm above thegrasp point, and the state is frozen there. Two observations are made of it: as it is, and withthe target piece moved `--shift-mm` sideways (four directions: along and across the jaws' closingaxis), with the arm unchanged. For each, the policy's 50-step action chunk is predicted withidentical sampling noise, and the pinch point of every predicted action is found by forwardkinematics. The chunk's aim is its lowest pinch point (where the predicted descent ends).
Follow ratio = the aim's shift along the piece's shift, divided by the piece's shift:1 = the aim follows the piece fully (the policy aims from the images), 0 = it ignores the change(it replays a path from the joint state). Noise floor: the aim of the same observation underdifferent sampling noise.
Run: MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/visual_probe.py \ --policy baseline=models/baseline --policy dart300=models/dart300 --out sim/reports/visual_probe"""from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))
DIRECTIONS = ("along+", "along-", "across+", "across-")
def make_probes(args, cfg): """Frozen teacher states at each height, as observations: unshifted and per shift direction.""" import mujoco import numpy as np
from camera_effects import training_look from episode import EpisodeRunner from lerobot_export import Recorder, video_settings from piece_sets import sample_piece_set
crf, pix_fmt = video_settings(cfg) runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9]), cfg, "probe"), render=True) m, d, kin, w = runner.m, runner.d, runner.expert.kin, runner.w heights = sorted((float(h) for h in args.heights.split(",")), reverse=True) shift = args.shift_mm / 1000 probes = []
for i in range(args.scenes): ep_seed = int(np.random.default_rng([args.seed, i]).integers(2**62)) task = runner.setup(np.random.default_rng(ep_seed)) pick = runner.expert.plan_pick(d, task.target, np.random.default_rng(ep_seed)) rec = Recorder(cfg, None) rec.begin(runner, task, np.random.default_rng(ep_seed ^ 0x5EED)) axis = np.array([np.cos(pick.yaw), np.sin(pick.yaw), 0.0]) # jaw closing direction across = np.array([-axis[1], axis[0], 0.0]) vecs = {"along+": axis, "along-": -axis, "across+": across, "across-": -across} a = w.qadr[task.target]
def observe(): return {"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])}
k = 0 for q, g in zip(pick.traj.q, pick.traj.g): d.ctrl[:5], d.ctrl[5] = q, g for _ in range(runner.n_sub): mujoco.mj_step(m, d) above = (kin.pose(d.qpos[kin.qadr], pick.offset)[0][2] - pick.grasp_point[2]) * 1000 if above > heights[k]: continue mujoco.mj_forward(m, d) # render every observation from the same, current kinematics base = observe() shifted = {} saved = d.qpos[a:a + 7].copy() for name, v in vecs.items(): d.qpos[a:a + 2] = saved[:2] + v[:2] * shift mujoco.mj_forward(m, d) shifted[name] = observe() d.qpos[a:a + 7] = saved mujoco.mj_forward(m, d) probes.append(dict(scene=i, height=heights[k], actual_mm=round(float(above), 1), piece=w.kind[task.target], move=f"{task.source}-{task.dest.square}", offset=pick.offset, vecs=vecs, base=base, shifted=shifted)) k += 1 if k == len(heights): break runner.close() return probes, cfg["dataset"]["instruction"], m
def run_policy(path, probes, instruction, noise_seeds, kin, shift): import numpy as np import torch from lerobot.utils.control_utils import predict_action
from eval_policy import load_policy
policy, pre, post, device = load_policy(path)
def aim(obs, seed, offset): policy.reset() torch.manual_seed(seed) chunk = np.array([predict_action(dict(obs), policy, device, pre, post, use_amp=False, task=instruction, robot_type="so101_follower").squeeze().float().cpu().numpy() for _ in range(50)]) pts = np.array([kin.pose(np.radians(c[:5]), offset)[0] for c in chunk]) return pts[int(np.argmin(pts[:, 2]))]
rows = [] for p in probes: ratios, perps, floors = [], [], [] for s in range(noise_seeds): seed = 1000 + s a0 = aim(p["base"], seed, p["offset"]) floors.append(float(np.linalg.norm((aim(p["base"], seed + 500, p["offset"]) - a0)[:2]) * 1000)) for name in DIRECTIONS: v = p["vecs"][name] dv = (aim(p["shifted"][name], seed, p["offset"]) - a0)[:2] ratios.append(float(dv @ v[:2]) / (np.linalg.norm(v[:2]) * shift)) perps.append(float(abs(dv @ np.array([-v[1], v[0]])) * 1000)) rows.append(dict(scene=p["scene"], height=p["height"], piece=p["piece"], move=p["move"], follow=float(np.mean(ratios)), sideways_mm=float(np.mean(perps)), floor_mm=float(np.mean(floors)))) del policy torch.cuda.empty_cache() return rows
def main(): import numpy as np
from episode import load_config
ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--policy", action="append", required=True, help="NAME=path, repeatable") ap.add_argument("--scenes", type=int, default=20) ap.add_argument("--seed", type=int, default=9_200_003, help="probe scenes; not a test set") ap.add_argument("--heights", default="40,20", help="mm above the grasp point") ap.add_argument("--shift-mm", type=float, default=4.0) ap.add_argument("--noise", type=int, default=3, help="sampling-noise seeds per probe") ap.add_argument("--out", required=True) args = ap.parse_args() out = Path(args.out) out.mkdir(parents=True, exist_ok=True) cfg = load_config() probes, instruction, model = make_probes(args, cfg) from kinematics import Kinematics
kin = Kinematics(model) results = {} for spec in args.policy: name, path = spec.split("=", 1) results[name] = run_policy(path, probes, instruction, args.noise, kin, args.shift_mm / 1000) print(name, "done", flush=True)
def med(rows, key): return round(float(np.median([r[key] for r in rows])), 2) if rows else None
heights = sorted({p["height"] for p in probes}, reverse=True) lines = ["# Visual-feedback probe", "", f"{args.scenes} scenes (seed {args.seed}); the teacher's hand frozen at {', '.join(f'{h:g}' for h in heights)} mm " f"above its grasp point; the target moved {args.shift_mm:g} mm along and across the jaw axis (4 directions) " f"with the arm unchanged; {args.noise} sampling-noise seeds per probe.", "", "Follow ratio: how far the predicted aim (lowest pinch point of the 50-step chunk) moves along the piece's " "shift, per mm of shift. 1 = follows the piece fully, 0 = ignores it. Floor: the aim's change from sampling " "noise alone (mm).", "", "| model | height | follow ratio, median (all) | pawns | knights | sideways drift mm | noise floor mm |", "|---|---|---|---|---|---|---|"] for name, rows in results.items(): for h in heights: r = [x for x in rows if x["height"] == h] lines.append(f"| {name} | {h:g} mm | {med(r, 'follow')} | {med([x for x in r if x['piece'] == 'pawn'], 'follow')} | " f"{med([x for x in r if x['piece'] == 'knight'], 'follow')} | {med(r, 'sideways_mm')} | {med(r, 'floor_mm')} |") text = "\n".join(lines) + "\n" (out / "visual_probe.md").write_text(text) (out / "visual_probe.json").write_text(json.dumps(dict(args=vars(args), results=results, probes=[dict(scene=p["scene"], height=p["height"], actual_mm=p["actual_mm"], piece=p["piece"], move=p["move"]) for p in probes]), indent=1)) print(text)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536{ "policy": "models/baseline", "out": "outputs/rl_pilot", "iterations": 24, "envs": 10, "episodes": 100, "train_seed": 7700003, "val_seed": 9300003, "val_episodes": 60, "val_every": 4, "save_every": 4, "seconds": 20.0, "lr": 3e-07, "sigma_lr": 0.003, "critic_lr": 0.0003, "sigma_start": 0.2, "sigma_end": 0.002, "learn_sigma": false, "expert_bf16": false, "gamma": 0.99, "lam": 0.95, "clip": 0.2, "epochs": 2, "minibatch": 8, "target_kl": 0.02, "vf_coef": 0.5, "max_grad_norm": 1.0, "critic_warmup": 1, "torch_threads": 2, "reward": { "success": 1.0, "clean_lift": 0.2, "disturbed": -0.5, "toppled": -0.3 }}12345678{"iteration": 0, "val_episodes": 60, "val_success": 0.2667, "val_return": 0.3467, "val_clean_lift": 0.4, "val_disturbed": 0.0, "val_toppled": 0.0, "val_success_pawn": 0.3243, "val_success_knight": 0.1739, "val_close_mm_median": 6.8, "val_seconds": 161.1}{"iteration": 1, "decisions": 516, "rollout_s": 78.8, "rollout_parts": {"prep": 2.5, "sample": 16.4, "env": 44.8, "reset": 13.2, "rounds": 60}, "update_s": 71.3, "sigma_mean": 0.04964, "train_episodes": 100, "train_success": 0.25, "train_return": 0.074, "train_clean_lift": 0.38, "train_disturbed": 0.27, "train_toppled": 0.39, "train_success_pawn": 0.283, "train_success_knight": 0.2128, "train_close_mm_median": null, "kl": 0.0, "clipfrac": 0.0, "pg_loss": -0.00136, "v_loss": 0.18036, "grad_norm": 0.73244, "epochs_done": 2, "kl_stop": false}{"iteration": 2, "decisions": 512, "rollout_s": 77.2, "rollout_parts": {"prep": 2.4, "sample": 16.1, "env": 43.7, "reset": 13.1, "rounds": 59}, "update_s": 71.2, "sigma_mean": 0.04964, "train_episodes": 100, "train_success": 0.28, "train_return": 0.083, "train_clean_lift": 0.35, "train_disturbed": 0.36, "train_toppled": 0.29, "train_success_pawn": 0.25, "train_success_knight": 0.3333, "train_close_mm_median": null, "kl": 0.0045, "clipfrac": 0.03586, "pg_loss": 0.00227, "v_loss": 0.17382, "grad_norm": 14.73046, "epochs_done": 2, "kl_stop": false}{"iteration": 3, "decisions": 524, "rollout_s": 76.6, "rollout_parts": {"prep": 2.5, "sample": 16.2, "env": 43.6, "reset": 12.5, "rounds": 59}, "update_s": 73.4, "sigma_mean": 0.04964, "train_episodes": 100, "train_success": 0.21, "train_return": 0.001, "train_clean_lift": 0.32, "train_disturbed": 0.36, "train_toppled": 0.31, "train_success_pawn": 0.2373, "train_success_knight": 0.1707, "train_close_mm_median": null, "kl": 0.00418, "clipfrac": 0.03461, "pg_loss": 0.00511, "v_loss": 0.12742, "grad_norm": 14.65937, "epochs_done": 2, "kl_stop": false}{"iteration": 4, "decisions": 499, "rollout_s": 78.6, "rollout_parts": {"prep": 2.2, "sample": 16.2, "env": 44.9, "reset": 13.6, "rounds": 59}, "update_s": 70.1, "sigma_mean": 0.04964, "train_episodes": 100, "train_success": 0.19, "train_return": -0.018, "train_clean_lift": 0.34, "train_disturbed": 0.27, "train_toppled": 0.47, "train_success_pawn": 0.2059, "train_success_knight": 0.1562, "train_close_mm_median": null, "kl": 0.004, "clipfrac": 0.03353, "pg_loss": 0.00309, "v_loss": 0.14007, "grad_norm": 14.34736, "epochs_done": 2, "kl_stop": false, "val_episodes": 60, "val_success": 0.2, "val_return": 0.28, "val_clean_lift": 0.4, "val_disturbed": 0.0, "val_toppled": 0.0, "val_success_pawn": 0.2432, "val_success_knight": 0.1304, "val_close_mm_median": 6.3, "val_seconds": 158.1}{"iteration": 5, "decisions": 511, "rollout_s": 78.8, "rollout_parts": {"prep": 2.3, "sample": 16.4, "env": 45.4, "reset": 12.8, "rounds": 59}, "update_s": 72.2, "sigma_mean": 0.04964, "train_episodes": 100, "train_success": 0.17, "train_return": -0.065, "train_clean_lift": 0.3, "train_disturbed": 0.41, "train_toppled": 0.3, "train_success_pawn": 0.1633, "train_success_knight": 0.1765, "train_close_mm_median": null, "kl": 0.00427, "clipfrac": 0.03482, "pg_loss": 0.00146, "v_loss": 0.13187, "grad_norm": 13.70813, "epochs_done": 2, "kl_stop": false}{"iteration": 6, "decisions": 533, "rollout_s": 78.3, "rollout_parts": {"prep": 2.4, "sample": 16.1, "env": 44.0, "reset": 14.1, "rounds": 58}, "update_s": 75.1, "sigma_mean": 0.04964, "train_episodes": 100, "train_success": 0.19, "train_return": -0.015, "train_clean_lift": 0.33, "train_disturbed": 0.32, "train_toppled": 0.37, "train_success_pawn": 0.2063, "train_success_knight": 0.1622, "train_close_mm_median": null, "kl": 0.00402, "clipfrac": 0.03346, "pg_loss": 0.00186, "v_loss": 0.13325, "grad_norm": 13.68406, "epochs_done": 2, "kl_stop": false}{"iteration": 7, "decisions": 515, "rollout_s": 76.4, "rollout_parts": {"prep": 2.4, "sample": 15.8, "env": 42.8, "reset": 13.8, "rounds": 57}, "update_s": 72.5, "sigma_mean": 0.04964, "train_episodes": 100, "train_success": 0.2, "train_return": 0.015, "train_clean_lift": 0.43, "train_disturbed": 0.32, "train_toppled": 0.37, "train_success_pawn": 0.2963, "train_success_knight": 0.087, "train_close_mm_median": null, "kl": 0.00428, "clipfrac": 0.03451, "pg_loss": 0.00275, "v_loss": 0.13026, "grad_norm": 13.50529, "epochs_done": 2, "kl_stop": false}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798# RL pilot on SmolVLA (ReinFlow-style PPO), 2026-09-24/25: stopped after round 7
**The owner's plan:**1. Load the baseline with its normalization and camera processing.2. Freeze the vision-language backbone.3. Update the action expert and the action-related layers.4. Connect the chess simulator to an RL loop.5. Verify everything before a long run.6. Run a small pilot, then test on held-out scenes.
**Status:** steps 1-5 are done, and the pilot ran 7 of 24 rounds. The owner stopped it at 01:02 UTC,during round 8, and closed the pod. **No held-out test was run.**
## What was built
| File | What it does ||---|---|| `sim/rl_env.py` | The simulator as an RL environment. One step is one 50-frame action chunk; scenes, rendering and success are those of `eval_policy.py`, and only the frames the policy sees are rendered. Rewards: +1 complete move, +0.2 first clean lift, -0.5 a neighbour moved (episode ends), -0.3 the piece toppled (episode ends). || `sim/rl_policy.py` | SmolVLA with Gaussian noise added at each of its 10 denoising steps (ReinFlow), so a chunk's probability is computable. The action expert and the 4 action/time layers are trained; the backbone and `state_proj` are frozen. A critic reads the frozen backbone's pooled features. The checkpoint is saved as a plain SmolVLA with the baseline's processors. || `sim/rl_train.py` | PPO over parallel simulators, with a noise-free validation run every few rounds. || `sim/rl_check.py` | The checks below. || `eval_policy.py` | Two new options. `--fast` renders only the frames the policy uses. `--expert-fp32` loads the action expert in float32; the checkpoint stores it that way, but loading normally rounds it to bfloat16. |
## Checks before training (`check/rl_check.md`)
| Check | Result ||---|---|| RL path vs eval_policy, noise off, same 8 scenes (both precisions), and `--fast` vs normal | identical || Noise schedule (first -> last denoising step), 60 scenes: success / clean lift / closing error | off 30% / 50% / 6.5 mm; **0.2 -> 0.002: 25% / 47% / 5.9 mm** (used); 0.1 -> 0.002: 23%; 0.3 -> 0.003: 25% || Log-probability recomputed from stored chains | max ratio error 0.003 || One update | only the 153 trained tensors change; backbone and `state_proj` bit-identical || Save and reload | identical normalization, weights and log-probabilities |
**Problems these checks caught, fixed before training:**1. **Precision of the joint targets.** Actions were converted to radians in float64 instead of float32, which made 0.1-1.4 mm path differences from eval_policy.2. **Noise size.** A noise of 0.02 at every step dropped success from 20% to 0%: it becomes about 0.7 deg of frame-to-frame jitter at the shoulder. The fix is a schedule, large at the first step (where the flow turns it into a coherent change of the chunk) and small at the last.3. **Backbone numerics.** The backbone runs in bfloat16, and its output depends on the batch size. Recomputed log-probabilities were off by up to 3 nats, so the prefix of every decision is now stored at sampling time and reused.4. **Action expert precision.** The expert loads as bfloat16, where updates at RL learning rates vanish. It now runs in float32.5. **Update size.** The log-probability of a whole denoising step (300 values) is too sharp with the small final noise: one step at lr 3e-6 moved it by about 640. The fix is a clipped ratio per element (as per-token ratios in language-model PPO) and lr 3e-7, which gives a per-element KL of 0.006 per pass.6. **Speed.** An idle PyTorch thread pool spinning on the CPU was starving the simulators; the policy process now runs with 2 threads. Training resets also skip the grasp-measurement planning.7. **GPU memory.** Updates with 16 decisions per batch ran out of memory next to 10 rendering simulators, so the batch was lowered to 8.
## Pilot (`pilot/log.jsonl`)
- **Settings:** from the baseline; 100 training episodes per round on 10 simulators; noise schedule 0.2 -> 0.002 (fixed); lr 3e-7 for the action expert and layers; 2 PPO epochs of minibatch 8; the first round trains only the critic; about 2.5 min per round.- **Validation:** 60 fixed scenes (seed 9300003), no noise, before training and every 4 rounds.
| Round | Training success (noise on) | Pawns | Knights | Clean lift | Neighbour moved | Toppled | Validation success (noise off) ||---|---|---|---|---|---|---|---|| 0 | - | - | - | - | - | - | **26.7%** (pawns 32%, knights 17%; closing error 6.8 mm) || 1 (critic only) | 25% | 28% | 21% | 38% | 27% | 39% | || 2 | 28% | 25% | 33% | 35% | 36% | 29% | || 3 | 21% | 24% | 17% | 32% | 36% | 31% | || 4 | 19% | 21% | 16% | 34% | 27% | 47% | **20.0%** (pawns 24%, knights 13%; closing error 6.3 mm) || 5 | 17% | 16% | 18% | 30% | 41% | 30% | || 6 | 19% | 21% | 16% | 33% | 32% | 37% | || 7 | 20% | 30% | 9% | 43% | 32% | 37% | |
**Reading:**- **The updates behaved as designed:** the per-element KL was about 0.004 per round and about 3.5% of ratios were clipped.- **In 6 policy-update rounds, nothing improved.** Training success fell from 25-28% to 17-20%, and validation fell from 26.7% to 20.0% (16 to 12 of 60 scenes). With 100 and 60 episodes these changes are within chance, so neither a decline nor its absence is established; the direction is a warning.- **Why it may not be learning yet** (not measured): - The reward is sparse, about 12 decisions per episode with about 25% success. - The critic was still fitting (value loss 0.18 -> 0.13). - The policy moves only a fraction of the noise size per round.- **Saved:** only the round-4 checkpoint (validation 20.0%). The round-7 weights were not saved, because checkpoints are written every 4 rounds.
## Cost
- **This pod:** one RTX 4090, 23:17-01:05 UTC, about 1.8 h, **about $1.33**.- **The owner's fresh $10:** with the DART-600 start ($0.08), about $1.41 has been used.
## Where things are (Machanize/playful, private)
- `chess-sim/experiments/rl_pilot/`: `checkpoint_round4/` (SmolVLA checkpoint; the action expert in float32, so load with `eval_policy.py --expert-fp32`; `rl_state.pt` holds the noise schedule and the critic), `args.json`, `log.jsonl`, `logs/` and `scripts/`.- `chess-sim/reports/rl/`: `check/` (the checks and their evaluation runs) and this summary.- `chess-sim/code/sim/`: `rl_env.py`, `rl_policy.py`, `rl_train.py`, `rl_check.py`, `eval_policy.py`.chess-sim/code/sim/README.md+5
chess-sim/code/sim/eval_policy.py+34-13
chess-sim/code/sim/rl_check.pyAdded+228
chess-sim/code/sim/rl_env.pyAdded+230
chess-sim/code/sim/rl_policy.pyAdded+219
chess-sim/code/sim/rl_train.pyAdded+278
chess-sim/code/sim/visual_probe.pyAdded+182
chess-sim/reports/rl/pilot/args.jsonAdded+36
chess-sim/reports/rl/pilot/log.jsonlAdded+8
chess-sim/reports/rl/summary.mdAdded+98