Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/solarrenderer-2: direct link, hf CLI and curl.
- Browser
- Download file 35.8 kB
-
https://huggingface.co/spaces/hugging-apps/solarrenderer-2/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/solarrenderer-2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/solarrenderer-2/resolve/main/app.py
35.8 kB
| """SolarRenderer on MiniMax-H3 — a structure video to a finished clip in four steps. | |
| `Enderfga/SolarRenderer` is a pair of rank-384 LoRAs for MiniMax-H3's `ref2va` partition: a control LoRA | |
| that reads a structure video (grey box, semantic map, skeletons, depth, a sketch the model never saw) | |
| frame by frame, and a four-step LoRA (fine-tuned from DMAD) that renders in four model evaluations. | |
| The inputs are encoded exactly as `scripts/render.py` + `tools/omni_preencode.py` encode a training | |
| sample: the structure video laid over every target frame, the optional first frame over latent 0, the | |
| six-part prompt through Qwen3-VL's `ref2va` presentation. | |
| This Space is the denoising half of a split deployment. MiniMax-H3 is 195.9 GiB in bfloat16 and a | |
| ZeroGPU Space is evicted at 150 GB of storage, so the 62 GiB Qwen3-VL conditioner lives in | |
| [`multimodalart/qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner): | |
| every request calls `/encode_ref2va` over the gradio API for `prompt_embeds` + `text_token_tags` | |
| (billed to the visitor's own ZeroGPU token), and this Space loads only the `transformer_ref` partition | |
| plus the float32 video VAE. The reference latents — the target, the structure video, the first-frame | |
| still — are computed here locally with the same `encode_vae_condition` recipe the released pipeline uses | |
| (posterior sampled at seed 42, rounded to fp16, normalized), which is exactly what `omni_preencode`'s | |
| conditioned chain produces. | |
| Hardware note: the authors run flash-attention 2; ZeroGPU's card is sm120, where only cuDNN's fused | |
| attention is available, so the transformer runs `_native_cudnn` instead. That is the one deviation from | |
| `scripts/render.py`, and it changes the attention kernel, not the math. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import traceback | |
| from functools import cache | |
| from pathlib import Path | |
| # Set before torch initializes CUDA. The renoise loop allocates and frees a whole-sequence | |
| # activation set four times over, and the fp32 decoder sits on the card across the encode phase; | |
| # without expandable segments the caching allocator fragments and the next allocation dies with | |
| # `NVML_SUCCESS == r INTERNAL ASSERT FAILED` instead of a clean OOM. The other H3 Spaces in this | |
| # org set the same flag for the same reason. | |
| os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| # Before anything that could initialize CUDA: `import spaces` patches `torch.cuda` so the 33B | |
| # transformer can be loaded at startup onto the emulated device (pack placement). | |
| import spaces | |
| import gradio as gr | |
| import torch | |
| HERE = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(HERE / "src")) | |
| VERSION = "solarrenderer/1" | |
| MODEL_REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3") | |
| LORA_REPO = os.environ.get("SOLAR_LORA_REPO", "Enderfga/SolarRenderer") | |
| CONTROL_FILE = os.environ.get("SOLAR_CONTROL_FILE", "solarrenderer_control_lora.safetensors") | |
| FEWSTEP_FILE = os.environ.get("SOLAR_FEWSTEP_FILE", "solarrenderer_4step_lora.safetensors") | |
| CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner") | |
| # cuDNN's fused attention: flash-attn 2 has no sm120 kernel; this is the same backend the other H3 | |
| # Spaces in this org run. | |
| ATTENTION = os.environ.get("H3_ATTENTION", "_native_cudnn").lower() | |
| GPU_SIZE = os.environ.get("H3_GPU_SIZE", "xlarge") | |
| RANK = ALPHA = 384 | |
| FRAMES = 158 | |
| FPS = 24 | |
| # The canvas table the conditioner serves; only these two can be a SolarRenderer canvas, because the | |
| # structure video's own aspect ratio decides it (768x1344 landscape / 1344x768 portrait). | |
| CANVASES = { | |
| "1344x768 · 16:9 full": (768, 1344), | |
| "768x1344 · 9:16 full": (1344, 768), | |
| } | |
| DEFAULT_CANVAS = "1344x768 · 16:9 full" | |
| # Clip lengths the demo offers, in frames of the 17*n+5 form. 158 is the release default (the | |
| # authors' own example); the shorter ones trade length for ZeroGPU latency. | |
| DEFAULT_FRAMES = 158 | |
| FRAME_CHOICES = [158, 107, 73] | |
| # A still laid over the target is encoded as video (H3 takes no video shorter than this), and only its | |
| # first latent is kept: the causal VAE's first latent sees the first frame alone. | |
| STILL_FRAMES = 13 | |
| IMAGE_EXT = (".png", ".jpg", ".jpeg", ".webp", ".bmp") | |
| SILENCE = HERE / "h3_silence_153_158_170.safetensors" | |
| # The fitted duration model of the other H3 Spaces in this org (seconds of GPU per denoise loop): | |
| # linear in packed rows for the matmuls, quadratic for attention, 1.15 safety on top. | |
| STEP_LINEAR, STEP_QUADRATIC, SAFETY = 1.1745e-4, 3.8396e-9, 1.15 | |
| DECODE_BASE, DECODE_PER_DEFAULT_CANVAS, DEFAULT_CANVAS_PIXELS = 15, 15, 960 * 544 * 124 | |
| # Pack placement of the 61.7 GiB transformer: ~12 s on a cold worker, plus 10 s of pad. | |
| PLACEMENT_ALLOWANCE, PAD = 12, 10 | |
| MIN_GPU_DURATION, MAX_GPU_DURATION = 120, 1500 | |
| CORE = None | |
| CONDITIONERS = None | |
| VAE = None | |
| LOAD_ERROR: str | None = None | |
| # ── geometry and duration arithmetic ────────────────────────────────────────── | |
| def snap_frames(seconds: float) -> int: | |
| """The frame count MiniMax-H3's video VAE decodes: the next `17 * n + 5` at 24 fps.""" | |
| frames = max(1, round(float(seconds) * FPS)) | |
| while frames % 17 != 5: | |
| frames += 1 | |
| return frames | |
| def video_latent_frames(num_frames: int) -> int: | |
| """`17 * n + 5` frames become `5 * n + 2` video latents.""" | |
| return 5 * ((num_frames - 5) // 17) + 2 | |
| def packed_rows(num_frames: int, prompt_rows: int, height: int = 768, width: int = 1344) -> int: | |
| """Rows of the packed document one request denoises, from the geometry alone. | |
| Text prompt rows + the two observations (the structure video aligned with every target frame and | |
| the first-frame still) + the target video rows + the silence audio rows. The structure video is | |
| the target's own geometry, so its rows equal the target's. | |
| """ | |
| patches = (height // 32) * (width // 32) | |
| target = video_latent_frames(num_frames) * patches | |
| structure = target | |
| still = 1 * patches | |
| audio = round(num_frames / FPS * 40) * 2 | |
| return prompt_rows + structure + still + target + audio | |
| def get_duration(prompt_embeds, text_token_tags, structure_video, first_frame, height, width, | |
| num_frames, seed, forwards, *_, **__): | |
| """Seconds of GPU to reserve for one request, from its packed row count. Takes the arguments of the | |
| `@spaces.GPU` function it decorates, positionally — so its signature mirrors `_generate`'s and reads | |
| the canvas off the `height` / `width` that `generate` resolved. 4 evaluations always (the four-step | |
| LoRA's count).""" | |
| height, width = int(height), int(width) | |
| sequence = packed_rows(int(num_frames), int(text_token_tags.shape[0]), height, width) | |
| denoise = int(forwards) * (STEP_LINEAR * sequence + STEP_QUADRATIC * sequence**2) * SAFETY | |
| # One full-length local VAE encode — the structure video's latents *are* the target latents (the | |
| # render clones them), so there is a single canvas-sized pass, not two — plus the decode + mux. The | |
| # still is 13 frames, an eighth of one pass, and rides inside the pad below. | |
| encode = DECODE_BASE + DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / DEFAULT_CANVAS_PIXELS | |
| decode = DECODE_BASE + DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / DEFAULT_CANVAS_PIXELS | |
| total = PLACEMENT_ALLOWANCE + encode + denoise + decode + PAD | |
| duration = max(MIN_GPU_DURATION, min(MAX_GPU_DURATION, int(total))) | |
| print(f"[{VERSION}] S={sequence} -> reserving {duration}s ({denoise:.0f}s of denoise at {forwards} steps)", flush=True) | |
| return duration | |
| # ── the SolarRenderer renderer (render.py's load_renderer, verbatim in structure) ─ | |
| def load_renderer() -> str | None: | |
| """The Ref2VA transformer with the four-step LoRA merged in and the control LoRA on top. | |
| Same order as `scripts/render.py`: `merge_lora_delta` folds the four-step LoRA into the bf16 | |
| weights (fp32 accumulation, alpha=rank so factor 1.0), then `inject_h3_lora` wraps the merged | |
| transformer in a live PEFT adapter that the control LoRA's tensors are loaded into. The control | |
| LoRA has to stay live rather than merged because its targets were trained *on top of* the | |
| four-step weights. | |
| """ | |
| global CORE, CONDITIONERS, VAE, LOAD_ERROR | |
| if CORE is not None or LOAD_ERROR is not None: | |
| return LOAD_ERROR | |
| started = time.time() | |
| try: | |
| from huggingface_hub import hf_hub_download | |
| from safetensors import safe_open | |
| from safetensors.torch import load_file | |
| from solarwm.backends.minimax_h3.artifacts import load_silence_latents | |
| from solarwm.backends.minimax_h3.lora import inject_h3_lora, merge_lora_delta | |
| from solarwm.backends.minimax_h3.observations import observation_profile_from_train_config | |
| from solarwm.backends.minimax_h3.optional import load_conditioners, load_transformer | |
| from solarwm.backends.minimax_h3.stage0p5 import H3Stage0p5Core | |
| # ZeroGPU's emulated CUDA has no device index yet at import time, so `torch.cuda.set_device` | |
| # would raise here; `spaces` places the tensors when the GPU is booked, and every downstream | |
| # consumer takes this `device` value rather than torch's global default. | |
| device = torch.device("cuda") | |
| model_cfg = { | |
| "checkpoint_path": MODEL_REPO, | |
| "transformer_subfolder": "transformer_ref", | |
| "torch_dtype": "bfloat16", | |
| "low_cpu_mem_usage": True, | |
| # render.py asks for "flash"; sm120 has no flash-attn 2 kernel, so the Space runs cuDNN. | |
| "attention_backend": ATTENTION, | |
| "adapter": {"rank": RANK, "alpha": ALPHA, "dropout": 0.0}, | |
| } | |
| print(f"[{VERSION}] loading transformer_ref from {MODEL_REPO} ...", flush=True) | |
| modules = load_transformer(model_cfg, device=device) | |
| def lora_pairs(path: str): | |
| with safe_open(path, framework="pt") as handle: | |
| meta = handle.metadata() or {} | |
| return load_file(path), float(meta.get("alpha", ALPHA)) | |
| fewstep_path = hf_hub_download(LORA_REPO, FEWSTEP_FILE) | |
| pairs, alpha = lora_pairs(fewstep_path) | |
| rank = int(next(v for k, v in pairs.items() if k.endswith("lora_A.weight")).shape[0]) | |
| merged = merge_lora_delta(modules.transformer, pairs, alpha=alpha, rank=rank, scale=1.0) | |
| print(f"[{VERSION}] four-step LoRA merged into {merged} weights", flush=True) | |
| wrapped, lora = inject_h3_lora(modules.transformer, model_cfg["adapter"], base_identity={}) | |
| control_path = hf_hub_download(LORA_REPO, CONTROL_FILE) | |
| pairs, _alpha = lora_pairs(control_path) | |
| lora.load_state_dict({f"base_model.model.{k}": v for k, v in pairs.items()}, broadcast=False) | |
| print(f"[{VERSION}] control LoRA loaded into the live adapter ({len(pairs) // 2} targets)", flush=True) | |
| conditioners = load_conditioners( | |
| model_cfg, device=device, qwen=False, video_vae=True, audio_vae=False, schedulers=False | |
| ) | |
| # The fp32 decoder has no cuDNN kernel; the registry's active backend is global, so it is | |
| # stamped after the transformer has claimed `_native_cudnn`. | |
| conditioners.video_vae.set_attention_backend("native") | |
| silence, _ = load_silence_latents(str(SILENCE), pixel_frames=FRAMES) | |
| core = H3Stage0p5Core( | |
| wrapped, | |
| silence, | |
| device, | |
| geometry=None, | |
| observations=observation_profile_from_train_config({}), | |
| flow_map=False, | |
| ) | |
| CORE, CONDITIONERS, VAE = core, conditioners, conditioners.video_vae | |
| print(f"[{VERSION}] ready in {time.time() - started:.0f}s", flush=True) | |
| except Exception as error: | |
| traceback.print_exc() | |
| LOAD_ERROR = ( | |
| f"Loading `{MODEL_REPO}` + `{LORA_REPO}` failed after {time.time() - started:.0f}s: " | |
| f"`{type(error).__name__}: {error}`" | |
| ) | |
| return LOAD_ERROR | |
| # ── the encoding half: prompt over the wire, latents locally ────────────────── | |
| def conditioner(): | |
| """The other half, over the gradio API. The visitor's own ZeroGPU token pays for its booking.""" | |
| from gradio_client import Client | |
| return Client(CONDITIONER_SPACE) | |
| def encode_prompt_remote(prompt: str, media: list[str], canvas: str, num_frames: int): | |
| """`/encode_ref2va` on the conditioner Space: the six-part prompt *with its references' vision | |
| blocks*, exactly the presentation the conditioned chain of `omni_preencode` encodes. | |
| The media order is the packed order (and the label order): the structure video first — | |
| `<Video 1>` — and the first-frame still second — `<Video 2>`. Both cross as videos so the | |
| presentation numbers them per modality as the training prompts do. | |
| """ | |
| from gradio_client import handle_file | |
| from safetensors import safe_open | |
| path, plan = conditioner().predict( | |
| prompt=prompt, | |
| media=[handle_file(item) for item in media], | |
| kinds=",".join("video" for _ in media), | |
| canvas=canvas, | |
| num_frames=num_frames, | |
| rewrite_prompt=False, | |
| api_name="/encode_ref2va", | |
| ) | |
| with safe_open(path, framework="pt") as handle: | |
| # The conditioner ships `prompt_embeds` batched — `(1, N, 5120)` — while the artifact contract | |
| # every consumer here is written against (`H3ArtifactBatch`, and `H3Stage0p5Core.prompt`, which | |
| # does its own `.unsqueeze(0)`) wants the flat `(N, 5120)`. Left batched, the extra leading axis | |
| # survives into the attention call and the query comes out 5-D, which fails deep inside the | |
| # backend's `permute` with a message that never mentions the prompt at all. | |
| embeds = handle.get_tensor("prompt_embeds").reshape(-1, 5120).to(torch.bfloat16).contiguous() | |
| tags = handle.get_tensor("text_token_tags").reshape(-1).to(torch.int64).contiguous() | |
| return embeds, tags, handle.metadata(), plan | |
| def encode_vae_local(frames: torch.Tensor, device) -> torch.Tensor: | |
| """One visual condition through the released encode recipe: ImageNet-normalized pixels, the | |
| posterior *sampled* at seed 42, rounded to fp16, then normalized — `encode_vae_condition`. | |
| `frames` is a `(F, H, W, 3)` uint8 array on the canvas already, exactly what the pipeline's | |
| normalized reference would be. | |
| """ | |
| from diffusers.modular_pipelines.minimax_h3.encoders import encode_vae_condition | |
| pixels = torch.from_numpy(frames.copy()).to(device).permute(3, 0, 1, 2)[None] | |
| return encode_vae_condition( | |
| VAE, | |
| pixels, | |
| (0.485, 0.456, 0.406), | |
| (0.229, 0.224, 0.225), | |
| 42, | |
| ) | |
| # ── frame preparation (omni_preencode's own helpers, inlined) ───────────────── | |
| def _open_media(path: str): | |
| """A PyAV container that tolerates undecodable metadata — `omni_preencode.open_media`. | |
| Newer PyAV releases dropped the ``metadata_errors`` option, so fall back to a | |
| plain ``av.open`` when the keyword is rejected. | |
| """ | |
| import av | |
| try: | |
| return av.open(path, metadata_errors="ignore") | |
| except TypeError: | |
| return av.open(path) | |
| def read_video(path: str, seconds: float = 0.0): | |
| """Decode a clip with PyAV, whole frames only — `omni_preencode.read_video`.""" | |
| import numpy as np | |
| with _open_media(path) as container: | |
| stream = container.streams.video[0] | |
| nominal = float(stream.average_rate or FPS) | |
| frames = [] | |
| for frame in container.decode(stream): | |
| frames.append(frame.to_ndarray(format="rgb24")) | |
| if seconds and len(frames) > seconds * nominal * 1.1: | |
| break | |
| if not frames: | |
| raise ValueError(f"{path} has no video frames") | |
| array = np.stack(frames) | |
| return array, nominal | |
| def on_grid(frames, fps: float): | |
| """Put frames on the 24 fps clock by holding each until the next one's slot — `on_grid`.""" | |
| import numpy as np | |
| if fps <= 0: | |
| raise ValueError(f"a clip needs a positive frame rate, got {fps}") | |
| if fps == FPS: | |
| return frames | |
| slots = np.floor(np.arange(frames.shape[0]) * (FPS / fps) + 0.5).astype(np.int64) | |
| total = int(np.floor(frames.shape[0] * FPS / fps + 0.5)) | |
| return np.repeat(frames, np.diff(slots, append=total), axis=0) | |
| def fit(frames, canvas_shape): | |
| """Center-crop to the canvas's aspect, then LANCZOS-rescale to it — `omni_preencode.fit`.""" | |
| import numpy as np | |
| from PIL import Image | |
| height, width = canvas_shape | |
| source_h, source_w = frames.shape[1], frames.shape[2] | |
| target = height / width | |
| if source_w * target <= source_h: # sides lost | |
| keep_w = source_w | |
| keep_h = round(source_w * target) | |
| top = (source_h - keep_h) // 2 | |
| region = (slice(top, top + keep_h), slice(0, keep_w)) | |
| else: # top and bottom lost | |
| keep_h = source_h | |
| keep_w = round(source_h / target) | |
| left = (source_w - keep_w) // 2 | |
| region = (slice(0, keep_h), slice(left, left + keep_w)) | |
| frames = frames[:, region[0], region[1]] | |
| if (height, width) == (keep_h, keep_w): | |
| return frames | |
| return np.stack( | |
| [np.asarray(Image.fromarray(frame).resize((width, height), Image.Resampling.LANCZOS)) for frame in frames] | |
| ) | |
| def still_frames(image_path: str, canvas_shape): | |
| """The first frame on the canvas, held STILL_FRAMES long — `omni_preencode.reference`'s aligned | |
| still path, minus the file-type dispatch.""" | |
| import numpy as np | |
| from PIL import Image | |
| image = Image.open(image_path).convert("RGB") | |
| frame = np.asarray(fit(np.asarray(image)[None], canvas_shape)[0]) | |
| return np.repeat(frame[None], STILL_FRAMES, axis=0) | |
| def still_as_video(frames, directory: str) -> str: | |
| """Write the 13-frame still to an mp4 so it crosses the wire as `<Video 2>`, not `<Picture 1>`. | |
| PyAV instead of imageio's ffmpeg: `av` is already a dependency for the decode side.""" | |
| import av | |
| import numpy as np | |
| path = os.path.join(directory, f"solar-still-{int(time.time() * 1000)}.mp4") | |
| height, width = frames.shape[1:3] | |
| container = av.open(path, mode="w", format="mp4") | |
| try: | |
| stream = container.add_stream("libx264", rate=int(FPS)) | |
| stream.width, stream.height = width, height | |
| # Near-lossless: the conditioner's vision tower reads these pixels back, and every frame here | |
| # is identical, so there is nothing to gain from rate control — only chroma to lose. 4:4:4 at | |
| # crf 0 keeps the first frame pixel-faithful through the round trip, as the authors' path does. | |
| stream.pix_fmt = "yuv444p" | |
| stream.options = {"crf": "0", "preset": "veryfast"} | |
| for frame in frames: | |
| container.mux(stream.encode(av.VideoFrame.from_ndarray(np.ascontiguousarray(frame), format="rgb24"))) | |
| container.mux(stream.encode(None)) # flush the encoder's tail | |
| finally: | |
| container.close() | |
| return path | |
| def mp4_bytes(decoded: "torch.Tensor", fps: int = FPS) -> bytes: | |
| """The decoded clip as mp4 bytes — `inference._mp4_bytes`'s exact pixel math, muxed with PyAV | |
| instead of imageio's ffmpeg (`av` is already a dependency; imageio-ffmpeg would be one more).""" | |
| import av | |
| import numpy as np | |
| frames = decoded[0].permute(1, 2, 3, 0).mul(255).round().clamp(0, 255).to(torch.uint8).cpu().numpy() | |
| with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temporary: | |
| path = Path(temporary.name) | |
| try: | |
| container = av.open(str(path), mode="w", format="mp4") | |
| try: | |
| stream = container.add_stream("libx264", rate=int(fps)) | |
| stream.width, stream.height = int(frames.shape[2]), int(frames.shape[1]) | |
| stream.pix_fmt = "yuv420p" | |
| for frame in frames: | |
| container.mux( | |
| stream.encode(av.VideoFrame.from_ndarray(np.ascontiguousarray(frame), format="rgb24")) | |
| ) | |
| container.mux(stream.encode(None)) | |
| finally: | |
| container.close() | |
| return path.read_bytes() | |
| finally: | |
| path.unlink(missing_ok=True) | |
| # ── the request ─────────────────────────────────────────────────────────────── | |
| def check(structure_path, first_path, prompt): | |
| if not prompt or not prompt.strip(): | |
| raise gr.Error("SolarRenderer always takes the six-part prompt.") | |
| if not structure_path: | |
| raise gr.Error("Add the structure video — it is the request's <Video 1>.") | |
| def pick_canvas(structure_path): | |
| """The canvas a structure video fixes: landscape or portrait by its own aspect.""" | |
| if not structure_path: | |
| return gr.update() | |
| try: | |
| import av | |
| with av.open(structure_path) as container: | |
| stream = container.streams.video[0] | |
| width, height = stream.width, stream.height | |
| except Exception: | |
| return gr.update() | |
| return gr.update(value="1344x768 · 16:9 full" if width >= height else "768x1344 · 9:16 full") | |
| def build_batch(prompt_embeds, text_token_tags, target_latents, observations): | |
| """The `H3ArtifactBatch` `H3OmniStream.read` would build from an encoded member.""" | |
| from solarwm.backends.minimax_h3.artifacts import H3ArtifactBatch | |
| return H3ArtifactBatch( | |
| sample_id="render", | |
| start_frame=0, | |
| plan_fingerprint="render", | |
| target_latents=target_latents.contiguous(), | |
| anchor_latents=None, | |
| prompt_embeds=prompt_embeds.contiguous(), | |
| text_token_tags=text_token_tags.contiguous(), | |
| source_frame_indices=None, | |
| camera_viewmats=None, | |
| camera_K=None, | |
| source_fps=24.0, | |
| dataset_source="", | |
| # The ref2va prompt never shows the first frame, so it is also the anchor-free prompt. | |
| text_prompt_embeds=prompt_embeds.contiguous(), | |
| text_prompt_tags=text_token_tags.contiguous(), | |
| visual_observations=tuple(observations) or None, | |
| known_degrees=None, | |
| ) | |
| def vram() -> str: | |
| """The allocator's own numbers, for the log.""" | |
| if not torch.cuda.is_available(): | |
| return "cpu" | |
| return ( | |
| f"allocated {torch.cuda.memory_allocated() / 2**30:.1f} GiB, " | |
| f"peak {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB, " | |
| f"reserved {torch.cuda.memory_reserved() / 2**30:.1f} GiB" | |
| ) | |
| def place_vae(which: str) -> None: | |
| """Put the fp32 video VAE on the card, or take it off, around the phases that need it. | |
| The transformer is 61.7 GiB of the 96 GiB card, and the fp32 autoencoder is another ~14.5 GiB. | |
| It is needed for the reference encodes (first) and the decode (last) — but *not* during the | |
| renoise loop, which is the memory peak: four whole-sequence forward/backward-shaped passes over | |
| 105k tokens. Left resident, the VAE pushes the sampling peak past the allocator's limit and the | |
| next block's feed-forward dies with `NVML_SUCCESS == r INTERNAL ASSERT FAILED`, an assert that | |
| reports a CUDA bug and never mentions memory. Moving it off before sampling gives the loop the | |
| whole card, which is what the other H3 Spaces in this org do. | |
| """ | |
| global VAE | |
| cuda = torch.device("cuda") | |
| if which == "card": | |
| VAE.to(cuda) | |
| else: | |
| VAE.to("cpu") | |
| torch.cuda.empty_cache() | |
| def _generate(prompt_embeds, text_token_tags, structure_path, first_frame_path, height, width, | |
| num_frames, seed, forwards): | |
| """The only thing on GPU time: the local VAE encodes, the 4-evaluation renoise loop, the decode. | |
| Every CUDA touch has to happen in here — the web process runs with ZeroGPU's *emulated* CUDA, where | |
| a real kernel launch raises "Low-level CUDA init reached". So the structure clip is decoded from its | |
| file *inside* this function, the VAE encodings of the structure video and the still are computed | |
| here, and only small CPU bf16 latents and the prompt embeddings cross into the denoise loop. | |
| """ | |
| from solarwm.backends.minimax_h3.inference import decode_h3_latents | |
| from solarwm.backends.minimax_h3.artifacts import H3VisualObservation | |
| device = CORE.device | |
| height, width, num_frames = int(height), int(width), int(num_frames) | |
| place_vae("card") # the fp32 autoencoder, and only it, while the references are encoded | |
| frames, fps = read_video(structure_path, num_frames / FPS + 0.5) | |
| frames = fit(on_grid(frames, fps)[:num_frames], (height, width)) | |
| target_latents = encode_vae_local(frames, device)[0].to(torch.bfloat16).cpu() | |
| structure_latents = target_latents.clone() | |
| still_latents = None | |
| if first_frame_path: | |
| still_latents = encode_vae_local(still_frames(first_frame_path, (height, width)), device)[0, :, :1] \ | |
| .to(torch.bfloat16).cpu() | |
| # Both reference encodes are done and their latents are on the CPU: the autoencoder leaves the | |
| # card before the sampling peak and does not come back until the latents exist. | |
| place_vae("cpu") | |
| torch.cuda.reset_peak_memory_stats() | |
| observations = [] | |
| if structure_latents is not None: | |
| # frames="all": laid over every target latent frame, trimmed to the target's own count. | |
| # Both arrive as the [24, f, h, w] batch H3VisualObservation takes. | |
| aligned = tuple(range(min(int(structure_latents.shape[1]), int(target_latents.shape[1])))) | |
| observations.append( | |
| H3VisualObservation( | |
| latents=structure_latents[: len(aligned)].contiguous(), | |
| frames=aligned, | |
| degree=0.999, | |
| boxes=None, | |
| ) | |
| ) | |
| if still_latents is not None: | |
| observations.append( | |
| H3VisualObservation(latents=still_latents.contiguous(), frames=(0,), degree=0.999, boxes=None) | |
| ) | |
| batch = build_batch(prompt_embeds.to(device), text_token_tags.to(device), target_latents.to(device), observations) | |
| # generate() counts schedule points: N points run N - 1 evaluations, so 4 evaluations need 5. | |
| began = time.perf_counter() | |
| with torch.no_grad(): | |
| latents = CORE.generate(batch, noise_seed=int(seed), num_inference_steps=int(forwards) + 1, renoise=True) | |
| print( | |
| f"[{VERSION}] sampled {int(forwards)} steps in {time.perf_counter() - began:.0f} s ({vram()})", | |
| flush=True, | |
| ) | |
| place_vae("card") # the fp32 decoder, and only it, for the decode | |
| decoded = decode_h3_latents(VAE, latents, device=device) | |
| return mp4_bytes(decoded), latents.shape | |
| def generate( | |
| # The first four are the columns `gr.Examples` varies; they lead the signature for that reason. | |
| prompt: str, | |
| structure_video: str | None = None, | |
| first_frame: str | None = None, | |
| num_frames: int = DEFAULT_FRAMES, | |
| seed: int = 0, | |
| forwards: int = 4, | |
| progress=gr.Progress(track_tqdm=True), | |
| ): | |
| """Render a structure video into a finished clip. | |
| Args: | |
| prompt: the six-part prompt (`skills/solarrenderer-caption` form), naming the structure video | |
| as `<Video 1>` and the first frame as `<Video 2>` (or `<Video 1>` without one). | |
| structure_video: the structure clip — grey box, semantic map, skeletons, depth, a sketch. | |
| first_frame: optional first frame in the look the clip should render in. | |
| num_frames: length of the render, in `17*n+5` frames at 24 fps. 158 is the release default. | |
| seed: RNG seed. | |
| forwards: model evaluations; the four-step LoRA was trained for 4. | |
| """ | |
| import numpy as np | |
| # gr.Radio hands its value over as a string; the rest of the path wants an int. | |
| num_frames = int(num_frames) | |
| forwards = int(forwards) | |
| seed = int(seed) | |
| if LOAD_ERROR: | |
| raise gr.Error(LOAD_ERROR.replace("**", "").replace("`", "")) | |
| if CORE is None: | |
| raise gr.Error("The renderer is still loading — watch the Space logs and retry shortly.") | |
| check(structure_video, first_frame, prompt) | |
| structure_path = structure_video if isinstance(structure_video, str) else structure_video.get("path") | |
| first_path = first_frame if isinstance(first_frame, str) or first_frame is None else first_frame.get("path") | |
| chosen = pick_canvas(structure_path) | |
| if not isinstance(chosen, dict) or "value" not in chosen: | |
| raise gr.Error("Could not read the structure video's stream.") | |
| height, width = CANVASES[chosen["value"]] | |
| with tempfile.TemporaryDirectory() as work: | |
| # The first-frame still, as a 13-frame mp4 so the presentation numbers it <Video 2>. Both this | |
| # and the read of the structure clip are pure file work (PyAV / PIL), so they stay in the web | |
| # process; every *tensor* on the card happens inside `_generate`. | |
| if first_path: | |
| still_video_path = still_as_video(still_frames(first_path, (height, width)), work) | |
| media = [structure_path, still_video_path] | |
| else: | |
| media = [structure_path] | |
| progress(0.0, desc=f"Encoding the six-part prompt with {len(media)} reference(s) ...") | |
| started = time.time() | |
| try: | |
| prompt_embeds, text_token_tags, metadata, plan = encode_prompt_remote( | |
| prompt, media, "1344x768 · 16:9 full" if height == 768 else "768x1344 · 9:16 full", num_frames | |
| ) | |
| except gr.Error: | |
| raise | |
| except Exception as error: | |
| traceback.print_exc() | |
| raise gr.Error( | |
| f"The conditioner ({CONDITIONER_SPACE}) failed with `{type(error).__name__}: {error}`. " | |
| "Its logs carry the full traceback." | |
| ) from error | |
| condition_seconds = time.time() - started | |
| height, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames")) | |
| progress(0.25, desc=f"Rendering {num_frames} frames at {width}x{height} in 4 steps ...") | |
| began = time.time() | |
| mp4, shape = _generate( | |
| prompt_embeds, text_token_tags, structure_path, first_path, | |
| height, width, num_frames, seed, forwards | |
| ) | |
| generate_seconds = time.time() - began | |
| out = os.path.join(tempfile.gettempdir(), "solarrenderer-out") | |
| os.makedirs(out, exist_ok=True) | |
| path = os.path.join(out, f"solarrenderer-{int(time.time() * 1000)}.mp4") | |
| Path(path).write_bytes(mp4) | |
| print( | |
| f"[{VERSION}] `{width}x{height}`, {num_frames} frames ({num_frames / FPS:.2f} s), " | |
| f"{int(forwards)} steps · conditioner {condition_seconds:.0f}s " | |
| f"({plan['num_text_tokens']} tokens) · render {generate_seconds:.0f}s · seed {int(seed)}", | |
| flush=True, | |
| ) | |
| return path | |
| load_renderer() | |
| INTRO = """# SolarRenderer · few-step structure-to-video on MiniMax-H3 | |
| <div align="center"> | |
| <a href="https://huggingface.co/Enderfga/SolarRenderer" target="_blank" rel="noopener"><strong>[ LoRAs ]</strong></a> | |
| <a href="https://enderfga.cn/SolarRenderer" target="_blank" rel="noopener"><strong>[ project page ]</strong></a> | |
| <a href="https://arxiv.org/abs/2610.28630" target="_blank" rel="noopener"><strong>[ paper ]</strong></a> | |
| <a href="https://huggingface.co/MiniMaxAI/MiniMax-H3" target="_blank" rel="noopener"><strong>[ base model ]</strong></a> | |
| </div> | |
| **Enderfga/SolarRenderer** turns a structure video — a game engine's grey box, a semantic map, skeletons, depth, | |
| a body mesh, or a sketch the model never saw in training — into a finished clip in **four model evaluations**, | |
| with an optional first frame and a six-part prompt deciding the look. The control LoRA reads the structure | |
| frame by frame; the four-step LoRA (fine-tuned from DMAD) does the sampling; both are rank-384 adapters on | |
| MiniMax-H3's `ref2va` partition, and the render follows `scripts/render.py` exactly: the four-step LoRA merged | |
| into the weights first, the control LoRA live on top, four renoised evaluations on the shifted σ grid. | |
| Name the structure clip **`<Video 1>`** and the first frame **`<Video 2>`** in the prompt. The canvas follows | |
| the structure video's aspect (1344x768 or 768x1344), and the output carries no audio track — the silence | |
| condition is pre-encoded. | |
| """ | |
| CSS = """ | |
| .main.fillable { max-width: 1250px !important; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| with gr.Blocks(title="SolarRenderer — few-step structure-to-video") as demo: | |
| gr.Markdown(INTRO) | |
| with gr.Row(): | |
| with gr.Column(): | |
| prompt = gr.Textbox( | |
| label="Six-part prompt — subject_definitions / summary / retention_analysis / detailed_description / overall_soundscape / non_diegetic_music", | |
| lines=10, | |
| value=Path(HERE / "examples" / "sem-highway_synthwave" / "prompt.txt").read_text(), | |
| placeholder="subject_definitions:\n<Video 1> is a semantic segmentation of the scene ...", | |
| ) | |
| with gr.Row(): | |
| structure = gr.Video(label="Structure video · <Video 1>", height=260) | |
| first = gr.Image(label="First frame (optional) · <Video 2>", type="filepath", height=260) | |
| run = gr.Button("Render the structure", variant="primary", size="lg") | |
| with gr.Accordion("Advanced options", open=False): | |
| num_frames = gr.Radio( | |
| label="Clip length (frames at 24 fps)", | |
| choices=[str(item) for item in FRAME_CHOICES], | |
| value=str(DEFAULT_FRAMES), | |
| info="158 frames is the release default; shorter clips render faster.", | |
| ) | |
| forwards = gr.Slider( | |
| label="Model evaluations", | |
| minimum=1, | |
| maximum=8, | |
| step=1, | |
| value=4, | |
| info="The four-step LoRA was trained for 4.", | |
| ) | |
| seed = gr.Number(label="Seed", value=0, precision=0) | |
| with gr.Column(): | |
| result = gr.Video(label="Rendered clip") | |
| canvas = gr.Textbox(label="Canvas (follows the structure video's aspect)", interactive=False) | |
| structure.change(pick_canvas, structure, canvas, show_progress="hidden", api_name=False) | |
| request = [prompt, structure, first, num_frames, seed, forwards] | |
| gr.Examples( | |
| # The authors' own example: the semantic highway run of examples/sem-highway_synthwave, with | |
| # its own prompt.txt, structure.mp4 and first.png (Apache-2.0 repo, credited in the README). | |
| # Only the three primary inputs are listed; every other parameter of `generate` carries the | |
| # same default as its UI component, so an example click and a Generate click run identically. | |
| examples=[ | |
| [ | |
| Path(HERE / "examples" / "sem-highway_synthwave" / "prompt.txt").read_text(), | |
| str(HERE / "examples" / "sem-highway_synthwave" / "structure.mp4"), | |
| str(HERE / "examples" / "sem-highway_synthwave" / "first.png"), | |
| ], | |
| ], | |
| inputs=[prompt, structure, first], | |
| outputs=result, | |
| fn=generate, | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| ) | |
| run.click(generate, request, result, api_name="generate") | |
| if __name__ == "__main__": | |
| demo.launch(show_error=True, theme=gr.themes.Citrus(), css=CSS, max_threads=1000) | |