"""O2LaF — interactive demo on Hugging Face ZeroGPU. * **Replay on a new scene** — the action encoder reads a source video and its latent actions drive the bidirectional world model from any first frame. * **Actions from video (IDM)** — the action tokens, a PCA view of the latent action space and the paper's action-query attention overlay. * **Atomic actions** — steer the world model with the shipped atomic actions. """ from __future__ import annotations import functools import sys import tempfile import time import traceback from pathlib import Path import spaces # must precede torch on ZeroGPU import gradio as gr import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import torch from PIL import Image ROOT = Path(__file__).parent sys.path.insert(0, str(ROOT / "O2LaF")) # vendored inference-only fork of showlab/O2LaF from o2laf import ActionAttentionExtractor, ActionGuidance, LatentActionPipeline # noqa: E402 from o2laf.inference.action_library import AtomicActionLibrary # noqa: E402 from o2laf.inference.video import load_source_video # noqa: E402 EXAMPLES_DIR = ROOT / "examples" MODELS = { "ego": ("YuxinJ/O2LaF/o2laf_dit_egodexmix", "Egocentric (egodexmix, 24 fps)"), "mixed": ("YuxinJ/O2LaF/o2laf_dit_mixed", "Third-person (mixed, 16 fps)"), } ATOMIC_ACTIONS = ["idle", "w", "s", "a", "d", "camera_up", "camera_down", "camera_left", "camera_right"] # (source video, first frame or None, model key). Cross-embodiment pairs come from # PH2D (human and Unitree H1 doing the same task on the same table), so only the # embodiment changes between the source video and the first frame. TRANSFER_EXAMPLES = [ ("ph2d_human_pick.mp4", "first_ph2d_robot_pick.png", "ego"), ("ph2d_human_pour.mp4", "first_ph2d_robot_pour.png", "ego"), ("ph2d_robot_pick.mp4", "first_ph2d_human_pick.png", "ego"), ("ego_wash_fruit.mp4", None, "ego"), ("ego_fry_bread.mp4", None, "ego"), ("ego_fry_egg.mp4", None, "ego"), ("ego_wash_kitchen_dishes.mp4", None, "ego"), ("gr1.mp4", None, "ego"), ("gta5.mp4", "first_west.png", "mixed"), ] IDM_EXAMPLES = [ ("ph2d_human_pick.mp4", "ego"), ("ph2d_robot_pick.mp4", "ego"), ("ego_wash_fruit.mp4", "ego"), ("ego_fry_bread.mp4", "ego"), ("ego_knit_scarf.mp4", "ego"), ("gr1.mp4", "ego"), ("gta5.mp4", "mixed"), ] # (source, matched reference or None, O2LaF output, caption) SHOWCASE = [ ("ph2d_human_pick.mp4", "ph2d_robot_pick.mp4", "out_ph2d_pick_h2r.mp4", "PH2D pick box: human -> Unitree H1, same table"), ("ph2d_human_pour.mp4", "ph2d_robot_pour.mp4", "out_ph2d_pour_h2r.mp4", "PH2D pour: human -> Unitree H1, same table"), ("ph2d_robot_pick.mp4", "ph2d_human_pick.mp4", "out_ph2d_pick_r2h.mp4", "PH2D pick box: Unitree H1 -> human, same table"), ("gta5.mp4", None, "out_gta5_to_west.mp4", "GTA5 walk -> wild west (mixed)"), ("ego_fry_bread.mp4", None, "out_egobread_self.mp4", "EgoDex fry bread — self-reconstruction"), ("ego_wash_fruit.mp4", None, "out_egofruit_self.mp4", "EgoDex wash fruit — self-reconstruction"), ("ego_fry_egg.mp4", None, "out_egoegg_self.mp4", "EgoDex fry egg — self-reconstruction"), ("ego_wash_kitchen_dishes.mp4", None, "out_egodishes_self.mp4", "EgoDex wash dishes — self-reconstruction"), ("gr1.mp4", None, "out_gr1_self.mp4", "GR-1 robot — self-reconstruction"), ] # ---------------------------------------------------------------- models # Loaded once at startup. On ZeroGPU, weights placed on "cuda" here stay in host # memory and are moved to the GPU at the start of each call, which takes seconds; # loading inside the @spaces.GPU function instead cost ~35 s on every call. PIPES = { key: LatentActionPipeline.from_pretrained(path, mode="bidirectional", device="cuda", dtype=torch.bfloat16) for key, (path, _) in MODELS.items() } PIPES["mixed"].vae = PIPES["ego"].vae # same Wan 2.2 VAE; keep one copy EXTRACTORS = {key: ActionAttentionExtractor.from_pipeline(pipe) for key, pipe in PIPES.items()} ATOMIC_LIBRARY = AtomicActionLibrary.from_pipeline(PIPES["mixed"]) # ---------------------------------------------------------------- helpers def gpu_task(fn): """Run on ZeroGPU and surface failures as a readable gr.Error (picklable across the worker boundary).""" @spaces.GPU(duration=120) @functools.wraps(fn) def wrapper(*args): start = time.perf_counter() try: return fn(*args) except gr.Error: raise except Exception as exc: traceback.print_exc() raise gr.Error(f"{type(exc).__name__}: {exc}") from None finally: print(f"[{fn.__name__}] {time.perf_counter() - start:.1f}s on {torch.cuda.get_device_name()}", flush=True) return wrapper def video_path(value) -> str: """Gradio video input -> local path (a str, or a VideoData-like object/dict).""" if isinstance(value, str): return value if isinstance(value, dict): value = value.get("video", value) return value["path"] if isinstance(value, dict) else value.path return value.video.path if hasattr(value, "video") else value.path def read_source(pipe, path: str) -> np.ndarray: """The source video at the model's fps, capped at the clip length its world model was trained on. Longer clips only extrapolate (and cost quadratically more attention).""" return load_source_video(path, pipe.fps, max_frames=pipe.num_rgb_frames) def read_image(path: str) -> np.ndarray: """An image file as one uint8 frame ``[1, H, W, 3]``.""" return np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)[None] def first_frame_latents(pipe, frame: np.ndarray) -> torch.Tensor: """Latents ``[1, C, 1, h, w]`` of one uint8 frame ``[1, H, W, 3]``.""" return pipe.encode_latents(pipe.preprocess_frames(frame)) def tmp_path(suffix: str) -> str: with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f: return f.name def render(pipe, latents) -> str: from diffusers.utils import export_to_video video = pipe.decode_latents(latents)[0].permute(0, 2, 3, 1).float().cpu().numpy() path = tmp_path(".mp4") export_to_video(list(video), path, fps=pipe.fps) return path def save_fig(fig) -> str: path = tmp_path(".png") fig.savefig(path, dpi=110, bbox_inches="tight") plt.close(fig) return path def actions_heatmap(actions: torch.Tensor, title: str) -> str: a = actions[0].float().cpu().numpy() fig, ax = plt.subplots(figsize=(9, 3.2)) im = ax.imshow(a.T, aspect="auto", cmap="viridis", interpolation="nearest", origin="lower") ax.set(xlabel="transition t -> t+1", ylabel="action dim", title=title) fig.colorbar(im, ax=ax, fraction=0.025, pad=0.01) fig.tight_layout() return save_fig(fig) def actions_pca(actions: torch.Tensor, anchors: dict[str, np.ndarray] | None) -> str: from sklearn.decomposition import PCA X = actions[0].float().cpu().numpy() A = np.stack(list(anchors.values())) if anchors else np.empty((0, X.shape[1])) pca = PCA(n_components=2).fit(np.concatenate([X, A])) fig, ax = plt.subplots(figsize=(5, 4.4)) z = pca.transform(X) sc = ax.scatter(z[:, 0], z[:, 1], c=np.arange(len(z)), cmap="viridis", s=28) if anchors: za = pca.transform(A) ax.scatter(za[:, 0], za[:, 1], marker="D", s=70, color="crimson", zorder=3) for name, (x, y) in zip(anchors, za): ax.annotate(name, (x, y), fontsize=7, xytext=(3, 3), textcoords="offset points", color="crimson") fig.colorbar(sc, ax=ax, fraction=0.04, pad=0.02, label="time") ax.set(title="Latent action space (PCA)", xlabel="PC 1", ylabel="PC 2") fig.tight_layout() return save_fig(fig) def atomic_vector(name: str) -> np.ndarray: return ATOMIC_LIBRARY.tensor(name, groups=1, device="cpu", dtype=torch.float32).reshape(-1).numpy() # ---------------------------------------------------------------- GPU entry points @gpu_task def run_transfer(source_video, first_frame, model_key, guidance, steps, seed): if not source_video: raise gr.Error("Pick or upload a source video first.") pipe = PIPES[model_key] source = read_source(pipe, video_path(source_video)) actions = pipe.encode_source_actions(source) frame = source[:1] if first_frame is None else read_image(first_frame) latents = pipe.generate_latents( actions=actions, first_frame_latents=first_frame_latents(pipe, frame), num_steps=int(steps), seed=int(seed), guidance=ActionGuidance(scale=float(guidance)), ) return render(pipe, latents), actions_heatmap(actions, "Latent actions driving the replay") @gpu_task def run_idm(source_video, model_key, block, head): if not source_video: raise gr.Error("Pick or upload a video first.") pipe = PIPES[model_key] path = video_path(source_video) actions = pipe.encode_source_actions(read_source(pipe, path)) anchors = {name: atomic_vector(name) for name in ATOMIC_ACTIONS} if model_key == "mixed" else None overlay = tmp_path(".mp4") EXTRACTORS[model_key].visualize(Path(path), Path(overlay), block=int(block), head=int(head)) return overlay, actions_heatmap(actions, "Action tokens: 32 dims per transition"), actions_pca(actions, anchors) @gpu_task def run_atomic(first_frame, action, num_frames, steps, seed): if first_frame is None: raise gr.Error("Pick or upload a first frame first.") pipe = PIPES["mixed"] groups = pipe.num_latent_frames_for(int(num_frames)) - pipe.num_context_frames latents = pipe.generate_latents( actions=ATOMIC_LIBRARY.tensor(action, groups=groups, device=pipe.device, dtype=pipe.dtype), first_frame_latents=first_frame_latents(pipe, read_image(first_frame)), num_steps=int(steps), seed=int(seed), guidance=ActionGuidance(scale=3.0), ) vec = atomic_vector(action) fig, ax = plt.subplots(figsize=(9, 2.6)) ax.bar(np.arange(len(vec)), vec, color="teal") ax.set(title=f"Atomic action token: {action} (32 dims)", xlabel="action dim") fig.tight_layout() return render(pipe, latents), save_fig(fig) # ---------------------------------------------------------------- UI def ex(name: str | None) -> str | None: return str(EXAMPLES_DIR / name) if name else None MODEL_CHOICES = [(label, key) for key, (_, label) in MODELS.items()] css = """ .gradio-container {max-width: 1100px !important; margin: 0 auto;} h1 {font-size: 1.6rem !important;} footer {visibility: hidden;} """ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo: gr.HTML( "
Encode actions from a video (IDM), then replay them on a new first frame (FDM). " "One 32-d token per frame pair.
" "" "Paper · " "Code · " "Project page · " "Checkpoints
" "" "The egocentric checkpoint fits hand manipulation; the mixed one adds third-person camera motion.
" ) with gr.Tabs(): with gr.Tab("Replay on a new scene"): gr.Markdown("Actions are read from the **source video** and replayed starting from the **first frame**.") with gr.Row(): with gr.Column(): src = gr.Video(label="Source video", sources=["upload"]) first = gr.Image(label="First frame (optional — own first frame)", sources=["upload"], type="filepath") model_radio = gr.Radio(MODEL_CHOICES, value="ego", label="Checkpoint") with gr.Accordion("Advanced", open=False): guidance = gr.Slider(1.0, 6.0, value=3.0, step=0.5, label="Action guidance") steps = gr.Slider(8, 30, value=12, step=1, label="Steps") seed = gr.Slider(0, 999, value=0, step=1, label="Seed") go = gr.Button("Generate", variant="primary") with gr.Column(): out_video = gr.Video(label="Generated video") out_heat = gr.Image(label="Latent actions used") gr.Examples( examples=[[ex(v), ex(f), m] for v, f, m in TRANSFER_EXAMPLES], inputs=[src, first, model_radio], examples_per_page=12, ) go.click(run_transfer, [src, first, model_radio, guidance, steps, seed], [out_video, out_heat]) with gr.Tab("Actions from video (IDM)"): gr.Markdown( "The encoder emits **one 32-d action token per frame pair**. The overlay video shows where each " "action query attends (hands, motion); tune the DiT block/head to inspect other layers." ) with gr.Row(): with gr.Column(): vid_in = gr.Video(label="Video", sources=["upload"]) model_radio2 = gr.Radio(MODEL_CHOICES, value="ego", label="Checkpoint") with gr.Accordion("Attention layer", open=False): block = gr.Slider(1, 30, value=30, step=1, label="DiT block") head = gr.Slider(0, 23, value=11, step=1, label="Head") go2 = gr.Button("Extract actions", variant="primary") with gr.Column(): attn_video = gr.Video(label="Action-query attention overlay") heat2 = gr.Image(label="Action tokens") pca2 = gr.Image(label="Latent action space") gr.Examples(examples=[[ex(v), m] for v, m in IDM_EXAMPLES], inputs=[vid_in, model_radio2]) go2.click(run_idm, [vid_in, model_radio2, block, head], [attn_video, heat2, pca2]) with gr.Tab("Atomic actions"): gr.Markdown( "Steer the world model directly with the shipped atomic action library " "(third-person checkpoint only): pick an action and a starting frame." ) with gr.Row(): with gr.Column(): atomic_frame = gr.Image(label="First frame", sources=["upload"], type="filepath") action = gr.Dropdown(ATOMIC_ACTIONS, value="w", label="Atomic action") n_frames = gr.Slider(21, 121, value=81, step=4, label="Frames") with gr.Accordion("Advanced", open=False): a_steps = gr.Slider(8, 30, value=12, step=1, label="Steps") a_seed = gr.Slider(0, 999, value=0, step=1, label="Seed") go3 = gr.Button("Generate", variant="primary") with gr.Column(): a_video = gr.Video(label="Generated video") a_plot = gr.Image(label="Action token") gr.Examples( examples=[[ex("first_west.png")], [ex("first_gta5.png")], [ex("first_gr1.png")]], inputs=[atomic_frame], ) go3.click(run_atomic, [atomic_frame, action, n_frames, a_steps, a_seed], [a_video, a_plot]) with gr.Tab("Showcase"): gr.Markdown( "Precomputed results (no GPU needed). Cross-embodiment rows show the matched demonstration of " "the other embodiment as a reference: O2LaF never sees it, only its first frame." ) for src_name, ref_name, out_name, caption in SHOWCASE: if not (EXAMPLES_DIR / out_name).exists(): continue gr.Markdown(f"**{caption}**") with gr.Row(): gr.Video(ex(src_name), label="Source (actions read from here)") if ref_name: gr.Video(ex(ref_name), label="Real demo of the target embodiment (reference)") gr.Video(ex(out_name), label="O2LaF replay") gr.HTML( "O2LaF: One for All — a single latent action " "model for egocentric and third-person video, built on Wan2.2 TI2V-5B. Demo assets from EgoDex (Apple) and " "PH2D (MIT).
" ) if __name__ == "__main__": demo.launch(show_error=True)