Skip to content

Packed rows on sliding-window layers take varlen on the transformers path, plus opt-in FA4 / FA3 for packed training - #13326

Merged
danielhanchen merged 19 commits into
mainfrom
packed-varlen-windows-fa4
Oct 12, 2026
Merged

danielhanchen merged 19 commits into
mainfrom
packed-varlen-windows-fa4

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

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_window 4096), Phi-3-mini-4k (2048), and the sliding layers of Cohere2, Qwen2 with use_sliding_window, and Gemma 4 text.

  • transformers (4.56 and 5.x) builds the window as kv_idx > q_idx - sliding_window on top of causal, so a key at most W - 1 tokens back is kept. The torch route passes window_size = (W - 1, 0) to varlen_attn, the flash-attn route passes the same, and the xformers route uses AttentionContext.sliding_window = W, whose band is the same.
  • The window comes from the call's sliding_window keyword, else the module's sliding_window. A window that is zero, negative, a float or a bool keeps the wrapped SDPA, as do softcap and sinks.
  • The mask check now also requires the band (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.
  • On ROCm, windowed packed rows keep the wrapped SDPA: flash-attn's ROCm backend lists sliding windows as work in progress.
  • The mask check now does one host sync instead of one per 1024-row block (about 60 ms down to 7 ms per step at 8K tokens on a 6-layer model).

Packed LoRA SFT (r=16, bs 1, alpaca rows packed to max_length, 4-bit) through FastModel on 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:

model main this PR packed attention calls on varlen
Phi-3-mini-4k (window 2048), 4K rows 1.154 / 1.152 s/step 0.614 / 0.613 s/step 0 of 1600 -> 1600 of 1600
Mistral-7B v0.1 (window 4096), 8K rows 4.125 / 4.126 s/step 1.875 / 1.874 s/step 0 of 1600 -> 1600 of 1600

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) with torch.nn.attention.activate_flash_attention_impl. New unsloth/utils/flash_impl.py uses it for packed training when asked:

  • UNSLOTH_FLASH_ATTENTION_IMPL = auto (default) | fa4 | fa3 | off. auto uses FA4 on sm100, and FA3 then FA4 on sm90, whichever kernels are installed; with neither installed, or on any other GPU, nothing changes.
  • Only while 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.
  • Only when every gate passes: every visible GPU is a supported major, the kernel package imports, the model has no attention dropout (FA4 raises on dropout instead of falling back), every head dim the model can send to flash is one the kernel has, and a probe on the model's own shapes (packed GQA causal, with its window if any, forward and backward) matches torch's bundled flash. Otherwise torch is left as it was, with the reason logged once.
  • Per call, 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.
  • An impl activated by the user outside Unsloth is left alone.

The gain depends on document length, so off stays available. On one B200 (torch 2.14.1, FA4 4.0.0b34, Qwen3-4B FastModel, LoRA r=16), alternating off / FA4 runs:

packed rows off FA4
16K-token documents 0.745 s/step (0.745, 0.745) 0.650 s/step (0.646, 0.655)
short chat rows, 8K packed 0.577 s/step (0.570, 0.583) 0.622 s/step (0.587, 0.656)

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 FastModel with padding-free and with packing=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.

model (FastModel) packed attention calls on varlen, main this PR max diff vs each document alone, main this PR
Mistral (window), transformers 5.17 and 4.56.2 0 of 8 8 of 8 0.012 0.012
Qwen2 (sliding layers) 4 of 8 8 of 8 0.012 0.012
Cohere2 (sliding layers) 4 of 8 8 of 8 0.001 0.0005
Gemma 4 text, compile off 0 of 8 4 of 8 (the sliding layers; the 512 global heads keep SDPA) 0.115 0.094
Llama, Qwen3, Phi-3 (no window), Gemma 3 (flex) unchanged unchanged unchanged unchanged

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_lengths never reach the new code, and FA3 / FA4 are only ever active inside trainer.train().

Tests

  • tests/test_hf_packed_attention.py: output and dQ / dK / dV parity against transformers' sdpa_attention_forward over 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 tiny MistralForCausalLM end 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.
  • The new and existing packing / attention test files pass on torch 2.14 + transformers 5.17, torch 2.14.1 + transformers 4.56.2 (with FA4 installed), torch 2.11, torch 2.10 (no torch varlen: the varlen-only cases skip) and torch 2.7.1 + transformers 4.57.6 + TRL 0.22.2 + PEFT 0.18.0, with the same results as main on the files main has.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 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 ✅ Completed 2026-10-12T09:56:59.929383Z 792d838 Manual request
ℹ️ 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.

@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: 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".

Comment thread unsloth/utils/flash_impl.py Outdated
Comment on lines +297 to +298
window_size = (window - 1, 0) if window else (-1, 0),
enable_gqa = 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 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 👍 / 👎.

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

Comment thread unsloth/utils/packing.py Outdated

mark_allow_overlength(model)
_enable_hf_packed_attention()
_scope_flash_attention_impl(model, trainer)

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

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 26350f40c8

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

@danielhanchen

Copy link
Copy Markdown
Member Author

The red here is not from this PR. This run merged onto main at 548fe076fa, which predates #13336. That PR fixed two problems #13308 left on main:

  • A fake diffusers left in sys.modules. That causes the AutoencoderKLWan / modular_pipelines / video Regex pattern did not match failures in (Python 3.13, rest).
  • Two unformatted files. That causes test_formatter_fixed_point in Repo tests (CPU, rest).

A rerun replays the same merge commit, so updating the branch onto current main should clear it.

@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: 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".

Comment thread unsloth/utils/flash_impl.py Outdated
Comment on lines +401 to +404
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)

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

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1d4517a7d2

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

# Conflicts:
#	unsloth/utils/packing.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 792d838c6f

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

1 participant