Fix int32 overflow in elem_count for tensors with >2.1B elements#116
Merged
polvalente merged 4 commits intoJun 14, 2026
Merged
Conversation
polvalente
reviewed
Jun 14, 2026
6f2abf0 to
bba71c1
Compare
polvalente
approved these changes
Jun 14, 2026
polvalente
left a comment
Collaborator
There was a problem hiding this comment.
Thanks for the quick fix!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
elem_countusesstd::accumulatewith anintinitial value:When the initial accumulator value is
int, all intermediate multiplications are performed in 32-bit signed arithmetic. For shapes whose element-count product exceedsINT32_MAX(~2.1B), the product overflows to a negativeint, which is then cast to a largeuint64_tvalue. The binary-size guard infrom_blobthen always fires:Reproduction
google/gemma-4-2b-it(and larger Gemma-4 variants) include a weight calledembed_tokens_per_layerwith shape{262144, 8960}:This causes
elem_count({262144, 8960})to return18,446,744,071,762,394,560instead of2,348,810,240, making it impossible to load the model viaEMLX.Backend.Fix
Seed the accumulator with
uint64_t{1}and usestd::multiplies<uint64_t>so every partial product stays in 64-bit arithmetic:Context
Discovered while implementing Gemma-4 support in Bumblebee: elixir-nx/bumblebee#460.
🤖 Generated with Claude Code