Skip to content

Fix Inductor gather bounds for negative indices - #184287

Closed
jansel wants to merge 2 commits into
gh/jansel/804/basefrom
gh/jansel/804/head
Closed

jansel wants to merge 2 commits into
gh/jansel/804/basefrom
gh/jansel/804/head

Conversation

@jansel

@jansel jansel commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Inductor should preserve eager gather/NLLLoss bounds semantics when negative indices are not valid inputs, including symbolic and CSE index paths.

Fixes #135546

Generated by my agent

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @mlazos

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/184287

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (1 Unrelated Failure)

As of commit 6ad6290 with merge base 4908f4e (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@jansel

jansel commented May 18, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 18, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 3m 0s —— View job


Review: Fix Inductor gather bounds for negative indices

  • Gather context and read changed files
  • Analyze the fix for correctness
  • Review test coverage
  • Post review feedback

Summary: This PR correctly fixes a semantic mismatch between eager and compiled torch.gather (and related ops like NLLLoss) for negative indices. The fix is clean, minimal, and well-tested.


Analysis

The bug (two interrelated issues):

  1. lowering.py: gather was calling ops.indirect_indexing(index_loader(idx), size[dim]) with the default wrap_neg=True. In eager mode, torch.gather raises an error for negative indices (idx_dim >= 0 && idx_dim < index_upper_bound in ScatterGatherKernel.cpp:116). Inductor was silently wrapping negative indices, making compiled code return wrong results instead of catching the bug.

  2. common.py (CSE path): When wrap_neg=False and var.bounds.lower < 0, the old code entered the wrapping block but took the else branch which just set stm = var — then fell through to the bounds propagation code. This was a no-op for the variable itself, but the code path was confusing and the bounds assertion at line 2823 could be incorrectly influenced since var was reassigned via cse.generate.

  3. index_propagation.py (symbolic path): The old code allowed can_prove_lower = True if -size <= expr, even when wrap_neg=False. This proof is only valid when wrapping will occur (since -size + size = 0). Without wrapping, we must prove 0 <= expr to skip the lower bounds assertion.

The fixes:

File Change Correctness
lowering.py:4192 wrap_neg=False for gather Correct — matches eager semantics
common.py:2792 if var.bounds.lower < 0 and wrap_neg: Correct — skip wrapping entirely when not needed
index_propagation.py:363-368 Guard -size <= expr proof behind wrap_neg Correct — this proof is invalid without wrapping

Feedback

Looks good overall. The logic is sound and the changes are minimal. A few observations:

  1. Test coverage is solid — four new test functions covering both gather and cross_entropy_loss, each with both runtime-computed indices and torch.arange-generated indices (hitting both the CSE and symbolic index propagation paths). They run across 2D/3D shapes and static/dynamic modes.

  2. Minor question on common.py bounds assertion (line 2823): After the fix, when wrap_neg=False and var.bounds.lower < 0, we skip the wrapping block entirely, so var retains its original bounds. Then assert_lower = not (var.bounds.lower >= 0) will be True, correctly triggering a lower-bounds assertion. This is the right behavior.

  3. cross_entropy_loss test functions — These use target = y[:x.shape[0]] - 1 producing negative targets, which flow through nll_loss decomposition into advanced indexing. The "generated" variants use torch.arange(...) - 1 which exercises the symbolic index propagation path (since the index expression is statically analyzable). Good coverage of both paths.

  4. No changes needed for scatter_reduce_ (lowering.py:4772) — it already uses wrap_neg=False, so it was already correct.

LGTM — no issues found. The PR is well-scoped, fixes a real correctness issue (compiled code silently producing wrong results when eager would error), and has comprehensive tests.


[ghstack-poisoned]
jansel added a commit that referenced this pull request May 19, 2026
Inductor should preserve eager gather/NLLLoss bounds semantics when negative indices are not valid inputs, including symbolic and CSE index paths.

Fixes #135546

Generated by my agent

ghstack-source-id: e7ea200
Pull-Request: #184287
@jansel
jansel marked this pull request as ready for review May 19, 2026 20:16
@jansel

jansel commented May 20, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label May 20, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit to khushi-411/pytorch that referenced this pull request May 20, 2026
Inductor should preserve eager gather/NLLLoss bounds semantics when negative indices are not valid inputs, including symbolic and CSE index paths.

Fixes pytorch#135546

Generated by my agent

Pull Request resolved: pytorch#184287
Approved by: https://github.com/oulgen
pytorchmergebot pushed a commit to weishi-deng/pytorch that referenced this pull request May 21, 2026
Inductor should preserve eager gather/NLLLoss bounds semantics when negative indices are not valid inputs, including symbolic and CSE index paths.

Fixes pytorch#135546

Generated by my agent

Pull Request resolved: pytorch#184287
Approved by: https://github.com/oulgen
@github-actions
github-actions Bot deleted the gh/jansel/804/head branch June 20, 2026 02:27
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Inductor should preserve eager gather/NLLLoss bounds semantics when negative indices are not valid inputs, including symbolic and CSE index paths.

Fixes pytorch#135546

Generated by my agent

Pull Request resolved: pytorch#184287
Approved by: https://github.com/oulgen
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Inductor should preserve eager gather/NLLLoss bounds semantics when negative indices are not valid inputs, including symbolic and CSE index paths.

Fixes pytorch#135546

Generated by my agent

Pull Request resolved: pytorch#184287
Approved by: https://github.com/oulgen
pytorchmergebot pushed a commit that referenced this pull request Aug 26, 2026
Human context: fix for #194490) exposed by #184287 although the underlying cause was prior CSE / loop hoisting logic (and ultimately the fact that this is all tied to one very complicated file)..

Triton load placement and CSE lifetime used separate heuristics. An indirect load emitted inside a loop could consequently remain cached after loop closure and be reused by an epilogue even though its temporary did not dominate that use.

Use the selected load buffer as the source of truth for whether a CSE value survives loop closure. Also prevent loads carrying reduction masks from being hoisted before those masks are defined.

Test Plan:

```
python test/inductor/test_indexing.py ReductionInvariantIndexingTests
python test/inductor/test_codegen_triton.py -k reduction_invariant_load_indexing
git diff --check
lintrunner -a test/inductor/test_indexing.py torch/_inductor/codegen/triton.py
```

The two test commands and git diff check pass. Lintrunner was invoked, but Pyrefly failed on unrelated repository-wide missing-attribute errors because this detached worktree has no initialized lintrunner data.

AI-Assisted: Author reviewed and validated all AI-generated content.

Pull Request resolved: #194786
Approved by: https://github.com/atalman, https://github.com/karthickai
atalman added a commit that referenced this pull request Aug 26, 2026
…me (#194786) (#194833)

* [inductor] Fix loop-local load CSE lifetime (#194786)

Manual cherry-pick of 60598ed (#194786) onto release/2.14.

Triton load placement and CSE lifetime used separate heuristics. An indirect
load emitted inside a loop could remain cached after loop closure and be
reused by an epilogue even though its temporary did not dominate that use. Use
the selected load buffer as the source of truth for whether a CSE value
survives loop closure, and stop hoisting loads that carry reduction masks
before those masks are defined.

Conflict resolution:

* torch/_inductor/codegen/triton.py: upstream also deletes the
  reduction_axes_omitted bookkeeping added by #184287, which is not on this
  branch, so that deletion is already satisfied and the surrounding code is
  left as-is. The two substantive changes (the has_rmask() guard on lifting,
  and load_buffer is self.body as the CSE-lifetime test) apply unchanged.
* test/inductor/test_indexing.py: upstream adds the regression test to
  ReductionInvariantIndexingTests, a class that #184287 introduced and which
  does not exist here. The regression test is ported verbatim into a new
  TestLoopLocalLoadCSELifetime class with the imports it needs
  (run_and_get_kernels, FileCheck, HAS_CUDA_AND_TRITON, config), all of which
  exist on this branch. The unrelated @parametrize("dense_indexing") hunk is
  dropped, since it belongs to a #184287 test.

Fixes #194490 on the release branch.

* Fix PYFMT import ordering

---------

Co-authored-by: eellison <[email protected]>
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
Human context: fix for pytorch#194490) exposed by pytorch#184287 although the underlying cause was prior CSE / loop hoisting logic (and ultimately the fact that this is all tied to one very complicated file)..

Triton load placement and CSE lifetime used separate heuristics. An indirect load emitted inside a loop could consequently remain cached after loop closure and be reused by an epilogue even though its temporary did not dominate that use.

Use the selected load buffer as the source of truth for whether a CSE value survives loop closure. Also prevent loads carrying reduction masks from being hoisted before those masks are defined.

Test Plan:

```
python test/inductor/test_indexing.py ReductionInvariantIndexingTests
python test/inductor/test_codegen_triton.py -k reduction_invariant_load_indexing
git diff --check
lintrunner -a test/inductor/test_indexing.py torch/_inductor/codegen/triton.py
```

The two test commands and git diff check pass. Lintrunner was invoked, but Pyrefly failed on unrelated repository-wide missing-attribute errors because this detached worktree has no initialized lintrunner data.

AI-Assisted: Author reviewed and validated all AI-generated content.

Pull Request resolved: pytorch#194786
Approved by: https://github.com/atalman, https://github.com/karthickai
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor release notes: inductor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants