blanchon commited on
Commit
d775356
·
verified ·
1 Parent(s): d766b4b

app: tabs for transfer, IDM, atomic actions, showcase

Browse files
Files changed (1) hide show
  1. app.py +432 -0
app.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """O2LaF — interactive demo on Hugging Face ZeroGPU.
2
+
3
+ Three live panels on top of the `o2laf` package:
4
+
5
+ * **Actions from video (IDM)** — the latent action encoder reads a video and
6
+ emits one 32-d action token per transition (t -> t+1). Shows the action-token
7
+ heatmap, a PCA view of the latent action space and the paper's action-query
8
+ attention overlay (which queries attend to hands and motion).
9
+ * **Replay on a new scene (FDM)** — transfer: the encoder's actions drive the
10
+ bidirectional world model to replay the motion from any first frame.
11
+ * **Atomic actions (FDM)** — steer the world model directly with the shipped
12
+ atomic action library (idle / w / a / s / d / camera moves).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import gc
18
+ import os
19
+ import tempfile
20
+ import threading
21
+ from pathlib import Path
22
+
23
+ import spaces # must precede torch/gradio on ZeroGPU
24
+
25
+ import gradio as gr
26
+ import matplotlib
27
+ import matplotlib.pyplot as plt
28
+ import numpy as np
29
+ import torch
30
+
31
+ matplotlib.use("Agg")
32
+
33
+ REPO_ID = "YuxinJ/O2LaF"
34
+ EXAMPLES_DIR = Path(__file__).parent / "examples"
35
+
36
+ MODELS = {
37
+ "ego": {"path": f"{REPO_ID}/o2laf_dit_egodexmix", "label": "Egocentric (egodexmix, 24 fps)"},
38
+ "mixed": {"path": f"{REPO_ID}/o2laf_dit_mixed", "label": "Third-person (mixed, 16 fps)"},
39
+ }
40
+ ATOMIC_ACTIONS = ["idle", "w", "s", "a", "d", "camera_up", "camera_down", "camera_left", "camera_right"]
41
+
42
+ # (source video, first frame or None, model key, caption)
43
+ TRANSFER_EXAMPLES = [
44
+ ("ego_wash_fruit.mp4", None, "ego", "Wash fruit -> own first frame"),
45
+ ("ego_fry_bread.mp4", None, "ego", "Fry bread -> own first frame"),
46
+ ("ego_fry_egg.mp4", None, "ego", "Fry egg -> own first frame"),
47
+ ("ego_wash_kitchen_dishes.mp4", None, "ego", "Wash dishes -> own first frame"),
48
+ ("ego_wash_fruit.mp4", "first_gr1.png", "ego", "Wash fruit -> GR-1 robot"),
49
+ ("ego_knit_scarf.mp4", "first_gr1.png", "ego", "Knit scarf -> GR-1 robot"),
50
+ ("ego_fry_bread.mp4", "first_gr1.png", "ego", "Fry bread -> GR-1 robot"),
51
+ ("ego_knit_scarf.mp4", "first_west.png", "mixed", "Knit scarf -> wild west"),
52
+ ("gta5.mp4", "first_west.png", "mixed", "GTA5 walk -> wild west"),
53
+ ]
54
+ IDM_EXAMPLES = [
55
+ ("ego_wash_fruit.mp4", "ego"),
56
+ ("ego_fry_bread.mp4", "ego"),
57
+ ("ego_fry_egg.mp4", "ego"),
58
+ ("ego_knit_scarf.mp4", "ego"),
59
+ ("gr1.mp4", "ego"),
60
+ ("gta5.mp4", "mixed"),
61
+ ]
62
+ SHOWCASE = [
63
+ ("ego_fry_bread.mp4", "out_egobread_self.mp4", "EgoDex fry bread — self-reconstruction (egodexmix)"),
64
+ ("ego_wash_fruit.mp4", "out_egofruit_self.mp4", "EgoDex wash fruit — self-reconstruction (egodexmix)"),
65
+ ("ego_fry_egg.mp4", "out_egoegg_self.mp4", "EgoDex fry egg — self-reconstruction (egodexmix)"),
66
+ ("ego_wash_kitchen_dishes.mp4", "out_egodishes_self.mp4", "EgoDex wash dishes — self-reconstruction (egodexmix)"),
67
+ ("gr1.mp4", "out_gr1_self.mp4", "GR-1 robot — self-reconstruction (egodexmix)"),
68
+ ("ego_wash_fruit.mp4", "out_egofruit_to_robot.mp4", "Human wash fruit -> GR-1 robot (egodexmix)"),
69
+ ("ego_knit_scarf.mp4", "out_egoknit_to_robot.mp4", "Human knit scarf -> GR-1 robot (egodexmix)"),
70
+ ("ego_fry_bread.mp4", "out_egobread_to_robot.mp4", "Human fry bread -> GR-1 robot (egodexmix)"),
71
+ ("ego_knit_scarf.mp4", "out_egoknit_to_west.mp4", "Human knit scarf -> wild west (mixed)"),
72
+ ("gta5.mp4", "out_gta5_to_west.mp4", "GTA5 walk -> wild west (mixed)"),
73
+ ]
74
+
75
+ _gpu_objects: list[tuple[str, object]] = [] # LRU: (key, pipeline/extractor)
76
+
77
+
78
+ def _evict_if_full():
79
+ while len(_gpu_objects) >= 2:
80
+ _, obj = _gpu_objects.pop(0)
81
+ del obj
82
+ gc.collect()
83
+ torch.cuda.empty_cache()
84
+
85
+
86
+ def _touch(key, obj):
87
+ _gpu_objects.append((key, obj))
88
+
89
+
90
+ def get_pipe(model_key: str):
91
+ key = f"pipe:{model_key}"
92
+ for i, (k, obj) in enumerate(_gpu_objects):
93
+ if k == key:
94
+ _gpu_objects.pop(i)
95
+ _gpu_objects.append((key, obj))
96
+ return obj
97
+ _evict_if_full()
98
+ from o2laf import LatentActionPipeline
99
+
100
+ pipe = LatentActionPipeline.from_pretrained(
101
+ MODELS[model_key]["path"], mode="bidirectional", device="cuda", dtype=torch.bfloat16
102
+ )
103
+ _touch(key, pipe)
104
+ return pipe
105
+
106
+
107
+ def get_extractor(model_key: str):
108
+ key = f"attn:{model_key}"
109
+ for i, (k, obj) in enumerate(_gpu_objects):
110
+ if k == key:
111
+ _gpu_objects.pop(i)
112
+ _gpu_objects.append((key, obj))
113
+ return obj
114
+ _evict_if_full()
115
+ from o2laf.inference.attention import ActionAttentionExtractor
116
+
117
+ extractor = ActionAttentionExtractor.from_pretrained(
118
+ MODELS[model_key]["path"], device="cuda", dtype=torch.bfloat16
119
+ )
120
+ _touch(key, extractor)
121
+ return extractor
122
+
123
+
124
+ def _video_to_tmp_path(video_file) -> str:
125
+ """gradio video input -> local path on disk."""
126
+ return video_file if isinstance(video_file, str) else video_file.name
127
+
128
+
129
+ def export_video(frames: torch.Tensor, fps: float) -> str:
130
+ from diffusers.utils import export_to_video
131
+
132
+ path = tempfile.mktemp(suffix=".mp4")
133
+ out = frames.permute(0, 2, 3, 1).float().clamp(0, 1).cpu().numpy()
134
+ export_to_video(list(out), path, fps=fps)
135
+ return path
136
+
137
+
138
+ def actions_heatmap(actions: torch.Tensor, title: str):
139
+ a = actions[0].float().cpu().numpy()
140
+ fig, ax = plt.subplots(figsize=(9, 3.2))
141
+ im = ax.imshow(a.T, aspect="auto", cmap="viridis", interpolation="nearest", origin="lower")
142
+ ax.set_xlabel("transition t -> t+1")
143
+ ax.set_ylabel("action dim")
144
+ ax.set_title(title)
145
+ fig.colorbar(im, ax=ax, fraction=0.025, pad=0.01)
146
+ fig.tight_layout()
147
+ return fig
148
+
149
+
150
+ def actions_pca(actions: torch.Tensor, anchors: dict[str, np.ndarray] | None = None):
151
+ from sklearn.decomposition import PCA
152
+
153
+ X = actions[0].float().cpu().numpy()
154
+ points = [X]
155
+ names = []
156
+ if anchors:
157
+ A = np.stack(list(anchors.values()))
158
+ points.append(A)
159
+ names = list(anchors.keys())
160
+ pca = PCA(n_components=2).fit(np.concatenate(points, axis=0))
161
+ fig, ax = plt.subplots(figsize=(5, 4.4))
162
+ z = pca.transform(X)
163
+ sc = ax.scatter(z[:, 0], z[:, 1], c=np.arange(len(z)), cmap="viridis", s=28)
164
+ if anchors:
165
+ za = pca.transform(A)
166
+ ax.scatter(za[:, 0], za[:, 1], marker="D", s=70, color="crimson", zorder=3)
167
+ for name, (x, y) in zip(names, za):
168
+ ax.annotate(name, (x, y), fontsize=7, xytext=(3, 3), textcoords="offset points", color="crimson")
169
+ fig.colorbar(sc, ax=ax, fraction=0.04, pad=0.02, label="time")
170
+ ax.set_title("Latent action space (PCA)")
171
+ ax.set_xlabel("PC 1")
172
+ ax.set_ylabel("PC 2")
173
+ fig.tight_layout()
174
+ return fig
175
+
176
+
177
+ def _atomic_anchors(pipe) -> dict[str, np.ndarray] | None:
178
+ """Atomic action centroids as anchors for the PCA plot (mixed model only)."""
179
+ try:
180
+ from o2laf.inference.action_library import AtomicActionLibrary
181
+
182
+ library = AtomicActionLibrary.from_pipeline(pipe)
183
+ groups = pipe.num_latent_frames_for(pipe.num_rgb_frames) - pipe.num_context_frames
184
+ return {
185
+ name: library.tensor(name, groups=groups, device="cpu", dtype=torch.float32)
186
+ .reshape(-1)
187
+ .numpy()
188
+ for name in ATOMIC_ACTIONS
189
+ }
190
+ except Exception:
191
+ return None
192
+
193
+
194
+ # ---------------------------------------------------------------- GPU entry points
195
+
196
+
197
+ @spaces.GPU(duration=240)
198
+ def run_transfer(source_video, first_frame, model_key, guidance, steps, seed):
199
+ if not source_video:
200
+ raise gr.Error("Pick or upload a source video first.")
201
+ from o2laf import ActionGuidance
202
+ from o2laf.inference.cli.common import load_source_video
203
+
204
+ pipe = get_pipe(model_key)
205
+ path = _video_to_tmp_path(source_video)
206
+ source = load_source_video(Path(path), pipe.fps)
207
+ actions = pipe.encode_source_actions(source)
208
+ if first_frame is None:
209
+ first_pixels = source[:1]
210
+ else:
211
+ from PIL import Image
212
+
213
+ first_pixels = np.asarray(Image.open(first_frame).convert("RGB"), dtype=np.uint8)[None]
214
+ first = pipe.encode_latents(pipe.preprocess_frames(first_pixels))[:, :1]
215
+ latents = pipe.generate_latents(
216
+ actions=actions,
217
+ first_frame_latents=first,
218
+ num_steps=int(steps),
219
+ seed=int(seed),
220
+ guidance=ActionGuidance(scale=float(guidance)),
221
+ )
222
+ video = pipe.decode_latents(latents)[0]
223
+ return export_video(video, pipe.fps), actions_heatmap(actions, "Latent actions driving the replay")
224
+
225
+
226
+ @spaces.GPU(duration=240)
227
+ def run_idm(source_video, model_key, block, head):
228
+ if not source_video:
229
+ raise gr.Error("Pick or upload a video first.")
230
+ pipe = get_pipe(model_key)
231
+ path = _video_to_tmp_path(source_video)
232
+ from o2laf.inference.cli.common import load_source_video
233
+
234
+ source = load_source_video(Path(path), pipe.fps)
235
+ actions = pipe.encode_source_actions(source)
236
+ fig_heat = actions_heatmap(actions, "Action tokens: 32 dims per transition")
237
+ fig_pca = actions_pca(actions, _atomic_anchors(pipe) if model_key == "mixed" else None)
238
+ extractor = get_extractor(model_key)
239
+ out_path = tempfile.mktemp(suffix=".mp4")
240
+ extractor.visualize(Path(path), Path(out_path), block=int(block), head=int(head))
241
+ return out_path, fig_heat, fig_pca
242
+
243
+
244
+ @spaces.GPU(duration=240)
245
+ def run_atomic(first_frame, action, num_frames, steps, seed):
246
+ if first_frame is None:
247
+ raise gr.Error("Pick or upload a first frame first.")
248
+ from o2laf import ActionGuidance
249
+ from o2laf.inference.action_library import AtomicActionLibrary
250
+ from o2laf.inference.cli.common import load_first_frame
251
+ from PIL import Image
252
+
253
+ if isinstance(first_frame, dict):
254
+ raise gr.Error("Unexpected first-frame input.")
255
+ frame = np.asarray(Image.open(first_frame).convert("RGB"), dtype=np.uint8)
256
+ pipe = get_pipe("mixed")
257
+ library = AtomicActionLibrary.from_pipeline(pipe)
258
+ num_frames = int(num_frames)
259
+ groups = pipe.num_latent_frames_for(num_frames) - pipe.num_context_frames
260
+ actions = library.tensor(action, groups=groups, device=pipe.device, dtype=pipe.dtype)
261
+ first = pipe.encode_latents(pipe.preprocess_frames(frame))
262
+ first = first[:, :1]
263
+ latents = pipe.generate_latents(
264
+ actions=actions,
265
+ first_frame_latents=first,
266
+ num_steps=int(steps),
267
+ seed=int(seed),
268
+ guidance=ActionGuidance(scale=3.0),
269
+ )
270
+ video = pipe.decode_latents(latents)[0]
271
+ vec = library.tensor(action, groups=1, device="cpu", dtype=torch.float32).reshape(-1).numpy()
272
+ fig, ax = plt.subplots(figsize=(9, 2.6))
273
+ ax.bar(np.arange(len(vec)), vec, color="teal")
274
+ ax.set_title(f"Atomic action token: {action} (32 dims)")
275
+ ax.set_xlabel("action dim")
276
+ fig.tight_layout()
277
+ return export_video(video, pipe.fps), fig
278
+
279
+
280
+ # ---------------------------------------------------------------- startup prefetch
281
+
282
+
283
+ def _prefetch():
284
+ try:
285
+ from huggingface_hub import snapshot_download
286
+
287
+ snapshot_download(REPO_ID)
288
+ snapshot_download("Wan-AI/Wan2.2-TI2V-5B-Diffusers")
289
+ except Exception as exc: # never block the UI on prefetch
290
+ print(f"prefetch failed: {exc}")
291
+
292
+
293
+ threading.Thread(target=_prefetch, daemon=True).start()
294
+
295
+
296
+ # ---------------------------------------------------------------- UI
297
+
298
+
299
+ def ex_path(name: str) -> str:
300
+ return str(EXAMPLES_DIR / name)
301
+
302
+
303
+ def example_rows(entries):
304
+ return [[ex_path(v) if v else None for v in row[:3]] for row in entries]
305
+
306
+
307
+ css = """
308
+ .gradio-container {max-width: 1100px !important; margin: 0 auto;}
309
+ h1 {font-size: 1.6rem !important;}
310
+ footer {visibility: hidden;}
311
+ """
312
+
313
+ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="O2LaF") as demo:
314
+ gr.HTML(
315
+ "<h1>O2LaF — Latent Actions for Video Generation</h1>"
316
+ "<p style='margin:0 0 6px'>Encode actions from a video (IDM), then replay them on a new first frame (FDM). "
317
+ "One 32-d token per frame pair.</p>"
318
+ "<p style='margin:0 0 4px'>"
319
+ "<a href='https://arxiv.org/abs/2511.20490' target='_blank'>Paper</a> · "
320
+ "<a href='https://github.com/showlab/O2LaF' target='_blank'>Code</a> · "
321
+ "<a href='https://showlab.github.io/o2laf/' target='_blank'>Project page</a> · "
322
+ "<a href='https://huggingface.co/YuxinJ/O2LaF' target='_blank'>Checkpoints</a></p>"
323
+ "<p style='margin:0 0 8px;font-size:0.9em;color:var(--body-text-color-subdued)'>"
324
+ "First generation per model builds it (~1 min extra); later runs are ~20-45 s. "
325
+ "The egocentric checkpoint fits hand manipulation; the mixed one adds third-person camera motion.</p>"
326
+ )
327
+
328
+ with gr.Tabs():
329
+ with gr.Tab("Replay on a new scene"):
330
+ gr.Markdown("Actions are read from the **source video** and replayed starting from the **first frame**.")
331
+ with gr.Row():
332
+ with gr.Column(scale=1):
333
+ src = gr.Video(label="Source video", sources=["upload"])
334
+ first = gr.Image(label="First frame (optional — own first frame)", sources=["upload"], type="filepath")
335
+ model_radio = gr.Radio(
336
+ [(v["label"], k) for k, v in MODELS.items()],
337
+ value="ego",
338
+ label="Checkpoint",
339
+ )
340
+ with gr.Accordion("Advanced", open=False):
341
+ guidance = gr.Slider(1.0, 6.0, value=3.0, step=0.5, label="Action guidance")
342
+ steps = gr.Slider(8, 30, value=20, step=1, label="Steps")
343
+ seed = gr.Slider(0, 999, value=0, step=1, label="Seed")
344
+ go = gr.Button("Generate", variant="primary")
345
+ with gr.Column(scale=1):
346
+ out_video = gr.Video(label="Generated video")
347
+ out_heat = gr.Plot(label="Latent actions used")
348
+ gr.Examples(
349
+ examples=example_rows(TRANSFER_EXAMPLES),
350
+ inputs=[src, first, model_radio],
351
+ examples_per_page=12,
352
+ )
353
+ go.click(
354
+ run_transfer,
355
+ inputs=[src, first, model_radio, guidance, steps, seed],
356
+ outputs=[out_video, out_heat],
357
+ )
358
+
359
+ with gr.Tab("Actions from video (IDM)"):
360
+ gr.Markdown(
361
+ "The encoder emits **one 32-d action token per frame pair**. The overlay video shows where each "
362
+ "action query attends (hands, motion); tune the DiT block/head to inspect other layers."
363
+ )
364
+ with gr.Row():
365
+ with gr.Column(scale=1):
366
+ vid_in = gr.Video(label="Video", sources=["upload"])
367
+ model_radio2 = gr.Radio(
368
+ [(v["label"], k) for k, v in MODELS.items()],
369
+ value="ego",
370
+ label="Checkpoint",
371
+ )
372
+ with gr.Accordion("Attention layer", open=False):
373
+ block = gr.Slider(1, 30, value=30, step=1, label="DiT block")
374
+ head = gr.Slider(0, 23, value=11, step=1, label="Head")
375
+ go2 = gr.Button("Extract actions", variant="primary")
376
+ with gr.Column(scale=1):
377
+ attn_video = gr.Video(label="Action-query attention overlay")
378
+ heat2 = gr.Plot(label="Action tokens")
379
+ pca2 = gr.Plot(label="Latent action space")
380
+ gr.Examples(
381
+ examples=example_rows([(v, m) for v, m in IDM_EXAMPLES]),
382
+ inputs=[vid_in, model_radio2],
383
+ examples_per_page=12,
384
+ )
385
+ go2.click(run_idm, inputs=[vid_in, model_radio2, block, head], outputs=[attn_video, heat2, pca2])
386
+
387
+ with gr.Tab("Atomic actions"):
388
+ gr.Markdown(
389
+ "Steer the world model directly with the shipped atomic action library "
390
+ "(third-person checkpoint only): pick an action and a starting frame."
391
+ )
392
+ with gr.Row():
393
+ with gr.Column(scale=1):
394
+ atomic_frame = gr.Image(label="First frame", sources=["upload"], type="filepath")
395
+ action = gr.Dropdown(ATOMIC_ACTIONS, value="w", label="Atomic action")
396
+ n_frames = gr.Slider(21, 121, value=81, step=4, label="Frames")
397
+ with gr.Accordion("Advanced", open=False):
398
+ a_steps = gr.Slider(8, 30, value=20, step=1, label="Steps")
399
+ a_seed = gr.Slider(0, 999, value=0, step=1, label="Seed")
400
+ go3 = gr.Button("Generate", variant="primary")
401
+ with gr.Column(scale=1):
402
+ a_video = gr.Video(label="Generated video")
403
+ a_plot = gr.Plot(label="Action token")
404
+ gr.Examples(
405
+ examples=[[ex_path("first_west.png")], [ex_path("first_gta5.png")], [ex_path("first_gr1.png")]],
406
+ inputs=[atomic_frame],
407
+ )
408
+ go3.click(
409
+ run_atomic,
410
+ inputs=[atomic_frame, action, n_frames, a_steps, a_seed],
411
+ outputs=[a_video, a_plot],
412
+ )
413
+
414
+ with gr.Tab("Showcase"):
415
+ gr.Markdown("Precomputed egocentric results (no GPU needed to browse).")
416
+ for i in range(0, len(SHOWCASE), 2):
417
+ with gr.Row():
418
+ for src_name, out_name, caption in SHOWCASE[i : i + 2]:
419
+ with gr.Column():
420
+ gr.Markdown(f"**{caption}**")
421
+ with gr.Row():
422
+ gr.Video(ex_path(src_name), label="Source")
423
+ gr.Video(ex_path(out_name), label="O2LaF replay")
424
+
425
+ gr.HTML(
426
+ "<p style='font-size:0.85em;color:var(--body-text-color-subdued)'>O2LaF: One for All — a single latent action "
427
+ "model for egocentric and third-person video, built on Wan2.2 TI2V-5B. Demo assets from EgoDex (Apple).</p>"
428
+ )
429
+
430
+
431
+ if __name__ == "__main__":
432
+ demo.launch()