Skip to content

fix(models): centralize the additive causal mask, build it batch-independently - #3879

Merged
ivarflakstad merged 1 commit into
huggingface:mainfrom
pjdurden:fix/causal-mask-batch-independent-sweep
Aug 13, 2026
Merged

ivarflakstad merged 1 commit into
huggingface:mainfrom
pjdurden:fix/causal-mask-batch-independent-sweep

Conversation

@pjdurden

@pjdurden pjdurden commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #3586, which fixed this in qwen3. That PR noted the same pattern in sibling models and offered to fix them separately. This is that sweep, with the shared logic moved into crate::utils next to build_causal_mask, following #3437.

The bug

These mask builders fill the additive buffer with tgt * (tgt + offset) elements, independent of the batch, but shape the tensor (b, 1, tgt, tgt + offset):

let mask: Vec<_> = (0..tgt)
    .flat_map(|i| (0..(tgt + offset)).map(move |j| /* ... */))
    .collect();                       // len = tgt * (tgt + offset), independent of b
Tensor::from_slice(&mask, (b, 1, tgt, tgt + offset), &self.device)?

Tensor::from_slice does not validate the element count against the shape. The blanket impl discards el_count:

impl<S: Into<Shape>> ShapeWithOneHole for S {
    fn into_shape(self, _el_count: usize) -> Result<Shape> {
        Ok(self.into())
    }
}

So the oversized tensor is built silently and only misbehaves when read. The failure mode depends on the backend:

Scope

Eight models carry the pattern: qwen3_moe, quantized_qwen3, quantized_qwen3_moe, glm4_new, quantized_glm4, smol/smollm3, smol/quantized_smollm3 and z_image/text_encoder. In smol/quantized_smollm3 the function is called create_causal_mask and z_image/text_encoder has no sliding window, but the defect is the same.

These are more exposed than qwen3 was. There the mask path was gated to CPU-only under the flash-attn feature. These gate only on l == 1, so the broken mask is built on every multi-token forward on every backend.

I checked this is the whole set by parsing every Tensor::from_slice and from_vec call in candle-transformers and looking for a batch-like leading dim, rather than grepping line by line. A line grep is how smol/quantized_smollm3 got missed when #3586 listed the siblings, since its call is split across lines. All eight hits are this bug and there are no other batch-leading constructions in the crate.

The fix

Rather than copy the corrected builder into eight more files, this adds utils::build_additive_causal_mask next to the existing utils::build_causal_mask, in the same spirit as #3437. It returns (1, 1, tgt, tgt + offset) and is broadcast over the batch by the existing broadcast_add.

The existing build_causal_mask is not reusable here: it returns a u8 (seq_len, kv_len) mask for models that select on it, whereas these nine add an f32/-inf mask and need a dtype. So this is a sibling of it, not a replacement.

All nine models now call the shared helper, including qwen3, which drops the per-model copy added in #3586. Net effect is 306 lines deleted against 189 added.

The sliding-window check uses usize arithmetic (j + w >= i + offset) as in #3586, which drops the signed casts. I kept the sw parameter even though every call site currently passes None: qwen3 bails with "sliding window is not supported" at construction, so it is the seam for when that lands, and removing it would be a second unrelated change.

Tests

The tests move with the helper into utils: mask shape and batch broadcast, the KV cache offset case, and the sliding window.

They are not vacuous: putting (2, 1, tgt, tgt + offset) back in the helper fails all three.

cargo test -p candle-transformers, cargo clippy -p candle-transformers --all-targets and cargo fmt --all -- --check are clean.

Copilot AI lite review requested due to automatic review settings August 13, 2026 03:09

Copilot AI 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.

Pull request overview

Fixes a correctness bug in several candle-transformers sibling models where additive causal masks were built from a batch-independent buffer but incorrectly shaped with a batch-leading dimension, causing backend-dependent misbehavior for batch > 1. The fix standardizes these masks to shape (1, 1, tgt, tgt + offset) and relies on broadcast_add for batch expansion, mirroring the prior qwen3 fix.

