Repository navigation
Carry the sliding window into SDPA, and treat a zero window as no window - #8253
Conversation
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.
There was a problem hiding this comment.
💡 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".
| local_mask = ( | ||
| (k_pos[None, :] <= q_pos[:, None]) | ||
| & (k_pos[None, :] >= (q_pos[:, None] - (sliding_window - 1))) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| q_pos = torch.arange(k_len - q_len, k_len, device = device) | ||
| k_pos = torch.arange(k_len, device = device) | ||
| mask = ( |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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))) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
…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>
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_forwardhands the window to the flash path throughwindow_size, but never passed it torun_attention. With xFormers off and FlashAttention absent, nothing carried it. Training takes theelif self.training: passbranch, so no 4D mask is synthesized either, and every sequence longer thanconfig.sliding_windowattended its entire causal history.run_attentionhad nothing to hang a window on. With no packing and no padding mask, the SDPA path fell through tois_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.pyalso recomputedHAS_XFORMERSasxformers is not None, overridingattention_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/utilsis green: 302 passed, 2 skipped.