Skip to content

Run packed rows of head-dim-routed flex decoders through varlen SDPA - #15514

Merged
danielhanchen merged 20 commits into
mainfrom
varlen-over-flex-v2
Oct 28, 2026
Merged

danielhanchen merged 20 commits into
mainfrom
varlen-over-flex-v2

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

On GPUs where SDPA with a dense mask does not reach cuDNN at head_dim 256 (H100 on torch 2.14 among them), Unsloth puts decoders with head_dim up to 256 on flex attention. With packed / padding-free rows, the packed varlen wrapper on the SDPA path already runs these rows through torch's flash varlen kernel exactly, and flash supports head_dim 256. This PR moves those packed runs from flex to SDPA, so they use varlen flash instead of compiling flex block masks.

Change

use_sdpa_for_packed_head_dim_flex(model) in unsloth/models/_utils.py: switches the text config's _attn_implementation from flex_attention to sdpa, only when all of these hold:

  • the model is on flex only because of its head dim: head_dim <= 256, not the gemma3 family, and no forced UNSLOTH_FLEX_ATTENTION_FOR_LARGE_HEAD_DIM;
  • the packed varlen wrapper is installed;
  • torch's varlen kernel runs on every visible CUDA device (sm80+, not ROCm).

unsloth/utils/packing.py: enable_sample_packing and enable_padding_free_metadata call it after installing the packed varlen wrapper.

Switch: UNSLOTH_PACKED_VARLEN_OVER_FLEX=0 keeps flex.

Only rows the varlen wrapper will take.
use_sdpa_for_packed_head_dim_flex(model) now switches to sdpa only when the packed varlen wrapper would actually run the packed rows. Every call the wrapper declines goes to SDPA over a dense mask, which is slower than flex and uses about 2x the memory at head_dim 256, so in each of these cases the decoder stays on flex_attention:

  • Explicit flex request: attn_implementation="flex_attention" (a string, or a mapping with a flex_attention entry) passed to FastModel.from_pretrained marks the loaded model, and that model stays on flex. The mark is per model, so two models of the same type loaded side by side keep their own routing. Only the automatic head-dim route is switched.
  • Dtype: attention must run in fp16 or bf16. The dtype comes from the input embeddings, else the config's dtype / torch_dtype. A float32 or unknown dtype stays on flex.
  • SDPA policy: the wrapper's own _sdpa_policy_requested check, run at setup for each CUDA device with the model's dtype, head dim and head counts. It covers deterministic algorithms (torch.use_deterministic_algorithms, full_determinism), a disabled flash SDPA backend, and a math-first sdpa_kernel priority.
  • Softcap and sinks: the wrapper's own _softcapped check over every module, plus attn_logit_softcapping on any text attention config.
  • No SDPA: model types the resolver loaded without SDPA (_NO_SDPA_MODEL_TYPES), SDPA-excluded model types, and classes that declare _supports_sdpa = False (the same checks as _maskless_causal_sdpa_accepts and the resolver).

The gate runs from enable_sample_packing / enable_padding_free_metadata, after Trainer.__init__ has applied full_determinism. Some conditions are only known per call and are not checked by the gate: positional attention arguments, an autocast dtype that differs from the model dtype, and deterministic mode turned on after the trainer is built. Those calls still fall back to dense-mask SDPA.

Long flattened rows keep flex. Under SDPA, transformers builds a dense [T, T] bool mask for the whole flattened packed row before the varlen wrapper runs. Flex keeps a compact block mask instead. At 65536 tokens that mask alone is 4 GiB, enough to OOM a run that fit on flex. The switch therefore only happens when one flattened row is at most 16384 tokens (a 256 MiB mask). The row length is max_length times the larger of per_device_train_batch_size and, when there is an eval dataset, per_device_eval_batch_size, since the padding-free collator joins a device batch into one row. The H100 benchmark above (one 8192-token row) is inside this limit. Tests: test_long_flattened_rows_keep_flex.

