Skip to content

Carry the sliding window into SDPA, and treat a zero window as no window - #8253

Merged
danielhanchen merged 4 commits into
mainfrom
nv/mistral-window-fix
Aug 9, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
nv/mistral-window-fix

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

A Mistral-style model could attend past its configured sliding window, silently, on an ordinary training step. Three small holes combine to allow it.

The window never reached SDPA. MistralAttention_fast_forward hands the window to the flash path through window_size, but never passed it to run_attention. With xFormers off and FlashAttention absent, nothing carried it. Training takes the elif self.training: pass branch, so no 4D mask is synthesized either, and every sequence longer than config.sliding_window attended its entire causal history.

run_attention had nothing to hang a window on. With no packing and no padding mask, the SDPA path fell through to is_causal, which is full causal and has no window. It now builds the band mask for that case.

A zero window was treated as a real width. That makes window_size (0, 0) for flash, and an SDPA mask whose lower bound sits above its causal upper bound, so nothing is visible at all. Both sites now read a non-positive window as "no local attention", which is how the mask builders already read an absent one.

llama.py also recomputed HAS_XFORMERS as xformers is not None, overriding attention_dispatch, which turns it off when the library imports but has no kernel that runs here. Model code then stayed on the xFormers path the dispatcher had already left, and Mistral answers xFormers by skipping the 4D mask, which is how the first hole is reached in practice.

Scope

This is the correctness half of #8157, cut out on its own after that PR was reverted for being too large to review. 21 lines of product code across three files, plus the tests. The diagnostics half of #8157 (the ABI compat table, the kernel probe widening, the accelerator report and its Settings panel) is not here and can follow separately.

Tests

tests/utils/test_attention_masks.py, 10 cases covering the packed and unpacked SDPA paths, the xFormers bias, flash varlen, the zero-window handling at both sites, and that Mistral hands the dispatcher its configured window. Each was mutation-checked: breaking the exact line it guards fails the test, restoring it passes.

tests/utils is green: 302 passed, 2 skipped.

Three related holes, all of which let a Mistral-style model attend past its
configured sliding window without saying anything.

MistralAttention_fast_forward passed the window to the flash path through
window_size but never to run_attention, so with xFormers off and FlashAttention
absent nothing carried it. Training takes the `elif self.training: pass` branch,
so no 4D mask is synthesized either, and every sequence longer than
config.sliding_window attended its whole causal history.

run_attention had no way to apply a window when there was nothing to hang it on.
With no packing and no padding mask it fell through to SDPA's is_causal, which
is full causal and has no window at all. It now builds the band mask for that
case.

A non-positive window was passed through as a real width. That makes
window_size (0, 0) for flash, and an SDPA mask whose lower bound sits above its
causal upper bound, hiding every position from every other. Both sites now read
it as "no local attention", which is how the mask builders already read an
absent one.

llama.py also recomputed HAS_XFORMERS as `xformers is not None`, overriding the
dispatcher, which turns it off when the library imports but has no kernel that
runs here. Model code then stayed on the xFormers path the dispatcher had
already left, and Mistral answers xFormers by skipping the 4D mask, which is how
the first hole above is reached in practice.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 9, 2026 11:17

@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: e60b2dc889

ℹ️ 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/utils/attention_dispatch.py Outdated
Comment on lines +408 to +410
local_mask = (
(k_pos[None, :] <= q_pos[:, None])
& (k_pos[None, :] >= (q_pos[:, None] - (sliding_window - 1)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reuse the dense sliding-window mask across layers

When long-context Mistral training falls back to SDPA, every attention layer constructs a new q_len × kv_len boolean mask here even though its shape and contents are identical across layers. At 32K tokens the resulting mask alone is about 1 GiB, and the two comparisons plus their conjunction require multiple such temporaries on every layer, adding substantial allocation pressure and potentially causing OOMs on the exact no-xFormers/no-FlashAttention path this change targets. Cache/share this mask by device, lengths, and window (as the packed SDPA path already does) rather than rebuilding it for each layer.

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.

Fixed in 39130c2, and you are right that this is on the exact path the change targets: at 32K the mask is 1 GiB with two more temporaries alive while it is built, and it was being rebuilt for every layer.

New _windowed_causal_mask caches per device, keyed on (q_len, k_len, window), which is the same single-entry-per-device shape _SDPA_MASK_CACHE already uses for the packed path. It is read-only by contract; the one caller that combines a mask with another (local_mask | no_allowed) does so out of place.

Regression test: test_the_window_mask_is_built_once_per_shape asserts the second call returns the same object and allocates nothing, and that a different window or shape is a miss rather than a stale hit. Mutation-checked both ways: removing the cache lookup fails it, and dropping the window from the key fails it too.

Every layer of a Mistral-style model asks the SDPA fallback for the identical
q_len x kv_len mask. At 32K that tensor is 1 GiB, and the two comparisons plus
their conjunction keep two more alive while it is built, so rebuilding it per
layer is how this path OOMs a run that xFormers or flash would have carried --
on exactly the no-xFormers, no-FlashAttention configuration the mask exists for.

Cached per device and keyed on shape and window, the same single-entry shape
_SDPA_MASK_CACHE already uses for the packed path. Read-only by contract; the
one caller that combines a mask with another does so out of place.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 39130c2746

ℹ️ 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 on lines +191 to +193
q_pos = torch.arange(k_len - q_len, k_len, device = device)
k_pos = torch.arange(k_len, device = device)
mask = (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Evict the stale window mask before allocating its replacement

When consecutive long-context batches use different sequence lengths or windows, the previous dense mask remains referenced by both _WINDOW_MASK_CACHE and the local entry while the replacement and its comparison temporaries are allocated. For a 32K mask this adds another roughly 1 GiB to an already memory-intensive construction and can OOM dynamic-length training even though only one mask is intended to be cached; drop the stale cache entry and local reference before building the new mask.

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.

Fixed in d0ff310. The eviction now happens before the build: _WINDOW_MASK_CACHE.pop(device, None) plus dropping the local entry reference, so a shape change no longer peaks a whole mask higher than an uncached build would. Regression test test_the_outgoing_window_mask_is_freed_before_its_replacement holds a weakref to the outgoing mask and asserts it is already dead at the moment the replacement allocates; removing the eviction fails it. tests/utils is green at 304 passed, 2 skipped.

@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: 93e43236a6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

k_pos = torch.arange(k_len, device = device)
mask = (
(k_pos[None, :] <= q_pos[:, None])
& (k_pos[None, :] >= (q_pos[:, None] - (sliding_window - 1)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the token at the configured window boundary

When Mistral falls back to this new unmasked SDPA path with config.sliding_window = N and a sequence longer than N, this lower bound keeps only keys whose distance is <= N - 1. The existing mask converter uses past_key_values_length - sliding_window - 1, and the flash path passes window_size=(N, N), so the boundary key at distance N is still attended there; SDPA now trains/evaluates with a narrower context than the other backends, e.g. N=3 drops key i-3 from the last row. Use the same inclusive boundary here so the fallback matches the configured window.

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.

Declining this one. The SDPA bound matches the two paths it stands in for; the flash path is the one that is a key wider, and that predates this PR.

xFormers, checked by materializing the bias this file actually builds (`make_local_attention(window_size = 3)`, `mistral.py:200`):

```
[[1 0 0 0 0 0]
[1 1 0 0 0 0]
[1 1 1 0 0 0]
[0 1 1 1 0 0]
[0 0 1 1 1 0]
[0 0 0 1 1 1]]
```

Three keys per row, and key i-3 is dropped from the last row. Its docstring is explicit: "The ith query in a block only attends to keys in its block with index greater than i - window_size and less than or equal to i." The new SDPA mask produces exactly this.

Unsloth's own mask converter agrees: mistral.py:229 is window_bool_mask = (q_indices - k_indices) < sliding_window, also N keys. So the SDPA fallback matches both the xFormers path and the in-repo converter. Widening it as suggested would make it the only backend in the file attending N + 1 keys.

FlashAttention with window_size = (N, N) does include distance N, since its range is inclusive at both ends, so flash is one key wider than xFormers here. That is a pre-existing property of the window_size = (sw, sw) line, unchanged by this PR, and I would rather not narrow a working accelerated path as a side effect of giving SDPA a window it previously did not have at all. Worth a separate look if the one-key difference matters.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 93e43236a6

ℹ️ 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 7088df8 into main Aug 9, 2026
50 of 54 checks passed
@danielhanchen
danielhanchen deleted the nv/mistral-window-fix branch August 9, 2026 12:33
danielhanchen added a commit that referenced this pull request Aug 9, 2026
…dow (#8253)

* Carry the sliding window into SDPA, and treat a zero window as no window

Three related holes, all of which let a Mistral-style model attend past its
configured sliding window without saying anything.

MistralAttention_fast_forward passed the window to the flash path through
window_size but never to run_attention, so with xFormers off and FlashAttention
absent nothing carried it. Training takes the `elif self.training: pass` branch,
so no 4D mask is synthesized either, and every sequence longer than
config.sliding_window attended its whole causal history.

run_attention had no way to apply a window when there was nothing to hang it on.
With no packing and no padding mask it fell through to SDPA's is_causal, which
is full causal and has no window at all. It now builds the band mask for that
case.

A non-positive window was passed through as a real width. That makes
window_size (0, 0) for flash, and an SDPA mask whose lower bound sits above its
causal upper bound, hiding every position from every other. Both sites now read
it as "no local attention", which is how the mask builders already read an
absent one.

llama.py also recomputed HAS_XFORMERS as `xformers is not None`, overriding the
dispatcher, which turns it off when the library imports but has no kernel that
runs here. Model code then stayed on the xFormers path the dispatcher had
already left, and Mistral answers xFormers by skipping the 4D mask, which is how
the first hole above is reached in practice.

* Build the dense window mask once per shape, not once per layer

Every layer of a Mistral-style model asks the SDPA fallback for the identical
q_len x kv_len mask. At 32K that tensor is 1 GiB, and the two comparisons plus
their conjunction keep two more alive while it is built, so rebuilding it per
layer is how this path OOMs a run that xFormers or flash would have carried --
on exactly the no-xFormers, no-FlashAttention configuration the mask exists for.

Cached per device and keyed on shape and window, the same single-entry shape
_SDPA_MASK_CACHE already uses for the packed path. Read-only by contract; the
one caller that combines a mask with another does so out of place.

* Free the outgoing window mask before allocating its replacement

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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