Repository navigation
Run packed rows of head-dim-routed flex decoders through varlen SDPA - #15514
Conversation
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. |
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]
|
@codex review |
There was a problem hiding this comment.
💡 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".
…, not per model type [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
…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]
|
@codex review |
1 similar comment
|
@codex review |
…(dense SDPA mask) [skip ci]
…lex for padded-to-multiple rows [skip ci]
|
That test compiles the statements ahead of the The other failures in that job (MXFP4 dequantize branch, the notebook restore test) are main issues, fixed by #15558 and #15548. |
…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.
|
@codex review |
1 similar comment
|
@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". |
# Conflicts: # unsloth/utils/hf_packed_attention.py
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
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)inunsloth/models/_utils.py: switches the text config's_attn_implementationfromflex_attentiontosdpa, only when all of these hold:UNSLOTH_FLEX_ATTENTION_FOR_LARGE_HEAD_DIM;unsloth/utils/packing.py:enable_sample_packingandenable_padding_free_metadatacall it after installing the packed varlen wrapper.Switch:
UNSLOTH_PACKED_VARLEN_OVER_FLEX=0keeps flex.Only rows the varlen wrapper will take.
use_sdpa_for_packed_head_dim_flex(model)now switches tosdpaonly 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 onflex_attention:attn_implementation="flex_attention"(a string, or a mapping with aflex_attentionentry) passed toFastModel.from_pretrainedmarks 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/torch_dtype. A float32 or unknown dtype stays on flex._sdpa_policy_requestedcheck, 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-firstsdpa_kernelpriority._softcappedcheck over every module, plusattn_logit_softcappingon any text attention config._NO_SDPA_MODEL_TYPES), SDPA-excluded model types, and classes that declare_supports_sdpa = False(the same checks as_maskless_causal_sdpa_acceptsand the resolver).The gate runs from
enable_sample_packing/enable_padding_free_metadata, afterTrainer.__init__has appliedfull_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 ismax_lengthtimes the larger ofper_device_train_batch_sizeand, 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 > 1pads 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=Truein the trainer args, or a model already wrapped bytorch.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_accumwith(total_q + 128 * n_seqs) * n_heads * round32(head_dim)elements and indexes it with int32. Rows that reach2**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 tosdpa, and was already the behaviour for models onsdpaon main.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 counterHF_PACKED_ATTENTION_STATS["int32_split"].block_varlen_kwargsmarks 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.max_length/max_seq_length(else the model'smax_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 existingtest_int32_guard_follows_training_or_grad_modecases.Results
Setup:
FastModel.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):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):
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:
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
FastLanguageModel's own Llama / Mistral / Qwen2 / Qwen3 / Gemma paths ignore_attn_implementation, so nothing changes there.trainer.train, so later unpacked use of the same model runs on SDPA rather than flex.