Skip to content

[Test] Enable XPU for test_decomp cross-reference tests - #193116

Open
libohao1201 wants to merge 9 commits into
pytorch:mainfrom
libohao1201:libo/enable_xpu_for_test_decomp
Open

libohao1201 wants to merge 9 commits into
pytorch:mainfrom
libohao1201:libo/enable_xpu_for_test_decomp

Conversation

@libohao1201

@libohao1201 libohao1201 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

For #114850, we will port test_decomp cross-reference cases to Intel GPU. We could enable Intel GPU with the following methods and try the best to keep the original code styles:

  • Enable XPU variants with instantiate_device_type_tests().

  • Use device-, dtype-, and op-level skip/expectedFailure rules to isolate unsupported operators and known XPU behavior differences instead of disabling the entire test suite.

  • Extend existing CUDA-specific decorators to ("cuda", "xpu") when the same failure, tolerance, or skip policy applies to both devices.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

Summary

Enables the TestDecomp decomposition cross-reference suite on XPU and adds the
XPU-specific excludes / tolerance overrides needed for it to pass. CPU/CUDA
behavior is unchanged.

Changes

test/test_decomp.py

  • do_cross_ref: add a (device.type, None, op.name) test key so device-scoped,
    dtype-agnostic exclude entries actually match (parity with the torch-xpu-ops
    reference). This is a strict superset — the only such entries today are the 3
    new XPU ones below, so CPU/CUDA are unaffected.
  • instantiate_device_type_tests(TestDecomp, globals(), allow_xpu=True).
  • New op_assert_ref_tol_table_xpu overlay, max-combined with the shared
    tolerance table only when the tensors live on XPU, so shared (CPU/CUDA)
    tolerances can never be loosened. Adds a bf16 reflection_pad2d_backward
    entry.
  • Exclude XPU int8/uint8 BLAS ops (baddbmm/addmm/addmv/mv/tensordot/
    __rmatmul__): oneDNN uses saturated arithmetic while the decompositions wrap
    modularly. Exclude max_pool1d/max_pool2d backward and
    max_pool2d_with_indices_backward on XPU.

torch/testing/_internal/common_methods_invocations.py

  • Extend existing CUDA-only expectedFailure / toleranceOverride / skip
    decorators to device_type=("cuda", "xpu") where XPU exhibits the same
    numeric behavior (logspace int-cast off-by-one, std_mean, var_mean,
    nn.functional.nll_loss, etc.).

Testing

python -m pytest test/test_decomp.py -v -k TestDecompXPU --tb=short

@libohao1201
libohao1201 requested a review from mruberry as a code owner August 12, 2026 07:42
@pytorch-bot

pytorch-bot Bot commented Aug 12, 2026 •

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

Enables TestDecomp on XPU (allow_xpu=True), adds XPU-specific cross-ref
exclusions with a new (device, None, op) lookup key, and extends existing CUDA
TestDecomp decorators to xpu. Tuple device_type is supported by DecorateInfo,
all excluded names match real OpInfos, test_decomp is not on the XPU blocklist,
and the new key doesn't change any existing entries. One minor issue: a dead xpu
device_type.

Findings (1):

[minor] torch/testing/_internal/common_methods_invocations.py:18525
__rmatmul__ complex64 tolerance override now lists xpu but is still gated by
active_if=TEST_WITH_ROCM, which is never true on XPU builds, so the xpu entry is
dead. Either drop "xpu" or change the gate if XPU needs this tolerance.

Reviewed commit: 511a914 (NOT the current head 165e76c)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ 1 Awaiting Approval, 6 New Failures, 5 Unrelated Failures

As of commit 165e76c with merge base 3afdbd3 (image):

AWAITING APPROVAL - The following workflow needs approval before CI can run:

