Skip to content

[Feature Refactoring]Parameterize device type checks in cpp_wrapper_mps - #196250

Closed
gavinwang269 wants to merge 1 commit into
pytorch:mainfrom
gavinwang269:cwm-device-type-decouple
Closed

gavinwang269 wants to merge 1 commit into
pytorch:mainfrom
gavinwang269:cwm-device-type-decouple

Conversation

@gavinwang269

@gavinwang269 gavinwang269 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

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

  • New suite, overlaying the patched sources into the env: 6/6 passed (cpu wheel venv)
  • 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)
  • 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
  • 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
  • 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.

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 8, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

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

The PR makes CppWrapperMps declare device = "mps" as a class attribute, has
CppWrapperGpu.__init__ keep a device a subclass already set, and turns
CppWrapperGpu.create into a classmethod returning cls(). Recommendation:
Approve. The last review's only blocking finding is fixed, and every remaining
point is non-blocking.

Findings (4):

[minor] torch/_inductor/codegen/cpp_wrapper_mps.py:26
Non-blocking, carried over from the last review and still open: no CI job on
this PR builds a real CppWrapperMps. CppWrapperMps.device and device_codegen are
now set by `device = "mps"` here together with the hasattr check at
cpp_wrapper_gpu.py:1295. Before, both came from get_gpu_type(). The new Linux
tests stub get_device_op_overrides and CppWrapperCpu.__init__. mac-mps.yml runs
only on ciflow/mps/* tags, and the trunk mac mps config needs ciflow/trunk/*.
The PR has neither label. The value should be the same on a Mac, but a
maintainer should add ciflow/mps before landing.

[minor] test/inductor/test_cpp_wrapper_asserts.py:333
Non-blocking, carried over and still open: the Test Plan in the PR body
contradicts itself. It says a staticmethod revert of create "fails the factory
type check", then says the new CppWrapperGpu classmethod create is "exercised
but not individually witnessed". CppWrapperMps.create was deleted, so
CppWrapperXpu.create(False, None, None) at :323 resolves to
CppWrapperGpu.create. A staticmethod revert would fail assertIs(type(made),
CppWrapperXpu) here, so create is individually witnessed. Only the lazy-scratch
half of the sentence is still true: FakeWrapper.codegen_device in
test_gpu_cpp_wrapper.py:750-752 ignores its argument. Fix: update the PR body to
match.

[minor] test/inductor/test_cpp_wrapper_asserts.py:216
Non-blocking: the class docstring says "which CppWrapperGpu now leaves alone
when a subclass  sets it". "now" describes this PR's change rather than the
behaviour, and it goes stale after merge. This is the same problem the last
review's blocking finding raised about the create() docstring. Fix: drop "now".

[minor] torch/_inductor/codegen/cpp_wrapper_gpu.py:1336
Non-blocking: the new classmethod create has no return annotation. Deleting
CppWrapperMps.create also dropped its -> "CppWrapperMps" annotation. Self is
already imported in this file (:9) and used at :1855. Fix: add -> Self. No
in-tree caller depends on it, because graph.py calls create through
type[PythonWrapperCodegen], so this is optional cleanup.

Reviewed commit: 9835b31 (NOT the current head 992117b)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ 2 Cancelled Jobs, 1 Unrelated Failure

As of commit 992117b with merge base 2e10e9e (image):

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

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

@pytorch-bot

pytorch-bot Bot commented Sep 8, 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 8, 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/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 cwm-device-type-decouple branch 2 times, most recently from 6704540 to 2079966 Compare September 14, 2026 03:12
@gavinwang269
gavinwang269 marked this pull request as ready for review September 14, 2026 10:38
@gavinwang269

Copy link
Copy Markdown
Contributor Author

Hi @desertfire — could you review this? cpp_wrapper_mps.py still has hardcoded device-type checks in its assert paths; this parameterizes them so out-of-tree backends reusing the cpp-wrapper assert machinery don't need monkey-patches. Scoped to this file only (plus its test), CUDA/MPS behavior unchanged. Would appreciate your perspective from the cpp_wrapper refactors (e.g. #182304).

@ezyang
ezyang requested a review from fffrog September 21, 2026 19:04
@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 21, 2026
@gavinwang269
gavinwang269 marked this pull request as draft September 22, 2026 06:32
@gavinwang269 gavinwang269 changed the title Parameterize device type checks in cpp_wrapper_mps [Feature Refactoring]Parameterize device type checks in cpp_wrapper_mps Oct 26, 2026
@desertfire

Copy link
Copy Markdown
Contributor

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@desertfire

Copy link
Copy Markdown
Contributor

@pytorchbot review

@pytorch-bot

pytorch-bot Bot commented Nov 3, 2026

Copy link
Copy Markdown

The automated review only re-runs on PRs labeled in progress and neither ready for review nor no automated review.

@gavinwang269
gavinwang269 marked this pull request as ready for review November 4, 2026 07:40
@gavinwang269

gavinwang269 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

@desertfire this is now ready for review -- thank you for the @pytorchbot rebase on 11-02, which landed cleanly onto viable/strict.

What the PR does, in one paragraph: torch/_inductor/codegen/cpp_wrapper_mps.py hardcodes the device type in its guards, so an out-of-tree backend reusing this codegen path has to copy the block and edit the literal. The change parameterizes those checks so the device type comes from a single overridable place, and test/inductor/test_cpp_wrapper_asserts.py pins both the default behaviour and the overridden one. Only these two files are touched, and the default is unchanged (device_type = "mps"), so on MPS hosts the guards compare against the same string as before; the diff changes which value is compared, not what is generated.

Two things I cannot do from this account and would appreciate help with:

  • the in progress label: your earlier @pytorchbot review was refused because the automated review only re-runs on PRs labeled in progress and without ready for review/no automated review, and adding labels is outside my permissions;
  • a review request: requestReviewsByLogin is also denied to my account, hence the mention here.

The branch is two days behind trunk, so I am asking the bot to rebase it onto viable/strict now to keep the review against a current base; I will hold off on further pushes unless the review finds something.

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@pytorchmergebot
pytorchmergebot force-pushed the cwm-device-type-decouple branch from 3dd6200 to ef40678 Compare November 4, 2026 07:44
@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 5, 2026
@gavinwang269
gavinwang269 force-pushed the cwm-device-type-decouple branch from 9835b31 to 992117b Compare November 5, 2026 14:15
@gavinwang269

Copy link
Copy Markdown
Contributor Author

cc @jansel - the automated review rounds converged (last one: nothing blocking) and @lizhihai137 approved; a re-approve on the current head plus CI approval is all that is left. Scope: cpp_wrapper_mps/cpp_wrapper_gpu read the wrapper's own device field instead of hardcoded "mps"/get_gpu_type(), and create() became a factory-correct classmethod - the MPS path is byte-identical on default paths, verified with a generated-code diff harness.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

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

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot recheck

@pytorch-bot

pytorch-bot Bot commented Nov 10, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: argument command: invalid choice: 'recheck' (choose from 'merge', 'revert', 'rebase', 'label', 'drci', 'review', 'triage', 'pre-review', 'lint', 'fix-lint', 'apply-lint', 'cherry-pick')

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,review,triage,pre-review,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

@gavinwang269

Copy link
Copy Markdown
Contributor Author

The two merge attempts on this PR are failing on infrastructure, not on this diff. Recording the evidence so that someone with permission can either re-run the jobs or force-merge with the reason.

Current check state at head 992117b4592: 344 passing, 8 skipping, 4 still running, and exactly 3 failing — Lint / Test collect_env (older_python_version | with_torch | without_torch, linux.24_04.4x).

In that run (job 130206148298) the older_python_version cell dies during environment setup, before anything runs:

2026-11-10T23:32:25.3295961Z ##[error]The version '3.8' with architecture 'x64' was not found for Ubuntu 26.04.

The other two cells of that matrix (with_torch, without_torch) were cancelled as a consequence of that setup failure — they report no test result of their own.

Three facts that make this clearly unrelated to the change under review:

  1. The same three Test collect_env cells on this same head all passed on 11-05 17:38, in run 42043197041. The failing run 42924085780 was created on 11-10 23:32, i.e. by the merge attempt itself.
  2. This PR touches only torch/_inductor/codegen/cpp_wrapper_gpu.py, torch/_inductor/codegen/cpp_wrapper_mps.py, test/inductor/test_cpp_wrapper_asserts.py and test/inductor/test_gpu_cpp_wrapper.py. Nothing on the collect_env path.
  3. The failure text is actions/setup-python being unable to resolve Python 3.8 on the runner image behind the linux.24_04.4x class; there is no assertion failure anywhere in the log.

Everything else is at the gate already: reviewDecision: APPROVED (@desertfire approved this exact head on 11-10, and @lizhihai137 approved earlier), mergeable: true, labels as they should be (triaged, open source, module: inductor, ciflow/trunk, ciflow/inductor, ciflow/torchtitan, release notes: inductor (aoti), ready for review), and all 14 review threads have been answered in-thread and resolved.

Could someone re-run the three failed jobs, or:

@pytorchbot merge -f "Trunk infra: actions/setup-python cannot resolve Python 3.8 on the linux.24_04.4x image (run 42924085780); the same head passed these three collect_env cells on 11-05 (run 42043197041); the PR does not touch collect_env."

I cannot retry it myself — both actions/runs/42924085780/rerun and .../rerun-failed-jobs return Must have admin rights to Repository.

@pytorch-bot

pytorch-bot Bot commented Nov 11, 2026

Copy link
Copy Markdown

You are not authorized to force merges to this repository. Please use the regular @pytorchmergebot merge command instead

@desertfire

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 3 checks: Lint / Test collect_env (with_torch, linux.24_04.4x), Lint / Test collect_env (without_torch, linux.24_04.4x), Lint / Test collect_env (older_python_version, linux.24_04.4x)

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: inductor (aoti) triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants