Repository navigation
Studio H3 / H3-Image: bit-exact fused q/k RMSNorm + RoPE, on for every tier - #17593
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.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review Summary: ❌ FailedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 22dabe562b
ℹ️ 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".
| scale = 10.0 ** torch.randint(-3, 4, (1, seq, heads, 1), generator = g).float() | ||
| base.mul_(scale).add_(torch.randn(1, seq, heads, 1, generator = g) * scale * 0.5) | ||
| base[..., :3] *= 40 | ||
| if strided: | ||
| qkv = qkv.to(dtype).to(device) |
There was a problem hiding this comment.
Keep the fp16 validation probes within the finite range
For torch.float16, multiplying the first three elements by 40 after applying row scales up to 1e3 produces values beyond fp16's maximum of 65504. Casting these probes creates infinities, and RMSNorm then produces NaNs from inf * 0. Since _check uses torch.equal(got, ref), which rejects matching NaNs, both forms fail validation even when they reproduce the reference correctly. That negative verdict is cached, disabling the optimization for subsequent finite fp16 inputs, including when a form is explicitly forced. Bound the finite probes to the target dtype's range, or validate nonfinite cases separately with an appropriate comparison.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 48e9428. The probe inputs are clamped to finfo(dtype).max / 8 before the cast, so fp16 probes stay finite (bf16 probes are unchanged). Added test_probe_inputs_stay_finite_in_the_target_dtype, which fails on the previous commit for fp16 and passes now.
…jected on NaN [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
…n the streamed tier (#17618) Stacked on #17593 (base branch `h3-exact-qk-rmsnorm-rope`). Retarget to `main` once that merges. ## Summary Two MiniMax-H3 / H3-Image denoiser changes, each with a kill switch. 1. **Per-row AdaLN modulation and gated residual without gathers, bit-exact** (`UNSLOTH_H3_ROW_MOD=0` turns it off). 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 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 module `video_minimax_h3_rowmod.py`. 2. **Int8 GEMM on the H3-Image streamed tier** (`UNSLOTH_H3_IMAGE_INT8_GEMM_STREAMED=0` or `UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED=0` keeps 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: | change | card | before | after | output | |---|---|---|---|---| | row modulation | RTX PRO 6000, int8 resident, denoise | 2.085 s | 2.01 s | byte-identical | | row modulation | same, elementwise / copy kernels per render | 112 / 30 ms | 2 / 2 ms | | | streamed int8 GEMM | L4, int8 streamed, s/img (denoise) | about 85 s (73 s) | 22.95 to 24.4 s (16.1 to 16.2 s) | see below | | streamed int8 GEMM | L4, 2720x1536 edit, first render | 184 to 194 s | 56 to 58 s | see below | 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 - New `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. - CPU, this branch: `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 - MiniMax-H3 video was not rendered with real weights with the row modulation on (the kernels are shared and checked per device). - The streamed GEMM was timed on L4 only; T4 and A100 40GB streamed tiers were not run. - ROCm and Apple are untouched (both kernels are CUDA only and fall back to the stock math).
… q/k RoPE int64 offsets, Gemma-4 band route int32 guard (unslothai#18141) Three fixes from a re-check of recent kernel PRs. 1. **Cold probes ask about capture on the operand's card (unslothai#17795, unslothai#17593, unslothai#17637).** The cold `verdict()` of the MiniMax-H3 row-mod kernel (`video_minimax_h3_rowmod.py`), the H3 q/k norm (`video_minimax_h3_qknorm.py`) and the FLUX.3 q/k RoPE (`diffusion_flux3_qk_rope.py`) read `torch.cuda.is_current_stream_capturing()` on the current card before switching to the operand's card. With another card current, the timing / equality probe could start inside a CUDA graph capture on the operand's card, then cache a failure or raise. The query now runs under `torch.cuda.device(x.device)`, with the probe. 2. **MOSS-Image fused q/k norm + RoPE: int64 row offsets (unslothai#17099).** The kernel multiplied the token index by the fused-QKV row stride in int32, which wraps past 2**31 (a 9216-wide row past about 233k tokens). The row index is now int64 before any stride product; output bits are unchanged. 3. **Block compile: the Gemma-4 sliding band route checks the interval kernel's int32 limit (unslothai#17817, unslothai#17860).** The long-band route in `unsloth/models/_block_compile.py` called `large_head_attention` directly and skipped the int32 span check the large-head router applies on its own path (`_shapes_qualify`), so a long enough sliding layer reached the int32-addressed kernel. The band route now keeps masked SDPA past that limit. ### GPU results, base (main 62d66cb) vs this branch Capture probes, Kaggle 2x T4 (sm75), torch 2.11.0+cu130: cuda:0 current, a `torch.cuda.graph` capture active on cuda:1, operand on cuda:1, cold call, probe runs counted. | probe | base | this branch | |---|---|---| | H3 row-mod `verdict` | probe ran inside the capture and cached `{exact: False, use: False}`; the next eager call still returns the cached failure | returns None, no probe, nothing cached; the next eager call computes `{exact: True, use: True}` | | H3 q/k norm `verdict` | probe ran inside the capture and the call raised `Cannot copy between CPU and CUDA tensors during CUDA graph capture` | returns None, no probe; the next eager call computes the real verdict | | FLUX.3 q/k RoPE `verdict` | probe ran inside the capture and cached a RuntimeError failure for cuda:1 for the process | returns None, nothing cached; the next eager call runs the real check | The captured graph itself replayed correctly in both arms; the defect is the probe running inside the capture and the cached failure or raise. MOSS and band route, L4 (sm89), Colab, torch 2.12.1+cu130, Triton 3.7.1: | fix | check | base | this branch | |---|---|---|---| | MOSS int64 offsets | fused kernel engaged (4 launches per arm); 1x4096x24, 2x1029x24, 1x16384x24, 1x37x4 | q / k / v hashes | identical to base; v equal to eager, q / k within 0.03125 of eager in both arms | | band route guard | S600 / w512 / hd256, S2048 / w512 / hd128, S4096 / w1024 / hd256 (kernel route), S256 / w512 (causal SDPA) | routes and output hashes | same routes, identical hashes; max error vs fp32 about 0.008 | ### Tests - `studio/backend/tests/test_diffusion_capture_probe_device.py` and `test_h3_row_mod.py::test_cold_verdict_asks_about_capture_on_the_operand_card`: on the T4 pair base 3 failed / 14 passed, this branch 17 passed (two-card tests included). - `studio/backend/tests/test_diffusion_moss_qk_rope_offsets.py` lowers the kernel to TTIR and rejects i32 row-stride products: fails on main; on the L4 base 1 failed / 8 passed, this branch 9 passed, and the existing MOSS fused GPU tests pass in both arms. - `tests/test_block_compile.py::test_gemma4_long_band_past_int32_keeps_the_plain_route`: fails on main; on the L4 base 1 failed / 83 passed, this branch 84 passed (4 skips, the same version gates in both arms). - CPU (torch 2.14.1) on this branch: 13 passed / 5 skipped in the probe and MOSS files, 74 passed / 14 skipped in `test_block_compile.py`. ### Not covered - The overflow sizes themselves (over 233k MOSS tokens, a band span past 2**31) cannot be allocated; the TTIR and CPU route tests are the evidence there. - A full MOSS-Image render with real weights; the op and its unit tests ran. - On fp16 / sm75 the FLUX.3 q/k RoPE check reports a real bit mismatch, so its fused path stays off on T4 regardless of this change; the capture fix is shown by the probe count, not by the fused path engaging there. - sm80 and sm120 cards; the capture probes ran on T4 only, MOSS and the band route on L4 only. - The GPU runs used main 62d66cb; the branch was then rebased onto main 142c398 and only the CPU tests were rerun there.
Summary
The fused q/k RMSNorm + RoPE kernel that MiniMax-H3 and MiniMax-H3-Image use is now bit-identical to the stock eager ops (
F.rms_normthen the rotary rotation), so it is on by default for every H3-Image tier, including the streamed one where it was off because it drifted.Measured on 2048 px H3-Image renders: denoise is 7.7 to 8.4% faster than the stock path on an A100 80GB (INT8, resident) and 5.7 to 7.2% faster on an L4 (FP8, streamed), with final latents byte-identical to stock on every prompt.
Why the old kernel drifted
Three places rounded differently from eager:
tl.sum, which adds in a different order from torch's CUDA_fused_rms_norm, sorstddiffered in the last bit on some rows. The kernel now sums in the same order as torch'slayer_norm_kernel.cu.fma.rn.bf16), skipping the rounding eager does after each product. It now usesmul.rn.f32/add.rn.f32, which cannot be merged.tl.sum; it is now explicit adds.Reverting any one of these makes the exactness checks fail again.
Safety
F.rms_normand only replaces the rotation) is checked bit for bit against eager on the device before it is used, and only on inputs that compile to the variant that was checked. Anything else falls back to the next form, then to stock.UNSLOTH_H3_IMAGE_QK_ROPE=0/UNSLOTH_H3_QK_ROPE=0turn it off;UNSLOTH_H3_QK_ROPE_MODE=fused|ropeforces one form, and only if it passes the check.Results
Kernel oracle (bit-equality with eager; bf16 and fp16, head dims 64 / 128 / 256, strided and contiguous, special values):
Kernel time at the H3-Image shape (56 heads, head dim 128, rotary dim 96, bf16, 4429 tokens):
H3-Image, 2048 px, 6 steps, three cases (two text-to-image prompts and one edit), base and head on one VM per card, with a repeated base arm as the A/A check. Denoise seconds:
On the A100 resident tier main already ran the old fused kernel. It was as fast as this PR (within 0.04 s), but its images differed from stock (LPIPS 0.04 to 0.48); this PR's are byte-identical. Peak VRAM is unchanged on both cards.
Tests
tests/test_h3_qk_rope_exact.py.test_video_minimax_h3_attn.py: the CUDA kernel test now requires exact equality with eager.test_diffusion_minimax_h3_image_speed.py: the op is on for every tier.test_h3_ref_encode.py::test_chunked_reference_matches_stock_bit_for_bit[22,34,39,56], which fails the same way on main.Not covered