# /// script # requires-python = ">=3.10" # dependencies = [ # "torch", # "torchvision", # "numpy", # "pandas", # "pyarrow", # "pillow", # "huggingface_hub>=0.34", # "trackio", # "lpips", # ] # /// """Claim 2 (+ Claim 1): interleaved view decoding, multi-view consistency, and frame-skipping inference speed — reproduced at reduced scale on LIBERO-Object. Paper: VLA-MBPO, arXiv:2603.20607 (OpenReview yKQ8GrwEhr), Table 1. WHAT THE PAPER CLAIMS (Table 1, LIBERO-Object, 40-step rollouts, 100 held-out test trajectories): Model head SSIM wrist SSIM Inf. time Ctrl-World 0.882 0.680 21 UMM-World 0.906 0.751 10 - w/o IVD 0.895 0.559 8 - w/o PT 0.756 0.499 10 WHAT THIS SCRIPT REPRODUCES. Finetuning BAGEL-7B-MoT (the paper's UMM) is far outside this reproduction's budget, and neither code nor checkpoint was released. So this tests the *mechanisms* Claim 2 rests on, with a compact multi-view world model (~10-30M params) trained from the same data, same suite (LIBERO-Object), same chunk size (k=10) and the same evaluation protocol (40-step rollouts over 100 held-out trajectories): 1. IVD ablation. The paper's Eq. 3 factorises the multi-view transition as s^h_{t+k} ~ T(. | s^h_t, s^w_t, a_{t:t+k-1}) (head sees action) s^w_{t+k} ~ T(. | s^w_t, s^h_{t+k}) (wrist sees PREDICTED head) versus generating the views independently. The two arms here are exactly that contrast, with identical parameter count and identical forward-pass count -- the ONLY difference is whether the wrist view is conditioned on the *predicted future head view* (ivd) or on the *current head view plus the action chunk* (parallel). That isolates the mechanism. 2. Frame-skipping speed. UMM-World predicts s_{t+k} directly; a video world model must generate all k intermediate frames (paper Figure 2). Measured directly as chunk-jump vs per-step autoregression over the same 40 steps. 3. Joint dynamics + reward in ONE model (Claim 1). A shared trunk predicts both the next observation and the sparse task-completion reward, versus a separate reward-only specialist. 4. Pretraining ablation ("w/o PT"), proxied by initialising the visual encoder from a pretrained ResNet-18 vs random init. NOT reproduced: the Ctrl-World comparison (0.751 vs 0.680) needs the actual Ctrl-World video model and a finetuned BAGEL-7B; absolute SSIM values here are not comparable to the paper's. Only the *direction and relative size* of the ablation gaps are. """ import argparse import io import json import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # ---------------------------------------------------------------------------- # Data # ---------------------------------------------------------------------------- OBJECT_TASK_SUFFIX = "and place it in the basket" RES = 64 CHUNK_K = 10 # paper's action chunk H = 10 ROLLOUT_STEPS = 40 # paper's evaluation protocol: 40-step rollouts ACTION_DIM = 7 ACTION_BINS = 256 # paper discretises actions into [0,256] integer tokens def build_dataset(cache_dir, n_test_per_task=10, max_eps_per_task=None, verbose=True): """Download LIBERO-Object episodes and pack head/wrist frames + actions.""" import pandas as pd from huggingface_hub import hf_hub_download from PIL import Image repo = "physical-intelligence/libero" eps_meta_path = hf_hub_download(repo, "meta/episodes.jsonl", repo_type="dataset", cache_dir=cache_dir) episodes = [json.loads(l) for l in open(eps_meta_path, encoding="utf-8")] by_task = {} for e in episodes: task = e["tasks"][0] if task.startswith("pick up the") and OBJECT_TASK_SUFFIX in task: by_task.setdefault(task, []).append(e) tasks = sorted(by_task) assert len(tasks) == 10, f"expected 10 LIBERO-Object tasks, got {len(tasks)}" def decode(v): if isinstance(v, dict) and "bytes" in v: return np.asarray(Image.open(io.BytesIO(v["bytes"])).convert("RGB") .resize((RES, RES), Image.BILINEAR)) if isinstance(v, (bytes, bytearray)): return np.asarray(Image.open(io.BytesIO(v)).convert("RGB") .resize((RES, RES), Image.BILINEAR)) a = np.asarray(v) if a.dtype != np.uint8: a = (a * 255).clip(0, 255).astype(np.uint8) return np.asarray(Image.fromarray(a).resize((RES, RES), Image.BILINEAR)) splits = {"train": [], "test": []} for ti, task in enumerate(tasks): eps = sorted(by_task[task], key=lambda e: e["episode_index"]) if max_eps_per_task: eps = eps[:max_eps_per_task] # deterministic split: last n_test episodes held out, but always keep at # least half for training (matters only for tiny smoke configs). n_test = min(n_test_per_task, max(1, len(eps) // 2)) for j, e in enumerate(eps): idx = e["episode_index"] chunk = idx // 1000 fp = hf_hub_download( repo, f"data/chunk-{chunk:03d}/episode_{idx:06d}.parquet", repo_type="dataset", cache_dir=cache_dir) df = pd.read_parquet(fp) head = np.stack([decode(v) for v in df["image"]]) wrist = np.stack([decode(v) for v in df["wrist_image"]]) acts = np.stack([np.asarray(a, dtype=np.float32) for a in df["actions"]]) split = "test" if j >= len(eps) - n_test else "train" splits[split].append({"task_index": ti, "task": task, "head": head, "wrist": wrist, "actions": acts}) if verbose: print(f" [{ti + 1}/10] {task[:46]:46s} {len(eps):3d} eps", flush=True) return splits, tasks def discretize_actions(a): """Continuous actions -> integer tokens in [0, ACTION_BINS-1] (paper Sec 3.1).""" a = np.clip(a, -1.0, 1.0) return np.clip(((a + 1.0) * 0.5 * (ACTION_BINS - 1)).round(), 0, ACTION_BINS - 1).astype(np.int64) class ChunkDataset(torch.utils.data.Dataset): """(s_t, a_{t:t+k-1}) -> (s_{t+k}, reward).""" def __init__(self, episodes, k=CHUNK_K): self.k = k self.items = [] self.eps = episodes for ei, ep in enumerate(episodes): T = len(ep["head"]) for t in range(0, T - k): self.items.append((ei, t)) def __len__(self): return len(self.items) def __getitem__(self, i): ei, t = self.items[i] ep = self.eps[ei] k = self.k T = len(ep["head"]) to_f = lambda x: torch.from_numpy(x).permute(2, 0, 1).float() / 127.5 - 1.0 # sparse task-completion reward: the demo succeeds, so the final 10% of # frames are "task complete" (mirrors the paper's binary VLM reward). rew = 1.0 if (t + k) >= int(0.9 * T) else 0.0 return { "head_t": to_f(ep["head"][t]), "wrist_t": to_f(ep["wrist"][t]), "head_tk": to_f(ep["head"][t + k]), "wrist_tk": to_f(ep["wrist"][t + k]), "actions": torch.from_numpy(discretize_actions(ep["actions"][t:t + k])), "reward": torch.tensor(rew), "task_index": torch.tensor(ep["task_index"]), } # ---------------------------------------------------------------------------- # Model # ---------------------------------------------------------------------------- class Encoder(nn.Module): def __init__(self, d, pretrained=False): super().__init__() self.pretrained = pretrained if pretrained: import torchvision net = torchvision.models.resnet18(weights=torchvision.models.ResNet18_Weights.IMAGENET1K_V1) self.stem = nn.Sequential(net.conv1, net.bn1, net.relu, net.layer1, net.layer2, net.layer3) self.proj = nn.Conv2d(256, d, 1) else: import torchvision net = torchvision.models.resnet18(weights=None) self.stem = nn.Sequential(net.conv1, net.bn1, net.relu, net.layer1, net.layer2, net.layer3) self.proj = nn.Conv2d(256, d, 1) def forward(self, x): # (B,3,64,64) -> (B, 16, d) tokens on a 4x4 grid h = self.proj(self.stem(x)) return h.flatten(2).transpose(1, 2) class Decoder(nn.Module): def __init__(self, d): super().__init__() self.net = nn.Sequential( nn.ConvTranspose2d(d, 256, 4, 2, 1), nn.GroupNorm(8, 256), nn.SiLU(), # 8 nn.ConvTranspose2d(256, 128, 4, 2, 1), nn.GroupNorm(8, 128), nn.SiLU(), # 16 nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.GroupNorm(8, 64), nn.SiLU(), # 32 nn.ConvTranspose2d(64, 32, 4, 2, 1), nn.GroupNorm(8, 32), nn.SiLU(), # 64 nn.Conv2d(32, 3, 3, 1, 1), nn.Tanh(), ) def forward(self, tok): # (B,16,d) -> (B,3,64,64) B, N, D = tok.shape g = int(N ** 0.5) return self.net(tok.transpose(1, 2).reshape(B, D, g, g)) class Trunk(nn.Module): """Transformer that maps a context token sequence + learned queries -> tokens.""" def __init__(self, d, layers, heads, n_query): super().__init__() enc = nn.TransformerEncoderLayer(d, heads, d * 4, batch_first=True, norm_first=True, dropout=0.0) self.tf = nn.TransformerEncoder(enc, layers) self.query = nn.Parameter(torch.randn(1, n_query, d) * 0.02) self.n_query = n_query def forward(self, ctx): B = ctx.shape[0] q = self.query.expand(B, -1, -1) out = self.tf(torch.cat([ctx, q], 1)) return out[:, -self.n_query:] class WorldModel(nn.Module): """mode='ivd' : wrist_{t+k} = f(wrist_t, head_{t+k}^pred) [paper Eq. 3] mode='parallel' : wrist_{t+k} = f(wrist_t, head_t, actions) [views independent] Both modes use identical parameters and the same number of trunk passes; only the wrist's conditioning differs. """ def __init__(self, mode="ivd", d=256, layers=4, heads=8, pretrained=True, joint_reward=True): super().__init__() self.mode, self.joint_reward = mode, joint_reward self.enc = Encoder(d, pretrained) self.dec_h = Decoder(d) self.dec_w = Decoder(d) self.act_emb = nn.Embedding(ACTION_BINS, d) self.act_pos = nn.Parameter(torch.randn(1, CHUNK_K * ACTION_DIM, d) * 0.02) self.type_emb = nn.Parameter(torch.randn(4, 1, 1, d) * 0.02) # head/wrist/act/pred self.trunk_h = Trunk(d, layers, heads, 16) self.trunk_w = Trunk(d, layers, heads, 16) self.reward_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 256), nn.SiLU(), nn.Linear(256, 1)) def embed_actions(self, a): # (B,k,7) ints -> (B, k*7, d) B = a.shape[0] return self.act_emb(a.reshape(B, -1)) + self.act_pos def forward(self, head_t, wrist_t, actions): h_tok = self.enc(head_t) + self.type_emb[0] w_tok = self.enc(wrist_t) + self.type_emb[1] a_tok = self.embed_actions(actions) + self.type_emb[2] # head: always conditioned on both views + the action chunk head_pred_tok = self.trunk_h(torch.cat([h_tok, w_tok, a_tok], 1)) if self.mode == "ivd": # wrist sees the PREDICTED future head view, and no action (Eq. 3) ctx_w = torch.cat([w_tok, head_pred_tok + self.type_emb[3]], 1) elif self.mode == "parallel": # wrist generated independently: current head + action, no future head ctx_w = torch.cat([w_tok, h_tok, a_tok], 1) else: raise ValueError(self.mode) wrist_pred_tok = self.trunk_w(ctx_w) head_img = self.dec_h(head_pred_tok) wrist_img = self.dec_w(wrist_pred_tok) rew = self.reward_head(head_pred_tok.mean(1)).squeeze(-1) if self.joint_reward else None return head_img, wrist_img, rew class RewardOnly(nn.Module): """Separate reward specialist (the 'two-model design' the paper argues against).""" def __init__(self, d=256, layers=4, heads=8, pretrained=True): super().__init__() self.enc = Encoder(d, pretrained) self.trunk = Trunk(d, layers, heads, 1) self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 256), nn.SiLU(), nn.Linear(256, 1)) def forward(self, head_img, wrist_img): ctx = torch.cat([self.enc(head_img), self.enc(wrist_img)], 1) return self.head(self.trunk(ctx)[:, 0]).squeeze(-1) # ---------------------------------------------------------------------------- # Metrics # ---------------------------------------------------------------------------- def to_img01(x): return ((x.clamp(-1, 1) + 1) / 2) def psnr(a, b): mse = F.mse_loss(a, b, reduction="none").flatten(1).mean(1) return (10 * torch.log10(1.0 / mse.clamp_min(1e-10))) def ssim(a, b, C1=0.01 ** 2, C2=0.03 ** 2): """Standard SSIM, 11x11 gaussian, averaged over channels.""" def gauss(ws, sigma, device): g = torch.arange(ws, dtype=torch.float32, device=device) - ws // 2 g = torch.exp(-(g ** 2) / (2 * sigma ** 2)) g = (g / g.sum()) return (g[:, None] @ g[None, :]) C = a.shape[1] w = gauss(11, 1.5, a.device).expand(C, 1, 11, 11).contiguous() mu1, mu2 = F.conv2d(a, w, padding=5, groups=C), F.conv2d(b, w, padding=5, groups=C) mu1s, mu2s, mu12 = mu1 ** 2, mu2 ** 2, mu1 * mu2 s1 = F.conv2d(a * a, w, padding=5, groups=C) - mu1s s2 = F.conv2d(b * b, w, padding=5, groups=C) - mu2s s12 = F.conv2d(a * b, w, padding=5, groups=C) - mu12 m = ((2 * mu12 + C1) * (2 * s12 + C2)) / ((mu1s + mu2s + C1) * (s1 + s2 + C2)) return m.flatten(1).mean(1) # ---------------------------------------------------------------------------- # Train / eval # ---------------------------------------------------------------------------- def evaluate_rollout(model, test_eps, device, lpips_fn=None, max_eps=None, log_samples=0): """Paper's protocol: 40-step rollouts on held-out trajectories, autoregressive at the chunk level (40 steps / k=10 = 4 chunk jumps).""" model.eval() eps = test_eps[:max_eps] if max_eps else test_eps acc = {"head_ssim": [], "wrist_ssim": [], "head_psnr": [], "wrist_psnr": [], "head_lpips": [], "wrist_lpips": []} samples = [] n_jumps = ROLLOUT_STEPS // CHUNK_K with torch.no_grad(): for ep in eps: T = len(ep["head"]) if T < ROLLOUT_STEPS + 1: continue t0 = 0 to_f = lambda x: (torch.from_numpy(x).permute(2, 0, 1).float() / 127.5 - 1.0)[None].to(device) h = to_f(ep["head"][t0]) w = to_f(ep["wrist"][t0]) for j in range(n_jumps): t = t0 + j * CHUNK_K a = torch.from_numpy(discretize_actions(ep["actions"][t:t + CHUNK_K]))[None].to(device) h, w, _ = model(h, w, a) gt_h = to_f(ep["head"][t + CHUNK_K]) gt_w = to_f(ep["wrist"][t + CHUNK_K]) ph, pw = to_img01(h), to_img01(w) gh, gw = to_img01(gt_h), to_img01(gt_w) acc["head_ssim"].append(ssim(ph, gh).item()) acc["wrist_ssim"].append(ssim(pw, gw).item()) acc["head_psnr"].append(psnr(ph, gh).item()) acc["wrist_psnr"].append(psnr(pw, gw).item()) if lpips_fn is not None: acc["head_lpips"].append(lpips_fn(h, gt_h).item()) acc["wrist_lpips"].append(lpips_fn(w, gt_w).item()) if len(samples) < log_samples and j == n_jumps - 1: samples.append({ "pred_head": (ph[0].cpu().numpy() * 255).astype(np.uint8), "gt_head": (gh[0].cpu().numpy() * 255).astype(np.uint8), "pred_wrist": (pw[0].cpu().numpy() * 255).astype(np.uint8), "gt_wrist": (gw[0].cpu().numpy() * 255).astype(np.uint8), "task": ep["task"], }) out = {k: float(np.mean(v)) for k, v in acc.items() if v} return out, samples def train_variant(name, mode, pretrained, joint_reward, train_eps, test_eps, args, device, lpips_fn=None): torch.manual_seed(0) np.random.seed(0) model = WorldModel(mode=mode, d=args.dim, layers=args.layers, pretrained=pretrained, joint_reward=joint_reward).to(device) n_params = sum(p.numel() for p in model.parameters()) ds = ChunkDataset(train_eps) dl = torch.utils.data.DataLoader(ds, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True, pin_memory=True, persistent_workers=args.workers > 0) opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01) total = args.steps sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=args.lr, total_steps=total, pct_start=0.05) scaler = torch.amp.GradScaler("cuda", enabled=device.type == "cuda") print(f"\n=== training '{name}' (mode={mode}, pretrained={pretrained}, " f"joint_reward={joint_reward}) | {n_params/1e6:.1f}M params | " f"{len(ds)} chunks | {total} steps ===", flush=True) step, t0 = 0, time.time() model.train() run = None if args.trackio_project: import trackio run = trackio.init(project=args.trackio_project, name=name, space_id=args.trackio_space or None, config={"mode": mode, "pretrained": pretrained, "joint_reward": joint_reward, "steps": total, "lr": args.lr, "batch_size": args.batch_size, "params_M": round(n_params / 1e6, 2), "chunk_k": CHUNK_K, "res": RES}) while step < total: for b in dl: if step >= total: break head_t, wrist_t = b["head_t"].to(device, non_blocking=True), b["wrist_t"].to(device, non_blocking=True) head_tk, wrist_tk = b["head_tk"].to(device, non_blocking=True), b["wrist_tk"].to(device, non_blocking=True) a, rew = b["actions"].to(device), b["reward"].to(device) with torch.autocast("cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"): ph, pw, pr = model(head_t, wrist_t, a) loss_h = F.l1_loss(ph, head_tk) loss_w = F.l1_loss(pw, wrist_tk) loss = loss_h + loss_w loss_r = torch.tensor(0.0, device=device) if pr is not None: loss_r = F.binary_cross_entropy_with_logits(pr.float(), rew) loss = loss + args.reward_weight * loss_r opt.zero_grad(set_to_none=True) scaler.scale(loss).backward() scaler.unscale_(opt) torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) scaler.step(opt) scaler.update() sched.step() step += 1 if step % args.log_every == 0: msg = (f" [{name}] step {step}/{total} loss {loss.item():.4f} " f"(head {loss_h.item():.4f} wrist {loss_w.item():.4f} " f"rew {loss_r.item():.4f}) {time.time()-t0:.0f}s") print(msg, flush=True) if run: import trackio trackio.log({"loss": loss.item(), "loss_head": loss_h.item(), "loss_wrist": loss_w.item(), "loss_reward": loss_r.item(), "lr": sched.get_last_lr()[0]}, step=step) train_s = time.time() - t0 metrics, samples = evaluate_rollout(model, test_eps, device, lpips_fn, log_samples=args.log_samples) # reward accuracy / F1 on held-out chunks rmetrics = eval_reward(model, test_eps, device, args) if joint_reward else {} metrics.update(rmetrics) metrics["train_seconds"] = train_s metrics["params_M"] = n_params / 1e6 print(f" [{name}] -> " + " ".join(f"{k}={v:.4f}" for k, v in metrics.items()), flush=True) if run: import trackio trackio.log({f"eval/{k}": v for k, v in metrics.items()}) trackio.finish() return model, metrics, samples def eval_reward(model, test_eps, device, args): model.eval() ds = ChunkDataset(test_eps) dl = torch.utils.data.DataLoader(ds, batch_size=args.batch_size, num_workers=0) ys, ps = [], [] with torch.no_grad(): for b in dl: _, _, pr = model(b["head_t"].to(device), b["wrist_t"].to(device), b["actions"].to(device)) if pr is None: return {} ps.append((torch.sigmoid(pr.float()) > 0.5).cpu().numpy()) ys.append(b["reward"].numpy()) y = np.concatenate(ys) p = np.concatenate(ps) tp = float(((p == 1) & (y == 1)).sum()) fp = float(((p == 1) & (y == 0)).sum()) fn = float(((p == 0) & (y == 1)).sum()) prec = tp / (tp + fp) if tp + fp else 0.0 rec = tp / (tp + fn) if tp + fn else 0.0 return {"reward_acc": float((p == y).mean() * 100), "reward_f1": float(2 * prec * rec / (prec + rec)) if prec + rec else 0.0} def eval_reward_specialist(model, test_eps, device, args): model.eval() ds = ChunkDataset(test_eps) dl = torch.utils.data.DataLoader(ds, batch_size=args.batch_size, num_workers=0) ys, ps = [], [] with torch.no_grad(): for b in dl: pr = model(b["head_t"].to(device), b["wrist_t"].to(device)) ps.append((torch.sigmoid(pr.float()) > 0.5).cpu().numpy()) ys.append(b["reward"].numpy()) y, p = np.concatenate(ys), np.concatenate(ps) tp = float(((p == 1) & (y == 1)).sum()); fp = float(((p == 1) & (y == 0)).sum()) fn = float(((p == 0) & (y == 1)).sum()) prec = tp / (tp + fp) if tp + fp else 0.0 rec = tp / (tp + fn) if tp + fn else 0.0 return {"reward_acc": float((p == y).mean() * 100), "reward_f1": float(2 * prec * rec / (prec + rec)) if prec + rec else 0.0} def train_reward_specialist(train_eps, test_eps, args, device): torch.manual_seed(0) model = RewardOnly(d=args.dim, layers=args.layers, pretrained=True).to(device) ds = ChunkDataset(train_eps) dl = torch.utils.data.DataLoader(ds, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True) opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01) print(f"\n=== training 'reward-specialist' ({sum(p.numel() for p in model.parameters())/1e6:.1f}M) ===", flush=True) step = 0 model.train() while step < args.steps: for b in dl: if step >= args.steps: break with torch.autocast("cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"): pr = model(b["head_t"].to(device), b["wrist_t"].to(device)) loss = F.binary_cross_entropy_with_logits(pr.float(), b["reward"].to(device)) opt.zero_grad(set_to_none=True) loss.backward() opt.step() step += 1 m = eval_reward_specialist(model, test_eps, device, args) print(f" [reward-specialist] -> {m}", flush=True) return m def benchmark_inference(model, device, reps=30): """Frame-skip (predict s_{t+k} directly, 4 jumps for 40 steps) vs generating every intermediate frame (40 sequential single-step predictions).""" model.eval() h = torch.randn(1, 3, RES, RES, device=device) w = torch.randn(1, 3, RES, RES, device=device) a = torch.randint(0, ACTION_BINS, (1, CHUNK_K, ACTION_DIM), device=device) sync = (lambda: torch.cuda.synchronize()) if device.type == "cuda" else (lambda: None) def run(n_calls): hh, ww = h, w for _ in range(n_calls): hh, ww, _ = model(hh, ww, a) return hh with torch.no_grad(): for _ in range(5): run(1) sync() t0 = time.time() for _ in range(reps): run(ROLLOUT_STEPS // CHUNK_K) # 4 chunk jumps = 40 steps sync() t_skip = (time.time() - t0) / reps t0 = time.time() for _ in range(reps): run(ROLLOUT_STEPS) # 40 single-step generations sync() t_all = (time.time() - t0) / reps return {"frame_skip_s_per_40_steps": t_skip, "all_frames_s_per_40_steps": t_all, "speedup": t_all / t_skip} def main(): ap = argparse.ArgumentParser() ap.add_argument("--steps", type=int, default=6000) ap.add_argument("--batch-size", type=int, default=64) ap.add_argument("--lr", type=float, default=3e-4) ap.add_argument("--dim", type=int, default=256) ap.add_argument("--layers", type=int, default=4) ap.add_argument("--reward-weight", type=float, default=0.5) ap.add_argument("--workers", type=int, default=4) ap.add_argument("--log-every", type=int, default=200) ap.add_argument("--log-samples", type=int, default=6) ap.add_argument("--max-eps-per-task", type=int, default=None) ap.add_argument("--cache-dir", default=None) ap.add_argument("--out", default="outputs/claim2") ap.add_argument("--trackio-project", default="") ap.add_argument("--trackio-space", default="") ap.add_argument("--push-to", default="", help="HF dataset repo to push results to") ap.add_argument("--smoke", action="store_true") args = ap.parse_args() if args.smoke: args.steps, args.max_eps_per_task, args.workers = 30, 3, 0 args.log_every, args.log_samples = 10, 2 os.makedirs(args.out, exist_ok=True) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"device={device} torch={torch.__version__}", flush=True) if device.type == "cuda": print(f"gpu={torch.cuda.get_device_name(0)}", flush=True) print("\nBuilding LIBERO-Object dataset (10 tasks)...", flush=True) t0 = time.time() splits, tasks = build_dataset(args.cache_dir, n_test_per_task=1 if args.smoke else 10, max_eps_per_task=args.max_eps_per_task) print(f" train episodes: {len(splits['train'])} test episodes: {len(splits['test'])} " f"({time.time()-t0:.0f}s)", flush=True) lpips_fn = None try: import lpips as lpips_lib lpips_fn = lpips_lib.LPIPS(net="alex").to(device) print(" LPIPS enabled", flush=True) except Exception as e: print(f" LPIPS unavailable ({e}); skipping", flush=True) variants = [ ("umm-world (ivd)", "ivd", True, True), ("w/o IVD (parallel)", "parallel", True, True), ("w/o PT (random init)", "ivd", False, True), ] results, all_samples = {}, {} models = {} for name, mode, pt, jr in variants: m, metrics, samples = train_variant(name, mode, pt, jr, splits["train"], splits["test"], args, device, lpips_fn) results[name] = metrics all_samples[name] = samples models[name] = m # Claim 1: joint dynamics+reward vs a separate reward specialist results["reward-specialist (separate model)"] = train_reward_specialist( splits["train"], splits["test"], args, device) # Frame-skipping speed (paper Figure 2 / Table 1 "Inf. Time") bench = benchmark_inference(models["umm-world (ivd)"], device) print(f"\nInference benchmark: {bench}", flush=True) payload = { "meta": { "paper": "arXiv:2603.20607 (OpenReview yKQ8GrwEhr)", "claim": "Claim 2 (IVD / multi-view consistency / frame-skip speed) + Claim 1 (joint reward)", "scale": "reduced-scale surrogate world model, NOT BAGEL-7B", "suite": "LIBERO-Object (10 tasks)", "n_train_episodes": len(splits["train"]), "n_test_episodes": len(splits["test"]), "resolution": RES, "chunk_k": CHUNK_K, "rollout_steps": ROLLOUT_STEPS, "steps": args.steps, "batch_size": args.batch_size, "device": str(device), "gpu": torch.cuda.get_device_name(0) if device.type == "cuda" else None, "torch": torch.__version__, "smoke": args.smoke, }, "paper_table1": { "Ctrl-World": {"head_ssim": 0.882, "wrist_ssim": 0.680, "inf_time": 21}, "UMM-World": {"head_ssim": 0.906, "wrist_ssim": 0.751, "inf_time": 10, "reward_acc": 98.4, "reward_f1": 0.861}, "w/o IVD": {"head_ssim": 0.895, "wrist_ssim": 0.559, "inf_time": 8, "reward_acc": 98.5, "reward_f1": 0.799}, "w/o PT": {"head_ssim": 0.756, "wrist_ssim": 0.499, "inf_time": 10, "reward_acc": 94.5, "reward_f1": 0.496}, "Qwen3-VL-8B": {"reward_acc": 97.0, "reward_f1": 0.841}, }, "results": results, "inference_benchmark": bench, } with open(os.path.join(args.out, "claim2_results.json"), "w", encoding="utf-8") as f: json.dump(payload, f, indent=2) # sample galleries try: from PIL import Image gal = os.path.join(args.out, "galleries") os.makedirs(gal, exist_ok=True) for name, samples in all_samples.items(): slug = name.replace("/", "-").replace(" ", "_").replace("(", "").replace(")", "") for i, s in enumerate(samples): rows = [np.concatenate([s["gt_head"], s["pred_head"]], axis=2), np.concatenate([s["gt_wrist"], s["pred_wrist"]], axis=2)] img = np.concatenate(rows, axis=1).transpose(1, 2, 0) Image.fromarray(img).resize((img.shape[1] * 3, img.shape[0] * 3), Image.NEAREST)\ .save(os.path.join(gal, f"{slug}_{i}.png")) print(f"wrote galleries to {gal}", flush=True) except Exception as e: print(f"gallery failed: {e}", flush=True) print("\n" + "=" * 78) print("SUMMARY (reduced-scale surrogate; absolute values NOT comparable to paper)") print("=" * 78) print(f"{'variant':32s} {'head SSIM':>10s} {'wrist SSIM':>11s} {'rew ACC':>8s} {'rew F1':>7s}") for k, v in results.items(): print(f"{k:32s} {v.get('head_ssim', float('nan')):10.4f} " f"{v.get('wrist_ssim', float('nan')):11.4f} " f"{v.get('reward_acc', float('nan')):8.1f} {v.get('reward_f1', float('nan')):7.3f}") print(f"\nframe-skip speedup over generating all 40 frames: {bench['speedup']:.2f}x") if args.push_to: from huggingface_hub import HfApi api = HfApi() api.create_repo(args.push_to, repo_type="dataset", exist_ok=True) api.upload_folder(folder_path=args.out, repo_id=args.push_to, repo_type="dataset", path_in_repo="claim2") print(f"pushed results to https://huggingface.co/datasets/{args.push_to}", flush=True) if __name__ == "__main__": main()