Padded-to-multiple rows keep flex. A collator with pad_to_multiple_of > 1 pads the flattened row past the last document. The varlen wrapper declines such rows and runs dense-mask SDPA (B200, documents of 2048 + 2045 tokens padded to 4096: 7.49 vs 5.96 ms and 175 vs 138 MiB), so those collators keep flex. Tests: test_eval_rows_and_aligned_tails_keep_flex.

Whole-model compile keeps flex. With torch_compile=True in the trainer args, or a model already wrapped by torch.compile, the outer compile inlines the decoder blocks. There the varlen wrapper falls back to dense-mask SDPA (B200, head_dim 256, 8 x 1024-token documents: 11.45 ms and 209 MiB vs 1.61 ms and 32 MiB on compiled flex), so those runs stay on flex. Tests: test_whole_model_compile_keeps_flex (both cases).

Rows past the varlen backward int32 limit.

flash-attn 2's varlen backward allocates dq_accum with (total_q + 128 * n_seqs) * n_heads * round32(head_dim) elements and indexes it with int32. Rows that reach 2**31 (for example 1024 documents over 131072 tokens at 32 heads and head_dim 256) used to be rejected by both varlen paths and fall back to SDPA over the dense block-causal mask, which is far slower and heavier than flex for the models this PR moves to sdpa, and was already the behaviour for models on sdpa on main.

  • Eager wrapper: when the guard trips, the packed documents are split into consecutive groups that each stay under the limit (greedy, on the host lengths the wrapper already reads). The varlen kernel runs per group on its own token slice with rebased cu_seqlens, and the outputs are concatenated. Documents never attend across each other, so this is exact: output and gradients are bitwise equal to the unsplit kernel in the tests. Covers both torch's varlen and the flash-attn / xformers dispatch route. New counter HF_PACKED_ATTENTION_STATS["int32_split"].
  • Compiled blocks: splitting inside the graph would need per-step group counts and slice bounds, so block_varlen_kwargs marks such rows and the traced wrapper hands them to the eager wrapper, which splits them. That is one graph break for overflowing rows only; every other row keeps the in-graph kernel with no break. Before, these rows ran dense-mask SDPA inside the graph.
  • One document alone past the limit cannot be split and still takes the dense fallback. At 32 heads and head_dim 256 that needs a single document of about 262016 tokens. To keep that from being worse than flex, the flex-to-sdpa switch now stays on flex when the trainer's max_length / max_seq_length (else the model's max_seq_length) alone could overflow. If none of those is set, the switch still happens.

Tests: test_int32_guard_splits_documents_instead_of_the_dense_fallback (torch and dispatch routes, with and without a window; the guard limit is patched small, the dense path raises, and output and grads must match the unsplit run bitwise), test_int32_safe_groups_split_at_document_boundaries, test_block_varlen_kwargs_sends_rows_past_int32_to_the_eager_wrapper, test_traced_leave_block_call_runs_the_eager_wrapper, test_a_document_too_long_to_split_under_int32_stays_on_flex, test_packing_passes_the_trainer_max_length. All 9 new cases fail on the previous head (the 4 split cases with the dense fallback) and pass on this head, alongside the existing test_int32_guard_follows_training_or_grad_mode cases.

Results

Setup:

  • H100 80GB HBM3, torch 2.14.1+cu130, transformers 4.57.6, TRL 0.24.0, PEFT 0.21.0.
  • Model: random-weight Qwen3 of about 2B (Qwen3-1.7B shape, head_dim 256), loaded with FastModel.
  • Training: LoRA r=16, packed SFT, 8192-token rows, 30 steps, median of steps 5-29.
  • Runs: 3 fresh processes per arm on one VM, in the order main, branch, branch, main, main, branch.
  • Main chose flex on its own; nothing was forced.
