rsm_rise_code / rsm_rise /scripts /beam /test_beam_cpu.py
rli14's picture
rsm_rise code snapshot (HF_PUSH_ALL) (part 11)
c6a8401 verified
Raw History Blame Contribute Delete
9.66 kB
"""BEAM_RISE CPU unit test (random checkpoints, then -- if given -- the real task checkpoints).
usage: python test_beam_cpu.py [rsm_ckpt hop_ckpt feat_stats]"""
import os, sys, tempfile, time, math, types
import torch
from robomimic.algo import rsm_scorer as S
from robomimic.algo.rsm_beam import BeamSearch, ChainReader, BEAM_DEFAULTS
from robomimic.algo.rsm_planner import RSMPlannerMixin, PLANNER_DEFAULTS
torch.set_num_threads(8)
ok = True
def check(c, msg):
global ok
print(("PASS " if c else "FAIL ") + msg, flush=True); ok &= bool(c)
# ---- 0. config schema: beam keys default None -> planner_kwargs unchanged ---------------------------
from sim_pipeline.configs.training._imitation_learning._offline_rl import iql_diffusion as C
cls = [v for v in vars(C).values() if isinstance(v, type) and hasattr(v, '__dataclass_fields__') and 'plan_beam_width' in v.__dataclass_fields__]
check(len(cls) >= 1, f"dataclass with beam fields: {[c.__name__ for c in cls]}")
try:
inst = cls[0]()
kw = C.planner_kwargs(inst)
check(not any(k.startswith('plan_beam') for k in kw), f"default planner_kwargs has no beam keys ({len(kw)} keys)")
inst.plan_beam_width = 4
check(C.planner_kwargs(inst).get('plan_beam_width') == 4, "set beam key reaches planner_kwargs")
except Exception as e:
check(False, f"dataclass instantiate: {e!r}")
def run(rsm, hop, fs, tag, beta=0.95, dev="cpu"):
sc = S.RSMScorer(backend="mlp", ckpt=rsm, hop_ckpt=hop, feat_stats=fs, mode="chain", depth=1, beta=beta,
gamma=0.99, n_particles=16, flow_steps=8, device=dev)
b = sc.backend
D, da = b.d_z, b.d_act
print(f"[{tag}] d_z={D} d_act={da} cfg beta_lo={b.cfg.get('beta_lo')} beta_hi={b.cfg.get('beta_hi')} T={sc.effective_temperature()}")
# ---- 1. ChainReader == _q_chain_logit (same generator seed) -------------------------------------
torch.manual_seed(1)
z = torch.randn(6, D) * 0.5; a = torch.randn(6, da) * 0.3
task = torch.zeros(6, dtype=torch.long)
T = sc.effective_temperature()
q_ref, lg_ref, _st = S._q_chain_logit(z, a, task, rew=b.rew, flow=b.flow, rms=b.rms, pol=b.hop, beta=beta,
gamma=0.99, n_particles=16, flow_steps=8, temperature=T, seed=123)
rd = ChainReader(b, beta, 0.99, 0, 8, T)
g = torch.Generator(device=dev); g.manual_seed(123)
lg = rd.logits(z, a, 16, generator=g)
q_me = torch.sigmoid(lg).mean(1)
err = float((q_me - q_ref).abs().max())
check(err < 1e-5, f"[{tag}] ChainReader reproduces _q_chain_logit: max|dq|={err:.2e} (q={q_ref.tolist()[:3]})")
# ---- 2. depth-1 beam == best-of-N (prob ranking), same global RNG state --------------------------
N = 32
z0 = torch.randn(D) * 0.5; A = torch.randn(N, da) * 0.3
cfg = dict(PLANNER_DEFAULTS); cfg.update(plan_particles=16, plan_beta=beta, plan_mode="beam", plan_score="prob",
plan_beam_depth=1)
bs = BeamSearch(sc, cfg)
torch.manual_seed(7); q_bon = b.q(z0.expand(N, -1), A, mode="chain", depth=1, beta=beta, gamma=0.99,
n_particles=16, flow_steps=8)
torch.manual_seed(7); j, info = bs.plan(z0, A)
err = float((info["f1"].exp() - q_bon).abs().max())
check(err < 1e-5 and j == int(q_bon.argmax()), f"[{tag}] depth-1 beam == best-of-N: max|dq|={err:.2e}, argmax {j} vs {int(q_bon.argmax())}")
# ---- 3. depth 3, all knobs ------------------------------------------------------------------------
for agg in ("logmean", "meanlog"):
for rw in (1, 0):
cfg.update(plan_beam_depth=3, plan_beam_width=8, plan_beam_branch=8, plan_beam_root_keep=8,
plan_beam_nwm=4, plan_beam_beta_t=0.95, plan_beam_tail_k=16, plan_beam_agg=agg, plan_beam_reward=rw)
bs = BeamSearch(sc, cfg)
t0 = time.time(); j, info = bs.plan(z0, A); dt = time.time() - t0
f = info["f"]
check(0 <= j < N and torch.isfinite(f).all() and float(f.max()) <= 1e-6,
f"[{tag}] depth-3 agg={agg} reward={rw}: root={j} rank_l1={int((info['f1'] > info['f1'][j]).sum())} "
f"f_fin_max={float(f.max()):.4f} levels={[(l['n'], round(l['f_max'], 3)) for l in info['levels']]} {dt:.2f}s")
print("[%s] describe %s" % (tag, bs.describe()))
# ---- 3b. run 6: quantile / LCB (gen_q #115). q=1.0 and L=0 must reproduce 'max' bit-for-bit -------------
for agg in ("logmean", "meanlog"):
base = dict(cfg); base.update(plan_beam_depth=3, plan_beam_width=8, plan_beam_branch=8, plan_beam_root_keep=8,
plan_beam_nwm=4, plan_beam_beta_t=0.95, plan_beam_tail_k=16, plan_beam_agg=agg,
plan_beam_reward=1, plan_beam_rescore=1)
def go(z0_, **kw):
c = dict(base); c.update(kw); torch.manual_seed(11); return BeamSearch(sc, c).plan(z0_, A)
moved = {"q0.9": 0, "q0.75": 0, "lcb0.5": 0, "lcb1.0": 0}
lcb_alive = False
for t in range(6):
torch.manual_seed(100 + t); zt = torch.randn(D) * 0.5
j0, i0 = go(zt, plan_beam_select="max")
jq, iq = go(zt, plan_beam_select="quantile", plan_beam_select_q=1.0)
jl, il = go(zt, plan_beam_select="lcb", plan_beam_lcb_lambda=0.0)
same = (j0 == jq == jl and torch.equal(i0["f"], iq["f"]) and torch.equal(i0["f"], il["f"])
and torch.equal(i0["f1"], iq["f1"]) and torch.equal(i0["root"], il["root"]))
check(same, f"[{tag}] agg={agg} state{t}: q=1.0 and L=0 == max bit-for-bit (root {j0}/{jq}/{jl})")
for nm, kw in (("q0.9", dict(plan_beam_select="quantile", plan_beam_select_q=0.9)),
("q0.75", dict(plan_beam_select="quantile", plan_beam_select_q=0.75)),
("lcb0.5", dict(plan_beam_select="lcb", plan_beam_lcb_lambda=0.5)),
("lcb1.0", dict(plan_beam_select="lcb", plan_beam_lcb_lambda=1.0))):
jk, ik = go(zt, **kw)
check(0 <= jk < N and torch.isfinite(ik["fs"]).all(), f"[{tag}] agg={agg} state{t} {nm}: root={jk} "
f"sel_rank={ik['sel_rank']} fs_max={float(ik['fs'].max()):.3f} f_max={float(ik['f'].max()):.3f}")
if nm == "q0.9": check(ik["sel_rank"] == 1, f"[{tag}] q0.9 at B=8 skips 1 rank (got {ik['sel_rank']})")
if nm == "q0.75": check(ik["sel_rank"] == 2, f"[{tag}] q0.75 at B=8 skips 2 ranks (got {ik['sel_rank']})")
moved[nm] += int(jk != j0)
if nm.startswith("lcb"): lcb_alive |= not torch.equal(ik["fs"], ik["f"])
print(f"[{tag}] {nm}: final-beam distinct roots={ik['levels'][-1].get('n_roots')}")
# INFO only: the executed ROOT moves only if the final beam holds >1 root (often it is one root's subtree)
print(f"[{tag}] agg={agg} INFO knob moved the executed root on (of 6 states): {moved}")
check(lcb_alive, f"[{tag}] agg={agg} lcb L>0 changes the selection scores (fs != f) on >=1 state")
return sc
# ---- 4. planner mixin end-to-end (fake proposer, fake state) ---------------------------------------
class FakeAlgo(RSMPlannerMixin):
def __init__(self, D, da):
class Cfg:
horizon = types.SimpleNamespace(observation_horizon=2, action_horizon=8, prediction_horizon=16)
def __getitem__(self, k): raise KeyError(k)
self.algo_config = Cfg()
self.nets = {}; self.device = "cpu"; self.ac_dim = 7; self.D = D
def _sample_action_chunks(self, obs, goal):
n = obs["x"].shape[0]; return torch.randn(n, 16, 7) * 0.3
with tempfile.TemporaryDirectory() as td:
rsm = S.save_random_rsm_ckpt(os.path.join(td, "rsm.pt"))
hop = S.save_random_hop_ckpt(os.path.join(td, "hop.pt"))
fs = S.save_feat_stats(os.path.join(td, "fs.npz"))
run(rsm, hop, fs, "random")
alg = FakeAlgo(S.STATE_DIM, 56)
alg.configure_planner(plan_n=16, plan_mode="beam", rsm_backend="mlp", rsm_ckpt=rsm, rsm_hop_ckpt=hop, rsm_feat_stats=fs,
plan_beta=0.95, plan_particles=8, plan_beam_depth=2, plan_beam_width=4, plan_beam_branch=4,
plan_beam_root_keep=4, plan_beam_nwm=2, plan_beam_tail_k=8)
sc = alg._get_scorer()
sc.state_from_obs = lambda obs_t: types.SimpleNamespace(x=torch.randn(obs_t["x"].shape[0], S.STATE_DIM) * 0.5, tok=None, pr=None)
obs = {"x": torch.randn(1, 2, 3)}
act = alg.plan_get_action(obs)
lg = alg.pop_plan_log()
check(tuple(act.shape) == (1, 8, 7) and lg and lg[0]["rule"] == "beam",
f"mixin dispatch: action {tuple(act.shape)} log keys {sorted(lg[0])[:6]}... idx={lg[0]['idx']}")
d = alg.planner_describe()
check("beam" in d and d["plan_mode"] == "beam", f"planner_describe carries beam: {d.get('beam')}")
# a non-beam mode on the same object never builds a BeamSearch
alg2 = FakeAlgo(S.STATE_DIM, 56)
alg2.configure_planner(plan_n=16, plan_mode="chain", rsm_backend="mlp", rsm_ckpt=rsm, rsm_hop_ckpt=hop, rsm_feat_stats=fs,
plan_beta=0.95, plan_particles=8)
alg2._get_scorer().state_from_obs = sc.state_from_obs
alg2.plan_get_action(obs)
check(getattr(alg2, "_planner_beam", None) is None and "beam" not in alg2.planner_describe(), "chain mode untouched by beam")
if len(sys.argv) == 4:
dev = "cuda" if torch.cuda.is_available() else "cpu"
run(sys.argv[1], sys.argv[2], sys.argv[3], "real", beta=float(os.environ.get("BEAM_TEST_BETA", "0.95")), dev=dev)
print("ALL_OK" if ok else "SOME_FAILED")
sys.exit(0 if ok else 1)