Skip to content

fix(tensor): validate shape element count in from_slice/from_vec - #3589

Closed
pjdurden wants to merge 2 commits into
huggingface:mainfrom
pjdurden:fix/from-slice-shape-validation
Closed

pjdurden wants to merge 2 commits into
huggingface:mainfrom
pjdurden:fix/from-slice-shape-validation

Conversation

@pjdurden

@pjdurden pjdurden commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

What

Enforce the documented contract that the data length must match the declared
shape in Tensor::from_slice and Tensor::from_vec.

Fixes #3534.

The bug

from_slice/from_vec both document "the number of elements ... must be the
same as the number of elements defined by the shape", but never checked it.
ShapeWithOneHole's blanket impl for concrete shapes ignores the el_count
it is handed (shape.rs:474), so:

let t = Tensor::from_slice(&[0.0f32], vec![10], &Device::Cpu).unwrap(); // Ok (!)
t.shape().elem_count();  // 10, but storage holds 1 element
t.to_vec1::<f32>();      // panics: range end index 10 out of range for slice of length 1

The tensor is constructed silently and lies about its size; any later read
against the declared shape indexes past the storage. The current safe-Vec
path panics, but shape-derived unsafe slicing (get_unchecked,
from_raw_parts) would be a true out-of-bounds read.

This is reachable from ordinary code and from loader frontends:

  • from_raw_buffer → convert_slice → from_slice reaches the same state.
  • candle-onnx's get_tensor (eval.rs:192) builds the dim vector straight
    from TensorProto.dims, so a crafted .onnx initializer (dims [1<<32],
    one element) yields a lying tensor inside the loaded model.

The fix

Check shape.elem_count() == data.len() immediately after into_shape in
from_vec_impl and from_slice, returning an error on a mismatch.

Deliberately scoped to the two construction entry points:

  • reshape already has its own elem_count check (tensor.rs:2525) and keeps
    its ShapeMismatchBinaryOp error — left untouched.
  • The ShapeWithOneHole one-hole inference paths (((), d), (d, ()), …)
    already produce a shape whose elem_count equals the data length, so they
    keep working; only the no-hole concrete-shape path is newly validated.

I avoided changing the blanket into_shape impl on purpose: that would also
alter reshape's error type and make its existing check dead code, expanding
the blast radius beyond the reported APIs.

Tests

Adds regression tests to candle-core/tests/tensor_tests.rs:

  • from_slice_validates_shape_element_count — mismatch via from_slice /
    from_vec now errors; matching shapes and one-hole inference still succeed.
  • from_raw_buffer_validates_shape_element_count — the from_raw_buffer path.

Verified RED before the fix, GREEN after. Full candle-core test suite passes
(tensor_tests 48 → 50); cargo fmt --check and cargo clippy clean.

Note / out of scope

The dummy-dtype branch of from_raw_buffer (F4/F6E2M3/F6E3M2/F8E8M0)
builds storage directly from raw bytes and doesn't go through from_slice, so
it isn't covered here. Happy to follow up if you'd like that path guarded too.

`Tensor::from_slice` and `Tensor::from_vec` documented that the data length
must match the declared shape, but never enforced it. `ShapeWithOneHole`'s
blanket impl for concrete shapes ignores the `el_count` it is given, so e.g.
`Tensor::from_slice(&[0.0], vec![10], &Device::Cpu)` returned `Ok` with a
tensor reporting `elem_count() == 10` backed by a single element. Later reads
against the declared shape then index past the storage (the issue reproducer
panics in `to_vec1`; shape-derived unsafe slicing would be a true OOB read).

`from_raw_buffer` reaches the same state via `convert_slice` -> `from_slice`,
and `candle-onnx`'s `get_tensor` builds the dim vector straight from
`TensorProto.dims`, so a crafted `.onnx` initializer produces a lying tensor.

Check `shape.elem_count() == data.len()` right after `into_shape` in
`from_vec_impl` and `from_slice` and return an error on a mismatch. This is
scoped to the two construction entry points and leaves `reshape` (which has
its own `elem_count` check) and the `ShapeWithOneHole` one-hole inference
paths untouched. Adds regression tests for the mismatch and for the matching
/ one-hole cases that must still succeed.

Fixes huggingface#3534

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 7, 2026 00:48

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

Note

Copilot was unable to run its full agentic suite in this review.

Adds explicit validation to tensor constructors to reject shapes whose element count doesn’t match the provided data length, preventing tensors from being created with inconsistent metadata (referenced as candle#3534).

Changes:

  • Validate shape.elem_count() equals the input data length in Tensor::from_vec / Tensor::from_slice.
  • Add regression tests covering mismatch failures and successful “one-hole” shape inference.
  • Add coverage ensuring from_raw_buffer enforces the same contract.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
candle-core/src/tensor.rs Adds runtime checks to prevent constructing tensors with shape/data length mismatches.
candle-core/tests/tensor_tests.rs Adds regression tests for shape element-count validation across constructors.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread candle-core/src/tensor.rs Outdated
Comment on lines +525 to +531
if shape.elem_count() != data.len() {
crate::bail!(
"shape {shape:?} ({} elements) does not match the {} elements in the data",
shape.elem_count(),
data.len()
)
}

@pjdurden pjdurden Jun 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done now. pulled both checks into a shared check_shape_matches_len helper that computes elem_count once.

Comment thread candle-core/src/tensor.rs Resolved
Address review feedback on huggingface#3589: factor the shape/data-length validation
shared by from_vec_impl and from_slice into a single private helper, which
also computes elem_count once instead of twice in the error path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@oyoyo4556

oyoyo4556 commented Jun 7, 2026 •

Copy link
Copy Markdown

Hi @pjdurden, thanks for looking into this and setting up the regression tests!

I encountered this exact silent data corruption last week and submitted #3572 to address it on the ShapeWithOneHole trait side. It's really great to see another perspective on fixing this critical issue .

Your approach on the tensor creation side looks clean as well. Either way, I'm just really glad to see this getting resolved soon, and I look forward to seeing which path the maintainers prefer for the codebase!

@pjdurden

pjdurden commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor Author

@oyoyo4556 thanks . I think these are complementary rather than competing. #3572 fixes the ShapeWithOneHole blanket impl in shape.rs (the one-hole inference path). This PR only touches from_slice/from_vec in tensor.rs and deliberately leaves the one-hole paths alone, so the two cover different entry points:

Landing both fully closes #3534; neither makes the other redundant. Happy to rebase on top of #3572 if a maintainer would rather have it as one path.

@pjdurden

Copy link
Copy Markdown
Contributor Author

@ivarflakstad whenever you have a moment, would appreciate a look here. Scoped shape validation fix with two regression tests, both Copilot threads resolved.

@pjdurden

Copy link
Copy Markdown
Contributor Author

Closing in favor of #3572, which fixes this centrally in ShapeWithOneHole::into_shape and covers the same from_slice/from_vec constructor paths this PR targeted.

Left a note on #3572 on one thing worth checking before merge: reshape (tensor.rs:2538) also routes through into_shape and runs its own elem_count check right after (tensor.rs:2540) returning Error::ShapeMismatchBinaryOp { op: "reshape" }. With the blanket-impl change, into_shape bails first, so reshape's mismatch error changes type and its own check at 2540-2547 becomes unreachable.

The two regression tests here (from_slice/from_vec with a mismatched declared shape, red-before/green-after) can be carried over to cover the constructor entry points.

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.

Tensor::from_slice / from_raw_buffer return Ok when the declared shape does not match the storage element count

3 participants