File size: 17,401 Bytes
2d27f16
 
 
 
ab9a2db
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab9a2db
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5b2326
 
 
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42ed079
 
 
 
 
 
 
 
 
f5b2326
42ed079
 
 
 
 
 
 
 
 
 
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab9a2db
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab9a2db
2d27f16
 
 
 
 
 
 
 
f5b2326
2d27f16
 
 
 
 
 
 
 
 
 
 
f5b2326
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
ab9a2db
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5b2326
 
 
 
 
2d27f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5b2326
 
 
 
 
 
 
 
 
 
 
 
2d27f16
f5b2326
2d27f16
 
 
 
 
 
 
 
 
f5b2326
 
 
2d27f16
 
 
 
 
 
 
 
ab9a2db
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import spaces  # must come before torch / CUDA-touching imports

import os
import tempfile
import time
from fractions import Fraction

import av
import gradio as gr
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from safetensors.torch import load_file

from solarwm.backends.wan22.ref2va.cores import Ref2VAWanBDCore
from solarwm.backends.wan22.ref2va.data import Ref2VAWanSample
from solarwm.backends.wan22.ref2va.model import Ref2VAWanModel
from solarwm.backends.wan22.runtime.components import Wan5BVAE
from solarwm.backends.wan22.runtime.modeling.t5 import umt5_xxl
from solarwm.backends.wan22.runtime.modeling.tokenizers import HuggingfaceTokenizer

# ----------------------------------------------------------------------------------- geometry
# GameWM-Wan2.2-5B (GameWM-engine GEOMETRY["wan2.2-5b"]): 121 frames, 24 fps, 1280x704 target,
# 640x352 proxy video. Latents: 31 frames, 44x80 target grid, 22x40 proxy grid.
FPS = 24
FRAMES = 121
WIDTH, HEIGHT = 1280, 704
PROXY_WIDTH, PROXY_HEIGHT = 640, 352
SHEET_SHORT_EDGE = 1024  # protocol: <Picture 2> is scaled to short edge 1024
SPAN = "[0.00s-5.17s]"  # the training captions' span, kept verbatim for every backbone
SHEET_PROMPT = (
    "<Picture 2> is the protagonist identity sheet (front / left profile / back). The character the "
    "camera follows is the <Picture 2> character in every frame, also while turning or entering and "
    "leaving the frame. Identity only: camera, pose, motion and framing come from <Video 1>."
)

CONFIG = {
    "model": {"family": "wan22_ti2v_5b"},
    "data": {
        "encoded_latents": 31,
        "latent_height": 44,
        "latent_width": 80,
        "proxy_latent_height": 22,
        "proxy_latent_width": 40,
        "num_given_latent_frames": 1,
        "align_proxy_reference_time": False,
        "chunk_latents": 5,
        "window_chunks": 6,
        "train_target_latents": 31,
    },
    "train": {"timestep_shift": 5.0},
}

REPO = "binghe-sjtu/GameWM"
VARIANT = "GameWM-Wan2.2-5B/BD-Sheet"  # character sheet optional (trained with 20% sheet dropout)
BASE = "Wan-AI/Wan2.2-TI2V-5B"

# ------------------------------------------------------------------------------------ loading
device = torch.device("cuda")

student_path = hf_hub_download(REPO, f"{VARIANT}/student.safetensors")
vae_path = hf_hub_download(BASE, "Wan2.2_VAE.pth")
t5_path = hf_hub_download(BASE, "models_t5_umt5-xxl-enc-bf16.pth")
for name in ("special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"):
    tok_file = hf_hub_download(BASE, f"google/umt5-xxl/{name}")
tokenizer_dir = os.path.dirname(tok_file)

# Transformer: the released GameWM student is a full fine-tune of Wan2.2-TI2V-5B.
with torch.device("meta"):
    transformer = Ref2VAWanModel("wan22_ti2v_5b")
state = load_file(student_path, device="cpu")
state = {k: v.to(torch.bfloat16) for k, v in state.items()}
transformer.load_state_dict(state, strict=True, assign=True)
del state
transformer = transformer.eval().requires_grad_(False).to(device)

# umT5-XXL text encoder (bf16)
text_encoder = umt5_xxl(
    encoder_only=True, return_tokenizer=False, dtype=torch.bfloat16, device="meta"
)
text_encoder.load_state_dict(
    torch.load(t5_path, map_location="cpu", weights_only=True), strict=True, assign=True
)
text_encoder = text_encoder.to(torch.bfloat16).eval().requires_grad_(False).to(device)
tokenizer = HuggingfaceTokenizer(name=tokenizer_dir, seq_len=512, clean="whitespace")