documents main step this PR repeat-run spread tokens/s peak memory
fixed 512 tokens 278.4 ms 259.7 ms (-6.7%) 0.3% 29.4k -> 31.5k 5.23 -> 5.42 GB
varying 32-2048 tokens 352.3 ms 299.1 ms (-15.1%) 0.1-0.3% 23.3k -> 27.4k 5.23 -> 5.45 GB
  • Stall on main: with fixed lengths, main also stalls for 2.45 s at step 6 in every run (the medians leave this out); this PR does not.
  • Memory: peak memory is about 4% higher.

Kernels: at step 6, main runs the flex Triton kernels, and this PR runs torch's flash forward and backward.

Correctness

  • Loss and gradients: per-step losses match main within 3e-4 (fixed) and 6e-4 (varying), and two runs of this PR differ from each other by up to 4e-4. Final loss 12.3675 vs 12.3676, and gradient norms within 6e-4 relative.

  • Tiny packed SFT through FastModel (2-layer Qwen3 at head_dim 256, LoRA, 20 steps):

    • losses within 1e-4 of main;
    • first-step LoRA gradients at cosine 0.99997;
    • with UNSLOTH_PACKED_VARLEN_OVER_FLEX=0, losses and gradients are bit-identical to main.
  • Attention op vs fp64 (head_dim 256, grouped KV heads, 4 packed documents):

    • output error: flex 1.96e-3, varlen 1.98e-3;
    • gradient error: flex 2.5-2.8e-3, varlen 2.8-3.4e-3.

    Both are at bf16 rounding.

Tests

Gate tests: new cases in tests/test_packed_varlen_over_flex.py (all 10 fail on the previous head, all pass now):

  • test_rows_the_varlen_wrapper_declines_stay_on_flex: float32 config, float32 embeddings, unknown dtype, deterministic algorithms, flash SDPA disabled, math-first priority, softcap config, sinks module, no-SDPA model type.
  • test_explicit_flex_request_stays_flex: a model marked by an explicit loader request stays on flex.
  • test_explicit_flex_is_per_model_not_per_type: of two same-type models, only the explicitly requested one stays on flex.

The existing bf16 switch tests are unchanged, including the CUDA test that runs packed rows on varlen and checks the logits against flex.

Float32 rows (the wrapper declines them): tiny random Gemma (head_dim 256, 4 layers), packed rows of 300 / 700 / 1000 / 2048 tokens, forward + backward, 5 steps after warmup:

dtype head impl varlen calls dense-mask fallbacks peak memory
float32 previous sdpa 0 20 1022 MiB
float32 this fix flex_attention 0 0 709 MiB
bfloat16 previous sdpa 20 0 478 MiB
bfloat16 this fix sdpa 20 0 478 MiB

New tests/test_packed_varlen_over_flex.py (14 tests): the gate conditions, the kill switch, the gemma3 / head_dim 512 / forced-override exclusions, and a GPU test checking that the switched model's packed logits match flex.

Related packed-attention suites: 291 passed on this branch and 277 on main, with the same 8 failures on both. Those 8 are test_hf_packed_attention.py::test_varlen_matches_sdpa_over_the_dense_mask[...], and they already fail on main.

Not covered

  • Which models it reaches: only models on the transformers modeling path. FastLanguageModel's own Llama / Mistral / Qwen2 / Qwen3 / Gemma paths ignore _attn_implementation, so nothing changes there.
  • Hybrid models: the benchmark is a dense model. Qwen3.5 / Qwen3-Next have only a quarter of their layers on full attention, so their gain should be smaller (not measured).
  • Persistence: the switch stays on the model after trainer.train, so later unpacked use of the same model runs on SDPA rather than flex.
  • B200: SDPA does not reach cuDNN at head_dim 256 on B200 with torch 2.14 either, so the switch engages there too. The tests above ran on B200, but its timing was not repeated on an exclusive card.
  • Timing: only torch 2.14 on H100 was timed. Other torch versions and GPUs were checked for correctness only.
  • Reused collator: a collator already wrapped for another model stays on flex, which is slower but correct.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 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-28T13:33:29.426603Z ce404f3 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.

