File size: 8,908 Bytes
0cde9e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63a11d4
0cde9e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5612e52
0cde9e0
 
 
 
 
bc8076e
0cde9e0
 
 
 
 
 
 
 
 
 
 
 
5612e52
0cde9e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5612e52
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
"""LDR — Extrapolative Video World Models via Latent Dynamics Reasoning.

Upload three conditioning frames, pick a task type, and the model rolls out
~29 future frames of physical motion (uniform, parabola, collision, looming,
or bouncing) and returns them as a video.
"""
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import spaces  # MUST be before torch
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gradio as gr
import tempfile
import imageio
import imageio.v3 as iio
from pathlib import Path
from huggingface_hub import hf_hub_download

from ldr import build_ldr

# ---------------------------------------------------------------------------
# Model loading (module scope — ZeroGPU intercepts .to("cuda"))
# ---------------------------------------------------------------------------

MODEL_ID = "haodongli/LDR"

# The joint-5task checkpoint handles all five tasks in one model.
# Single-task checkpoints are smaller but only work for one task.
# We load both 256x256 single-task and joint so users can pick.
CKPT_CONFIGS = {
    "uniform":   ("256x256/single_task/uniform.pt",   256),
    "parabola":  ("256x256/single_task/parabola.pt",  256),
    "collision": ("256x256/single_task/collision.pt", 256),
    "looming":   ("256x256/single_task/looming.pt",   256),
    "bouncing":  ("256x256/single_task/bouncing.pt",  256),
    "joint":     ("256x256/joint_task/joint_5task.pt", 256),
}

OURS_ARCH = dict(num_pred=29, width=256, accel_scale=0.5, n_kp=16,
                 warp_flow_res=64, kappa_init=0.15)


def _load_checkpoint(ckpt_path, img_size):
    """Load a .pt checkpoint into an LDR model (mirrors eval.build_model)."""
    ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    arch = dict(OURS_ARCH)
    cargs = ck.get("args") if isinstance(ck, dict) else None
    if cargs:
        arch.update(width=cargs.get("accel_width", 256),
                    n_kp=cargs.get("n_kp", 16),
                    accel_scale=cargs.get("accel_scale", 0.5),
                    kappa_init=cargs.get("kappa_init", cargs.get("accel_init_damp", 0.15)))
    model = build_ldr(**arch).to("cuda").eval()
    sd = ck["model"] if (isinstance(ck, dict) and "model" in ck) else ck
    sd = {k[7:] if k.startswith("module.") else k: v for k, v in sd.items()}
    model.load_state_dict(sd)
    return model


# Pre-download all checkpoints at module scope so they are on disk for the
# worker to stream.
_ckpt_cache = {}  # task_name -> (model, img_size)
for _task, (_rel, _img) in CKPT_CONFIGS.items():
    _path = hf_hub_download(MODEL_ID, _rel, repo_type="model")
    _model = _load_checkpoint(_path, _img)
    _ckpt_cache[_task] = (_model, _img)


def _get_model(task):
    return _ckpt_cache[task]


# ---------------------------------------------------------------------------
# Frame utilities (ported from infer.py)
# ---------------------------------------------------------------------------

def _resize(ft, fr, img_size):
    """Resize a frame tensor (N, 3, H, W) and its numpy companion to img_size."""
    if ft.shape[-1] != img_size:
        ft = nn.functional.interpolate(ft, size=(img_size, img_size),
                                       mode="bilinear", align_corners=False)
        fr = (((ft + 1) * 127.5).clamp(0, 255).byte().permute(0, 2, 3, 1).numpy())
    return ft, fr


def _load_frames(images, img_size):
    """Load a list of PIL images → (float_tensor [-1,1], numpy uint8 frames)."""
    fr = np.stack([np.asarray(img.convert("RGB")) for img in images], 0)
    ft = (torch.from_numpy(fr.astype(np.float32)).permute(0, 3, 1, 2) / 127.5 - 1.0)
    return _resize(ft, fr, img_size)


def _gen(model, frames_t, frames_np, nc):
    """Run the model and concatenate conditioning frames with predictions."""
    cond_t = frames_t[:nc].to("cuda")
    with torch.no_grad():
        pred = model(cond_t.unsqueeze(0), nc, full=False,
                      cond_img=cond_t[nc - 1:nc])
        pf = ((pred.squeeze(0).clamp(-1, 1) + 1) * 127.5).byte().cpu() \
              .permute(0, 2, 3, 1).numpy()
    return np.concatenate([frames_np[:nc], pf], axis=0)


# ---------------------------------------------------------------------------
# Inference function
# ---------------------------------------------------------------------------

@spaces.GPU(duration=30)
def generate(frame1, frame2, frame3, task="uniform",
             fps=8, progress=gr.Progress(track_tqdm=True)):
    """Roll out future video frames from three conditioning images.

    Args:
        frame1: First conditioning frame (earliest in the sequence).
        frame2: Second conditioning frame.
        frame3: Third conditioning frame (latest in the sequence).
        task: Physics task type — uniform, parabola, collision, looming, or bouncing.
             Use "joint" for the model trained on all five tasks.
        fps: Output video frames per second.
    Returns:
        Path to the generated MP4 video file.
    """
    model, img_size = _get_model(task)
    images = [frame1, frame2, frame3]
    ft, fr = _load_frames(images, img_size)
    all_frames = _gen(model, ft, fr, nc=3)

    # Write to a unique temp file (concurrency-safe)
    tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False, dir="/tmp")
    tmp.close()
    imageio.mimwrite(tmp.name, list(all_frames), fps=fps, codec="libx264",
                     quality=8, macro_block_size=1)
    return tmp.name


# ---------------------------------------------------------------------------
# Gradio UI
# ---------------------------------------------------------------------------

CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

with gr.Blocks() as demo:
    gr.Markdown("""
    # Latent Dynamics Reasoning (LDR)
    Upload three conditioning frames of a physical scene and the model
    extrapolates ~29 future frames as video. Pick the physics task type that
    matches your input (uniform motion, parabola, collision, looming, or
    bouncing), or use the **joint** model trained on all five.

    [Model](https://huggingface.co/haodongli/LDR) ·
    [Code](https://github.com/Lat-Dyn-Reason/Lat-Dyn-Reason) ·
    [Project Page](https://lat-dyn-reason.github.io/)
    """)

    with gr.Row():
        with gr.Column(scale=3):
            frame1 = gr.Image(label="Frame 1 (t=0)", type="pil",
                              height=200)
            frame2 = gr.Image(label="Frame 2 (t=1)", type="pil",
                              height=200)
            frame3 = gr.Image(label="Frame 3 (t=2)", type="pil",
                              height=200)
        with gr.Column(scale=2):
            task = gr.Dropdown(
                choices=["uniform", "parabola", "collision", "looming",
                         "bouncing", "joint"],
                value="uniform",
                label="Task / Checkpoint",
                info="Match the physics type of your scene. "
                     "'joint' handles all five but slightly lower quality.")
            fps = gr.Slider(4, 16, value=8, step=1, label="Output FPS")
            run = gr.Button("Generate Video", variant="primary")

    output = gr.Video(label="Generated Video (conditioning + prediction)")

    with gr.Accordion("Examples", open=True):
        gr.Examples(
            examples=[
                # [frame1, frame2, frame3, task, fps]
                ["examples/uniform/00.png", "examples/uniform/01.png",
                 "examples/uniform/02.png", "uniform", 8],
                ["examples/parabola/00.png", "examples/parabola/01.png",
                 "examples/parabola/02.png", "parabola", 8],
                ["examples/collision/00.png", "examples/collision/01.png",
                 "examples/collision/02.png", "collision", 8],
                ["examples/looming/00.png", "examples/looming/01.png",
                 "examples/looming/02.png", "looming", 8],
                ["examples/bouncing/00.png", "examples/bouncing/01.png",
                 "examples/bouncing/02.png", "bouncing", 8],
                ["examples/uniform_pikachu/00.png",
                 "examples/uniform_pikachu/01.png",
                 "examples/uniform_pikachu/02.png", "uniform", 8],
                ["examples/uniform_soccer/00.png",
                 "examples/uniform_soccer/01.png",
                 "examples/uniform_soccer/02.png", "uniform", 8],
            ],
            inputs=[frame1, frame2, frame3, task, fps],
            outputs=output,
            fn=generate,
            cache_examples=True,
            cache_mode="lazy",
        )

    run.click(
        fn=generate,
        inputs=[frame1, frame2, frame3, task, fps],
        outputs=output,
        api_name="generate",
    )


if __name__ == "__main__":
    demo.launch(mcp_server=True, theme=gr.themes.Citrus(), css=CSS)