Fix integer overflow in single rounding requantization#220
Open
veblush wants to merge 1 commit into
Open
Conversation
mansnils
requested changes
May 22, 2026
Contributor
mansnils
left a comment
There was a problem hiding this comment.
Thanks for this Esun!
Could you also update the date/revision? New version v22.9.1.
| const int64_t new_val = val * (int64_t)multiplier; | ||
|
|
||
| int32_t result = new_val >> (total_shift - 1); | ||
| int64_t result = new_val >> (total_shift - 1); |
Contributor
There was a problem hiding this comment.
I think this should work as well?
Avoiding INT32_MAX + 1 overflow.
const int64_t new_val = (int64_t)val * multiplier;
const int32_t total_shift = 31 - shift;
const int32_t result = (int32_t)(new_val >> (total_shift - 1));
return (result >> 1) + (result & 1);
And likely be more performant.
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
When
CMSIS_NN_USE_SINGLE_ROUNDINGis enabled,arm_nn_requantizesuffered from an integer overflow. The intermediate value evaluated asnew_val >> (total_shift - 1)can require up to 33 bits. Truncating this into anint32_tprematurely flipped the sign bit for large positive values, resulting in catastrophic output errors (e.g., yielding heavily negative numbers instead of saturated maximums).Solution
int32_ttoint64_tto safely hold the 33-bit value.int32_tcast to the final return after the >> 1 shift has brought the value safely back into 32-bit bounds.