File size: 12,823 Bytes
c31e109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e1d5b0
c31e109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e1d5b0
c31e109
 
 
 
 
 
 
 
 
 
 
 
3e1d5b0
c31e109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aced06
 
 
 
 
 
c31e109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aced06
c31e109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aced06
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
import os

os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import spaces  # must precede torch / diffusers

import json
import tempfile
import time
from pathlib import Path

import gradio as gr
import imageio.v3 as iio
import numpy as np
import torch
from accelerate import init_empty_weights
from diffusers import Cosmos3OmniPipeline, Cosmos3OmniTransformer
from diffusers.pipelines.cosmos.pipeline_cosmos3_omni import CosmosActionCondition
from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
from huggingface_hub import hf_hub_download, snapshot_download
from PIL import Image, ImageDraw
from safetensors.torch import load_file

BASE_ID = "nvidia/Cosmos3-Nano"  # diffusers-format VAE / tokenizer / transformer config
MODEL_ID = "WorldReforge/Cosmos3-Nano-WorldReforge"  # fine-tuned DiT weights (Cosmos framework layout)
DATA_ID = "WorldReforge/Reforge-Eval"

# Reference inference settings from the WorldReforge repo (docs/data_format.md, inference/nano.py)
DOMAIN = "droid_lerobot"
VIEW_POINT = "concat_view"
FPS = 15
CHUNK = 16
DEFAULT_SEED = 62100
DEFAULT_STEPS = 30
SHIFT = 10.0


# ---------------------------------------------------------------------------
# Model: diffusers Cosmos3OmniTransformer populated with WorldReforge weights
# ---------------------------------------------------------------------------
def remap_key(k: str) -> str:
    """Cosmos-framework checkpoint key -> diffusers Cosmos3OmniTransformer key."""
    k = k.removeprefix("model.net.")
    k = k.replace("language_model.model.", "").replace("language_model.lm_head", "lm_head")
    k = k.replace("vae2llm.", "proj_in.").replace("llm2vae.", "proj_out.")
    k = k.replace("action2llm.", "action_proj_in.").replace("llm2action.", "action_proj_out.")
    k = k.replace("time_embedder.mlp.0.", "time_embedder.linear_1.").replace("time_embedder.mlp.2.", "time_embedder.linear_2.")
    for a, b in [
        ("q_proj_moe_gen", "add_q_proj"), ("k_proj_moe_gen", "add_k_proj"), ("v_proj_moe_gen", "add_v_proj"),
        ("o_proj_moe_gen", "to_add_out"), ("q_norm_moe_gen", "norm_added_q"), ("k_norm_moe_gen", "norm_added_k"),
        ("self_attn.q_proj", "self_attn.to_q"), ("self_attn.k_proj", "self_attn.to_k"),
        ("self_attn.v_proj", "self_attn.to_v"), ("self_attn.o_proj", "self_attn.to_out"),
        ("self_attn.q_norm", "self_attn.norm_q"), ("self_attn.k_norm", "self_attn.norm_k"),
    ]:
        k = k.replace(a, b)
    return k


def load_worldreforge_transformer() -> Cosmos3OmniTransformer:
    cfg = json.load(open(hf_hub_download(BASE_ID, "transformer/config.json")))
    cfg["sound_gen"] = False  # WorldReforge checkpoint ships no sound projections
    with init_empty_weights():  # params on meta, buffers (rotary inv_freq) stay real
        transformer = Cosmos3OmniTransformer.from_config(cfg)
    ckpt_dir = Path(snapshot_download(MODEL_ID, allow_patterns=["*.safetensors", "*.json"]))
    expected = set(transformer.state_dict().keys())
    loaded = set()
    for shard in sorted(ckpt_dir.glob("model-*.safetensors")):
        sd = {remap_key(k): v for k, v in load_file(str(shard)).items()}
        transformer.load_state_dict(sd, strict=False, assign=True)
        loaded |= set(sd)
        del sd
    missing, unexpected = expected - loaded, loaded - expected
    if missing or unexpected:
        raise RuntimeError(f"Weight mismatch: missing={sorted(missing)[:5]} unexpected={sorted(unexpected)[:5]}")
    # checkpoint tensors are already bf16; keep fp32 buffers (rotary inv_freq) untouched
    transformer.time_embedder.to(torch.float32)  # diffusers keeps time_embedder in fp32
    return transformer.eval()


