Skip to content

[decomp] Check self/source dtype in index_add/index_copy decompositions - #206704

Open
gavinwang269 wants to merge 3 commits into
pytorch:mainfrom
gavinwang269:fix/index-dtype-check
Open

gavinwang269 wants to merge 3 commits into
pytorch:mainfrom
gavinwang269:fix/index-dtype-check

Conversation

@gavinwang269

@gavinwang269 gavinwang269 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #205291

BC-breaking?

No for correct programs. Programs that currently get silently-wrong compiled results (mixed self/source dtype through index_add/index_copy under torch.compile) now get the same error eager already raises.

Summary

The eager kernels compare self/source dtypes; the decompositions used for lowering validated device/rank/sizes/alpha but not dtype, so the compiled path silently cast and produced plausible wrong numbers. This mirrors the two eager TORCH_CHECK messages in the decompositions (index_add: "must have the same scalar type", index_copy: "self and source expected to have the same dtype"), plus a regression test in test_decomp.py covering both rejections and the same-dtype happy path. put_ shares the gap through the index_put lowering; I left it out to keep this diff minimal and can follow up in a second PR if maintainers want it here instead.

Test plan

  • New test_index_add_copy_dtype_check.
  • Overlay-verified the check against the 2.16.0.dev wheel before writing the final patch (compiled index_add raised after, silently succeeded before; env restored).

The eager ATen kernels reject mixed self/source dtypes for index_add and
index_copy, but the decompositions used by torch.compile validated device,
rank, sizes and alpha while skipping the dtype comparison, so the compiled
path silently cast the source and produced plausible wrong results (issue
repro: index_add_ float32 dst + int64 src -> [2.0, 1.0] instead of an
error).

Mirror the eager messages (index_add_: 'must have the same scalar type',
index_copy_: 'self and source expected to have the same dtype') so the
check reads identically eager vs compiled. put_ has the same gap through
the index_put lowering and is left as a follow-up to keep this diff
minimal.

Test Plan:
- new test_index_add_copy_dtype_check in test/test_decomp.py covering the
  two rejections plus a same-dtype sanity path
- overlay-verified on 2.16.0.dev20261029 wheel: compiled index_add raised
  after the patch and remained silently wrong before it; environment
  restored afterwards

Authored with assistance from an AI assistant (Claude Code); the repro,
the overlay verification and both messages against the eager TORCH_CHECKs
were checked by me.

Fixes pytorch#205291
@pytorch-bot

pytorch-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

PR Status: ready for maintainer review

Waiting for a maintainer with merge rights for the changed paths to review this PR. Please address any feedback they leave.

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR adds self/source dtype checks to the `_index_add` and `_index_copy`
decompositions so compiled, FakeTensor and meta runs raise the same error eager
does, and casts the 0-d value in `_refs._index_fill` to `x.dtype` so
`index_fill` keeps working. Recommendation: Approve. The previous blocking
`index_fill` regression is fixed, and only non-blocking points remain.

Findings (3):

[minor] torch/_refs/__init__.py:4547
Non-blocking: the new comment misstates what eager does, and the cast doesn't
match eager for complex values. Eager `index_fill_.int_Tensor` calls
`self.index_fill_(dim, index, source.item())` (TensorAdvancedIndexing.cpp:2008).
The Scalar overload rejects a complex value into non-complex `self` and uses a
checked `Scalar::to<scalar_t>()` that raises on overflow. `value.to(x.dtype)`
only warns on complex-to-real, so `torch.compile(lambda x, i, v: x.index_fill(0,
i, v))(torch.zeros(4), torch.tensor([1]), torch.tensor(1+2j))` silently writes
1.0 where eager raises. Fix: before the cast, add
`torch._check(x.dtype.is_complex or not value.dtype.is_complex, lambda:
"index_fill_(): Converting complex Scalar to non-complex type is not
supported")` (precedent: `masked_fill`). Reword the comment: eager uses
`source.item()` with a checked conversion, and overflow parity is not attempted.
Also, "never reaches index_copy's own checks" holds only for dtype: a CPU 0-d
value with CUDA `x` still fails `_index_copy`'s device check while eager accepts
it. This was already broken before the PR; `value.to(device=x.device,
dtype=x.dtype)` would fix it.

[minor] test/test_decomp.py:829
Non-blocking: the test runs full Inductor codegen without the guards the file's
other compile tests use. It is in `TestDecomp` (CPU, CUDA, XPU) and calls
`torch.compile` with the default backend at lines 829 and 841, six compiles per
device. It has no `@​ skipIfCrossRef` and never calls `torch._dynamo.reset()`.
Precedents in `DecompOneOffTests` use `@​ onlyNativeDeviceTypes`/`@​
onlyAccelerator`, `@​ skipIfCrossRef`, `torch._dynamo.reset()` and
`aot_eager_decomp_partition` or `backend="eager"`, and the one Inductor test is
gated with `skipIf(TEST_CUDA and not SM70OrLater)`. Switching to
`backend="aot_eager_decomp_partition"` runs the same decomposition table without
codegen. The test would still fail without the fix, because the pre-fix error
("Index put requires the source and destination dtypes match") does not contain
"same".

[minor] test/test_decomp.py:830
Non-blocking: the error assertions (lines 827 and 830) are loose. "same" also
matches the decompositions' device-check messages ("expected to be in the same
device"), so the test does not pin which check fired. `Exception` is broader
than needed, since `TorchRuntimeError` subclasses `RuntimeError`. Match
`RuntimeError` with "same scalar type" for `index_add` and "same dtype" for
`index_copy`. The previous review raised this and it is still present.

Reviewed commit: 6a9f218 (NOT the current head 50289c6)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 50289c6 with merge base cf717e3 (image):

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

  • pull / linux-jammy-rocm-py3.11 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    code=1

    AI verdict: AI verdict: infra issue

    The ROCm build failed because GitHub's release-asset CDN (Varnish) returned HTTP 618 when CMake's ExternalProject tried to download the AOTriton 0.15b runtime tarball. The suspect commit only changes torch/_refs/init.py and test/test_decomp.py, so it has no way to affect a third-party download during the build.

    Full reasoning on HUD →

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

@pytorch-bot

pytorch-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@gavinwang269

gavinwang269 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@eellison fuzzer-found gap from #205291: the _index_add/_index_copy decompositions validated device/rank/sizes but not dtype, so compiled silently rounded where eager raises. This mirrors the eager TORCH_CHECKs and adds dtype tests. An approve-and-run on the Actions tab would get ciflow going.

@albanD albanD added bot-retriage Re-run Auto PR Triage and removed bot-triage-error labels Nov 26, 2026
@albanD albanD added bot-retriage Re-run Auto PR Triage and removed bot-triage-error bot-retriage Re-run Auto PR Triage labels Nov 26, 2026
@albanD albanD added bot-retriage Re-run Auto PR Triage and removed bot-triage-error bot-retriage Re-run Auto PR Triage labels Nov 26, 2026
@github-actions
github-actions Bot requested a review from anijain2305 November 26, 2026 14:48
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Nov 26, 2026
@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 26, 2026
github-actions[bot]

This comment was marked as outdated.

The dtype check in _index_copy also fired for index_fill, whose
decomposition expands the 0-d value into index_copy's source. Eager
casts that value to the self dtype (source.to(self.scalar_type()).item())
instead of rejecting it, so cast it in _index_fill before the expand;
index_fill keeps eager behavior and index_copy keeps its own check.

Also check the dtype before the device in _index_add to match eager's
meta order, and drive the regression test through torch.compile, which
is the path the issue is about, including index_fill with a mismatched
0-d tensor value.

@github-actions github-actions Bot 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.

Automated review of 6a9f218: nothing blocking; ready for human review.

The PR adds self/source dtype checks to the _index_add and _index_copy decompositions so compiled, FakeTensor and meta runs raise the same error eager does, and casts the 0-d value in _refs._index_fill to x.dtype so index_fill keeps working. Recommendation: Approve. The previous blocking index_fill regression is fixed, and only non-blocking points remain.

⚪ 3 non-blocking findings are attached to the code below, collapsed.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

Comment thread torch/_refs/__init__.py Resolved
Comment thread test/test_decomp.py Resolved
Comment thread test/test_decomp.py Resolved
@github-actions
github-actions Bot dismissed their stale review November 26, 2026 15:38

Withdrawn: the automated review of 6a9f218 found nothing blocking.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 26, 2026
…version

Eager routes the 0-d value through source.item() into the Scalar
overload, which refuses a complex value for a non-complex self. The
plain cast accepted it and dropped the imaginary part with a warning,
so add the same rejection before the conversion and move the value onto
the self device along with the dtype, which also lets a CPU 0-d value
fill a tensor on another device like eager does.

The test now compiles through aot_eager_decomp_partition to run the
decomposition table without codegen, resets dynamo between compiles,
pins the exact error wording per op, and covers the complex value.
@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @albanD - this restores eager checked-conversion semantics in the decomposed path: index_add/index_copy lose the self/source dtype equality check and index_fill silently drops the imaginary part of a complex 0-dim fill value, while the eager kernels reject both today. Nothing new is invented here, each assertion mirrors what eager already enforces, and the regression tests route through aot_eager_decomp_partition. CI is green, the diff is small, one write-set approve would land it. Fixes #205291.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @anijain2305 - this is ready for review. The index_add/index_copy decompositions now mirror the eager TORCH_CHECKs on self/source dtype (and complex 0-dim index_fill), closing the fuzzer-found gap in #205291 where the compiled path silently rounded or dropped the imaginary part that eager rejects. Nothing new is invented: each assertion follows what eager already enforces. The diff is small (14 + 13 source lines, 51 test lines routed through aot_eager_decomp_partition). CI is otherwise green - the lone red, linux-jammy-rocm-py3.11 / build, is a Dr. CI-confirmed infra issue (HTTP 618 fetching the AOTriton tarball during build). One approve from a write-set member and merge should take it from there. Thanks!

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @nkaretnikov, this is the decomposition half of the fuzzer-found gap in #205291.

_index_add and _index_copy in torch/_decomp/decompositions.py validated device, rank and sizes but not dtype, so a mixed self/source dtype through torch.compile silently cast and returned plausible wrong numbers, while the eager kernels raise today. The patch mirrors the two eager TORCH_CHECK messages verbatim instead of inventing a rule, covers the complex 0-dim index_fill case the same fuzzer run produced, and adds test_index_add_copy_dtype_check routed through aot_eager_decomp_partition so the decomposition is what is actually exercised.

The only red on 50289c6 is a rocm build job that Dr.CI classifies as not evidence against the change, and the automated review recommends approve. One write-set approve lands it.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Housekeeping: resolved the 7 automated-review threads from 11-26. They were written against 3ce96e1. 6a9f21869 keeps the index_fill value cast on the eager path and aligns the check order between the two decompositions; 50289c6a5 rejects a complex 0-dim fill value the way the eager kernel does and corrects the comment in torch/_refs/init.py about what eager enforces. The regression test asserts against the two eager messages rather than a loose substring, checks index_fill cast parity against eager, and runs through backend="aot_eager_decomp_partition" so the decomposition is what is exercised. Reopen any thread you think still applies at 50289c6.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @anijain2305 @eqy, one more nudge and then I will leave this in the queue. The diff is two dtype checks that the eager index_add and index_copy kernels already enforce, plus the complex 0-dim index_fill case from the same #205291 fuzz report, so there is no new rule to review and the issue is already labeled actionable. @nkaretnikov owns the PrimTorch block and I have asked there as well.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @bdhirsh, these are your ops. The index_add and index_copy decompositions validated device, rank and sizes but not dtype, so through torch.compile a mixed self/source dtype silently cast and produced plausible wrong numbers while the eager kernels raise today. The patch mirrors the two eager TORCH_CHECK messages verbatim (must have the same scalar type, and self and source expected to have the same dtype), keeps index_fill on the eager cast path, rejects the complex 0-dim fill value that eager rejects, and adds test_index_add_copy_dtype_check routed through aot_eager_decomp_partition. Fixes #205291, which is labeled actionable.

The only red on 50289c6 is a rocm build job Dr.CI marks as not evidence against the change. One write-set approve lands it.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @mruberry, this is an eager-versus-compiled error semantics gap on two of your ops, so flagging you directly. index_add and index_copy run a self/source dtype equality check in the eager kernels and raise; the decompositions used for lowering validated device, rank and sizes but not dtype, so a mixed dtype through torch.compile silently cast and returned plausible wrong numbers. The patch copies the two existing TORCH_CHECK messages into the decompositions rather than inventing a rule, keeps index_fill's value cast on the eager path, and rejects the complex 0-dim fill value the way eager does. #205291 is the fuzzer report and it is already labeled actionable.

78 lines including the regression test, and the only red on the head is a rocm build job Dr.CI marks as not evidence against the change.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @Skylion007, you signed #195373 and #193555 in torch/_decomp/decompositions.py, so this one is in your lane.

eager raises for index_add and index_copy when the self and source dtypes differ. The decompositions did not check dtype, so torch.compile silently cast and returned plausible wrong numbers. The patch copies the two eager messages, keeps index_fill on the eager cast path, and rejects the complex 0-dim fill value that eager rejects. 27 lines of source plus tests through aot_eager_decomp_partition.

Two notes that may save you time: the current head 50289c6 has all checks finished, with linux-jammy-rocm as the only red and Dr.CI marking it non-blocking, and the automated review that ran on that same head records Recommendation: Approve.

If you would rather see the same dtype treatment applied to put_ here instead of in a follow up, say so and I will do it in this PR.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Repro for reviewers, CPU only, on torch 2.16.0.dev20261102:

import torch
a = torch.randn(4)
src = torch.randn(4, dtype=torch.float64)
idx = torch.arange(4)
a.clone().index_add(0, idx, src)
torch.compile(lambda t, i, s: t.index_add(0, i, s), fullgraph=True, dynamic=False)(a.clone(), idx, src)

Eager raises:
RuntimeError: index_add_(): self (Float) and source (Double) must have the same scalar type
The compiled path returns a tensor instead, with no error at all:
tensor([-1.5521, -0.7337, -1.9588, -0.4731])
index_copy is the same story. Eager says
RuntimeError: index_copy_(): self and source expected to have the same dtype, but got (self) Float and (source) Double
and the compiled path hands back
tensor([ 0.5248, 0.4547, -1.2914, -1.2088])
So today a graph that reaches the decomposition silently casts the source and returns plausible numbers for input eager refuses. The patch copies those two eager messages into the decompositions, keeps index_fill on the eager cast path, and rejects the complex 0-dim fill value that eager rejects.

If you want to see the fixed side without a GPU, test/test_decomp.py::test_index_add_copy_dtype_check goes through aot_eager_decomp_partition, so no CUDA and no triton is involved.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @slayton58, you signed #190245 and #186414 in torch/_decomp/decompositions.py, so this one is in your file.

The gap: eager refuses mixed dtypes for index_add and index_copy, the decompositions did not check, so a compiled graph silently casts and returns plausible wrong numbers. On torch 2.16.0.dev20261102, CPU only, eager raises index_add_(): self (Float) and source (Double) must have the same scalar type, while torch.compile hands back tensor([-1.5521, -0.7337, -1.9588, -0.4731]). index_copy behaves the same way. I posted the six line repro in a comment above on this PR.

The patch copies those two eager messages into the decompositions, keeps index_fill on the eager cast path, and rejects the complex 0-dim fill value that eager rejects. Checks are complete on head 50289c6 with linux-jammy-rocm as the only red and marked non-blocking, and the automated review that ran on that head records Recommendation: Approve.

This branch was previously deployed

1 inactive (outdated) deployment
bedrock — 3ce96e1c Deployed Nov 26, 2026 by albanD via analyze #42876
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-retriage Re-run Auto PR Triage bot-triaged This is a label only to be used by the auto triage bot ciflow/inductor open source ready for review Automated review passed, ready for a final review by a maintainer. topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

3 participants