mirror of
https://github.com/harvard-edge/cs249r_book.git
synced 2026-07-16 06:07:17 -05:00
[PR #1872] [MERGED] fix(tensor): reshape -1 silently truncates when size is not divisible #27333
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/harvard-edge/cs249r_book/pull/1872
Author: @Shashank-Tripathi-07
Created: 6/16/2026
Status: ✅ Merged
Merged: 6/16/2026
Merged by: @profvjreddi
Base:
main← Head:fix/reshape-neg1-divisibility-check📝 Commits (1)
74b2118fix reshape -1 to check divisibility before inferring the dimension📊 Changes
1 file changed (+7 additions, -0 deletions)
View changed files
📝
tinytorch/src/01_tensor/01_tensor.py(+7 -0)📄 Description
What breaks
Tensor.reshape(-1, n)infers the unknown dimension withself.size // known_size(integer division). Whenself.sizeis not divisible byknown_size, floor division silently produces a wrong truncated value.Example:
The element-count guard does eventually catch it, but with a confusing message that doesn't explain why the -1 inference failed. PyTorch raises immediately:
Fix
Check
self.size % known_size != 0before the division and raise a clearValueErrorexplaining that the total size is not divisible by the known dimensions product.Test plan
pytest tinytorch/tests/01_tensor/passesTensor(np.ones(7)).reshape(-1, 3)raisesValueErrorwith clear messageTensor(np.ones(6)).reshape(-1, 3)still works, returns shape(2, 3)🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.