The packed varlen-over-flex switch now leaves a decoder on flex_attention when the
user asked for flex_attention, when attention runs in float32 (or an unknown dtype),
when deterministic algorithms, a disabled flash SDPA backend or a math-first SDPA
priority would make the wrapper keep SDPA, when the model has softcapping or sinks,
and when the model type or class cannot take SDPA. Each of those otherwise ran
packed rows through SDPA over a dense mask.

[skip ci]
@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: bf1d8be8e7

ℹ️ 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/models/_utils.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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.

ℹ️ 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/models/_utils.py Resolved
…to document groups

A packed row whose varlen backward dq_accum would reach 2**31 elements fell back to
SDPA over the dense mask. Documents are independent, so the eager wrapper now runs the
varlen kernel per group of consecutive documents under the limit and joins the rows.
Compiled blocks hand such rows to the eager wrapper (a graph break for those rows only),
and the flex-to-sdpa switch stays on flex when the trainer's max length alone overflows.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen danielhanchen self-assigned this Oct 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Repo tests (CPU, rest) fails 6 tests in tests/test_attn_dtype_custom_datatype.py here (job 122197461249), all passing on main (7 of 7):

tests/test_attn_dtype_custom_datatype.py:69: in _selected
E   NameError: name 'requests_flex_attention' is not defined

That test compiles the statements ahead of the resolve_attention_implementation call in vision.py with a fixed namespace. This PR makes that preamble call the new requests_flex_attention from _utils, which the namespace does not provide. Adding it to the namespace in _selected (the real one, from unsloth.models._utils import requests_flex_attention, or a stub returning False for these dtype cases) clears all six, including test_custom_datatype_load_does_not_disable_flash_attention.

The other failures in that job (MXFP4 dequantize branch, the notebook restore test) are main issues, fixed by #15558 and #15548.

danielhanchen added a commit that referenced this pull request Oct 27, 2026
…f it (#15558)

Seven tests in `tests/test_mxfp4_lora_packed_experts_dequantize.py` fail
on main (`Repo tests (CPU, rest)`, e.g. job 122197461249 on #15514, and
every PR based after #15367):

```
unsloth/models/vision.py:4132: NameError: name '_fp8_full_finetune' is not defined
```

## Cause

The test compiles only the `if` in `FastBaseModel.from_pretrained` that
sets `quantizer_kwargs["dequantize"]`, with a hand-written namespace of
its inputs. #15367 added a local just ahead of it,

```python
_fp8_full_finetune = full_finetuning and str(quant_method).lower() == "fp8"
```

and reads it in that `if`'s condition. The product is right; the harness
namespace was missing the new local, so every case that reaches the
condition stopped on the NameError.

## Change

The harness now also runs the `name = ...` statements ahead of the
branch in each block enclosing it (within the function) whose name the
branch reads, outermost first, skipping any name the test already
provides. Today that adds only the `_fp8_full_finetune` line; a future
local computed the same way is picked up instead of breaking the file
again, and the stubs keep precedence.

## Verification (local, CPU)

- Whole file: main 7 failed, 37 passed; this branch 44 passed.
- Sabotage: replacing that line in `vision.py` with `_fp8_full_finetune
= True` fails 5 tests on this branch
(`test_native_load_unchanged_without_packed_path`,
`test_offloading_device_map_keeps_native_load`, ...), so the lifted line
is the real one from `vision.py` and it is evaluated on every case.
@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. Another round soon, please!

Reviewed commit: a496d3b475

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

@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. Breezy!

Reviewed commit: ce404f353d

ℹ️ 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
danielhanchen merged commit 92ecb52 into main Oct 28, 2026
3 of 34 checks passed
@danielhanchen
danielhanchen deleted the varlen-over-flex-v2 branch October 28, 2026 15:33
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