Repository navigation
fix(models): rectangular causal mask for prefix KV caching - #3437
Merged
EricLBuehler merged 4 commits intoApr 1, 2026
Merged
EricLBuehler merged 4 commits into
EricLBuehler merged 4 commits into
Conversation
Previously `mask()` always created a square (seq_len × seq_len) mask. When a prefix KV cache is pre-populated (index_pos > 0), attention scores have shape (seq_len × (index_pos + seq_len)), so broadcasting the square mask failed with: cannot broadcast [seq_len, seq_len] to [batch, heads, seq_len, kv_len] Fix: pass `index_pos` into `mask()` and build a (seq_len, kv_len) mask where kv_len = index_pos + seq_len. - First `index_pos` columns = 0 → every query attends to all prefix keys - Last `seq_len` columns = standard causal triangle When index_pos == 0 the mask is still square — fully backwards compatible. The mask cache key changes from usize to (usize, usize) to accommodate different (seq_len, kv_len) pairs in the same session. This enables batched user-turn prefill after KV-cache prefix restoration, making prefix KV caching actually fast (one batched forward instead of feeding tokens one at a time to avoid the mask crash).
… affected models Extend the quantized_llama rectangular mask fix to all models that share the same square-mask + HashMap<usize> cache pattern: - llama.rs - llama2_c.rs - quantized_llama2_c.rs - quantized_phi.rs - quantized_phi3.rs - quantized_qwen2.rs - quantized_lfm2.rs - granite.rs - granitemoehybrid.rs - voxtral/voxtral_llama.rs Shared utility: move `build_causal_mask(seq_len, index_pos, device)` into `crate::utils` so all models call a single implementation. Also add 5 unit tests for `build_causal_mask` in quantized_llama.rs covering: - square shape (index_pos=0) - rectangular shape (index_pos>0) - correct values for square and rectangular cases - single-query with prefix (all-zero row) - broadcast compatibility with (batch, heads, seq_len, kv_len) attention shape Co-Authored-By: Arthur Zucker <[email protected]>
ArthurZucker
force-pushed
the
fix/prefix-caching-rectangular-mask
branch
from
April 1, 2026 11:27
1982e08 to
4239c27
Compare
EricLBuehler
approved these changes
Apr 1, 2026
EricLBuehler
left a comment
Member
There was a problem hiding this comment.
Thank you @ArthurZucker!
Contributor
Author
|
Yuhu my first PR here! |
Abhinav5132
pushed a commit
to Abhinav5132/candle
that referenced
this pull request
Jul 24, 2026
…ce#3437) * feat(quantized_llama): rectangular causal mask for prefix KV caching Previously `mask()` always created a square (seq_len × seq_len) mask. When a prefix KV cache is pre-populated (index_pos > 0), attention scores have shape (seq_len × (index_pos + seq_len)), so broadcasting the square mask failed with: cannot broadcast [seq_len, seq_len] to [batch, heads, seq_len, kv_len] Fix: pass `index_pos` into `mask()` and build a (seq_len, kv_len) mask where kv_len = index_pos + seq_len. - First `index_pos` columns = 0 → every query attends to all prefix keys - Last `seq_len` columns = standard causal triangle When index_pos == 0 the mask is still square — fully backwards compatible. The mask cache key changes from usize to (usize, usize) to accommodate different (seq_len, kv_len) pairs in the same session. This enables batched user-turn prefill after KV-cache prefix restoration, making prefix KV caching actually fast (one batched forward instead of feeding tokens one at a time to avoid the mask crash). * fix(models): rectangular causal mask for prefix KV caching across all affected models Extend the quantized_llama rectangular mask fix to all models that share the same square-mask + HashMap<usize> cache pattern: - llama.rs - llama2_c.rs - quantized_llama2_c.rs - quantized_phi.rs - quantized_phi3.rs - quantized_qwen2.rs - quantized_lfm2.rs - granite.rs - granitemoehybrid.rs - voxtral/voxtral_llama.rs Shared utility: move `build_causal_mask(seq_len, index_pos, device)` into `crate::utils` so all models call a single implementation. Also add 5 unit tests for `build_causal_mask` in quantized_llama.rs covering: - square shape (index_pos=0) - rectangular shape (index_pos>0) - correct values for square and rectangular cases - single-query with prefix (all-zero row) - broadcast compatibility with (batch, heads, seq_len, kv_len) attention shape Co-Authored-By: Arthur Zucker <[email protected]> * style: rustfmt + remove unused repeat_n import in granitemoehybrid * fix(tests): remove unused super::* import in quantized_llama tests
pjdurden
added a commit
to pjdurden/candle
that referenced
this pull request
Aug 13, 2026
…pendently Follow-up to huggingface#3586 / huggingface#3582, extending that fix to every remaining model with the same pattern and moving the shared logic into `crate::utils` alongside `build_causal_mask`, as huggingface#3437 did for the rectangular mask. Eight models filled the additive mask buffer with `tgt * (tgt + offset)` elements (independent of the batch) but shaped the tensor `(b, 1, tgt, tgt + offset)`. `Tensor::from_slice` does not validate the element count against the shape, since the blanket `impl<S: Into<Shape>> ShapeWithOneHole` discards `el_count`, so the oversized tensor is built silently and only misbehaves at use: - CPU: panics with `range end index N out of range for slice of length M` once the mask is read. - Metal/CUDA: reads past the buffer, so every batch row after the first is masked with garbage and the model returns wrong output. That is what huggingface#3582 reported. Affected: qwen3_moe, quantized_qwen3, quantized_qwen3_moe, glm4_new, quantized_glm4, smol/smollm3, smol/quantized_smollm3 and z_image/text_encoder. Unlike qwen3, where the mask path was gated to CPU-only under the `flash-attn` feature, these gate only on `l == 1`, so the broken mask was built on every multi-token forward on every backend. `utils::build_additive_causal_mask` returns `(1, 1, tgt, tgt + offset)` and is broadcast over the batch by the existing `broadcast_add`. All nine models now call it, including qwen3, which drops the per-model copy added in huggingface#3586. The sliding-window check uses `usize` arithmetic (`j + w >= i + offset`) as in huggingface#3586, avoiding the signed casts. Tests move with the helper: mask shape and batch broadcast, the KV-cache offset case, and the sliding window.
pjdurden
added a commit
to pjdurden/candle
that referenced
this pull request
Aug 13, 2026
…pendently Follow-up to huggingface#3586 / huggingface#3582, extending that fix to every remaining model with the same pattern and moving the shared logic into `crate::utils` alongside `build_causal_mask`, as huggingface#3437 did for the rectangular mask. Eight models filled the additive mask buffer with `tgt * (tgt + offset)` elements (independent of the batch) but shaped the tensor `(b, 1, tgt, tgt + offset)`. `Tensor::from_slice` does not validate the element count against the shape, since the blanket `impl<S: Into<Shape>> ShapeWithOneHole` discards `el_count`, so the oversized tensor is built silently and only misbehaves at use: - CPU: panics with `range end index N out of range for slice of length M` once the mask is read. - Metal/CUDA: reads past the buffer, so every batch row after the first is masked with garbage and the model returns wrong output. That is what huggingface#3582 reported. Affected: qwen3_moe, quantized_qwen3, quantized_qwen3_moe, glm4_new, quantized_glm4, smol/smollm3, smol/quantized_smollm3 and z_image/text_encoder. Unlike qwen3, where the mask path was gated to CPU-only under the `flash-attn` feature, these gate only on `l == 1`, so the broken mask was built on every multi-token forward on every backend. `utils::build_additive_causal_mask` returns `(1, 1, tgt, tgt + offset)` and is broadcast over the batch by the existing `broadcast_add`. All nine models now call it, including qwen3, which drops the per-model copy added in huggingface#3586. The sliding-window check uses `usize` arithmetic (`j + w >= i + offset`) as in huggingface#3586, avoiding the signed casts. Tests move with the helper: mask shape and batch broadcast, the KV-cache offset case, and the sliding window.
ivarflakstad
pushed a commit
that referenced
this pull request
Aug 13, 2026
…pendently (#3879) Follow-up to #3586 / #3582, extending that fix to every remaining model with the same pattern and moving the shared logic into `crate::utils` alongside `build_causal_mask`, as #3437 did for the rectangular mask. Eight models filled the additive mask buffer with `tgt * (tgt + offset)` elements (independent of the batch) but shaped the tensor `(b, 1, tgt, tgt + offset)`. `Tensor::from_slice` does not validate the element count against the shape, since the blanket `impl<S: Into<Shape>> ShapeWithOneHole` discards `el_count`, so the oversized tensor is built silently and only misbehaves at use: - CPU: panics with `range end index N out of range for slice of length M` once the mask is read. - Metal/CUDA: reads past the buffer, so every batch row after the first is masked with garbage and the model returns wrong output. That is what #3582 reported. Affected: qwen3_moe, quantized_qwen3, quantized_qwen3_moe, glm4_new, quantized_glm4, smol/smollm3, smol/quantized_smollm3 and z_image/text_encoder. Unlike qwen3, where the mask path was gated to CPU-only under the `flash-attn` feature, these gate only on `l == 1`, so the broken mask was built on every multi-token forward on every backend. `utils::build_additive_causal_mask` returns `(1, 1, tgt, tgt + offset)` and is broadcast over the batch by the existing `broadcast_add`. All nine models now call it, including qwen3, which drops the per-model copy added in #3586. The sliding-window check uses `usize` arithmetic (`j + w >= i + offset`) as in #3586, avoiding the signed casts. Tests move with the helper: mask shape and batch broadcast, the KV-cache offset case, and the sliding window.
FerrisMind
pushed a commit
to FerrisMind/candle
that referenced
this pull request
Aug 23, 2026
…pendently (huggingface#3879) Follow-up to huggingface#3586 / huggingface#3582, extending that fix to every remaining model with the same pattern and moving the shared logic into `crate::utils` alongside `build_causal_mask`, as huggingface#3437 did for the rectangular mask. Eight models filled the additive mask buffer with `tgt * (tgt + offset)` elements (independent of the batch) but shaped the tensor `(b, 1, tgt, tgt + offset)`. `Tensor::from_slice` does not validate the element count against the shape, since the blanket `impl<S: Into<Shape>> ShapeWithOneHole` discards `el_count`, so the oversized tensor is built silently and only misbehaves at use: - CPU: panics with `range end index N out of range for slice of length M` once the mask is read. - Metal/CUDA: reads past the buffer, so every batch row after the first is masked with garbage and the model returns wrong output. That is what huggingface#3582 reported. Affected: qwen3_moe, quantized_qwen3, quantized_qwen3_moe, glm4_new, quantized_glm4, smol/smollm3, smol/quantized_smollm3 and z_image/text_encoder. Unlike qwen3, where the mask path was gated to CPU-only under the `flash-attn` feature, these gate only on `l == 1`, so the broken mask was built on every multi-token forward on every backend. `utils::build_additive_causal_mask` returns `(1, 1, tgt, tgt + offset)` and is broadcast over the batch by the existing `broadcast_add`. All nine models now call it, including qwen3, which drops the per-model copy added in huggingface#3586. The sliding-window check uses `usize` arithmetic (`j + w >= i + offset`) as in huggingface#3586, avoiding the signed casts. Tests move with the helper: mask shape and batch broadcast, the KV-cache offset case, and the sliding window.
jacobgorm
pushed a commit
to jacobgorm/candle
that referenced
this pull request
Nov 24, 2026
…pendently (huggingface#3879) Follow-up to huggingface#3586 / huggingface#3582, extending that fix to every remaining model with the same pattern and moving the shared logic into `crate::utils` alongside `build_causal_mask`, as huggingface#3437 did for the rectangular mask. Eight models filled the additive mask buffer with `tgt * (tgt + offset)` elements (independent of the batch) but shaped the tensor `(b, 1, tgt, tgt + offset)`. `Tensor::from_slice` does not validate the element count against the shape, since the blanket `impl<S: Into<Shape>> ShapeWithOneHole` discards `el_count`, so the oversized tensor is built silently and only misbehaves at use: - CPU: panics with `range end index N out of range for slice of length M` once the mask is read. - Metal/CUDA: reads past the buffer, so every batch row after the first is masked with garbage and the model returns wrong output. That is what huggingface#3582 reported. Affected: qwen3_moe, quantized_qwen3, quantized_qwen3_moe, glm4_new, quantized_glm4, smol/smollm3, smol/quantized_smollm3 and z_image/text_encoder. Unlike qwen3, where the mask path was gated to CPU-only under the `flash-attn` feature, these gate only on `l == 1`, so the broken mask was built on every multi-token forward on every backend. `utils::build_additive_causal_mask` returns `(1, 1, tgt, tgt + offset)` and is broadcast over the batch by the existing `broadcast_add`. All nine models now call it, including qwen3, which drops the per-model copy added in huggingface#3586. The sliding-window check uses `usize` arithmetic (`j + w >= i + offset`) as in huggingface#3586, avoiding the signed casts. Tests move with the helper: mask shape and batch broadcast, the KV-cache offset case, and the sliding window.
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.
Problem
All models with a
HashMap<usize, Tensor>mask cache build a square(seq_len × seq_len)causal mask. When a prefix KV cache is pre-populated(
index_pos > 0), attention scores have shape(batch, heads, seq_len, index_pos + seq_len)— the square mask cannotbroadcast to that shape and the forward pass panics:
This makes batched user-turn prefill after KV-cache prefix restoration
impossible — a common pattern for efficient multi-turn or multi-request
inference (prefill the system prompt once, restore per request).
Fix
Add
build_causal_mask(seq_len, index_pos, device) -> Result<Tensor>tocrate::utils. It builds a(seq_len, kv_len)mask wherekv_len = index_pos + seq_len:index_poscolumns = 0 (every query attends to all prefix keys)seq_lencolumns = standard causal triangleindex_pos == 0→ classic square mask, fully backwards compatibleUpdate the mask cache key from
usizeto(usize, usize)(i.e.(seq_len, kv_len))in all affected models.
Tests
Five unit tests added to
quantized_llama.rs(no model files required):causal_mask_square_shape—index_pos=0produces(seq_len, seq_len)causal_mask_rectangular_shape—index_pos>0produces(seq_len, kv_len)causal_mask_square_values— correct lower-triangular patterncausal_mask_rectangular_values— prefix columns all-zero, user columns causalcausal_mask_broadcasts_to_attention_shape— mask broadcasts to(batch, heads, seq_len, kv_len)Co-Authored-By: Arthur Zucker [email protected]