Spaces:
Sleeping
Sleeping
File size: 16,794 Bytes
d775356 19583ce d775356 19583ce 18a5625 d775356 96ec2ac 06de6e8 d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 96ec2ac d775356 96ec2ac 19583ce 96ec2ac 19583ce d775356 96ec2ac d775356 5fdc717 d775356 5fdc717 d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce 96ec2ac 19583ce 96ec2ac d775356 19583ce 96ec2ac 19583ce d775356 19583ce d775356 19583ce 22fb356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce 96ec2ac d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce 96ec2ac 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 5fdc717 d775356 19583ce d775356 22fb356 d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 19583ce d775356 22fb356 19583ce d775356 19583ce d775356 5fdc717 d775356 19583ce d775356 22fb356 d775356 19583ce d775356 19583ce d775356 5fdc717 6925657 5fdc717 d775356 5fdc717 d775356 5fdc717 d775356 d033720 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | """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(
"<h1>O2LaF β Latent Actions for Video Generation</h1>"
"<p style='margin:0 0 6px'>Encode actions from a video (IDM), then replay them on a new first frame (FDM). "
"One 32-d token per frame pair.</p>"
"<p style='margin:0 0 4px'>"
"<a href='https://arxiv.org/abs/2511.20490' target='_blank'>Paper</a> Β· "
"<a href='https://github.com/showlab/O2LaF' target='_blank'>Code</a> Β· "
"<a href='https://showlab.github.io/o2laf/' target='_blank'>Project page</a> Β· "
"<a href='https://huggingface.co/YuxinJ/O2LaF' target='_blank'>Checkpoints</a></p>"
"<p style='margin:0 0 8px;font-size:0.9em;color:var(--body-text-color-subdued)'>"
"The egocentric checkpoint fits hand manipulation; the mixed one adds third-person camera motion.</p>"
)
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(
"<p style='font-size:0.85em;color:var(--body-text-color-subdued)'>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 "
"<a href='https://human-as-robot.github.io/' target='_blank'>PH2D</a> (MIT).</p>"
)
if __name__ == "__main__":
demo.launch(show_error=True)
|