Repository navigation
Packed rows on sliding-window layers take varlen on the transformers path, plus opt-in FA4 / FA3 for packed training - #13326
Conversation
…sm90, gated and probed
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: 406688e1f8
ℹ️ 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".
| window_size = (window - 1, 0) if window else (-1, 0), | ||
| enable_gqa = True, |
There was a problem hiding this comment.
Avoid requiring varlen GQA in the PyTorch 2.11 probe
When FA3/FA4 is requested under PyTorch 2.11, this probe always passes enable_gqa=True, but that release's varlen_attn has no enable_gqa parameter (the compatibility path in hf_packed_attention.py likewise identifies it as a 2.12 addition). The reference probe therefore raises TypeError, caches a failed verdict, and disables the requested implementation even when it is otherwise supported. Inspect the signature here as well and repeat K/V heads, as the packed-attention path already does for 2.11.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 26350f4: the probe now checks varlen_attn's signature and, on torch 2.11 (no enable_gqa), repeats the K/V heads the same way the packed path does. test_probe_repeats_kv_heads_without_enable_gqa covers both signatures.
|
|
||
| mark_allow_overlength(model) | ||
| _enable_hf_packed_attention() | ||
| _scope_flash_attention_impl(model, trainer) |
There was a problem hiding this comment.
Scope flash attention when reusing a padding-free collator
When a padding-free collator that was already wrapped is reused for another trainer, the early return on _unsloth_padding_free_lengths_wrapped occurs before this call, so the new trainer's train method is never scoped and the requested FA3/FA4 implementation is silently never activated. This also occurs if the environment option is enabled after the collator was initially wrapped and setup is run again. Move the trainer-scoping step ahead of the already-wrapped guard, as enable_sample_packing does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 26350f4: enable_padding_free_metadata now scopes the trainer before the already-wrapped return, matching enable_sample_packing. test_reused_padding_free_collator_still_scopes_the_new_trainer covers it.
… reused padding-free collator
|
@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". |
|
The red here is not from this PR. This run merged onto main at
A rerun replays the same merge commit, so updating the branch onto current main should clear it. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 141dd22b9a
ℹ️ 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".
| impl, major = candidates[0], next(iter(majors)) | ||
| error = _package_error(impl) | ||
| facts = model_facts(model) if model is not None else (False, [], None, None, None, None) | ||
| error = error or _model_gate(impl, major, facts) |
There was a problem hiding this comment.
Try the next auto candidate after a failed probe
When auto runs on Hopper with both FA3 and FA4 installed, this commits to FA3 before applying the model gate and runtime probe. If FA3 imports successfully but its probe fails for the model or installed kernel while FA4 would pass, the error branch disables custom flash attention and returns without trying FA4, so the documented FA3-then-FA4 fallback does not occur. Iterate through the auto candidates until one passes all gates and its probe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1d4517a: auto now walks its candidates in order and moves on when one is not installed, is refused by the model gate, or fails its probe, so on Hopper a failing FA3 falls through to FA4. test_hopper_auto_tries_fa4_when_fa3_fails_its_probe covers it.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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: # unsloth/utils/packing.py
|
@codex review |
1 similar comment
|
@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". |
Follow-up to #13234. Packed / padding-free SFT on the transformers modeling path (
FastModel, zoo-compiled modules) now runs its sliding-window layers on varlen attention too, and packed training can optionally run torch's flash kernels as FA4 (Blackwell) or FA3 (Hopper).Sliding-window layers take varlen
#13234 sent every packed attention call with a sliding window back to the wrapped SDPA, which builds a dense block-causal mask and runs on the masked memory-efficient kernels. That covered every layer of Mistral v0.1 style models (
sliding_window4096), Phi-3-mini-4k (2048), and the sliding layers of Cohere2, Qwen2 withuse_sliding_window, and Gemma 4 text.kv_idx > q_idx - sliding_windowon top of causal, so a key at mostW - 1tokens back is kept. The torch route passeswindow_size = (W - 1, 0)tovarlen_attn, the flash-attn route passes the same, and the xformers route usesAttentionContext.sliding_window = W, whose band is the same.sliding_windowkeyword, else the module'ssliding_window. A window that is zero, negative, a float or a bool keeps the wrapped SDPA, as do softcap and sinks.k > q - W) inside each document, so a mask built with another window, or no window, is still rejected. Its cached verdict is kept per window, so a sliding layer and a full layer in one forward each keep their own.Packed LoRA SFT (r=16, bs 1, alpaca rows packed to
max_length, 4-bit) throughFastModelon a Colab A100 40GB (torch 2.14.1, transformers 5.17.0), main and this PR alternating base / head / head / base, step time = median after 5 warmup steps of 25:Losses match main to bf16 noise (Mistral-7B first steps 1.2724 / 1.3626 / 1.0076 on main, 1.2722 / 1.3628 / 1.0073 here) and peak memory is a little lower (6.29 to 6.07 GB, 3.05 to 3.02 GB).
FA4 / FA3 for packed training (on by default when installed)
torch 2.11+ can swap the kernels behind its flash ops for FA4 (
flash_attn.cute, sm90 / sm100) or FA3 (flash_attn_interface, sm90) withtorch.nn.attention.activate_flash_attention_impl. Newunsloth/utils/flash_impl.pyuses it for packed training when asked:UNSLOTH_FLASH_ATTENTION_IMPL = auto(default)| fa4 | fa3 | off.autouses FA4 on sm100, and FA3 then FA4 on sm90, whichever kernels are installed; with neither installed, or on any other GPU, nothing changes.trainer.train()runs: the impl is process-wide, and FA4's Python launch makes each decode step's attention several times slower, so inference before and after training keeps torch's bundled flash.flash_impl_allows(head_dim, window, device)keeps shapes the active impl lacks (sm100: head dims 136 to 248, and head dim 256 with a window) off torch varlen, on both the Unsloth model path and the transformers path, so they take their existing route instead of an assertion inside the kernel.The gain depends on document length, so
offstays available. On one B200 (torch 2.14.1, FA4 4.0.0b34, Qwen3-4B FastModel, LoRA r=16), alternating off / FA4 runs:On short rows FA4's launch cost (about 1 ms more host time per call) outweighs the kernel saving, peak memory is 0.2 to 0.3 GB higher, and the first activation compiles for about 16 s. FA3 / FA4 on Hopper are gated by the same probe but were not measured here.
Correctness
Packed SFT on tiny random models of each architecture (4 documents per row, sliding windows shrunk to 64 so they bind, real tokenizers), 2 steps each through
FastModelwith padding-free and withpacking=True, then each document's packed logits compared against the same document run alone. "max diff" is the worst document; a row that attends across documents shows about 2.0 here.Gemma 4 with compile on fails to load on main and here alike (unslothai/unsloth-zoo#1690 fixes that). Inference is unchanged: calls without
packed_seq_lengthsnever reach the new code, and FA3 / FA4 are only ever active insidetrainer.train().Tests
tests/test_hf_packed_attention.py: output and dQ / dK / dV parity against transformers'sdpa_attention_forwardover its own banded mask for windows 3, 4 and 128 (documents of 2 to 230 tokens, shorter and longer than the window), MHA and GQA, on the torch, torch 2.11 (repeated K/V) and xformers routes; masks with the window off by one or missing are rejected; per-window verdicts; a tinyMistralForCausalLMend to end with window None and 4 (both layers take varlen, logits and grads match).tests/utils/test_flash_impl.py: the env parsing (off by default), every gate, the probe, train-only scoping and restore, per-call shape refusal on both paths (including the window reaching the check), compile without graph breaks, and on a real FA4 install: varlen parity against bundled flash, the sm100 head dim 256 window refusal, and the dispatcher really leaving FA4 after restore. With FA4 installed on B200: 50 passed.