Repository navigation
Conversation
`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]>
There was a problem hiding this comment.
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 inTensor::from_vec/Tensor::from_slice. - Add regression tests covering mismatch failures and successful “one-hole” shape inference.
- Add coverage ensuring
from_raw_bufferenforces 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.
| if shape.elem_count() != data.len() { | ||
| crate::bail!( | ||
| "shape {shape:?} ({} elements) does not match the {} elements in the data", | ||
| shape.elem_count(), | ||
| data.len() | ||
| ) | ||
| } |
There was a problem hiding this comment.
Done now. pulled both checks into a shared check_shape_matches_len helper that computes elem_count once.
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]>
|
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 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! |
|
@oyoyo4556 thanks . I think these are complementary rather than competing. #3572 fixes the
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. |
|
@ivarflakstad whenever you have a moment, would appreciate a look here. Scoped shape validation fix with two regression tests, both Copilot threads resolved. |
|
Closing in favor of #3572, which fixes this centrally in Left a note on #3572 on one thing worth checking before merge: The two regression tests here ( |
What
Enforce the documented contract that the data length must match the declared
shape in
Tensor::from_sliceandTensor::from_vec.Fixes #3534.
The bug
from_slice/from_vecboth document "the number of elements ... must be thesame as the number of elements defined by the shape", but never checked it.
ShapeWithOneHole's blanket impl for concrete shapes ignores theel_countit is handed (
shape.rs:474), so:The tensor is constructed silently and lies about its size; any later read
against the declared shape indexes past the storage. The current safe-
Vecpath 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_slicereaches the same state.candle-onnx'sget_tensor(eval.rs:192) builds the dim vector straightfrom
TensorProto.dims, so a crafted.onnxinitializer (dims[1<<32],one element) yields a lying tensor inside the loaded model.
The fix
Check
shape.elem_count() == data.len()immediately afterinto_shapeinfrom_vec_implandfrom_slice, returning an error on a mismatch.Deliberately scoped to the two construction entry points:
reshapealready has its ownelem_countcheck (tensor.rs:2525) and keepsits
ShapeMismatchBinaryOperror — left untouched.ShapeWithOneHoleone-hole inference paths (((), d),(d, ()), …)already produce a shape whose
elem_countequals the data length, so theykeep working; only the no-hole concrete-shape path is newly validated.
I avoided changing the blanket
into_shapeimpl on purpose: that would alsoalter
reshape's error type and make its existing check dead code, expandingthe blast radius beyond the reported APIs.
Tests
Adds regression tests to
candle-core/tests/tensor_tests.rs:from_slice_validates_shape_element_count— mismatch viafrom_slice/from_vecnow errors; matching shapes and one-hole inference still succeed.from_raw_buffer_validates_shape_element_count— thefrom_raw_bufferpath.Verified RED before the fix, GREEN after. Full
candle-coretest suite passes(tensor_tests 48 → 50);
cargo fmt --checkandcargo clippyclean.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, soit isn't covered here. Happy to follow up if you'd like that path guarded too.