Upload 5 files
Browse filesFiles changed (4)
- README.md+14-67
- app.py+170-869
- h3_split_blocks.py+9-64
- requirements.txt+1-5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778---title: MiniMax-H3 4-Step FlashGen LoRAemoji: ⚡colorFrom: bluecolorTo: redsdk: gradiosdk_version: 6.25.0app_file: app.pypython_version: "3.12"startup_duration_timeout: 1hshort_description: 4-step text-to-video+audio with MiniMax-H3 FlashGen LoRAmodels:- MiniMaxAI/MiniMax-H3- Beidouqixing/minimax-h3-4step-lora-flashgen---# MiniMax-H3 4-Step FlashGen LoRAA demo of the [FlashGen 4-step distillation LoRA](https://huggingface.co/Beidouqixing/minimax-h3-4step-lora-flashgen)applied to [MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3), MiniMax's 33B omni-modal model that generatesvideo with native stereo audio.The FlashGen LoRA uses distribution-matching distillation (DMD2 / VSD, data-free) to reduce inference from ~20 stepsto just **4 steps** — approximately a 5x speedup. The distilled `base_schedule` `[1.0, 0.7, 0.4, 0.15, 0.0]` replacesthe *uniform* `linspace(1, 0, num_inference_steps)` grid `MiniMaxH3Scheduler.set_timesteps` would otherwise build, andH3's per-modality exponential sigma shift still applies on top of it — a single base schedule can serve bothmodalities precisely because it is pre-shift. So the video scheduler runsσ `1 → 0.9655 → 0.8889 → 0.6792 → 0` (`shift = 12.0`) and the audio scheduler σ `1 → 0.875 → 0.6667 → 0.3462 → 0`(`shift = 3.0`). Each shifted grid is injected through `MiniMaxH3Scheduler.set_timesteps(sigmas=...)`, which takes itverbatim, and *pinned* onto its scheduler, because the pipeline's own denoise step calls`set_timesteps(num_inference_steps, ...)` again — and for this scheduler `num_inference_steps` counts sigma gridpoints (terminal `0.0` included), so it runs `len(sigmas) - 1` model evaluations. Pinning is the runtime equivalent of`merge_lora_ckpt.py` writing `_minimax_h3.base_schedule` into `model_index.json`. Each generation reports the numberof Euler steps the scheduler actually took, read back off `scheduler.step_index`, rather than a hardcoded 4.## How it works| Piece | What runs here ||---|---|| Transformer | `MiniMaxH3Transformer3DModel` — the 33B / 50-block H3 DiT, bf16, with the FlashGen LoRA folded in || VAEs | `AutoencoderKLMiniMaxH3` (video) + `AutoencoderKLMiniMaxH3Audio` (audio), float32 || Schedulers | `MiniMaxH3Scheduler` with the 4-step distilled `base_schedule` `[1.0, 0.7, 0.4, 0.15, 0.0]` under each modality's own shift (video `12.0`, audio `3.0`) || Conditioning | Delegated to [`multimodalart/qwen3vl-conditioner`](https://huggingface.co/spaces/multimodalart/qwen3vl-conditioner) over the gradio API (the 62 GB Qwen3-VL text encoder does not fit alongside the transformer on a single ZeroGPU worker) |## How the LoRA is appliedThe LoRA repo ships its own merge script,[`merge_lora_ckpt.py`](https://huggingface.co/Beidouqixing/minimax-h3-4step-lora-flashgen/blob/main/merge_lora_ckpt.py),and this Space follows it rather than a default diffusers LoRA load. The adapter is **merged** into the base weightsat startup — `W' = W + scale * (lora_B @ lora_A)`, accumulated in fp32, at `scale = lora_alpha / rank = 1.0`(FlashGen's alpha equals its rank of 64) — instead of being attached as a runtime PEFT adapter, and all 259 LoRAtargets are required to resolve or startup fails, exactly as the reference script does.The reference script merges into the *original* MiniMax-H3 partition, whose keys are the LoRA's own(`blocks.N.attn.qkv_proj.weight`, `mlp.fc1/fc2`, `attn.out_proj`, `adaln_proj.linear`). Merging into the diffusersport instead requires replaying the same layout transforms[`convert_minimax_h3_to_diffusers.py`](https://github.com/huggingface/diffusers/blob/main/scripts/convert_minimax_h3_to_diffusers.py)applied to the base weights, because a delta is only valid in the layout of the weight it is added to:| Original LoRA target | diffusers parameter | Transform ||---|---|---|| `blocks.N.…` / `token_refiner.blocks.N.…` | `transformer_blocks.N.…` / `token_refiner.refiner_blocks.N.…` | rename || `attn.out_proj` | `attn.to_out.0` | rename || `mlp.fc2` | `ff.net.2` | rename || `final_layer.adaln_proj.linear` | `norm_out.linear` | rename || `adaln_proj.linear` | `adaln_proj.linear` | identity || `mlp.fc1` | `ff.net.0.proj` | fused halves swapped, `[gate; value]` → `[value; gate]` for diffusers' `SwiGLU` || `attn.qkv_proj` | `attn.to_q` / `to_k` / `to_v` | **de-interleave the per-head rows** (`[head0: q k v, head1: q k v, …]` → `[q_all; k_all; v_all]`), *then* split thirds |That last row is the one that is easy to get wrong: the checkpoint's fused QKV rows are per-head interleaved, sosplitting them into contiguous thirds — the naive reading — scatters every head's q/k/v across all three projectionsand turns the adapter into noise on all 52 attention blocks. With the de-interleave in place, the merged weightsreproduce `merge_lora_ckpt.py`-then-convert to within bf16 rounding.## LicenseMiniMax-H3 is covered by the **MiniMax H3 Community License Agreement**. The FlashGen LoRA is Apache-2.0.Read both before using any output of this Space.12345678910111213141516171819202122232425---title: MiniMax-H3 Motion Enhanceremoji: 🎬colorFrom: indigocolorTo: purplesdk: gradiosdk_version: 6.26.0app_file: app.pyshort_description: Animate a still image with MiniMax-H3 motionpython_version: "3.12"startup_duration_timeout: 1h---# MiniMax-H3 Motion EnhancerAnimate a still image with the 8-step motion-enhancer LoRA for [MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3).The app generates a short video and the model's native soundtrack.## Model- LoRA: [rzgar/minimax-h3_fl2v_8Step_motion_enhancer](https://huggingface.co/rzgar/minimax-h3_fl2v_8Step_motion_enhancer)- Base: [MiniMaxAI/MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3)- License: Apache-2.0 for the LoRA; see the base model's [MiniMax H3 Community License](https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/main/LICENSE)Use only images you own or have permission to animate. Do not upload private or intimate imagery of real people without their explicit consent.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812821 unmodified line2842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416423 unmodified lines646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026"""MiniMax-H3 4-Step FlashGen LoRA — text (and optional keyframes) to video + audio in 4 steps.The FlashGen LoRA (``Beidouqixing/minimax-h3-4step-lora-flashgen``) is a data-free DMD2 distillationadapter (rank 64, alpha == rank) that reduces MiniMax-H3's T2VA inference from ~20 steps to **4**. Ittargets the ``transformer/`` partition in the original checkpoint's naming (``blocks.N.attn.qkv_proj``,``mlp.fc1/fc2``, ``attn.out_proj``, ``adaln_proj.linear``). Following ``merge_lora_ckpt.py`` — the mergescript the LoRA repo ships — it is *merged* into the base weights at startup rather than attached as aruntime PEFT adapter: ``W' = W + scale * (lora_B @ lora_A)`` at ``scale = 1.0``, with every targetrequired to resolve. See the LoRA section below for the layout transforms the diffusers port needs.The distilled schedule ``[1.0, 0.7, 0.4, 0.15, 0.0]`` is a ``base_schedule``: it replaces the *uniform*``linspace(1, 0, num_inference_steps)`` grid that ``MiniMaxH3Scheduler.set_timesteps`` builds, and H3'sper-modality exponential sigma shift (``shift = 12.0`` video, ``3.0`` audio — the release's``_minimax_h3.sigma_shift_scales``) still applies on top of it. A single ``base_schedule`` serves twomodalities precisely because it is pre-shift. It is injected through``MiniMaxH3Scheduler.set_timesteps(sigmas=...)``, which takes a sigma grid verbatim, so each scheduler ishanded ``BASE_SCHEDULE`` already pushed through *its own* shift. Note that ``num_inference_steps`` counts*sigma grid points* for this scheduler (the terminal ``0.0`` included), so a 4-step schedule is 5 pointsand the pipeline has to be asked for 5, not 4 — and because the pipeline re-runs ``set_timesteps`` itselfinside the denoise step, the distilled grid is pinned onto both schedulers rather than merely set beforethe call.H3's 62 GiB Qwen3-VL text encoder does not fit alongside the 66 GiB transformer on a single ZeroGPUworker, so conditioning is delegated to ``multimodalart/qwen3vl-conditioner`` over the gradio API —the same split every MiniMax-H3 LoRA Space uses."""from __future__ import annotationsimport osimport tempfileimport timeimport tracebackfrom functools import cacheimport spacesimport gradio as grimport torchMODEL_REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3")LORA_REPO = os.environ.get("H3_LORA_REPO", "Beidouqixing/minimax-h3-4step-lora-flashgen")LORA_FILE = os.environ.get("H3_LORA_FILE", "minimax_h3_4step_lora_flashgen_v1.0_768p_bf16.safetensors")# Additional LoRAs, merged on top of the FlashGen 4-step weights.MOTION_LORA_REPO = os.environ.get("H3_MOTION_LORA_REPO","rzgar/minimax-h3_fl2v_8Step_motion_enhancer",)MOTION_LORA_FILE = os.environ.get("H3_MOTION_LORA_FILE","minimax-h3_fl2v_8Step_motion_enhancer.safetensors",)MOTION_LORA_SCALE = float(os.environ.get("H3_MOTION_LORA_SCALE", "1.0"))# Realism / anatomy LoRAs. These are folded after FlashGen and the existing# Motion Enhancer, using the same extra-LoRA merge path below.REALISM_LORA_REPO = os.environ.get("H3_REALISM_LORA_REPO","fal/MiniMax-H3-Realism-People-LoRA",)REALISM_LORA_FILE = os.environ.get("H3_REALISM_LORA_FILE","h3-realism-people-t2v-i2v-r2v.safetensors",)REALISM_LORA_SCALE = float(os.environ.get("H3_REALISM_LORA_SCALE", "0.8"))REALISM_LORA_TRIGGER = "r34l1sm"# Perfect Eyes / Skin / Hands. The original release is on Civitai, but the# weights are mirrored in a Hugging Face repository so this Space never needs# to contact Civitai at startup. The filename is pinned; no model-page/API lookup.DETAIL_LORA_REPO = os.environ.get("H3_DETAIL_LORA_REPO","Alex995647/loras-minimax-h3",)DETAIL_LORA_FILE = os.environ.get("H3_DETAIL_LORA_FILE","minimax-h3-t2va-t2v-polyhedron-perfect-eyes-perfect-skin/polyhedron_minimax_h3_image_lora_v2__perfe8ct.safetensors",)DETAIL_LORA_SCALE = float(os.environ.get("H3_DETAIL_LORA_SCALE", "0.7"))# Spatial & Physics: object collisions, gravity, stacking, falling, occlusion, and# more consistent spatial relationships. The clean pruned H3 adapter has no trigger word.SPATIAL_LORA_REPO = os.environ.get("H3_SPATIAL_LORA_REPO","Jojocodex/minimax-h3-spatial-physics-lora",)SPATIAL_LORA_FILE = os.environ.get("H3_SPATIAL_LORA_FILE","wushu_spatial_physics_clean_3000_pruned.safetensors",)SPATIAL_LORA_SCALE = float(os.environ.get("H3_SPATIAL_LORA_SCALE", "0.4"))# HMBreasts V2: H3 anatomy adapter for chest size/shape control.# The weight is pulled directly from Hugging Face; there is no Civitai/API lookup.BREASTS_LORA_REPO = os.environ.get("H3_BREASTS_LORA_REPO","Hearmeman/minimax-h3-loras",)BREASTS_LORA_FILE = os.environ.get("H3_BREASTS_LORA_FILE","HMBreastsV2.safetensors",)BREASTS_LORA_SCALE = float(os.environ.get("H3_BREASTS_LORA_SCALE", "1.0"))CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner")# ``pack`` places the transformer at startup (66 GB on disk via the spaces pack); VAEs move on first GPU call.PLACEMENT = os.environ.get("H3_PLACEMENT", "pack").lower()ATTENTION = os.environ.get("H3_ATTENTION", "_native_cudnn").lower()GPU_SIZE = os.environ.get("H3_GPU_SIZE", "xlarge")# The distilled schedule from the LoRA README: 5 *base* sigma points = 4 Euler steps. This is the grid# before H3's per-modality shift, i.e. the replacement for `linspace(1, 0, num_inference_steps)` — see# `shifted_schedule` below.BASE_SCHEDULE = [1.0, 0.7, 0.4, 0.15, 0.0]NUM_STEPS = len(BASE_SCHEDULE) - 1 # 4 model evaluations# `MiniMaxH3Scheduler.set_timesteps(num_inference_steps=...)` counts *sigma grid points*, terminal 0.0# included, and runs `len(sigmas) - 1` model evaluations (`timesteps = 1 - sigmas[:-1]`). So the number the# pipeline has to be given for NUM_STEPS Euler steps is NUM_STEPS + 1 == len(BASE_SCHEDULE); passing 4 there# yields a 4-point grid and only 3 steps.NUM_SIGMA_POINTS = len(BASE_SCHEDULE) # 5FPS, FRAMES_PER_CHUNK, LATENTS_PER_CHUNK = 24, 17, 5MIN_UI_DURATION, MAX_UI_DURATION = 2, 14CANVASES = {# 16:9"960x544 · 16:9 fast": (544, 960),"1024x576 · 16:9 fast": (576, 1024),"1152x640 · 16:9": (640, 1152),"1280x704 · 16:9": (704, 1280),"1344x768 · 16:9 full": (768, 1344),# 9:16"544x960 · 9:16 fast": (960, 544),"640x1152 · 9:16": (1152, 640),"768x1344 · 9:16 full": (1344, 768),# 1:1"544x544 · 1:1 fast": (544, 544),"768x768 · 1:1 full": (768, 768),# 4:3 / 3:4"768x576 · 4:3 fast": (576, 768),"1024x768 · 4:3 full": (768, 1024),"576x768 · 3:4 fast": (768, 576),"768x1024 · 3:4 full": (1024, 768),# 21:9"1152x512 · 21:9 fast": (512, 1152),"1536x672 · 21:9 full": (672, 1536),}DEFAULT_CANVAS = "960x544 · 16:9 fast"OUTPUT_DIR = os.path.join(tempfile.gettempdir(), "h3-flashgen-out")os.makedirs(OUTPUT_DIR, exist_ok=True)PIPE = NoneLOAD_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))while frames % FRAMES_PER_CHUNK != LATENTS_PER_CHUNK:frames += 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)*σ)``.``base_schedule`` is what ``merge_lora_ckpt.py`` pins into ``_minimax_h3.base_schedule``, and the nameis literal: it replaces the *base* grid — ``MiniMaxH3Scheduler.set_timesteps``'s``linspace(1, 0, num_inference_steps)``, which the merge script calls "the server's uniform schedule" —and the release's per-modality ``sigma_shift_scales`` (video ``12.0``, audio ``3.0``) still apply afterit. One schedule can only serve both modalities because it is pre-shift.Feeding the base grid to the model as if it were already shifted is what produced the ghosted,superimposed-frames output: every step conditioned the transformer on a timestep far from the latent'sreal noise level (σ 0.7 instead of 0.966, 0.4 instead of 0.889, 0.15 instead of 0.679), so eachprediction was an average over noise levels the student was never distilled at. The shift fixes 1.0 and0.0, so the endpoints — and the 4-step count — are unchanged."""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.Setting the sigmas before calling the pipeline is not enough: the denoise step contains``MiniMaxH3SetTimestepsStep``, which calls ``scheduler.set_timesteps(num_inference_steps, device=...)``itself and so rebuilds the uniform shifted grid, throwing the distilled one away. That grid is alsowhere the missing step went — ``num_inference_steps`` is a *grid point* count for this scheduler, sothe 4 we asked for produced a 4-sigma grid, i.e. ``len(sigmas) - 1 == 3`` model evaluations.The schedule pinned here is ``BASE_SCHEDULE`` under *this* scheduler's own ``shift``, so the videoscheduler (``shift = 12.0``) and the audio one (``shift = 3.0``) keep the distinct grids the twomodalities are denoised on. ``set_timesteps(sigmas=...)`` takes its argument verbatim, so the shift hasto be applied here rather than left to the scheduler.Pinning is the equivalent of ``merge_lora_ckpt.py``'s ``_minimax_h3.base_schedule`` in``model_index.json``: the served checkpoint carries its distilled schedule and the caller's step countcannot silently replace it."""if getattr(scheduler, "_flashgen_pinned", False):returnoriginal = scheduler.set_timestepspinned = shifted_schedule(scheduler.shift)def set_timesteps(num_inference_steps=None, device=None, sigmas=None):return original(device=device, sigmas=pinned if sigmas is None else sigmas)scheduler.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 a# default ``load_lora_adapter`` + ``set_adapters``. That script folds the adapter into the base# weights ahead of serving (``W' = W + scale * (lora_B @ lora_A)``, accumulated in fp32, with# ``scale = lora_alpha / rank = 1.0`` because FlashGen's alpha equals its rank of 64), pins the# distilled ``base_schedule``, and hard-fails if any LoRA target finds no base weight. We reproduce# all of that here — merge-and-unload semantics, not a runtime adapter.## The one thing the reference script never has to do is translate names: it merges into the# *original* MiniMax-H3 partition, whose keys are exactly the LoRA's own# (``blocks.N.attn.qkv_proj.weight``). Merging into the diffusers port instead means replaying the# very same transforms ``scripts/convert_minimax_h3_to_diffusers.py`` applied to the base weights,# because a delta is only valid in the layout of the weight it is added to:## * ``blocks.`` -> ``transformer_blocks.``, ``token_refiner.blocks.`` -># ``token_refiner.refiner_blocks.``, ``final_layer.adaln_proj.linear`` -> ``norm_out.linear``,# ``attn.out_proj`` -> ``attn.to_out.0``, ``mlp.fc2`` -> ``ff.net.2`` (pure renames),# * ``mlp.fc1`` -> ``ff.net.0.proj`` with its two fused halves swapped, because diffusers' SwiGLU# reads ``[value; gate]`` where the checkpoint stores ``[gate; value]``,# * ``attn.qkv_proj`` -> ``to_q`` / ``to_k`` / ``to_v``, and this is the subtle one: the fused QKV# rows of the original checkpoint are **per-head interleaved**# (``[head0: q k v, head1: q k v, ...]``), so they must be de-interleaved into# ``[q_all; k_all; v_all]`` *before* being split into thirds. Splitting the raw rows into# 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]``.Identical to ``reorder_interleaved_qkv`` in diffusers' MiniMax-H3 conversion script, whichapplies it to the base fused QKV weight before splitting it. ``lora_B`` indexes that same fusedoutput space, so the delta needs the same reorder."""grouped = weight.reshape(num_heads, 3 * head_dim, *weight.shape[1:])query, key, value = grouped.split(head_dim, dim=1)return torch.cat([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."):target = source_name.replace("token_refiner.blocks.", "token_refiner.refiner_blocks.", 1)elif source_name.startswith("blocks."):target = source_name.replace("blocks.", "transformer_blocks.", 1)else:target = 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)if target.endswith(".attn.qkv_proj"):prefix = target.removesuffix("qkv_proj")# De-interleave the per-head rows first, then split contiguous thirds — exactly the# composition the base fused QKV weight went through during conversion.rows = _reorder_interleaved_qkv(b_weight, num_heads, head_dim)for kind, part in zip(("q", "k", "v"), rows.split(num_heads * head_dim, dim=0)):yield f"{prefix}to_{kind}.weight", part.contiguous()elif target.endswith(".mlp.fc1"):# SwiGLU gate/value swap: the checkpoint stores [gate, value]; diffusers stores [value, gate].gate, value = b_weight.chunk(2, dim=0)yield target.replace(".mlp.fc1", ".ff.net.0.proj") + ".weight", torch.cat([value, gate]).contiguous()elif target.endswith(".mlp.fc2"):1 unmodified lineelif target.endswith(".attn.out_proj"):yield target.replace(".attn.out_proj", ".attn.to_out.0") + ".weight", b_weightelse:# 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 torchfrom huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filelora_path = hf_hub_download(LORA_REPO, LORA_FILE)lora = load_file(lora_path)# Same pairing and validation contract as merge_lora_ckpt.py's `load_lora_pairs`.suffix_a, suffix_b = ".lora_A.default.weight", ".lora_B.default.weight"bases = sorted({key[: -len(suffix_a)] for key in lora if key.endswith(suffix_a)})unexpected = [key for key in lora if not key.endswith((suffix_a, suffix_b))]if unexpected:raise ValueError(f"{LORA_FILE} holds {len(unexpected)} non-LoRA tensors, e.g. {unexpected[:5]}")if not bases:raise ValueError(f"No lora_A/lora_B pairs found in {LORA_FILE}")ranks = set()for name in bases:if f"{name}{suffix_b}" not in lora:raise ValueError(f"LoRA is missing the lora_B twin of {name}{suffix_a}")ranks.add(lora[f"{name}{suffix_a}"].shape[0])if len(ranks) != 1:raise ValueError(f"LoRA mixes ranks {sorted(ranks)}; a DMD2 student export uses a single rank")rank = ranks.pop()num_heads = transformer.config.num_attention_headshead_dim = transformer.config.attention_head_dim# merge_lora_ckpt.py's --scale, i.e. lora_alpha / rank; 1.0 because FlashGen's alpha == rank.scale = float(os.environ.get("H3_LORA_SCALE", "1.0"))params = dict(transformer.named_parameters())folded, missed = 0, []with torch.no_grad():for name in bases:a = lora[f"{name}{suffix_a}"]b = lora[f"{name}{suffix_b}"]for key, b_part in _lora_targets(name, b, num_heads, head_dim):param = params.get(key)if param is None:missed.append(key)continue# Accumulate in fp32 so a bf16 base does not swallow the update.delta = scale * (b_part.to(torch.float32) @ a.to(torch.float32))if delta.shape != param.shape:raise ValueError(f"LoRA delta for `{key}` has shape {tuple(delta.shape)}, "f"base weight is {tuple(param.shape)}")param.data = (param.data.float() + delta.to(param.device)).to(param.dtype)folded += 1# merge_lora_ckpt.py treats an unmatched target as fatal, and so do we: a silently skipped# target means the name mapping is wrong and the demo would serve a half-applied adapter.if missed:raise ValueError(f"{len(missed)} LoRA targets matched no transformer weight, e.g. {missed[:5]}. ""The LoRA and the diffusers transformer disagree on module naming.")return (f"FlashGen LoRA merged · {len(bases)} targets, rank {rank}, scale {scale:g} "f"-> {folded} weight deltas · {LORA_FILE}")# ── Additional LoRAs ─────────────────────────────────────────────────────────## These are folded after FlashGen, so the original 4-step FlashGen schedule and# all of its QKV/layout handling remain unchanged. The extra adapters use the# standard .lora_A.weight/.lora_B.weight export used by the motion-enhancer and# additional H3 checkpoints.def _apply_extra_lora(transformer,repo_id: str,filename: str,label: str,scale: float = 1.0,) -> str:from huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_file# All adapters used by this Space are pinned to repository/file paths.# There is deliberately no Civitai/API fallback here: startup must only# resolve repository files through the Hugging Face Hub.path = hf_hub_download(repo_id, filename)lora = load_file(path, device="cpu")normalized = {}for key, tensor in lora.items():k = keyif k.startswith("lora_unet__"):k = k.replace("lora_unet__", "", 1)k = k.replace("_blocks_", ".blocks.")k = k.replace("_self_attn_", ".attn.")k = k.replace("_ffn_net_0_proj", ".mlp.fc1")k = k.replace("_ffn_net_2", ".mlp.fc2")k = k.replace("to_out_0", "out_proj")elif k.startswith("lora_unet_"):body = k[len("lora_unet_"):]parts = body.split(".")head = parts[0].split("_")out = []i = 0while i < len(head):if head[i] == "blocks" and i + 1 < len(head) and head[i + 1].isdigit():out += ["blocks", head[i + 1]]i += 2continueif head[i] == "self" and i + 1 < len(head) and head[i + 1] == "attn":out.append("attn")i += 2continueout.append(head[i])i += 1k = ".".join(out + parts[1:])for prefix in ("base_model.model.", "diffusion_model.", "transformer.", "pipe.dit."):if k.startswith(prefix):k = k[len(prefix):]k = k.replace(".self_attn.", ".attn.")k = k.replace(".ffn.0.", ".mlp.fc1.")k = k.replace(".ffn.2.", ".mlp.fc2.")k = k.replace(".lora_down.weight", ".lora_A.weight")k = k.replace(".lora_up.weight", ".lora_B.weight")k = k.replace(".lora_A.default.weight", ".lora_A.weight")k = k.replace(".lora_B.default.weight", ".lora_B.weight")normalized[k] = tensorlora = normalizedsuffix_a = ".lora_A.weight"suffix_b = ".lora_B.weight"bases = sorted({key[: -len(suffix_a)] for key in lora if key.endswith(suffix_a)})if not bases:sample = list(lora.keys())[:5]raise ValueError(f"{label}: no lora_A/lora_B pairs found; keys: {sample}")params = dict(transformer.named_parameters())num_heads = transformer.config.num_attention_headshead_dim = transformer.config.attention_head_dimfolded = 0missed = []with torch.no_grad():for name in bases:a = lora[f"{name}{suffix_a}"]b = lora.get(f"{name}{suffix_b}")if b is None:raise ValueError(f"{label}: missing lora_B for {name}")# These older H3 LoRAs use the original checkpoint names. Reuse# the same layout transforms as the FlashGen merge path.source_name = name.removeprefix("diffusion_model.")target_name = _lora_target_name(source_name)# ComfyUI H3 LoRAs may store q/k/v as separate targets. The# diffusers H3 transformer used by this Space has separate to_q/k/v# parameters, so those can be folded directly.if target_name.endswith((".attn.q", ".attn.k", ".attn.v")):kind = target_name.rsplit(".", 1)[-1]target_parts = [(target_name.replace(f".attn.{kind}", f".attn.to_{kind}") + ".weight",b,)]elif target_name.endswith(".attn.qkv_proj"):prefix = target_name.removesuffix("qkv_proj")rows = _reorder_interleaved_qkv(b, num_heads, head_dim)targets = zip(("q", "k", "v"),rows.split(num_heads * head_dim, dim=0),)target_parts = [(f"{prefix}to_{kind}.weight", part.contiguous())for kind, part in targets]elif target_name.endswith(".mlp.fc1"):gate, value = b.chunk(2, dim=0)target_parts = [(target_name.replace(".mlp.fc1", ".ff.net.0.proj") + ".weight",torch.cat([value, gate]).contiguous(),)]elif target_name.endswith(".mlp.fc2"):target_parts = [(target_name.replace(".mlp.fc2", ".ff.net.2") + ".weight",b,)]elif target_name.endswith(".attn.out_proj"):target_parts = [(target_name.replace(".attn.out_proj", ".attn.to_out.0") + ".weight",b,)]else:target_parts = [(target_name + ".weight", b)]for key, b_part in target_parts:param = params.get(key)if param is None:missed.append(key)continuedelta = float(scale) * (b_part.float() @ a.float())if delta.shape != param.shape:raise ValueError(f"{label}: LoRA shape mismatch for {key}: "f"{tuple(delta.shape)} vs {tuple(param.shape)}")param.data = (param.data.float() + delta.to(param.device)).to(param.dtype)folded += 1if missed:raise ValueError(f"{label}: {len(missed)} LoRA targets did not match the H3 transformer, "f"e.g. {missed[:5]}")return (f"{label} merged · {len(bases)} targets, "f"{folded} weight deltas · scale {float(scale):g}")def load_and_apply_extra_loras(transformer) -> list[str]:return [_apply_extra_lora(transformer,MOTION_LORA_REPO,MOTION_LORA_FILE,"Motion Enhancer LoRA",MOTION_LORA_SCALE,),_apply_extra_lora(transformer,REALISM_LORA_REPO,REALISM_LORA_FILE,"H3 Realism People LoRA",REALISM_LORA_SCALE,),_apply_extra_lora(transformer,DETAIL_LORA_REPO,DETAIL_LORA_FILE,"Perfect Eyes / Skin / Hands LoRA",DETAIL_LORA_SCALE,),_apply_extra_lora(transformer,SPATIAL_LORA_REPO,SPATIAL_LORA_FILE,"Spatial & Physics LoRA",SPATIAL_LORA_SCALE,),_apply_extra_lora(transformer,BREASTS_LORA_REPO,BREASTS_LORA_FILE,"HMBreasts V2 LoRA",BREASTS_LORA_SCALE,),]# ── 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_INif PIPE is not None or LOAD_ERROR is not None:return LOAD_ERRORstarted = time.time()try:import torchfrom diffusers import ComponentsManagerfrom h3_split_blocks import MiniMaxH3GeneratorBlockslower_duration_floor()manager = ComponentsManager()blocks = MiniMaxH3GeneratorBlocks()print(f"[gen] loading {[c.name for c in blocks.expected_components]} from {MODEL_REPO} ...", flush=True)pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")pipe.load_components(dtype=torch.bfloat16)pipe.vae.set_attention_backend("native")pipe.audio_vae.set_attention_backend("native")pipe.transformer.set_attention_backend(ATTENTION)# Fold the original FlashGen LoRA first. Its distilled 4-step schedule# remains the schedule used by the merged transformer.lora_status = load_and_apply_lora(pipe.transformer)print(f"[gen] {lora_status}", flush=True)# Then fold the requested extra LoRAs into the same transformer.# They add their deltas on top of FlashGen.for extra_status in load_and_apply_extra_loras(pipe.transformer):print(f"[gen] {extra_status}", flush=True)# ... and pin the distilled schedule the merged weights were trained for, so the pipeline's own# `set_timesteps` call cannot fall back to a uniform grid (and to NUM_STEPS - 1 evaluations).pin_distilled_schedule(pipe.scheduler)pin_distilled_schedule(pipe.audio_scheduler)print(f"[gen] distilled base_schedule {BASE_SCHEDULE} pinned -> {NUM_STEPS} steps; "f"video σ (shift {pipe.scheduler.shift:g}) "f"{[round(s, 4) for s in shifted_schedule(pipe.scheduler.shift)]}, "f"audio σ (shift {pipe.audio_scheduler.shift:g}) "f"{[round(s, 4) for s in shifted_schedule(pipe.audio_scheduler.shift)]}",flush=True,)if PLACEMENT == "pack":pipe.transformer.to("cuda")PIPE = pipeLOADED_IN = time.time() - startedprint(f"[gen] ready in {LOADED_IN:.0f}s", flush=True)except Exception as error:traceback.print_exc()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 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.``rewrite_prompt`` is the same prompt-enhancement path ``multimodalart/minimax-h3`` uses: the conditionerSpace already hosts H3's Qwen3-VL, so it first has that model *rewrite* the prompt into MiniMax-H3'sstructured shot description (the LLM-based rewriting step) and then encodes the rewritten text instead ofthe raw one. The rewritten text comes back in the plan under ``refined_prompt`` (``None`` when no rewritehappened). Encoding the enhanced prompt on the conditioner keeps the enhancement and the embeddings insync — nothing about the FlashGen merge, the 4-step schedule, or the VAEs is involved."""from gradio_client import handle_filefrom safetensors import safe_opendef call():return conditioner_client(ip_token).predict(prompt=prompt,image_path=handle_file(image_path) if image_path else None,last_image_path=handle_file(last_image_path) if last_image_path else None,canvas=canvas,num_frames=num_frames,rewrite_prompt=bool(rewrite_prompt),3 unmodified linestry:path, plan = call()except Exception as first:print(f"[conditioner] retrying with a fresh client after: {first}", flush=True)conditioner.cache_clear()path, plan = call()with safe_open(path, framework="pt") as handle:metadata = 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()from gradio_client import Clientreturn 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``.Same selection ``multimodalart/minimax-h3`` makes: among the canvases sharing a ratio keep thesmallest (fastest) one, then take the ratio nearest the image's — so a 3:4 photo renders 3:4 ratherthan being letterboxed into the 16:9 default. A canvas the user already picked is kept when it is atleast as close to the image as the best candidate, so ``1344x768`` survives a 1.75 image."""fastest: dict[float, tuple[str, tuple[int, int]]] = {}for label, (h, w) in CANVASES.items():r = w / hif r not in fastest or w * h < fastest[r][1][0] * fastest[r][1][1]:fastest[r] = (label, (h, w))ratio = min(fastest, key=lambda r: abs(r - aspect))cur_h, cur_w = CANVASES[current_canvas]if abs(cur_w / cur_h - aspect) <= abs(ratio - aspect):return current_canvasreturn fastest[ratio][0]def _cover_crop(image_path: str, canvas_label: str) -> str:"""Resize/crop the keyframe to fill the selected canvas, with no blurred background."""from PIL import Image as _Image, ImageOps as _ImageOpsh, w = CANVASES[canvas_label]with _Image.open(image_path) as source:img = _ImageOps.exif_transpose(source).convert("RGB")if img.size == (w, h):return image_path# Fill the complete canvas; if aspect ratios differ, crop excess edges.fitted = _ImageOps.fit(img, (w, h), method=_Image.Resampling.LANCZOS)fitted.save(image_path)return image_pathdef _fit_keyframe(image_path, current_canvas):"""Fit a keyframe to the selected canvas ratio without changing the selected resolution."""return _cover_crop(image_path, current_canvas), current_canvasdef _fit_keyframe_ui(image_path, current_canvas):"""Crop the uploaded keyframe to the selected canvas ratio; preserve the Canvas dropdown."""path = _as_path(image_path)if not path:return gr.update(), gr.update()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 lastframe uploaded on top of it is only cover-cropped to the canvas already chosen."""path = _as_path(last_image_path)if not path:return gr.update(), gr.update()if _as_path(image_path):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, 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)steps = NUM_STEPSlatent_frames = (num_frames - LATENTS_PER_CHUNK) // FRAMES_PER_CHUNK * LATENTS_PER_CHUNK + 2patches = (height // 32) * (width // 32)rows = latent_frames * patches + (int(image is not None) + int(last_image is not None)) * patchesdenoise = steps * (_DUR_B * rows + _DUR_C * rows**2)decode = _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."""import torchif PLACEMENT == "pack":PIPE.vae.to("cuda")PIPE.audio_vae.to("cuda")elif PLACEMENT == "lazy":PIPE.to("cuda")# Inject the distilled base_schedule into both schedulers, and keep it there: the pipeline calls# `set_timesteps` again inside its denoise step, so the schedule has to survive that call.pin_distilled_schedule(PIPE.scheduler)pin_distilled_schedule(PIPE.audio_scheduler)PIPE.scheduler.set_timesteps(device="cuda")PIPE.audio_scheduler.set_timesteps(device="cuda")state = PIPE(prompt_embeds=prompt_embeds.to("cuda"),text_token_tags=text_token_tags,image=image,last_image=last_image,height=height,width=width,num_frames=num_frames,# Grid points, terminal 0.0 included -> NUM_STEPS Euler steps. See NUM_SIGMA_POINTS above.num_inference_steps=NUM_SIGMA_POINTS,generator=torch.Generator("cpu").manual_seed(int(seed)),)# Read the step count back off the scheduler rather than trusting the constant: `step_index` counted# the Euler updates the denoise loop actually took, and `sigmas` is the grid it took them on.steps_taken = int(PIPE.scheduler.step_index or 0)sigmas_used = [round(float(s), 4) for s in PIPE.scheduler.sigmas.tolist()]return (state.get("videos")[0],state.get("audio")[0].cpu(),state.get("sampling_rate"),steps_taken,sigmas_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,last_image_path=None,canvas=DEFAULT_CANVAS,duration=5,seed=42,enhance_prompt=False,progress=gr.Progress(track_tqdm=True),):"""One request: prompt (+ optional first/last frame) -> video with synchronized audio.``enhance_prompt`` turns on the conditioner's LLM prompt rewriting (the same enhancement``multimodalart/minimax-h3`` offers); off, the raw prompt is encoded verbatim as before. It is last anddefaults to off, so a positional API client written against the previous signature is unaffected."""if LOAD_ERROR:raise gr.Error(LOAD_ERROR.replace("**", "").replace("`", ""))if PIPE is None:raise gr.Error("The model is still loading — watch the Space logs and retry shortly.")if not prompt or not prompt.strip():raise gr.Error("MiniMax-H3 always takes a prompt, keyframes or not.")from PIL import Image, ImageOpsfrom diffusers.utils import encode_video# The user's Canvas selection is authoritative. Crop keyframes to its aspect ratio,# but never replace the selected resolution with a preset chosen from the source image.first, last = _as_path(image_path), _as_path(last_image_path)if first:first = _cover_crop(first, canvas)if last:last = _cover_crop(last, canvas)num_frames = snap_frames(duration)progress(0.0, desc="Enhancing the prompt, then encoding ..." if enhance_prompt else "Encoding prompt ...")conditioned = time.time()condition_prompt = prompt# Realism People was trained with the `r34l1sm` trigger. Keep it hidden# from the UI while ensuring the adapter receives its intended trigger.if REALISM_LORA_TRIGGER.lower() not in condition_prompt.lower():condition_prompt = f"{REALISM_LORA_TRIGGER}, {condition_prompt}"prompt_embeds, text_token_tags, metadata, plan = encode_remote(condition_prompt,first,last,canvas,num_frames,ip_token=_caller_ip_token(),rewrite_prompt=bool(enhance_prompt),)condition_seconds = time.time() - conditioned# Keep the requested Canvas dimensions even if the remote conditioner reports a fallback size.height, width = CANVASES[canvas]num_frames = int(metadata["num_frames"])# `None` whenever no rewrite happened — either none was asked for, or the conditioner declined one.enhanced = (plan or {}).get("refined_prompt") or ""def keyframe(path):return ImageOps.exif_transpose(Image.open(path)).convert("RGB") if path else Noneprogress(0.1, desc=f"Generating {num_frames / FPS:.1f}s at {width}x{height} in {NUM_STEPS} steps ...")started = time.time()frames, audio, sampling_rate, steps_taken, sigmas_used = _generate(prompt_embeds,text_token_tags,keyframe(first),keyframe(last),height,width,num_frames,seed,)generate_seconds = time.time() - startedpath = os.path.join(OUTPUT_DIR, f"h3-flashgen-{int(time.time() * 1000)}.mp4")encode_video(frames, fps=FPS, output_path=path, audio=audio, audio_sample_rate=sampling_rate)# Verify the encoded MP4 dimensions. If the pipeline/encoder emitted another size, normalize# the final video to the selected Canvas while preserving its audio track.import jsonimport shutilimport subprocessffprobe = shutil.which("ffprobe")ffmpeg = shutil.which("ffmpeg")actual_width, actual_height = width, heightif ffprobe:probe = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0","-show_entries", "stream=width,height", "-of", "json", path],capture_output=True, text=True, check=True,)streams = json.loads(probe.stdout).get("streams", [])if streams:actual_width = int(streams[0]["width"])actual_height = int(streams[0]["height"])resized = Falseif (actual_width, actual_height) != (width, height):if not ffmpeg:raise gr.Error(f"Выбрано {width}x{height}, но модель создала {actual_width}x{actual_height}; ""FFmpeg недоступен для исправления размера.")corrected = path[:-4] + "-canvas.mp4"subprocess.run([ffmpeg, "-y", "-i", path,"-vf",f"scale={width}:{height}:force_original_aspect_ratio=increase:flags=lanczos,"f"crop={width}:{height},setsar=1","-map", "0:v:0", "-map", "0:a?","-c:v", "libx264", "-preset", "veryfast", "-crf", "18","-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", corrected],capture_output=True, text=True, check=True,)os.replace(corrected, path)resized = Trueprint(f"[canvas] Model/encoder output {actual_width}x{actual_height}; "f"final MP4 filled to selected Canvas (excess edges cropped) {width}x{height}.",flush=True,)# Reported, not assumed: `steps_taken` is the number of Euler updates the scheduler actually took.schedule = " → ".join(f"{s:g}" for s in sigmas_used)report = (f"{width}x{height}{' (final size corrected with FFmpeg)' if resized else ''} · "f"{num_frames} frames ({num_frames / FPS:.3f}s) · "f"{steps_taken} steps (FlashGen σ {schedule}) · "f"conditioner {condition_seconds:.0f}s{' (prompt enhanced)' if enhanced else ''} · "f"denoise + decode {generate_seconds:.0f}s · seed {int(seed)}")print(f"[gen] {report}", flush=True)expected_sigmas = [round(s, 4) for s in shifted_schedule(PIPE.scheduler.shift)]if steps_taken != NUM_STEPS or sigmas_used != expected_sigmas:print(f"[gen] WARNING: expected {NUM_STEPS} steps on {expected_sigmas} "f"(base_schedule {BASE_SCHEDULE} at shift {PIPE.scheduler.shift:g}), "f"ran {steps_taken} on {sigmas_used}",flush=True,)return path, report, enhanced, gr.update(visible=bool(enhanced))# ── UI ──────────────────────────────────────────────────────────────────────CSS = """.main.fillable { max-width: 1100px !important; }"""EXAMPLE_PROMPTS = ["Cinematic, medium wide shot. A golden retriever puppy chases autumn leaves through a sunlit park, leaves swirling around it. Warm afternoon light, shallow depth of field. The dog barks playfully and leaves rustle.","A serene Japanese garden with a koi pond. Cherry blossom petals drift slowly on the water's surface. A small wooden bridge arcs over the pond. Gentle wind chimes tinkle in the breeze. Ambient birdsong and water sounds.","Close-up of a chef's hands kneading dough on a flour-dusted wooden board. Flour particles float in the warm kitchen light. The dough stretches and folds rhythmically. Soft thumping sounds of dough and ambient kitchen noise.","A neon-lit cyberpunk street in the rain. Reflected neon signs shimmer in puddles. A figure in a long coat walks away from camera. Rain patters on metal awnings, distant synth music echoes.","A majestic eagle soars over snow-capped mountains at golden hour. The camera follows from behind, sweeping past peaks. Wind rushes past. Distant orchestral music swells.",]with gr.Blocks(title="MiniMax-H3 4-Step FlashGen") as demo:with gr.Row(equal_height=True):with gr.Column():prompt = gr.Textbox(label="Prompt",lines=4,value=EXAMPLE_PROMPTS[0],placeholder="Describe the scene, shot style, and soundscape ...",)enhance = gr.Checkbox(label="Enhance prompt",value=False,)with gr.Accordion("Image-to-video (optional)", open=True):with gr.Row():image = gr.Image(label="First frame (optional)", type="filepath", height=200)last_image = gr.Image(label="Last frame (optional)", type="filepath", height=200)run = gr.Button("Generate", variant="primary", size="lg")with gr.Accordion("Advanced", open=False):canvas = gr.Dropdown(label="Canvas", choices=list(CANVASES), value=DEFAULT_CANVAS)duration = gr.Slider(label="Duration (s)",minimum=MIN_UI_DURATION,maximum=MAX_UI_DURATION,step=1,value=5,)seed = gr.Number(label="Seed", value=42, precision=0)with gr.Column():result = gr.Video(label="Video + soundtrack", autoplay=True)report = gr.Markdown()# An output, so it is revealed only for a request that actually asked for an enhancement.with gr.Accordion("Enhanced prompt", open=False, visible=False) as enhanced_panel:enhanced_box = gr.Textbox(show_label=False, lines=8, interactive=False)OUTPUTS = [result, report, enhanced_box, enhanced_panel]# An uploaded I2V frame decides the output geometry: snap Canvas to the nearest supported ratio and# cover-crop the frame to it, right away, so what is shown is what will be rendered.image.upload(_fit_keyframe_ui, [image, canvas], [image, canvas])last_image.upload(_fit_last_keyframe_ui, [last_image, image, canvas], [last_image, canvas])gr.Examples(examples=[[p] for p in EXAMPLE_PROMPTS],inputs=[prompt],fn=generate,outputs=OUTPUTS,cache_examples=True,cache_mode="lazy",)run.click(generate,inputs=[prompt, image, last_image, canvas, duration, seed, enhance],outputs=OUTPUTS,api_name="generate",)prompt.submit(generate,inputs=[prompt, image, last_image, canvas, duration, seed, enhance],outputs=OUTPUTS,api_name="generate_submit",)load_models()if __name__ == "__main__":demo.launch(show_error=True, theme=gr.themes.Citrus(), css=CSS, allowed_paths=[OUTPUT_DIR])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465661 unmodified line68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741753 unmodified lines179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327from __future__ import annotationsimport osimport tempfileimport timefrom functools import lru_cacheimport spacesos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")import gradio as grimport torchfrom h3_split_blocks import MiniMaxH3GeneratorBlocksMODEL_REPO = "MiniMaxAI/MiniMax-H3"LORA_REPO = "rzgar/minimax-h3_fl2v_8Step_motion_enhancer"LORA_FILE = "minimax-h3_fl2v_8Step_motion_enhancer.safetensors"CONDITIONER_SPACE = "multimodalart/qwen3vl-conditioner"FPS = 24STEPS = 8OUTPUT_DIR = os.path.join(tempfile.gettempdir(), "minimax-h3-motion-enhancer")os.makedirs(OUTPUT_DIR, exist_ok=True)CANVASES = {"960x544 · 16:9 fast": (544, 960),"1024x576 · 16:9 fast": (576, 1024),"544x960 · 9:16 fast": (960, 544),"544x544 · 1:1 fast": (544, 544),"768x576 · 4:3 fast": (576, 768),"576x768 · 3:4 fast": (768, 576),"1152x512 · 21:9 fast": (512, 1152),}DEFAULT_CANVAS = "960x544 · 16:9 fast"def _reorder_interleaved_qkv(weight: torch.Tensor, num_heads: int, head_dim: int) -> torch.Tensor:grouped = weight.reshape(num_heads, 3 * head_dim, *weight.shape[1:])query, key, value = grouped.split(head_dim, dim=1)return torch.cat([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:target = source_name.removeprefix("diffusion_model.")if target.startswith("token_refiner.blocks."):target = target.replace("token_refiner.blocks.", "token_refiner.refiner_blocks.", 1)elif target.startswith("blocks."):target = target.replace("blocks.", "transformer_blocks.", 1)return target.replace("final_layer.adaln_proj.linear", "norm_out.linear")def _lora_targets(name: str, b_weight: torch.Tensor, num_heads: int, head_dim: int):target = _lora_target_name(name)if target.endswith(".attn.qkv_proj"):prefix = target.removesuffix("qkv_proj")rows = _reorder_interleaved_qkv(b_weight, num_heads, head_dim)for kind, part in zip(("q", "k", "v"), rows.split(num_heads * head_dim, dim=0)):yield f"{prefix}to_{kind}.weight", part.contiguous()elif target.endswith(".mlp.fc1"):gate, value = b_weight.chunk(2, dim=0)yield target.replace(".mlp.fc1", ".ff.net.0.proj") + ".weight", torch.cat([value, gate]).contiguous()elif target.endswith(".mlp.fc2"):1 unmodified lineelif target.endswith(".attn.out_proj"):yield target.replace(".attn.out_proj", ".attn.to_out.0") + ".weight", b_weightelse:yield target + ".weight", b_weightdef _apply_motion_lora(transformer) -> str:from huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filepath = hf_hub_download(LORA_REPO, LORA_FILE)lora = load_file(path, device="cpu")suffix_a = ".lora_A.weight"suffix_b = ".lora_B.weight"bases = sorted({key[: -len(suffix_a)] for key in lora if key.endswith(suffix_a)})if not bases:raise ValueError("The motion enhancer LoRA did not contain any lora_A/lora_B pairs")params = dict(transformer.named_parameters())num_heads = transformer.config.num_attention_headshead_dim = transformer.config.attention_head_dimfolded = 0missed = []with torch.no_grad():for name in bases:a = lora[f"{name}{suffix_a}"]b = lora.get(f"{name}{suffix_b}")if b is None:raise ValueError(f"Missing LoRA B matrix for {name}")for key, b_part in _lora_targets(name, b, num_heads, head_dim):param = params.get(key)if param is None:missed.append(key)continuedelta = b_part.float() @ a.float()if delta.shape != param.shape:raise ValueError(f"LoRA shape mismatch for {key}: {delta.shape} vs {param.shape}")param.data = (param.data.float() + delta.to(param.device)).to(param.dtype)folded += 1if missed:raise ValueError(f"{len(missed)} LoRA targets did not match the H3 transformer, e.g. {missed[:3]}")return f"Motion enhancer loaded: {len(bases)} adapters, {folded} matrices"def _load_pipeline():from diffusers import ComponentsManagermanager = ComponentsManager()blocks = MiniMaxH3GeneratorBlocks()pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")pipe.load_components(dtype=torch.bfloat16)pipe.vae.set_attention_backend("native")pipe.audio_vae.set_attention_backend("native")pipe.transformer.set_attention_backend(os.environ.get("H3_ATTENTION", "_native_cudnn"))print(_apply_motion_lora(pipe.transformer), flush=True)# Module-scope placement lets ZeroGPU pack the weights once instead of per request.pipe.transformer.to("cuda")return pipePIPE = _load_pipeline()@lru_cache(maxsize=1)def _conditioner_client():from gradio_client import Clientreturn Client(CONDITIONER_SPACE)def _snap_frames(seconds: float) -> int:frames = max(120, round(float(seconds) * FPS))while frames % 17 != 5:frames += 1return framesdef _cover_crop(image_path: str, canvas: str) -> str:from PIL import Image, ImageOpsheight, width = CANVASES[canvas]with Image.open(image_path) as image:image = ImageOps.exif_transpose(image).convert("RGB")image = ImageOps.fit(image, (width, height), method=Image.Resampling.LANCZOS)output = os.path.join(OUTPUT_DIR, f"frame-{time.time_ns()}.png")image.save(output)return outputdef _condition(prompt: str, image_path: str, canvas: str, num_frames: int, rewrite_prompt: bool = False):"""Encode the prompt through the same Qwen3-VL conditioner path used by FlashGen.When rewrite_prompt=True, the conditioner first rewrites the user's prompt intoMiniMax-H3's structured shot description, then encodes that rewritten prompt.This is the "Upsample/Enhance prompt" behavior from the FlashGen Space."""from gradio_client import handle_filefrom safetensors import safe_opendef call():return _conditioner_client().predict(prompt=prompt,image_path=handle_file(image_path),last_image_path=None,canvas=canvas,num_frames=num_frames,rewrite_prompt=bool(rewrite_prompt),3 unmodified linestry:path, plan = call()except Exception as first:# The conditioner can occasionally leave a stale Gradio client behind.# Retry once with a fresh client, matching the FlashGen implementation.print(f"[conditioner] retrying with a fresh client after: {first}", flush=True)_conditioner_client.cache_clear()path, plan = call()with safe_open(path, framework="pt") as handle:embeds = handle.get_tensor("prompt_embeds")tags = handle.get_tensor("text_token_tags")metadata = handle.metadata()return embeds, tags, metadata, plan@spaces.GPU(duration=120, size="xlarge")def _generate_gpu(embeds, tags, image, height: int, width: int, num_frames: int, seed: int):"""Run MiniMax-H3 denoising and return CPU video frames plus soundtrack."""PIPE.vae.to("cuda")PIPE.audio_vae.to("cuda")pipe_state = PIPE(prompt_embeds=embeds.to("cuda"),text_token_tags=tags,image=image,height=int(height),width=int(width),num_frames=int(num_frames),num_inference_steps=STEPS + 1,generator=torch.Generator("cpu").manual_seed(int(seed)),)frames = pipe_state.get("videos")[0]audio = pipe_state.get("audio")[0]if torch.is_tensor(frames):frames = frames.cpu()if torch.is_tensor(audio):audio = audio.cpu()return frames, audio, int(pipe_state.get("sampling_rate"))def generate(prompt: str,image_path: str | None,canvas: str,duration: float,seed: int,enhance_prompt: bool = False,progress=gr.Progress(track_tqdm=True),):"""Animate an uploaded image, optionally using H3's Qwen3-VL prompt enhancement."""if not image_path:raise gr.Error("Upload a first frame before generating.")if not prompt or not prompt.strip():raise gr.Error("Describe the motion you want to see.")height, width = CANVASES[canvas]num_frames = _snap_frames(duration)cropped_path = _cover_crop(image_path, canvas)from PIL import Imagefrom diffusers.utils import encode_videoprogress(0.05,desc="Enhancing prompt, then encoding..." if enhance_prompt else "Encoding the first frame...",)embeds, tags, metadata, plan = _condition(prompt.strip(), cropped_path, canvas, num_frames, rewrite_prompt=bool(enhance_prompt))height = int(metadata.get("height", height))width = int(metadata.get("width", width))num_frames = int(metadata.get("num_frames", num_frames))enhanced = (plan or {}).get("refined_prompt") or ""progress(0.15, desc=f"Generating {num_frames / FPS:.1f}s at {width}x{height} in {STEPS} steps")with Image.open(cropped_path) as image:frames, audio, sampling_rate = _generate_gpu(embeds, tags, image.convert("RGB"), height, width, num_frames, int(seed))output = os.path.join(OUTPUT_DIR, f"motion-enhanced-{time.time_ns()}.mp4")encode_video(frames, fps=FPS, output_path=output, audio=audio, audio_sample_rate=sampling_rate)status = (f"{width}x{height} · {num_frames / FPS:.2f}s · {STEPS} denoising steps · "f"seed {int(seed)}")return output, status, enhanced, gr.update(visible=bool(enhanced))DESCRIPTION = """# MiniMax-H3 Motion EnhancerUpload a still image and describe the movement. The Space uses the **8-step Motion Enhancer LoRA**with MiniMax-H3 and synchronized audio.**Enhance / Upsample prompt** uses the same Qwen3-VL prompt-rewriting path as the MiniMax-H3 FlashGenSpace: your short instruction is first expanded into a structured shot/action/sound description andthen those rewritten embeddings are sent to H3.Use only images you own or have permission to animate."""with gr.Blocks(title="MiniMax-H3 Motion Enhancer") as demo:gr.Markdown(DESCRIPTION)with gr.Row(equal_height=True):with gr.Column(scale=1):image = gr.Image(label="First frame", type="filepath", sources=["upload", "webcam"])prompt = gr.Textbox(label="Motion prompt",value="The person naturally performs the described action. Keep the same identity and appearance. Natural body motion, realistic facial expression, synchronized sound effects and speech if specified.",lines=5,placeholder="Describe the action, camera movement and sound...",)enhance = gr.Checkbox(label="Enhance / Upsample prompt",value=False,info="Rewrite the prompt with H3's Qwen3-VL into a detailed structured shot description before generation.",)with gr.Row():canvas = gr.Dropdown(list(CANVASES), value=DEFAULT_CANVAS, label="Output canvas")duration = gr.Slider(5, 15, value=5, step=1, label="Duration (seconds)")seed = gr.Number(value=42, precision=0, label="Seed")generate_button = gr.Button("Generate motion", variant="primary", size="lg")with gr.Column(scale=1):video = gr.Video(label="Generated video + soundtrack", autoplay=True)status = gr.Markdown()with gr.Accordion("Upsampled prompt", open=False, visible=False) as enhanced_panel:enhanced_box = gr.Textbox(show_label=False, lines=10, interactive=False)outputs = [video, status, enhanced_box, enhanced_panel]generate_button.click(fn=generate,inputs=[prompt, image, canvas, duration, seed, enhance],outputs=outputs,api_name="generate",)prompt.submit(fn=generate,inputs=[prompt, image, canvas, duration, seed, enhance],outputs=outputs,api_name="generate_submit",)demo.queue(max_size=8).launch(mcp_server=True)
12345678910111213141516 unmodified lines323334353637383940414243444546474849505152535455565758596061626364656667686970717273747 unmodified lines8283848586878889902 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281294 unmodified lines134135136137138139140141142143144145146147"""The halves of a **split** MiniMax-H3 deployment, for both of its checkpoint partitions.MiniMax-H3 is 195.9 GiB in bfloat16 and a ZeroGPU Space is evicted at 150 GB of storage, so `MiniMaxH3Blocks` is cutat its `text_encoder` step: the 62.14 GiB Qwen3-VL runs in the conditioner Space, everything else in a generatorSpace, and `prompt_embeds` + `text_token_tags` is the whole wire format between them.`resize` / `setup` run on **both** sides: they own no pretrained component, and each half needs the canvas and theprepared keyframes or normalized references. Both conditioner halves also return the resolved `height` / `width` /`num_frames`, which the generating half pins rather than re-deriving.Two things the blocks leave to the caller: a keyframe reaches them EXIF-transposed and in RGB, and the `t2va` / `fl2va`frame count is aligned to `17 * n + 5` before the call, since that arithmetic lives on the denoising side of the cut."""from diffusers.modular_pipelines.minimax_h3.before_encoder import MiniMaxH3Ref2VASetupStep16 unmodified linesdef _wire_outputs(num_frames: bool = True) -> list[OutputParam]:"""The wire format of the split. `num_frames` is declared by the `ref2va` half alone, whose setup resolves one."""return [OutputParam.template("prompt_embeds"),OutputParam("text_token_tags", description="The per-row modality tag of every row of `prompt_embeds`."),OutputParam("height", type_hint=int, description="Resolved height of the generated video in pixels."),OutputParam("width", type_hint=int, description="Resolved width of the generated video in pixels."),*([OutputParam("num_frames", type_hint=int, description="Resolved number of frames, of the form 17 * n + 5.")]if num_frameselse []),]class MiniMaxH3ConditionerBlocks(SequentialPipelineBlocks):"""The conditioner half of a split MiniMax-H3: the keyframes on the canvas plus the Qwen3-VL read at layer 50."""model_name = "minimax-h3"block_classes = [MiniMaxH3AutoResizeStep, MiniMaxH3TextEncoderStep]block_names = ["resize", "text_encoder"]@propertydef description(self):return ("The conditioner half of a split MiniMax-H3 deployment: puts the keyframes onto the target canvas and ""encodes MiniMax-H3's presentation of the request into the `prompt_embeds` / `text_token_tags` pair the ""denoising half consumes. The frame count is the caller's to align.")@propertydef outputs(self):return _wire_outputs(num_frames=False)class MiniMaxH3GeneratorBlocks(SequentialPipelineBlocks):"""The denoising half of a split MiniMax-H3: `MiniMaxH3Blocks` with its `text_encoder` step removed."""model_name = "minimax-h3"block_classes = [MiniMaxH3AutoResizeStep,7 unmodified lines@propertydef description(self):return ("The denoising half of a split MiniMax-H3 deployment: the `t2va` / `fl2va` branch of `MiniMaxH3Blocks` ""without its text-encoder step, so `prompt_embeds` and `text_token_tags` come in as inputs and the ""62.14 GiB Qwen3-VL conditioner is never loaded here.")@property2 unmodified linesclass MiniMaxH3Ref2VAConditionerBlocks(SequentialPipelineBlocks):"""The conditioner half of a split `ref2va`: the resolved plan plus the Qwen3-VL read at its 50th layer.Component for component this is `MiniMaxH3ConditionerBlocks`, so one conditioner Space serves both partitions.What differs is the presentation: `ref2va` prepends a label per reference and a vision block per image and permerged video frame pair, so the references themselves have to reach this half."""model_name = "minimax-h3"block_classes = [MiniMaxH3Ref2VASetupStep, MiniMaxH3Ref2VATextEncoderStep]block_names = ["setup", "text_encoder"]@propertydef description(self):return ("The conditioner half of a split MiniMax-H3 `ref2va` deployment: resolves the request plan (canvas, frame ""count, references normalized onto MiniMax-H3's own rates and resolutions) and encodes MiniMax-H3's ""presentation of it into the `prompt_embeds` / `text_token_tags` pair the denoising half consumes.")@propertydef outputs(self):return _wire_outputs()class MiniMaxH3Ref2VAGeneratorBlocks(SequentialPipelineBlocks):"""The denoising half of a split `ref2va`: the `ref2va` branch with its `text_encoder` step removed.`reference_encoder` stays here, next to the two autoencoders it runs: its output shapes are where every referenceblock's geometry in the packed layout comes from."""model_name = "minimax-h3"block_classes = [MiniMaxH3Ref2VASetupStep,4 unmodified lines]block_names = ["setup", "reference_encoder", "denoise", "after_denoise", "decode"]@propertydef description(self):return ("The denoising half of a split MiniMax-H3 `ref2va` deployment: the `ref2va` branch of `MiniMaxH3Blocks` ""without its text-encoder step, so `prompt_embeds` and `text_token_tags` come in as inputs and the ""62.14 GiB Qwen3-VL conditioner is never loaded here. The transformer is the `transformer_ref` partition.")@propertydef outputs(self):return _generation_outputs()123456716 unmodified lines24252627282930313233343536373839404142434445464748497 unmodified lines57585960616263642 unmodified lines676869707172737475767778798081824 unmodified lines878889909192"""The denoising half of MiniMax-H3 used by this Space.The Qwen3-VL conditioner is served by the publicmultimodalart/qwen3vl-conditioner Space so the generator can fit on ZeroGPU."""from diffusers.modular_pipelines.minimax_h3.before_encoder import MiniMaxH3Ref2VASetupStep16 unmodified linesdef _wire_outputs(num_frames: bool = True) -> list[OutputParam]:return [OutputParam.template("prompt_embeds"),OutputParam("text_token_tags", description="The per-row modality tag of every row of prompt_embeds."),OutputParam("height", type_hint=int),OutputParam("width", type_hint=int),*([OutputParam("num_frames", type_hint=int)] if num_frames else []),]class MiniMaxH3ConditionerBlocks(SequentialPipelineBlocks):model_name = "minimax-h3"block_classes = [MiniMaxH3AutoResizeStep, MiniMaxH3TextEncoderStep]block_names = ["resize", "text_encoder"]@propertydef outputs(self):return _wire_outputs(num_frames=False)class MiniMaxH3GeneratorBlocks(SequentialPipelineBlocks):model_name = "minimax-h3"block_classes = [MiniMaxH3AutoResizeStep,7 unmodified lines@propertydef description(self):return ("The denoising half of MiniMax-H3 with the text encoder removed. ""Prompt embeddings and token tags arrive from the external conditioner Space.")@property2 unmodified linesclass MiniMaxH3Ref2VAConditionerBlocks(SequentialPipelineBlocks):model_name = "minimax-h3"block_classes = [MiniMaxH3Ref2VASetupStep, MiniMaxH3Ref2VATextEncoderStep]block_names = ["setup", "text_encoder"]@propertydef outputs(self):return _wire_outputs()class MiniMaxH3Ref2VAGeneratorBlocks(SequentialPipelineBlocks):model_name = "minimax-h3"block_classes = [MiniMaxH3Ref2VASetupStep,4 unmodified lines]block_names = ["setup", "reference_encoder", "denoise", "after_denoise", "decode"]@propertydef outputs(self):return _generation_outputs()
1234561 unmodified line891011121314151617# diffusers from the MiniMax-H3 PR (https://github.com/huggingface/diffusers/pull/14371), pinned to a commit# on its minimax-h3-refactor branch. This Space subclasses its block classes in h3_split_blocks.py.# 665f578278365ea4a3318cb8c9b66ce6c01204b9 = refs/pull/14371/head at the time of this deploy--extra-index-url https://download.pytorch.org/whl/cu130diffusers @ git+https://github.com/huggingface/diffusers.git@665f578278365ea4a3318cb8c9b66ce6c01204b9torch==2.11.01 unmodified linetransformers==5.8.0accelerate==1.14.0huggingface-hub==1.24.0gradio @ https://huggingface.co/buckets/gradio/pypi-previews/resolve/a9ce60ae03123ed6374b739d862e62dcae2f451e/gradio-6.25.0-py3-none-any.whlavpillownumpyrequestssafetensors>=0.8.0peft12341 unmodified line678910111213# MiniMax-H3 modular pipeline support is currently provided by this reviewed PR.--extra-index-url https://download.pytorch.org/whl/cu130diffusers @ git+https://github.com/huggingface/diffusers.git@665f578278365ea4a3318cb8c9b66ce6c01204b9torch==2.11.01 unmodified linetransformers==5.8.0accelerate==1.14.0huggingface-hub==1.24.0avpillownumpyrequestssafetensors>=0.8.0
README.md+14-67
app.py+170-869
h3_split_blocks.py+9-64
requirements.txt+1-5