Skip to content

[ShardedTensor] Make ShardedTensor Device Transfer Methods Hardware-Agnostic - #187939

Closed
kisnwangg wants to merge 1 commit into
pytorch:mainfrom
kisnwangg:main
Closed

kisnwangg wants to merge 1 commit into
pytorch:mainfrom
kisnwangg:main

Conversation

@kisnwangg

@kisnwangg kisnwangg commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

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:

    # 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():

    # 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:

    # 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:

# 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)

cc @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @pragupta @msaroufim @dcci @aditvenk @weifengpy @chauhang @penguinwu @H-Huang @kwen2501 @zpcore

@pytorch-bot

pytorch-bot Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

🔗 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 Failure

As of commit 934c92e with merge base 9f132a8 (image):

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.

@pytorch-bot pytorch-bot Bot added ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (sharded) release notes category labels Jun 23, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

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

@kisnwangg

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Jun 23, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

@pytorch-bot

pytorch-bot Bot commented Jun 24, 2026

Copy link
Copy Markdown

The label oncall: pt2 is only applicable to issues and has been removed. Please only use this label on issues.

@drisspg drisspg added the oncall: distributed Add this issue/PR to distributed oncall triage queue label Jun 24, 2026
@pytorch-bot pytorch-bot Bot removed the oncall: distributed Add this issue/PR to distributed oncall triage queue label Jun 24, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 24, 2026

Copy link
Copy Markdown

The label oncall: distributed is only applicable to issues and has been removed. Please only use this label on issues.

@janeyx99
janeyx99 requested review from d4l3k, guangyey and wconstab June 24, 2026 19:02
@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 24, 2026
@d4l3k

d4l3k commented Jun 24, 2026

Copy link
Copy Markdown
Member

@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

@claude

claude Bot commented Jun 24, 2026

Copy link
Copy Markdown

Claude Code is working…

I'll analyze this and get back to you.

View job run

1 similar comment
@claude

claude Bot commented Jun 25, 2026

Copy link
Copy Markdown

Claude Code is working…

I'll analyze this and get back to you.

View job run

@dcci

dcci commented Jun 25, 2026

Copy link
Copy Markdown
Member

@fegin mentioned SharedTensor is deprecated and we shouldn't accept new features. @kisnwangg -- what's your motivation for this?

@kisnwangg

Copy link
Copy Markdown
Contributor Author

@fegin mentioned SharedTensor is deprecated and we shouldn't accept new features. @kisnwangg -- what's your motivation for this?
to support third-party accelerator devices (e.g., NPU, XPU) by removing hardcoded CUDA-specific logic. @dcci

@claude

claude Bot commented Jun 25, 2026

Copy link
Copy Markdown

Claude Code is working…

I'll analyze this and get back to you.

View job run

1 similar comment
@claude

claude Bot commented Jun 25, 2026

Copy link
Copy Markdown

Claude Code is working…

I'll analyze this and get back to you.

View job run

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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Don't change this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

No, the original code is already device-agnostic.

@fffrog fffrog moved this from Backlog to Ready for Merge in PyTorch Test Refactoring Jul 6, 2026
@kisnwangg

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: 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 team Raised by workflow job

@fffrog

fffrog commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@github-project-automation github-project-automation Bot moved this from Ready for Merge to Done in PyTorch Test Refactoring Jul 6, 2026
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…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
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
…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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…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
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 3, 2026
…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.
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 3, 2026
…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.
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 3, 2026
…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).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 3, 2026
…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).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 3, 2026
…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).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 3, 2026
…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).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 3, 2026
…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).
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Sep 7, 2026
…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).
pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: distributed (sharded) release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

10 participants