Repository navigation
Add a Triton head_dim 512 attention kernel for Gemma-4 global layers - #13869
Conversation
Codex Review SummaryThis 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: a94fc26b0e
ℹ️ 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 kwargs.get("position_bias", None) is None | ||
| and kwargs.get("softcap", None) is None | ||
| and not kwargs.get("output_attentions", False) |
There was a problem hiding this comment.
Defer paged-cache calls to the original SDPA
When Transformers passes a PagedAttentionCache through cache, a head-dim-512 prefill with matching query/key lengths satisfies this condition and returns from the Triton path without calling the original SDPA implementation. The original implementation performs cache.update(...) before attention; skipping it leaves the prompt absent from the cache, so subsequent single-token decoding attends to an incomplete history. Exclude calls with a non-None cache (or reproduce the cache update) before routing.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The router only replaces ALL_ATTENTION_FUNCTIONS["sdpa"]. In transformers 5.x, paged / continuous batching calls are dispatched through separate keys ("paged|sdpa": sdpa_attention_paged_forward, plus paged|eager and paged|flash_attention_*, modeling_utils.py ~5082), and continuous batching always switches the model to paged|. The cache.update happens inside sdpa_attention_paged_forward, not in the plain sdpa_attention_forward this router wraps, so paged calls never reach this path.
| def _load(): | ||
| spec = importlib.util.spec_from_file_location("_unsloth_large_head_attention", _PATH) | ||
| module = importlib.util.module_from_spec(spec) | ||
| spec.loader.exec_module(module) |
There was a problem hiding this comment.
Avoid re-executing the custom-op module in this test
When the startup import in tests/conftest.py succeeds, importing unsloth already reaches models/vision.py and executes this kernel module, registering unsloth::large_head_attention_fwd and unsloth::large_head_attention_bwd. Executing the same file again under this private module name attempts to register those dispatcher names a second time and raises during test collection on Torch versions with torch.library.custom_op; load the existing module or isolate/mock registration instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
torch.library.custom_op allows registering the same qualname again: it goes through get_library_allowing_overwrite, which drops the previous library for that qualname first (torch/_library/custom_ops.py). Loading the module twice, including register_fake and register_autograd, works on torch 2.6 and 2.13, and the earlier op object still runs forward and backward. On GPU this file collects and passes with unsloth already imported by conftest (36 passed).
…utside inference mode [skip ci]
…or a math SDPA selection
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c2fb9f51a1
ℹ️ 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".
| if hasattr(torch.compiler, "assume_constant_result"): | ||
| _math_sdpa_requested = torch.compiler.assume_constant_result(_math_sdpa_requested) |
There was a problem hiding this comment.
Preserve backend-policy guards in compiled graphs
When a router is compiled under the default SDPA policy and the compiled callable is later invoked inside sdpa_kernel([SDPBackend.MATH]), assume_constant_result has already folded _math_sdpa_requested() to False without guarding the mutable backend state, so the graph continues calling the Triton custom op and ignores the explicit math selection. Fresh evidence beyond the earlier eager-path fix is this new assume_constant_result decoration; the policy must be re-evaluated or guarded when compiled calls can execute under a different SDPA context.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This matches how native SDPA behaves under torch.compile. Dynamo installs no guard on the sdp backend flags or the priority order, and compiled SDPA settles its backend at trace time: a function compiled with F.scaled_dot_product_attention under the default policy still runs inside a later sdpa_kernel([SDPBackend.EFFICIENT_ATTENTION]) on CPU, where eager raises "No viable backend" (checked on torch 2.13). So the compiled router keeps the policy that applied at trace time, as plain SDPA does. Eager calls still re-evaluate _math_sdpa_requested() on every call.
|
Codex Review: Didn't find any major issues. More of your lovely PRs 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". |
[skip ci]
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
|
pre-commit.ci run |
… kernel lazily (its autotuners need a driver)
…lls back to SDPA, no per-call mask sync (unslothai#13977) Follow-up to unslothai#13869 for three problems on the default-on path. **T4 step time.** On a Colab T4, fp16 Gemma-4 E2B vision SFT (12 steps, ABBA) ran 1.8% to 3.5% slower per step with unslothai#13869 than with its parent or with `UNSLOTH_HD512_ATTENTION=0`. Yet the kernel never ran there: its self check fails on sm75, and fp16 Gemma-4 text attention reaches SDPA directly through the float32 path. The kernel was only timed faster on sm80+. Pre-Ampere GPUs now skip the self check entirely (no compile, no autotune), and the router is not installed when every device and dtype of the model failed its self check. On the same T4 job, this change is level with the kernel switched off (4300 / 4307 ms against 4403 / 4379 ms), with identical peak memory. **Autotune memory.** Triton's default autotune benchmarker allocates a 256 MB L2 flush buffer. With head_dim 512 this happens in the load-time self check, and again on the first forward and first backward of every new GQA group size, because the autotune key is `(HEAD_DIM, G)` and the self check only covers G = 2. A model that fit on the previous SDPA path could therefore OOM at load or on its first training step. Under a 128 MB process cap, SDPA succeeds on a G = 8 call, while the kernel failed allocating 256 MB. The self check also added 258 MB of peak allocation. - The three autotuned kernels now time configs in place with CUDA events (warmup, estimate, about 10 ms of reps) and allocate nothing extra. Every config only rewrites its own outputs, so rerunning is safe. This is set as the autotuner's `do_bench` attribute, which works on Triton 3.2 (where `autotune()` does not forward `do_bench=`) through 3.7. `OutOfResources` handling for configs that do not fit is unchanged. - An OOM in the self check now disables the kernel for that device and dtype (SDPA, as before) instead of failing the load. An OOM in the forward kernel falls back to SDPA for that call. - Self check peak: 270,408,704 to 8,917,504 bytes. The G = 8 call under the 128 MB cap now runs forward and backward on the kernel. **Mask scan sync.** The router scanned the mask (one host sync) before looking at the self-check verdict, and inference-mode masks, which cannot cache the verdict, were rescanned on every layer. Left-padded generation prefill is then rejected anyway. Masks are now scanned only when the result can be used: not for inference-mode masks (they go straight to the previous SDPA, unchanged) and not after a failed self check. Training masks keep the one-scan-per-step cache. **Tests:** 7 new tests in `tests/test_large_head_attention.py`: benchmarker installed, self-check OOM, fresh autotune adds under 32 MB, router OOM fallback, no scan for inference masks or after a failed check, no compile before sm80, and no install when every self check fails. The first 5 fail on the current main. Router and self-check GPU tests now need sm80+. The full file plus the formatter and encoding tests give 79 passed, 2 skipped. **Not covered:** a Triton 3.2 run (checked against its source only), sm80+ step time, AMD (the route stays off on ROCm), and a speed comparison of the configs picked by in-place timing versus flush-based timing.
…lf check, forced float32 skip (unslothai#14188) ## Summary Follow-ups for the head-dim 512 attention kernel (unslothai#13869) and one test gap from unslothai#13888. The default path is unchanged except where noted. 1. **Kill switch read under compile.** `_enabled()` was an `lru_cache`. Dynamo warns when it traces through that wrapper, and it re-reads the environment there, so compiled code could disagree with eager after the variable changed at runtime. It now reads the value once into a module-level holder that both paths share. `_enabled.cache_clear()` still resets it. 2. **4-bit-only GPU shards skipped the self check.** At load, the kernel self-checks every (device, dtype) holding fp16 / bf16 weights. A GPU that holds only bitsandbytes 4-bit weights (uint8 storage, for example with CPU-offloaded embeddings or a device-mapped shard) produced no target, so the kernel stayed off there. It now uses the 4-bit weights' compute dtype from `quant_state`. 3. **No wasted fp16 self check under forced float32.** Models stamped `_unsloth_forced_float32` (zoo's Gemma-4 float32 path) run attention in float32 on plain SDPA and never reach this router, so the patch now returns before the fp16 self check and autotune at load. 4. **Test only:** `test_rms_layernorm_backward_leaves_shared_grad_alone` now sets `_SAVE_OUTPUT` and asserts the backward-from-output path runs. Before, its `save_output = True` cases never exercised that path. ## Tests (GPU) - `tests/test_large_head_attention.py`: 3 new tests (compiled vs eager kill switch, 4-bit-only shard self check, forced float32 skip). They fail on main and pass here. - With `tests/test_norm_backward_grad_alias.py`: 52 passed. Not run here: a real Gemma-4 load for items 2 and 3, or any timing. The kernel itself is unchanged. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…on mask-scan OOM (unslothai#14691) Two edge cases in the head_dim 512 attention router from unslothai#13869 (`unsloth/kernels/large_head_attention.py`). The common paths (no mask, a causal / packed / padded mask without an explicit `is_causal`) take the same kernel route as before; the change adds one boolean check per call (about 0.04 us). **1. Explicit `is_causal=True` next to a mask** transformers 4.57.6 `sdpa_attention_forward` keeps an explicit `is_causal` beside the mask, and SDPA then applies both. The router built its intervals from the mask alone and dropped the causal part, so a call carrying a non-causal mask (all-allowed, or a 4D padding mask) plus `is_causal=True` let early tokens attend to later ones. transformers 5.x drops `is_causal` whenever a mask is present, so the two versions disagree on what that pairing means. The router now hands it to the wrapped function, which keeps each version's own meaning. No transformers model passes `is_causal` into the attention interface, and Unsloth's own callers that pass `is_causal=True` drop the mask first, so this only affects model code that passes both. **2. OOM in the mask scan** `intervals_from_mask` allocates int32 row chunks (512 MiB at mask batch 8, length 16384) before the kernel's own OOM guard, so an OOM there escaped instead of falling back to SDPA. It now falls back like an OOM in the kernel. The strided-view int32 bound this PR first carried landed on main in unslothai#14790 (`_row_span`, which bounds only the int32 row offset since batch and head offsets are int64); main's version is kept and the duplicate helper and tests were dropped in the merge. **Tests** (`tests/test_large_head_attention.py`, both fail on main and pass here): - `test_router_leaves_an_explicit_is_causal_beside_a_mask_to_sdpa` - `test_router_falls_back_to_sdpa_on_mask_scan_oom` **Verification** (B200, torch 2.13, transformers 5.19): - Test file, main source vs this branch with the branch's tests: 2 FIXED (fail on main, pass here), 60 unchanged passes, 0 failures on the branch. - Mask plus `is_causal=True` probe with the 4.57.6 `sdpa_attention_forward` semantics (repeat_kv, then SDPA with both): main returns 6.81 for row 3 where SDPA gives 2.03 (it reads future tokens, max abs diff 10.19); this branch matches SDPA exactly (max abs diff 0.0). - Causal mask without `is_causal`: one kernel call on both main and this branch, max diff 0 vs SDPA. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Gemma-4 global attention layers use head_dim 512. FlashAttention-2 and the flash / cuDNN SDPA backends stop at 256, so these layers run on SDPA's memory-efficient or math kernels, and padded or packed batches also materialise a dense 4D mask for them.
This adds
unsloth/kernels/large_head_attention.py, a Triton flash attention forward and backward for head_dim 512, and routes transformers'sdpaattention through it when a call qualifies. It reads GQA kv heads in place (the dK/dV pass loops over each kv head's query heads, so there are no atomics and no repeated K/V), and takes any mask whose allowed keys per query row form one interval with non-decreasing ends: causal, bidirectional, packed documents, right padding and sliding windows. Whole kv blocks outside a row block's interval are skipped, which is where packed batches gain the most. Masks are converted once per step with one host sync and the result is cached on the mask tensor for every layer.The route is installed by
FastModel.from_pretrainedonly for models with head_dim 512 layers. It engages for CUDA fp16 / bf16, dropout 0, no softcap, equal query and key lengths, and after a one time forward and backward self check against SDPA on that device and dtype; everything else (left padding, per-head masks, decode with a cache, ROCm, fp32) goes to the previoussdpafunction unchanged. Under torch.compile the maskless case runs the kernel as an opaque custom op with no graph break; masked calls keep SDPA.UNSLOTH_HD512_ATTENTION=0disables it. The tiling follows axolotl's flash_attn_d512 kernel (Apache-2.0).Accuracy: against an fp64 reference over 1344 cases (S from 2 to 700, GQA 1 to 8, seven mask kinds, fp16 and bf16) on B200 and A100, the mean error of out / dQ / dK / dV is at or below SDPA's memory-efficient backend at the same dtype (median ratios 0.99 / 0.84 / 0.77 / 0.81). On q, k, v captured from Gemma-4 global layers the kernel is again at or below SDPA's error. compute-sanitizer memcheck is clean on every config. A 50-step LoRA run on a tiny Gemma-4 matches the SDPA path within the SDPA path's own run-to-run noise, and the kernel path is deterministic.
Speed, attention forward plus backward on an A100 at head_dim 512: 1.4x to 2.1x on causal rows (S 1024 to 8192) and 1.8x to 18x on packed rows (more documents, larger gain), with 3x to 4.9x lower peak memory. The packed numbers are against SDPA with a dense 4D mask. Main's packed router (#13384) already sends packed rows that carry
packed_seq_lengths(the usual packing / padding-free SFT flow) to SDPA's efficient kernel over cu_seqlens, and that route is kept: the head_dim 512 wrapper sits beneath it. So in standard training the gains apply to dense causal and right-padded batches. On a B200 the range is 1.09x to 1.80x causal and 1.5x to 19x packed; one case is slower (8 query heads on 1 kv head, S 1024, two packed documents: 0.73x), where the per-call mask scan dominates in the microbenchmark (in training it is shared across all global layers). In fp16, Unsloth's Gemma-4 path computes attention in float32 and does not reach this kernel, so the gain applies to bf16 training.Not covered: T4 and L4 (the larger block configs do not fit T4 shared memory; the self check should fall back to SDPA there, untested), an end to end timing on a real Gemma-4 checkpoint, older torch versions and ROCm (the route stays off on ROCm).