Skip to content

safetensors: copy only whole elements on the unaligned path - #3965

Open
apollo-2006 wants to merge 1 commit into
huggingface:mainfrom
apollo-2006:fix-safetensors-unaligned-copy-overflow
Open

apollo-2006 wants to merge 1 commit into
huggingface:mainfrom
apollo-2006:fix-safetensors-unaligned-copy-overflow

Conversation

@apollo-2006

Copy link
Copy Markdown

convert_slice rounds the element count down:

let elem_count = data.len() / size_in_bytes;

so the Vec<T> built on the unaligned path holds elem_count * size_of::<T>() bytes. The copy that fills it moved data.len() bytes instead:

let mut c: Vec<T> = Vec::with_capacity(elem_count);
std::ptr::copy_nonoverlapping(data.as_ptr(), c.as_mut_ptr() as *mut u8, data.len());

Whenever data.len() is not a multiple of the element size, that writes past the end of the allocation.

Reachable from safe code

Tensor::from_raw_buffer is public and passes caller-supplied bytes straight through, so a seven-byte F32 buffer at an unaligned address is enough to trigger it. It returns Ok with no indication anything went wrong. Miri:

error: Undefined Behavior: memory access failed: attempting to access 7 bytes,
but got alloc42051 which is only 4 bytes from the end of the allocation
 --> candle-core/src/safetensors.rs:133:12
    candle_core::safetensors::convert_slice::<f32>
    candle_core::Tensor::from_raw_buffer

This is a write, not a read.

Fix

Copy elem_count * size_of::<T>() bytes. That is exactly the capacity allocated, and it matches the aligned branch, which already exposes only the first elem_count whole elements and ignores a trailing partial one. The two branches now agree. Well formed input is unaffected, since its length is a multiple of the element size.

I kept this to making the copy match the allocation rather than rejecting a non-multiple length outright, because the aligned branch already silently truncates and changing that is a wider behaviour question. Happy to make both branches reject instead if you would prefer that contract.

convert_slice_with_cast carries the same pattern and is changed the same way. Being straight about its reachability: its only caller path is a safetensors tensor view, and the parser checks that a tensor's byte span agrees with its shape, so I could not construct a trigger for that one. It is corrected for consistency, not because I have a repro.

Not a duplicate of #3534

#3534 is about a declared shape disagreeing with the storage element count, and its own text notes it "yields a panic, not undefined behavior". This overflow happens during the copy, before any shape is looked at, and the failing test uses shape [1] with elem_count == 1, so the shapes agree. A fix for #3534 would not address it.

Tests

candle-core/tests/safetensors_convert_tests.rs. The unaligned path is forced by placing the payload at an odd address, which is never 2-, 4- or 8-aligned on any allocator, so the tests do not depend on allocator behaviour.

test without this change with it
unaligned_trailing_bytes_do_not_overflow Miri reports the overflow pass
unaligned_data_loads_correct_values pass pass
unaligned_wide_dtype_loads_correct_values pass pass
aligned_data_loads_correct_values pass pass

The three that pass either way are controls showing correct data still loads correctly on both branches.

Verified: cargo test -p candle-core 232 passed 0 failed, cargo clippy -p candle-core --all-targets -- -D warnings clean, cargo fmt --check clean, and cargo +nightly miri test -p candle-core --test safetensors_convert_tests reports no undefined behaviour with the change and one error without it.

`convert_slice` rounds the element count down:

    let elem_count = data.len() / size_in_bytes;

so the `Vec<T>` built on the unaligned path holds `elem_count * size_of::<T>()`
bytes. The copy that fills it moved `data.len()` bytes instead:

    let mut c: Vec<T> = Vec::with_capacity(elem_count);
    std::ptr::copy_nonoverlapping(data.as_ptr(), c.as_mut_ptr() as *mut u8, data.len());

Whenever `data.len()` is not a multiple of the element size, that writes past
the end of the allocation. `Tensor::from_raw_buffer` is public and safe and
passes caller-supplied bytes straight through, so a seven-byte F32 buffer at an
unaligned address is enough. Miri:

    error: Undefined Behavior: memory access failed: attempting to access 7
    bytes, but got alloc42051 which is only 4 bytes from the end of the
    allocation
     --> candle-core/src/safetensors.rs:133:12
        candle_core::safetensors::convert_slice::<f32>

Copy `elem_count * size_of::<T>()` bytes instead. That is exactly the capacity
allocated, and it matches the aligned branch, which already exposes only the
first `elem_count` whole elements and ignores a trailing partial one. Well
formed input is unaffected, since its length is a multiple of the element size.

`convert_slice_with_cast` carries the same pattern and is changed the same way.
Its only caller path is a safetensors tensor view, and the parser checks that a
tensor's byte span agrees with its shape, so no reachable trigger for that one
could be constructed. It is corrected for consistency.

Distinct from huggingface#3534, which is about a shape that disagrees with the storage
element count and surfaces as a panic rather than as undefined behaviour. The
overflow here happens during the copy, before any shape is validated, and the
test case has a shape that matches its element count.

Adds four tests. The trailing-bytes case reports the overflow under Miri without
this change; the other three cover correct data on the aligned and unaligned
paths and pass either way.
Copilot AI lite review requested due to automatic review settings September 8, 2026 21: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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@apollo-2006

Copy link
Copy Markdown
Author

@ivarflakstad you have been merging most of candle-core lately, so you are probably the right person for the one thing I left open in the description.

I fixed the copy to match the allocation rather than rejecting a non-multiple length, because the aligned branch already truncates a trailing partial element silently and changing that is a wider contract question. I want to check that was the right call.

It is not settled by the fixes for #3534 either. Both open ones, #3572 and #3615, check the declared shape inside from_slice, but convert_slice only calls from_slice after the copy has already run, so the overflow happens before either check sees anything. I ran each of them under Miri with this PR's change removed, and both still report it:

attempting to access 7 bytes, but got alloc43337 which is only 4 bytes from the end

So: is silently dropping a trailing partial element the contract you want for from_raw_buffer, or should both branches reject a non-multiple length outright? Happy to push the stricter version if that is what you would rather have.

This branch has not been deployed

No deployments
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