Skip to content

Keep flash attention from reading Qwen3.5 mRoPE position ids as packed sequences - #12856

Merged
danielhanchen merged 5 commits into
mainfrom
fa2-mrope-not-packed
Oct 7, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fa2-mrope-not-packed

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

On transformers 5.3, Qwen3.5 passes its 3-row mRoPE position ids, shape (3, batch, L), into every full attention layer (huggingface/transformers#44910; 5.5 passes 2D ids). For a batch of one with no padding, flash attention drops the all-ones mask and asks _is_packed_sequence whether the input is several packed sequences. That check reads shape[1] (the batch, 1) as the length and answers yes, so _prepare_from_posids builds cu_seqlens = [0, L, 2L, 3L] over a q/k/v of only L tokens.

flash-attn then reads and writes 2L tokens past its buffers:

  • plain transformers 5.3.0, no Unsloth, Qwen3.5-0.8B, one 304-token input: the recorded call has 304 query rows and cu_seqlens [0, 304, 608, 912]
  • compute-sanitizer on that call: 8319 invalid reads in the varlen kernel
  • the 608 rows after the output buffer are overwritten (505,376 non-finite values); the correct single-sequence call touches none

The rows actually read stay correct, so the damage lands in whatever tensor sits next in memory and shows up intermittently. Studio runs Qwen3.5 on its transformers 5.3 side environment with flash-attn installed: decision model calibration (batch of one) produced NaN logits and the run saved nothing. An instrumented Studio training worker recorded 18 such calls per run before this change and 0 after.

fix_transformers_flash_attention_mrope_packed_sequence() in unsloth/import_fixes.py, applied at import from _gpu_init.py, wraps _is_packed_sequence so position ids with more than 2 dimensions are never treated as packed (packed sequences are flattened (1, total) ids). It is chosen by behaviour: a probe call with (3, 1, 4) ids decides whether the installed transformers has the bug, so fixed versions are left alone. Idempotent, functools.wraps, original kept on __wrapped__. _is_packed_sequence is only referenced inside modeling_flash_attention_utils.py (checked on 4.57.6, 5.5.0, 5.17.0), so wrapping the module attribute covers every caller.

Tests

tests/test_flash_attention_mrope_packed.py drives the real transformers functions, including _flash_attention_forward against an SDPA reference on a GPU with flash-attn. 5/5 pass on transformers 5.3.0 and 5.5.0; with the guard removed 3 fail on both. With test_import_fixes_drift.py: 62 passed on 5.17.0, 61 passed on 5.5.0. On 4.57.6 the same 4 drift tests fail with and without this change (pre-existing).

Not covered: transformers 5.4.x, and padding-free packed training with 3D ids on 5.3 (it already miscounted lengths before this change).

Regression suite (smoke tier, merge base vs head, tiny checkpoints across model families, all cases finished): 103 cases each side, 66 passed, 13 xpass, 24 skipped on both, 0 regressions, 0 metric moves. Studio journeys (auth, settings, crawl): no functional regression. Staging CI: the only failures are the ones every PR on that staging repo currently shows (unsloth-zoo test_maskless_causal_skip and patch list, test_wsl_host, workflow trigger lint).

@danielhanchen danielhanchen self-assigned this Oct 6, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 6, 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-07T10:34:33.473687Z 258d2d8 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 7, 2026
@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. Hooray!

Reviewed commit: 258d2d8c03

ℹ️ 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 c6cfbb7 into main Oct 7, 2026
@danielhanchen
danielhanchen deleted the fa2-mrope-not-packed branch October 7, 2026 12:06
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 28, 2026
…PE position ids (unslothai#15771)

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