Skip to content

[FIX][TOPI] Broadcast values in index_put - #20984

Open
YidaWeng wants to merge 1 commit into
apache:mainfrom
YidaWeng:fix/index-put-broadcast-values
Open

YidaWeng wants to merge 1 commit into
apache:mainfrom
YidaWeng:fix/index-put-broadcast-values

Conversation

@YidaWeng

Copy link
Copy Markdown

topi.index_put broadcasts the index tensors together to obtain the indexed
region shape, but it read values at each flat position of that shape without
broadcasting values first. When values needed broadcasting (for example
x[:, [0, 2]] = v with v of shape (2, 1)), the generated kernel indexed
past the end of values and produced wrong values. The Relax index_put
legalization passes values through unchanged, so the bug was reachable from
Relax and from the PyTorch frontend.

Broadcast values to the indexed-region shape with NumPy rules before building
the store, for both the overwrite and accumulate=True paths. This matches
torch.index_put semantics.

Tests:

  • tests/python/topi/test_topi_ir_builder.py: new
    test_index_put_broadcast_values, covering (2, 1), (2,) and scalar
    values with and without accumulation.
  • tests/python/relax/test_op_manipulate.py: new
    test_index_put_broadcast_values, an end-to-end Relax compile/run test with
    indices_0 of shape (2, 1) and values of shape (2, 1).

Local verification:

  • pytest tests/python/topi/test_topi_ir_builder.py tests/python/relax/test_op_manipulate.py -n 8
    -> 171 passed.
  • The new Relax test fails against main's topi.index_put (writes
    [[10, 1, 20], [0, 4, 0]] instead of [[10, 1, 10], [20, 4, 20]]).
  • pre-commit run --files ... passes.

Fixes #20925.

topi.index_put flattened the broadcast index shape and read values at each flat position, but never broadcast values to that shape. Values that needed broadcasting (for example x[:, [0, 2]] = v with v of shape (2, 1)) therefore indexed past the end of values and wrote garbage.

Broadcast values to the indexed-region shape following NumPy rules before building the store, matching torch.index_put semantics for both the overwrite and accumulate paths.

Add topi and Relax regression tests covering (2, 1), (2,) and scalar values, with accumulate disabled and enabled.

This branch has not been deployed

No deployments
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.

[Bug][Relax] x[:, i] = v writes garbage values when v has to be broadcast

1 participant