Skip to content

Keep packed documents apart under flash attention when layers get mRoPE position ids - #15771

Merged
danielhanchen merged 2 commits into
mainfrom
qwen35-fa-packed-mrope
Oct 28, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
qwen35-fa-packed-mrope

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

On transformers 5.3, Qwen3.5 and Qwen3.5-MoE hand their decoder layers the 3-row mRoPE position ids instead of the text position ids (5.5 and later pass the text ids). Flash attention finds document boundaries in a packed row from the position ids, so with mRoPE ids it cannot see them: since #12856 stopped those ids from being read as three packed rows (the out-of-bounds crash in huggingface/transformers#44910), flash attention runs one causal span over the whole packed row, and every packed document attends to the documents before it.

This is what Unsloth Studio hits when it trains Qwen3.5 with packing: Studio runs Qwen3.5 on its transformers 5.3 side environment with flash attention, so packed documents leak into each other there. The Gated DeltaNet layers were already kept apart by Unsloth's varlen kernels; only the full attention layers leaked.

Fix

When a flash attention call gets an Unsloth packed row (packed_seq_lengths, one row, no attention mask, no cu_seq_lens_q from the caller) and its position ids have more than two dimensions, the document boundaries are taken from packed_seq_lengths and passed as cu_seq_lens_q/k and max_length_q/k, which flash attention already takes ahead of position ids. Every other call is passed through unchanged:

  • no packed_seq_lengths (anything that is not Unsloth packing, inference, generation): untouched, one dict lookup
  • 2D position ids (every model on transformers 5.5+, and every non-mRoPE model): untouched, flash attention finds the boundaries itself as before
  • a padding mask, a batch of more than one row, caller supplied cu_seq_lens_q, or lengths that do not cover the row: untouched

Evidence

Probe on Qwen3.5-0.8B inside a fresh install.sh --local Studio, in each of its transformers environments (L4, flash attention 2): a 61 token document followed by a 41 token document in one packed row, versus the second document alone. Max logit difference; shifting the document's positions alone moves the logits by 0.36, so anything near that is isolated.

