Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/187939
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 1 Unrelated FailureAs of commit 934c92e with merge base 9f132a8 ( NEW FAILURE - The following job has failed:
BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
@pytorchbot merge |
|
This PR needs to be approved by an authorized maintainer before merge. |
|
The label |
|
The label |
|
@claude Conduct a thorough review of this PR. 1) Check for correctness and bugs 2) check for race conditions and deadlocks when using multiple communicators/process groups 3) check if main logic is minimal and clean 4) For tests, see if they are efficient and maximally use existing test infrastructure. Tests should comprehensively test functionality yet should be minimal and compact 5) Suggest required changes |
|
I'll analyze this and get back to you. |
1 similar comment
|
I'll analyze this and get back to you. |
|
@fegin mentioned SharedTensor is deprecated and we shouldn't accept new features. @kisnwangg -- what's your motivation for this? |
|
|
I'll analyze this and get back to you. |
1 similar comment
|
I'll analyze this and get back to you. |
| if not ( | ||
| isinstance(device, torch.device) | ||
| and device.index == torch.cuda.current_device() | ||
| and device.type == device_type | ||
| and device.index == device_module.current_device() |
There was a problem hiding this comment.
Here we should use API in torch.accelerator instead of _get_device_module
| @@ -641,7 +683,7 @@ def to(self, *args, **kwargs) -> ShardedTensor: | |||
| elif self._process_group._get_backend_name() == "gloo": | |||
| current_device = torch.device("cpu") | |||
| else: | |||
| current_device = torch.device(torch.accelerator.current_device_index()) | |||
| current_device = self._get_preferred_device() | |||
There was a problem hiding this comment.
This creates a device with just an index. use torch.device(device_to.type, current_idx) for
clarity.
| # if device_to set to accelerator, set to current device even | ||
| # if user specifies the device index. | ||
| device_module = _get_device_module(device_to.type) | ||
| current_idx = device_module.current_device() |
There was a problem hiding this comment.
No, the original code is already device-agnostic.
|
@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 |
Merge failedReason: 1 jobs have failed, first few of them are: trunk / win-vs2022-cpu-py3 / test (default, 2, 4, windows.4xlarge.nonephemeral) Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 2 checks: torchtitan-test / torchtitan-x-pytorch-test / test-osdc (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8), trunk / win-vs2022-cpu-py3 / test (default, 2, 4, windows.4xlarge.nonephemeral) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…gnostic (pytorch#187939) # Make ShardedTensor Device Transfer Methods Hardware-Agnostic ## Summary Refactored `ShardedTensor.cuda()` and `ShardedTensor.to()` methods to support third-party accelerator devices (e.g., NPU, XPU) by removing hardcoded CUDA-specific logic. The implementation leverages the `torch.accelerator` API to dynamically determine the current accelerator device. --- ## Problem ### The Gap The `ShardedTensor` class in `torch/distributed/_shard/sharded_tensor/api.py` contained hardcoded CUDA-specific logic in its device transfer methods, preventing third-party hardware vendors (e.g., Huawei NPU, Intel XPU) from integrating their accelerators into the sharded tensor ecosystem. ### Hardcoded patterns (before fix): | Location | Original Code | Issue | |----------|---------------|-------| | `cuda()` method | `torch.cuda.current_device()` | Direct CUDA API call | | `cuda()` method | `shard.tensor.cuda(...)` | Calls tensor.cuda() instead of device-agnostic tensor.to() | | `cuda()` method | `meta.placement.device().type != "cuda"` | Hardcoded string comparison | | `to()` method | `device_to.type in {"cuda", "xpu"}` | Explicit device type list | --- ## Implementation The implementation took a simpler approach than originally proposed, modifying the existing methods directly rather than creating a new `_to_device()` abstraction. ### Changes to `cuda()` method 1. **Device index retrieval**: Changed from `torch.cuda.current_device()` to `torch.accelerator.current_device_index()` 2. **Error message**: Made device-type aware: ```python # Before: raise AssertionError( 'Only device without device id (e.g. "cpu" or "cuda") is expected for ShardedTensor!' ) # After: raise AssertionError( f"Only device without device id (e.g. 'cpu' or '{device.type}') " f"is expected for ShardedTensor!" ) ``` 3. **Tensor transfer**: Changed from `shard.tensor.cuda()` to `shard.tensor.to()`: ```python # Before: cuda_tensor = shard.tensor.cuda( device=current_device, non_blocking=non_blocking, memory_format=memory_format, ) # After: new_tensor = shard.tensor.to( device=current_device, non_blocking=non_blocking, memory_format=memory_format, ) ``` 4. **Metadata comparison**: Changed from hardcoded `"cuda"` to dynamic `current_device.type`: ```python # Before: if meta.placement.device().type != "cuda": # After: if meta.placement.device().type != current_device.type: ``` ### Changes to `to()` method Changed the device type check from an explicit allowlist to a denylist: ```python # Before: if device_to.type in {"cuda", "xpu"}: # if device_to set to cuda, set to current device even # if user specify the device index. # After: if device_to.type != "cpu": # if device_to set to accelerator, set to current device even # if user specifies the device index. ``` This change: - Removes the need to add each new accelerator type (npu, xpu, etc.) explicitly - Treats all non-CPU devices uniformly as accelerators - Uses `torch.accelerator.current_device_index()` to get the current device --- ## Why This Approach 1. **Using `torch.accelerator` API**: - `torch.accelerator.current_device_index()` returns the current accelerator device index - `torch.device(int)` automatically uses the current accelerator type - This abstracts away device-specific calls 2. **Using denylist (`!= "cpu"`) instead of allowlist**: - Automatically supports any new accelerator type - No need to update the code when adding support for NPU, XPU, etc. - Simpler and more maintainable --- ## Backward Compatibility | API | Change | Impact | |-----|--------|--------| | `.cuda()` | Uses accelerator API | No breaking change - identical behavior for CUDA users | | `.to(device)` | Uses denylist for device check | Extends support to all accelerator types | | `.cpu()` | No changes | Unaffected | All existing CUDA workflows remain identical. The only observable change is that `to()` now works correctly with any non-CPU accelerator device. --- ## Test Plan **Existing tests validate the changes:** 1. `test_sharded_tensor_to_cuda` - validates CUDA transfer behavior 2. `test_sharded_tensor_to_test` - validates `to()` method with various device/dtype combinations 3. `test_sharded_tensor_to_cpu` - validates CPU transfer behavior The implementation was verified against the existing test suite. --- ## References - `torch.accelerator` module: `torch/accelerator/__init__.py` - `current_device_index()`: returns current accelerator device index - `_get_preferred_device()` implementation: `torch/distributed/_shard/sharded_tensor/api.py` (preserved for third-party backend support via ProcessGroup) Pull Request resolved: pytorch#187939 Approved by: https://github.com/guangyey, https://github.com/malfet
…gnostic (pytorch#187939) # Make ShardedTensor Device Transfer Methods Hardware-Agnostic ## Summary Refactored `ShardedTensor.cuda()` and `ShardedTensor.to()` methods to support third-party accelerator devices (e.g., NPU, XPU) by removing hardcoded CUDA-specific logic. The implementation leverages the `torch.accelerator` API to dynamically determine the current accelerator device. --- ## Problem ### The Gap The `ShardedTensor` class in `torch/distributed/_shard/sharded_tensor/api.py` contained hardcoded CUDA-specific logic in its device transfer methods, preventing third-party hardware vendors (e.g., Huawei NPU, Intel XPU) from integrating their accelerators into the sharded tensor ecosystem. ### Hardcoded patterns (before fix): | Location | Original Code | Issue | |----------|---------------|-------| | `cuda()` method | `torch.cuda.current_device()` | Direct CUDA API call | | `cuda()` method | `shard.tensor.cuda(...)` | Calls tensor.cuda() instead of device-agnostic tensor.to() | | `cuda()` method | `meta.placement.device().type != "cuda"` | Hardcoded string comparison | | `to()` method | `device_to.type in {"cuda", "xpu"}` | Explicit device type list | --- ## Implementation The implementation took a simpler approach than originally proposed, modifying the existing methods directly rather than creating a new `_to_device()` abstraction. ### Changes to `cuda()` method 1. **Device index retrieval**: Changed from `torch.cuda.current_device()` to `torch.accelerator.current_device_index()` 2. **Error message**: Made device-type aware: ```python # Before: raise AssertionError( 'Only device without device id (e.g. "cpu" or "cuda") is expected for ShardedTensor!' ) # After: raise AssertionError( f"Only device without device id (e.g. 'cpu' or '{device.type}') " f"is expected for ShardedTensor!" ) ``` 3. **Tensor transfer**: Changed from `shard.tensor.cuda()` to `shard.tensor.to()`: ```python # Before: cuda_tensor = shard.tensor.cuda( device=current_device, non_blocking=non_blocking, memory_format=memory_format, ) # After: new_tensor = shard.tensor.to( device=current_device, non_blocking=non_blocking, memory_format=memory_format, ) ``` 4. **Metadata comparison**: Changed from hardcoded `"cuda"` to dynamic `current_device.type`: ```python # Before: if meta.placement.device().type != "cuda": # After: if meta.placement.device().type != current_device.type: ``` ### Changes to `to()` method Changed the device type check from an explicit allowlist to a denylist: ```python # Before: if device_to.type in {"cuda", "xpu"}: # if device_to set to cuda, set to current device even # if user specify the device index. # After: if device_to.type != "cpu": # if device_to set to accelerator, set to current device even # if user specifies the device index. ``` This change: - Removes the need to add each new accelerator type (npu, xpu, etc.) explicitly - Treats all non-CPU devices uniformly as accelerators - Uses `torch.accelerator.current_device_index()` to get the current device --- ## Why This Approach 1. **Using `torch.accelerator` API**: - `torch.accelerator.current_device_index()` returns the current accelerator device index - `torch.device(int)` automatically uses the current accelerator type - This abstracts away device-specific calls 2. **Using denylist (`!= "cpu"`) instead of allowlist**: - Automatically supports any new accelerator type - No need to update the code when adding support for NPU, XPU, etc. - Simpler and more maintainable --- ## Backward Compatibility | API | Change | Impact | |-----|--------|--------| | `.cuda()` | Uses accelerator API | No breaking change - identical behavior for CUDA users | | `.to(device)` | Uses denylist for device check | Extends support to all accelerator types | | `.cpu()` | No changes | Unaffected | All existing CUDA workflows remain identical. The only observable change is that `to()` now works correctly with any non-CPU accelerator device. --- ## Test Plan **Existing tests validate the changes:** 1. `test_sharded_tensor_to_cuda` - validates CUDA transfer behavior 2. `test_sharded_tensor_to_test` - validates `to()` method with various device/dtype combinations 3. `test_sharded_tensor_to_cpu` - validates CPU transfer behavior The implementation was verified against the existing test suite. --- ## References - `torch.accelerator` module: `torch/accelerator/__init__.py` - `current_device_index()`: returns current accelerator device index - `_get_preferred_device()` implementation: `torch/distributed/_shard/sharded_tensor/api.py` (preserved for third-party backend support via ProcessGroup) Pull Request resolved: pytorch#187939 Approved by: https://github.com/guangyey, https://github.com/malfet
…gnostic (pytorch#187939) # Make ShardedTensor Device Transfer Methods Hardware-Agnostic ## Summary Refactored `ShardedTensor.cuda()` and `ShardedTensor.to()` methods to support third-party accelerator devices (e.g., NPU, XPU) by removing hardcoded CUDA-specific logic. The implementation leverages the `torch.accelerator` API to dynamically determine the current accelerator device. --- ## Problem ### The Gap The `ShardedTensor` class in `torch/distributed/_shard/sharded_tensor/api.py` contained hardcoded CUDA-specific logic in its device transfer methods, preventing third-party hardware vendors (e.g., Huawei NPU, Intel XPU) from integrating their accelerators into the sharded tensor ecosystem. ### Hardcoded patterns (before fix): | Location | Original Code | Issue | |----------|---------------|-------| | `cuda()` method | `torch.cuda.current_device()` | Direct CUDA API call | | `cuda()` method | `shard.tensor.cuda(...)` | Calls tensor.cuda() instead of device-agnostic tensor.to() | | `cuda()` method | `meta.placement.device().type != "cuda"` | Hardcoded string comparison | | `to()` method | `device_to.type in {"cuda", "xpu"}` | Explicit device type list | --- ## Implementation The implementation took a simpler approach than originally proposed, modifying the existing methods directly rather than creating a new `_to_device()` abstraction. ### Changes to `cuda()` method 1. **Device index retrieval**: Changed from `torch.cuda.current_device()` to `torch.accelerator.current_device_index()` 2. **Error message**: Made device-type aware: ```python # Before: raise AssertionError( 'Only device without device id (e.g. "cpu" or "cuda") is expected for ShardedTensor!' ) # After: raise AssertionError( f"Only device without device id (e.g. 'cpu' or '{device.type}') " f"is expected for ShardedTensor!" ) ``` 3. **Tensor transfer**: Changed from `shard.tensor.cuda()` to `shard.tensor.to()`: ```python # Before: cuda_tensor = shard.tensor.cuda( device=current_device, non_blocking=non_blocking, memory_format=memory_format, ) # After: new_tensor = shard.tensor.to( device=current_device, non_blocking=non_blocking, memory_format=memory_format, ) ``` 4. **Metadata comparison**: Changed from hardcoded `"cuda"` to dynamic `current_device.type`: ```python # Before: if meta.placement.device().type != "cuda": # After: if meta.placement.device().type != current_device.type: ``` ### Changes to `to()` method Changed the device type check from an explicit allowlist to a denylist: ```python # Before: if device_to.type in {"cuda", "xpu"}: # if device_to set to cuda, set to current device even # if user specify the device index. # After: if device_to.type != "cpu": # if device_to set to accelerator, set to current device even # if user specifies the device index. ``` This change: - Removes the need to add each new accelerator type (npu, xpu, etc.) explicitly - Treats all non-CPU devices uniformly as accelerators - Uses `torch.accelerator.current_device_index()` to get the current device --- ## Why This Approach 1. **Using `torch.accelerator` API**: - `torch.accelerator.current_device_index()` returns the current accelerator device index - `torch.device(int)` automatically uses the current accelerator type - This abstracts away device-specific calls 2. **Using denylist (`!= "cpu"`) instead of allowlist**: - Automatically supports any new accelerator type - No need to update the code when adding support for NPU, XPU, etc. - Simpler and more maintainable --- ## Backward Compatibility | API | Change | Impact | |-----|--------|--------| | `.cuda()` | Uses accelerator API | No breaking change - identical behavior for CUDA users | | `.to(device)` | Uses denylist for device check | Extends support to all accelerator types | | `.cpu()` | No changes | Unaffected | All existing CUDA workflows remain identical. The only observable change is that `to()` now works correctly with any non-CPU accelerator device. --- ## Test Plan **Existing tests validate the changes:** 1. `test_sharded_tensor_to_cuda` - validates CUDA transfer behavior 2. `test_sharded_tensor_to_test` - validates `to()` method with various device/dtype combinations 3. `test_sharded_tensor_to_cpu` - validates CPU transfer behavior The implementation was verified against the existing test suite. --- ## References - `torch.accelerator` module: `torch/accelerator/__init__.py` - `current_device_index()`: returns current accelerator device index - `_get_preferred_device()` implementation: `torch/distributed/_shard/sharded_tensor/api.py` (preserved for third-party backend support via ProcessGroup) Pull Request resolved: pytorch#187939 Approved by: https://github.com/guangyey, https://github.com/malfet
…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 `TestMetalKernelDeviceType` to `test/inductor/test_mps_basic.py`: it drives the production `call_kernel()` with a stubbed kernel state and a mocked wrapper, and asserts the `device` kwarg follows the class attribute (`"xpu"` as the retarget example, which is present in every build's device type table). One case asserting the default `"mps"` binding runs where MPS is built.
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 kernel-side class attribute keeps the value sourced from the kernel itself (no new dependency on scheduler state at call time), preserves the existing failure mode of an explicit device, 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
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -k MetalKernelDeviceType -q
# 2 passed, 1 skipped (torch 2.15.0.dev20260901+cpu wheel, changed mps.py overlaid)
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -q
# head: 62 collected, 2 passed, 60 skipped
# base commit (same command, test file from 00ea408): 59 collected, 59 skipped
# the 3-collected difference is exactly the new class; all pre-existing cases unchanged
```
```
lintrunner init
lintrunner torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# No issues from any linter except PYREFLY. PYREFLY is not meaningful on this
# unbuilt source tree: it reports ~20k missing-attribute errors tree-wide
# against unmodified lines (e.g. torch.bool), both on this diff and on the
# base commit, so the local run cannot adjudicate it either way. CI's pyrefly
# job will exercise the change.
```
The macOS shards (`linux-macos / test,mps` / AOTInductor MPS) exercise the real Metal path in CI. 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` still hits two further device checks on the wrapper side, deliberately out of scope here to keep this diff small: `PythonWrapperCodegen._generate_kernel_call_helper()` dispatches on `device.type not in ("cuda", "xpu")` and raises for unknown types, and `CppWrapperMps.generate_kernel_call()` asserts `device.type == "mps"` while its shader-library pass skips non-mps `KernelCallLine`s. Those read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
Disclosure: this PR was authored with the assistance of an AI coding assistant, under direct human review; the human author takes responsibility for the change.
…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 `TestMetalKernelDeviceType` to `test/inductor/test_mps_basic.py`: it drives the production `call_kernel()` with a stubbed kernel state and a mocked wrapper, and asserts the `device` kwarg follows the class attribute (`"xpu"` as the retarget example, which is present in every build's device type table). One case asserting the default `"mps"` binding runs where MPS is built.
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 kernel-side class attribute keeps the value sourced from the kernel itself (no new dependency on scheduler state at call time), preserves the existing failure mode of an explicit device, 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
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -k MetalKernelDeviceType -q
# 2 passed, 1 skipped (torch 2.15.0.dev20260901+cpu wheel, changed mps.py overlaid)
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -q
# head: 62 collected, 2 passed, 60 skipped
# base commit (same command, test file from 00ea408): 59 collected, 59 skipped
# the 3-collected difference is exactly the new class; all pre-existing cases unchanged
```
```
lintrunner init
lintrunner torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# No issues from any linter except PYREFLY. PYREFLY is not meaningful on this
# unbuilt source tree: it reports ~20k missing-attribute errors tree-wide
# against unmodified lines (e.g. torch.bool), both on this diff and on the
# base commit, so the local run cannot adjudicate it either way. CI's pyrefly
# job will exercise the change.
```
The macOS shards (`linux-macos / test,mps` / AOTInductor MPS) exercise the real Metal path in CI. 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` still hits two further device checks on the wrapper side, deliberately out of scope here to keep this diff small: `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 `KernelCallLine`s. Those read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
Disclosure: this PR was authored with the assistance of an AI coding assistant, under direct human review; the human author takes responsibility for the change.
…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 `TestMetalKernelDeviceType` to `test/inductor/test_mps_basic.py`: it drives the production `call_kernel()` with a stubbed kernel state and a mocked wrapper, and asserts the `device` kwarg follows the class attribute (`"xpu"` as the retarget example, which is present in every build's device type table). One case asserting the default `"mps"` binding runs where MPS is built.
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 kernel-side class attribute keeps the value sourced from the kernel itself (no new dependency on scheduler state at call time), preserves the existing failure mode of an explicit device, 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
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -k MetalKernelDeviceType -q
# 2 passed, 1 skipped (torch 2.15.0.dev20260901+cpu wheel, changed mps.py overlaid)
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -q
# head: 62 collected, 2 passed, 60 skipped
# base commit (same command, test file from 00ea408): 59 collected, 59 skipped
# the 3-collected difference is exactly the new class; all pre-existing cases unchanged
```
```
lintrunner init
lintrunner torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# No issues from any linter except PYREFLY. PYREFLY is not meaningful on this
# unbuilt source tree: it reports ~20k missing-attribute errors tree-wide
# against unmodified lines (e.g. torch.bool), both on this diff and on the
# base commit, so the local run cannot adjudicate it either way. CI's pyrefly
# job will exercise the change.
```
The macOS shards (`linux-macos / test,mps` / AOTInductor MPS) exercise the real Metal path in CI. 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` still hits two further device checks on the wrapper side, deliberately out of scope here to keep this diff small: `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 `KernelCallLine`s. Those read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
…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 tests to `test/inductor/test_mps_basic.py`. `TestMetalKernelDeviceType` (`hw_classification = GENERIC`) drives the production `call_kernel()` with a stubbed kernel state and a mocked wrapper, and asserts the `device` kwarg follows the class attribute; `"meta"` is the retarget example since it is a core device type in every build and carries no accelerator semantics (the cases never allocate or initialize a device). A second class `TestMetalKernelDeviceTypeMps` (`hw_classification = MPS`, gated on `torch.backends.mps.is_built()`) asserts the default `"mps"` binding on MPS builds. The shared stubbing lives in a non-collected harness base.
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 kernel-side class attribute keeps the value sourced from the kernel itself (no new dependency on scheduler state at call time), preserves the existing failure mode of an explicit device, 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
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -k MetalKernelDeviceType -q
# 2 passed, 1 skipped (torch 2.15.0.dev20260901+cpu wheel, changed mps.py overlaid)
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -q
# head: 62 collected, 2 passed, 60 skipped
# base commit (same command, test file from 00ea408): 59 collected, 59 skipped
# the 3-collected difference is exactly the new class; all pre-existing cases unchanged
```
```
lintrunner init
lintrunner torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# No issues from any linter except PYREFLY. PYREFLY is not meaningful on this
# unbuilt source tree: it reports ~20k missing-attribute errors tree-wide
# against unmodified lines (e.g. torch.bool), both on this diff and on the
# base commit, so the local run cannot adjudicate it either way. CI's pyrefly
# job will exercise the change.
```
The macOS shards (`linux-macos / test,mps` / AOTInductor MPS) exercise the real Metal path in CI. 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` still hits two further device checks on the wrapper side, deliberately out of scope here to keep this diff small: `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 `KernelCallLine`s. Those read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
…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 tests to `test/inductor/test_mps_basic.py`. `TestMetalKernelDeviceType` (`hw_classification = GENERIC`) drives the production `call_kernel()` with a stubbed kernel state and a mocked wrapper, and asserts the `device` kwarg follows the class attribute; `"meta"` is the retarget example since it is a core device type in every build and carries no accelerator semantics (the cases never allocate or initialize a device). A second class `TestMetalKernelDeviceTypeMps` (`hw_classification = MPS`, gated on `torch.backends.mps.is_built()`) asserts the default `"mps"` binding on MPS builds. The shared stubbing lives in a non-collected harness base.
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 kernel-side class attribute keeps the value sourced from the kernel itself (no new dependency on scheduler state at call time), preserves the existing failure mode of an explicit device, 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
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -k MetalKernelDeviceType -q
# 2 passed, 1 skipped (torch 2.15.0.dev20260901+cpu wheel, changed mps.py overlaid)
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -q
# head: 62 collected, 2 passed, 60 skipped
# base commit (same command, test file from 00ea408): 59 collected, 59 skipped
# the 3-collected difference is exactly the new class; all pre-existing cases unchanged
```
```
lintrunner init
lintrunner torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# No issues from any linter except PYREFLY. PYREFLY is not meaningful on this
# unbuilt source tree: it reports ~20k missing-attribute errors tree-wide
# against unmodified lines (e.g. torch.bool), both on this diff and on the
# base commit, so the local run cannot adjudicate it either way. CI's pyrefly
# job will exercise the change.
```
The macOS shards (`linux-macos / test,mps` / AOTInductor MPS) exercise the real Metal path in CI. 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` still hits two further device checks on the wrapper side, deliberately out of scope here to keep this diff small: `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 `KernelCallLine`s. Those read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
…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 tests to `test/inductor/test_mps_basic.py`. `TestMetalKernelDeviceType` (`hw_classification = GENERIC`) drives the production `call_kernel()` with a stubbed kernel state and a mocked wrapper, and asserts the `device` kwarg follows the class attribute; `"meta"` is the retarget example since it is a core device type in every build and carries no accelerator semantics (the cases never allocate or initialize a device). A second class `TestMetalKernelDeviceTypeMps` (`hw_classification = MPS`) takes the `device` parameter via `instantiate_device_type_tests(..., only_for=("mps",), allow_mps=True)` and asserts the default binding resolves to the instantiated device on MPS builds (macOS CI). The shared stubbing lives in a non-collected harness base.
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 kernel-side class attribute keeps the value sourced from the kernel itself (no new dependency on scheduler state at call time), preserves the existing failure mode of an explicit device, 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
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -k MetalKernelDeviceType -q
# 2 passed, 1 skipped (torch 2.15.0.dev20260901+cpu wheel, changed mps.py overlaid)
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -q
# head: 61 collected, 2 passed, 59 skipped
# base commit (same command, test file from 00ea408): 59 collected, 59 skipped
# the +2 collected are the new GENERIC cases; the MPS-classified case is
# instantiated by instantiate_device_type_tests only for MPS builds and runs
# in the macOS CI shards
```
```
lintrunner init
lintrunner torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# No issues from any linter except PYREFLY. PYREFLY is not meaningful on this
# unbuilt source tree: it reports ~20k missing-attribute errors tree-wide
# against unmodified lines (e.g. torch.bool), both on this diff and on the
# base commit, so the local run cannot adjudicate it either way. CI's pyrefly
# job will exercise the change.
```
The macOS shards (`linux-macos / test,mps` / AOTInductor MPS) exercise the real Metal path in CI. 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` still hits two further device checks on the wrapper side, deliberately out of scope here to keep this diff small: `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 `KernelCallLine`s. Those read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
…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 tests to `test/inductor/test_mps_basic.py`. `TestMetalKernelDeviceType` (`hw_classification = GENERIC`) drives the production `call_kernel()` with a stubbed kernel state and a mocked wrapper, and asserts the `device` kwarg follows the class attribute; `"meta"` is the retarget example since it is a core device type in every build and carries no accelerator semantics (the cases never allocate or initialize a device). A second class `TestMetalKernelDefaultDevice` (`hw_classification = MPS`) takes the `device` parameter via `instantiate_device_type_tests(..., only_for=("mps",), allow_mps=True)` and asserts the default binding resolves to the instantiated device type on MPS builds (macOS CI). The shared stubbing lives in a non-collected harness base.
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 kernel-side class attribute keeps the value sourced from the kernel itself (no new dependency on scheduler state at call time), preserves the existing failure mode of an explicit device, 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
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -q
# head: 61 collected, 2 passed, 59 skipped (torch 2.15.0.dev20260901+cpu wheel,
# changed mps.py overlaid)
/tmp/torchenv/bin/python -m pytest $PT/test/inductor/test_mps_basic.py -k MetalKernel -q
# 2 passed, 59 deselected
```
Base commit (`00ea4089`, same command): 59 collected, 59 skipped. The +2 collected are the new GENERIC cases. The MPS-classified case is instantiated by `instantiate_device_type_tests` only for MPS builds, so on Linux it is absent from collection rather than skipped; the `TestMetalKernelDefaultDeviceMPS` variant runs in the macOS shards, where the real `torch.device("mps")` construction is exercised. The instantiated device arrives as the primary device (e.g. "mps:0"), so the variant compares `.type` and pins the index-free contract of the kernel-side default.
```
lintrunner init
lintrunner torch/_inductor/codegen/mps.py test/inductor/test_mps_basic.py
# ok No lint issues.
```
Local PYREFLY was excluded from the adjudication above: on this unbuilt source tree it emits ~20k missing-attribute errors tree-wide against unmodified lines (e.g. `torch.bool`), on both the base commit and this diff, so it cannot discriminate here. CI's pyrefly job only covers `torch/` (test/ is not in its project includes), 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 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` still hits two further device checks on the wrapper side, deliberately out of scope here to keep this diff small: `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 `KernelCallLine`s. Those read like good standalone follow-ups (a negated check like the merged pytorch#187939 used for ShardedTensor would fit the wrapper side).
…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).
…attribute (#195809) ## 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 00ea408 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 `KernelCallLine`s. 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. Pull Request resolved: #195809 Approved by: https://github.com/jansel, https://github.com/kurtamohler

Make ShardedTensor Device Transfer Methods Hardware-Agnostic
Summary
Refactored
ShardedTensor.cuda()andShardedTensor.to()methods to support third-party accelerator devices (e.g., NPU, XPU) by removing hardcoded CUDA-specific logic. The implementation leverages thetorch.acceleratorAPI to dynamically determine the current accelerator device.Problem
The Gap
The
ShardedTensorclass intorch/distributed/_shard/sharded_tensor/api.pycontained hardcoded CUDA-specific logic in its device transfer methods, preventing third-party hardware vendors (e.g., Huawei NPU, Intel XPU) from integrating their accelerators into the sharded tensor ecosystem.Hardcoded patterns (before fix):
cuda()methodtorch.cuda.current_device()cuda()methodshard.tensor.cuda(...)cuda()methodmeta.placement.device().type != "cuda"to()methoddevice_to.type in {"cuda", "xpu"}Implementation
The implementation took a simpler approach than originally proposed, modifying the existing methods directly rather than creating a new
_to_device()abstraction.Changes to
cuda()methodDevice index retrieval: Changed from
torch.cuda.current_device()totorch.accelerator.current_device_index()Error message: Made device-type aware:
Tensor transfer: Changed from
shard.tensor.cuda()toshard.tensor.to():Metadata comparison: Changed from hardcoded
"cuda"to dynamiccurrent_device.type:Changes to
to()methodChanged the device type check from an explicit allowlist to a denylist:
This change:
torch.accelerator.current_device_index()to get the current deviceWhy This Approach
Using
torch.acceleratorAPI:torch.accelerator.current_device_index()returns the current accelerator device indextorch.device(int)automatically uses the current accelerator typeUsing denylist (
!= "cpu") instead of allowlist:Backward Compatibility
.cuda().to(device).cpu()All existing CUDA workflows remain identical. The only observable change is that
to()now works correctly with any non-CPU accelerator device.Test Plan
Existing tests validate the changes:
test_sharded_tensor_to_cuda- validates CUDA transfer behaviortest_sharded_tensor_to_test- validatesto()method with various device/dtype combinationstest_sharded_tensor_to_cpu- validates CPU transfer behaviorThe implementation was verified against the existing test suite.
References
torch.acceleratormodule:torch/accelerator/__init__.pycurrent_device_index(): returns current accelerator device index_get_preferred_device()implementation:torch/distributed/_shard/sharded_tensor/api.py(preserved for third-party backend support via ProcessGroup)cc @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @pragupta @msaroufim @dcci @aditvenk @weifengpy @chauhang @penguinwu @H-Huang @kwen2501 @zpcore