Upload app.py
Browse files108 unmodified lines1091101111121121131141 unmodified line11611711812011912012112212312412712512612711 unmodified lines13914014114514214314424 unmodified lines16917017117617217317421 unmodified lines1961971982041992002017 unmodified lines2092102112182122132144 unmodified lines21922022122922222322417 unmodified lines24224324425324524624760 unmodified lines30830931032031131231398 unmodified lines41241341442541541641712 unmodified lines43043143244443343444743543643753 unmodified lines49149249350749449551049649749849950050151750250350429 unmodified lines5345355365535375385391 unmodified line54154254356154454556454654754814 unmodified lines56356456558556656756818 unmodified lines5875885896105905915923 unmodified lines5965975986205996006017 unmodified lines6096106116346126136144 unmodified lines6196206216456226236246256266516276286296306316326586336346355 unmodified lines64164264367064464567364664764836 unmodified lines68568668771668868969069169269372369469569693 unmodified lines790791792823793794826795796797108 unmodified linesLOAD_ERROR: str | None = NoneLOADED_IN: float | None = None
def snap_frames(seconds: float) -> int: """The frame count MiniMax-H3's video VAE can decode: the next ``17 * n + 5`` at 24 fps.""" frames = max(1, round(float(seconds) * FPS))1 unmodified line frames += 1 return frames
def lower_duration_floor(seconds: float = MIN_UI_DURATION) -> None: """Let the pipeline generate below its 5 s floor.""" from diffusers.modular_pipelines.minimax_h3.modular_pipeline import MiniMaxH3ModularPipeline
MiniMaxH3ModularPipeline.min_duration = property(lambda self: float(seconds))
def shifted_schedule(shift: float) -> list[float]: """``BASE_SCHEDULE`` pushed through H3's exponential sigma shift ``s*Ο / (1 + (s - 1)*Ο)``.
11 unmodified lines """ return [shift * sigma / (1 + (shift - 1) * sigma) for sigma in BASE_SCHEDULE]
def pin_distilled_schedule(scheduler) -> None: """Pin the shifted ``BASE_SCHEDULE`` onto a scheduler so *every* ``set_timesteps`` call lands on it.
24 unmodified lines scheduler.set_timesteps = set_timesteps scheduler._flashgen_pinned = True
# ββ LoRA loading (weight folding) βββββββββββββββββββββββββββββββββββββββββββββ## This mirrors ``merge_lora_ckpt.py``, the merge script the LoRA repo itself ships, rather than a21 unmodified lines# contiguous thirds directly β the naive reading β scatters every head's q/k/v across all three# projections, which turns the adapter into structured noise on all 52 attention blocks.
def _reorder_interleaved_qkv(weight, num_heads: int, head_dim: int): """De-interleave per-head fused-QKV rows into ``[q_all; k_all; v_all]``.
7 unmodified lines [part.reshape(num_heads * head_dim, *weight.shape[1:]) for part in (query, key, value)], dim=0 )
def _lora_target_name(source_name: str) -> str: """Map an original-checkpoint base name (without ``.lora_A/B.*``) to the diffusers parameter path.""" if source_name.startswith("token_refiner.blocks."):4 unmodified lines target = source_name return target.replace("final_layer.adaln_proj.linear", "norm_out.linear")
def _lora_targets(name: str, b_weight, num_heads: int, head_dim: int): """Yield ``(diffusers_param_key, row_transformed_B)`` for one original LoRA base name.""" target = _lora_target_name(name)17 unmodified lines # adaln_proj.linear (block-level) and norm_out.linear: identical row layout. yield target + ".weight", b_weight
def load_and_apply_lora(transformer) -> str: """Download the FlashGen LoRA, remap keys, and fold ``scale * (B @ A)`` into the base weights.""" import torch60 unmodified lines f"-> {folded} weight deltas Β· {LORA_FILE}" )
# ββ Additional LoRAs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ## These are folded after FlashGen, so the original 4-step FlashGen schedule and98 unmodified lines f"{folded} weight deltas Β· scale {float(scale):g}" )
def load_and_apply_extra_loras(transformer) -> list[str]: return [ _apply_extra_lora(12 unmodified lines ), ]
# ββ Model loading βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_models() -> str | None: """Load the denoising half at startup: transformer + VAEs + schedulers, then fold the LoRA in.""" global PIPE, LOAD_ERROR, LOADED_IN53 unmodified lines LOAD_ERROR = f"**Loading failed** after {time.time() - started:.0f}s: `{type(error).__name__}: {error}`" return LOAD_ERROR
# ββ Remote conditioning ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@cachedef conditioner(): from gradio_client import Client
return Client(CONDITIONER_SPACE)
def encode_remote(prompt, image_path, last_image_path, canvas, num_frames, ip_token=None, rewrite_prompt=False): """Call the conditioner Space to get ``prompt_embeds`` + ``text_token_tags`` + resolved geometry.
29 unmodified lines metadata = handle.metadata() return handle.get_tensor("prompt_embeds"), handle.get_tensor("text_token_tags"), metadata, plan
def conditioner_client(ip_token): if not ip_token: return conditioner()1 unmodified line
return Client(CONDITIONER_SPACE, headers={"x-ip-token": ip_token})
# ββ Geometry helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _snap_canvas(aspect: float, current_canvas: str) -> str: """The supported canvas whose aspect ratio is closest to ``aspect``.
14 unmodified lines return current_canvas return fastest[ratio][0]
def _cover_crop(image_path: str, canvas_label: str) -> str: """Center cover-crop the file at ``image_path`` to ``canvas_label``'s aspect ratio, in place.
18 unmodified lines img.save(image_path) return image_path
def _fit_keyframe(image_path, current_canvas): """Snap the canvas to a keyframe's aspect ratio, then cover-crop the keyframe to that canvas.""" from PIL import Image as _Image3 unmodified lines label = _snap_canvas(aspect, current_canvas) return _cover_crop(image_path, label), label
def _fit_keyframe_ui(image_path, current_canvas): """``image.upload`` handler β the reference Space's behaviour, ported.
7 unmodified lines cropped, label = _fit_keyframe(path, current_canvas) return gr.update(value=cropped), gr.update(value=label)
def _fit_last_keyframe_ui(last_image_path, image_path, current_canvas): """``last_image.upload`` handler. The first frame owns the canvas when there is one, so a last frame uploaded on top of it is only cover-cropped to the canvas already chosen."""4 unmodified lines return gr.update(value=_cover_crop(path, current_canvas)), gr.update() return _fit_keyframe_ui(path, current_canvas)
def _as_path(value): if isinstance(value, dict): value = value.get("path") or (value.get("url") or "").removeprefix("/gradio_api/file=") return value or None
# ββ GPU duration estimation βββββββββββββββββββββββββββββββββββββββββββββββββ
_DUR_B, _DUR_C = 1.1745e-4, 3.8396e-9_DECODE_BASE, _DECODE_PER_DEFAULT_CANVAS, _DEFAULT_CANVAS_PIXELS = 15, 15, 960 * 544 * 124_PLACEMENT_ALLOWANCE, _PAD = 12, 10
def get_duration(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, seed, *a, **k): """Estimate GPU duration for the ``_generate`` call. Steps is fixed at NUM_STEPS (4).""" height, width, num_frames = int(height), int(width), int(num_frames)5 unmodified lines decode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / _DEFAULT_CANVAS_PIXELS return max(60, int(denoise + decode) + _PLACEMENT_ALLOWANCE + _PAD)
# ββ Inference βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@spaces.GPU(duration=get_duration, size=GPU_SIZE)def _generate(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, seed): """Denoise + decode on GPU time. The LoRA is already folded at startup; 4 steps with custom sigmas."""36 unmodified lines sigmas_used, )
def _caller_ip_token() -> str | None: from gradio.context import LocalContext
request = LocalContext.request.get() return request.headers.get("x-ip-token") if request is not None else None
def generate( prompt, image_path=None,93 unmodified lines ) return path, report, enhanced, gr.update(visible=bool(enhanced))
# ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
INTRO = """# MiniMax-H3 4-Step FlashGen LoRA
<div align="center">app.py-32