Repository navigation
Studio H3 / H3-Image: bit-exact per-row AdaLN modulation, int8 GEMM on the streamed tier - #17618
Conversation
…y tier The fused q/k norm + RoPE kernel summed the squares with tl.sum, so rstd differed from torch's in the last fp32 bit on some rows and the 6-step H3-Image render drifted; it was left off on the streamed tier for that reason. - The norm now reproduces torch's CUDA _fused_rms_norm vectorized row kernel: lane l of warp g sums elements 4*(32g+l)..+3 in order, each warp folds its lanes in shuffle-down order (16, 8, 4, 2, 1), the warps fold last, then rsqrt(sum / D + eps) and w * (rstd * x) rounded once. The rotation already rounded where eager does. - A second form runs the stock F.rms_norm and the exact rotation kernel, for a torch whose norm takes another path (the composite one) or inputs the vectorized kernel would not take (misaligned or mixed-dtype weight). - Each form is engaged only after matching the eager chain bit for bit on the device (per device, dtype, head dim, rotary dim; never first checked during graph capture); anything else runs the stock math. - H3-Image now turns it on for every tier. UNSLOTH_H3_IMAGE_QK_ROPE=0 / UNSLOTH_H3_QK_ROPE=0 still turn it off; UNSLOTH_H3_QK_ROPE_MODE=fused|rope restricts the form.
…device race - The rotation's products and sum round to the activation dtype through explicit-rounding PTX mul / add: with fp fusion on, plain ops were narrowed to bf16 and contracted into one fma.rn.bf16, skipping eager's rounding. - The norm's per-thread sums are explicit adds over four strided [rows, 32] loads, so only the warp butterfly is left to tl.sum (the reshape tree was correct but 100x slower). - The fused form runs only on the kernel specialization the device check compiled (16-byte aligned input, token and head strides divisible by 16). - The device check races the exact forms against the stock chain and keeps those more than 2% faster, fastest first; UNSLOTH_H3_QK_ROPE_MODE still forces one.
…jected on NaN [skip ci]
[skip ci]
…hout gathers, bit-exact The block forward read its six AdaLN chunks per packed row with index_select, one [seq, hidden] copy each, and ran every op as its own pass. Two Triton kernels read the AdaLN tables through the row index instead and keep eager's fp32-op-then-round chain with explicit-rounding PTX. They engage per (device, dtype, hidden) only after a bit-exact check and a timed probe; anything else takes the stock math. The block forward is swapped only when its class forward is the stock body statement for statement. Every tier unless the opt-in regional compile is on. UNSLOTH_H3_ROW_MOD=0 turns it off.
The streamed tier only took the attention levers, so its int8 ConvRot Linears ran the stock rotate + int8 Linear path while their block was on the card. On an L4 with the default int8 DiT streamed, a 2048x2048 image took about 81 s (73 s denoise), and that path hit an illegal memory access / CUBLAS_STATUS_EXECUTION_FAILED on the first 1024 render after the 2048 ones in 5 of 6 arms (main and integration). The speed installer now asks the int8 GEMM for its call-time mode on the streamed tier (the mode the generic offloaded denoisers use): a Linear whose weight is on the card at call time runs the fused-dequant GEMM the resident tiers run, anything else keeps the stock path. Row pads the GEMM serves are unwrapped as on the resident tiers. L4: 24.1-24.4 s per 2048 image (16.2 s denoise), 1024 and edits complete. Not byte-identical to the stock streamed path (LPIPS 0.08-0.15 between the two on L4); against a bf16 render it lands in the same band as the resident int8 tier. UNSLOTH_H3_IMAGE_INT8_GEMM_STREAMED=0 (or UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED=0) keeps the stock path.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: abc5225c3b
ℹ️ 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".
| # whenever their weight is there at call time and keep the stock path otherwise. | ||
| from . import diffusion_int8_gemm as int8_gemm | ||
| if int8_gemm.install(transformer, logger, device = dev): | ||
| _unwrap(_row_pads(transformer), keep = _fused_gemm_serves) |
There was a problem hiding this comment.
Preserve row padding when the streamer replaces weight parameters
When pinned streaming is disabled (UNSLOTH_H3_IMAGE_PINNED_STREAM=0) or unavailable, H3-Image uses ModuleListStreamer, whose _onload replaces each weight with a new Parameter. The installed GEMM's _linear_forward consequently always takes its stock fallback because self.weight is not weight. However, this unwrap removes those Linears' row padding based only on the install-time fused flag. Packed sequence lengths unsupported by the stock int8 GEMM therefore lose the padding that previously prevented its slow fp32 fallback, making this supported streamed configuration slower rather than faster. Keep the wrappers for this streamer, or make the GEMM safely support its parameter-replacement behavior before unwrapping.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 652188c: the streamed GEMM now engages only when the DiT blocks stream through the pinned prefetch streamer, which copies into the same parameters. Behind the pageable ModuleListStreamer (pinned streaming off or unavailable) the stock path and its row pads stay. The streamed-tier test now covers pinned, pageable and no streamer.
The pageable ModuleListStreamer swaps in a new Parameter per call, so the swapped GEMM always took its stock fallback there, and unwrapping the row pads only lost them (slow fp32 fallback on unsupported row counts). That streamer now keeps the stock path and its row pads. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
# Conflicts: # studio/backend/core/inference/diffusion_minimax_h3_image_speed.py [skip ci]
…rs (#17658) Stacked on #17617 (base branch `h3-int8-sm120`). Retarget to `main` once that merges. ## Summary #17617 moved uncompiled, resident int8 denoisers onto Studio's bit-identical int8 GEMM routes. A denoiser that streams block by block still ran torchao's eager int8 Linear. That covers MiniMax-H3 INT8 at speed `off` on L4, A100-40 and any card where the other components need the room. This PR gives those streamed denoisers the same routes in call-time mode. MiniMax-H3 INT8-ConvRot, speed `off`, streamed, 640x384, 124 frames, 20 steps: - G4: 2.06 -> 1.14 s/step, the same speed as the resident tier (1.13). - L4: 12.26 -> 9.16 s/step (-25%). - Frames are byte-identical to the base on both cards (sha256). ## Root cause `apply_speed_optims` runs `_install_eager_int8_gemm` (#17617) before placement, and that function skips any denoiser that will move (`moved = offload_active if denoiser_offloaded is None else denoiser_offloaded`). The compiled streamed install (`video.py`, `if denoiser_streamed and "compiled" in speed_optims`) covers only the compiled tier. So a streamed H3 denoiser on speed `off` / `eager`, or after a declined compile, kept torchao's Linear for all 300 int8 calls per step: a float32 epilogue, an eager rotation and an eager act quant. The generic video placement (`apply_memory_plan`, with the event-fenced prefetch from `diffusion_memory`) has the same gap for any other family that streams int8 Linears. ## Change - `diffusion_int8_gemm.install_streamed_eager(transformer, device)` is `install(..., device=device, exact=True)`. These are `install_eager`'s routes: the fused-dequant GEMM, the dense `rotq_i8` rotation + act quant (never `rotq_h16`), and no SwiGLU fusion. They run in the existing call-time mode: each call checks that the Linear's own weight is still the installed Parameter and sits on the activation's card. Otherwise the call takes torchao's path. - `diffusion_speed.install_streamed_eager_int8_gemm(pipe, device)` runs after placement. It engages only on a denoiser that: - is driven by the event-fenced prefetcher (`module_prefetcher`). That prefetcher copies into the same Parameters (`swap_tensors` / inner-tensor re-pointing), so the identity check sees every onload; - is not compiled (`compiled_denoiser`), not already swapped, and has int8 candidates. - `video.py` calls it in two places: - in the MiniMax-H3 branch, for a streamed denoiser the compile did not take; - in the generic video placement, right after `compile_pipe_below_offload_hooks`, for every denoiser view. Status reports `int8_gemm_streamed`, and `int8_gemm_live` drops it when nothing swapped. - `shared_rotq_linears` (shared Q/K/V act quant) now passes `exact` when every Linear in the group is on the eager routes. The shared quant is then the same dense kernel each Linear runs on its own. Compiled installs never set the mark, so they are unchanged. Switches: - `UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED_EAGER=0` keeps torchao's path on streamed denoisers. - `UNSLOTH_DIFFUSION_INT8_GEMM_EAGER=0`, `UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED=0` and `UNSLOTH_DIFFUSION_INT8_GEMM=0` also turn it off. ## Results MiniMax-H3 fl2va, hosted INT8-ConvRot (text encoder int8), 640x384, 124 frames, 20 steps, guidance 1.0, torch 2.14.1+cu130, torchao 0.18.0, Triton 3.8.0. Setup: - Base is this PR's parent with #17618 and #17613 merged in, and it is repeated (A/A). The base already includes #17613's TN-layout `_int_mm`, so it is faster than the 3.31 s/step #17617 started from. - One Colab session per card. Each arm runs in a fresh process. - s/step is the median over steady denoiser forwards. A `cuda.synchronize` at each forward boundary applies to every arm alike. - s/clip is the `generate` wall time, which includes the encode and the decode. G4 (RTX PRO 6000 Blackwell), streaming forced with the VRAM budget, 2 clips: | placement | arm | s/step | s/clip (clip 1, clip 2) | peak VRAM alloc GiB | frames vs base | |---|---|---:|---|---:|---| | fully streamed (budget 30%, `UNSLOTH_H3_DIT_RESIDENT=0`) | base | 2.056 | 45.9, 43.9 | 6.37 | - | | | base repeat | 2.057 | 45.7, 43.9 | 6.37 | identical | | | this PR | **1.140** | 28.6, 25.6 | 6.38 | identical | | | this PR, switch off | 2.057 | 45.2, 43.9 | 6.37 | identical | | part resident (budget 20%, 27 of 50 blocks resident) | base | 2.049 | 45.7, 43.7 | 16.95 | - | | | base repeat | 2.050 | 45.7, 43.7 | 16.95 | identical | | | this PR | **1.137** | 26.7, 25.5 | 16.95 | identical | | budget 30% (per-request refit holds all 50 blocks) | base | 2.037 | 45.9, 43.5 | 26.60 | - | | | base repeat | 2.039 | 45.2, 43.5 | 26.60 | identical | | | this PR | **1.126** | 27.3, 25.3 | 26.60 | identical | | | this PR, switch off | 2.039 | 45.2, 43.5 | 26.60 | identical | | resident (no budget, #17617's eager install) | this PR | 1.128 | 25.4, 25.3 | 25.32 | identical | | speed default (compiled), budget 30% | base / this PR | 0.891 / 0.891 | 28.9, 19.8 / 22.9, 19.8 | 25.13 / 25.13 | identical | | speed default (compiled), fully streamed | this PR | 0.895 | 28.6, 20.0 | 4.91 | - | L4, 1 clip (it streams on its own: 9 blocks resident at load, 37 of 50 after the per-request refit): | arm | s/step | s/clip | peak VRAM alloc GiB | frames vs base | |---|---:|---:|---:|---| | base, speed off | 12.261 | 298.7 | 20.31 | - | | base repeat | 12.264 | 288.0 | 20.31 | identical | | this PR, speed off | **9.156** | 225.7 | 20.31 | identical | | base, speed default (compiled) | 6.345 | 189.2 | 19.30 | - | | this PR, speed default (compiled) | 6.359 | 176.3 | 19.30 | identical | Host RSS peaks were 96-105 GiB on G4 and 46.4-46.7 GiB on L4. The spread was the same between the base and its repeat, with no shift this PR adds. What runs per denoiser forward (torch.profiler, two steady forwards, per forward): | card, placement | arm | int8 Linear calls | route | int8 GEMM kernel | H2D copy (overlapped) | |---|---|---:|---|---|---| | G4, fully streamed | base | 300 | torchao: eager rotation + quant, cuBLAS `i16832gemm_s8 tn`, float32 epilogue | 451 ms | 344 ms (330 ms) | | G4, fully streamed | this PR | 300, 0 fallbacks | `rotq_i8` + `i8mm_dq_tma` | 431 ms | 344 ms (333 ms) | | L4, streamed | base | 300 | torchao | 2555 ms | 414 ms (394 ms) | | L4, streamed | this PR | 300, 0 fallbacks | `rotq_i8` + cuBLAS TN + torchao's epilogue op for op (the Triton GEMM stays off on sm_89) | 2699 ms | 412 ms (392 ms) | The prefetcher already hides the copies (14 ms exposed per forward on G4, 20 ms on L4), so the streamed tier was compute-bound on torchao's eager Linear. On G4 the base's three largest elementwise kernels (the float32 / bf16 epilogue passes and the bf16 copy, about 490 ms per forward) are gone, and the eager rotation + quant becomes one `rotq_i8` launch per Linear. With them gone, the streamed tier runs at the resident tier's speed. ## Tests - New CPU tests: - both kill switches, and `install_streamed_eager` threading `device` + `exact` through `install`; the streamed and global switches also stop it; - `install_streamed_eager_int8_gemm` engages behind the prefetcher and skips: - a denoiser with no prefetcher; - a compiled denoiser; - a dense denoiser; - an already swapped denoiser; - a call with no device; - it swallows an install failure; - `int8_gemm_live` drops the new key; - the shared Q/K/V quant is exact only when every Linear is; - an AST check that `video.py` calls it in the H3 streamed-uncompiled branch and after the generic offload hooks. - New GPU test: a ConvRot int8 Linear (torchao v1 and v2 configs) is installed while its weight is on the host. After a `swap_tensors` onload (what the prefetcher does) it takes the eager routes, bit-identical to torchao's Linear, with no `rotq_h16`. - `test_diffusion_int8_gemm.py` + `test_diffusion_stream_int8_gemm.py` with CUDA tests on (`-o addopts=`): - G4: 188 passed (base 181). - L4: 187 passed, 1 failed (base 180 passed, 1 failed). The L4 failure, `test_no_compiled_variant_spills_to_local_memory`, fails the same way on the base (Triton 3.8 spills on sm_89). - The commit applies cleanly on #17617 alone, and `test_diffusion_int8_gemm.py` + `test_diffusion_speed.py` pass there (308 passed). ## Not covered - Other video families that stream int8 Linears through the generic placement (Wan, LTX, HunyuanVideo-1.5) are covered by the CPU wiring tests only. No GPU render was run for them. - A100-40 was not run. On sm_80 the route is the same as on L4: the dense rotation kernel plus cuBLAS TN, because the Triton GEMM stays off on sm_8x with Triton 3.8. - Streamers that swap in new Parameters per call (H3-Image's pageable `ModuleListStreamer`) are excluded by the prefetcher gate. Diffusers' own onload without the prefetcher is excluded too. - The shared Q/K/V quant change affects the resident `eager` speed tier with strided attention, which now takes the dense kernel instead of `rotq_h16`. That tier was not timed here. - ROCm, MPS and Windows were not run. The install refuses ROCm and non-CUDA devices.
…e them as stock math under compile (#17795) ## Summary Follow-up to #17618. The MiniMax-H3 row-mod kernels (`video_minimax_h3_rowmod.py`) launched on whatever CUDA device the calling thread had current, not on the operands' card. ## Root cause Triton launches on the current device and its current stream. `_launch_modulate` and `_launch_gated` called the kernels with no device scope; only the one-time probe inside `verdict()` ran under `torch.cuda.device(x.device)`. When a render thread's current device is not the tensors' card (multi-GPU host, a pooled or unpinned thread), the launch goes to the wrong device and stream. On two B200s with `cuda:0` current and the tensors on `cuda:1`, main fails the launch with: ``` ValueError: Pointer argument cannot be accessed from Triton (cpu tensor?) ``` Where the pointer check passes, the kernel would instead run on the wrong stream, unordered against the producer stream. The sibling kernel `video_minimax_h3_qknorm.py` already guards its launch. ## Fix - New `_on_card(t)` helper: returns `torch.cuda.device(index)` when the operand sits on a card other than the current one, and a null context otherwise. Single-card renders skip the switch, which saves about 3 us per launch (the same rule `diffusion_vae_fused._on_card` uses). - `_launch_modulate` launches under `_on_card(x)`, `_launch_gated` under `_on_card(residual)`. ## Audit of other Triton launch sites under `studio/backend/core/inference/` I enumerated every `kernel[grid](...)` call with an AST walk and checked the device scope at each one. Already guarded, no change needed: - `diffusion_convrot_quant.py`, `diffusion_flux2_rope.py`, `diffusion_flux3_qk_rope.py`, `diffusion_grouped_int8_gemm.py`, `diffusion_grouped_int8_triton.py`, `diffusion_int8_fused.py`, `diffusion_int8_gemm.py`, `diffusion_int8_gemv.py`, `diffusion_moss_fused.py`, `diffusion_native_w8a8_rdna.py`, `diffusion_nvfp4_bias.py`, `diffusion_packed_block.py`, `diffusion_qwenimage21_eager.py`, `diffusion_rocm_fused.py`, `diffusion_vae_fused.py`, `diffusion_vae_strips.py`, `video_minimax_h3_qknorm.py`: guarded at the launch. - `diffusion_fp8_dequant.py` (`launch_triton`): its only caller wraps it in `torch.cuda.device(codes.device)`. - `diffusion_nvfp4_act_quant.py`: the `triton_op` is only invoked under `torch.cuda.device(...)`. - `video_wan_fused.py`: every launch runs inside `_fused_forward`, which holds `torch.cuda.device(hidden_states.device)`. - `video_minimax_h3_vae.py`: launches run inside the encoder / decoder forwards, which hold `torch.cuda.device(hidden_states.device)`, and `_int8_linear` switches devices on its own. Missing the guard, not changed here because other open PRs touch these files: - `diffusion_int8_attention_triton.py` (`quantise`, `attend`, `half_attention`): #17789, #17791, #17790. - `diffusion_multigpu.py`, `diffusion_cast_cache.py`, and the `diffusion_int8_gemm.py` / `diffusion_convrot_quant.py` probes: #17790. ## Compile safety (second commit) Two more issues in the same helpers, both reproduced on CPU with torch 2.14.1: - `modulate` / `gated_residual` bump the global `STATS` counters inside the traced region. Dynamo guards on the Python int (`G['STATS']['stock'] == ...`), so compiling either helper recompiled on every call: 5 frames for 5 identical calls (`CompileCounter`). - On a cold verdict cache an eligible call reaches `verdict()`, whose `_LOCK` and timing probe fail `fullgraph=True` with `Unsupported context manager` (Dynamo cannot enter a `lock`). Studio's own `UNSLOTH_H3_IMAGE_COMPILE=1` path never installs the rewrite, so this only bites when an already-patched transformer or the helpers are compiled directly. Fix: under `torch.compiler.is_compiling()` both helpers return the stock expression directly, without touching `STATS` or the verdict cache. After the fix: 1 frame for 5 calls, and cold `fullgraph=True` compiles with the verdict cache still empty. Eager dispatch is unchanged. ## Tests Added to `studio/backend/tests/test_h3_row_mod.py`: - `test_launches_switch_to_the_operand_card` (CPU): patches `torch.cuda.device` / `current_device` and the kernels to record the current device at each launch, with operands on a mocked `cuda:1` while device 0 is current. Both launches must fire on device 1, and device 0 must be current again afterwards. - `test_launches_on_the_current_card_skip_the_switch` (CPU): same-card operands never enter `torch.cuda.device`. - `test_compiling_the_row_ops_does_not_recompile_per_call` (CPU): one compiled frame across 5 calls of each helper, output equal to the reference. - `test_cold_tracing_of_an_eligible_call_compiles_fullgraph` (CPU): CUDA eligibility simulated, empty verdict cache, `fullgraph=True` compiles both helpers and the probe never runs. - `test_kernels_on_a_second_card_while_card_0_is_current` (bf16, fp16; skips with fewer than 2 GPUs): real tensors on `cuda:1` with `torch.cuda.set_device(0)`. The fused output must be bit-equal to `reference_modulate` / `reference_gated_residual`, and `cuda:0` must still be current after the call. Each arm imports its own tree (the test file was copied into a checkout of the merge base). | Run | main (merge base) | this branch | | --- | --- | --- | | CPU, `test_h3_row_mod.py` | 3 failed (device test, `assert 5 == 1` recompiles, `Unsupported context manager`), 6 passed, 5 skipped | 9 passed, 5 skipped | | 2x B200, `test_h3_row_mod.py` (first commit) | 3 failed (CPU device test, plus both two-card tests with `Pointer argument cannot be accessed from Triton`), 9 passed | 12 passed | | 1x B200, `test_h3_row_mod.py` (both commits) | not rerun | 12 passed, 2 skipped (two-card tests) | The existing single-card CUDA tests (bit-exactness of the kernels and the whole row forward) pass on the branch.
Stacked on #17593 (base branch
h3-exact-qk-rmsnorm-rope). Retarget tomainonce that merges.Summary
Two MiniMax-H3 / H3-Image denoiser changes, each with a kill switch.
UNSLOTH_H3_ROW_MOD=0turns it off). The block forward read its six AdaLN chunks per packed row withindex_select, one[seq, hidden]copy each, and ran every op as its own pass. Two Triton kernels now read the AdaLN tables through the row index and keep eager's fp32-op-then-round chain with explicit-rounding PTX. They engage per (device, dtype, hidden) only after a bit-exact check and a timed probe; anything else takes the stock math. The block forward is swapped only when its class forward is the stock body statement for statement. On for every tier unless the opt-in regional compile is on. New modulevideo_minimax_h3_rowmod.py.UNSLOTH_H3_IMAGE_INT8_GEMM_STREAMED=0orUNSLOTH_DIFFUSION_INT8_GEMM_STREAMED=0keeps the stock path). The streamed tier only took the attention levers, so its int8 ConvRot Linears ran the stock rotate + int8 Linear path while their block was on the card. The speed installer now asks the int8 GEMM for its call-time mode on the streamed tier (the mode the generic offloaded denoisers already use): a Linear whose weight is on the card at call time runs the fused-dequant GEMM the resident tiers run; anything else keeps the stock path. This one is tolerance-level, not byte-identical to the stock streamed path.Results
Steady-state 2048 px H3-Image renders, 6 steps, seed-matched noise, measured as per-commit deltas on one integration branch:
Accuracy of the streamed GEMM: LPIPS against a bf16 render is 0.087 to 0.095, in the same band as the resident int8 tier rendered on a different card (0.072 to 0.088). Against the stock streamed path it is 0.08 to 0.15 (different rounding, not a regression).
The L4 "before" includes the per-call weight copy that #17613 removes; with #17613 alone the L4 2048 denoise is about 34 s, and this change takes it to about 14 to 16 s.
Tests
tests/test_h3_row_mod.py: the bit-exact check, the stock-forward match, the probe gating and the kill switch. On GPU: 8 passed on each of an RTX PRO 6000, an L4 and an A100.test_diffusion_minimax_h3_image_speed.py: the streamed tier asks for the call-time mode and the kill switches keep the stock path.test_h3_row_mod.py,test_diffusion_minimax_h3_image_speed.py,test_diffusion_minimax_h3_image.py,test_video_minimax_h3_attn.py,test_h3_qk_rope_exact.py: 187 passed, 58 skipped (CUDA-only cases).Not covered