# Wan2.2 48-channel VAE
vae = Wan5BVAE(vae_path).to(device, dtype=torch.bfloat16)

core = Ref2VAWanBDCore(transformer, device, CONFIG)


# ------------------------------------------------------------------------------ preprocessing
def cover(image: Image.Image, size: tuple[int, int], resample=Image.LANCZOS) -> Image.Image:
    """Scale to cover ``size`` and centre-crop (the transform the VM applies to <Picture 1>)."""
    w, h = size
    scale = max(w / image.width, h / image.height)
    resized = image.resize(
        (max(w, round(image.width * scale)), max(h, round(image.height * scale))), resample
    )
    left, top = (resized.width - w) // 2, (resized.height - h) // 2
    return resized.crop((left, top, left + w, top + h))


def read_proxy(path: str, modality: str) -> np.ndarray:
    """Proxy video -> [121, 352, 640, 3] uint8 at 24 fps (whole-frame selection, last frame held)."""
    container = av.open(path)
    stream = container.streams.video[0]
    rate = float(stream.average_rate or stream.guessed_rate or FPS)
    frames = [f.to_image() for f in container.decode(video=0)]
    container.close()
    if not frames:
        raise gr.Error("The proxy video has no frames.")
    picks = []
    for i in range(FRAMES):
        src = int(np.floor(i * rate / FPS + 1e-3))
        picks.append(frames[min(src, len(frames) - 1)])
    resample = Image.NEAREST if modality in ("semantic", "duv") else Image.LANCZOS
    out = []
    for im in picks:
        im = im.convert("RGB")
        if modality == "depth":
            im = im.convert("L").convert("RGB")
        out.append(np.asarray(cover(im, (PROXY_WIDTH, PROXY_HEIGHT), resample)))
    return np.stack(out)


def to_pixels(frames: np.ndarray) -> torch.Tensor:
    """[T, H, W, 3] uint8 -> [1, 3, T, H, W] in [-1, 1] on the GPU."""
    x = torch.from_numpy(np.ascontiguousarray(frames).copy()).to(device).permute(3, 0, 1, 2).float()
    return (x / 127.5 - 1.0).unsqueeze(0).to(torch.bfloat16)


@torch.no_grad()
def encode(frames: np.ndarray) -> torch.Tensor:
    """VAE latents [C, T, h, w] (fp32) of [T, H, W, 3] uint8 pixels."""
    return vae.encode(to_pixels(frames))[0].permute(1, 0, 2, 3).float()


def sheet_size(image: Image.Image) -> tuple[int, int]:
    scale = SHEET_SHORT_EDGE / min(image.width, image.height)
    w = max(32, int(round(image.width * scale / 32)) * 32)
    h = max(32, int(round(image.height * scale / 32)) * 32)
    return w, h


@torch.no_grad()
def encode_text(text: str) -> torch.Tensor:
    ids, mask = tokenizer([text], return_mask=True, add_special_tokens=True)
    ids, mask = ids.to(device), mask.to(device)
    length = int(mask.gt(0).sum())
    context = text_encoder(ids, mask)
    return context[0, :length].float()


def build_document(caption: str, modality: str, has_sheet: bool) -> str:
    caption = caption.strip()
    if has_sheet and "from the identity sheet" not in caption:
        # protocol: the subject reads "The protagonist from the identity sheet" when a sheet is given
        caption = caption.replace("The protagonist,", "The protagonist from the identity sheet,", 1)
    if not caption.startswith("["):
        caption = f"{SPAN} {caption}"
    lines = [f"Reference modality: {modality} video."]
    if has_sheet:
        lines.append(SHEET_PROMPT)
    lines.append(caption)
    return "\n".join(lines)


def write_mp4(pixels_tchw: torch.Tensor, path: str) -> None:
    frames = pixels_tchw.float().add(1).mul(127.5).round().clamp(0, 255).to(torch.uint8)
    frames = frames.permute(0, 2, 3, 1).cpu().numpy()
    container = av.open(path, mode="w")
    stream = container.add_stream("libx264", rate=Fraction(FPS, 1))
    stream.width, stream.height = frames.shape[2], frames.shape[1]
    stream.pix_fmt = "yuv420p"
    stream.options = {"crf": "18", "movflags": "+faststart"}
    for frame in frames:
        for packet in stream.encode(av.VideoFrame.from_ndarray(frame, format="rgb24")):
            container.mux(packet)
    for packet in stream.encode():
        container.mux(packet)
    container.close()


