Skip to content

Run packed rows on the transformers modeling path through varlen flash attention - #13234

Merged
danielhanchen merged 16 commits into
mainfrom
packed-varlen-hf-attention
Oct 11, 2026
Merged

danielhanchen merged 16 commits into
mainfrom
packed-varlen-hf-attention

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

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 from position_ids and 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

  • New unsloth/utils/hf_packed_attention.py wraps transformers' ALL_ATTENTION_FUNCTIONS["sdpa"]. A call carrying packed_seq_lengths runs on torch.nn.attention.varlen.varlen_attn (torch's own flash varlen, about the host cost of plain SDPA) with the packed cu_seqlens: torch 2.12+ with native GQA, torch 2.11 (no enable_gqa yet) 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's attention_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.
  • The flash varlen int32 backward guard run_attention already applies covers the torch route too.
  • It is installed when enable_padding_free_metadata or enable_sample_packing turns on, so only runs that produce packed_seq_lengths get it.
  • The varlen path is taken only when the result is the same as the wrapped SDPA's. Anything else falls back:
    • transformers' mask must be exactly causal inside each packed segment and closed across them. It is compared once per mask object and checked again after an in-place edit. This also covers sliding windows, bidirectional spans and a pad tail segmented differently.
    • CUDA, bf16 / fp16 matching the autocast dtype, batch 1 Q / K / V of the same length, no KV or paged cache, no dropout, causal module.
    • Equal Q/K/V head widths up to 256 (not MLA's 192 / 128, nor Gemma-4's 512 global heads).
    • No sliding window, logit softcap (config or layer) or sinks, no explicit is_causal = False, keyword-only call. Not under torch.compile tracing.
    • Not in deterministic mode, with flash SDPA disabled, or under an sdpa_kernel priority that puts math first: those ask for SDPA itself, so no varlen kernel replaces it.
    • torch's varlen_attn, or an xformers or flash-attn backend that runs on this device.
  • The unsloth-zoo sdpa routers re-wrap the same entry on every model load; their sentinels are forwarded and the wrapper installs once per process, so the chain never loops.
  • UNSLOTH_HF_PACKED_VARLEN=0 turns it off. UNSLOTH_TORCH_VARLEN=0 (the switch for torch's varlen_attn from 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:

model main s/step this PR s/step speedup peak GB main / PR varlen calls / fallbacks
Qwen3-4B 3.384 / 3.384 0.786 / 0.787 4.3x 5.26 / 5.04 1800 / 0
Llama-3.2-1B 0.576 / 0.575 0.239 / 0.240 2.4x 2.58 / 2.42 800 / 0

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):

run main this PR per-pair ratio
Qwen3-4B, packed rows of 4 to 6K tokens, gradient checkpointing on 441.7 ms (427 to 464) 317.3 ms (290 to 341) 0.74, 0.74, 0.66, 0.72
Llama-3.2-1B, packed rows of 4 to 6K tokens, gradient checkpointing on 155.1 ms (151 to 169) 134.1 ms (117 to 166) 0.99, 0.75, 0.84, 0.92
Llama-3.2-1B, packed rows of 4 to 6K tokens, gradient checkpointing off, with #13177 122.3 ms (120 to 126) 90.5 ms (85 to 116) 0.72, 0.76, 0.71, 0.92
Llama-3.2-1B, short rows (about 1.5K tokens packed) 153.1 ms (142 to 191) 153.4 ms (144 to 168) 0.97, 1.08, 0.76, 1.02, 1.02, 0.99
Gemma-3-1B (flex attention, wrapper not called) 216.2 ms (208 to 227) 202.0 ms (195 to 223) 0.95, 0.94, 0.98, 0.92

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:

run main this PR per-pair ratio
Qwen3-0.6B, packed rows of 4 to 6K tokens 1003.4 ms (996 to 1008) 467.5 ms (462 to 468) 0.47, 0.46, 0.46
Llama-3.2-1B, packed rows of 4 to 6K tokens 1005.7 ms (1004 to 1007) 681.4 ms (680 to 685) 0.68, 0.68, 0.68
Llama-3.2-1B, short rows 391.9 ms (384 to 394) 314.8 ms (314 to 331) 0.82, 0.80, 0.84

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

  • Losses match main to within bf16 noise in every run above, for example Qwen3-4B 4.791 / 4.573 / 4.197 on main against 4.787 / 4.583 / 4.200 here, and every attention call took the varlen path (fast 1800, fallback 0 over 25 steps).
  • Outputs and gradients match transformers' sdpa_attention_forward over 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 (no enable_gqa) and the run_attention route. 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-11T08:52:51.345333Z f2f1884 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… and hand a refusing torch varlen back to sdpa
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: a6ec091d79

ℹ️ 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".

@Etherll

Etherll commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

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:

model mode main this PR peak memory
Qwen3-0.6B packing 5.85 s/step 0.344 s/step 6.90 → 4.63 GB
Llama-3.2-1B packing 7.06 s/step 0.359 s/step 10.25 → 7.91 GB
Qwen3-0.6B padding-free 0.332 s/step 0.218 s/step same
Llama-3.2-1B padding-free 0.265 s/step 0.126 s/step same

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. UNSLOTH_HF_PACKED_VARLEN=0 restores main's route and timing exactly, and padding_free=False never installs the wrapper.

tests/test_hf_packed_attention.py passes 43/43 on transformers 4.52.4, 5.5.0 and 5.17.0. The existing packing and attention tests give the same result on main and this branch; test_peak_memory_is_linear_in_tokens fails on both. Small-config checks of llama, qwen2, qwen3, phi3, gpt_neox, gemma, olmo2, granite and jetmoe took the fast path with matching loss; mistral fell back because of its sliding window. No issues were found on this head. Not run: ROCm, pre-Ampere GPUs, the flash-attn package route, Windows/macOS. Fork CI is running: Etherll#224.

@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 643d6f4afa

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +200 to +203
if (
bsz == 1
and q_len > 0
and query.is_cuda

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +224 to +227
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: fd9c2d514d

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants