Repository navigation
Run packed rows on the transformers modeling path through varlen flash attention - #13234
Conversation
…ositional and softcapped calls
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dff6b7a749
ℹ️ 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".
| pass | ||
| setattr(_sdpa_packed_varlen, _FLAG, True) | ||
| # Direct assignment: register() does not update the mapping layers read. | ||
| ALL_ATTENTION_FUNCTIONS["sdpa"] = _sdpa_packed_varlen |
There was a problem hiding this comment.
Register the wrapper in the class-wide attention mapping
On supported Transformers 5 releases, direct assignment updates only this AttentionInterface instance's local mapping. Models that create their own interface instance, such as Doge, continue reading the unchanged class-wide sdpa entry and therefore silently bypass this wrapper for every packed forward. The existing patch_flex_attention_kernel_options implementation explicitly performs both assignment and type(ALL_ATTENTION_FUNCTIONS).register(...) for this reason; this installer needs the same class-wide registration.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one as is. The class-wide entry is the stock sdpa, while the instance entry carries the unsloth_zoo routers; registering this wrapper there would route models that build their own interface (Doge) through those routers as well, which they skip today. Those models only miss the speedup and keep their current, correct path.
…and keep the overflow guard and counters out of grad mode and tracing
… and hand a refusing torch varlen back to sdpa
|
@codex security review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
|
Packed and padding-free SFT through FastModel now runs attention on the varlen kernel, and the loss curve stays on main's. On one B200 (LoRA r=16, 20 steps, rows of 8 x 4096 tokens packed into one sequence) every attention call took the fast path with zero fallbacks:
The rows here are much longer than the ones in the description, so the packed gap is larger. Per-step loss stayed within 0.0012 of main for packing and 0.0031 for padding-free.
|
…t has no enable_gqa
|
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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 52f1ee98eb
ℹ️ 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 ( | ||
| bsz == 1 | ||
| and q_len > 0 | ||
| and query.is_cuda |
There was a problem hiding this comment.
Preserve deterministic mode by falling back to SDPA
When torch.use_deterministic_algorithms(True) is enabled, this eligibility block still selects torch varlen or the flash-attn/xFormers dispatch path. The sibling attention_dispatch._torch_varlen_takes explicitly rejects varlen in deterministic mode, but this new wrapper bypasses that safeguard, so packed FastModel training can silently lose the reproducibility requested by the caller. Fall back to the wrapped SDPA whenever deterministic algorithms are enabled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fd9c2d5: deterministic mode now sends the call back to the wrapped sdpa before any varlen kernel is considered, so neither torch varlen nor the xformers / flash-attn dispatch runs. A test enables deterministic algorithms and checks only the wrapped sdpa was called, then that varlen runs again once it is off.
| torch_varlen = _torch_varlen(query.device) | ||
| if torch_varlen is not None and _sdpa_picks_math(query, key): | ||
| torch_varlen = None | ||
| backend = select_attention_backend(use_varlen = True) |
There was a problem hiding this comment.
Fall back entirely when SDPA selects the math backend
On installations with flash-attn or xFormers, a math-first sdpa_kernel context only clears torch_varlen here; the following select_attention_backend(use_varlen=True) still selects the external varlen backend and runs it. Consequently, callers explicitly forcing the SDPA math implementation still receive flash attention for packed rows, contrary to the documented purpose of the SDPA context manager and this helper's own stated intent. When _sdpa_picks_math is true, return through the wrapped SDPA rather than merely disabling the torch route.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fd9c2d5: a disabled flash SDPA backend or a math-first priority now returns through the wrapped sdpa, so the xformers / flash-attn dispatch is skipped too, not only torch varlen. The test covers sdpa_kernel(MATH), a flash-less backend list and a math-first priority with the dispatch spied on, plus the same call taking varlen outside the context.
…end or a math-first priority
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
Padding-free and packed SFT on the transformers modeling path (
FastModel/FastBaseModel) spends most of its GPU time in attention. transformers detects the packed rows fromposition_idsand builds a dense block-causal mask, and SDPA can only run that on its masked memory-efficient kernels. A varlen flash kernel computes the same thing 5 to 10x faster. This routes the transformers path's packed rows to one.Change
unsloth/utils/hf_packed_attention.pywraps transformers'ALL_ATTENTION_FUNCTIONS["sdpa"]. A call carryingpacked_seq_lengthsruns ontorch.nn.attention.varlen.varlen_attn(torch's own flash varlen, about the host cost of plain SDPA) with the packedcu_seqlens: torch 2.12+ with native GQA, torch 2.11 (noenable_gqayet) with the K/V heads repeated the way transformers' SDPA path already repeats them. Without that API (torch 2.10 and older, ROCm, pre-sm80) it goes to Unsloth'sattention_dispatch.run_attention(xformers block-diagonal or flash-attn varlen), and failing that to the wrapped SDPA. Every other call goes straight to the wrapped function.run_attentionalready applies covers the torch route too.enable_padding_free_metadataorenable_sample_packingturns on, so only runs that producepacked_seq_lengthsget it.is_causal = False, keyword-only call. Not undertorch.compiletracing.sdpa_kernelpriority that puts math first: those ask for SDPA itself, so no varlen kernel replaces it.varlen_attn, or an xformers or flash-attn backend that runs on this device.UNSLOTH_HF_PACKED_VARLEN=0turns it off.UNSLOTH_TORCH_VARLEN=0(the switch for torch'svarlen_attnfrom Packed SDPA rows: one torch varlen_attn call instead of one SDPA call per segment #13221) keeps torch's kernel off on this path too.Speed
Colab RTX PRO 6000 Blackwell (sm120, G4), torch 2.14.1, transformers 5.17.0, this branch at its final head against main,
FastModel, packed rows of 8192 tokens (yahma/alpaca-cleaned), bs 1, LoRA r16, 25 steps (first 5 not timed), runs in the order main, PR, PR, main:Mean absolute loss difference over the 25 steps, main vs this PR: 0.0012 (Qwen3-4B) and 0.00046 (Llama-3.2-1B), the same as main vs main (0.0011 and 0.00045). With dynamo counters on, main and this PR both show 0 graph breaks and 14 unique graphs over a 6-step Qwen3-4B run.
Earlier measurements:
One exclusive B200, LoRA r=16, bs 8 rows of chat text, main and this PR interleaved in alternating pairs, step time = median after 5 warmup steps (4 pairs each, 6 for short rows):
Short rows are host bound on a 1B model, so the kernel saving does not show there, and the wrapper itself costs about 10 us more host time per attention call than the plain SDPA call (75 vs 60 to 76 us). Main-thread CPU time per step is the same (58.4 vs 57.6 ms median).
On Colab (torch 2.11.0, transformers 5.17.0, L4, bf16), same harness, three alternating pairs each:
On a Colab T4 (sm75, fp16) the varlen kernels do not apply, so every packed call takes the wrapped SDPA: step times match main within noise (pair ratios 0.98 to 1.04) and losses are identical.
The profiler shows where the long-row gain comes from. Per step, SDPA's memory-efficient attention kernels take about 83 ms (Llama-3.2-1B) and 258 ms (Qwen3-4B) on main; the varlen kernels take about 4 ms and 18 ms.
Peak memory is the same or lower: the torch route reads the grouped K/V heads directly instead of expanding them (Llama-3.2-1B, gradient checkpointing off: 8.94 to 7.88 GB; Qwen3-4B: 8.78 to 8.71 GB).
The gradient checkpointing off row is measured on top of #13177, which stops training from building a KV cache (with one, transformers drops the packed mask, so main's number above is from rows attending across documents). With both, that configuration is correct and about 25% faster than main.
Correctness
fast1800,fallback0 over 25 steps).sdpa_attention_forwardover the same mask, for MHA and GQA, including under reentrant checkpointing.Tests
tests/test_hf_packed_attention.py(51 cases): the mask check (exact block-causal accepted; cross-document, bidirectional, window, plain causal, pad tail, float and missing masks rejected; in-place edits and new length tensors rechecked; long masks checked in row blocks), every fallback reason against a control that takes the fast path, unpacked calls passing through untouched, the kill switch, sentinel forwarding and install-once, full-graph compile without touching the counters, the int32 guard in training, grad and pure no_grad eval mode, a refusing torch varlen, deterministic mode, a disabled flash backend and a math-first SDPA priority (with the xformers / flash-attn dispatch spied on), K / V batched differently from Q, reentrant checkpointing, and output plus gradient parity on GPU for the torch 2.12+ route, the torch 2.11 route (noenable_gqa) and therun_attentionroute. It passes on torch 2.10, 2.11, 2.12, 2.13 and 2.14 (transformers 5.17.0, with and without xformers; on 2.10 the torch route is skipped since it needs 2.11) and on transformers 4.52.4, 4.56.2, 4.57.6, 5.17.0 and 5.19.0 (on 4.52.4 transformers builds no packed mask, so the wrapper always falls through). The existing packing and attention test files give the same results on main and this branch (348 passed, the same 2 failures on both).Other training paths are unchanged: base vs head SFT, GRPO, DPO, vision SFT and inference smoke jobs all came back NO_REGRESSION (identical losses, identical peak memory, no new graph breaks), and the tiny-model regression suite shows 0 regressions, 0 metric moves. Backend CI's CPU shard rerun locally in the same environment (Python 3.12, CPU torch 2.10, transformers 5.17.0, 4 xdist workers) gives identical failing test IDs on main and this branch.
On the final head against main, the tiny-model regression suite (smoke tier, 103 cases) shows 0 regressions, 0 metric moves, and the same 4 failures on both sides (environment-only: qwen3moe 4bit load, compressed-tensors mxfp4, fp8_block, qwen35 text-only), and the Studio journeys show no visual change.
Platforms: AMD gfx1151 Linux runs the packing and attention test files base vs head with no regressions (the varlen kernels are gated off on ROCm, so the new tests take the fallback cases there). Ubuntu, macOS 15 and Windows CPU CI pass, as do the Backend, Core, Wheel, Lint, Notebooks and Version Compat suites. Not covered: Hopper and Ampere GPUs were not run for this head (B200, RTX PRO 6000 Blackwell, and earlier L4 / T4 were), and Windows ROCm.