Skip to content

fix(torch_bin): honour _rebuild_tensor_v2 storage_offset and reject non-contiguous tensors - #757

Merged
0xShug0 merged 1 commit into
0xShug0:mainfrom
Zhuoxi2000:fix-torch-bin-storage-offset
Oct 2, 2026
Merged

0xShug0 merged 1 commit into
0xShug0:mainfrom
Zhuoxi2000:fix-torch-bin-storage-offset

Conversation

@Zhuoxi2000

Copy link
Copy Markdown
Contributor

What / why

The torch .bin reader in src/framework/assets/torch_bin.cpp loads VibeVoice fine-tune adapters: diffusion_head_full.bin and the connector pytorch_model.bin files, via src/models/vibevoice/lora.cpp. From each _rebuild_tensor_v2(storage, storage_offset, size, stride, ...) it kept only storage and size, and every tensor was read from byte 0 of its storage.

torch.save stores tensors that share a storage only once, and records a separate storage_offset for each one. So a file saved as {"head": x[:4], "tail": x[4:]} loaded tail with head's values, and a transposed tensor was read in storage order. Neither raised an error, so the model silently ran with the wrong weights.

After this change, such files either load the values torch.load returns or fail with a clear error. The reader now behaves the same way as the RVC checkpoint reader in src/models/rvc/voice_model.cpp.

Change

  • src/framework/assets/torch_bin.cpp:
    • op_reduce requires storage_offset (args[1]) to be an Int and stride (args[3]) to be a Tuple of Int, and stores both on the tensor. It rejects negative offsets and dimensions, and a stride whose rank differs from the shape.
    • The constructor sets byte_offset = storage.offset + storage_offset * element_bytes. It replaces the "larger than its storage" check with a bounds check that accounts for the offset and cannot overflow.
    • Non-contiguous tensors are rejected with torch .bin tensor is not contiguous, which is not supported: <name>. The check follows torch's is_contiguous, which ignores the stride of size-1 dimensions: for example torch.arange(4.).reshape(1, 4).t() (shape (4, 1), stride (1, 4)) is laid out row-major and is accepted. RVC's contiguous_strides is stricter and would reject that tensor; I followed torch here. I did not add a strided gather, to keep the change small.
  • include/engine/framework/assets/torch_bin.h: the comment now describes this behaviour.
  • tests/unittests/test_torch_bin_storage_offset.cpp (new) is registered in CMakeLists.txt after safetensors_metadata_depth_test. It builds the checkpoint in memory as a STORED zip with a protocol 2 pickle, using the same opcodes torch.save emits. It checks:
    • 1-D views that share a storage
    • a 2-D chunk view at offset 9
    • a size-1 dimension with an arbitrary stride
    • rejection of a transposed tensor
    • rejection of a view that runs past the end of its storage

Ordinary module.state_dict() files are unaffected: every tensor is at offset 0 and contiguous, and the bytes read are the same as before. There is no performance or memory impact; the change only adds a few integer checks per tensor at load time.

Validation

macOS on Apple M4, Release build, CPU:

cmake -S . -B build -DAUDIOCPP_MODEL_SET=core -DENGINE_BUILD_TESTS=ON -DENGINE_BUILD_MODEL_TESTS=ON -DENGINE_ENABLE_OPENMP=OFF -DCMAKE_BUILD_TYPE=Release
cmake --build build -j4 --target torch_bin_storage_offset_test safetensors_offsets_test safetensors_metadata_depth_test gguf_tensor_source_test torch_bin_parity
(cd build && ctest -R '^(torch_bin_storage_offset_test|safetensors_offsets_test|safetensors_metadata_depth_test|gguf_tensor_source_test)$' --output-on-failure)

Unit test. On main (f16f23a), with only the new test added (this branch with torch_bin.cpp and torch_bin.h reverted to main):

torch .bin storage offset test failed: tail (storage_offset 4) should be [4, 5, 6, 7] as torch.load returns, got [0, 1, 2, 3]
0% tests passed, 1 tests failed out of 1

With this PR, all four tests pass:

100% tests passed out of 4

Real torch.save files. I wrote these files with torch 2.14.1 and read them with the torch_bin_parity tool (tests/vibevoice/torch_bin_parity.cpp, built by the commands above), once with main's loader (f16f23a) and once with this PR:

x = torch.arange(8.)
torch.save({"head": x[:4], "tail": x[4:]}, "views.bin")
torch.save({"head": x.half()[:4], "tail": x.half()[4:]}, "views_f16.bin")
w = torch.randn(8, 4); q, k = w.chunk(2, 0)
torch.save({"q": q, "k": k}, "chunk.bin")
torch.save({"wt": torch.arange(6.).reshape(2, 3).t()}, "transposed.bin")
torch.save({"row": torch.arange(4.).unsqueeze(0)}, "unsqueezed.bin")   # stride (4, 1)
file torch.load main this PR
views.bin tail = 4,5,6,7 tail = 0,1,2,3 tail = 4,5,6,7
views_f16.bin tail = 4,5,6,7 tail = 0,1,2,3 tail = 4,5,6,7
chunk.bin k = rows 4..7 of w k identical to q (rows 0..3) k matches torch.load
transposed.bin [[0,3],[1,4],[2,5]] 0,1,2,3,4,5 (exit 0) torch .bin tensor is not contiguous, which is not supported: wt (exit 1)
unsqueezed.bin [[0,1,2,3]] 0,1,2,3 0,1,2,3

Regression check on ordinary state dicts. I saved state dicts with torch.save(module.state_dict()):

  • an nn.Linear(4, 4);
  • a connector-shaped module (fc1 = Linear(64, 128), LayerNorm(128), fc2 = Linear(128, 128)), in F32 and in BF16.

torch_bin_parity output (dtype, shape, mean and first values of every tensor) is byte-identical between main and this PR for all three files. I do not have a real VibeVoice fine-tune adapter locally, so I did not run end-to-end VibeVoice inference with an adapter. Adapters written with torch.save(module.state_dict()) take the unchanged path shown above.

AI assistance: this change was drafted with an AI coding assistant (Claude) and verified locally with the tests above.

…on-contiguous tensors

The torch .bin reader used by VibeVoice fine-tune adapters kept only the
storage and size arguments of _rebuild_tensor_v2 and always read a tensor
from byte 0 of its storage. torch.save writes views that share a storage
once, each with its own storage_offset, so a checkpoint saved as
{"head": x[:4], "tail": x[4:]} loaded "tail" with head's values, and a
transposed tensor was read in storage order. Neither raised an error.

Read storage_offset and stride, start each tensor at its offset, bound the
offset against the storage size, and reject non-contiguous strides (size-1
dims may carry any stride, as in torch's is_contiguous). This matches what
the RVC checkpoint reader already does. Ordinary module state_dicts (offset
0, contiguous) load exactly as before.

Add torch_bin_storage_offset_test covering 1-D and 2-D views, size-1 dims,
and the rejected transposed and out-of-range cases.
@0xShug0
0xShug0 merged commit 2d600d9 into 0xShug0:main Oct 2, 2026
6 checks passed
@0xShug0

0xShug0 commented Oct 2, 2026

Copy link
Copy Markdown
Owner

@Zhuoxi2000 Thanks! PR merged.

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