[MPS] Fix sum reduction saturated cast for integer overflow#37
Draft
wdvr wants to merge 1 commit into
Draft
Conversation
… cast for MPS sum reduction MPS backend's sum reduction was using MPSGraph's castTensor which performs saturated casting (clamps to type range), causing incorrect results for integer overflow. For example, summing uint8 values [255, 2, 1, 5, 3, 6] returned 255 (saturated) instead of 16 (wrapping). This adds modular arithmetic (floor-modulo) before the final cast for small integer types (uint8, int8, int16), matching CPU's wrapping behavior: - Unsigned: value - floor(value / range) * range - Signed: shift to unsigned, modulo, shift back Fixes pytorch#179415
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.
Fixes pytorch#179415
Problem
MPS backend's
sumreduction uses[MPSGraph castTensor:toType:]to convert the float32 reduction result back to the original integer dtype. This API performs saturated casting (clamps to type range), but CPU uses wrapping (preserves only least significant bits).Example:
Fix
Before the final
castTensorcall inreduction_out_mps(), apply floor-modulo wrapping for small integer output types (uint8, int8, int16):value - floor(value / range) * range(equivalent tovalue % range)This ensures the float32 value is already within the valid type range before the saturated cast, making both casts equivalent.
Test plan
test_sum_integer_overflow_wrappingintest/test_mps.py[255, 2, 1, 5, 3, 6].sum() == 16[127, 1].sum() == -128