Repository navigation
Keep packed documents apart under flash attention when layers get mRoPE position ids - #15771
Merged
Merged
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. |
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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". |
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, nocu_seq_lens_qfrom the caller) and its position ids have more than two dimensions, the document boundaries are taken frompacked_seq_lengthsand passed ascu_seq_lens_q/kandmax_length_q/k, which flash attention already takes ahead of position ids. Every other call is passed through unchanged:packed_seq_lengths(anything that is not Unsloth packing, inference, generation): untouched, one dict lookupcu_seq_lens_q, or lengths that do not cover the row: untouchedEvidence
Probe on Qwen3.5-0.8B inside a fresh
install.sh --localStudio, 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."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:
Tests in
tests/test_flash_attention_mrope_packed.pycover 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.