Skip to content

argmin-negation-overflow: fix aten.min.dim indices at dtype-extremal minima#43

Open
arames wants to merge 1 commit into
apple:mainfrom
arames:user/arames/fuzz/argmin-negation-overflow
Open

argmin-negation-overflow: fix aten.min.dim indices at dtype-extremal minima#43
arames wants to merge 1 commit into
apple:mainfrom
arames:user/arames/fuzz/argmin-negation-overflow

Conversation

@arames

@arames arames commented Jul 16, 2026

Copy link
Copy Markdown

Symptom

aten.min.dim returns the wrong indices when the true minimum is a
dtype-extremal integer value (e.g. uint8 min 0, int8 min -128). values
is correct; only indices is wrong. Silent — no crash.

Root cause

replace_min_dim in coreai_torch/_aten_to_core.py computed argmin as
argmax(x * -1). Negation via multiply is not order-reversing at integer
extremes: 0 * -1 == 0 (not the range top) for unsigned, and -128 * -1
overflows int8. So argmax scores the true minimum incorrectly.

Fix

Reverse order for integer dtypes with the bitwise complement ~x = x ^ -1
(broadcasting_bitwise_xor with an all-ones constant) instead of negation.
~x = -x - 1 is a strictly decreasing bijection over the full range of every
integer dtype (signed and unsigned), never overflows, and introduces no new
ties, so argmax(~x) == argmin(x) with first-index-on-tie semantics preserved.
The float path keeps x * -1 (exact, no overflow).

Tests

Adds dtype-extremal coverage (uint8 min 0; int8/int16/int32 dtype-min),
duplicate-minima tie-break, and a float case proving the float path is
unchanged. Reverting the fix fails all integer cases.

replace_min_dim computed argmin as argmax(x * -1), which is wrong at integer
dtype extremes: uint8 min 0 negates to 0 (not the range top), and int8 min
-128 overflows on negation. Reverse order with the bitwise complement
~x = x ^ -1 (broadcasting_bitwise_xor) for integer dtypes -- a strictly
decreasing, overflow-free bijection that preserves first-index tie-breaking;
keep x * -1 for float. Adds dtype-extremal and tie-break coverage.
Comment thread tests/ops/test_ops.py
await validate_numerical_output(model=model, x=x, dynamic_shapes=dynamic_shapes)


class TestMinDimArgminDtypeExtremes:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gokulkrishna98 : Should we split this test file per op? Maybe in a separate commit?

@arames
arames marked this pull request as ready for review July 16, 2026 23:54
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.

1 participant