Skip to content

Studio: keep MiniMax-H3 reference images at the size Studio fits them to - #17747

Merged
danielhanchen merged 2 commits into
mainfrom
studio-h3-ref-image-size
Nov 14, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-h3-ref-image-size

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

MiniMax-H3 reference-to-video (ref2va) sizes each reference image in fit_h3_reference_image:

  • match (default): scale the image down, never up, to the generation's pixel area.
  • max: scale it down, never up, to a 2048 px short edge.

In both cases the aspect ratio is kept, each side snaps to 32 px and the resize is LANCZOS.

Diffusers' MiniMaxH3Ref2VASetupStep then rescaled every image reference to its reference_image_short_edge config (2048), upscaling included, and Studio never overrode that. So:

  • the default match ran at the full 2048 token cost, with a reference blurred by the shrink and the upscale;
  • max upscaled any image smaller than 2048 px.

The step is identical in diffusers 0.41.0, 0.42.1 and 0.43.0.

Changes

  • keep_h3_reference_image_sizes(pipe) (video_minimax_h3.py) switches the pipeline's Ref2VA setup step to a subclass that skips that rescale for the PIL images the request passed. The VAE encode and the vision tower now both receive the image Studio sized, pixel for pixel.
    • A single config value cannot do this, because several references in one request can have different short edges.
    • The subclass is called once per render with references, is idempotent, and leaves array or tensor references to diffusers' own conversion.
  • stable-diffusion.cpp gets ref_image_size=max (--ref-image-args on the CLI, ref_image_args in the server request) whenever reference images are passed. sd.cpp re-applies its default match rule to the already sized image, and because of the 32 px snap that rule is not idempotent: about 8% of source sizes were resized a second time. For an image whose short edge is at most 2048, max is an exact no-op.
  • The default stays match, and max stays a 2048 down-only limit.

Tests

studio/backend/tests/test_h3_reference_image_size.py (CPU, no weights, runs the real diffusers blocks):

  • Sizing: the policy result for 10 source sizes x 4 generation sizes x both policies, never upscaled, LANCZOS.
  • Live pipeline: for both policies, with four references of different sizes in one request:
    • the images leaving the setup step are the very objects Studio sized;
    • the pixels handed to the VAE encode match those sizes;
    • the vision grids and token counts are what that size implies.
  • Control: without the switch, stock diffusers returns every image at a 2048 short edge.
  • max parity: for sources with a short edge of at least 2048, max is byte-identical to diffusers' own 2048 resize.
  • Mechanics: the switch is idempotent and scoped to its own pipeline, and array references keep diffusers' sizing.
  • sd.cpp: the CLI argv and the server request carry ref_image_size=max only when reference images are present.

Results:

run result
diffusers 0.41.0 / 0.42.1 / 0.43.0, this branch 93 passed each
main, file as written import error
main, with a no-op stub of the new function VAE/vision and sd.cpp assertions fail

test_sd_cpp_args.py only gains the new flag in its reading-order list.

GPU results

Setup: Colab G4 (RTX PRO 6000 Blackwell), Studio defaults (hosted INT8 ref2va transformer, 960x544, 124 frames, 20 steps, CFG 1), diffusers 0.42.1.

  • 10 pairs: 8 single references (3:2, 4:5, 1:1, 16:9, 9:16 at 1461 px, 5:4, 2:1, and a 580x800 image) plus 2 two-reference prompts. All are NASA public-domain photos.
  • Same seed in every arm. The trained reference is diffusers alone, fed the source and resizing it to 2048, upscale included.
  • Every render checked the sizes that actually reached the VAE and the vision tower: 60 of 60 as expected.

Means over the 10 pairs:

arm wall s denoise s sequence peak alloc GiB peak nvidia-smi GiB DINO to ref CLIP to ref
main (match, rescaled to 2048) 136.8 129.9 33,592 53.31 59.23 0.793 0.871
this PR, match 62.3 58.0 20,547 52.02 57.44 0.818 0.878
this PR, max 119.6 113.2 30,767 53.03 58.35 0.786 0.863
diffusers alone at 2048 (3 seeds) 136.1 129.7 33,554 53.30 59.25 0.791 0.858
  • match: 2.1x faster per clip (per-pair wall ratio 0.475 [0.421, 0.531], 95% CI), with 1.3 GiB less allocated.
  • Identity holds: match's paired difference from the 3-seed trained mean is DINO +0.027 [0.003, 0.050] and CLIP +0.021 [0.004, 0.037].
  • Distance from the trained render: match's mean LPIPS is 0.58, while a different seed of the trained render sits at 0.61.
  • max on sources with a short edge of at least 2048: the VAE input and the vision pixel_values are byte-identical to diffusers alone (md5). Two separate runs of diffusers alone differ by LPIPS 0.175 on the same input, and max sits at that level (0.23).
  • max on smaller sources: they are no longer upscaled (9:16 at 1461 px: 94 s instead of 136 s).
  • L4: match loads and runs (two references, 471 s, 20.5 GiB peak in nvidia-smi).

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T10:47:49.194323Z efabfec Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: efabfece73

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@danielhanchen
danielhanchen merged commit ed9b327 into main Nov 14, 2026
@danielhanchen
danielhanchen deleted the studio-h3-ref-image-size branch November 14, 2026 11:44
danielhanchen added a commit that referenced this pull request Nov 14, 2026
…ng and seeds (#17764)

## 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):
- **Rotation:** a video's display rotation is applied in quarter turns,
so phone footage is no longer conditioned sideways with the wrong
canvas.
- **Decode:** YUV video is converted through float RGB (`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.
- **Canvas:** each axis of the reference-video canvas rounds to its
nearest 32 px on its own (Python `round`). A 1.9:1 source now gets
1408x736, where it used to get 1376x736.
- **Audio:**
- resampled to 32 kHz with torchaudio's default bandlimited sinc kernel,
reimplemented in torch, so torchaudio is no longer needed;
- the first two channels kept, with mono copied to both, so 5.1 and 7.1
tracks are accepted instead of refused;
  - centre-cropped to whole 800-sample latent frames.
  stable-diffusion.cpp receives the same samples.
- **Last keyframe:** the centre crop uses the reference's whole-pixel
margin and crops before the LANCZOS resize.

Diffusers blocks (class swaps on the pipeline's own blocks, the same
mechanism #17747 uses):
- **Small videos:** frames Studio already fitted are no longer rescaled
to the full canvas. A 640x360 reference stays 640x352 instead of
becoming 1344x768.
- **Soundtracks:** encoded whole, not cut to the generated length.
- **Vision input:**
  - the 2 fps frames are picked after the `17n+5` snap;
- each two-frame block is sized on its own (3136 to 12,845,056 pixels,
factor 32, bilinear) instead of against a whole-clip budget;
  - image references and keyframes use the same limits and arithmetic.
- **Noise:**
- video noise, then audio noise drawn as `[1, 32, 2, T]`, both from one
CPU generator seeded with the request seed;
- condition-augmentation noise from its own generator, re-seeded with
the seed for every condition, in packed-row shape.
  The same seed now gives the same noise as the reference.
- **Schedule:** the `simple` grid 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.
- **Determinism:** the keyframe and reference VAE encode runs with
`cudnn.benchmark` held 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.
- **Sampler:** `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_a` on the video sigmas, which is what makes it equal the
reference. PDD (turbo) banks keep Euler.

Output:
- **Soundtrack:** divided by `max(1, 5 * std)` and trimmed to `ceil(rate
/ fps * frames)` samples.

Kill switches:
- `UNSLOTH_H3_SAMPLER=euler` brings back Euler for every checkpoint.
- `UNSLOTH_H3_VISION_BUDGET=clip` brings back the whole-clip vision
budget for long references.

## Kept different on purpose
- **8-bit rounding:** decoded float frames are rounded to 8 bit; the
reference truncates, which darkens by half a step on average.
- **Posterior:** reference latents keep the sampled posterior (seed 42,
float16) rather than the posterior mean. MiniMax's own VAE code
(`klvae.py`, `encode_base`) always samples, and the Diffusers port
documents seed 42 plus float16 as the released recipe.
- Unchanged from before:
  - the dense AdaLN keeps its float32 timestep embedding;
  - keyframes keep the aspect-matched canvas when no size is given;
  - the int8 VAE decoder stays the default;
  - the AdaLN curve keeps its exact interpolation.

## 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:
- **Media:** rotation, the float decode, the canvas rule, audio
conforming and the resampler kernel.
- **Setup step:** small videos stay small and soundtracks stay whole,
with a stock control.
- **Vision:** snapped frame picks, per-block sizing and image limits.
- **Noise:** video/audio order and layout, and per-condition restarts.
- **Schedule and sampler:** the sigma grid and timesteps for 7, 8, 20,
30 and 33 steps, and a 20-step `res_multistep` trajectory for video and
carried audio, bit for bit. Euler is unchanged for PDD.
- **Output:** the audio limiter and trim, and the keyframe crop.

`test_h3_reference_image_size.py` gains a fitted-video case.

| run | result |
|---|---|
| this branch, new file + #17747's file | 146 passed, 1 skipped
(torchaudio absent) |
| #17747 head, new file | import error (new code absent) |
| `test_video_backend.py` + `test_video_i2v.py`, both trees | same
failing IDs on both (missing optional deps in the CPU venv) |

## GPU results

Setup:
- Colab G4 (RTX PRO 6000 Blackwell), Studio defaults (hosted INT8
denoiser and text encoder), 1344x768, 124 frames, 20 steps, seed 4242.
- Base is #17747's head; head is this branch. Every arm is a fresh
process, run in the order base, head, head, base.
- Media are NASA public-domain clips:
- a 15 s portrait video stored sideways with rotation metadata, plus its
own soundtrack;
  - a 640x360 video with a 15 s replacement soundtrack;
  - a 5.1 audio reference;
  - two photos for first and last frame.

Wall time per clip in seconds (two processes each):

| job | base | head |
|---|---|---|
| t2va | 160.2, 160.6 | 160.6, 160.7 |
| fl2va | 195.8, 191.0 | 193.8, 191.1 |
| ref2va, rotated portrait + soundtrack + image | 629.5, 629.6 | 308.1,
308.2 |
| ref2va, 640x360 + replacement soundtrack + 5.1 audio | refused (5.1) |
240.1, 240.0 |

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:
- Conditioning token counts now equal the reference implementation's on
every job: 59, 2085, 2968 and 1208.
- Peak nvidia-smi memory: 60.1 GiB (t2va and fl2va), 61.8 GiB (ref2va
head), 66.0 GiB (ref2va base).
- Host RSS is at most 6.5 GiB.

LPIPS to a reference-implementation render of the same job, with the
same seed on the same GPU type:

| job | base | head |
|---|---|---|
| t2va | 0.239 | 0.121 |
| fl2va | 0.344, 0.348 | 0.064 |
| ref2va, rotated portrait | 0.755, 0.756 | 0.333 |
| ref2va, 640x360 + 5.1 | refused | 0.359 |

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:

| | DINOv2 | CLIP |
|---|---|---|
| base | 0.57-0.58 | |
| head | 0.63-0.65 | 0.72-0.75 |
| reference | 0.65 | 0.74 |

Determinism (same seed, fresh processes):
- Before this change, t2va was already bit-identical, but every
conditioned job differed (LPIPS 0.02-0.24). The stage digests put the
whole difference in the condition VAE encode.
- With the encode under a fixed algorithm choice, all three conditioned
jobs are bit-identical across processes.
- The condition encode costs 0.1 s more on ref2va and 1.6 s less on
fl2va, where the timed search itself was overhead.

Speed trade to decide on:
- Per-block vision sizing keeps long full-size reference videos at full
resolution for the conditioner.
- A 14.4 s 1344x768 reference becomes 15,120 vision tokens instead of
12,540 (+20%); references of 10 s or less, or smaller than the canvas,
are unchanged.
- `UNSLOTH_H3_VISION_BUDGET=clip` restores 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.
danielhanchen added a commit that referenced this pull request Nov 14, 2026
…quality through the MP4 export (#17770)

## Summary

Makes Studio's MiniMax-H3 GGUF (stable-diffusion.cpp) video engine
follow the reference workflow's sampling recipe and stop losing quality
between sd.cpp and the exported MP4. Builds on #17747 (merged).

**Needs a new sd.cpp prebuilt.** Every new behaviour is gated on what
the installed build offers, so this PR is safe on the current pin
(`master-982-0518b34-u67cba2c`), but the lossless handoff and explicit
soundtrack pairing only switch on once `DEFAULT_TAG` in
`studio/install_sd_cpp_prebuilt.py` points at a prebuilt that contains
unslothai/stable-diffusion.cpp#88. Bump the tag in a follow-up after
that fork PR merges and its prebuilt is published.

## Changes

1. **Sampler and schedule.** Regular H3 checkpoints now run
`res_multistep` on the `simple` schedule, on both the sd-cli argv
(`--sampling-method`, `--scheduler`) and the sd-server `sample_params`.
Distilled and PDD files keep Euler, on the same `simple` schedule.
Before this, Studio sent no sampler, so sd.cpp ran Euler on its discrete
grid (base `linspace(1, 0.001, N)`), which spends about one evaluation
near sigma 0. `UNSLOTH_H3_SD_CPP_SAMPLER=legacy` restores Euler on the
discrete grid.
2. **One lossy encode.** When the build lists it, Studio asks sd.cpp for
an uncompressed AVI (BGR24 frames and float PCM): `--lossless-video`
with a `.avi` output on sd-cli, or `output_format: "avi_raw"` on
sd-server. The server result is downloaded as raw bytes from the job's
`media_url` instead of base64 JSON. Studio's x264 / AAC export is then
the only lossy step. `UNSLOTH_H3_SD_CPP_LOSSLESS=0` keeps MJPG.
3. **Export fixes** in `transcode_video_to_mp4`. These help every build,
including the current pin:
- sd.cpp's MJPG frames decode as full-range `yuvj420p`. The `yuv420p`
encoder treated them as limited range and stretched them (gain 1.14,
offset -16), so they now go through RGB first.
- Decoded frames are tagged as I frames, and libx264 obeyed that, so
every export was all-intra. The tag is now cleared.
- The export now uses the shared x264 stream: frame threads, and libx264
capped at AVX2 for reproducible output.
- Float audio is limited to [-1, 1] and NaN is set to 0 before AAC,
because the AAC encoder rejects NaN.
4. **Soundtrack pairing.** A silent reference video can now come before
one with a soundtrack when the build accepts `--ref-video-audio-index`
(on sd-server, the `ref_video_audio_indices` feature). Older builds keep
the refusal. If the soundtracks already pair by position, the argv is
unchanged.
5. The NaN-render probe now also catches float PCM that is all NaN.
6. **Audio shift.** A non-default `audio_flow_shift` is no longer
refused on builds that accept `--audio-flow-shift`. It is sent on the
argv and in `sample_params`, and the saved recipe records the shift that
ran. Older builds keep the refusal.

## Evidence

- Unit tests: `studio/backend/tests/test_h3_sd_cpp_parity.py` (24
tests). Each export test fails on the base branch: MJPG gain 1.099, 0
inter frames, and AAC raises on NaN audio.
- Related suites pass: `test_h3_native_server.py`,
`test_h3_native_nonfinite.py`, `test_sd_cpp_args.py`,
`test_video_backend.py` and `test_media_auto_switch.py` (875 tests). Two
failures exist on the base branch as well:
`test_h3_reference_image_size.py::test_vae_and_vision_tower_see_the_fitted_images[max]`
and
`test_sd_cpp_moss_image.py::test_diffusers_takes_a_moss_safetensors_single_file`.
- Export quality, measured on a real 1344x768, 124-frame H3 clip. All
three arms use the same frames written by the fork's own AVI writer, and
PSNR is taken of the final MP4 against those frames:

| arm | sd.cpp container | export | final MP4 | PSNR mean / min |
|---|---|---|---|---|
| base (current Studio) | MJPG q90, 22.0 MB | 1.8 s | 7.9 MB | 27.98 /
27.56 dB |
| this PR, old build (MJPG) | MJPG q90, 22.0 MB | 2.0 s | 2.9 MB | 37.55
/ 37.12 dB |
| this PR, new build (raw) | raw AVI, 385 MB | 1.6 s | 2.9 MB | 37.73 /
37.24 dB |

Writing the raw container takes 0.7 s, against 2.4 s for MJPG. The cost
is temporary disk (about 385 MB per 5 s clip) and a 385 MB loopback
download from sd-server. GPU end to end: Colab RTX PRO 6000 Blackwell,
Studio defaults (1344x768, 124 frames, 20 steps), runs ordered base,
head, head, base. Both runs of each arm were pixel-identical. Base is
the current prebuilt plus the base branch; head is the new fork build
plus this branch.

| task | arm | s/clip | export | final MP4 | final MP4 vs true frames
(Y) | identity cos (ref2va) |
|---|---|---|---|---|---|---|
| t2va | base | 239.3 | 0.84 s | 5.93 MB | 28.25 dB | |
| t2va | head | 236.9 | 0.54 s | 1.78 MB | 39.11 dB | |
| fl2va | base | 278.0 | 0.97 s | 6.83 MB | 28.12 dB | |
| fl2va | head | 276.4 | 0.75 s | 4.47 MB | 38.11 dB | |
| ref2va | base | 447.9 | 0.87 s | 6.05 MB | 28.14 dB | 0.649 |
| ref2va | head | 446.5 | 0.54 s | 1.57 MB | 38.66 dB | 0.657 |

On head, the true frames are the raw AVI, which matches PNG frames
written by sd-cli exactly. On base, they are the PNG frames that the
base prebuilt's sd-cli writes at the same seed.

Denoise and VAE decode times are unchanged. The server handoff drops
from 2.0 s to 0.8 s, of which the raw media download is 0.21 s. Python
peak RSS rises by 0.55 GB because Studio holds the 385 MB AVI. LPIPS
against the Diffusers engine was not measured.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant