Repository navigation
[Feature Refactoring] Make MetalKernel launch device overridable via a class attribute - #195809
gavinwang269 wants to merge 1 commit into
Conversation
🔗 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 ( 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. |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
5873ccf to
b2c4ea9
Compare
|
@claude review these changes |
|
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 Full reviewPR Review: #195809SummaryReplaces the Testing
API Design
RecommendationRequest 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- |
…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).
b2c4ea9 to
b9424db
Compare
|
Thanks for the detailed review -- the test block was the problem, and your own last line in the white-box bullet (" Diff shape now
Point by point on the testing items
API design
Test plan (rerun after trimming) 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 ( |
|
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 |
|
@claude review again |
|
Claude finished @jansel's task in 7m 36s —— View job Re-reviewed the trimmed head ( Full reviewPR Review: #195809 (re-review of
|
| 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_typeappears nowhere inSIMDKernel(simd.py) orKernel/CodeGen(common.py) — the only otherdevice_typeintorch/_inductor/codegen/outside cutlass/cpp-utils iscommon.py:522-528, a local inget_backend_features, andtriton.py's locals fromV.graph.get_current_device_or_throw().type. Nothing readskernel.device_typereflectively, so the new attribute cannot be picked up by unrelated machinery. torch.device("mps")andtorch.device(self.device_type)construct the same object, and the MPS branch atwrapper.py:4362-4364dispatches only ondevice.type(it never readsdevice.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.pynow returns only:549(the overrides table key, correctly left alone) and:567(the new default).
Nits (non-blocking)
-
mps.py:566points 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 withgit blamestill 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"
-
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 drivecall_kernel()end-to-end on the macOS--mpsshards (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/+1production diff) is also a defensible landing state if @jansel prefers no test for a constant. -
The comment's scope, for completeness: it names only
PythonWrapperCodegen, whilecpp_wrapper_mps.py:82-83(assert ondevice.type != "mps") and:266(shader-library pass skipping non-mpsKernelCallLines) 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 getmps_lib_*kernel names fromMetalScheduling.define_kernel(mps.py:1239), whichCppWrapperMpsmatches 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.
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).
|
Hi @kurtamohler, could you take a look at this PR when you have a chance? It makes the Current status:
cc @jansel in case you want to double-check the final state. Thanks! |
|
@pytorchbot merge |
Merge startedYour 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 |
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).
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).
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).
…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).
…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).
…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).
…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).
…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).
…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).
…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).
…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
Motivation
MetalKernel.call_kernel()is the only kernel-call site across the in-tree Inductor codegen backends that pins a device literal: it unconditionally passesdevice=torch.device("mps")togenerate_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
MetalKernelfor a device that follows the same one-thread-per-element launch convention) currently has to copy the wholecall_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
device_type = "mps"class attribute toMetalKernel, next to the existing class-level knobs (max_threadgroup_size,simd_group_size, ...).call_kernel()derives the launch device fromself.device_typeinstead of the literal.test/inductor/test_mps_basic.py's existing MPS-gatedMPSBasicTestsclass (assertEqual(MetalKernel.device_type, "mps")). An earlier version of this PR shipped a larger test block that drovecall_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 ameta-device retarget the real wrapper rejects. Those were dropped; the existing end-to-end MPS tests already drivecall_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 toV.graph.get_current_device_or_throw(), like Triton (wrapper.pyalready doesdevice = 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 ofPythonWrapperCodegen._generate_kernel_call_helper()only dispatches ondevice.type(it never consumes the value or the index formps). No other backend references the touched symbols, and the change adds no import-time device probing.Test Plan
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_npudoes 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_typeis not usable end-to-end on its own yet:PythonWrapperCodegen._generate_kernel_call_helper()dispatches ondevice.type not in ("cuda", "xpu")and raises for unknown types, andCppWrapperMps._generate_kernel_call_helper()assertsdevice.type == "mps"while its shader-library pass skips non-mpsKernelCallLines. 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 theCppWrapperMpsassert) touches the cpu/cuda/xpu paths and deserves its own PR. This is noted in the code comment abovedevice_typeas 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