Repository navigation
fix(models): centralize the additive causal mask, build it batch-independently - #3879
Conversation
There was a problem hiding this comment.
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_maskfree functions that return a batch-independent(1, 1, ...)mask. - Update model
forwardpaths to stop passing/usingbfor 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.
f7d071e to
038d4e3
Compare
…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.
038d4e3 to
eda2af8
Compare
|
@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 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 I kept the |
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]>
…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.
…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.
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 intocrate::utilsnext tobuild_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):Tensor::from_slicedoes not validate the element count against the shape. The blanket impl discardsel_count:So the oversized tensor is built silently and only misbehaves when read. The failure mode depends on the backend:
range end index 18 out of range for slice of length 9incpu_backend/utils.rs.Scope
Eight models carry the pattern:
qwen3_moe,quantized_qwen3,quantized_qwen3_moe,glm4_new,quantized_glm4,smol/smollm3,smol/quantized_smollm3andz_image/text_encoder. Insmol/quantized_smollm3the function is calledcreate_causal_maskandz_image/text_encoderhas no sliding window, but the defect is the same.These are more exposed than
qwen3was. There the mask path was gated to CPU-only under theflash-attnfeature. These gate only onl == 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_sliceandfrom_veccall incandle-transformersand looking for a batch-like leading dim, rather than grepping line by line. A line grep is howsmol/quantized_smollm3got 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_masknext to the existingutils::build_causal_mask, in the same spirit as #3437. It returns(1, 1, tgt, tgt + offset)and is broadcast over the batch by the existingbroadcast_add.The existing
build_causal_maskis not reusable here: it returns au8(seq_len, kv_len)mask for models that select on it, whereas these nine add anf32/-infmask and need adtype. 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
usizearithmetic (j + w >= i + offset) as in #3586, which drops the signed casts. I kept theswparameter even though every call site currently passesNone:qwen3bails 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-targetsandcargo fmt --all -- --checkare clean.