Skip to content

[Fix][Relax][Frontend][Torch] Gather sliced advanced indices jointly in index.Tensor - #21010

Open
Viranshul-P wants to merge 2 commits into
apache:mainfrom
Viranshul-P:fix/torch-index-tensor-sliced-advanced
Open

Viranshul-P wants to merge 2 commits into
apache:mainfrom
Viranshul-P:fix/torch-index-tensor-sliced-advanced

Conversation

@Viranshul-P

Copy link
Copy Markdown

Fixes #20905.

If certain dimensions are sliced and two or more index tensors are provided, then one take is applied per index tensor. It is the outer product of the indices, and x[:, i, j] would have returned all of the tuples (i, j) and not the tuples (i[k], j[k]), but there was no error. The arange fallback failed with "cannot broadcast index shapes" when a sliced size did not broadcast with the index shape.

The take pattern is still used when it results in the same: the indexed dimensions are adjacent and each index tensor varies along its own broadcast axis only, e.g. the decomposed interpolate pattern x[:, :, h (H, 1), w (W,)]. Its IR does not change. Otherwise, the indexed dimensions are placed at the front and collected together with index_tensor, and the broadcast dimensions are placed where PyTorch puts them: in place of the indexed dimensions if they are adjacent, first otherwise.

It has been tested on CPU (llvm):

  • New test_index_tensor_with_sliced_dims (11 cases): 10 fail on main; all pass with the fix. The case that passes on main is the interpolate pattern
  • Of 17 index patterns compared with eager PyTorch, 4 matched on main and 16 match now. The last one is negative indices, which are also wrong on main for x[:, i] and x[i, j], so they are [Bug][Relax][PyTorch] Negative index in x[:, -1] / select reads out of bounds after from_exported_program #20855 and not part of this PR.
  • test_frontend_from_exported_program.py + test_frontend_from_fx.py: 449 pass. test_norm fails on main too with torch 2.15 (amax.default is not supported)
  • pre-commit clean

The patch, tests and verification were completed with the help of AI (Claude Code).

…in index.Tensor

With a sliced dimension and two or more index tensors, `_index_tensor`
applied one `take` per index tensor. That computes the outer product of
the indices, so `x[:, i, j]` returned every (i, j) pair instead of the
pairs (i[k], j[k]), with no error (apache#20905). The arange fallback failed
whenever a sliced size did not broadcast with the index shape.

Keep the take path only when it is exact: the indexed dimensions are
adjacent and each index tensor varies along its own broadcast axis only,
as in the decomposed interpolate pattern x[:, :, h (H, 1), w (W,)].
Otherwise move the indexed dimensions to the front, gather them with
index_tensor, and put the broadcast dimensions where PyTorch does: in
place of the indexed dimensions when they are adjacent, first otherwise.

Fixes apache#20905

Generated-by: Claude Code (Claude Opus 5.5)
@Viranshul-P

Copy link
Copy Markdown
Author

Hi people, could either of you folks take a look at this when you have the time, @tlopex and @mshr-h? Fixes #20905 (x[:, i, j] gives wrong values after import). CI is green.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The advanced-indexing fast path can introduce unwanted output dimensions, while squeezing symbolic extents loses rank information and blocks legalization.

2 open issues
What changed in this PR

Updates TVM’s PyTorch exported-program frontend to gather sliced advanced indices jointly, addressing #20905 and matching PyTorch’s output-dimension placement.

Changes:

  • Replace the arange-based fallback with dimension permutation and joint index_tensor gathering.
  • Preserve sequential take lowering for adjacent, orthogonal index shapes used by interpolation.
  • Add 11 LLVM-gated numerical cases covering sliced and broadcast indexing.
File Description
tests/​python/​relax/​test_frontend_from_exported_program.py Add numerical regression cases for advanced indexing with sliced dimensions.
python/​tvm/​relax/​frontend/​torch/​base_fx_graph_translator.py Update _index_tensor to gather indices jointly and restore output-axis order.

Review effort: Max

return k - offset if k >= offset else -1

own_axes = [own_extent_axis(k, idx) for k, idx in enumerate(adv_indices)]
if adjacent and all(axis is not None for axis in own_axes):

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.

Good catch, reproduced it: (1,1), (2,1), (2,) gave (2, 1, 2, 2). In order to use the take path, the broadcast rank must be equal to the number of indices, otherwise it falls back to index_tensor. Added that case to the test.

if own_axis == -1:
idx = self.block_builder.emit(relax.op.reshape(idx, [1]))
elif idx.ty.ndim > 1:
if is_one(idx.ty.shape.values[own_axis]):

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.

Yes, with dynamic index lengths it lost the rank and didn't compile. It now squeezes explicit axes when the extent isn't a static non-1 value, so the interpolate IR stays the same. Added a dynamic-shape test.

…ex.Tensor

Use sequential takes only when the index broadcast rank equals the number
of index tensors; x[:, i, j, k] with index shapes (1, 1), (2, 1), (2,)
returned (2, 1, 2, 2) instead of (2, 2, 2).

Squeeze explicit axes when an index tensor own extent is symbolic, so the
take keeps a known rank and the module legalizes.

Generated-by: Claude Code (Claude Opus 5.5)
@Viranshul-P

Copy link
Copy Markdown
Author

Hi @tlopex @mshr-h, the two Copilot notes are fixed (each with a test that fails on the old code) and CI is green. Could one of you review when you have time? It fixes #20905, where x[:, i, j] gave wrong values after import.

Written with Claude Code, reviewed by @Viranshul-P.

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][PyTorch] x[:, i, j] returns the outer product of the indices after from_exported_program

2 participants