Upload app.py
Browse files108 unmodified lines1091101111121131141151 unmodified line11711811912012112212312412512612712812913011 unmodified lines14214314414514614714824 unmodified lines17317417517617717817921 unmodified lines2012022032042052062077 unmodified lines2152162172182192202214 unmodified lines22622722822923023123217 unmodified lines25025125225325425525660 unmodified lines31731831932032132232398 unmodified lines42242342442542642742812 unmodified lines44144244344444544644744844945053 unmodified lines50450550650750850951051151251351451551651751851952029 unmodified lines5505515525535545555561 unmodified line55855956056156256356456556656714 unmodified lines58258358458558658758818 unmodified lines6076086096106116126133 unmodified lines6176186196206216226237 unmodified lines6316326336346356366374 unmodified lines6426436446456466476486496506516526536546556566576586596606615 unmodified lines66766866967067167267367467567636 unmodified lines71371471571671771871972072172272372472572693 unmodified lines820821822823824825826827828829108 unmodified linesLOAD_ERROR: str | None = NoneLOADED_IN: float | None = Nonedef 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 lineframes += 1return framesdef 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 MiniMaxH3ModularPipelineMiniMaxH3ModularPipeline.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 linesscheduler.set_timesteps = set_timestepsscheduler._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 linestarget = source_namereturn 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_weightdef load_and_apply_lora(transformer) -> str:"""Download the FlashGen LoRA, remap keys, and fold ``scale * (B @ A)`` into the base weights."""import torch60 unmodified linesf"-> {folded} weight deltas Β· {LORA_FILE}")# ββ Additional LoRAs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ## These are folded after FlashGen, so the original 4-step FlashGen schedule and98 unmodified linesf"{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 linesLOAD_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 Clientreturn 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 linesmetadata = handle.metadata()return handle.get_tensor("prompt_embeds"), handle.get_tensor("text_token_tags"), metadata, plandef conditioner_client(ip_token):if not ip_token:return conditioner()1 unmodified linereturn 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 linesreturn current_canvasreturn 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 linesimg.save(image_path)return image_pathdef _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 lineslabel = _snap_canvas(aspect, current_canvas)return _cover_crop(image_path, label), labeldef _fit_keyframe_ui(image_path, current_canvas):"""``image.upload`` handler β the reference Space's behaviour, ported.7 unmodified linescropped, 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 lastframe uploaded on top of it is only cover-cropped to the canvas already chosen."""4 unmodified linesreturn 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, 10def 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 linesdecode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / _DEFAULT_CANVAS_PIXELSreturn 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 linessigmas_used,)def _caller_ip_token() -> str | None:from gradio.context import LocalContextrequest = LocalContext.request.get()return request.headers.get("x-ip-token") if request is not None else Nonedef 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">108 unmodified lines1091101111121131141 unmodified line11611711811912012112212312412512612711 unmodified lines13914014114214314424 unmodified lines16917017117217317421 unmodified lines1961971981992002017 unmodified lines2092102112122132144 unmodified lines21922022122222322417 unmodified lines24224324424524624760 unmodified lines30830931031131231398 unmodified lines41241341441541641712 unmodified lines43043143243343443543643753 unmodified lines49149249349449549649749849950050150250350429 unmodified lines5345355365375385391 unmodified line54154254354454554654754814 unmodified lines56356456556656756818 unmodified lines5875885895905915923 unmodified lines5965975985996006017 unmodified lines6096106116126136144 unmodified lines6196206216226236246256266276286296306316326336346355 unmodified lines64164264364464564664764836 unmodified lines68568668768868969069169269369469569693 unmodified lines790791792793794795796797108 unmodified linesLOAD_ERROR: str | None = NoneLOADED_IN: float | None = Nonedef 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 lineframes += 1return framesdef 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 MiniMaxH3ModularPipelineMiniMaxH3ModularPipeline.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 linesscheduler.set_timesteps = set_timestepsscheduler._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 linestarget = source_namereturn 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_weightdef load_and_apply_lora(transformer) -> str:"""Download the FlashGen LoRA, remap keys, and fold ``scale * (B @ A)`` into the base weights."""import torch60 unmodified linesf"-> {folded} weight deltas Β· {LORA_FILE}")# ββ Additional LoRAs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ## These are folded after FlashGen, so the original 4-step FlashGen schedule and98 unmodified linesf"{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 linesLOAD_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 Clientreturn 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 linesmetadata = handle.metadata()return handle.get_tensor("prompt_embeds"), handle.get_tensor("text_token_tags"), metadata, plandef conditioner_client(ip_token):if not ip_token:return conditioner()1 unmodified linereturn 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 linesreturn current_canvasreturn 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 linesimg.save(image_path)return image_pathdef _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 lineslabel = _snap_canvas(aspect, current_canvas)return _cover_crop(image_path, label), labeldef _fit_keyframe_ui(image_path, current_canvas):"""``image.upload`` handler β the reference Space's behaviour, ported.7 unmodified linescropped, 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 lastframe uploaded on top of it is only cover-cropped to the canvas already chosen."""4 unmodified linesreturn 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, 10def 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 linesdecode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / _DEFAULT_CANVAS_PIXELSreturn 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 linessigmas_used,)def _caller_ip_token() -> str | None:from gradio.context import LocalContextrequest = LocalContext.request.get()return request.headers.get("x-ip-token") if request is not None else Nonedef 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