transformer = load_worldreforge_transformer()
pipe = Cosmos3OmniPipeline.from_pretrained(
    BASE_ID,
    transformer=transformer,
    sound_tokenizer=None,
    enable_safety_checker=False,
    use_native_flow_schedule=True,
    torch_dtype=torch.bfloat16,
)
# Native flow-UniPC schedule with shift=10, as in the WorldReforge reference inference.
pipe.scheduler = UniPCMultistepScheduler.from_config(
    pipe.scheduler.config, use_karras_sigmas=False, use_flow_sigmas=True, flow_shift=SHIFT
)
pipe.to("cuda")


# ---------------------------------------------------------------------------
# Examples: Reforge-Eval windows, fetched from the authors' dataset at startup
# ---------------------------------------------------------------------------
EXAMPLES = [
    ("c56f4e59b037773458fc718d", "Mustard bottle, gripper shifted ~9 mm at first contact"),
    ("1663a975224502fcad59f48e", "Ceramic mug, gripper yawed -10 deg at first contact"),
    ("4976fe00b8cc4c1cd648298b", "Banana, weaker gripper closure (x0.7) after contact"),
    ("e1c6c09a3c947081c1699ec0", "Rubik's cube, stronger gripper closure (x1.3)"),
    ("2221ca7d6a366a182865750c", "Apple, 21 mm offset along closing axis"),
    ("1060695f6afa02c8b58149a9", "Red mug, 40 mm offset against closing axis"),
]
EX_DIR = Path(__file__).parent / "examples"
example_rows = []
for sid, caption in EXAMPLES:
    try:
        paths = {
            f: hf_hub_download(DATA_ID, f"samples/{sid}/{f}", repo_type="dataset", local_dir=EX_DIR)
            for f in ("condition.png", "actions.json", "gt.npy")
        }
        actions = json.load(open(paths["actions.json"]))
        example_rows.append([paths["condition.png"], json.dumps([[round(v, 6) for v in r] for r in actions]), sid])
    except Exception as e:  # keep the app usable even if the dataset is temporarily unreachable
        print(f"Could not fetch example {sid}: {e!r}")


def parse_actions(text: str) -> torch.Tensor:
    try:
        data = json.loads(text)
    except json.JSONDecodeError as e:
        raise gr.Error(f"Actions must be valid JSON: {e}")
    arr = np.asarray(data, dtype=np.float32)
    if arr.ndim != 2 or arr.shape[1] != 10 or not (1 <= arr.shape[0] <= CHUNK):
        raise gr.Error(f"Actions must be a list of 1-{CHUNK} rows with 10 values each, got shape {arr.shape}.")
    if not np.isfinite(arr).all():
        raise gr.Error("Actions contain non-finite values.")
    return torch.from_numpy(arr)


def _label(frame: np.ndarray, text: str) -> np.ndarray:
    img = Image.fromarray(frame)
    d = ImageDraw.Draw(img)
    d.rectangle([0, 0, 8 * len(text) + 16, 24], fill=(0, 0, 0))
    d.text((8, 6), text, fill=(255, 255, 255))
    return np.asarray(img)


def _write_mp4(frames: np.ndarray, path: Path) -> str:
    iio.imwrite(path, frames, fps=FPS, codec="libx264", quality=9, macro_block_size=16)
    return str(path)


def _rollout(image: Image.Image, actions: torch.Tensor, seed: int, steps: int) -> np.ndarray:
    generator = torch.Generator(device="cuda").manual_seed(int(seed))
    out = pipe(
        prompt="",
        action=CosmosActionCondition(
            mode="forward_dynamics",
            chunk_size=CHUNK,
            domain_name=DOMAIN,
            resolution_tier=480,
            raw_actions=actions,
            image=image,
            view_point=VIEW_POINT,
        ),
        fps=FPS,
        num_inference_steps=int(steps),
        guidance_scale=1.0,
        generator=generator,
        output_type="np",
    )
    video = np.asarray(out.video)
    if video.ndim == 5:
        video = video[0]
    return (np.clip(video, 0, 1) * 255).round().astype(np.uint8)


def _gpu_duration(image, actions_json, sample_id="", seed=DEFAULT_SEED, steps=DEFAULT_STEPS, *args, **kwargs):
    # measured ~11 s for 30 steps on ZeroGPU large (+~15% and a few seconds for video encoding)
    return int(4 + 0.43 * int(steps or DEFAULT_STEPS)) + 1


@spaces.GPU(duration=_gpu_duration)
def predict(
    image: Image.Image,
    actions_json: str,
    sample_id: str = "",
    seed: int = DEFAULT_SEED,
    steps: int = DEFAULT_STEPS,
    progress=gr.Progress(track_tqdm=True),
):
    """Roll out the WorldReforge world model from one conditioning frame and a robot action chunk.

    Args:
        image: Three-view RGB mosaic (wrist view on top, two external views below), e.g. 1280x1080 Reforge-Eval/DROID layout.
        actions_json: JSON list of up to 16 rows x 10 values: normalized end-effector transition (3D translation +
            6D rotation) followed by 1 - gripper closure, in the Reforge-Eval normalized convention.
        sample_id: Optional Reforge-Eval sample id; when set, the simulator ground truth is shown side by side.
        seed: Random seed for the diffusion noise.
        steps: Number of denoising steps.

    Returns:
        Path to the predicted 17-frame rollout video, path to the prediction-vs-ground-truth video, and timing info.
    """
    if image is None:
        raise gr.Error("Please provide a conditioning image.")
    actions = parse_actions(actions_json)
    image = image.convert("RGB") if isinstance(image, Image.Image) else Image.fromarray(image).convert("RGB")
    t0 = time.perf_counter()
    video = _rollout(image, actions, int(seed), int(steps))
    elapsed = time.perf_counter() - t0

    out_dir = Path(tempfile.mkdtemp(prefix="worldreforge_"))
    pred_path = _write_mp4(video, out_dir / "prediction.mp4")

    gt_file = EX_DIR / "samples" / str(sample_id or "").strip() / "gt.npy"
    if sample_id and gt_file.is_file():
        gt = np.load(gt_file)
        n = min(len(gt), len(video))
        h = min(gt.shape[1], video.shape[1]); w = min(gt.shape[2], video.shape[2])
        pairs = [np.concatenate([_label(video[i, :h, :w], "WorldReforge prediction"),
                                 _label(gt[i, :h, :w], "Simulator ground truth")], axis=1) for i in range(n)]
        cmp_path = _write_mp4(np.stack(pairs), out_dir / "comparison.mp4")
        info = f"Rollout: {video.shape[0]} frames at {video.shape[2]}x{video.shape[1]}, {elapsed:.1f}s. Compared with sample {sample_id}."
    else:
        cmp_path = pred_path
        info = f"Rollout: {video.shape[0]} frames at {video.shape[2]}x{video.shape[1]}, {elapsed:.1f}s. No ground truth for custom inputs."
    return pred_path, cmp_path, info


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

with gr.Blocks(title="WorldReforge") as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            "# WorldReforge: Cosmos3 Nano robot world model\n"
            "Action-conditioned video world model from *Beyond the Happy Path: Generalizing Robot World Models from "
            "Simulated Failures*. Give it one three-view frame and 16 robot state transitions, and it predicts the next "
            "17 frames (~1 s at 15 FPS), including what happens when a grasp goes wrong.\n\n"
            "[Paper](https://huggingface.co/papers/2611.33925) 路 [Code](https://github.com/aim-uofa/WorldReforge) 路 "
            "[Model](https://huggingface.co/WorldReforge/Cosmos3-Nano-WorldReforge) 路 "
            "[Reforge-Eval](https://huggingface.co/datasets/WorldReforge/Reforge-Eval)"
        )
        with gr.Row():
            with gr.Column():
                image_in = gr.Image(label="Conditioning frame (wrist view on top, two external views below)", type="pil", height=360)
                actions_in = gr.Code(
                    label="Action chunk: 16 x [dx, dy, dz, r11, r21, r31, r12, r22, r32, 1-gripper] (normalized)",
                    language="json", lines=8, max_lines=12,
                )
                sample_in = gr.Textbox(label="Reforge-Eval sample id (optional, for ground-truth comparison)", max_lines=1)
                run = gr.Button("Predict rollout", variant="primary")
            with gr.Column():
                pred_out = gr.Video(label="Predicted rollout", autoplay=True, loop=True)
                cmp_out = gr.Video(label="Prediction vs. simulator ground truth", autoplay=True, loop=True)
                info_out = gr.Markdown()
        with gr.Accordion("Advanced settings", open=False):
            seed_in = gr.Number(label="Seed", value=DEFAULT_SEED, precision=0)
            steps_in = gr.Slider(label="Denoising steps", minimum=10, maximum=50, step=1, value=DEFAULT_STEPS)

        run.click(predict, inputs=[image_in, actions_in, sample_in, seed_in, steps_in],
                  outputs=[pred_out, cmp_out, info_out], api_name="predict")

        if example_rows:
            gr.Markdown("### Reforge-Eval examples (perturbed grasps from the paper's benchmark)")
            gr.Examples(
                examples=example_rows,
                example_labels=[c for (sid, c) in EXAMPLES if any(r[2] == sid for r in example_rows)],
                inputs=[image_in, actions_in, sample_in],
                outputs=[pred_out, cmp_out, info_out],
                fn=predict,
                cache_examples=True,
                cache_mode="lazy",
            )

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