Skip to content

fix(models): rectangular causal mask for prefix KV caching - #3437

Merged
EricLBuehler merged 4 commits into
huggingface:mainfrom
ArthurZucker:fix/prefix-caching-rectangular-mask
Apr 1, 2026
Merged

EricLBuehler merged 4 commits into
huggingface:mainfrom
ArthurZucker:fix/prefix-caching-rectangular-mask

Conversation

@ArthurZucker

@ArthurZucker ArthurZucker commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

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 cannot
broadcast to that shape and the forward pass panics:

cannot broadcast [seq_len, seq_len] to [batch, heads, seq_len, index_pos + seq_len]

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> to
crate::utils. It builds 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
  • index_pos == 0 → classic square mask, fully backwards compatible

Update the mask cache key from usize to (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=0 produces (seq_len, seq_len)
  • causal_mask_rectangular_shape — index_pos>0 produces (seq_len, kv_len)
  • causal_mask_square_values — correct lower-triangular pattern
  • causal_mask_rectangular_values — prefix columns all-zero, user columns causal
  • causal_mask_broadcasts_to_attention_shape — mask broadcasts to (batch, heads, seq_len, kv_len)

Co-Authored-By: Arthur Zucker [email protected]

@ArthurZucker ArthurZucker changed the title fix(quantized_llama): rectangular causal mask for prefix KV caching fix(models): rectangular causal mask for prefix KV caching Apr 1, 2026
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
ArthurZucker force-pushed the fix/prefix-caching-rectangular-mask branch from 1982e08 to 4239c27 Compare April 1, 2026 11:27

@EricLBuehler EricLBuehler left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you @ArthurZucker!

@EricLBuehler
EricLBuehler merged commit aa812d7 into huggingface:main Apr 1, 2026
11 checks passed
@ArthurZucker

Copy link
Copy Markdown
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.
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.

2 participants