NEW FAILURES - The following jobs have failed:

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:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@liangel-02
liangel-02 requested a review from guangyey August 13, 2026 15:06
@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 13, 2026
Comment thread test/test_decomp.py Outdated
op_assert_ref_tol_table_xpu = {
# XPU eager reflection_pad2d_backward accumulates slightly larger bfloat16
# rounding error than the decomposition; shared 5e-3 is marginally too tight.
(torch.bfloat16, torch.ops.aten.reflection_pad2d_backward.default): 1e-2,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is it possible to skip torch.ops.aten.reflection_pad2d_backward.default for bfloat16 on XPU.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Remove this change in commit 27f9fe, since this case is already skipped in Opinfo: nn.functional.pad

Comment thread test/test_decomp.py
@@ -448,6 +448,26 @@ def normalize_op_input_output(f, sample, requires_grad=True):
(None, None, "nn.functional.adaptive_max_pool1d"),
(None, None, "nn.functional.adaptive_max_pool2d"),
(None, None, "nn.functional.adaptive_max_pool3d"),
("xpu", None, "max_pool2d_with_indices_backward"),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Does this mean that all data types failed on max_pool2d_with_indices_backward

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yes

@chuanqi129 chuanqi129 added the ciflow/xpu Run XPU CI tasks label Aug 24, 2026
@libohao1201
libohao1201 marked this pull request as draft August 24, 2026 10:05
@libohao1201
libohao1201 force-pushed the libo/enable_xpu_for_test_decomp branch from 8e603c9 to 511a914 Compare August 25, 2026 02:21
@pytorch-bot

pytorch-bot Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

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

@libohao1201
libohao1201 marked this pull request as ready for review August 26, 2026 08:03
@daisyden
daisyden requested a review from jansel September 7, 2026 05:36
@jansel jansel added the topic: not user facing topic category label Sep 7, 2026
@daisyden daisyden changed the title Enable XPU for test_decomp cross-reference tests [Test] Enable XPU for test_decomp cross-reference tests Sep 29, 2026
@jansel jansel added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 7, 2026
@github-actions github-actions 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 Oct 7, 2026

@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 511a914: nothing blocking; ready for human review.

Enables TestDecomp on XPU (allow_xpu=True), adds XPU-specific cross-ref exclusions with a new (device, None, op) lookup key, and extends existing CUDA TestDecomp decorators to xpu. Tuple device_type is supported by DecorateInfo, all excluded names match real OpInfos, test_decomp is not on the XPU blocklist, and the new key doesn't change any existing entries. One minor issue: a dead xpu device_type.

⚪ 1 non-blocking finding

https://github.com/pytorch/pytorch/blob/511a9147c8d82462603a8cb0bbf3ca96461a958b/torch/testing/_internal/common_methods_invocations.py#L18525

rmatmul complex64 tolerance override now lists xpu but is still gated by active_if=TEST_WITH_ROCM, which is never true on XPU builds, so the xpu entry is dead. Either drop "xpu" or change the gate if XPU needs this tolerance.

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

pytorchmergebot pushed a commit that referenced this pull request Oct 15, 2026
… device-agnostic instead of backend-enumerated (#197530)

## Summary

`log_sigmoid_forward` returns `(output, buffer)`. The buffer is only consumed
by the CPU backward kernel (`log_sigmoid_backward_cpu`); the CUDA/XPU/MPS
forward kernels (`log_sigmoid_forward_{cuda,mps}`) allocate an empty `(0,)`
buffer and ignore its contents (the "buffer is only used by CPU dispatch, we
just ignore it here" NOTE also appears in some backward and out variants, e.g.
`log_sigmoid_backward_cuda` and `log_sigmoid_forward_out_mps`). PrivateUse1
(out-of-tree) backends follow the accelerator semantics: we verified on
torch_npu (Ascend) that the real kernel returns an empty `(0,)` buffer.

The decomposition in `torch/_decomp/decompositions.py` (used for FakeTensor
shape inference under `torch.compile`/export and `CrossRefFakeMode`) decided
the buffer shape by enumerating backends:

    if self.is_cuda or self.is_xpu:
        buffer = self.new_zeros((0,))
    else:
        buffer = z

Every time a new backend was added, someone had to extend this enumeration and
until then FakeTensor inference disagreed with the real kernel, making
`torch.compile`/export/`CrossRefFakeMode` fail with a `MetadataMismatchError`
on that backend: XPU in #141332/#141333, MPS in #195417, and we reproduced the
identical failure on an out-of-tree PrivateUse1 device:

    MetadataMismatchError: When comparing the output of
    aten.log_sigmoid_forward.default on FakeTensor and concrete Tensors, found
    mismatched tensor metadata for output[1]: Shapes torch.Size([0]) and
    torch.Size([4]) are not equal!

This PR makes the empty-buffer set explicit and evidence-backed — cuda/xpu/mps
(source-verified) plus PrivateUse1 (verified on device, where the real kernel
returns `(0,)` and the old enumeration produced a full-shape buffer that broke
`CrossRefFakeMode`) — while **every backend not in that list (XLA, HPU, MTIA,
and any backend whose contract is unverified) keeps the historical full-shape
buffer**: no behavioral delta beyond the two fixes.

## Changes

- `torch/_decomp/decompositions.py` and `torch/_decomp/decompositions_for_jvp.py`
  (the twin copies must stay in lockstep — upstream precedent #141333/#195417):
  the branch now enumerates the evidence-backed empty-buffer devices and keeps
  the historical full-shape default for everything else:

      if self.is_cpu or self.is_meta:
          buffer = z
      elif (
          self.is_cuda
          or self.is_xpu
          or self.is_mps
          or self.device.type == torch._C._get_privateuse1_backend_name()
      ):
          buffer = self.new_zeros((0,))
      else:
          buffer = z

  Design notes: (a) meta tensors stay on the full branch — this op has no Meta
  kernel, so the decomposition defines its meta behavior, and `not
  self.is_cpu` alone would silently flip meta to the empty branch; (b)
  `Tensor.is_privateuseone` is not exposed as a Python property, so the
  PrivateUse1 backend is identified via its registered name
  (`torch._C._get_privateuse1_backend_name()`, called at runtime — no
  import-time freeze); (c) backends whose contract is unverified keep the
  historical default — no behavioral delta beyond the two fixes.
- Added a regression test `TestDecomp::test_log_sigmoid_forward_buffer_shape`
  (in `test/test_decomp.py`, owner: `module: decompositions`) calling the
  production symbols through `FakeTensorMode`: buffer full-shape for cpu,
  empty for cuda, **empty for mps (the discriminating leg — the pre-PR
  enumeration gives a full-shape buffer for mps, so the test fails without
  this fix)**, empty for PrivateUse1 (the backend name is resolved at runtime
  via `torch._C._get_privateuse1_backend_name()` and pinned with an explicit
  `:0` index, so renamed trees are covered and fake creation skips the
  `is_initialized` lookup in `FakeTensor._normalize_fake_device`), full for
  meta. `@onlyCPU` per the file's convention for device-agnostic tests (the
  assertions pivot on fake/meta devices).
- Added the `hw_classification` class attributes `test/test_decomp.py` was
  missing (TestDecomp / DecompOneOffTests → ACCELERATOR, HasDecompTest →
  GENERIC, per the #190991 convention) so the new test is picked up by
  device-parameterized CI runs.
- Removed the two `fake_backward_mps_xfails` entries in `test/test_ops.py`
  for `nn.functional.logsigmoid` and
  `nn.functional.binary_cross_entropy_with_logits` (the latter decomposes
  through `logsigmoid`). They were added on main to mask exactly the
  fake-vs-real MPS buffer mismatch this PR fixes; with the fix in place
  they report unexpected successes. The remaining entries mask unrelated
  mismatches and stay.

| device | before | after | delta |
|---|---|---|---|
| CPU | full buffer | full buffer | none |
| CUDA / XPU | empty `(0,)` | empty `(0,)` | none |
| MPS | full buffer (wrong, mismatched the real kernel) | empty `(0,)` | **fixes the #195417 mismatch** |
| meta (incl. device-less) | full buffer | full buffer | none |
| PrivateUse1 (FakeTensor) | full buffer (wrong, mismatched the real kernel) | empty `(0,)` | **fixes the mismatch** |
| XLA / HPU / MTIA / unknown | full buffer (historical) | full buffer (unchanged) | none — preserved |

## Depends on

- **#190991** (`HardwareClassification` enum) — used by the added labels.
  Already merged; present in trunk.
- No other merge dependencies. Relations, not dependencies: #195417 (same
  condition, enumeration fix — the evidence-backed form here subsumes it) and
  #193116 (XPU enablement of the same suite, orthogonal).

## Not changed

- The `test_meta.py` crossref expected failures for `log_sigmoid_forward` on
  cuda/xpu (#196554-style) are intentionally untouched: those are about
  device-less meta tensors vs real kernels, and meta behavior is unchanged.
- Pre-existing method-level `@onlyCPU` / `@onlyCUDA` gates in
  `test/test_decomp.py` are left untouched — most encode per-method device
  semantics (RNG determinism, precision, CUDA-specific NaN behavior,
  CPU-only reference behavior), a few are legacy CPU scoping that
  device-enablement efforts like #193116 are better positioned to remove.
- `torch_npu` requires no changes: its native `log_sigmoid_forward` already
  returns an empty `(0,)` buffer (verified on device), so the fix aligns
  FakeTensor inference with the real kernel.

## Test plan

- [x] NPU (PrivateUse1, torch_npu 2.13.0+git45fbeae, Ascend 910B3):
      `CrossRefFakeMode` + `F.logsigmoid` raised `MetadataMismatchError`
      before this PR (output[1] `(0,)` vs `(4,)`) and passes after;
      probe `aten.log_sigmoid_forward` buffer stays `(0,)`;
      new UT green on the box (cpu variant; `@onlyCPU` skips the real npu
      variant by design — the in-test fake PrivateUse1 leg resolves to
      `npu:0` on this tree and passes; real-kernel behavior is additionally
      covered by the probes).
- [x] CPU: new UT 1 passed; `test/functorch/test_ops.py -k logsigmoid`
      14 OK; `test_meta.py -k logsigmoid` 12 passed / 14 skipped (xfails
      unchanged).
- [x] CUDA (A100, torch 2.13.0a0): probe `(0,)` unchanged; functorch 28 OK;
      test_meta 52 tests OK (skipped=27); new UT 2 passed (cpu + cuda
      variants, pre-`@onlyCPU` form).
- [ ] CI (lint / unittest shards).

Pull Request resolved: #197530
Approved by: https://github.com/jansel, https://github.com/guangyey
@libohao1201
libohao1201 force-pushed the libo/enable_xpu_for_test_decomp branch from 511a914 to e774539 Compare October 19, 2026 08:12
@libohao1201

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased libo/enable_xpu_for_test_decomp onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout libo/enable_xpu_for_test_decomp && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the libo/enable_xpu_for_test_decomp branch from e774539 to e6ffc00 Compare October 19, 2026 08:16
@etaf

etaf commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@libohao1201

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebase failed due to Command git -C /home/runner/work/pytorch/pytorch rebase --onto refs/remotes/origin/viable/strict e6aeb381195b1dc032bdf216d85023a86ba7075b pull/193116/head returned non-zero exit code 1

Rebasing (1/5)
Rebasing (2/5)
Rebasing (3/5)
Rebasing (4/5)
Auto-merging torch/testing/_internal/common_methods_invocations.py
CONFLICT (content): Merge conflict in torch/testing/_internal/common_methods_invocations.py
error: could not apply b62c5865ce0... test_decomp: skip unsupported XPU complex arange
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Could not apply b62c5865ce0... # test_decomp: skip unsupported XPU complex arange

Raised by https://github.com/pytorch/pytorch/actions/runs/40823068964

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 29, 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

Copy link
Copy Markdown
Collaborator

@libohao1201
libohao1201 force-pushed the libo/enable_xpu_for_test_decomp branch from 3aa63b1 to 143914a Compare October 29, 2026 10:07
- do_cross_ref: add (device.type, None, op.name) test key so device-scoped,
  dtype-agnostic exclude entries match (parity with torch-xpu-ops).
- instantiate_device_type_tests(allow_xpu=True).
- Add XPU tolerance overlay (op_assert_ref_tol_table_xpu), max-combined with
  the shared table so CPU/CUDA tolerances are untouched.
- Exclude XPU int8/uint8 BLAS ops (baddbmm/addmm/addmv/mv/tensordot/__rmatmul__)
  where oneDNN saturates but decompositions wrap; exclude max_pool1d/2d backward
  and max_pool2d_with_indices_backward on XPU.
- Extend CUDA-only expectedFailure/tolerance/skip decorators to ("cuda","xpu")
  where the same numeric behavior applies (logspace int-cast off-by-one,
  std_mean/var_mean, nll_loss, etc.).
…licy

Remove temporary XPU-only tolerance relaxation from op_assert_ref (op_assert_ref_tol_table_xpu + xpu max(atol, ...)).

Why: align with upstream shared tolerance behavior and avoid masking device-specific deltas in the core assertion path.

OpInfo note: no new OpInfo changes in this commit; the reflect-pad comprehensive skip update is already present in prior branch commits.
Test Plan:
No changes detected in lint configuration files. Skipping setup.
Regenerating version...
$ /root/miniforge3/bin/python3.13 -m tools.generate_torch_version --is-debug=false
Regenerating type stubs...
No changes detected in type stub files for Pytorch type stubs.
No hash file for Datapipes type stubs. Regenerating...
$ /root/miniforge3/bin/python3.13 torch/utils/data/datapipes/gen_pyi.py
Type stubs regenerated.
Done.
$ uvx --python 3.10 [email protected] list
$ uvx --python 3.10 [email protected]
ok No lint issues.

Prepared with assistance from an AI tool; the change was reviewed against the XPU issue and PR pytorch#193412 pattern.
@libohao1201
libohao1201 force-pushed the libo/enable_xpu_for_test_decomp branch from 143914a to d63703f Compare October 29, 2026 13:57
libohao1201 and others added 3 commits November 3, 2026 14:49
The grid_sample comprehensive XPU test now succeeds, so its strict expectedFailure decorator causes CI to fail with Unexpected success. The pinned torch-xpu-ops revision includes the 5-D bicubic implementation from intel/torch-xpu-ops#5511, addressing the limitation tracked in issues pytorch#5452 and pytorch#5542.

Remove only the TestDecomp/test_comprehensive XPU expectedFailure; retain all other suite annotations and numerical tolerances. Verified all four float16, bfloat16, float32 and float64 cases on XPU with torch 2.16.0.dev20261028+xpu.

Co-authored-by: Copilot <[email protected]>
Resolve the FLAKE8 E127 diagnostic reported by PR 193116 CI. File linters pass for test_decomp.py and common_methods_invocations.py; all four comprehensive grid_sample XPU dtypes still pass.

Co-authored-by: Copilot <[email protected]>
The XPU arange int64 and linalg.matrix_sqrth cases pass on current XPU. Remove their OpInfo-wide skips so enabled test suites exercise them.

Co-authored-by: Copilot <[email protected]>
daisyden added a commit to daisyden/pytorch that referenced this pull request Nov 12, 2026
…rence tests)

Authored with AI assistant (opencode).
@libohao1201

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebase failed due to Command git -C /home/runner/work/pytorch/pytorch rebase --onto refs/remotes/origin/viable/strict 3afdbd3b95ecc89f9113968991569dd7412a2a79 pull/193116/head returned non-zero exit code 1

Rebasing (1/9)
Auto-merging test/test_decomp.py
Auto-merging torch/testing/_internal/common_methods_invocations.py
CONFLICT (content): Merge conflict in torch/testing/_internal/common_methods_invocations.py
error: could not apply 06fae15bbcd... Enable XPU for test_decomp cross-reference tests
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Could not apply 06fae15bbcd... # Enable XPU for test_decomp cross-reference tests

Raised by https://github.com/pytorch/pytorch/actions/runs/45786201306

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

ciflow/trunk Trigger trunk jobs on your pull request ciflow/xpu Run XPU CI tasks 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

Status: No status

Development

Successfully merging this pull request may close these issues.

8 participants