Skip to content

Studio: MiniMax-H3 joint video and audio LoRA training - #8244

Merged
danielhanchen merged 122 commits into
mainfrom
h3-video-lora
Aug 10, 2026
Merged

danielhanchen merged 122 commits into
mainfrom
h3-video-lora

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Adds MiniMax-H3 as Studio's second trainable video family, and its first family trained from clips with sound.

This stacks on two open PRs

The branch is origin/ltx2-video-lora (#8196) with oobabooga:feat/minimax-h3-video (#7989) merged into it, because it needs both:

Diff against main therefore includes both. The new work is 6 files: diffusion_h3_clips.py, diffusion_h3_trainer.py, their tests, and the routing lines in diffusion_train_common.py.

The three blockers, resolved

The design note said H3 waits on the ModularPipeline, joint audio and the 63 GB encoder. Measured against the code:

ModularPipeline: not a blocker, and a better fit than the DiffusionPipeline path. The trainer never builds a pipeline for the denoising half at all. The two things it needs from the pipeline layer, MiniMaxH3PrepareLayoutStep.build_packed_sequence and MiniMaxH3SetTimestepsStep.build_row_timesteps, are @staticmethods and are called directly, so the row layout, the fp64 rotary grid and the modality tags cannot drift from the sampler's. The transformer loads standalone through MiniMaxH3Transformer3DModel.from_pretrained(subfolder="transformer"). The phased load is expressed as load_components(names=[...]), which is more precise than the DiT trainer's transformer = None trick: the denoiser is never even fetched during the conditioning phase.

Joint audio: the real blocker, and it changes the design rather than being worked around. H3 runs one block stack over one packed sequence holding text, audio and video rows under full self-attention. There is no cross-attention, no per-modality block weights, and no isolate_modalities flag. LTX-2 has all three, which is why #8196 could exclude audio_attn* from the targets and pass a placeholder audio stream. Here:

  • A LoRA on attn / ff is applied to the audio rows too. There is no target set that adapts video and not audio.
  • The audio rows are keys and values for every video row, so a placeholder audio stream perturbs the video prediction directly.

So "freeze the audio branch" is not available, and the only honest objective is the model's own: regress both velocities. That forces a real audiovisual dataset, which is why there is no still-image milestone here.

The two schedules are coupled the way the sampler couples them. Video is shifted by 12.0 and audio by 3.0, and at inference both are indexed by the same step, so (sigma_video, sigma_audio) walks one curve. Training draws one base u and pushes it through both shifts; drawing them independently would train pairs the sampler never visits.

The text encoder: 63 GiB, measured. text_encoder/ is 65,162,668 KiB = 62.1 GiB (66.7 GB decimal) across 14 shards, matching the 66.8 GB the family record already quotes for the conditioner. It is a preprocessing cost, not a training one: captions are encoded once and it is dropped before the VAEs encode and long before the denoiser loads. The fp8 pre-cast encoder path (te_prequant_repos) does not apply here, because the hosted H3 prequant repo carries the denoiser, not the conditioner.

What the packed sequence costs, and the clip length

The attention is quadratic in the whole sequence, and H3 generates at 5 s minimum. At the released 768 short edge a 5 s clip is ~38k rows. Training clips are one VAE chunk, 22 frames (17 * 1 + 5, 0.917 s), which is 7,178 rows at the same canvas.

That trade is deliberate and is the reverse of the obvious one. A style LoRA learns spatial statistics, so the canvas stays at the released 768 short edge and the temporal extent shortens; shrinking the canvas instead would put every spatial statistic off distribution. The temporal rotary grid of a 22-frame clip is a strict prefix of a generated clip's, so no row sits at a coordinate the model never visits.

Other things a modular, mixed-precision, packed-sequence family needed

nf4 needs a skip list, or the forward dies. The transformer aligns activations with x.to(self.<m>.weight.dtype) in five places. A bitsandbytes Params4bit reports uint8, so quantizing one of those casts the activation to Byte and the next norm raises "rms_norm" not implemented for 'Byte'. proj_in / audio_proj_in / proj_out / audio_proj_out / time_embedder are already excluded by the checkpoint's _keep_in_fp32_modules; context_embedder, adaln_proj and norm_out are not, so they are passed to llm_int8_skip_modules. That costs the nf4 saving on adaln_proj (36.6 GB resident rather than ~17 GB), still well under the 66.3 GB dense weight. torchao int8 is unaffected, since its tensor subclass reports the logical bfloat16.

Targets are a regex, not a list. MiniMaxH3TokenRefinerBlock carries attn and ff under the same leaf names as a transformer block, so PEFT's suffix rule for a list would adapt the text refiner as well. PEFT globs nothing: it either suffix-matches a list or re.fullmatches a string, so "transformer_blocks.*.attn.to_q" in a list matches nothing at all and the adapter trains zero parameters while every step still reports a loss. Both halves of that mistake are covered, and the trainer refuses an empty adapter.

Batch size is pinned to 1. The batch axis of an H3 forward is a pure replication axis: the layout, the rotary grid and the row timesteps describe one packed sequence every item shares, and two clips with different captions have different text lengths. Use gradient accumulation for the effective batch.

Velocity sign is reversed. H3 predicts a data-ward velocity (x0 = x_t + sigma * v), so the target is latents - noise, the negation of the DiT trainer's convention.

Why not a seventh _FamilySpec. The _FamilySpec seams are latent packing, the forward signature, embedding collation and the save entrypoint. H3's differences are none of those: they are the sigma table (two coupled schedules, and MiniMaxH3Scheduler is not a FlowMatchEulerDiscreteScheduler), the loss (two targets), and the noising. Those all live in the shared loop body, so a spec would have meant per-family branches inside the loop rather than inside the hooks. It is a sibling trainer instead, sharing diffusion_train_common wholesale, exactly as the SDXL trainer does. get_trainer routes it; TRAINABLE_VIDEO_FAMILIES still gates it.

Verification

Trained a style LoRA. 30 clips of 22 frames at 24 fps cut from Big Buck Bunny (CC-BY, Blender Foundation), each with its own soundtrack, one shared caption with a bbbstyle trigger. 1344x768, rank/alpha 32, lr 1e-4, 800 steps, nf4, batch 1, gradient checkpointing. 38 minutes on a B200, 2.86 s/step, sequence 7,144 rows.

Both halves of the objective improve, which is what says the audio branch is being trained rather than dragged:

first 10 logs last 10 logs
video loss 0.294 0.237
audio loss 0.361 0.266
total 0.656 0.503

Whole-run peak 77.8 GB, set by the conditioning phase (the 63 GiB encoder plus both fp32 VAEs), not by the loop. The loop itself measured 43.5 GB at rank 16 in a standalone probe.

Generated with and without it, same prompt and seed, in a stock diffusers ModularPipeline with no Studio code on the path, via transformer.load_lora_adapter(path, prefix="transformer"). 124 frames, 1344x768, 30 steps, 138 to 155 s each, peak 150 GB with component offload.

The difference is style. Without the adapter the triggered prompt renders a photographic bird on a mossy branch with shallow depth of field and cool daylight. At scale 1.0 it becomes a backlit, warm-key, high-contrast forest with saturated chunky moss and a rounded plush-looking bird, i.e. the source film's look, while staying prompt-faithful and temporally coherent. At 1.5 the effect saturates: the palette deepens further and the subject starts to lose definition, which is ordinary LoRA scale behaviour. An untriggered prompt (a woman on a rainy night street) also shifts from neon-saturated to the dataset's warmer, greener key, i.e. normal style bleed for a style LoRA trained without a rare trigger token, and stays coherent.

Audio, checked rather than assumed. No output is silent or degenerate: silent-frame fraction is 0 everywhere and spectral flatness stays in 0.15 to 0.44 (a collapse to noise would push it toward 1). The birdsong survives with the adapter, as visible harmonic chirp structure in the spectrogram. But it is honestly weaker: on that prompt the adapter drops RMS from 0.0049 to 0.0014, the spectral centroid from 5.5 kHz to 4.1 kHz, and the frame-level dynamic range from 20.5 dB to 6.8 dB, so the foreground transients are flattened into the bed. On the untriggered prompt it moves the other way (RMS 0.0059 to 0.0221). This is the expected consequence of adapting a shared block stack, it is the reason audio is in the loss rather than out of it, and it is the reason a lower rank or a shorter run is the right default for an audio-sensitive adapter. It is not a silent failure, and it is measurable, which is what the split video_loss / audio_loss progress fields are for.

Tests. New tests/test_diffusion_h3_trainer.py, 61 tests. Every assertion was mutation-tested: break the thing it guards, confirm a test fails, restore. 52 mutations, 52 caught, including the velocity sign on either modality, audio dropped from the loss, an independent u for audio, the two shifts swapped or equalised, the LoRA targets written as the glob list PEFT cannot match, the targets unqualified so they leak into the text refiner, adaln_proj left to be quantized to uint8, the transformer named in the conditioning load, a keyframe conditioning row in the layout, the row timestep plan built audio-first, the adapter written without the transformer. prefix, the audio hop not derived from the latent rate, still images accepted as clips, a metadata row beating a sidecar, and every routing and refusal line.

studio/backend/tests/ and studio/backend/hub/tests/ diffed against the merge base in a separate worktree, both runs with --continue-on-collection-errors (this box has a huggingface-hub version skew that otherwise aborts collection): identical FAILED/ERROR line sets, 19,235 to 19,292 passed, 366 hub tests pass on both.

Deliberately left out

  • The Train UI listing. family_train_infos() is built from the image family registry, so like LTX-2 this is reachable through the API and the model_family override but does not appear in the Train picker yet.
  • A load path on the Video tab. core/inference/video.py has no LoRA surface at all, for any family, so the adapter is reported as lora_path and loaded by the caller. Diffusers also ships no MiniMaxH3LoraLoaderMixin, so there is no save_lora_weights / load_lora_weights pair to route through; the file written is nonetheless the ordinary single-file layout with the transformer. prefix, so it will load with load_lora_weights unchanged the day that mixin lands.
  • fp8 and mxfp8. Refused with a reason: the packed sequence mixes three modalities through one set of linears, so the per-family activation range the fp8 filter was measured against does not describe it.
  • A weighted loss and CFG dropout. Both refused with a reason: two schedules make a single weight over "the" timestep ambiguous, and the checkpoint is guidance-distilled so there is no unconditional branch to train.
  • Multi-clip batching, keyframe-conditioned training, and ref2va. All follow-ups.

oobabooga and others added 30 commits August 5, 2026 19:54
low_vram maps to the `model` policy, and offload_flags emits --vae-on-cpu for it
unconditionally. On H3 that kills the process:

    ggml/src/ggml-cpu/ops.cpp:6321: GGML_ASSERT(src0->type == GGML_TYPE_F16) failed

deterministically, SIGABRT, exit 134. Bisected on the flags: --vae-on-cpu with
--audio-vae aborts, the same command without --audio-vae renders in 95.87s, and an
fp16-converted audio VAE aborts too. So the trigger is the audio VAE, not the video
one, and the F32 type is imposed inside stable-diffusion.cpp rather than by the
file: ggml_conv_1d hardcodes an F16 im2col destination (ggml/src/ggml.c),
ggml_compute_forward_im2col_f16 then asserts the KERNEL is F16, and
audio_conv_weight_type (src/model/vae/ltx_audio_vae.hpp) maps only BF16 to F16 and
lets F32 through. It cannot be fixed by shipping a different checkpoint.

low_vram is the one mode a small-card user reaches for, so this drops the flag
rather than the mode. offload_flags takes vae_on_cpu, defaulting True so no other
family changes, and the H3 native path passes False. --offload-to-cpu and
--clip-on-cpu still apply, which is where the saving actually is: the denoiser
dominates, and with --offload-to-cpu the whole model peaks at 13.14 GiB.
Two conflicts, both mechanical:

- transformers_version.py: main reworded the comment under
  TRANSFORMERS_DEFAULT_VERSION while this branch changed the value.
  Kept both.
- test_video_backend.py: both sides appended a new test at the end of
  the file. Kept both.

Main also added test_curated_gguf_repos_are_unsloth_mirrors, which
requires every curated video gguf_repo to be an unsloth mirror so a
one-click pick cannot 404 when a community repack is renamed. H3 was
pointing at leejet/MiniMax-H3-GGUF, so it now points at
unsloth/MiniMax-H3-GGUF instead.

NOTE: unsloth/MiniMax-H3-GGUF is still private. It has to be made
public before this merges, or the pick will 401.
Main added test_curated_gguf_repos_are_unsloth_mirrors, which requires
every curated video gguf_repo to live under unsloth/ so a one-click pick
cannot 404 when a community repack is renamed or taken down. H3 was the
one family still on a community repo.

This was meant to be part of the merge commit but was left in the
worktree, so CI on that commit still saw the old value.

unsloth/MiniMax-H3-GGUF is still private and has to be made public
before this merges, or the pick will 401. No CI check reads it.
H3 is distilled and CFG-free: its empty unconditional prompt encodes to
zero tokens, and the transposed tensor that produces trips
GGML_ASSERT(!ggml_is_transposed(a)) in ggml.c. SIGABRT, exit 134.
Measured: cfg 1.0 renders, cfg 1.5 and cfg 4.0 both abort. sd.cpp
defaults cfg-scale to 7.0, so this is a crash a plausible refactor
reintroduces by forwarding guidance the way every other family does.

The native path already hardcodes 1.0 and the family sets
supports_cfg = False, but nothing held either in place. supports_cfg
only gates the diffusers path; the native path builds its own params.

Checked the test fails when cfg_scale is changed to forward guidance,
so it is not passing vacuously.
The macos-15-intel leg fails deterministically, not flakily:

  process didn't exit successfully: `/usr/bin/git init` (exit status: 1)
  --- stderr
  xcode-select: note: No developer tools were found, requesting install.

That runner has no Xcode, so /usr/bin/git is the developer-tools shim and
exits 1 for everything. uv needs a working git to resolve a git+https
dependency, so the diffusers pin this branch added cannot install there
at all. Main is unaffected because it depends on plain diffusers.

GitHub serves the same commit as a source archive, which uv installs with
no git involved. Verified by stubbing git to fail exactly the way the
macOS shim does: the git+ form reproduces the CI error, the archive form
installs diffusers 0.40.0.dev0 from the same SHA with
MiniMaxH3Transformer3DModel present and exported.

Also drops a full clone of diffusers from every install.
With the archive pin the macOS leg gets past `git init` and installs, but
then trips the nobuild guard:

  built from source: diffusers -- these must resolve to wheels on a clean machine

There is no wheel to resolve to. MiniMax-H3 support is not in any
diffusers release, so this branch has to pin a commit, and neither a git
URL nor a source archive can produce a wheel from an index.

Added to the same allowlist that already carries triton-kernels for the
same reason. Checked against the bar the comment there sets: diffusers
builds with plain setuptools, declares no ext_modules, and its tree has
zero .c/.cpp/.pyx/.rs/.cu files and no shipped binaries, so the PEP 517
build is a pure-Python copy step and needs no toolchain. The separate
compiler-invocation check in both scripts is untouched and still fires if
one is ever needed.

Verified the allowlist logic still rejects a non-allowlisted source build
(a log building both diffusers and numpy reports only numpy).

Remove this entry once a diffusers release carries H3 and the requirement
goes back to a version specifier. Noted in both scripts.
`pip scan-packages :: hf-stack` fails on this branch with 1 unbaselined
CRITICAL:

  C2 polling/beaconing loop detected
  Package: huggingface-hub
  File:    huggingface_hub/utils/_http.py
  L461:    while True:

This is on us, not upstream drift. Main pins huggingface-hub==0.36.2;
this branch needs >=1.23.0,<2.0 because diffusers at the pinned commit
requires it, so the resolved version moves 0.36.2 -> 1.27.0.

The baseline already carries this exact file and check at L462 and L298,
from earlier versions. It did not carry over because the key hashes the
matched code, not the line number, and the surrounding code changed
across the major version. That is the guard behaving correctly: changed
code in a baselined file reopens for review rather than staying
suppressed.

Reviewed it rather than just re-suppressing. L461 is the retry loop in
`http_backoff`: bounded by `nb_tries > max_retries`, the URL comes from
the caller, there is no hardcoded endpoint and nothing is exfiltrated.
Same benign construct as the entries it replaces.

Entry generated with the scanner's own _evidence_hash rather than
hand-written, and inserted beside its siblings so the diff stays 8 lines.
Verified: with the baseline the scan is exit 0 with 4 suppressed, without
it exit 1, so the guard still bites.
…iable

`mac macos-15 / trace / file` fails on this branch and passes on main. uv
reports:

  No solution found when resolving dependencies:
  Because you require huggingface-hub>=0.34.0,<1.0 and
  huggingface-hub>=1.23.0,<2.0, your requirements are unsatisfiable.

This branch moved base.txt, no-torch-runtime.txt, studio.txt and
constraints.txt to hub >=1.23.0,<2.0, because diffusers at the pinned
commit requires it, but left the flat <1.0 cap in
overrides-darwin-arm64.txt. That file is macOS-arm only, which is why
only the mac legs see it and Linux and Windows stayed green.

The failure then presents as something else entirely: uv gives up, the
installer falls back to pip, and the clean-machine trace fails on
"installer invoked toolchain: rustc" rather than on the resolution.

The cap's own comment explains it exists so the resolver can never pair
hub 1.x with a pinned transformers 4.57.6 / hub 0.36.2 stack. That is
still true below python 3.10 and still capped there. At 3.10 and above
this branch is on transformers 5.5.0 and hub 1.x, so the premise is gone,
and mlx-audio's own >=1.0 floor is satisfied by the 1.x window anyway.

Checked by collecting every hub specifier that applies per Python version
across all five files: py3.9 resolves to 0.36.2 as intended, py3.13 to
1.23.0/1.27.0. Before this change py3.13 resolved to nothing.
The curated-mirror test main added only inspects VideoFamily.gguf_repo.
H3's native path does not read that field: video_minimax_h3.py has its
own H3_GGUF_REPO constant, used for both the transformer and the Qwen3-VL
encoder. So pointing the family at the unsloth mirror in the previous
commit satisfied that test while the actual one-click download still came
from a community repack, which is the exact failure the test exists to
prevent.

Pointed the constant at the same mirror and added
test_the_h3_native_repo_matches_the_family_gguf_repo to pin the pair, so
the two cannot drift apart again. Verified it fails when the constant is
put back to leejet, so it is not passing vacuously.

The mirror now carries the Qwen3-VL encoder quants alongside the
denoisers, byte-identical in size to the community ones, so this repo
alone satisfies both of h3_native_hub_files' hub entries. The encoder is
part of MiniMaxAI/MiniMax-H3 itself (FL2VA/text_encoder) which we already
mirror publicly at unsloth/MiniMax-H3 under the same licence, so shipping
a quantization of it beside the denoisers is the same act.

Also checked the encoder-tier routing survives the dynamic rung names:
-UD-Q2_K_XL selects the Q2_K_M encoder and -UD-Q3_K_XL the Q4_K_M one,
asserted in the new test.

Updated the download-plan test, which hardcoded the old repo id.

NOTE: unsloth/MiniMax-H3-GGUF is private. Unlike before, that now really
does gate this: the native path downloads from it. It has to be public
before this merges.
validate_h3_transformer_filename had no test. That mattered less when the
denoisers lived alone; the mirror now ships the Qwen3-VL encoder quants in
the same repo, so the picker lists both and a user can name either. Loading
a 12-17 GB encoder as the transformer would fail deep inside sd-cli instead
of at the boundary.

The accept cases include the dynamic rung names on purpose. The guard is a
prefix/suffix check and `-UD-Q2_K_XL` is a shape it had never seen when it
was written; it happens to pass, and now that is asserted rather than
assumed.

Checked the test fails when the prefix check is dropped, so it is not
vacuous.
The comment justified the drop entirely by an sd.cpp abort. That abort is fixed
in the Unsloth fork, which would have made this look like a stale workaround to
revert once the fix reaches the pinned prebuilt.

Measured on a build carrying the fix, 640x384, 25 frames, 4 steps, q4_K, with
--offload-to-cpu --clip-on-cpu already applied: adding --vae-on-cpu moved peak
VRAM 12.42 -> 12.42 GiB and wall time 20.9s -> 100.4s. Under --offload-to-cpu
the peak is set by the streamed denoiser, so the flag saves nothing and costs
4.8x. It stays off on its own merits.
The pin was master-812-ea7f0c8, a stock upstream build, and on a stock build H3
does not work: it aborts on the default --cfg-scale, aborts again on
--vae-on-cpu, and its 1-D norms are quantized into an output uncorrelated with
its own bf16 reference (LPIPS 0.981). The Studio side worked around the first by
pinning cfg to 1.0 and the second by dropping the flag; the third had no
workaround on the consumer side at all.

All three are fixed in unslothai/stable-diffusion.cpp and open upstream as
leejet/stable-diffusion.cpp#1861, #1862 and #1863. The mirror's prebuilt
pipeline now applies them on top of the aged upstream tag it already builds, and
marks such a build with a -u<id> suffix naming the patch set, so
master-813-bfbef5b-u0665242 is upstream master-813-bfbef5b plus those three
patches and nothing else. The patches are deleted once upstream releases them,
at which point this pin goes back to a plain tag.

Verified on the published Linux x86_64 asset, not on a local build: both new
error strings are in the shipped sd-cli, and running it on a q4_K H3 denoiser
without --mode vid_gen now exits 1 with the instruction instead of core dumping
on a ggml assert.

test_video_backend's fake engine returned the old tag as its version string,
which read like a second pin; it only needs a non-None value, so it now says so.
Both are consequences of the two preceding commits, found in review.

The prebuilt pin is now mirror-only (master-813-bfbef5b-u0665242), and
_resolve_with_fallback still asked leejet for it. That request is a guaranteed
404 by construction, since the -u<id> suffix marks a build only the mirror
makes, so it was a wasted round trip on every install. Worse, when the mirror
genuinely cannot serve a host the fallback lands on leejet's latest, which has
none of the H3 fixes. For every other model that is the right trade, better a
stock native engine than none. For H3 it is not visible: it aborts on the
default cfg-scale, aborts on --vae-on-cpu, and a blanket --type renders a broken
video rather than failing. A user who saw only the generic 'falling back to
leejet' line had nothing connecting that to the output. It now says so.

Second, hub/utils/gguf.py filtered H3 companion GGUFs by the old community repo
id only. The mirror the family and catalog now advertise carries the Qwen3-VL
encoder quants beside the denoisers, so a 12 GB text encoder was being
aggregated as if it were a selectable transformer quant. Both bundle repos are
now recognised, case-insensitively, and the cache-dir match follows.

Tests are mutation-verified rather than assumed: restoring the upstream 404
attempt fails the ordering test, removing the H3 warning fails the fallback
test, and dropping the mirror from the bundle set fails three. The ordering test
deliberately makes the mirror serve nothing, because with the mirror serving the
first attempt succeeds and the upstream attempts are never reached, which made
an earlier version of it pass under its own mutation.

A third test pins the native loader's H3_GGUF_REPO to the bundle set, since
those live in different files and a future repo move that updated only the
loader would silently reintroduce the same aggregation bug.
_INT8_FAMILY_EXCLUDE_NAME_TOKENS has entries for qwen-image and hunyuanvideo-1.5
but none for minimax-h3, and H3 needs one for the same reason they do.

H3's adaLN projection is named adaln_proj, which no token in the generic list
matches: 'norm' is the closest and does not appear in the name. On the dense
checkpoint that projection is Linear(2688 -> 96768), so it clears
min_features = 512, gets quantized, and then runs at M = 1. Inductor lowers int8
matmul to _int_mm, which requires M > 16, so it raises 'self.size(0) needs to be
greater than 16, but got 1' at the first denoise. The offline prequant builder
bakes it in happily, which is exactly the drift the exclude list exists to
prevent for Flux and Qwen.

The pruned-modulation form hides this rather than fixing it: there adaln_proj is
Linear(8 -> 96768) and falls under min_features anyway. So this exclusion is what
makes the DENSE path correct and is a no-op on the pruned one.

context_embedder and token_refiner are added for the same reason hunyuanvideo-1.5
excludes its text stream. Measured at M = 10 text tokens against the video
stream's thousands, they are 3.47% of GEMM time even in the slow eager int8 path,
so leaving them bf16 costs nothing measurable.

This is what made an earlier measurement conclude int8 does not work on H3. It
does: on the pruned form int8 compiles and is 4.24% +-0.54% faster than fp8 at
identical memory, paired over 12 renders.
H3 pulls four files from two repos, and the Hub returns the same
'Repository Not Found ... make sure you are authenticated' for a repo that does
not exist, one that is private, and one your token does not cover. A user
reading that has no way to tell which of the four failed, and the wording points
away from the real cause whenever the repo exists but is not public.

That is the state the GGUF mirror is in today: it is unpublished, so picking H3
fails with a message suggesting the user fix their token, which will not help.
This replaces it with the repo, the component, and the actual remedy, and says
the other components are unaffected so the failure is not read as total.

Gated repos get different wording, since accepting a licence is a different
action from waiting for a repo to be published.

Anything that is not a recognised access error is passed back unchanged rather
than reworded, so a timeout or a full disk still reads as itself. The helper
returns the exception instead of raising, so the caller keeps raise-from and the
original traceback survives.

Mutation-verified three ways: rewording every error (timeouts included), fixing
the component name to 'denoiser', and giving gated repos the private wording
each fail the test.
Two thirds of an H3 render's peak is not activations. Measured at
640x384 across 124 frames, a 20.25 GB int8 denoiser peaks at 36.96 GB,
and the gap is almost all weights: the video VAE alone is 10.42 GB
because diffusers pins it to float32, and a further 4.91 GB is
autocast's own float16 copy of those same weights. A memory snapshot
puts 92.9% of the transient in 437 blocks allocated from nn.Linear,
largest 67.1 MB, which is the decoder's [2048, 16384] SwiGLU projection
in float16.

MiniMaxH3VideoDecodeStep wraps vae.decode in torch.autocast(float16),
and autocast caches every weight it casts for the lifetime of the
region, so the float32 original and its float16 twin are both resident
through the whole decode. Storing those weights as float16 up front
makes the cast a no-op and removes both. This is not an approximation:
x.to(float16).to(float16) is x.to(float16), and the four regression
tests check that on a real matmul rather than on the reasoning. The
audio VAE decode is not under autocast, so it keeps float32.

t2va starts from noise and never encodes, so vae.encoder and
vae.quant_conv go too. That part is gated on the workflow name rather
than dropped unconditionally, because an image-conditioned workflow
needs them.

Measured 36.96 -> 28.37 GB peak with the encoder drop and the pre-cast,
28.27 with expandable_segments as well, over 5 prompts x 2 seeds. Speed
is unchanged (-0.05% +-0.86% eager, -0.34% +-2.23% compiled), and every
arm hashes identically to its control on latents, audio_latents, frames
and audio.

The estimator's base still reads 68.5 GB. That figure was measured on
the bfloat16 modular components, not the int8 arm above, so it stays put
until it is re-measured in the same configuration rather than adjusted
by arithmetic.
torch._int_mm asserts self.size(0) > 16. torchao's eager path never trips
it (safe_int_mm falls back to a widened matmul), but inductor lowers the
same quantized linear straight to _int_mm, so any quantized Linear invoked
at a small activation row count crashes under torch.compile. Until now the
fix was to leave those linears dense bf16, which on H3 meant excluding
context_embedder and both token_refiner blocks: 13 linears, 798M
parameters, 0.80 GB of weights the int8 checkpoint was not allowed to
touch.

Pad instead. diffusion_quant_pad.PadToMinM pads the flattened row count up
to 32, runs the GEMM and slices the result back, so the module compiles
with no change to the quantization config and the caller's rows come back
bitwise unchanged. Verified bitwise on all 65 (module, M) cases across
H3's 13 linears at M = 10, 13, 14, 17, 19, on real torchao-quantized
weights; compiling those same modules unpadded raises the _int_mm assert
at M = 10, 13 and 14.

Two properties carry that exactness and both are asserted rather than
assumed. The pad rows replicate row 0, not zeros: an all-zero row has amax
0, so the activation quantizer divides by zero. And the activation scale
must be per row, so each kept row's scale comes from that row alone; a
quantized Linear whose granularity cannot be proven per row raises instead
of being quietly skipped, because a half-padded transformer compiles on
the wrapped modules and crashes on the rest.

Everything below pad_to normalises to pad_to rather than only what is
below the floor, so one inductor graph covers every prompt length in the
range. H3's seven eval prompts run at M = 10..19, which straddles the
floor, and padding only to 17 would leave three shapes behind.

The wrapper reparents the Linear, so it runs after quantize_ on the
runtime path and after load_state_dict on the prequant one. The offline
builder drives quantize_ directly and saves the state dict, so it never
sees a wrapper; PadToMinM is also state-dict transparent as a second line
of defence, saving and loading under its own prefix so a wrapped
transformer still writes context_embedder.weight.

Scoped to minimax-h3. qwen-image, qwen-image-edit and hunyuanvideo-1.5
have the same small-M shape but published int8 prequant checkpoints whose
metadata bakes the current exclusion set, and _validate_checkpoint
compares that set against exclude_tokens_for_scheme, so they move only
together with a rebuild. adaln_proj stays excluded for a different reason:
on the dense checkpoint it is Linear(2688 -> 96768) and runs at M = 1,
while on the pruned form it is Linear(8 -> 96768) and falls under
min_features anyway (verified: the filter rejects all 51 for min_features).

Measured on B200, 640x384 x 124 frames, 4 steps, 7 prompts x 2 seeds, the
two arms alternated within each cell so drift on a shared box cancels:

  checkpoint      21.052 -> 20.254 GB  (-0.798, -3.8%)
  transformer     21.051 -> 20.253 GB  (-0.798)
  load peak       21.137 -> 20.336 GB  (-0.801)
  render peak     37.766 -> 36.966 GB  (-0.800, -2.1%)
  step time       +0.0597 s +-0.0057 eager, +0.0533 s +-0.0086 compiled

The time is torchao's un-fused eager activation quantization on 13 modules
that run ONCE per render, so it is a fixed cost rather than a per-step
one, and it does not scale with steps or resolution. Compiling those
modules alongside the blocks removes it: +0.0034 s +-0.0040, no detectable
difference. Quality is unchanged as far as n = 14 can resolve: against the
same bf16 twin the padded arm sits +0.0070 +-0.0151 LPIPS from the
excluded one, which rules out a degradation larger than 0.022.
The H3 GGUFs are stable-diffusion.cpp conversions and carry no metadata
keys at all (kv_count 0), so general.architecture is absent where the
LTX-2 and Wan video GGUFs declare ltxv/wan. _arch_to_task therefore left
the downloaded repo with no task, which drops it from the Video picker's
On Device list and hands it to chat as a plain GGUF. Key the two bundle
repo ids before the arch is consulted.
On a CUDA/ROCm host /video/load acquires the VIDEO arbiter owner because the
resolved device target is not CPU. _run_load_h3_native then asks for an
accelerator-matched sd-cli, and the pinned prebuilt release publishes no Linux
CUDA/ROCm archive, so ensure_sd_cpp_binary returns None and the load commits the
CPU build with native_device = cpu. Nothing dropped the VIDEO claim, so the next
chat or image acquire evicted and unloaded an H3 runtime that holds no VRAM.

Release the claim once the CPU fallback is committed, through release_if so the
token check is atomic against a newer load that already took ownership. Mirrors
the CPU-only native release /images/load already does.
…ise, forward the hub token

- VideoBackend.loaded_repo_ids() publishes the repos the committed native H3 runtime
  re-reads every generation (Qwen encoder + both VAEs), and the delete-cached guard
  consults it, so deleting a companion under a loaded model is refused.
- The H3 modular workflow no longer falls back to a null progress context: the denoise
  loop drives pipe.scheduler.step once per step, so the existing wrapper gives it the
  same per-step progress and cancellation the other callback-less pipeline gets.
- load_components() gets the Settings token, so gated/private component loads are not
  issued anonymously.
ensure_sd_cpp_binary hands back whatever find_sd_cpp_binary locates and only
probes that it runs, so an install upgraded from an older Studio kept serving
its pre-H3 managed sd-cli. The H3 load's only gate is SdCppEngine.version(),
which that binary passes, so the load reported ready and the failure surfaced
on the first generation, after the whole bundle had downloaded.

Gate the H3 path alone on the capability instead of a version string: upstream
added --ref-video and the other H3-only options in the same commit that added
MiniMax-H3 (leejet/stable-diffusion.cpp#1854, master-812-ea7f0c8), and the
release prebuilts report 'version unknown, commit unknown' because they are
built without a .git directory, so --help is the only usable signal. Image
generation keeps accepting any user-supplied build.

A stale copy under the installer-owned root is removed so the pinned prebuilt
reinstalls; a build the user supplied is left in place and the load fails
naming it, the same ownership split _usable_or_discard_managed makes. A --help
that cannot be read means 'cannot tell', never 'no H3'.
On a Linux CUDA host the first H3 load installs the CPU prebuilt through the
fallback and correctly commits native_device = cpu, because the pinned tag
publishes no Linux CUDA, ROCm or Vulkan asset. Every later load then calls
ensure_sd_cpp_binary(accelerator = cuda), which finds that same CPU binary and
returns it without looking at what it was built for, so the fallback was
skipped, native_device stayed cuda, and Studio applied GPU offload policy and
retained the VIDEO gpu_arbiter claim while sd-cli ran wholly on the CPU. A
later chat or image acquire then evicted an unrelated GPU model.

Fall back on what the binary offers rather than on whether one was returned:
sd-cli --list-devices prints one name/description line per available ggml
backend device, so a CPU-only build answers with CPU alone. The second load now
reaches the same cpu conclusion as the first, which is what lets the existing
release_if drop the stale claim. Unreadable output, or an older build that
rejects the flag, keeps the GPU: neither says the accelerator is missing.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d7c5dab8c9

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

# and the row timesteps describe ONE packed sequence that every batch item shares. Two
# clips with different captions have different text lengths and therefore different
# layouts, so a batch > 1 cannot be formed without padding the model has no mask for.
if cfg.train_batch_size != 1:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Lock the H3 batch control to one

When a user enters Batch > 1—or switches to H3 after using that value for another family—this validation rejects Start even though the Train panel still renders an unrestricted Batch field and always sends its state (diffusion-train-panel.tsx:1295 and the request payload). The frontend also ignores the reported train_batch_size family default, so advertise this limitation and clamp/hide the control for H3, as is already done for its unsupported compile and checkpoint settings.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and it belongs with the two controls already handled this way. save_steps and compile are both hidden for a family that refuses them, precisely so a set value cannot turn into a rejected Start with nothing on the control to say why, and Batch was left out of that treatment while carrying the same kind of refusal.

The carry-over case you name is the likely one: the field holds panel state, not a family default, so a 2 set for SDXL is still 2 after switching to H3.

7058e74 reports max_train_batch_size per family, 1 for a new SINGLE_SEQUENCE_FAMILIES set kept beside the refusal it explains, null everywhere else. The panel hides Batch when the cap is 1 and sends the cap rather than the field, because the field is hidden and not reset. The Grad accumulation hint changes for a capped family to say it is the only way to raise the effective batch, which is what the refusal message already tells anyone who hit it. An older backend reports nothing, reads as null, and behaves exactly as today.

diffusion-train-batch-cap.test.ts asserts the contract against the panel source, the way dataset-file-selection.test.ts does for the labeling-grid gate, since the payload is built inline. Mutation checked: restoring train_batch_size: batchSize fails the wire assertion. Frontend typecheck clean, 1565 pass.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 405cffdfbf

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

try:
pairs = await asyncio.to_thread(
_dtc.discover_image_caption_pairs,
_dtc.discover_training_pairs,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exempt H3 datasets from the legacy clip refusal

When resolved_family is minimax-h3 and the dataset contains the captioned video clips that this discovery now expects, execution never reaches this call: immediately above it, start_diffusion_training still invokes _clip_dataset_refusal, which returns an error for every folder with clip_count > 0. Consequently every valid H3 training request through /diffusion/start receives HTTP 400, making the new trainer unreachable through the API; apply that refusal only to image-trained families or otherwise bypass it for CLIP_TRAINED_FAMILIES.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and it made the feature unreachable. _clip_dataset_refusal sits above the discovery and fires on any folder holding a clip, while discover_training_pairs immediately below it had already been taught to branch on CLIP_TRAINED_FAMILIES. So a MiniMax-H3 dataset, which is captioned clips and nothing else, was turned away with "training from clips is not supported yet" before the family-aware half ever ran: the trainer this branch adds, refused by its own route.

Fixed in 7058e74 by asking the same family question one step earlier rather than by bypassing the refusal. Image-trained families keep it exactly as it was, including the mixed-folder case it was written for.

test_a_clip_trained_family_is_not_turned_away_by_the_clip_refusal drives the real route: the refusal is stubbed with a recorder, an H3 request returns 200 with the recorder never consulted, and the control, an image family posting the same dataset, still gets 400 through that same refusal. Mutation checked: removing the family guard fails with assert 400 == 200 and the clip message in the body.

import torch
from diffusers import ModularPipeline

pipe = ModularPipeline.from_pretrained(cfg.base_model, token = cfg.hf_token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Pin H3 training loads to the active Hub cache

When the user changes Studio's Hugging Face cache folder during the current backend session, this unpinned load resolves through huggingface_hub's import-time cache constant rather than active_hf_hub_cache(). The diffusion training subprocess is spawned without the cache-environment wrapper, and set_hf_cache_home persists the new setting without updating that environment, so the subsequent load_components calls and _load_transformer also miss components already present in the selected cache and can download roughly 145 GB into the old/default location, potentially failing for disk space. Pass the live cache_dir to the modular index, both component loads, and the transformer loads, as the H3 inference path does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and the reasoning about the subprocess is the part that makes it bite: the training child is spawned without the cache-environment wrapper, and set_hf_cache_home persists the new setting without updating that environment, so an unset cache_dir here resolves through huggingface_hub import-time constant and points at the old root for the whole run.

7058e74 pins all five call sites to hub_cache_dir(), the same helper the inference H3 loader uses: the ModularPipeline index, both load_components calls, and both arms of _load_transformer. The denoiser is the expensive one, which is where the 145 GB figure comes from.

Two tests. The existing conditioner-token test now also asserts every one of the three conditioner calls carries the live root, and test_the_h3_denoiser_load_is_pinned_to_the_live_cache is parametrized over bf16 and nf4 so neither arm can be missed. Mutation checked on the denoiser: dropping cache_dir fails with KeyError: cache_dir on both arms.

Comment thread studio/backend/core/inference/video.py Outdated
# and the native path pins cfg_scale to 1.0. Clamp it here so the recipe cannot
# record a guidance that did not run.
guidance = float(fam.default_guidance)
guidance = float(default_guidance)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Record the fixed CFG-free guidance value

For a CFG-free H3 model loaded from an identifier or local path containing another entry from _VIDEO_GENERATION_DEFAULTS—for example /models/wan/minimax_h3_fl2va-Q4.gguf—default_video_generation_params returns that unrelated family's guidance (5.0 here). This branch now records that value even though the Diffusers path forwards no guidance and the native path always pins cfg_scale to 1.0, recreating the inaccurate gallery recipe this normalization is intended to prevent. Use fam.default_guidance for supports_cfg=False families rather than the identifier-derived variant default.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. default_video_generation_params matches on the repo id or path, so a local H3 file under a folder named after another family, /models/wan/minimax_h3_fl2va-Q4_K_M.gguf being the obvious one, picks up that family 5.0. Recording it writes back exactly the inaccurate recipe this normalisation exists to prevent, and with a number no H3 sampler can have produced, since the diffusers branch forwards no guidance and the native branch pins cfg_scale 1.0.

7058e74 uses fam.default_guidance for a supports_cfg=False family. The identifier-derived value still governs everywhere else.

test_h3_guidance_normalises_to_its_own_default_not_a_neighbours asserts the precondition first, that the identifier really does resolve to a different guidance, so the test cannot pass by that lookup happening to agree with H3. Mutation checked: assert 5.0 == 1.0.

@danielhanchen

Copy link
Copy Markdown
Member Author

Full backend suite on the merged head vs current main, both run on the same box.

studio/backend/tests studio/backend/hub/tests
head 405cffd 6 failed, 20951 passed, 87 skipped, 15 errors 479 passed
main 3bbed68 6 failed, 20825 passed, 88 skipped, 15 errors 479 passed

The failing and erroring sets are identical, line for line: test_kv_cache_estimation resolves_real_transformers_arches, the three test_mcp_stdio_improvements cases, test_studio_api test_help_output, test_text_io_encoding for moe_utils.py, and the 15 test_studio_api server-exited errors. All of them fail the same way on main, so nothing here is new. The branch adds 126 passing tests.

Current main is merged in (405cffd) and the PR is mergeable with no conflicts.

danielhanchen and others added 2 commits August 10, 2026 11:09
Four things the review found, all real.

The clip refusal ran unconditionally above a discovery that had already been taught
to branch on the family, and it fires on any folder holding a clip. A MiniMax-H3
dataset is captioned clips and nothing else, so every valid request came back 400
"training from clips is not supported yet": the trainer this branch adds, unreachable
through its own route. Ask the same family question one step earlier.

The H3 loads resolved cache_dir through huggingface_hub's import-time constant. The
training subprocess is spawned without the cache-environment wrapper, so a cache
folder changed mid-session was invisible: components already in the selected root
were missed and roughly 145 GB re-downloaded into the old one. Pin the modular index,
both component loads and both denoiser arms to hub_cache_dir(), as the inference path
does.

A CFG-free family recorded the identifier-derived guidance, so a local H3 file under a
folder named after another family wrote back that family's 5.0 -- exactly the
inaccurate gallery recipe the normalisation exists to prevent. Use fam.default_guidance.

And the Batch control was rendered unrestricted while the validation refuses anything
above 1, so a value typed here, or carried over from the family the user was on a
moment ago, rejected Start with nothing on the control to say why. Report
max_train_batch_size per family, hide the field when it caps at 1, and send the cap:
the field is hidden, not reset.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 505b6aea4c

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

# "Checkpoint every" control: save_steps is refused, not ignored, for such a family, so
# offering the control means offering a value that rejects Start. Defaults True so an older
# backend's payload, which has no such families in it, keeps the control.
supports_checkpoints: bool = True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Expose the batch cap in the response model

When /diffusion/info constructs DiffusionTrainableFamily(**info), Pydantic drops the undeclared max_train_batch_size emitted by family_train_infos(). Consequently the frontend always reads this cap as undefined, continues rendering Batch, and sends a carried-over value above 1 that H3 rejects. This is fresh evidence for the previously accepted batch-control issue: the new frontend clamp exists, but the response schema prevents its input from reaching the browser. Add the cap to this model so it survives serialization.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed in de510d7. family_train_infos() was already emitting max_train_batch_size, but DiffusionTrainableFamily did not declare the field, so pydantic dropped it on the way out and the browser never saw the cap. Declared it as Optional[int] = None, which leaves every other family unchanged, and pinned it with studio/frontend/tests/diffusion-train-batch-cap.test.ts so the emitter and the response model cannot drift apart again.

Comment thread studio/backend/routes/training.py Outdated
clip_refusal = await asyncio.to_thread(_clip_dataset_refusal, config["data_dir"])
if clip_refusal is not None:
raise HTTPException(status_code = 400, detail = clip_refusal)
if normalized_cfg.resolved_family not in _dtc.CLIP_TRAINED_FAMILIES:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refuse mixed-media folders for clip training

When H3 is selected and a dataset contains both clips and still images, this exemption skips the only mixed-media guard, after which discover_training_pairs() dispatches to discover_clip_caption_pairs(), which enumerates only video extensions. The run therefore succeeds while silently omitting every still image even though /diffusion/info and the frontend count them as training items—the same partial-dataset behavior this guard prevents for image families. Add the converse image refusal for clip-trained families, or otherwise surface and filter the exact subset that will train.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed in de510d7. The refusal was one-directional: a clip folder offered to an image-trained family was refused, but an image folder offered to a clip-trained family was not, so an H3 run could start on a dataset with no video in it at all. _mixed_media_refusal now picks the check by the resolved family, so each direction is refused with the message that names what it actually wanted.

continue
if not isinstance(row, dict):
continue
key = row.get("file_name") or row.get("video") or row.get("image") or row.get("file")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count metadata captions keyed by video

For a clip dataset whose metadata.jsonl uses the newly supported {"video": "clip.mp4", "text": "..."} form, H3 discovery accepts the caption here, but routes.training._load_metadata_captions() recognizes only file_name/image/file. Thus /diffusion/info reports caption_count = 0, and the frontend blocks Start until the user supplies an unnecessary trigger prompt even though the trainer already has captions for every clip. Teach the shared summary loader the same video alias so discovery and UI validation agree.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed in de510d7. The caption counter only read file_name, so a metadata.jsonl keyed by video counted zero captions and the run reported an uncaptioned dataset while the loader itself read the rows fine. The key list now matches the loader's: file_name, then video, image, file.

danielhanchen and others added 4 commits August 10, 2026 11:39
…clip run

Three follow-ons the review found on the previous commit.

DiffusionTrainableFamily did not declare max_train_batch_size, so Pydantic dropped it
from /diffusion/info and the panel read the cap as undefined: the clamp was there and
never received its input.

Exempting a clip family from the clip refusal exempted it from the only mixed-media
guard too, and discover_clip_caption_pairs enumerates video extensions alone, so a
folder holding stills trained on the clips and said nothing while the picker counted the
stills as trainable items. That is the same silent partial dataset the refusal exists to
prevent, in the other direction, so it gets the converse refusal and both now go through
one function that picks the direction by family.

And the summary loader knew file_name/image/file while the clip discovery also accepts
video, so a clip dataset written with that key reported no captions and the panel
demanded a trigger prompt the trainer did not need.
Resolves the video.py overlap with the reference-denoiser prequant rungs. The
download-plan route test for a quantized reference pick asserted a contract that
main has since changed: ref2va now has its own hosted int8 and fp8 denoisers, so
that pairing resolves instead of being refused. Retargeted at the rule that is
still live, which is the one worth protecting anyway: the plan is judged per
(scheme, partition), so int8 ref2va plans the reference partition and a scheme
with no hosted checkpoint is still refused before anything is staged.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4eb75b782b

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

Comment thread studio/backend/routes/training.py Outdated
Comment on lines +3223 to +3224
if any(_listed_dataset_clip_count(s) > 0 for s in datasets):
return infos

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Advertise clip families only with a usable clip dataset

When the listed folders contain a mixed image/clip dataset, this condition advertises MiniMax-H3 merely because clip_count > 0, even though _mixed_media_refusal() rejects that same folder for H3 because it contains still images. The picker can therefore offer H3 with no compatible selectable dataset, and more generally it does not prevent pairing H3 with an image-only folder or an image family with a clip-only folder, so Start predictably returns 400. Filter datasets by the selected family's medium or base the advertisement on at least one dataset that passes the corresponding refusal.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed in 836b71a. The advertisement gate asked only whether a folder had clips, but _image_dataset_refusal turns a MIXED folder away from a clip family at Start, so a folder of clips and stills advertised H3 and then rejected the pick. That is the same dead end the narrowing exists to close, reached one click later. _listed_dataset_trains_clips now asks the question the refusal asks: clips present, no stills. Two existing fixtures reported clips on top of a real still count, which made every folder they built read as mixed, so they now say what they meant instead of the new rule being relaxed to fit them.

Comment on lines +820 to +821
video_loss = round(step_video, 5),
audio_loss = round(step_audio, 5),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Thread the split H3 losses through training status

During every H3 run these two metrics are placed on the progress event, but DiffusionTrainingService._apply_event() copies only loss, avg_loss, learning rate, gradient norm, and performance fields; neither its state/history nor the response models declare video_loss or audio_loss. The queue therefore discards both values immediately, so users cannot observe whether only one half of the joint objective is improving—the main diagnostic intended to reveal audio degradation. Persist and expose the per-modality values in live status and run history, or remove the misleading emission.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed in 836b71a. Correct on both counts: the trainer emitted them every step and _apply_event copied neither, so the queue dropped them and the diagnostic that shows one half of the joint objective degrading did not exist at all. Persisted rather than removed, since that signal is the reason the split is computed. They now reach the status snapshot, the bounded metric history and the run record, and DiffusionTrainingStatusResponse / DiffusionMetricHistory declare them so pydantic does not drop them on the way out. A step that reports only the combined loss contributes nulls, so the series stay index-aligned with steps, and the history arrays are now driven off a single list so a new series cannot be added to the appends and forgotten in the decimation.

Comment on lines +450 to +452
if not chunks:
raise ValueError(f"{Path(path).name} decoded to no audio samples.")
samples = np.concatenate(chunks, axis = 0).astype("float32")[:target_samples]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject soundtracks that decode entirely to silence

For a full-length but muted audio track, chunks is nonempty and the duration check passes, so this returns an all-zero waveform even though the dataset contract requires clips with sound. That clip is then included in the joint audio loss and teaches the shared adapter to predict silence—the same harmful outcome the missing/short-audio checks are intended to prevent. Detect an entirely silent or effectively zero-energy decoded window and reject it with the other audio validation errors.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed in 836b71a. The function's own docstring already made this argument for the short case: padding a materially short soundtrack out to the window trains the adapter on a target that is mostly silence. A full-length muted track reaches the identical target while passing every check, because the checks all measure duration. Refused now with the other audio validation errors. Measured on peak amplitude rather than mean energy, at 1e-4 (about -80 dBFS), so a clip that is merely quiet, or silent for almost all its length with one real sound in it, is still accepted, and a track authored as digital silence is caught whether or not an encode round trip left it at exact zeros.

@danielhanchen

Copy link
Copy Markdown
Member Author

Full backend suite on the merged head

Ran studio/backend/tests/ and studio/backend/hub/tests/ as separate invocations at a36707e81, on the same box as the reference run.

suite result
studio/backend/tests 9 failed, 21181 passed, 87 skipped, 15 errors, 11 subtests passed (846.98s)
studio/backend/hub/tests 479 passed

The 9 are the same set main carries, none of them in video or training:

tests/test_kv_cache_estimation.py::TestTransformersIntrospection::test_resolves_real_transformers_arches
tests/test_mcp_stdio_improvements.py::test_client_refuses_stdio_when_disabled
tests/test_mcp_stdio_improvements.py::test_client_builds_stdio_when_enabled_without_spawning
tests/test_mcp_stdio_improvements.py::test_client_http_unaffected_by_gate
tests/test_research_runs_storage.py::test_delete_thread_cancels_active_research_run
tests/test_research_runs_storage.py::test_project_delete_cancels_runs_captured_by_delete_transaction
tests/test_research_runs_storage.py::test_clear_history_cancels_runs_captured_by_delete_transaction
tests/test_studio_api.py::test_help_output
tests/test_text_io_encoding.py::test_text_io_names_its_encoding[moe_utils.py]

The 15 errors are all tests/test_studio_api.py server-start failures, also present on main.

One test changed contract in the merge, deliberately

test_video_download_plan_refuses_a_quantized_reference_pick asserted that an int8 ref2va pick is refused. That was true only while the keyframe partition was the only one with hosted checkpoints. #8329 published the reference denoiser's int8 and fp8 rungs and generalised the check to video_family_prequant_available(fam, scheme, task, base_repo), so the pairing now resolves and the plan is correctly reached. Refusing it would be the bug.

I retargeted the test at the rule that is still live, and which is the one actually worth protecting: the plan is judged per (scheme, PARTITION). It now asserts both halves, since either alone passes for the wrong reason.

  • int8 + ref2va returns 200 and download_plan is called with h3_task="ref2va", so the reference partition is what gets staged rather than the keyframe one it used to fall back to.
  • nvfp4 + ref2va still 400s before download_plan is reached, and the message names ref2va and points at int8 and fp8.

Mutation-checked: making video_family_prequant_available return True unconditionally fails the new test.

CI

Every check on this branch reads red, and all of them are cancelled rather than failure - the org queue mass-cancelled at 12:00 across every branch including main. Validation is running on the staging repo instead: danielhanchen#892.

danielhanchen and others added 3 commits August 10, 2026 12:12
…e a silent track

Three gaps the reviewers found, all of them mine.

The Train picker advertised a clip family whenever any listed folder had clips,
but Start refuses a MIXED folder for those families, so a folder of clips and
stills offered MiniMax-H3 and then rejected the pick. The advertisement now asks
the question the refusal asks: clips, and no stills. Two test fixtures reported
clips on top of a real still count, which made every folder they built read as
mixed; they now say what they meant.

The H3 trainer emitted video_loss and audio_loss on every progress event and the
service copied neither, so the queue dropped them and the one diagnostic that
shows a joint run degrading in only one modality did not exist. They are folded
into the status snapshot, the bounded history and the persisted run record. The
history series are now driven off one list, so a new series cannot be added to
the appends and forgotten in the decimation.

A muted soundtrack is full length, so every audio check passed and the window
came back all zeros: the same target the short-audio refusal exists to keep out,
by a route it cannot see. Refused on peak amplitude, so a quiet clip, or one
that is silent except for a single sound, is still accepted.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 7632d7d194

ℹ️ 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

Copy link
Copy Markdown
Member Author

Full suite on the head carrying the three new fixes

836b71a4f, with main merged forward through #8337.

suite result
studio/backend/tests 9 failed, 21188 passed, 87 skipped, 15 errors (868.99s)
studio/backend/hub/tests 479 passed

The 9 are main's set, unchanged and none of them in video or training: test_kv_cache_estimation, three in test_mcp_stdio_improvements, three in test_research_runs_storage, test_studio_api::test_help_output, test_text_io_encoding. The 15 errors are test_studio_api server-start failures, also on main. Against the pre-fix run on this branch the count is identical and the pass count is up by 7, which is the new tests.

Ruff clean. Each of the three fixes was mutation-checked: reverting it fails exactly the test that covers it and nothing else.

On the red checks

Two separate things, neither of them this PR.

Most of them are cancelled, not failure - the org queue drained at 12:00 across every branch including main, and those runs refuse both retry endpoints, so they only clear on a push.

The four (Python 3.10/3.11/3.12/3.13) jobs are a real breakage on main, which this branch inherits through the merge:

ERROR collecting studio/backend/tests/test_trainer_stdout_quiet.py
ImportError: Unsloth: Please install unsloth_zoo via `pip install unsloth_zoo` then retry!

That module imports core.training.trainer at module scope, which imports unsloth and through it unsloth_zoo, and the backend pytest matrix installs neither. It fails collection, so it fails the whole job, on every open PR. Fixed separately in #8342, which also carries a guard so a fourth module cannot arrive without stubbing first. Verified there by reproducing the matrix dep set: 21280 collected, 0 collection errors.

oobabooga and others added 5 commits August 10, 2026 06:04
* Studio: add MiniMax H3 reference generation

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: offer the H3 task choice on a routed video pick too

A MiniMax H3 pick made in the chat picker arrives on the video page as ?model=,
and that effect called loadOrStage directly. Only the direct-pick branch opened
the task dialog, so the routed path staged the default fl2va denoiser, 66 GB,
with no way to ask for References. Both branches now share one predicate.

* Slice the staged download plan out of the flow that builds it

The base now calls getVideoDownloadPlan earlier for the row-sizing footprint probe, and
that call only ever runs for a named GGUF file, where the partition is the filename
rather than a task flag. Finding the plan by the first occurrence in the file therefore
read the wrong call and the H3 task assertion no longer described the staging path.
Slice loadOrStage first, then find the plan inside it.

* Reach the H3 partition dialog from an on-device copy, and unwind it on hide

Three things the review found on the picker side of reference generation.

An on-device copy of the pipeline reaches the generic local-pipeline branch, which a
Hub-id equality test never recognises, so an omitted h3_task pinned it to fl2va and its
transformer_ref partition was unreachable with the weights sitting on disk. Match on the
final path segment, the way a local checkpoint's family is read off its filename
elsewhere, and consult it from that branch too.

Hiding the page cleared the dialog without taking its cancellation path. The pick that
opened it had already replaced the quant label, steps and guidance and parked their
rollback, and the load it was deferring never ran, so returning to Video found controls
describing H3 over whatever model was still resident, plus a stale rollback for the next
pick to trip over. Take the same ending as Cancel, guarded on there being a pending pick
so hiding an idle page reverts nothing.

And defaultVariant is a quant key chosen across the whole repo, which a filenamePrefix
subset need not contain: H3 offers 6 ref2va quants against 8 fl2va ones. Stored
unchanged, the budget-unavailable branch of the recommendation returned a key with no
visible row, so nothing read as recommended and the sorter fell through to largest
first. Drop it when the prefix filters it out; an unfiltered listing is untouched.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
One conflict, in test_video_backend.py, and it is additive on both sides: this
branch appended the two-partition H3 denoiser cases at the end of the file while
#8274 appended its managed-tree admission cases in the same place. Kept both.

214 passed in that file, 642 across the video, H3 and sd.cpp suites.
One conflict, in test_diffusion_training.py, additive on both sides: this branch
appended the clip-refusal ordering cases while #8267 appended its normalized
fetch-mirror preflight cases in the same place. Kept both.

131 passed in that file, 593 across the diffusion, H3 and video suites,
frontend 1599 passed with tsc clean.
@danielhanchen
danielhanchen merged commit ae09aa8 into main Aug 10, 2026
16 of 56 checks passed
@danielhanchen
danielhanchen deleted the h3-video-lora branch August 10, 2026 13:12

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 81925af121

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

Comment on lines +984 to +985
video_loss: List[Optional[float]] = Field(default_factory = list)
audio_loss: List[Optional[float]] = Field(default_factory = list)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Render the split H3 losses in the training UI

During a MiniMax-H3 run, adding these arrays to the response model still does not make the diagnostic observable: studio/frontend/src/features/images/api.ts declares neither split-loss field, and diffusion-train-panel.tsx builds both live and persisted charts solely from combined loss and gradient norm; a repo-wide frontend search finds no consumption of video_loss or audio_loss. Fresh evidence after the previously accepted status-threading fix is that the backend now serializes both metrics while the frontend ignores them, despite the adjacent comment saying the chart should decide whether to draw the split curves. Add the frontend fields and render the two series or corresponding stats.

Useful? React with 👍 / 👎.

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.

2 participants