Changes:

  • Extract causal mask construction into per-model build_causal_mask free functions that return a batch-independent (1, 1, ...) mask.
  • Update model forward paths to stop passing/using b for mask shaping and to call the new helper.
  • Add regression tests per model to validate mask shape and correct broadcast behavior (and sliding-window / KV-cache offset behavior where applicable).

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
candle-transformers/src/models/z_image/text_encoder.rs Replace batch-shaped mask with (1,1,...) builder + add regression tests for broadcast/offset.
candle-transformers/src/models/smol/smollm3.rs Make causal mask batch-independent; adjust sliding-window arithmetic; add regression tests.
candle-transformers/src/models/smol/quantized_smollm3.rs Fix create_causal_mask to be batch-independent via helper; add regression tests.
candle-transformers/src/models/qwen3_moe.rs Fix causal mask shaping to (1,1,...) and update forward path; add regression tests.
candle-transformers/src/models/quantized_qwen3.rs Fix causal mask shaping to (1,1,...) and update forward path; add regression tests.
candle-transformers/src/models/quantized_qwen3_moe.rs Fix causal mask shaping to (1,1,...) and update forward path; add regression tests.
candle-transformers/src/models/quantized_glm4.rs Fix causal mask shaping to (1,1,...) and update forward path; add regression tests.
candle-transformers/src/models/glm4_new.rs Fix causal mask shaping to (1,1,...) and update forward path; add regression tests.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@pjdurden
pjdurden force-pushed the fix/causal-mask-batch-independent-sweep branch from f7d071e to 038d4e3 Compare August 13, 2026 03:20
@pjdurden pjdurden changed the title fix(models): build causal mask batch-independently across sibling models fix(models): centralize the additive causal mask, build it batch-independently 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
pjdurden force-pushed the fix/causal-mask-batch-independent-sweep branch from 038d4e3 to eda2af8 Compare August 13, 2026 03:26
@pjdurden

Copy link
Copy Markdown
Contributor Author

@ivarflakstad you merged #3586, this is the sibling sweep that PR offered.

Same bug in 8 more models. Rather than copy the fixed builder into each one, it moves to utils::build_additive_causal_mask next to the existing build_causal_mask, following what #3437 did. qwen3 calls the shared helper too, so the copy added in #3586 goes away. Net -118 lines.

Two things worth a look:

The buggy path is wider here than it was in qwen3. qwen3 gates the mask on the device, so the bad shape was only reachable on one backend per feature set. These 8 gate only on l == 1, so they built it on every multi-token forward everywhere. On CPU that is a panic, not silent corruption.

I kept the sw parameter even though all 9 call sites pass None, since qwen3 bails with "sliding window is not supported" at construction and it looked like a deliberate seam. Happy to drop it if you would rather it go.

@ivarflakstad
ivarflakstad merged commit 3b7af4a into huggingface:main Aug 13, 2026
11 checks passed
astorise added a commit to astorise/candle that referenced this pull request Aug 15, 2026
Resolves the conflicts from upstream huggingface#3879, which centralized the additive
causal mask into `utils::build_additive_causal_mask`. This fork had already
fixed the same batch-dim bug per-model (`(b, 1, tgt, ..)` -> `(1, 1, tgt, ..)`),
so every conflict was fork-local copy vs. upstream shared helper.

Took upstream's helper in all seven files and dropped the per-model
`causal_mask` duplicates. Fork-only additions caught inside the same hunks are
preserved:
- quantized_glm4: `ModelWeights::clear_kv_cache`
- quantized_qwen3_moe: the `clear_kv_cache` / `kv_cache_state` /
  `set_kv_cache_state` session checkpoint API

Note upstream's helper uses `j + w >= i + offset` for the sliding window,
avoiding the signed casts the fork copies used; behaviour is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
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.

3 participants