"""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 ────────────────── @cache 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 — `