transformers without the fix with the fix
5.3.0 (Studio's Qwen3.5 tier) 14.75 0.44
5.5.0 0.44 0.44
5.10.2 0.44 0.44

"Without the fix" is the same packed forward without packed_seq_lengths, so the patch cannot engage; on 5.3 that is the path every Unsloth packed row took before. Per layer on 5.3, the first full attention layer (layer 3) now differs by 0.012, like the linear attention layers around it (an earlier probe had it at 0.117, where the leak starts).

On 5.5 and 5.10 the patch does not engage (2D position ids reach the layers), and Qwen3-0.6B (no mRoPE) gives 0.79 on all three, against 0.96 for shifted positions.

End to end through Studio's fine-tuning API (Qwen3.5-0.8B on RTX PRO 6000, packing on, 16 documents, 20 steps; a job trained alone, then the same job batched beside another, on #15733 with this fix merged in). Without the fix, Studio's packing check finds the packed documents not isolated on 5.3 and trains the batch unpacked, and the job trained alone leaks across its own documents. With it:

mode packing check batched job packed step 1 loss alone / batched step 20 loss alone / batched learning rate
4-bit isolated 16 documents into 8 rows 0.8034 / 0.8004 0.0000 / 0.0001 identical every step
16-bit isolated 16 documents into 8 rows 0.7438 / 0.7444 0.0000 / 0.0000 identical every step

Tests in tests/test_flash_attention_mrope_packed.py cover the boundary kwargs, every pass-through case, idempotency, and (on CUDA with flash-attn) that a packed row's output matches each document's attention computed alone. All 10 pass with flash-attn 2.8.4 in each of Studio's environments (transformers 5.3.0, 5.5.0, 5.10.2). Negative control: the same packed-row call with the patch removed differs from per-document attention by 2.91 (bf16) on all three versions, against 0.0 with it, so the CUDA test fails without the fix.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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:26:49.382027Z 2f0d534 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.

@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: 2f0d534a52

ℹ️ 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 added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
…documents (unslothai#15733)

Since unslothai#15478 turned packing on by default, every queued fine-tuning job
asks for packing, and unslothai#15344 sent packing jobs to train alone. So
compatible jobs stopped batching at all, and three batching tests in
`studio/backend/tests/test_openai_fine_tuning.py` fail on main
(`test_compatible_queued_jobs_start_as_one_batch`,
`test_jobs_differing_only_in_member_fields_batch_in_queue_order`,
`test_only_plain_dense_models_batch[dense]`).

This PR lets packing jobs batch, with packing kept per job so a job's
documents never meet another job's:

* Each member packs only its own documents, with TRL's default packing
strategy at the run's max length, the same packing its single run would
get. Pre-tokenized datasets stay unpacked, as in the single run.
* Once any member packs, each micro-batch is one padding-free row, as in
the single packed run: positions restart at every document,
`packed_seq_lengths` is passed to the model, every token is routed to
its own member's adapter, and the label opening each document is masked
so nothing is predicted across a boundary. A document never spans two
members.
* Packing is used only where the single job's Unsloth SFTTrainer would
pack: not on padding-free blocklisted models, encoder-decoders, forwards
that cannot take `packed_seq_lengths`, or hybrid linear-attention models
whose varlen kernels are not available (their recurrent state would
carry across documents). Elsewhere packing is ignored, as the single job
ignores it.
* Packing is also used only where a packed forward provably keeps
documents apart: before packing, one forward of a short document after
another in one packed row is compared with that document alone, and a
model whose packed documents see each other trains unpacked with a
warning. Qwen3.5 on transformers 5.3 (Studio's tier for it) passes every
static check above, yet its full attention layers let packed documents
attend across the boundary (logits off by up to 14.7 against 0.36
elsewhere); the root cause is fixed in core by unslothai#15771, and this check
keeps batched jobs isolated on any install that lacks it.
* Vision-language models (Qwen3.5, Qwen3.6) tokenize their text through
the processor's tokenizer, as the single job does; the full processor is
still what gets saved.
* `packing` is now a per-member field, so packed and unpacked jobs can
share a batch; an unpacked member in a packed batch trains exactly as it
would alone.

Tests (CPU, tiny Qwen3;
`studio/backend/tests/test_multi_lora_trainer.py`):

* a packing member's losses and saved adapter are the same with a
different neighbour and alone, and every packed document holds one
adapter's tokens with positions restarting at each;
* an unpacked member beside packed ones matches its own run;
* packing is ignored when the model cannot pack; a hybrid packs only
with its varlen kernels;
* packed rows keep each document's labels with its tokens.

Negative control: with positions not restarting per document, the
isolation checks fail. All of `test_multi_lora_trainer.py`,
`test_openai_fine_tuning.py` and `test_training_batch_backend.py` pass
(113).

GPU, through the OpenAI-compatible API on a fresh `install.sh --local`
Studio (Qwen3-0.6B, 4-bit and 16-bit; a job trained alone, then the same
job batched beside another while a third holds the GPU; 16 documents, 20
steps, packing on by default):

| GPU | mode | batched job packed | steps alone / batched | step 1 loss
alone / batched | final loss alone / batched | learning rate |
|---|---|---|---|---|---|---|
| RTX PRO 6000 (bf16) | 4-bit | 16 documents into 1 row | 20 / 20 |
2.2689 / 2.2807 | 0.00017 / 0.00027 | identical every step |
| RTX PRO 6000 (bf16) | 16-bit | 16 documents into 1 row | 20 / 20 |
2.6012 / 2.5983 | 0.00016 / 0.00019 | identical every step |
| T4 (fp16) | 4-bit | 16 documents into 1 row | 20 / 20 | 2.2761 /
2.2772 | 0.00058 / 0.00020 | see below |
| T4 (fp16) | 16-bit | 16 documents into 1 row | 20 / 20 | 2.6012 /
2.6012 | 0.00017 / 0.00015 | see below |

The single run packed too ("Unsloth: Packing enabled") on every arm. On
the T4 the learning-rate schedules drift apart after the single run
skips a step on an fp16 overflow while the batched job does not; that
comes from the batch sharing one fp16 loss scale, which is on main
already and is fixed separately in unslothai#15741.
@danielhanchen
danielhanchen merged commit 3b01845 into main Oct 28, 2026
@danielhanchen
danielhanchen deleted the qwen35-fa-packed-mrope branch October 28, 2026 13:51
danielhanchen added a commit that referenced this pull request Oct 30, 2026
… compiled (#16058)

Follow-up to #15771.

## Problem

A padding-free collator with `pad_to_multiple_of` pads the flattened row
after the document lengths are taken, so the lengths stop short of the
query. The wrapper then passed the row through and flash attention ran
causal over every document, which is the leak #15771 set out to stop
(lengths [3, 5] in a 16-token row).

Under `torch.compile` the coverage check was skipped. A padded row got
boundaries that left the tail unwritten, and an overrunning row got
boundaries past the end of the query. A warm metadata cache also handed
the compiled region its maximum document length as a guarded constant,
so it compiled one graph per distinct length (8 frames for 8 lengths).

## Change

The padded tail gets its own segment through `cover_padded_cu_seqlens`,
as Unsloth's own attention dispatch already does (cu_seqlens [0, 3, 8,
16] for the example). Lengths running past the row are still passed
through. When compiling, the boundary computation runs under
`torch.compiler.disable`, so compiled calls take the same decision as
eager and the maximum length arrives as a call result: 3 frames for the
same 8 lengths, warm or cold. Warm calls now have 2 graph breaks instead
of 0, in exchange for no per-length recompiles.

## Tests

`tests/test_flash_attention_mrope_packed.py`, CPU, torch 2.13,
transformers 5.17:

- main: 5 failed, 8 passed, 2 skipped. Failing:
`test_padded_tail_gets_its_own_segment`,
`test_compiled_calls_match_eager_boundaries[False]`, `[True]`,
`test_compiled_calls_do_not_recompile_per_document_length[False]`,
`[True]`.
- this branch: 13 passed, 2 skipped.

On CUDA (B200, flash attention 2 from the
`kernels-community/flash-attn2` hub kernel), same test file:

- main: 5 failed, 10 passed.
- this branch: 15 passed, including both flash attention cases.

With real flash attention on a row ending in a 16 token padded tail,
main lets the second document attend into the first (max abs error 3.98
against attending that document alone); this branch gives 0.0. Without a
tail both give 0.0.

## Not covered

The CUDA cases ran with the hub flash attention kernel, not the
`flash-attn` wheel. If the whole model is compiled, each packed
attention call now has a graph break where main had none; Unsloth
compiles with attention excluded by default, so the default flow should
not see it. The cold `.item()` graph break remains, on par with the
upstream packed varlen path.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant