Skip to content

Keep packed documents apart on Unsloth's own models (flash path, eval, cached eval) and match transformers' Mistral window - #13313

Merged
danielhanchen merged 4 commits into
mainfrom
mistral-packed-sliding-fa2
Oct 12, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
mistral-packed-sliding-fa2

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Unsloth's own Mistral attention sends packed (padding-free / packing=True) rows to dense flash attention whenever the packed row is longer than sliding_window, because use_varlen also required no active window. Dense flash ignores packed_seq_lengths, so with flash-attn installed every document in a packed row attends into the documents before it, up to the window. The xformers and SDPA paths were not affected: both already build a block-diagonal mask with the window.

Separately, in eval mode without xformers, CausalLM_fast_forward builds a causal mask over the whole row and ignores packed_seq_lengths, so SDPA attends across the documents of a packed row. Padding-free is auto-enabled for SFT, so trainer.evaluate() eval batches are packed rows and hit this. Training mode was already correct (it builds no mask), as is Llama's eval path.

The dense flash path also used window_size = (sliding_window, sliding_window), one key wider than transformers (k > q - sliding_window, which is (sliding_window - 1, sliding_window - 1) in transformers' own flash path) and than Unsloth's SDPA and xformers paths.

Change

  • use_varlen no longer requires window_size == (-1, -1): packed rows take flash_attn_varlen_func, which gets the window through flash_varlen_kwargs["window_size"] (supported since flash-attn 2.3, the same versions the dense path already passes it to).

  • The window is (sliding_window - 1, sliding_window - 1) on both flash paths.

  • A packed row builds no causal mask in eval either, the same as training, so attention keeps the documents apart from packed_seq_lengths (SDPA varlen / per-segment path, with the window).

  • Every Unsloth model forward decided varlen from past_key_value after it had been replaced by the cache it returns, so an eval forward with use_cache=True (the default) sent a packed row to dense flash, across documents. use_varlen now reads the cache passed in (had_cache) in llama, qwen3, cohere, granite, gemma2, falcon_h1 and mistral. Inside the trainer prediction_step already passes use_cache=False for packed batches, so this covers direct eval forwards.

Rows that are not packed and rows no longer than the window are unchanged apart from the one-key window fix.

Tests

New tests/utils/test_packed_flash_documents.py loads hf-internal-testing/tiny-random-MistralForCausalLM with a window of 4 and stands in for flash-attn with reference flash_attn_func / flash_attn_varlen_func that apply flash-attn's causal and window semantics exactly:

  • a packed row of documents of length 7, 9 and 5 gives the same logits as each document run on its own (on main: 21% of logits differ, max 0.27, from the second document attending into the first)
  • one 12-token document gives the same logits on the flash path as on the SDPA path (on main: max difference 0.12 from the extra key)
  • a packed row in eval mode with use_cache=True, with and without a window, on the SDPA and the flash path, gives the same logits as each document alone (fails on main)
  • the same for tiny Llama and Qwen3 on the flash path (fails on main)

With the existing packing, padding-free eval and attention test files (test_packing.py, test_padding_free_eval.py, test_attention_masks.py, test_sdpa_packed_segments.py) everything passes except test_peak_memory_is_linear_in_tokens, which fails the same way on main on this B200 host.

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

chatgpt-codex-connector Bot commented Oct 11, 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 ⚠️ Failed 2026-10-11T12:34:33.127800Z 539751a New commits
ℹ️ 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 danielhanchen changed the title Mistral: keep packed documents apart on the flash-attn path and match transformers' sliding window Mistral: keep packed documents apart (flash-attn path and eval) and match transformers' sliding window Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@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: 6bd427a6c5

ℹ️ 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/mistral.py Outdated

use_varlen = seq_info is not None and past_key_value is None and window_size == (-1, -1)
# Packed rows always take varlen: dense flash would let a document attend into the one before it.
use_varlen = seq_info is not None and past_key_value is None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep packed eval on varlen when producing a cache

In eval mode, Mistral's default config.use_cache=True causes line 113 to replace the initially absent cache with (K, V) before this condition is evaluated. Consequently use_varlen is false, FlashAttention selects its dense path, and packed_seq_lengths is ignored, so documents in a packed row can still attend across boundaries. The newly added packed-eval test also omits use_cache=False and will fail on CUDA environments with real FlashAttention installed; determine varlen eligibility from whether an input cache was supplied rather than from the output cache being constructed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 2e8de8f. The varlen decision now reads the cache passed in (had_cache, taken before past_key_value becomes the returned cache), so an eval forward with use_cache=True keeps a packed row on varlen. Every Unsloth model forward had the same pattern (llama, qwen3, cohere, granite, gemma2, falcon_h1, mistral), so all of them get the same change. The packed eval tests now run on the flash path with use_cache=True for Mistral (with and without a window), Llama and Qwen3, and fail on main. Inside the trainer, prediction_step already passes use_cache=False for packed batches, so this mainly covers direct eval forwards.

@danielhanchen danielhanchen changed the title Mistral: keep packed documents apart (flash-attn path and eval) and match transformers' sliding window Keep packed documents apart on Unsloth's own models (flash path, eval, cached eval) and match transformers' Mistral window Oct 11, 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. Bravo.

Reviewed commit: 2e8de8fd10

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

The red here is not from this PR. This run merged onto main at 9c4c4a1cee, which predates #13336. That PR fixed two problems #13308 left on main:

  • test_torchao_fqn_alias.py left a fake diffusers in sys.modules. That causes the AutoencoderKLWan / modular_pipelines / video Regex pattern did not match failures in (Python 3.13, rest).
  • _torchao_stub.py and test_torchao_fqn_alias.py were not formatted. That causes test_formatter_fixed_point in Repo tests (CPU, rest).

A rerun replays the same merge commit, so updating the branch onto current main should clear both.

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