Skip to content

[Feature Refactoring] Make MetalKernel launch device overridable via a class attribute - #195809

Closed
gavinwang269 wants to merge 1 commit into
pytorch:mainfrom
gavinwang269:inductor/mps-codegen-device-decoupling
Closed

gavinwang269 wants to merge 1 commit into
pytorch:mainfrom
gavinwang269:inductor/mps-codegen-device-decoupling

Conversation

@gavinwang269

@gavinwang269 gavinwang269 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

MetalKernel.call_kernel() is the only kernel-call site across the in-tree Inductor codegen backends that pins a device literal: it unconditionally passes device=torch.device("mps") to generate_kernel_call(). For comparison, Triton and Cpp rely on the graph's current device (the wrapper default), and Halide passes a computed device value.

An out-of-tree backend that reuses the Metal-style kernel plumbing (subclassing MetalKernel for a device that follows the same one-thread-per-element launch convention) currently has to copy the whole call_kernel() body just to retarget the launch device.

This is one of the small patches that remove device hardcodings from codegen so out-of-tree backends need fewer monkey-patches.

Changes

  • Add a device_type = "mps" class attribute to MetalKernel, next to the existing class-level knobs (max_threadgroup_size, simd_group_size, ...).
  • call_kernel() derives the launch device from self.device_type instead of the literal.
  • Test: a single assertion on test/inductor/test_mps_basic.py's existing MPS-gated MPSBasicTests class (assertEqual(MetalKernel.device_type, "mps")). An earlier version of this PR shipped a larger test block that drove call_kernel() with a stubbed kernel state and a mocked wrapper; the review correctly found that it does not run in the Linux CI shards this file targets, and that its two behavioral assertions were a tautology and an assertion of a meta-device retarget the real wrapper rejects. Those were dropped; the existing end-to-end MPS tests already drive call_kernel(), so the only genuinely new thing to pin is the class attribute default, which is one line.

An alternative considered was to drop the device= kwarg and let the wrapper default to V.graph.get_current_device_or_throw(), like Triton (wrapper.py already does device = device or V.graph.get_current_device_or_throw()). I did not take that path: it changes the source of truth for the launch device from the kernel that emitted the call to whatever the graph's current device happens to be at wrapper time, and with it the failure mode for an unimplemented device type, which is a behavior question rather than a decoupling one. The kernel-side class attribute keeps the value sourced from the kernel and gives subclasses a single explicit knob.

Behavior

No change for in-tree backends. The default attribute value yields the exact same torch.device("mps") object as before, and the MPS branch of PythonWrapperCodegen._generate_kernel_call_helper() only dispatches on device.type (it never consumes the value or the index for mps). No other backend references the touched symbols, and the change adds no import-time device probing.

Test Plan

cd /tmp && unset PYTHONPATH
python -m pytest <repo>/test/inductor/test_mps_basic.py -q
# 60 collected, 60 skipped (torch 2.15.0.dev20260819+cpu wheel, changed mps.py overlaid)
# base commit 00ea4089 on the same command: 59 collected, 59 skipped
# (the +1 is the single new MPS-gated assertion; on Linux it is skipped like the
#  other 59 cases and runs on the macOS --mps shards, where MPSBasicTests is
#  gated by torch.backends.mps.is_available())
python -m pytest <repo>/test/inductor/test_mps_basic.py --collect-only -k metal_kernel
# test_mps_basic.py::MPSBasicTests::test_metal_kernel_device_type
lintrunner -a --take PYFMT,RUFF torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# ok No lint issues.

PYREFLY note: on this unbuilt source tree it emits ~20k missing-attribute errors against unmodified lines on both the base commit and this diff, so it cannot discriminate locally; CI's pyrefly job covers torch/, where the only functional lines changed live. No NPU-side verification is claimed: torch_npu does not reference this file, and the diff does not change generated code for any in-tree backend.

Notes

MetalOverrides._initialize_pointwise_overrides("mps") is intentionally left unchanged: every backend passes its codegen backend name there ("cpp", "cppvec", "halide", "triton", "mps"), so it is a table key, not a device hardcoding.

A subclass retargeting device_type is not usable end-to-end on its own yet: PythonWrapperCodegen._generate_kernel_call_helper() dispatches on device.type not in ("cuda", "xpu") and raises for unknown types, and CppWrapperMps._generate_kernel_call_helper() asserts device.type == "mps" while its shader-library pass skips non-mps KernelCallLines. This PR is deliberately kernel-side only to keep the diff reviewable in isolation; the wrapper-side change (a negated dispatch like the merged #187939 used for ShardedTensor, plus the CppWrapperMps assert) touches the cpu/cuda/xpu paths and deserves its own PR. This is noted in the code comment above device_type as well. If you would rather the attribute land after that wrapper-side change so it is exercisable, I am glad to restack this on top of it.

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

@pytorch-bot

pytorch-bot Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (3 Unrelated Failures)

As of commit b9424db with merge base 123739a (image):

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

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

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/torchtitan Run TorchTitan integration tests module: inductor labels Sep 3, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented Sep 3, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/mps
  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

1 similar comment
@pytorch-bot

pytorch-bot Bot commented Sep 3, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/mps
  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@gavinwang269
gavinwang269 force-pushed the inductor/mps-codegen-device-decoupling branch 7 times, most recently from 5873ccf to b2c4ea9 Compare September 3, 2026 08:59
@jansel

jansel commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 23m 11s —— View job


Reviewed — the one-line codegen change is fine, but the 87 lines of new tests don't run in CI, are tautological, and the "meta" case asserts behavior that would actually raise against the real wrapper.

Full review

PR Review: #195809

Summary

Replaces the torch.device("mps") literal in MetalKernel.call_kernel() with a new device_type class attribute, plus 87 lines of new tests. The production change (torch/_inductor/codegen/mps.py:564, :1165) is behavior-preserving and correctly named (no device_type in the MetalKernel -> SIMDKernel -> Kernel MRO, so nothing is shadowed). The test additions, however, are the bulk of the diff and have substantive problems: they never execute in CI, one of them is a tautology, and the other asserts a retarget scenario that would raise on the real wrapper.

Testing

  • The GENERIC test never runs in CI. test/inductor/test_mps_basic.py:593 gates the whole module behind if torch.backends.mps.is_available(): run_tests(...), and run_test.py:649 invokes the file as python inductor/test_mps_basic.py. On Linux inductor shards the guard is false, so zero tests are collected regardless of hw_classification. The --hw-classification flag (run_test.py:595) is not passed by anything in .ci/ or .github/, so HardwareClassification.GENERIC here is inert metadata, not a platform opt-in. The PR's test plan (61 collected, 2 passed) comes from a direct pytest invocation that CI never performs — on macOS both new classes run, and on Linux neither does. The claim that "the +2 collected are the new GENERIC cases" does not describe any CI job. Either move these cases to a file that actually runs on CPU shards (e.g. test/inductor/test_torchinductor.py-adjacent codegen tests) or drop them.

  • test_call_kernel_follows_class_device_type (line 553) asserts something that cannot happen. With device_type = "meta", the real PythonWrapperCodegen._generate_kernel_call_helper() hits wrapper.py:4342 (not triton and device.type not in ("cuda", "xpu")), falls past the cpu/mps branches, and raises RuntimeError("device meta nyi") at wrapper.py:4349; on the AOTI path cpp_wrapper_mps.py:82-83 raises AssertionError. The test only passes because wrapper is a MagicMock. So the test encodes ""meta" flows through call_kernel()" as a contract, while the actual system rejects it. The PR description acknowledges these two wrapper-side checks and defers them — which means today no value other than "mps" is usable, and the test is asserting the plumbing works for a case that provably doesn't. This should either be deferred until the wrapper-side follow-ups land, or the assertion should be limited to what is true (torch.device(self.device_type) is what gets forwarded) without implying "meta" is a valid target.

  • test_default_kernel_binds_primary_device (line 575) is a tautology. It reduces to torch.device("mps").type == torch.device("mps:0").type, i.e. "mps" == "mps", plus .index is None — which is a property of how torch.device("mps") is constructed, not of the code under test. It cannot fail unless test_default_device_type_is_mps (line 549) also fails. Standing up the full mock harness, instantiate_device_type_tests, and an MPS-only classification to reach that comparison is not buying coverage. Note also that the case is classified HardwareClassification.MPS and gated on torch.backends.mps.is_available() while touching no MPS hardware at all.

  • The white-box stub will rot silently. _stub_kernel (line 514) bypasses __init__ via __new__ and hand-supplies six internal attributes of MetalKernel/SIMDKernel. Every loop it feeds is empty, so call_kernel() reaches line 1165 with args == [] and arg_types == [] and nothing about argument marshalling, threadgroup sizing, or the error_buf_idx path is exercised. When call_kernel() starts reading any new state, this stub fails in a way that looks like a product bug. The rest of this file tests codegen by asserting on generated source with FileCheck (e.g. lines 490-506); an assertion on the generated .run(...) line would match the file's convention and survive refactors. More directly: every existing MPS test in this file already drives call_kernel() end-to-end, so a broken default is already covered — assertEqual(MetalKernel.device_type, "mps") is the only genuinely new assertion the PR needs.

  • kernel.active_range_trees = list (line 529) is dead code and misleading. The real SIMDKernel.active_range_trees() (torch/_inductor/codegen/simd.py:1217-1222) already returns [] given range_trees = [] and inside_reduction = False, so the override changes nothing while making it look as though a method had to be defeated. Relatedly, sizevars=[] (line 520) is type-wrong: the real KernelArgs.sizevars is a dict (torch/_inductor/codegen/common.py:1724).

  • @unittest.skipUnless(torch.backends.mps.is_available(), ...) at line 568 is redundant with only_for=("mps",) at line 586 — instantiate_device_type_tests generates no class at all on a non-MPS host, so the decorator is unreachable.

Fix this →

API Design

  • device_type is added as a subclass knob for a value no subclass can currently change. As the PR description itself notes, a subclass that sets it to anything but "mps" immediately hits RuntimeError(f"device {device.type} nyi") (wrapper.py:4349) and cpp_wrapper_mps.py:82-83/:266. There is no in-tree subclass of MetalKernel. This is configuration that is not reachable end-to-end, which is what CLAUDE.md warns against ("Don't design for hypothetical future requirements"). Landing the wrapper-side changes first — or in the same PR — would make the attribute actually mean something. As-is, the only observable effect is the removal of a string literal.

  • Worth reconsidering the rejected alternative, because it is a smaller diff, not a larger one: wrapper.py:4300 already does device = device or V.graph.get_current_device_or_throw(), so deleting the device= kwarg entirely is a -1/+0 change that achieves the stated out-of-tree goal with no new public attribute, and matches TritonKernel.call_kernel() and HalideKernel.call_kernel(). The counter-argument in the description (avoiding a dependency on scheduler state, preserving the explicit-device failure mode) is reasonable, but note generate_kernel_call already reads V.graph.scheduler.current_stream_idx at wrapper.py:4301 on this exact path, so the scheduler dependency is not actually being avoided. If you keep the class attribute, that reasoning belongs in the code comment at mps.py:561-563, not only in the PR description.

Recommendation

Request Changes

The production change is sound. The blocker is the test block: it does not execute in the CI configuration the PR's test plan describes, its retarget assertion contradicts what the real wrapper does with a non-mps device, and its default-device assertion cannot fail. Trimming it to the single meaningful assertion, or landing it together with the wrapper-side device checks so the new knob is genuinely exercisable, would resolve this.

| Branch: `inductor/mps-codegen-device-decoupling`

…attribute

## Motivation

`MetalKernel.call_kernel()` is the only kernel-call site across the in-tree Inductor codegen backends that pins a device literal: it unconditionally passes `device=torch.device("mps")` to `generate_kernel_call()`. For comparison, Triton and Cpp rely on the graph's current device (the wrapper default), and Halide passes a computed device value.

An out-of-tree backend that reuses the Metal-style kernel plumbing (subclassing `MetalKernel` for a device that follows the same one-thread-per-element launch convention) currently has to copy the whole `call_kernel()` body just to retarget the launch device.

This is one of the small patches that remove device hardcodings from codegen so out-of-tree backends need fewer monkey-patches.

## Changes

- Add a `device_type = "mps"` class attribute to `MetalKernel`, next to the existing class-level knobs (`max_threadgroup_size`, `simd_group_size`, ...).
- `call_kernel()` derives the launch device from `self.device_type` instead of the literal.
- Add one test, `MPSBasicTests.test_metal_kernel_device_type`, that pins the default: `assertEqual(MetalKernel.device_type, "mps")`. It joins the file's existing MPS-gated class instead of introducing a new one, so the test diff is a single assertion with no scaffolding.

An alternative considered was to drop the `device=` kwarg and let the wrapper default to `V.graph.get_current_device_or_throw()`, like Triton. I did not take that path: the class attribute keeps this patch behavior-neutral (the wrapper default would follow the graph device instead of the value the kernel itself decides), preserves the existing failure mode of an explicit device, and gives subclasses one explicit knob. To be precise about the cost/benefit: `PythonWrapperCodegen.generate_kernel_call()` already reads `V.graph.scheduler.current_stream_idx` (codegen/wrapper.py:4301), so sourcing the launch device from the kernel does not remove a scheduler dependency, it just keeps that decision with the kernel that emits the call.

## Behavior

No change for in-tree backends. The default attribute value yields the exact same `torch.device("mps")` object as before, and the MPS branch of `PythonWrapperCodegen._generate_kernel_call_helper()` only dispatches on `device.type` (it never consumes the value or the index for `mps`). No other backend references the touched symbols, and the change adds no import-time device probing.

## Test Plan

```
cd /tmp && unset PYTHONPATH
PY=/usr/local/miniconda/envs/torch-2.15-cpu/bin/python   # torch 2.15.0.dev20260819+cpu

$PY -m pytest $PT/test/inductor/test_mps_basic.py -q
# 60 collected, 60 skipped. Base commit 00ea408 on the same command collects and
# skips 59, so the delta is exactly the one new case. Like every other case in this
# file it is under the class-level MPS skipUnless, so it is skipped on this Linux
# shard and runs in the macOS shards inside MPSBasicTests.

$PY -m pytest $PT/test/inductor/test_mps_basic.py -q --collect-only -k metal_kernel
# test/inductor/test_mps_basic.py::MPSBasicTests::test_metal_kernel_device_type

# Attribute value check, with the edited torch/_inductor/codegen/mps.py temporarily
# overlaid on the installed wheel (the wheel file was restored afterwards and its
# sha256 verified against the pre-overlay value):
$PY -c "from torch._inductor.codegen.mps import MetalKernel; print(MetalKernel.device_type)"
# mps

lintrunner -a --take PYFMT,RUFF torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# ok No lint issues.
```

Only PYFMT and RUFF were run locally. PYREFLY was excluded from local adjudication: on this unbuilt source tree it emits thousands of missing-attribute errors tree-wide against unmodified lines (e.g. `torch.bool`), on the base commit as well as on this diff, so it cannot discriminate here. CI's pyrefly job only covers `torch/`, which is where the only functional lines changed live. No NPU-side verification is claimed: `torch_npu` does not reference this file, and the diff does not change emitted code for any in-tree backend.

## Notes

`MetalOverrides._initialize_pointwise_overrides("mps")` is intentionally left unchanged: every backend passes its codegen backend name there (`"cpp"`, `"cppvec"`, `"halide"`, `"triton"`, `"mps"`), so it is a table key, not a device hardcoding.

Why a subclass retarget is not sufficient by itself, now stated at the attribute in `mps.py` rather than only here: `PythonWrapperCodegen._generate_kernel_call_helper()` dispatches on `device.type not in ("cuda", "xpu")` and raises `device <type> nyi` for anything else (codegen/wrapper.py:4342, :4349), and `CppWrapperMps._generate_kernel_call_helper()` asserts `device.type == "mps"` (codegen/cpp_wrapper_mps.py:82) while its shader-library pass skips non-mps `KernelCallLine`s (codegen/cpp_wrapper_mps.py:266). Those wrapper-side checks are deliberately out of scope here to keep this diff on the kernel side; they read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
@gavinwang269
gavinwang269 force-pushed the inductor/mps-codegen-device-decoupling branch from b2c4ea9 to b9424db Compare September 7, 2026 10:37
@gavinwang269

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review -- the test block was the problem, and your own last line in the white-box bullet ("assertEqual(MetalKernel.device_type, "mps") is the only genuinely new assertion the PR needs") is exactly what I implemented. The production change is untouched from the version you reviewed; the tests shrank from 87 added lines to 4, and the wrapper-side reasoning now lives in the code comment rather than only in the description.

Diff shape now

  • test/inductor/test_mps_basic.py: +4/-0 (was +87). The harness class, both new test classes, the instantiate_device_type_tests(...) call and the imports added for them (SimpleNamespace, mock, V, HardwareClassification, instantiate_device_type_tests) are gone. The only remaining additions are the MetalKernel import and:

    def test_metal_kernel_device_type(self):
        self.assertEqual(MetalKernel.device_type, "mps")
  • torch/_inductor/codegen/mps.py: comment above device_type expanded to state the wrapper-side limitation, per your "that reasoning belongs in the code comment" point.

  • No other file touched; device= is still passed explicitly (see the API section).

Point by point on the testing items

  1. The GENERIC case never runs in CI. Accepted, and I did not keep the HardwareClassification experiment at all -- no inert metadata is left in the file. The retained assertion is a method of the existing MPSBasicTests class, so it runs where that file runs: the --mps selection in test/run_test.py (run_test.py:1832-1849 includes inductor/test_mps_basic), i.e. the macOS MPS shards, and it is skipped everywhere else along with the other 59 cases. I chose not to relocate it to a CPU-shard file: the value being pinned is the in-tree Metal backend's launch default, and this is the file whose whole purpose is Metal codegen, so a CPU-shard copy would test a constant far from the thing it configures.

  2. test_call_kernel_follows_class_device_type asserts something that cannot happen. Dropped, and the diagnosis was right: it only passed because the wrapper was a MagicMock, while the real _generate_kernel_call_helper() raises device <type> nyi for a device outside cpu/cuda/xpu/mps and cpp_wrapper_mps.py:82-83 asserts on the AOTI path. I did not keep the narrowed variant ("asserts only that torch.device(self.device_type) is forwarded") because without the mock there is nothing left in it that the retained assertion does not already cover.

  3. test_default_kernel_binds_primary_device is a tautology. Agreed -- it reduced to "mps" == "mps" plus an index is None check about how torch.device("mps") is built, not about this diff. Deleted together with the only_for=("mps",) instantiation and its classification.

  4. The white-box stub will rot silently. The stub is gone, so there is no __new__ bypass and no hand-supplied internal state to drift out of sync. I also did not add a FileCheck case on the emitted call line: it would be a second way to observe the same device= value, and as you noted the existing end-to-end MPS tests in this file already drive call_kernel(), so a broken default is caught there. That leaves the single assertion, which is the "or trim it" branch of your recommendation.

  5. kernel.active_range_trees = list is dead and sizevars=[] is type-wrong. Both removed with the harness.

  6. skipUnless redundant with only_for=("mps",). Removed with the class. On the chosen host class: MPSBasicTests is the file's primary non-AOTI class and already carries the class-level @unittest.skipUnless(torch.backends.mps.is_available(), ...), which is why the new test needs no decorator of its own; MPSBasicTestsAOTI would have been the wrong neighbor since it is about the aoti_compile_and_package path.

API design

  • The knob is not reachable end-to-end today. Correct, and now said in the source: the comment above the attribute notes that a retarget is not usable on its own because the non-triton branch of _generate_kernel_call_helper() raises device ... nyi for device types other than cpu/cuda/xpu/mps, so subclasses need the wrapper-side follow-up. Keeping this PR kernel-side only is a deliberate review-surface decision, not an oversight: the diff is behavior-neutral and reviewable in isolation, while the wrapper-side change (a negated dispatch, plus CppWrapperMps's assert at cpp_wrapper_mps.py:82 and its shader-library pass at :266) touches the cpu/cuda/xpu paths and deserves its own PR with its own CI signal. That does mean, as you say, that until the follow-up lands "mps" is the only value that works end to end, and no end-to-end test can be written for a retarget. If you would rather have the wrapper change first so the attribute lands with something that can use it, I am glad to resequence and restack this on top -- the kernel-side piece is small enough to move.

  • Reconsider deleting the device= kwarg. I read the -1/+0 argument and it is the smaller diff, but I am keeping the class attribute for the reason you called reasonable, with one correction to my own description: the "no new dependency on scheduler state" line does not hold up, because generate_kernel_call() already reads V.graph.scheduler.current_stream_idx on this exact path. So the honest case is narrower: dropping the kwarg changes the source of truth for the launch device from the kernel that emitted the call to whatever the graph's current device happens to be at wrapper time (and with it, the failure mode for an unimplemented device type), and that is a behavior question rather than a style question. I preferred not to answer it as a side effect of a decoupling patch; I may be wrong that this matters in practice, since for an MPS graph the two coincide today. That reasoning is now also summarized in the code comment instead of only in prose.

Test plan (rerun after trimming)

cd /tmp && unset PYTHONPATH
python -m pytest <repo>/test/inductor/test_mps_basic.py -q
# 60 collected, 60 skipped   (base 00ea4089 on the same command: 59 collected, 59 skipped)
python -m pytest <repo>/test/inductor/test_mps_basic.py -q --collect-only -k metal_kernel
# test/inductor/test_mps_basic.py::MPSBasicTests::test_metal_kernel_device_type
lintrunner -a --take PYFMT,RUFF torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# ok No lint issues.

Collection is back to the base count plus exactly the one new case. To be explicit about the limitation: on this Linux machine the new case is skipped like the other 59, so the assertion was verified by importing the patched module directly (MetalKernel.device_type reads back as mps) rather than by executing the test; the macOS --mps shard is where it actually runs.

@gavinwang269

gavinwang269 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @jansel, following up on this PR: the test issues from the review have been addressed as prescribed (tests reduced from 87 to 4 added lines, keeping the single MetalKernel.device_type assertion inside the existing MPS-gated class). The production change is untouched. The only failing check is the torchtitan integration job, which looks like a self-hosted runner infrastructure failure ("custom container implementation failed") rather than anything related to this diff. Could you take a look when you have a chance? Happy to take another pass over the updated head if that is useful.

@jansel

jansel commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 7m 36s —— View job


Re-reviewed the trimmed head (b9424db): the prior review's blockers are all resolved, the production change is behavior-preserving, and what remains is two small nits in the new comment plus a note that the retained test is close to zero-value.

Full review

PR Review: #195809 (re-review of b9424db)

  • Read the PR diff against the merge base
  • Verify the prior review's items were addressed
  • Check the production change and new comment for correctness
  • Post review

Verification of the previous review's items

All six testing items and the API-design point are addressed. Confirmed against the tree:

Prior finding Status
HardwareClassification.GENERIC class never runs in CI Removed; no HardwareClassification reference remains in the file
test_call_kernel_follows_class_device_type asserted a "meta" retarget the real wrapper rejects Deleted
test_default_kernel_binds_primary_device was "mps" == "mps" Deleted
White-box _stub_kernel (__new__ bypass, six hand-supplied attrs, sizevars=[]) Deleted
kernel.active_range_trees = list dead override Deleted
skipUnless redundant with only_for=("mps",) Deleted with the class
Wrapper-side limitation lived only in the PR description Now stated at torch/_inductor/codegen/mps.py:561-566

The test block is now test/inductor/test_mps_basic.py:358-359 inside the existing MPS-gated MPSBasicTests, plus the module-level MetalKernel import at :10. That import is safe on non-MPS platforms — mps.py does no device probing at import time (its only import-time side effects are MetalOverrides._initialize_pointwise_overrides("mps") / _initialize_special_ops() at :549-550), and test/inductor/test_op_completeness.py:6 already imports from this module at module scope, so there is precedent.

Production change

torch/_inductor/codegen/mps.py:567 and :1168 are correct and behavior-preserving:

  • No shadowing. device_type appears nowhere in SIMDKernel (simd.py) or Kernel/CodeGen (common.py) — the only other device_type in torch/_inductor/codegen/ outside cutlass/cpp-utils is common.py:522-528, a local in get_backend_features, and triton.py's locals from V.graph.get_current_device_or_throw().type. Nothing reads kernel.device_type reflectively, so the new attribute cannot be picked up by unrelated machinery.
  • torch.device("mps") and torch.device(self.device_type) construct the same object, and the MPS branch at wrapper.py:4362-4364 dispatches only on device.type (it never reads device.index), so generated code for the in-tree backend is byte-identical.
  • Nothing else in the file regressed to a literal: grep '"mps"' torch/_inductor/codegen/mps.py now returns only :549 (the overrides table key, correctly left alone) and :567 (the new default).

Nits (non-blocking)

  1. mps.py:566 points a source comment at the PR description. "the wrapper-side follow-up noted in the PR description" is not resolvable by someone reading the file in six months — the PR number isn't in the comment, and a reader with git blame still has to leave the tree. Since the point of moving this text into the source was to make it self-contained, name the code instead. Suggested trim, which also drops the comment from 6 lines to 3 for a 1-line attribute (CLAUDE.md: minimize comments, keep them to non-obvious global context):

    # Launch device for generated kernels; subclasses reusing this call plumbing
    # can override it. Not usable end-to-end yet: the non-triton branch of
    # PythonWrapperCodegen._generate_kernel_call_helper raises for other devices.
    device_type = "mps"

    Fix this →

  2. The retained test is close to zero-value, which I want to be honest about since my previous review nominated it. assertEqual(MetalKernel.device_type, "mps") asserts a literal in the source equals the same literal in the test; the only regression it can catch (someone changing the default) is already caught by every other case in the file, all of which drive call_kernel() end-to-end on the macOS --mps shards (test/run_test.py:1850). It is 2 lines and harmless, so I would not hold the PR on it — but "trim to this one assertion" was the floor of my earlier recommendation, and deleting it entirely (leaving a pure -1/+1 production diff) is also a defensible landing state if @jansel prefers no test for a constant.

  3. The comment's scope, for completeness: it names only PythonWrapperCodegen, while cpp_wrapper_mps.py:82-83 (assert on device.type != "mps") and :266 (shader-library pass skipping non-mps KernelCallLines) are the AOTI-path equivalents. "the wrapper-side follow-up" reads as covering both, so this is fine as-is; also note that a retargeting subclass would still get mps_lib_* kernel names from MetalScheduling.define_kernel (mps.py:1239), which CppWrapperMps matches on. Nothing to change here — just confirming the deferred surface is larger than the one function named.

On the API-design question

The author's response is correct on the fact I raised, and self-corrected the part of the original rationale that didn't hold (generate_kernel_call does already read V.graph.scheduler.current_stream_idx at wrapper.py:4318, so the "avoids scheduler state" argument was wrong). What's left is a real, narrow difference: passing device= sources the launch device from the kernel that emitted the call, while omitting it takes whatever V.graph.get_current_device_or_throw() returns at wrapper time (wrapper.py:4317, :4358). For an MPS graph those coincide today, so this is a judgment call rather than a correctness one, and it is @jansel's to make — the -1/+0 alternative (delete the kwarg, matching TritonKernel) is still the smaller diff if you'd rather not add the attribute at all.

The "knob no subclass can currently use" concern from my last review stands as a sequencing question, not a defect: the attribute is inert for in-tree code, and the author has offered to restack on top of the wrapper-side change if you'd prefer it land exercisable.

Recommendation

Approve (nits only). The blocking test problems are gone, the codegen change is provably behavior-neutral for in-tree backends, and nothing in the trimmed diff asserts behavior the system doesn't have. Nit 1 is worth a follow-up push; nits 2 and 3 are informational.

| Branch: `inductor/mps-codegen-device-decoupling`

gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 11, 2026
Replace two hardcoded 'mps' string comparisons with a class-level
device_type attribute so subclasses targeting other devices can reuse
the wrapper without copying the guard logic. Error message is now
built from device_type. No behavior change for MPS: generated C++
output verified byte-identical via a 16-case differential harness
(14 must-be-identical + 2 knob counterexamples).

Stacked on pytorch#195809 (mps.py device_type attribute).
@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @kurtamohler, could you take a look at this PR when you have a chance?

It makes the MetalKernel launch device overridable via a class attribute in torch/_inductor/codegen/mps.py, plus a small touch to test/inductor/test_mps_basic.py. Since it touches the MPS-specific test file, your approval (per the MPS merge rules) is what's still missing — @jansel has already reviewed and approved the rest of the change (test scope was trimmed per his review feedback, from 87 added lines down to 4).

Current status:

  • Approved by @jansel
  • All CI green; the only failing check is torchtitan_models_integration, which fails with No module named 'fla' — a CI environment dependency issue unrelated to this change (same job passes on main)

cc @jansel in case you want to double-check the final state.

Thanks!

@jansel

jansel commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

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

gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 14, 2026
Replace two hardcoded 'mps' string comparisons with a class-level
device_type attribute so subclasses targeting other devices can reuse
the wrapper without copying the guard logic. Error message is now
built from device_type. No behavior change for MPS: generated C++
output verified byte-identical via a 16-case differential harness
(14 must-be-identical + 2 knob counterexamples).

Add three tests in test_cpp_wrapper_asserts.py driving the production
guard and filter paths:

- test_guard_error_message_uses_device_type: a non-cpu, non-mps
  device hits the class guard and raises the parameterized message
- test_subclass_device_type_override_passes_guard: a subclass
  overriding device_type changes the guard outcome and message,
  proving the attribute is consumed, not a copy of the old literal
- test_additional_funcs_filters_by_device_type: a non-matching
  KernelCallLine produces no shader library scaffolding

The wrapper is constructed via object.__new__ with the minimal
attributes the two methods touch, avoiding the full __init__ chain
that requires a complete graph lowering.

Stacked on pytorch#195809 (mps.py device_type attribute).
@gavinwang269 gavinwang269 changed the title [MPSInductor] Make MetalKernel launch device overridable via a class attribute [Feature Refactoring] Make MetalKernel launch device overridable via a class attribute Oct 26, 2026
pytorchmergebot pushed a commit to gavinwang269/pytorch that referenced this pull request Nov 2, 2026
Replace two hardcoded 'mps' string comparisons with a class-level
device_type attribute so subclasses targeting other devices can reuse
the wrapper without copying the guard logic. Error message is now
built from device_type. No behavior change for MPS: generated C++
output verified byte-identical via a 16-case differential harness
(14 must-be-identical + 2 knob counterexamples).

Add three tests in test_cpp_wrapper_asserts.py driving the production
guard and filter paths:

- test_guard_error_message_uses_device_type: a non-cpu, non-mps
  device hits the class guard and raises the parameterized message
- test_subclass_device_type_override_passes_guard: a subclass
  overriding device_type changes the guard outcome and message,
  proving the attribute is consumed, not a copy of the old literal
- test_additional_funcs_filters_by_device_type: a non-matching
  KernelCallLine produces no shader library scaffolding

The wrapper is constructed via object.__new__ with the minimal
attributes the two methods touch, avoiding the full __init__ chain
that requires a complete graph lowering.

Stacked on pytorch#195809 (mps.py device_type attribute).
pytorchmergebot pushed a commit to gavinwang269/pytorch that referenced this pull request Nov 4, 2026
Replace two hardcoded 'mps' string comparisons with a class-level
device_type attribute so subclasses targeting other devices can reuse
the wrapper without copying the guard logic. Error message is now
built from device_type. No behavior change for MPS: generated C++
output verified byte-identical via a 16-case differential harness
(14 must-be-identical + 2 knob counterexamples).

Add three tests in test_cpp_wrapper_asserts.py driving the production
guard and filter paths:

- test_guard_error_message_uses_device_type: a non-cpu, non-mps
  device hits the class guard and raises the parameterized message
- test_subclass_device_type_override_passes_guard: a subclass
  overriding device_type changes the guard outcome and message,
  proving the attribute is consumed, not a copy of the old literal
- test_additional_funcs_filters_by_device_type: a non-matching
  KernelCallLine produces no shader library scaffolding

The wrapper is constructed via object.__new__ with the minimal
attributes the two methods touch, avoiding the full __init__ chain
that requires a complete graph lowering.

Stacked on pytorch#195809 (mps.py device_type attribute).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Nov 5, 2026
…own device field

CppWrapperMps hardcoded "mps" in its kernel-call guard and its
codegen_additional_funcs device filter, so an out-of-tree backend reusing this
wrapper shape had to copy the helper and hand-edit the literals. It also grew
a second target-device concept next to the existing one.

Fix: the two comparisons now read ``self.device``, the single field the
hierarchy already carries. CppWrapperGpu stops overwriting a subclass-set
device (the CppWrapperCpu hasattr pattern), CppWrapperMps declares
device = "mps", and the lazy-scratch emitter in cpp_wrapper_gpu.py asks the
wrapper for its device instead of calling get_gpu_type(). On a Mac, where
get_gpu_type() already returns "mps", nothing changes; the generated C++ for
the default path was verified byte-identical via the 16-case differential
harness (14 must-be-identical + 2 knob counterexamples). CppWrapperMps.create
becomes a classmethod returning cls() so a subclass actually gets its own
class from the factory (graph.py calls wrapper_code_gen_cls.create); before
this, overriding the device still handed back a plain CppWrapperMps. The
class comment states what a retarget still does NOT get for free (the
aoti_torch_mps_* shims, AOTIMetal* types and include paths stay MPS-specific
until the follow-up refactor, same limitation documented on the companion
attribute in codegen/mps.py).

Six tests in test_cpp_wrapper_asserts.py drive the production guard and
filter: base message, matching-line positive emission (get_mps_lib_0_handle
in the prefix), non-matching silence, subclass filter choosing its own
device's line, subclass guard rejecting the base device, and the create
factory contract. Restoring the old wheel and re-running the new suite
fails 3 of the 6 -- the suite now discriminates the change, which the
previously shipped tests did not. The graph handler installed by the helper
is scoped via enterContext (the previous version leaked a fake V.graph into
later tests in the process).

Stacked on pytorch#195809 (mps.py device_type attribute).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Nov 5, 2026
…own device field

## Summary

`CppWrapperMps` hardcoded `"mps"` in two device checks. Both now read `self.device` — the target-device field the wrapper hierarchy already carries — instead of adding a second concept next to it.

Changes (single commit, 4 files):
- `torch/_inductor/codegen/cpp_wrapper_gpu.py`: `CppWrapperGpu.__init__` keeps a subclass-set `device` (same `hasattr` pattern `CppWrapperCpu` already uses) instead of overwriting with `get_gpu_type()`; the lazy-scratch emitter uses `wrapper.device` rather than calling `get_gpu_type()` directly
- `torch/_inductor/codegen/cpp_wrapper_mps.py`: class attribute `device = "mps"`; the guard in `_generate_kernel_call_helper` and the filter in `codegen_additional_funcs` compare against `self.device`, message built from it; `create()` becomes a classmethod returning `cls()` so `wrapper_code_gen_cls.create(...)` (graph.py) gives a subclass its own class; the class comment states what a retarget still does NOT inherit (the `aoti_torch_mps_*` shims, `AOTIMetal*` types, include paths remain MPS-specific until the follow-up refactor — same caveat the companion attribute in `codegen/mps.py` carries)
- `test/inductor/test_gpu_cpp_wrapper.py`: the `FakeWrapper` in
  `test_lazy_triton_wrapper_forwards_launch_pdl` gains the `device` attribute the real
  wrappers always have (production-contract fidelity for the lazy-scratch path)
- `test/inductor/test_cpp_wrapper_asserts.py`: seven tests driving the production guard and filter paths (base message, matching line emits `get_mps_lib_0_handle`, non-matching emits nothing, subclass filter picks its own device's line, subclass guard rejects the base device, create returns the subclass); the fake graph handler is installed via `enterContext` so it cannot leak into later tests

## Motivation

`CppWrapperMps` is dispatched per-device via `register_backend_for_device` in `common.py`, yet the "which device does this class belong to" checks inside the class body were string literals, and the class grew a second target-device concept next to the existing `self.device` that already drives `device_codegen`, the shim header path and the generated `device_type`. A subclass setting only the second field got an object whose two fields disagreed. Unifying on `self.device` removes the disagreement by construction. An out-of-tree backend reusing this runtime-shader-library + lazy-handle + callback-launch model no longer needs to hand-edit literals or bypass the factory.

Companion to pytorch#195809 (same retarget limitation, sibling file).

## Test Plan

- [x] New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
- [x] Discrimination matrix (overlay into the installed wheel): untouched pre-change
  sources -> 3/10 fail; mps literals restored in the guard/filter only -> the 2 subclass
  tests fail; hasattr guard reverted in CppWrapperGpu.__init__ only -> the
  init/factory test fails. Every half of the change has a witness
- [x] Full file green on cpu venv (10/10) and on the NPU host with the overlay (10/10); the previously-broken `test_lazy_triton_wrapper_forwards_launch_pdl` passes both parametrizations with the FakeWrapper fix
- [x] Differential harness (16 cases: 14 must-be-identical + 2 knob counterexamples): default-path generated C++ byte-identical; knob cases show the subclass device is consumed
- [x] lint: lintrunner clean on all three files
- [ ] MPS end-to-end on mac (ciflow/mps) — not executable in this environment (aarch64 Linux, no Metal runtime); byte-identical argument + harness only, does not substitute mac CI

Ready once mac CI signal is observed.

## Review follow-up (2026-11-05 round)

This revision responds to the automated round on the previous head: the second device field (`device_type`) is gone in favour of `self.device` (their finding + the Cpu hasattr precedent); `create()` is a classmethod (factory-contract finding); the fake `V.graph` handler is scoped (leak finding); positive-path assertions were added and the misleadingly named subclass test split into filter+guard pairs (discrimination finding — measured: 3 of the 6 new tests fail on pre-change code).

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

Round 2 (findings on `ceeedf1c9eac`) is addressed in the follow-up push: FakeWrapper device attribute, a real-`__init__` test that fails when the hasattr guard is reverted, the class comment now listing everything the single `device` field actually retargets, inline raise style, the renamed guard test, module-level subclass/imports, and the `@requires_triton` gate question stays parked for the same maintainer ruling as pytorch#192434.
Stacked on pytorch#195809 (mps.py device_type attribute).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Nov 5, 2026
…own device field

## Summary

`CppWrapperMps` hardcoded `"mps"` in two device checks. Both now read `self.device` — the target-device field the wrapper hierarchy already carries — instead of adding a second concept next to it.

Changes (single commit, 4 files):
- `torch/_inductor/codegen/cpp_wrapper_gpu.py`: `CppWrapperGpu.__init__` keeps a subclass-set `device` (same `hasattr` pattern `CppWrapperCpu` already uses) instead of overwriting with `get_gpu_type()`; the lazy-scratch emitter uses `wrapper.device` rather than calling `get_gpu_type()` directly
- `torch/_inductor/codegen/cpp_wrapper_mps.py`: class attribute `device = "mps"`; the guard in `_generate_kernel_call_helper` and the filter in `codegen_additional_funcs` compare against `self.device`, message built from it; `create()` becomes a classmethod returning `cls()` so `wrapper_code_gen_cls.create(...)` (graph.py) gives a subclass its own class; the class comment states what a retarget still does NOT inherit (the `aoti_torch_mps_*` shims, `AOTIMetal*` types, include paths remain MPS-specific until the follow-up refactor — same caveat the companion attribute in `codegen/mps.py` carries)
- `test/inductor/test_gpu_cpp_wrapper.py`: the `FakeWrapper` in
  `test_lazy_triton_wrapper_forwards_launch_pdl` gains the `device` attribute the real
  wrappers always have (production-contract fidelity for the lazy-scratch path)
- `test/inductor/test_cpp_wrapper_asserts.py`: seven tests driving the production guard and filter paths (base message, matching line emits `get_mps_lib_0_handle`, non-matching emits nothing, subclass filter picks its own device's line, subclass guard rejects the base device, create returns the subclass); the fake graph handler is installed via `enterContext` so it cannot leak into later tests

## Motivation

`CppWrapperMps` is dispatched per-device via `register_backend_for_device` in `common.py`, yet the "which device does this class belong to" checks inside the class body were string literals, and the class grew a second target-device concept next to the existing `self.device` that already drives `device_codegen`, the shim header path and the generated `device_type`. A subclass setting only the second field got an object whose two fields disagreed. Unifying on `self.device` removes the disagreement by construction. An out-of-tree backend reusing this runtime-shader-library + lazy-handle + callback-launch model no longer needs to hand-edit literals or bypass the factory.

Companion to pytorch#195809 (same retarget limitation, sibling file).

## Test Plan

- [x] New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
- [x] Discrimination matrix (overlay into the installed wheel): untouched pre-change
  sources -> 3/10 fail; mps literals restored in the guard/filter only -> the 2 subclass
  tests fail; hasattr guard reverted in CppWrapperGpu.__init__ only -> the
  init/factory test fails. Every half of the change has a witness
- [x] Full file green on cpu venv (10/10) and on the NPU host with the overlay (10/10); the previously-broken `test_lazy_triton_wrapper_forwards_launch_pdl` passes both parametrizations with the FakeWrapper fix
- [x] Differential harness (16 cases: 14 must-be-identical + 2 knob counterexamples): default-path generated C++ byte-identical; knob cases show the subclass device is consumed
- [x] lint: lintrunner clean on all three files
- [ ] MPS end-to-end on mac (ciflow/mps) — not executable in this environment (aarch64 Linux, no Metal runtime); byte-identical argument + harness only, does not substitute mac CI

Ready once mac CI signal is observed.

## Review follow-up (2026-11-05 round)

This revision responds to the automated round on the previous head: the second device field (`device_type`) is gone in favour of `self.device` (their finding + the Cpu hasattr precedent); `create()` is a classmethod (factory-contract finding); the fake `V.graph` handler is scoped (leak finding); positive-path assertions were added and the misleadingly named subclass test split into filter+guard pairs (discrimination finding — measured: 3 of the 6 new tests fail on pre-change code).

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

Round 2 (findings on `ceeedf1c9eac`) is addressed in the follow-up push: FakeWrapper device attribute, a real-`__init__` test that fails when the hasattr guard is reverted, the class comment now listing everything the single `device` field actually retargets, inline raise style, the renamed guard test, module-level subclass/imports, and the `@requires_triton` gate question stays parked for the same maintainer ruling as pytorch#192434.
Stacked on pytorch#195809 (mps.py device_type attribute).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Nov 5, 2026
…own device field

## Summary

`CppWrapperMps` hardcoded `"mps"` in two device checks. Both now read `self.device` — the target-device field the wrapper hierarchy already carries — instead of adding a second concept next to it.

Changes (single commit, 4 files):
- `torch/_inductor/codegen/cpp_wrapper_gpu.py`: `CppWrapperGpu.__init__` keeps a subclass-set `device` (same `hasattr` pattern `CppWrapperCpu` already uses) instead of overwriting with `get_gpu_type()`; the lazy-scratch emitter uses `wrapper.device` rather than calling `get_gpu_type()` directly
- `torch/_inductor/codegen/cpp_wrapper_mps.py`: class attribute `device = "mps"`; the guard in `_generate_kernel_call_helper` and the filter in `codegen_additional_funcs` compare against `self.device`, message built from it; `create()` becomes a classmethod returning `cls()` so `wrapper_code_gen_cls.create(...)` (graph.py) gives a subclass its own class; the class comment states what a retarget still does NOT inherit (the `aoti_torch_mps_*` shims, `AOTIMetal*` types, include paths remain MPS-specific until the follow-up refactor — same caveat the companion attribute in `codegen/mps.py` carries)
- `test/inductor/test_gpu_cpp_wrapper.py`: the `FakeWrapper` in
  `test_lazy_triton_wrapper_forwards_launch_pdl` gains the `device` attribute the real
  wrappers always have (production-contract fidelity for the lazy-scratch path)
- `test/inductor/test_cpp_wrapper_asserts.py`: seven tests driving the production guard and filter paths (base message, matching line emits `get_mps_lib_0_handle`, non-matching emits nothing, subclass filter picks its own device's line, subclass guard rejects the base device, create returns the subclass); the fake graph handler is installed via `enterContext` so it cannot leak into later tests

## Motivation

`CppWrapperMps` is dispatched per-device via `register_backend_for_device` in `common.py`, yet the "which device does this class belong to" checks inside the class body were string literals, and the class grew a second target-device concept next to the existing `self.device` that already drives `device_codegen`, the shim header path and the generated `device_type`. A subclass setting only the second field got an object whose two fields disagreed. Unifying on `self.device` removes the disagreement by construction. An out-of-tree backend reusing this runtime-shader-library + lazy-handle + callback-launch model no longer needs to hand-edit literals or bypass the factory.

Companion to pytorch#195809 (same retarget limitation, sibling file).

## Test Plan

- [x] New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
- [x] Discrimination matrix (overlay into the installed wheel): untouched pre-change
  sources -> 3/10 fail; mps literals restored in the guard/filter only -> the 2 subclass
  tests fail; hasattr guard reverted in CppWrapperGpu.__init__ only -> the
  init/factory test fails. Every half of the change has a witness
- [x] Full file green on cpu venv (10/10) and on the NPU host with the overlay (10/10); the previously-broken `test_lazy_triton_wrapper_forwards_launch_pdl` passes both parametrizations with the FakeWrapper fix
- [x] Differential harness (16 cases: 14 must-be-identical + 2 knob counterexamples): default-path generated C++ byte-identical; knob cases show the subclass device is consumed
- [x] lint: lintrunner clean on all three files
- [ ] MPS end-to-end on mac (ciflow/mps) — not executable in this environment (aarch64 Linux, no Metal runtime); byte-identical argument + harness only, does not substitute mac CI

Ready once mac CI signal is observed.

## Review follow-up (2026-11-05 round)

This revision responds to the automated round on the previous head: the second device field (`device_type`) is gone in favour of `self.device` (their finding + the Cpu hasattr precedent); `create()` is a classmethod (factory-contract finding); the fake `V.graph` handler is scoped (leak finding); positive-path assertions were added and the misleadingly named subclass test split into filter+guard pairs (discrimination finding — measured: 3 of the 6 new tests fail on pre-change code).

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

Round 2 (findings on `ceeedf1c9eac`) is addressed in the follow-up push: FakeWrapper device attribute, a real-`__init__` test that fails when the hasattr guard is reverted, the class comment now listing everything the single `device` field actually retargets, inline raise style, the renamed guard test, module-level subclass/imports, and the `@requires_triton` gate question stays parked for the same maintainer ruling as pytorch#192434.
Stacked on pytorch#195809 (mps.py device_type attribute).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Nov 5, 2026
…own device field

## Summary

`CppWrapperMps` hardcoded `"mps"` in two device checks. Both now read `self.device` — the target-device field the wrapper hierarchy already carries — instead of adding a second concept next to it.

Changes (single commit, 4 files):
- `torch/_inductor/codegen/cpp_wrapper_gpu.py`: `CppWrapperGpu.__init__` keeps a subclass-set `device` (same `hasattr` pattern `CppWrapperCpu` already uses) instead of overwriting with `get_gpu_type()`; the lazy-scratch emitter uses `wrapper.device` rather than calling `get_gpu_type()` directly
- `torch/_inductor/codegen/cpp_wrapper_mps.py`: class attribute `device = "mps"`; the guard in `_generate_kernel_call_helper` and the filter in `codegen_additional_funcs` compare against `self.device`, message built from it; `create()` becomes a classmethod returning `cls()` so `wrapper_code_gen_cls.create(...)` (graph.py) gives a subclass its own class; the class comment states what a retarget still does NOT inherit (the `aoti_torch_mps_*` shims, `AOTIMetal*` types, include paths remain MPS-specific until the follow-up refactor — same caveat the companion attribute in `codegen/mps.py` carries)
- `test/inductor/test_gpu_cpp_wrapper.py`: the `FakeWrapper` in
  `test_lazy_triton_wrapper_forwards_launch_pdl` gains the `device` attribute the real
  wrappers always have (production-contract fidelity for the lazy-scratch path)
- `test/inductor/test_cpp_wrapper_asserts.py`: seven tests driving the production guard and filter paths (base message, matching line emits `get_mps_lib_0_handle`, non-matching emits nothing, subclass filter picks its own device's line, subclass guard rejects the base device, create returns the subclass); the fake graph handler is installed via `enterContext` so it cannot leak into later tests

## Motivation

`CppWrapperMps` is dispatched per-device via `register_backend_for_device` in `common.py`, yet the "which device does this class belong to" checks inside the class body were string literals, and the class grew a second target-device concept next to the existing `self.device` that already drives `device_codegen`, the shim header path and the generated `device_type`. A subclass setting only the second field got an object whose two fields disagreed. Unifying on `self.device` removes the disagreement by construction. An out-of-tree backend reusing this runtime-shader-library + lazy-handle + callback-launch model no longer needs to hand-edit literals or bypass the factory.

Companion to pytorch#195809 (same retarget limitation, sibling file).

## Test Plan

- [x] New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
- [x] Discrimination matrix (overlay into the installed wheel): untouched pre-change
  sources -> 3/10 fail; mps literals restored in the guard/filter only -> the 2 subclass
  tests fail; hasattr guard reverted in CppWrapperGpu.__init__ only -> the
  init/factory test fails. Every half of the change has a witness
- [x] Full file green on cpu venv (10/10) and on the NPU host with the overlay (10/10); the previously-broken `test_lazy_triton_wrapper_forwards_launch_pdl` passes both parametrizations with the FakeWrapper fix
- [x] Differential harness (16 cases: 14 must-be-identical + 2 knob counterexamples): default-path generated C++ byte-identical; knob cases show the subclass device is consumed
- [x] lint: lintrunner clean on all three files
- [ ] MPS end-to-end on mac (ciflow/mps) — not executable in this environment (aarch64 Linux, no Metal runtime); byte-identical argument + harness only, does not substitute mac CI

Ready once mac CI signal is observed.

## Review follow-up (2026-11-05 round)

This revision responds to the automated round on the previous head: the second device field (`device_type`) is gone in favour of `self.device` (their finding + the Cpu hasattr precedent); `create()` is a classmethod (factory-contract finding); the fake `V.graph` handler is scoped (leak finding); positive-path assertions were added and the misleadingly named subclass test split into filter+guard pairs (discrimination finding — measured: 3 of the 6 new tests fail on pre-change code).

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

Round 2 (findings on `ceeedf1c9eac`) is addressed in the follow-up push: FakeWrapper device attribute, a real-`__init__` test that fails when the hasattr guard is reverted, the class comment now listing everything the single `device` field actually retargets, inline raise style, the renamed guard test, module-level subclass/imports, and the `@requires_triton` gate question stays parked for the same maintainer ruling as pytorch#192434.
Stacked on pytorch#195809 (mps.py device_type attribute).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Nov 5, 2026
…own device field

## Summary

`CppWrapperMps` hardcoded `"mps"` in two device checks. Both now read `self.device` — the target-device field the wrapper hierarchy already carries — instead of adding a second concept next to it.

Changes (single commit, 4 files):
- `torch/_inductor/codegen/cpp_wrapper_gpu.py`: `CppWrapperGpu.__init__` keeps a subclass-set `device` (same `hasattr` pattern `CppWrapperCpu` already uses) instead of overwriting with `get_gpu_type()`; the lazy-scratch emitter uses `wrapper.device` rather than calling `get_gpu_type()` directly
- `torch/_inductor/codegen/cpp_wrapper_mps.py`: class attribute `device = "mps"`; the guard in `_generate_kernel_call_helper` and the filter in `codegen_additional_funcs` compare against `self.device`, message built from it; `create()` becomes a classmethod returning `cls()` so `wrapper_code_gen_cls.create(...)` (graph.py) gives a subclass its own class; the class comment states what a retarget still does NOT inherit (the `aoti_torch_mps_*` shims, `AOTIMetal*` types, include paths remain MPS-specific until the follow-up refactor — same caveat the companion attribute in `codegen/mps.py` carries)
- `test/inductor/test_gpu_cpp_wrapper.py`: the `FakeWrapper` in
  `test_lazy_triton_wrapper_forwards_launch_pdl` gains the `device` attribute the real
  wrappers always have (production-contract fidelity for the lazy-scratch path)
- `test/inductor/test_cpp_wrapper_asserts.py`: seven tests driving the production guard and filter paths (base message, matching line emits `get_mps_lib_0_handle`, non-matching emits nothing, subclass filter picks its own device's line, subclass guard rejects the base device, create returns the subclass); the fake graph handler is installed via `enterContext` so it cannot leak into later tests

## Motivation

`CppWrapperMps` is dispatched per-device via `register_backend_for_device` in `common.py`, yet the "which device does this class belong to" checks inside the class body were string literals, and the class grew a second target-device concept next to the existing `self.device` that already drives `device_codegen`, the shim header path and the generated `device_type`. A subclass setting only the second field got an object whose two fields disagreed. Unifying on `self.device` removes the disagreement by construction. An out-of-tree backend reusing this runtime-shader-library + lazy-handle + callback-launch model no longer needs to hand-edit literals or bypass the factory.

Companion to pytorch#195809 (same retarget limitation, sibling file).

## Test Plan

- [x] New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
- [x] Discrimination matrix (overlay into the installed wheel): untouched pre-change
  sources -> 3/10 fail; mps literals restored in the guard/filter only -> the 2 subclass
  tests fail; hasattr guard reverted in CppWrapperGpu.__init__ only -> the
  init/factory test fails. Every half of the change has a witness
- [x] Full file green on cpu venv (10/10) and on the NPU host with the overlay (10/10); the previously-broken `test_lazy_triton_wrapper_forwards_launch_pdl` passes both parametrizations with the FakeWrapper fix
- [x] Differential harness (16 cases: 14 must-be-identical + 2 knob counterexamples): default-path generated C++ byte-identical; knob cases show the subclass device is consumed
- [x] lint: lintrunner clean on all three files
- [ ] MPS end-to-end on mac (ciflow/mps) — not executable in this environment (aarch64 Linux, no Metal runtime); byte-identical argument + harness only, does not substitute mac CI

Ready once mac CI signal is observed.

## Review follow-up (2026-11-05 round)

This revision responds to the automated round on the previous head: the second device field (`device_type`) is gone in favour of `self.device` (their finding + the Cpu hasattr precedent); `create()` is a classmethod (factory-contract finding); the fake `V.graph` handler is scoped (leak finding); positive-path assertions were added and the misleadingly named subclass test split into filter+guard pairs (discrimination finding — measured: 3 of the 6 new tests fail on pre-change code).

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

Round 2 (findings on `ceeedf1c9eac`) is addressed in the follow-up push: FakeWrapper device attribute, a real-`__init__` test that fails when the hasattr guard is reverted, the class comment now listing everything the single `device` field actually retargets, inline raise style, the renamed guard test, module-level subclass/imports, and the `@requires_triton` gate question stays parked for the same maintainer ruling as pytorch#192434.
Stacked on pytorch#195809 (mps.py device_type attribute).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Nov 5, 2026
…own device field

## Summary

`CppWrapperMps` hardcoded `"mps"` in two device checks. Both now read `self.device` — the target-device field the wrapper hierarchy already carries — instead of adding a second concept next to it.

Changes (single commit, 4 files):
- `torch/_inductor/codegen/cpp_wrapper_gpu.py`: `CppWrapperGpu.__init__` keeps a subclass-set `device` (same `hasattr` pattern `CppWrapperCpu` already uses) instead of overwriting with `get_gpu_type()`; the lazy-scratch emitter uses `wrapper.device` rather than calling `get_gpu_type()` directly
- `torch/_inductor/codegen/cpp_wrapper_mps.py`: class attribute `device = "mps"`; the guard in `_generate_kernel_call_helper` and the filter in `codegen_additional_funcs` compare against `self.device`, message built from it; `create()` becomes a classmethod returning `cls()` so `wrapper_code_gen_cls.create(...)` (graph.py) gives a subclass its own class; the class comment states what a retarget still does NOT inherit (the `aoti_torch_mps_*` shims, `AOTIMetal*` types, include paths remain MPS-specific until the follow-up refactor — same caveat the companion attribute in `codegen/mps.py` carries)
- `test/inductor/test_gpu_cpp_wrapper.py`: the `FakeWrapper` in
  `test_lazy_triton_wrapper_forwards_launch_pdl` gains the `device` attribute the real
  wrappers always have (production-contract fidelity for the lazy-scratch path)
- `test/inductor/test_cpp_wrapper_asserts.py`: seven tests driving the production guard and filter paths (base message, matching line emits `get_mps_lib_0_handle`, non-matching emits nothing, subclass filter picks its own device's line, subclass guard rejects the base device, create returns the subclass); the fake graph handler is installed via `enterContext` so it cannot leak into later tests

## Motivation

`CppWrapperMps` is dispatched per-device via `register_backend_for_device` in `common.py`, yet the "which device does this class belong to" checks inside the class body were string literals, and the class grew a second target-device concept next to the existing `self.device` that already drives `device_codegen`, the shim header path and the generated `device_type`. A subclass setting only the second field got an object whose two fields disagreed. Unifying on `self.device` removes the disagreement by construction. An out-of-tree backend reusing this runtime-shader-library + lazy-handle + callback-launch model no longer needs to hand-edit literals or bypass the factory.

Companion to pytorch#195809 (same retarget limitation, sibling file).

## Test Plan

- [x] New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
- [x] Discrimination matrix (overlay into the installed wheel): untouched pre-change
  sources -> 3/10 fail; mps literals restored in the guard/filter only -> the 2 subclass
  tests fail; hasattr guard reverted in CppWrapperGpu.__init__ only -> the
  init/factory test fails. Every half of the change has a witness
- [x] Full file green on cpu venv (10/10) and on the NPU host with the overlay (10/10); the previously-broken `test_lazy_triton_wrapper_forwards_launch_pdl` passes both parametrizations with the FakeWrapper fix
- [x] Differential harness (16 cases: 14 must-be-identical + 2 knob counterexamples): default-path generated C++ byte-identical; knob cases show the subclass device is consumed
- [x] lint: lintrunner clean on all three files
- [ ] MPS end-to-end on mac (ciflow/mps) — not executable in this environment (aarch64 Linux, no Metal runtime); byte-identical argument + harness only, does not substitute mac CI

Ready once mac CI signal is observed.

## Review follow-up (2026-11-05 round)

This revision responds to the automated round on the previous head: the second device field (`device_type`) is gone in favour of `self.device` (their finding + the Cpu hasattr precedent); `create()` is a classmethod (factory-contract finding); the fake `V.graph` handler is scoped (leak finding); positive-path assertions were added and the misleadingly named subclass test split into filter+guard pairs (discrimination finding — measured: 3 of the 6 new tests fail on pre-change code).

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

Round 2 (findings on `ceeedf1c9eac`) is addressed in the follow-up push: FakeWrapper device attribute, a real-`__init__` test that fails when the hasattr guard is reverted, the class comment now listing everything the single `device` field actually retargets, inline raise style, the renamed guard test, module-level subclass/imports, and the `@requires_triton` gate question stays parked for the same maintainer ruling as pytorch#192434.
Stacked on pytorch#195809 (mps.py device_type attribute).
pytorchmergebot pushed a commit that referenced this pull request Nov 11, 2026
…ps (#196250)

## Summary

`CppWrapperMps` hardcoded `"mps"` in two device checks. Both now read `self.device` — the target-device field the wrapper hierarchy already carries — instead of adding a second concept next to it.

Changes (single commit, 4 files):
- `torch/_inductor/codegen/cpp_wrapper_gpu.py`: `CppWrapperGpu.__init__` keeps a subclass-set `device` (same `hasattr` pattern `CppWrapperCpu` already uses) instead of overwriting with `get_gpu_type()`; the lazy-scratch emitter uses `wrapper.device` rather than calling `get_gpu_type()` directly; `CppWrapperGpu.create` becomes a classmethod returning `cls()`, so a subclass that inherits it (e.g. one handed to `register_backend_for_device`) is built with its own overrides provided its `__init__` is argument-free
- `torch/_inductor/codegen/cpp_wrapper_mps.py`: class attribute `device = "mps"`; the guard in `_generate_kernel_call_helper` and the filter in `codegen_additional_funcs` compare against `self.device`, message built from it; the now-redundant `create` override is deleted (the base classmethod already returns `cls()`); the class comment keeps a short contract: `device` drives everything reading `self.device` or `device_codegen` (the per-device kernel-driver header included); a retargeting subclass must still override `get_device_include_path_aot` and the `aoti_torch_mps_*`/`AOTIMetal*` emission, and match `MetalKernel.device_type` in `codegen/mps.py`
- `test/inductor/test_gpu_cpp_wrapper.py`: the `FakeWrapper` in
  `test_lazy_triton_wrapper_forwards_launch_pdl` gains the `device` attribute the real
  wrappers always have (production-contract fidelity for the lazy-scratch path)
- `test/inductor/test_cpp_wrapper_asserts.py`: six tests driving the production guard and filter paths (base message, matching line emits `get_mps_lib_0_handle`, non-matching emits nothing, subclass filter picks its own device's line, subclass guard rejects the base device, create returns the subclass); the fake graph handler is installed via `enterContext` so it cannot leak into later tests

## Motivation

`CppWrapperMps` is dispatched per-device via `register_backend_for_device` in `common.py`, yet the "which device does this class belong to" checks inside the class body were string literals, and the class grew a second target-device concept next to the existing `self.device` that already drives `device_codegen` (per-device kernel-driver header included), the constant checks and the generated `device_type`. A subclass setting only the second field got an object whose two fields disagreed. Unifying on `self.device` removes the disagreement by construction. An out-of-tree backend reusing this runtime-shader-library + lazy-handle + callback-launch model no longer needs to hand-edit literals or bypass the factory.

Companion to #195809 (same retarget limitation, sibling file).

## Test Plan

- [x] New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
- [x] Discrimination matrix (overlay into the installed wheel): untouched pre-change
  sources -> 3/10 fail; mps literals restored in the guard/filter only -> the 2 subclass
  tests fail; hasattr guard reverted in CppWrapperGpu.__init__ only -> the
  init/factory test fails; `create` reverted to a staticmethod fails the factory type
  check. The lazy-scratch `wrapper.device` line is exercised but not discriminated
  (the fake's `codegen_device` ignores its argument)
- [x] Full file green on cpu venv (10/10) and on the NPU host with the overlay (10/10); the previously-broken `test_lazy_triton_wrapper_forwards_launch_pdl` passes both parametrizations with the FakeWrapper fix
- [x] Differential harness (16 cases: 14 must-be-identical + 2 knob counterexamples): default-path generated C++ byte-identical; knob cases show the subclass device is consumed
- [x] lint: lintrunner clean on all four files
- [ ] MPS end-to-end on mac (ciflow/mps) — not executable in this environment (aarch64 Linux, no Metal runtime); byte-identical argument + harness only, does not substitute mac CI

Ready once mac CI signal is observed.

## Review follow-up (2026-11-05 round)

This revision responds to the automated round on the previous head: the second device field (`device_type`) is gone in favour of `self.device` (their finding + the Cpu hasattr precedent); `create()` is a classmethod (factory-contract finding); the fake `V.graph` handler is scoped (leak finding); positive-path assertions were added and the misleadingly named subclass test split into filter+guard pairs (discrimination finding — measured: 3 of the 6 new tests fail on pre-change code).

Round 2 (findings on `ceeedf1c9eac`) is addressed in the follow-up push: FakeWrapper device attribute, a real-`__init__` test that fails when the hasattr guard is reverted, the class comment now listing everything the single `device` field actually retargets, inline raise style, the renamed guard test, module-level subclass/imports, and the `@requires_triton` gate question stays parked for the same maintainer ruling as #192434.

Round 3 (findings on `5b9881e2a60a`) addressed in the follow-up push: the two unneeded fake `device` lines were dropped (only the fake reaching `_generate_lazy_scratch` keeps the attribute); the factory-test docstring and the guard-revert comment now describe the stubbed `CppWrapperCpu.__init__` and the classmethod-vs-staticmethod distinction correctly; the cwc/cwg imports moved to module level.

Round 4 (review on `2c756fa806a5`) addressed in the follow-up push: the class comment is cut to the short contract above (the round-3 wording got the jit-include inheritance and the kernel-driver header wrong); the docstring also covers a class-attribute `device`. This paragraph supersedes the merge-readiness claims in the 2026-11-04 comments: the approval on `ef406784850` predates every `CppWrapperGpu` change, and a re-approval on the current head is what counts.

Round 5 (review on `b470dbfd171b`) addressed in the follow-up push: the redundant `CppWrapperMps.create` override is deleted so the factory test exercises the base `CppWrapperGpu.create` classmethod directly (unused imports dropped, test comment reworded); the out-of-tree behavior change of the base `create` is now stated in both the docstring and this body. The stale-body items that round flagged quoted the round-3 body text that was superseded before its review published; the current body carries the six-tests/four-files counts and the honest witness note.

Round 6 (review on `3a9038e4aed6`) addressed in the follow-up push: the docstring's create paragraph is now the one-line contract (returns `cls()`; a subclass that inherits it must have an argument-free `__init__`) instead of change-history wording, and the Test Plan witness claim was corrected once the Mps override was gone (the base classmethod is witnessed by the factory type check; only the lazy-scratch line stays non-discriminated). One ask for whoever lands this: please add the `ciflow/mps` label -- no current job on the PR builds a real `CppWrapperMps`, and the mac signal is the honest check for the device field path.

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

Labels

ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants