Repository navigation
Studio: follow the MiniMax-H3 reference recipe for references, sampling and seeds - #17764
Merged
Merged
Conversation
fit_h3_reference_image scales each ref2va reference image down (never up) to the "match" or "max" limit, but Diffusers' Ref2VA setup step then rescaled every image reference to its 2048 px short edge, upscaling included. The default "match" therefore ran at the full 2048 token cost with a blurred reference, and "max" upscaled images under 2048 px. Switch the pipeline's Ref2VA setup step to a subclass that skips that rescale for the images the request passed, so the VAE encode and the vision tower both receive the fitted LANCZOS image. One config value cannot express this because references in one request can differ in size. The step is identical in diffusers 0.41.0, 0.42.1 and 0.43.0. Pass ref_image_size=max to stable-diffusion.cpp with reference images: its default "match" rule is not idempotent after the 32 px snap and resized about 8% of fitted images a second time, while "max" leaves an image with a short edge of at most 2048 untouched.
[skip ci]
Reference media: video rotation applied, YUV decoded through float RGB, small videos no longer upscaled, soundtracks encoded whole, audio resampled to 32 kHz with the bandlimited sinc kernel, the first two channels kept (mono copied), centre-cropped to whole 800-sample frames. The reference-video canvas rounds each axis on its own. Conditioner input: 2 fps vision frames picked after the 17n+5 snap and each two-frame block sized on its own (3136 to 12,845,056 pixels); image references and keyframes get the same limits. Sampling: res_multistep by default (Euler stays for PDD), with audio stepped in the carried variable on the video sigmas; the simple sigma grid read off the 1000-entry table; video then audio noise from one seeded CPU generator, condition noise restarted per condition. Output: the soundtrack is limited to 1/(5 std) when loud and trimmed to end with the last frame. UNSLOTH_H3_SAMPLER=euler and UNSLOTH_H3_VISION_BUDGET=clip bring back the old sampler and the whole-clip vision budget.
The keyframe and reference VAE encode ran fp16 convolutions under a timed cuDNN search, which picks an algorithm per process: the same seed gave different condition latents, and so different clips, in every fresh process. The encode steps now run with the search held off; the denoise and decode are unchanged and t2va was already identical.
…3-comfy-parity-video
Member
Author
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
danielhanchen
added a commit
that referenced
this pull request
Nov 15, 2026
…#17802) ## Summary MiniMax-H3 video on the Diffusers engine now ships the reference implementation's defaults. #17764 matched the recipe (sampler, sigma grid, noise, media handling); this PR flips the divergences it kept on purpose, plus the ones found while checking the reference's pinned workflow templates and the kernels it runs on GPU. | default | before | after | switch to the old behaviour | |---|---|---|---| | q/k RMSNorm + RoPE rotation | diffusers chain: each product and the sum rounded to bf16 | the reference kernel's float32 fma, rounded once | `UNSLOTH_H3_QK_ROPE_ROUNDING=eager` | | 8-bit quantisation of decoded reference frames | rounded | truncated, as the reference LANCZOS helper (`astype(uint8)`) | none | | output frames | `round(x * 255)` | `(x * 255).clamp(0, 255).byte()` truncation, as the reference save | none | | dense time embedding | float32 up to the AdaLN SiLU | rounded to the compute dtype before the SiLU, as the reference | none | | condition latents (keyframes, reference images and videos) | posterior sampled under seed 42, rounded to float16 | posterior mean in float32, as the reference encode | `UNSLOTH_H3_REFERENCE_LATENT=sample` | | keyframe canvas without a size | matched to the keyframe's aspect | the reference node's 1344x768 (first frame stretched, last centre-cropped) | send `width` / `height`, or pick "Match source" | | page: keyframe upload | switched the size to "Match source" | keeps the chosen size; "Match source" is explicit and sends the matched size | pick "Match source" | | page size | 1344x768 preset; a fresh page rendered 800x544 | 864x480 (the t2v and r2v templates' 0.4 MP 16:9) from the first render | pick a preset | | MP4 export | libx264 CRF 23, BT.601 matrix, untagged, int16 AAC | CRF 18, BT.709 matrix, tagged BT.709 / sRGB / limited, float AAC | none | Unchanged because they already equal the reference: 20 steps, CFG 1, 124 frames, 24 fps, shifts 12 / 3, `res_multistep` + `simple`, the AdaLN curve, and the int8 ConvRot video decoder (the templates load an int8_convrot VAE; Studio's int8 and float16 decoders are equally close to it, 0.00087 vs 0.00086 LPIPS on the reference's own latent, so int8 stays and `UNSLOTH_H3_VAE_INT8=0` gives float16). The denoiser file stays Studio's hosted INT8 ConvRot build: the templates' pruned int8_convrot file is no faster, needs 0.74 GiB more VRAM and 16.6 GiB more host RAM at load, and is not consistently closer to the reference render (closer on one t2va case, further on fl2va and on t2va with the reference's conditioning). Speed levers that do not change what the reference computes stay on: compile, INT8 attention routing, the fused VAE kernels, the int8 decoder, tile batching, frame-threaded x264. The request API keeps 1344x768 for a request without a size (the reference node's default). The page takes the templates' 864x480 for its first render; a size the user picked, or a stored recipe, is kept. The text encoder default does not change: a request without `text_encoder_quant` still loads the hosted int8 ConvRot conditioner, exactly as on `main`. The reference templates' nvfp4_awq conditioner is not adopted: against the bf16 conditioner it is less accurate than the int8 one (per-token cosine 0.99744 vs 0.99990; video LPIPS vs a bf16-conditioner render 0.0876 vs 0.0325). ## q/k-norm + RoPE The reference CUDA kernel normalises, rounds the normed value to bf16, then rotates with `fma(x1, f01, x0 * f00)` in float32 and rounds once. Diffusers rounds each product and the sum. The video denoiser now uses the reference's rotation in the same Triton kernel (the device check compares it bit for bit against an exact emulation before engaging). On H3's shape (41,811 tokens x 24 heads x 128, rotary 96) against the reference kernel on a G4: | | elements that differ | max abs | kernel | |---|---|---|---| | before | 23.0% | 0.0625 | 0.390 ms | | after | 0.0013% | 0.0156 | 0.388 ms | The rest comes from the RMS sum order. The image pipeline keeps the eager rounding. ## Measurements Colab G4 (RTX PRO 6000 Blackwell) unless noted, Studio defaults otherwise (hosted INT8 denoiser, compiled), 1344x768x124, 20 steps. Every arm ran in a fresh process. The reference renders come from the reference implementation at `eee5918` with exactly the files its templates load; they are bit-identical across two VMs, as are Studio's. LPIPS is AlexNet on every 4th frame. LPIPS to the reference render of the same seed, `main` against this PR (the int8 conditioner on both sides). Two G4 VMs ran both sides in fresh processes, and every main/main and PR/PR pair across them is bit-identical, so the differences below are the change, not noise. | job | seed 4242 | seed 11 | seed 777 | mean | |---|---|---|---|---| | t2va | 0.119 -> 0.214 | 0.207 -> 0.229 | 0.253 -> **0.224** | 0.193 -> 0.222 | | fl2va | 0.054 -> **0.028** | 0.086 -> 0.144 | 0.120 -> **0.115** | 0.087 -> 0.095 | | ref2va_long | 0.361 -> **0.323** | 0.347 -> **0.299** | 0.483 -> **0.431** | 0.397 -> **0.351** | ref2va_long, the job the condition-latent change targets, is closer on all 3 seeds, which is why the posterior mean stays. t2va has no condition latents: only the RoPE rounding and the output truncation touch it, and its trajectories are chaotic, so a kernel-level change that brings the RoPE within 0.0013% of the reference still moves a single render as much as any perturbation. Speed and memory against `main`, same VM, fresh processes (VM a / VM b): | job | wall s, main | wall s, this PR | peak GPU memory GiB, main / this PR | |---|---|---|---| | t2va 4242 / 11 / 777 | 161.73, 161.80, 161.73 / 160.88, 161.24, 161.18 | 161.54, 161.96, 161.88 / 161.32, 161.37, 161.29 | 60.06 / 60.06 | | fl2va 4242 / 11 / 777 | 194.63, 191.03, 191.03 / 194.87, 190.38, 190.42 | 195.69, 191.14, 191.13 / 194.08, 190.53, 190.52 | 60.06, 58.64 / same | | ref2va_long 4242 / 11 / 777 | 309.41, 309.51, 309.48 / 308.20, 308.79, 308.36 | 309.63, 309.69, 309.73 / 308.61, 308.93, 308.74 | 62.83 / 62.84 | The flips add +0.1 to +0.4 s per clip (at most 0.1%, on the edge of the 0.4 s same-arm spread on one VM; fl2va 4242 is the first fl2va of each VM, cold cuDNN autotune) and leave peak VRAM and the decode peaks unchanged. Costs beyond noise: - **CRF 18 export:** +0.21 s per 124-frame clip (0.89 -> 1.10 s, CPU), and the file is twice the size. The reference's quality setting. - **Non-16:9 keyframe without a size:** renders the full 1344x768 canvas, as the reference node does. - **RoPE where the Triton kernel does not run** (ROCm, CPU, MPS): the single-rounding fallback is 13% slower than the eager chain for that op on CPU. ## Evidence - **CPU bit-parity against the reference's own code** (`scripts/h3_parity/ref_parity.py`, default mode): 97/97 after (the original 59/59), 72/97 before. The 38 new checks cover the dense time embedding, the AdaLN curve, the condition posterior, output quantisation, the keyframe canvas, the template defaults and the MP4 export against the reference's own save (pictures 29.4 -> 51.8 dB PSNR, soundtrack bit-identical). - **GPU probes:** the RoPE table above; the exported MP4 carries tags (1, 13, 1, 1) on the GPU renders. - **Unit tests:** new `tests/test_h3_reference_defaults.py`, new cases in `test_h3_ref_encode.py`, `test_video_encode.py`, `test_h3_qk_rope_exact.py` and `test_video_minimax_h3_attn.py` (CUDA cases ran on G4 and A100). Tests that pinned the old behaviour were updated: - `test_h3_reference_recipe.py`: the 8-bit conversion expects truncation (`[0, 1, 254]`, was `[0, 2, 255]`). - `test_h3_ref_encode.py`: the chunked-vs-stock tests run the explicit `sample` switch, because they compare against Diffusers' sampled encode. - `test_video_backend.py`: a portrait last frame without a size renders 1344x768. - `test_video_stream_encode.py`: the H3 stream is compared with the reference-profile export (CRF 18). - `test_h3_qk_rope_exact.py`: monkeypatched helpers take the new rounding argument. - Frontend `video-start-frame-upload.test.ts`: the 1:4 to 4:1 warning shows only where a keyframe would pick the canvas. - **Neighbouring suites** (every `test_video_*`, `test_h3_*` and `test_openai_videos*` file, CPU): the head failures are a subset of base's and all pre-existing in the CPU venv (the chunked-encode contiguity assertion on torch 2.14 and three ffmpeg-missing cases). Head merged with current `main`: 4864 passed, 7 failed; base: 4769 passed, 8 failed (its extra one is a timing flake that passes alone). Frontend: the touched `node --test` files pass, `tsc` and the Vite build pass. ## Not covered - **Vision tower precision:** the reference runs the Qwen3-VL vision tower in float32 (bf16 weights cast up per op). Moving Studio's whole tower to float32 brought fl2va from 0.029 to 0.017 LPIPS and ref2va_long from 0.351 to 0.295 (seed 4242), but cost 1.2 to 1.7 GiB of peak VRAM and also widened the language model on vision prompts, so it is not in this PR. A vision-only per-op cast is the follow-up. - **sd.cpp engine:** unchanged, except that it shares the keyframe resolver, so a keyframe without a size renders 1344x768 there too. - **Not proven:** - the RMS sum order of the reference RoPE kernel (the remaining 0.0013%); - fl2va seed 11 was not bisected to a single change; - G4 and A100 only (no L4); the page change has helper and source tests, tsc, a build, and the browser screenshots below. ## Screenshots MiniMax-H3 on the Video page, using the status a loaded MiniMax-H3 pipeline reports (no weights are loaded for the screenshot). A fresh render now opens at 864 x 480, the reference workflow's default (800 x 544 before):  Uploading a start frame no longer switches the size to Match source; the chosen 864 x 480 is kept: 
danielhanchen
added a commit
that referenced
this pull request
Nov 20, 2026
…coprime with 32 kHz (#18569) #17764 added `resample_h3_audio`, which converts MiniMax-H3 reference audio to 32 kHz before either engine (Diffusers or sd.cpp) sees it. It builds the sinc filter as one dense table of shape `[new, 1, 2 * width + orig]`, where `orig` and `new` are the two rates divided by their gcd. For common rates the table is tiny (44.1 kHz is `[320, 1, 459]`), but a rate that shares almost no factor with 32 kHz makes it enormous regardless of clip length. A valid WAV at 44,099 Hz gives `[32000, 1, 44117]`, 5.3 GiB per float32 intermediate, and the filter construction holds several of them at once. Resampling 1,024 samples (23 ms) of such a clip peaked at 22.2 GiB of host RAM and took 8.6 s on CPU. The rate comes straight from the uploaded container (`stream.codec_context.sample_rate`), so any user upload can hit it. ## Change When the dense table would exceed 4M elements (16 MiB in float32), `resample_h3_audio` now evaluates the same filter only on the `2 * width + 1` taps around each output sample, in chunks of 65,536 output samples. Every tap outside that window is clamped to the edge of the filter window, where the dense kernel is below 1e-20, so dropping them changes nothing beyond float rounding. The kernel values are computed with the same float32 expressions as the dense path. Memory now scales with the output length instead of the rate ratio. Rates whose table fits under the threshold (44.1, 48, 22.05, 11.025, 16, 8, 96, 192 kHz and every other common rate) still take the existing dense path, so their output is bit for bit unchanged and still equals torchaudio's default kernel. ## Tests - `test_resampler_memory_does_not_scale_with_the_rate_ratio` (44,099, 44,101, 8,001 and 32,001 Hz) runs the resampler on meta tensors and records the largest tensor any op produces, requiring it to stay under 64 MiB. It fails on main (largest intermediate 5.3 GiB at 44,099 Hz) and passes here. - `test_windowed_resampler_matches_the_dense_kernel` forces the windowed path on five rates and compares it with the reference dense implementation: within 1e-12 in float64 and within 1e-6 in float32. - Measured on CPU, 1,024 stereo samples at 44,099 Hz: peak RSS 22.2 GiB and 8.6 s on main, 0.01 GiB and 0.03 s here; a 15 s clip at 44,099 Hz takes 0.5 s and 0.03 GiB. Against a float64 oracle the float32 error is the same on both sides (1.42e-4 main, 1.42e-4 here, dominated by the float32 phase computation both share); main and this branch differ by at most 7.2e-7 on unit-variance input. 44.1 kHz and 22.05 kHz output is identical to main. - `tests/test_h3_reference_recipe.py` plus the H3 and video test files that import `video_minimax_h3`: same failing test IDs on main and on this branch, no new failures. ## Not proven - No comparison against `torchaudio.functional.resample` at a coprime rate (torchaudio itself builds the same dense table, so it needs the same tens of GiB); the windowed path is checked against the dense formula instead. - No GPU render with a coprime-rate reference clip; the resampler runs on CPU before either engine starts.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
MiniMax-H3 on the Diffusers engine now follows the reference implementation's process end to end: how reference media is decoded and sized, what the conditioner reads, how noise is drawn, the sigma grid, the sampler and the saved soundtrack. On CPU, every tensor Studio builds was compared with the one the reference code builds from the same files and seed, and all 59 checks are bit-identical (see Tests). The only difference left on purpose is rounding instead of truncating when decoded frames become 8-bit.
Stacked on #17747 (reference image sizing).
Changes
Reference media (shared by both engines):
gbrpf32le) as the reference does. A frame whose width is off the 32 px grid is edge-padded for the conversion and cropped back. Full-range JPEG YUV and RGB sources still go straight to 8-bit.round). A 1.9:1 source now gets 1408x736, where it used to get 1376x736.stable-diffusion.cpp receives the same samples.
Diffusers blocks (class swaps on the pipeline's own blocks, the same mechanism #17747 uses):
17n+5snap;[1, 32, 2, T], both from one CPU generator seeded with the request seed;The same seed now gives the same noise as the reference.
simplegrid is read off the 1000-entry shifted table, so step counts that do not divide 1000 floor the way the reference does. The audio timesteps come from the video sigma.cudnn.benchmarkheld off. A timed search picked the conv algorithm per process, so the same seed gave different condition latents, and different clips, in every fresh process.res_multistep(second order, eta 0, one evaluation per step) is the default. Audio is stepped in the carried variable(sigma_v / sigma_a) * x_aon the video sigmas, which is what makes it equal the reference. PDD (turbo) banks keep Euler.Output:
max(1, 5 * std)and trimmed toceil(rate / fps * frames)samples.Kill switches:
UNSLOTH_H3_SAMPLER=eulerbrings back Euler for every checkpoint.UNSLOTH_H3_VISION_BUDGET=clipbrings back the whole-clip vision budget for long references.Kept different on purpose
klvae.py,encode_base) always samples, and the Diffusers port documents seed 42 plus float16 as the released recipe.Tests
studio/backend/tests/test_h3_reference_recipe.py(CPU, no weights, real Diffusers blocks). Each check compares Studio's output with a literal rewrite of the reference code:res_multisteptrajectory for video and carried audio, bit for bit. Euler is unchanged for PDD.test_h3_reference_image_size.pygains a fitted-video case.test_video_backend.py+test_video_i2v.py, both treesGPU results
Setup:
Wall time per clip in seconds (two processes each):
The rotated-portrait job is 2x faster because the reference is no longer turned sideways and upscaled. Its packed sequence drops from 82,220 rows to 55,142.
Token counts and memory:
LPIPS to a reference-implementation render of the same job, with the same seed on the same GPU type:
The t2va residual is the floor between the two stacks, which use different quantised weights and VAE decoder precision. It is not a recipe difference.
For the rotated-portrait job, identity to the references:
Determinism (same seed, fresh processes):
Speed trade to decide on:
UNSLOTH_H3_VISION_BUDGET=cliprestores the old budget.Not covered here: no GGUF (stable-diffusion.cpp) render. That engine now receives the upright, 32 kHz stereo, frame-aligned media, but no render was run with it.