# ---------------------------------------------------------------------------------- inference
try:
    import flash_attn  # noqa: F401  (the vendored dense_attention uses FlashAttention-2 when present)

    ATTENTION = "flash_attn"
except ImportError:
    ATTENTION = "sdpa"
print(f"[gamewm] attention backend: {ATTENTION}", flush=True)

# Measured GPU seconds per denoising step (plus fixed encode/decode cost), see the build log.
SECONDS_PER_STEP = {"flash_attn": 6.2, "sdpa": 7.4}
FIXED_SECONDS = 15.0


def gpu_duration(proxy_video, first_frame, caption, character_sheet=None, modality="style",
                 steps=30, seed=0, progress=None) -> int:
    per_step = SECONDS_PER_STEP[ATTENTION] * (1.07 if character_sheet is not None else 1.0)
    return int(1.15 * (FIXED_SECONDS + per_step * (int(steps) - 1))) + 1


@spaces.GPU(duration=gpu_duration)
def generate(
    proxy_video: str,
    first_frame: Image.Image,
    caption: str,
    character_sheet: Image.Image | None = None,
    modality: str = "style",
    steps: int = 30,
    seed: int = 0,
    progress=gr.Progress(track_tqdm=True),
) -> str:
    """Turn a coarse game-engine proxy video into a finished game clip with GameWM-Wan2.2-5B.

    Args:
        proxy_video: The engine's proxy render (grey-box / capsule / depth / semantic video) from the player's camera; resampled to 121 frames at 24 fps, 640x352.
        first_frame: <Picture 1>, scene concept art painted over the proxy's opening camera view (objects where proxy frame 0 has them).
        caption: Take caption: "{medium} captures {setting}. {lighting}. The protagonist, {look}, {action}. {camera}".
        character_sheet: Optional <Picture 2> identity sheet (front / side / back) of the protagonist.
        modality: What the proxy frames are: style, depth, semantic or duv.
        steps: Number of shifted-Euler grid points (the authors use 30).
        seed: Noise seed.

    Returns:
        Path to the generated 1280x704, 121-frame, 24 fps MP4.
    """
    if not proxy_video:
        raise gr.Error("Upload a proxy video.")
    if first_frame is None:
        raise gr.Error("Upload a first frame (<Picture 1>).")
    if not caption or not caption.strip():
        raise gr.Error("Write a caption.")

    started = time.perf_counter()
    progress(0, desc="Encoding references")
    proxy = read_proxy(proxy_video, modality)
    anchor = np.asarray(cover(first_frame.convert("RGB"), (WIDTH, HEIGHT)))[None]

    proxy_latent = encode(proxy)  # [48, 31, 22, 40]
    anchor_latent = encode(anchor)  # [48, 1, 44, 80]
    pictures = [anchor_latent]
    has_sheet = character_sheet is not None
    if has_sheet:
        sheet = character_sheet.convert("RGB")
        sheet = sheet.resize(sheet_size(sheet), Image.LANCZOS)
        pictures.append(encode(np.asarray(sheet)[None]))

    target = torch.zeros((48, 31, 44, 80), dtype=torch.float32, device=device)
    target[:, :1] = anchor_latent  # the leading latent is given from <Picture 1>
    prompt = encode_text(build_document(caption, modality, has_sheet))

    sample = Ref2VAWanSample(
        sample_id="gradio",
        target=target,
        proxy=proxy_latent,
        pictures=tuple(pictures),
        prompt=prompt,
        i2v_latent=None,
        info={},
        fingerprint="",
    )

    progress(0.05, desc="Denoising")
    latents = core.generate(sample, noise_seed=int(seed), num_inference_steps=int(steps))
    core.release_caches()
    torch.cuda.empty_cache()

    progress(0.95, desc="Decoding video")
    with torch.no_grad():
        pixels = vae.decode(latents.permute(0, 2, 1, 3, 4).to(torch.bfloat16), use_cache=False)[0]
    out = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
    write_mp4(pixels, out)
    print(f"[gamewm] steps={steps} sheet={has_sheet} gpu_seconds={time.perf_counter() - started:.1f}", flush=True)
    return out


# ----------------------------------------------------------------------------------------- UI
FIRE_CAPTION = (
    "[0.00s-5.17s] A 3D video game captures a walled sandstone training courtyard in an autumn old "
    "town with three wooden training dummies on round stands, stacked wooden crates and square "
    "sandstone pillars. Bright clear afternoon sunlight casts soft shadows across the paving. The "
    "protagonist from the identity sheet, a young dark-haired man in a dark red leather coat with a crimson hood holding a "
    "short wand, stands loose and ready, the wand low in his right hand, then walks toward the center "
    "training dummy with an easy stride, his free arm swinging and red coat flapping, then raises his "
    "wand to shoulder height at the center training dummy, a flame gathering at its tip, and hurls a "
    "fireball that bursts into flames on it, rocking it back on its stand, then raises his wand again "
    "and hurls another fireball at the center training dummy, rocking it back on its stand. The camera "
    "follows from behind the protagonist."
)
ICE_CAPTION = (
    "[0.00s-5.17s] A 3D video game captures a snow-covered walled stone training courtyard in a "
    "northern winter town with three wooden training dummies on round stands, frosted crates and "
    "square stone pillars hung with icicles. Cold pale winter daylight lights the snow. The "
    "protagonist from the identity sheet, a silver-haired woman in a white and blue fur-trimmed robe with a long blue cape "
    "holding an ice-crystal staff, stands poised, staff upright at her side, her cape stirring in the "
    "wind, then walks toward the center training dummy with a graceful stride through the snow, her "
    "blue cape swaying, then levels her ice-crystal staff at the center training dummy at shoulder "
    "height, frost swirling around its head, and fires an ice shard that shatters into frost on it, "
    "rocking it back on its stand, then levels her staff again and fires another ice shard at the "
    "center training dummy, rocking it back on its stand. The camera follows from behind the "
    "protagonist."
)

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

with gr.Blocks() as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            "# 馃幃 GameWM-Wan2.2-5B\n"
            "The engine decides *where everything is and what happens*; the video model decides "
            "*how it looks*. Give a coarse engine **proxy video** (grey-box / capsule render from the "
            "player's camera), a painted **first frame** of the opening view and a caption, and "
            "GameWM turns the proxy into a finished 5 s game clip (1280脳704, 24 fps).\n\n"
            "[Paper](https://huggingface.co/papers/2611.19247) 路 "
            "[Project page](https://game-world-model.github.io/) 路 "
            "[Code](https://github.com/hebing-sjtu/GameWM) 路 "
            "[Weights](https://huggingface.co/binghe-sjtu/GameWM)"
        )
        with gr.Row():
            with gr.Column():
                with gr.Row():
                    proxy_in = gr.Video(label="Proxy video (<Video 1>)", height=230)
                    first_in = gr.Image(label="First frame (<Picture 1>)", type="pil", height=230)
                    sheet_in = gr.Image(
                        label="Character sheet (<Picture 2>, optional)", type="pil", height=230
                    )
                caption_in = gr.Textbox(
                    label="Caption",
                    lines=6,
                    placeholder="A 3D video game captures <setting>. <lighting>. The protagonist, "
                    "<look>, <action>. <camera>",
                )
                run = gr.Button("Generate", variant="primary")
                with gr.Accordion("Advanced settings", open=False):
                    modality_in = gr.Dropdown(
                        ["style", "depth", "semantic", "duv"],
                        value="style",
                        label="Proxy modality",
                    )
                    steps_in = gr.Slider(10, 40, value=30, step=1, label="Sampling steps")
                    seed_in = gr.Number(value=0, precision=0, label="Seed")
            with gr.Column():
                video_out = gr.Video(label="Generated clip", autoplay=True, height=420)

        gr.Examples(
            examples=[
                [
                    "examples/training_ground_proxy.mp4",
                    "examples/01_fire_mage_first_frame.jpg",
                    FIRE_CAPTION,
                    "examples/01_fire_mage_sheet.jpg",
                ],
                [
                    "examples/training_ground_proxy.mp4",
                    "examples/02_ice_mage_first_frame.jpg",
                    ICE_CAPTION,
                    "examples/02_ice_mage_sheet.jpg",
                ],
            ],
            inputs=[proxy_in, first_in, caption_in, sheet_in],
            outputs=video_out,
            fn=generate,
            cache_examples=True,
            cache_mode="lazy",
        )
        gr.Markdown(
            "Example proxy rendered with the authors' GameWM-engine *training ground* (capsule "
            "proxy, two fireball casts resolved by the engine); captions composed by the engine's "
            "own `compose.caption`; first frames painted over the proxy's opening view with "
            "Qwen-Image-Edit-2511 using the engine's `restyle_prompt`, and character sheets made from "
            "those first frames with the same model. A character sheet noticeably tightens how "
            "closely the clip follows the proxy."
        )

    run.click(
        generate,
        inputs=[proxy_in, first_in, caption_in, sheet_in, modality_in, steps_in, seed_in],
        outputs=video_out,
    )

demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)