Repository navigation
Gemma-4 attention kernels inside compiled blocks: 1.4-2.6x faster gemma-4-12b training - #17817
Merged
Merged
Conversation
…ng routers The hook read the plain SDPA from the top router's module. unsloth's head_dim 512 router is installed at load, before block compile, and has no _ORIG_SDPA, so the hook never installed: sliding layers within the window ran masked SDPA instead of is_causal flash. Fall back to unsloth_zoo's gemma4_flash_sliding module.
…compiled blocks Inside a compiled block the head_dim 512 router cannot scan the 4D mask (host sync), so every global layer fell back to masked SDPA, which repeats the single kv head 16 times and computes all S x S scores. Block compile now scans the mask eagerly before the block (a band as wide as the sequence, cached on the mask) and marks a plain causal mask; the compiled router then runs the kernel over dense causal intervals.
…piled blocks Past the 1024 window the block routed sliding layers (head_dim 256) to masked SDPA: dense S x S scores plus repeated kv heads (G4 seq 8192: 75 ms fwd+bwd per layer). The interval kernel reads only each row's window (3.9 ms). The block marks a plain band eagerly; the kernel self-checks per head_dim (64 / 128 / 256) and dtype. UNSLOTH_BLOCK_SLIDING_KERNEL=0 keeps masked SDPA.
…ould idle One kv head (Gemma-4 global layers) over a short sequence ran the dK / dV pass on 64 programs. Split the G query heads into groups with fp32 partials summed afterwards, until kv blocks x kv heads x splits fill the GPU twice (A100 hd512 seq 2048 fwd+bwd 11.2 -> 7.5 ms; G4 seq 8192 49.1 -> 40.1 ms). UNSLOTH_LH_DKDV_SPLIT=0 keeps one pass.
The router is CUDA only (torch.version.hip disables it), as gfx1151 CI showed; the older router tests share the sm80 gate and fail there the same way at main.
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. |
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@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". |
danielhanchen
added a commit
that referenced
this pull request
Nov 15, 2026
…ource lint red on main) (#17838) ## Summary `Source lint` has been red on `main` since #17817 merged (also seen on the staging run of #17835): ``` No new risky loader call sites: Failed 1 risky loader call site(s) not in the baseline: unsloth/models/_block_compile.py:1364 [dynamic-import] import_module ``` `_band_kernel_check` loads the band-attention kernel module through `importlib.import_module(_LH_MODULE)`. The risky-loader lint flags a dynamic import whose module name is not written at the call site. Here the name is the constant `"unsloth.kernels.large_head_attention"`, so nothing is actually dynamic. ## Change `from unsloth.kernels import large_head_attention as lh` replaces the `importlib` call. It stays in the same place, so the module is still loaded lazily, only for a layer whose sliding-window head dim qualifies, and still inside the `try/except` that falls back to the stock attention path. No baseline entry is needed. `sys.modules[_LH_MODULE]` lookups elsewhere are unchanged. ## Verification On a clean export of the tree: | | `scripts/lint_risky_loaders.py` | |---|---| | main | 1 call site not in the baseline (`_block_compile.py:1364`) | | this branch | ok: 117 risky loader call sites, all recorded | `tests/test_block_compile.py tests/test_large_head_attention.py tests/security/test_lint_risky_loaders.py`: 120 passed, 68 skipped (CUDA-only cases).
Stanley00
pushed a commit
to stanley-fork/unsloth
that referenced
this pull request
Nov 15, 2026
…router never engages (unslothai#17851) `tests/test_large_head_attention.py` fails on AMD GPUs even though the kernel behaves as designed there. This is a test-only fix. ## Cause The kernel tests are gated on `_SM80 = has_real_cuda() and capability[0] >= 8`. A ROCm device reports its gfx version as the capability (gfx1151 reports `(11, 5)`), so the gate opens on AMD. But `patch_large_head_attention` and the router refuse ROCm (`torch.version.hip`), so the kernel never engages there and the tests fail. `_SM80` now also requires `torch.version.hip is None`, which matches the router's own gate. ## Evidence (AMD gfx1151 CI, base vs head in the same job) | | main | this PR | |---|---|---| | Linux / ROCm 7.13 | 10 failures in the file | 0 failures, 17 skipped | | Windows 11 / ROCm 7.14 | `test_self_check_per_head_dim` (added in unslothai#17817) and the same set fail | same gate; not re-run, because the CI patch step is Linux-only | Nothing changes on NVIDIA. Gemma-4 training on gfx1151 is identical before and after unslothai#17817.
danielhanchen
added a commit
that referenced
this pull request
Nov 16, 2026
… _launch helper (#17891) ## Summary Two kernel lint tests in `Repo tests (CPU, rest)` have failed on `main` since #17817 added `unsloth/kernels/large_head_attention.py` (Gemma-4 large-head attention kernels): ``` tests/test_triton_constexpr_comments.py::test_every_constexpr_line_has_a_comment E tl.constexpr parameters without a comment: E unsloth/kernels/large_head_attention.py:158 _lh_bwd_pre.HEAD_DIM ... (23 parameters) tests/test_triton_fp_fusion.py::test_every_launch_requests_fp_fusion E Triton launches without enable_fp_fusion: ['large_head_attention.py:702:kernel', 'large_head_attention.py:696:kernel.fn'] ``` The forward kernel follows the constexpr convention, but the backward, TMA and `_tma_tile` signatures do not. On fp fusion the kernels are fine. Every launch goes through a `_launch(kernel, grid, tile, *args, **kwargs)` helper, and all three callers pass `enable_fp_fusion = True`. The lint only sees the `kernel[...]` / `kernel.fn[...]` subscripts inside the helper. That is the same shape as `layernorm.py`'s and `rms_layernorm.py`'s helpers, which the test already handles. ## Changes - `unsloth/kernels/large_head_attention.py`: a short comment on each of the 23 constexpr parameters (head dim, rows per program or step, which gradient a pass stores). `_tma_tile` gets one parameter per line, so `ROWS` and `HALF` carry their own comments. Comments only, no code change. - `tests/test_triton_fp_fusion.py`: register `large_head_attention.py`'s `_launch` in `_LAUNCH_HELPERS`, and its `kernel` / `kernel.fn` subscripts in `_NOT_LAUNCHES`, as for the two layernorm files. Each `_launch(...)` call is now checked for `enable_fp_fusion` directly. ## Verification - `tests/test_triton_constexpr_comments.py tests/test_triton_fp_fusion.py tests/test_large_head_attention.py tests/test_block_compile.py`: 94 passed, 102 skipped (CUDA-only). On `main`, the two lint tests fail. - The fp fusion lint still catches a missing flag. Deleting `enable_fp_fusion = True` from the forward `_launch` call gives `Triton launches without enable_fp_fusion: ['large_head_attention.py:787:_launch']`.
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Nov 17, 2026
… 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
gemma-4-12b training spent about half of its GPU time in attention. Inside a compiled block, every Gemma-4 layer (sliding hd256 and global hd512) fell back to masked memory-efficient SDPA: it computes all S x S scores with a dense bias and repeats the key / value heads (16x on the global layers). Block compile removes launch gaps but leaves that cost in place, which is why #10744 alone gave this model only 1.05-1.11x.
Changes
_block_compile.py): run the existing interval kernel, which reads only each row's window, instead of masked SDPA. Within the window, flash withis_causalis used as before. Kill switch:UNSLOTH_BLOCK_SLIDING_KERNEL=0._block_compile.py): block compile now marks a plain causal mask before the block, so the compiled head_dim 512 kernel takes these layers. It reads the single KV head in place.large_head_attention.py): it ran on only 64 programs. It is now split over query-head groups when SMs would sit idle (A100: 1.5x on that layer). Kill switch:UNSLOTH_LH_DKDV_SPLIT=0.Results
gemma-4-12b-it with random weights from the real config, FastModel, batch 1, GC
"unsloth", adamw_8bit, transformers 5.22.1. Runs were ordered base, head, head, base. Repeated runs of the same arm differed by 0-2.5%.Attention alone, forward + backward per layer, in ms (masked SDPA on main -> this PR):
Against an fp64 reference, the kernel's error is equal to or lower than masked SDPA's, at scale 1.0 and 1/sqrt(d).
Correctness
tests/test_block_compile.py(router hook beneath a wrapper, global-layer causal verdict, long-band routing, kill switch): 5 fail on main and pass here.Not covered