"""ResWAM: Learning What Changes, Not What Stays, for World-Action Models. Single-step LIBERO policy demo: one agentview + one wrist observation, a task instruction, and the 8-D proprioceptive state are mapped to an 8-step chunk of 7-D delta-EEF actions, together with the model's predicted latent DINOv3 world residual ("what changes") as an 8x8 spatial heatmap. Weights: OPTML-Group/ResWAM-LIBERO (ResWAM system checkpoint). VLM backbone: Alibaba-DAMO-Academy/RynnBrain1.1-2B (24 vision blocks / 16 text layers). Frozen vision features: DINOv3-ViT-B/16 (blocks 8 & 10, 2x2 pooled -> 64 tokens). """ import json import time from pathlib import Path import spaces # noqa: F401 (must be imported before torch) import gradio as gr import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import torch from huggingface_hub import hf_hub_download from PIL import Image from reswam.data import ZScoreCodec from reswam.models import ( DINOv3DualViewEncoder, RynnBrainText16Encoder, ResWAMSystem, preprocess_camera, synchronous_sample, system_config, ) CKPT_REPO = "OPTML-Group/ResWAM-LIBERO" ASSETS = Path(__file__).parent / "assets" HORIZON = 8 ACTION_DIM = 7 STATE_DIM_RAW = 8 ACTION_COLS = ["dx", "dy", "dz", "droll", "dpitch", "dyaw", "gripper"] STATE_COLS = ["eef_x", "eef_y", "eef_z", "aa_x", "aa_y", "aa_z", "finger_l", "finger_r"] DEFAULT_TASK = ( "put the white mug on the left plate and put the yellow and white mug on the right plate" ) # -------------------------------------------------------------------------------------- # Model loading (module scope, eager .to("cuda")) # -------------------------------------------------------------------------------------- def build_local_dinov3() -> torch.nn.Module: """Build the DINOv3-ViT-B/16 architecture locally from config values. The original facebook/dinov3-vitb16-pretrain-lvd1689m repo is gated; the full frozen encoder ships inside the ResWAM checkpoint under ``dino.model.*`` (211 keys covering the identical architecture), so we construct transformers' native DINOv3 implementation here and let the system state dict below fill every weight. This reproduces the encoder bit-for-bit without Hub access to the gated repo. """ from transformers import DINOv3ViTConfig, DINOv3ViTModel config = DINOv3ViTConfig( patch_size=16, hidden_size=768, intermediate_size=3072, num_hidden_layers=12, num_attention_heads=12, image_size=256, num_register_tokens=4, rope_theta=100.0, layer_norm_eps=1e-5, ) return DINOv3ViTModel(config) def load_system() -> tuple[ResWAMSystem, ZScoreCodec]: codec = ZScoreCodec.from_file(hf_hub_download(CKPT_REPO, "codec_statistics.json")) vlm = RynnBrainText16Encoder( views=("head", "left_wrist"), # LIBERO uses exactly these two cameras prompt_style="libero_cot", ) dino = DINOv3DualViewEncoder(model=build_local_dinov3()) config = system_config( action_dim=codec.action_dim, state_dim=codec.state_dim, horizon=HORIZON, views=("head", "left_wrist"), world_views=("head",), world_loss_weight=0.5, action_tau_shift=1.0, world_tau_shift=1.0, solver_steps=10, state_dropout_prob=0.3, prompt_style="libero_cot", ) system = ResWAMSystem(config, vlm=vlm, dino=dino) ckpt_path = hf_hub_download(CKPT_REPO, "model.pt") print(f"[reswam] loading checkpoint payload from {ckpt_path}", flush=True) payload = torch.load(ckpt_path, map_location="cpu", weights_only=False) system.load_state_dict(payload["model"], strict=True) system.eval() system.to("cuda") return system, codec print("[reswam] boot: loading checkpoint (first boot downloads ~9.3 GB) ...", flush=True) SYSTEM, CODEC = load_system() print("[reswam] system ready on cuda", flush=True) # -------------------------------------------------------------------------------------- # Inference (replicates ResWAMSystem.sample_actions, keeping the world residual) # -------------------------------------------------------------------------------------- @torch.inference_mode() def run_policy( head_img: Image.Image, wrist_img: Image.Image, instruction: str, raw_state: np.ndarray, seed: int, ) -> tuple[np.ndarray, np.ndarray]: """Predict one 8-step action chunk + latent world residual from one observation. Follows the eval script's sample_actions 1:1 (bicubic 256 camera prep, VLM context, DINOv3 features on world views, z-scored state, 10-step synchronous flow matching with the checkpoint's tau shifts) but keeps the latent residual that the published sampler discards, for visualization. """ cameras = { "head": [np.array(head_img.convert("RGB"), dtype=np.uint8, copy=True)], "left_wrist": [np.array(wrist_img.convert("RGB"), dtype=np.uint8, copy=True)], } processed = { name: torch.stack( [preprocess_camera(torch.from_numpy(img).permute(2, 0, 1)) for img in cameras[name]] ) for name in SYSTEM.views } images = { name: [f.mul(255).round().to(torch.uint8).permute(1, 2, 0).numpy() for f in processed[name]] for name in SYSTEM.views } context, mask = SYSTEM.vlm(SYSTEM.vlm.prepare(images, [instruction])) device = context.device primaries = [SYSTEM.dino(processed[v].to(device)) for v in SYSTEM.world_views] primary = primaries[0] if len(primaries) == 1 else torch.cat(primaries, dim=1) state = torch.from_numpy(CODEC.encode_state(np.asarray(raw_state, np.float32))).unsqueeze(0) state = state.to(device, dtype=torch.float32) state_mask = torch.ones_like(state, dtype=torch.bool) actions, world_residual, _ = synchronous_sample( SYSTEM.objective.expert, current_primary=primary, vlm_context=context, vlm_mask=mask, state=state, state_mask=state_mask, seeds=[int(seed)], action_shift=SYSTEM.objective.action_tau_shift, world_shift=SYSTEM.objective.world_tau_shift, steps=SYSTEM.objective.solver_steps, ) chunk = CODEC.decode_action(actions[0].detach().float().cpu().numpy()) # [8, 7] residual = world_residual[0].detach().float().cpu().numpy() # [64, 768] return chunk, residual @spaces.GPU(duration=10) def predict( head_img, wrist_img, instruction, eef_x, eef_y, eef_z, aa_x, aa_y, aa_z, finger_l, finger_r, seed=0, ): """Gradio handler: images + instruction + 8-D state -> action table, plots, heatmap.""" raw_state = np.array([eef_x, eef_y, eef_z, aa_x, aa_y, aa_z, finger_l, finger_r], np.float32) t0 = time.perf_counter() chunk, residual = run_policy(head_img, wrist_img, instruction, raw_state, int(seed)) elapsed = time.perf_counter() - t0 print(f"[reswam] inference took {elapsed:.2f}s", flush=True) # ---- action chunk table ----------------------------------------------------------- rows = chunk.tolist() # ---- end-effector path + gripper timeline ----------------------------------------- pos = np.cumsum(chunk[:, :3], axis=0) fig, axes = plt.subplots(1, 2, figsize=(9, 3.2)) ax = axes[0] ax.plot(pos[:, 0], pos[:, 1], "o-", color="#1f77b4", label="xy path") ax.plot(pos[0, 0], pos[0, 1], "s", color="green", markersize=9, label="start") ax.set_xlabel("cumulative dx [m]") ax.set_ylabel("cumulative dy [m]") ax.set_title("Predicted end-effector path (top view)") ax.legend(fontsize=8) ax.axis("equal") ax2 = axes[1] steps_axis = np.arange(HORIZON) ax2.step(steps_axis, chunk[:, 6], where="post", color="#d62728") ax2.set_xlabel("step in chunk") ax2.set_ylabel("gripper cmd (+1 close / -1 open)") ax2.set_title("Gripper command over the chunk") ax2.set_ylim(-1.3, 1.3) ax2.set_xticks(steps_axis) fig.tight_layout() fig.savefig("/tmp/reswam_traj.png", dpi=110) plt.close(fig) # ---- world residual heatmap --------------------------------------------------------- token_norm = np.linalg.norm(residual.reshape(8, 8, -1), axis=-1) fig2, axm = plt.subplots(figsize=(4.2, 4.0)) im = axm.imshow(token_norm, cmap="viridis") axm.set_title("Predicted world residual ||Delta_t||\nper DINO patch (8x8 pooled grid)") axm.set_xlabel("patch column") axm.set_ylabel("patch row") fig2.colorbar(im, ax=axm, shrink=0.85) fig2.tight_layout() fig2.savefig("/tmp/reswam_residual.png", dpi=110) plt.close(fig2) table = [[f"{v:.4f}" for v in row] for row in rows] return ( table, "/tmp/reswam_traj.png", "/tmp/reswam_residual.png", ) # -------------------------------------------------------------------------------------- # Examples (real LIBERO demonstration observations; CC-BY-4.0, see README) # -------------------------------------------------------------------------------------- def _load_example(name: str) -> list: payload = json.loads((ASSETS / f"{name}.json").read_text()) return [ str(ASSETS / f"{name}_head.png"), str(ASSETS / f"{name}_wrist.png"), str(payload["task"]), *[float(x) for x in payload["state"]], 0, ] EXAMPLES = [_load_example(f"example{i}") for i in (1, 2, 3)] EX1_STATE = json.loads((ASSETS / "example1.json").read_text())["state"] # -------------------------------------------------------------------------------------- # UI # -------------------------------------------------------------------------------------- CSS = """ #col-container { max-width: 1100px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ def build_ui() -> gr.Blocks: with gr.Blocks(title="ResWAM · LIBERO policy") as demo: gr.Markdown( """ # ResWAM: Learning What Changes, Not What Stays, for World-Action Models Single-step policy inference with the **ResWAM-LIBERO** checkpoint ([OPTML-Group/ResWAM-LIBERO](https://huggingface.co/OPTML-Group/ResWAM-LIBERO) · paper [2611.19559](https://huggingface.co/papers/2611.19559) · [code](https://github.com/OPTML-Group/ResWAM)). Give one head-camera and one wrist-camera observation, the task instruction, and the robot's 8-D proprioceptive state; ResWAM's 2.3B RynnBrain VLM + frozen DINOv3-B/16 + 0.5B dual-stream DiT predicts the next **8 actions** (7-D delta-EEF) in one shot via 10-step synchronous flow matching, along with its latent **world residual** — where the scene is predicted to change. """ ) with gr.Row(): with gr.Column(scale=1): head_in = gr.Image(label="Head / agentview camera (o_t)", type="pil", height=256) wrist_in = gr.Image(label="Wrist camera (o_t)", type="pil", height=256) instruction_in = gr.Textbox( label="Task instruction", placeholder="put the white mug on the left plate ...", value=DEFAULT_TASK, ) with gr.Accordion("Robot proprioceptive state (8-D raw)", open=False): state_inputs = [ gr.Number(label=STATE_COLS[i], value=EX1_STATE[i], precision=5) for i in range(STATE_DIM_RAW) ] seed_in = gr.Slider(0, 1000, value=0, step=1, label="Flow seed") run_btn = gr.Button("Predict action chunk", variant="primary") with gr.Column(scale=1): actions_out = gr.Dataframe( headers=ACTION_COLS, label="Predicted 8-step action chunk (delta-EEF [m/step], gripper ±1)", interactive=False, wrap=True, ) traj_out = gr.Image(label="End-effector path & gripper timeline") residual_out = gr.Image(label="Predicted world residual (what changes)") run_btn.click( predict, inputs=[head_in, wrist_in, instruction_in, *state_inputs, seed_in], outputs=[actions_out, traj_out, residual_out], ) gr.Examples( examples=EXAMPLES, inputs=[head_in, wrist_in, instruction_in, *state_inputs, seed_in], fn=predict, outputs=[actions_out, traj_out, residual_out], cache_examples=True, cache_mode="lazy", label="Real LIBERO demonstration observations (physical-intelligence/libero)", ) gr.Markdown( """ **Notes.** Actions are LIBERO 7-D delta-EEF (xyz, roll/pitch/yaw, binary gripper) decoded with the checkpoint's z-score statistics. The residual heatmap shows the L2 norm of the predicted latent change per 16x16-patch (2x2 pooled) DINOv3 token. Example observations come from the LIBERO demonstration dataset (physical-intelligence/libero, CC-BY-4.0). This Space runs a single observation step, not a closed-loop simulator rollout. """ ) return demo demo = build_ui() if __name__ == "__main__": demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)