Skip to content

[MPS] Migrate nll_loss backward from MPSGraph to a Metal kernel - #195153

Closed
Isalia20 wants to merge 2 commits into
pytorch:mainfrom
Isalia20:migrate-nll-loss-bwd-to-metal
Closed

Isalia20 wants to merge 2 commits into
pytorch:mainfrom
Isalia20:migrate-nll-loss-bwd-to-metal

Conversation

@Isalia20

@Isalia20 Isalia20 commented Aug 28, 2026 •

Copy link
Copy Markdown
Collaborator

nll_loss_backward and nll_loss2d_backward on MPS used an MPSGraph one-hot graph.
The graph cache is keyd on shape, which meant that variable length workloads would ocmpile one graph per shape and the driver memory would grow a lot due to caching of the one hot tensor in the intermediate calculation which wasn't being released. This PR replaces it with a single Metal scatter kernel.
Some numbers:

Variable-length causal-LM training run, 140 steps, 107 distinct sequence lengths:

Driver memory Before After
Peak 20,967 MB 7,969 MB

Speed

Case Before After Speedup
BF16 [740, 32000] 0.974 ms 0.226 ms 4.31x
BF16 [2048, 32000] 2.640 ms 0.519 ms 5.09x
BF16 [3812, 32000] 5.010 ms 0.988 ms 5.07x
FP32 [2048, 32000] 3.183 ms 1.052 ms 3.03x
BF16 [2, 64, 17, 19], transposed target, 2d 0.068 ms 0.040 ms 1.69x

@pytorch-bot

pytorch-bot Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 463f408 with merge base a0edfca (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added ciflow/mps Run MPS tests (subset of trunk) release notes: mps Release notes category labels Aug 28, 2026
@Isalia20 Isalia20 added the topic: improvements topic category label Aug 28, 2026
@Isalia20
Isalia20 marked this pull request as ready for review August 28, 2026 15:49
@Isalia20
Isalia20 requested a review from malfet as a code owner August 28, 2026 15:49
@Isalia20 Isalia20 added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 28, 2026
@Isalia20

Copy link
Copy Markdown
Collaborator 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 pushed a commit that referenced this pull request Aug 31, 2026
For 1D input `nll_loss` has a single loss element and only `target[0]` is used. The Metal kernel added in #195153 unconditionally dispatched `target.numel()` threads. When `aten.nll_loss_backward` is called directly with a 1D input and a multi-element target (as the inductor decomposition test does), the extra threads read the single-element `grad_output` out of bounds and scatter that garbage into `grad_input[target[i]]`.

In clean memory the out-of-bounds read is zero, so the result happens to match the reference; when the caching allocator hands back a dirty buffer it is garbage (e.g. `FLT_MAX`). That is why `test_nll_loss_backward_1d_input_mps` was flaky (#195391, #195392).

## How the previous (MPSGraph) op handled this
The MPSGraph implementation that #195153 replaced reshaped a 1D input `[C]` to `[1, C]` (an explicit batch of one) up front:
```objc
auto grad_input = grad_input_arg.dim() == 1 ? grad_input_arg.view({1, grad_input_arg.size(0)}) : grad_input_arg;
```
so the number of output rows was structurally pinned to 1, independent of the target's element count. The Metal migration dropped this normalization and instead derives the iteration count from `target.numel()`, which is where the out-of-bounds read comes from.

Note this 1D handling was **not** present in the original MPS op (#77343) -- it was added later in #81290 ("[MPS] Handle 1D inputs for NLL") and then lost in the migration.

## Fix
Dispatch a single thread for 1D input, matching the CPU and decomposition semantics ("the C++ kernel only uses `target[0]`") and re-instating the old `view({1, C})` invariant as a thread count. The 2D and 2D-loss paths are unchanged since `target.numel()` already equals the number of loss elements there.

## Test
Added a device-generic regression test that backs `grad_output` with a larger sentinel-filled tensor and views out a single element, so the out-of-bounds read is a deterministic non-zero value rather than relying on allocator state. It fails before the fix and passes after (`@onlyAccelerator`; the CPU path is correct and used as the reference).

Fixes #195389
Fixes #195390
Fixes #195391
Fixes #195392

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #195411
Approved by: https://github.com/Isalia20, https://github.com/Skylion007

Co-authored-by: Claude Opus 4.8 <[email protected]>
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…rch#195153)

`nll_loss_backward` and `nll_loss2d_backward` on MPS used an MPSGraph one-hot graph.
The graph cache is keyd on shape, which meant that variable length workloads would ocmpile one graph per shape and the driver memory would grow a lot due to caching of the one hot tensor in the intermediate calculation which wasn't being released. This PR replaces it with a single Metal scatter kernel.
Some numbers:

Variable-length causal-LM training run, 140 steps, 107 distinct sequence lengths:

| Driver memory | Before | After |
|---|---:|---:|
| Peak | 20,967 MB | 7,969 MB |

Speed

| Case | Before | After | Speedup |
|---|---:|---:|---:|
| BF16 `[740, 32000]` | 0.974 ms | 0.226 ms | 4.31x |
| BF16 `[2048, 32000]` | 2.640 ms | 0.519 ms | 5.09x |
| BF16 `[3812, 32000]` | 5.010 ms | 0.988 ms | 5.07x |
| FP32 `[2048, 32000]` | 3.183 ms | 1.052 ms | 3.03x |
| BF16 `[2, 64, 17, 19]`, transposed target, 2d | 0.068 ms | 0.040 ms | 1.69x |

Pull Request resolved: pytorch#195153
Approved by: https://github.com/malfet
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
For 1D input `nll_loss` has a single loss element and only `target[0]` is used. The Metal kernel added in pytorch#195153 unconditionally dispatched `target.numel()` threads. When `aten.nll_loss_backward` is called directly with a 1D input and a multi-element target (as the inductor decomposition test does), the extra threads read the single-element `grad_output` out of bounds and scatter that garbage into `grad_input[target[i]]`.

In clean memory the out-of-bounds read is zero, so the result happens to match the reference; when the caching allocator hands back a dirty buffer it is garbage (e.g. `FLT_MAX`). That is why `test_nll_loss_backward_1d_input_mps` was flaky (pytorch#195391, pytorch#195392).

## How the previous (MPSGraph) op handled this
The MPSGraph implementation that pytorch#195153 replaced reshaped a 1D input `[C]` to `[1, C]` (an explicit batch of one) up front:
```objc
auto grad_input = grad_input_arg.dim() == 1 ? grad_input_arg.view({1, grad_input_arg.size(0)}) : grad_input_arg;
```
so the number of output rows was structurally pinned to 1, independent of the target's element count. The Metal migration dropped this normalization and instead derives the iteration count from `target.numel()`, which is where the out-of-bounds read comes from.

Note this 1D handling was **not** present in the original MPS op (pytorch#77343) -- it was added later in pytorch#81290 ("[MPS] Handle 1D inputs for NLL") and then lost in the migration.

## Fix
Dispatch a single thread for 1D input, matching the CPU and decomposition semantics ("the C++ kernel only uses `target[0]`") and re-instating the old `view({1, C})` invariant as a thread count. The 2D and 2D-loss paths are unchanged since `target.numel()` already equals the number of loss elements there.

## Test
Added a device-generic regression test that backs `grad_output` with a larger sentinel-filled tensor and views out a single element, so the out-of-bounds read is a deterministic non-zero value rather than relying on allocator state. It fails before the fix and passes after (`@onlyAccelerator`; the CPU path is correct and used as the reference).

Fixes pytorch#195389
Fixes pytorch#195390
Fixes pytorch#195391
Fixes pytorch#195392

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#195411
Approved by: https://github.com/Isalia20, https://github.com/Skylion007

Co-authored-by: Claude Opus 4.8 <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
Following this PR #195153 I tried to pin down other ops which might make memory usage high as the nll_loss backward did.
To make findings meaningful, I tried doing inference of various LLM/image/video generation models and found that for `Wan-AI/Wan2.2-TI2V-5B-Diffusers` memory usage explodes because of the pad function that is used during VAE decode phase of the model.

PR migrates MPS Graph constant pad to metal kernels. Perf:

| Metric | MPSGraph | Fused Metal | Change |
|---|---:|---:|---:|
| MPS current-memory peak | 4.422 GiB | 4.095 GiB | -0.327 GiB |
| MPS allocator-reserved peak | 8.070 GiB | 8.070 GiB | unchanged |
| Driver memory outside allocator | 262.065 GiB | 0.038 GiB | -262.027 GiB (-99.986%) |
| Total driver-memory peak | 270.135 GiB | 8.108 GiB | -262.027 GiB (-97.0%) |

The reason for such huge memory is because of Wan model calling `F.pad` before every 3D convolution where one spatial tile makes 300+ calls to this function, the complete 28-tile decode makes 8,764 calls.

The way kernels work is simple, there are dense and strided kernels:

- **Dense** (`constant_pad_nd_dense`): input and output contiguous, at most 3 padded dims. The output is treated as `[outer, D, H, W]` (`outer` = all leading dims flattened) and dispatched as the matching 3D grid `(W / ILP_PER_THREAD, H, outer * D)`, each thread writing 4 elements along `W`. One of the reason of this is kernel speed, with this, we avoid the stride calculations which makes the kernel faster.
- **Strided** (`constant_pad_nd`): everything else. Dims are sorted by output stride, `tid.x` walks the innermost dim, `tid.y` is decomposed over the remaining dims and per-dim input/output strides are applied directly. Offsets use uint32 when every element offset of both tensors fits or uint64 otherwise.

<details>
<summary> Latency changes </summary>

| Case | Input shape | Padding | Dtype | Layout | Before | After | Speedup |
|---|---|---|---|---|---:|---:|---:|
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float32` | `contiguous` | 0.0178 ms | 0.0118 ms | 1.52x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float32` | `transposed` | 0.0192 ms | 0.0121 ms | 1.58x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float32` | `sliced` | 0.0189 ms | 0.0090 ms | 2.10x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float16` | `contiguous` | 0.0159 ms | 0.0077 ms | 2.07x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float16` | `transposed` | 0.0187 ms | 0.0116 ms | 1.61x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float16` | `sliced` | 0.0186 ms | 0.0080 ms | 2.33x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bfloat16` | `contiguous` | 0.0152 ms | 0.0081 ms | 1.88x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bfloat16` | `transposed` | 0.0187 ms | 0.0120 ms | 1.56x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bfloat16` | `sliced` | 0.0185 ms | 0.0084 ms | 2.20x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `int32` | `contiguous` | 0.0152 ms | 0.0079 ms | 1.94x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `int32` | `transposed` | 0.0189 ms | 0.0120 ms | 1.58x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `int32` | `sliced` | 0.0187 ms | 0.0088 ms | 2.12x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bool` | `contiguous` | 0.0164 ms | 0.0072 ms | 2.29x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bool` | `transposed` | 0.0188 ms | 0.0098 ms | 1.92x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bool` | `sliced` | 0.0189 ms | 0.0083 ms | 2.27x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float32` | `contiguous` | 0.0190 ms | 0.0143 ms | 1.33x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float32` | `transposed` | 0.0531 ms | 0.0190 ms | 2.80x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float32` | `sliced` | 0.0317 ms | 0.0176 ms | 1.80x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float16` | `contiguous` | 0.0176 ms | 0.0123 ms | 1.42x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float16` | `transposed` | 0.0369 ms | 0.0167 ms | 2.22x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float16` | `sliced` | 0.0256 ms | 0.0159 ms | 1.61x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bfloat16` | `contiguous` | 0.0166 ms | 0.0124 ms | 1.33x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bfloat16` | `transposed` | 0.0369 ms | 0.0168 ms | 2.20x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bfloat16` | `sliced` | 0.0256 ms | 0.0159 ms | 1.61x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `int32` | `contiguous` | 0.0168 ms | 0.0143 ms | 1.17x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `int32` | `transposed` | 0.0411 ms | 0.0191 ms | 2.16x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `int32` | `sliced` | 0.0302 ms | 0.0177 ms | 1.71x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bool` | `contiguous` | 0.0185 ms | 0.0108 ms | 1.72x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bool` | `transposed` | 0.0350 ms | 0.0150 ms | 2.33x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bool` | `sliced` | 0.0234 ms | 0.0145 ms | 1.61x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float32` | `contiguous` | 0.0186 ms | 0.0127 ms | 1.46x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float32` | `transposed` | 0.0217 ms | 0.0130 ms | 1.67x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float32` | `sliced` | 0.0213 ms | 0.0129 ms | 1.66x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float16` | `contiguous` | 0.0191 ms | 0.0115 ms | 1.66x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float16` | `transposed` | 0.0215 ms | 0.0120 ms | 1.79x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float16` | `sliced` | 0.0212 ms | 0.0120 ms | 1.77x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bfloat16` | `contiguous` | 0.0183 ms | 0.0116 ms | 1.57x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bfloat16` | `transposed` | 0.0214 ms | 0.0119 ms | 1.80x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bfloat16` | `sliced` | 0.0213 ms | 0.0118 ms | 1.80x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `int32` | `contiguous` | 0.0182 ms | 0.0130 ms | 1.40x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `int32` | `transposed` | 0.0217 ms | 0.0132 ms | 1.65x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `int32` | `sliced` | 0.0212 ms | 0.0128 ms | 1.66x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bool` | `contiguous` | 0.0187 ms | 0.0109 ms | 1.71x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bool` | `transposed` | 0.0214 ms | 0.0115 ms | 1.86x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bool` | `sliced` | 0.0209 ms | 0.0115 ms | 1.81x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `contiguous` | 0.0286 ms | 0.0074 ms | 3.86x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `transposed` | 0.0310 ms | 0.0107 ms | 2.90x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `sliced` | 0.0311 ms | 0.0101 ms | 3.09x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `contiguous` | 0.0284 ms | 0.0074 ms | 3.82x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `transposed` | 0.0313 ms | 0.0104 ms | 3.00x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `sliced` | 0.0310 ms | 0.0099 ms | 3.14x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `contiguous` | 0.0287 ms | 0.0075 ms | 3.85x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `transposed` | 0.0312 ms | 0.0105 ms | 2.98x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `sliced` | 0.0308 ms | 0.0095 ms | 3.26x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `contiguous` | 0.0288 ms | 0.0073 ms | 3.95x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `transposed` | 0.0309 ms | 0.0103 ms | 3.01x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `sliced` | 0.0312 ms | 0.0099 ms | 3.15x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `contiguous` | 0.0285 ms | 0.0073 ms | 3.92x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `transposed` | 0.0307 ms | 0.0101 ms | 3.04x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `sliced` | 0.0309 ms | 0.0096 ms | 3.21x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `contiguous` | 0.1519 ms | 0.0430 ms | 3.54x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `transposed` | 0.2057 ms | 0.0644 ms | 3.20x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `sliced` | 0.1902 ms | 0.0693 ms | 2.74x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `contiguous` | 0.1059 ms | 0.0396 ms | 2.68x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `transposed` | 0.1534 ms | 0.0607 ms | 2.53x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `sliced` | 0.1308 ms | 0.0609 ms | 2.15x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `contiguous` | 0.1057 ms | 0.0393 ms | 2.69x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `transposed` | 0.1533 ms | 0.0607 ms | 2.52x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `sliced` | 0.1303 ms | 0.0609 ms | 2.14x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `contiguous` | 0.1522 ms | 0.0430 ms | 3.54x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `transposed` | 0.2045 ms | 0.0670 ms | 3.05x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `sliced` | 0.1906 ms | 0.0684 ms | 2.79x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `contiguous` | 0.0973 ms | 0.0303 ms | 3.21x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `transposed` | 0.1432 ms | 0.0541 ms | 2.64x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `sliced` | 0.1194 ms | 0.0545 ms | 2.19x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float32` | `contiguous` | 0.0461 ms | 0.0526 ms | 0.88x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float32` | `transposed` | 0.2299 ms | 0.0767 ms | 3.00x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float32` | `sliced` | 0.1857 ms | 0.0960 ms | 1.94x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float16` | `contiguous` | 0.0386 ms | 0.0279 ms | 1.38x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float16` | `transposed` | 0.2154 ms | 0.0699 ms | 3.08x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float16` | `sliced` | 0.1240 ms | 0.0721 ms | 1.72x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bfloat16` | `contiguous` | 0.0384 ms | 0.0285 ms | 1.35x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bfloat16` | `transposed` | 0.2150 ms | 0.0710 ms | 3.03x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bfloat16` | `sliced` | 0.1256 ms | 0.0733 ms | 1.71x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `int32` | `contiguous` | 0.0514 ms | 0.0520 ms | 0.99x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `int32` | `transposed` | 0.2317 ms | 0.0753 ms | 3.08x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `int32` | `sliced` | 0.1884 ms | 0.1065 ms | 1.77x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bool` | `contiguous` | 0.0359 ms | 0.0174 ms | 2.07x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bool` | `transposed` | 0.2035 ms | 0.0635 ms | 3.21x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bool` | `sliced` | 0.1162 ms | 0.0637 ms | 1.82x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float32` | `contiguous` | 0.6938 ms | 0.2953 ms | 2.35x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float32` | `transposed` | 1.2018 ms | 0.3505 ms | 3.43x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float32` | `sliced` | 1.1201 ms | 0.4372 ms | 2.56x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float16` | `contiguous` | 0.4209 ms | 0.1144 ms | 3.68x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float16` | `transposed` | 0.9549 ms | 0.1926 ms | 4.96x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float16` | `sliced` | 0.7193 ms | 0.2155 ms | 3.34x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bfloat16` | `contiguous` | 0.4179 ms | 0.1097 ms | 3.81x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bfloat16` | `transposed` | 0.9514 ms | 0.1937 ms | 4.91x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bfloat16` | `sliced` | 0.7133 ms | 0.2131 ms | 3.35x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `int32` | `contiguous` | 0.6962 ms | 0.2960 ms | 2.35x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `int32` | `transposed` | 1.2045 ms | 0.3451 ms | 3.49x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `int32` | `sliced` | 1.1212 ms | 0.4381 ms | 2.56x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bool` | `contiguous` | 0.3444 ms | 0.0948 ms | 3.63x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bool` | `transposed` | 0.8468 ms | 0.1806 ms | 4.69x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bool` | `sliced` | 0.5935 ms | 0.1726 ms | 3.44x |

</details>
Pull Request resolved: #195368
Approved by: https://github.com/malfet
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…rch#195153)

`nll_loss_backward` and `nll_loss2d_backward` on MPS used an MPSGraph one-hot graph.
The graph cache is keyd on shape, which meant that variable length workloads would ocmpile one graph per shape and the driver memory would grow a lot due to caching of the one hot tensor in the intermediate calculation which wasn't being released. This PR replaces it with a single Metal scatter kernel.
Some numbers:

Variable-length causal-LM training run, 140 steps, 107 distinct sequence lengths:

| Driver memory | Before | After |
|---|---:|---:|
| Peak | 20,967 MB | 7,969 MB |

Speed

| Case | Before | After | Speedup |
|---|---:|---:|---:|
| BF16 `[740, 32000]` | 0.974 ms | 0.226 ms | 4.31x |
| BF16 `[2048, 32000]` | 2.640 ms | 0.519 ms | 5.09x |
| BF16 `[3812, 32000]` | 5.010 ms | 0.988 ms | 5.07x |
| FP32 `[2048, 32000]` | 3.183 ms | 1.052 ms | 3.03x |
| BF16 `[2, 64, 17, 19]`, transposed target, 2d | 0.068 ms | 0.040 ms | 1.69x |

Pull Request resolved: pytorch#195153
Approved by: https://github.com/malfet
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
For 1D input `nll_loss` has a single loss element and only `target[0]` is used. The Metal kernel added in pytorch#195153 unconditionally dispatched `target.numel()` threads. When `aten.nll_loss_backward` is called directly with a 1D input and a multi-element target (as the inductor decomposition test does), the extra threads read the single-element `grad_output` out of bounds and scatter that garbage into `grad_input[target[i]]`.

In clean memory the out-of-bounds read is zero, so the result happens to match the reference; when the caching allocator hands back a dirty buffer it is garbage (e.g. `FLT_MAX`). That is why `test_nll_loss_backward_1d_input_mps` was flaky (pytorch#195391, pytorch#195392).

## How the previous (MPSGraph) op handled this
The MPSGraph implementation that pytorch#195153 replaced reshaped a 1D input `[C]` to `[1, C]` (an explicit batch of one) up front:
```objc
auto grad_input = grad_input_arg.dim() == 1 ? grad_input_arg.view({1, grad_input_arg.size(0)}) : grad_input_arg;
```
so the number of output rows was structurally pinned to 1, independent of the target's element count. The Metal migration dropped this normalization and instead derives the iteration count from `target.numel()`, which is where the out-of-bounds read comes from.

Note this 1D handling was **not** present in the original MPS op (pytorch#77343) -- it was added later in pytorch#81290 ("[MPS] Handle 1D inputs for NLL") and then lost in the migration.

## Fix
Dispatch a single thread for 1D input, matching the CPU and decomposition semantics ("the C++ kernel only uses `target[0]`") and re-instating the old `view({1, C})` invariant as a thread count. The 2D and 2D-loss paths are unchanged since `target.numel()` already equals the number of loss elements there.

## Test
Added a device-generic regression test that backs `grad_output` with a larger sentinel-filled tensor and views out a single element, so the out-of-bounds read is a deterministic non-zero value rather than relying on allocator state. It fails before the fix and passes after (`@onlyAccelerator`; the CPU path is correct and used as the reference).

Fixes pytorch#195389
Fixes pytorch#195390
Fixes pytorch#195391
Fixes pytorch#195392

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#195411
Approved by: https://github.com/Isalia20, https://github.com/Skylion007

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
Following this PR pytorch#195153 I tried to pin down other ops which might make memory usage high as the nll_loss backward did.
To make findings meaningful, I tried doing inference of various LLM/image/video generation models and found that for `Wan-AI/Wan2.2-TI2V-5B-Diffusers` memory usage explodes because of the pad function that is used during VAE decode phase of the model.

PR migrates MPS Graph constant pad to metal kernels. Perf:

| Metric | MPSGraph | Fused Metal | Change |
|---|---:|---:|---:|
| MPS current-memory peak | 4.422 GiB | 4.095 GiB | -0.327 GiB |
| MPS allocator-reserved peak | 8.070 GiB | 8.070 GiB | unchanged |
| Driver memory outside allocator | 262.065 GiB | 0.038 GiB | -262.027 GiB (-99.986%) |
| Total driver-memory peak | 270.135 GiB | 8.108 GiB | -262.027 GiB (-97.0%) |

The reason for such huge memory is because of Wan model calling `F.pad` before every 3D convolution where one spatial tile makes 300+ calls to this function, the complete 28-tile decode makes 8,764 calls.

The way kernels work is simple, there are dense and strided kernels:

- **Dense** (`constant_pad_nd_dense`): input and output contiguous, at most 3 padded dims. The output is treated as `[outer, D, H, W]` (`outer` = all leading dims flattened) and dispatched as the matching 3D grid `(W / ILP_PER_THREAD, H, outer * D)`, each thread writing 4 elements along `W`. One of the reason of this is kernel speed, with this, we avoid the stride calculations which makes the kernel faster.
- **Strided** (`constant_pad_nd`): everything else. Dims are sorted by output stride, `tid.x` walks the innermost dim, `tid.y` is decomposed over the remaining dims and per-dim input/output strides are applied directly. Offsets use uint32 when every element offset of both tensors fits or uint64 otherwise.

<details>
<summary> Latency changes </summary>

| Case | Input shape | Padding | Dtype | Layout | Before | After | Speedup |
|---|---|---|---|---|---:|---:|---:|
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float32` | `contiguous` | 0.0178 ms | 0.0118 ms | 1.52x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float32` | `transposed` | 0.0192 ms | 0.0121 ms | 1.58x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float32` | `sliced` | 0.0189 ms | 0.0090 ms | 2.10x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float16` | `contiguous` | 0.0159 ms | 0.0077 ms | 2.07x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float16` | `transposed` | 0.0187 ms | 0.0116 ms | 1.61x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `float16` | `sliced` | 0.0186 ms | 0.0080 ms | 2.33x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bfloat16` | `contiguous` | 0.0152 ms | 0.0081 ms | 1.88x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bfloat16` | `transposed` | 0.0187 ms | 0.0120 ms | 1.56x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bfloat16` | `sliced` | 0.0185 ms | 0.0084 ms | 2.20x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `int32` | `contiguous` | 0.0152 ms | 0.0079 ms | 1.94x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `int32` | `transposed` | 0.0189 ms | 0.0120 ms | 1.58x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `int32` | `sliced` | 0.0187 ms | 0.0088 ms | 2.12x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bool` | `contiguous` | 0.0164 ms | 0.0072 ms | 2.29x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bool` | `transposed` | 0.0188 ms | 0.0098 ms | 1.92x |
| `vector_2d` | `(32, 4096)` | `(8, 8)` | `bool` | `sliced` | 0.0189 ms | 0.0083 ms | 2.27x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float32` | `contiguous` | 0.0190 ms | 0.0143 ms | 1.33x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float32` | `transposed` | 0.0531 ms | 0.0190 ms | 2.80x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float32` | `sliced` | 0.0317 ms | 0.0176 ms | 1.80x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float16` | `contiguous` | 0.0176 ms | 0.0123 ms | 1.42x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float16` | `transposed` | 0.0369 ms | 0.0167 ms | 2.22x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `float16` | `sliced` | 0.0256 ms | 0.0159 ms | 1.61x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bfloat16` | `contiguous` | 0.0166 ms | 0.0124 ms | 1.33x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bfloat16` | `transposed` | 0.0369 ms | 0.0168 ms | 2.20x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bfloat16` | `sliced` | 0.0256 ms | 0.0159 ms | 1.61x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `int32` | `contiguous` | 0.0168 ms | 0.0143 ms | 1.17x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `int32` | `transposed` | 0.0411 ms | 0.0191 ms | 2.16x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `int32` | `sliced` | 0.0302 ms | 0.0177 ms | 1.71x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bool` | `contiguous` | 0.0185 ms | 0.0108 ms | 1.72x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bool` | `transposed` | 0.0350 ms | 0.0150 ms | 2.33x |
| `image_4d` | `(1, 64, 128, 128)` | `(1, 1, 1, 1)` | `bool` | `sliced` | 0.0234 ms | 0.0145 ms | 1.61x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float32` | `contiguous` | 0.0186 ms | 0.0127 ms | 1.46x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float32` | `transposed` | 0.0217 ms | 0.0130 ms | 1.67x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float32` | `sliced` | 0.0213 ms | 0.0129 ms | 1.66x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float16` | `contiguous` | 0.0191 ms | 0.0115 ms | 1.66x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float16` | `transposed` | 0.0215 ms | 0.0120 ms | 1.79x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `float16` | `sliced` | 0.0212 ms | 0.0120 ms | 1.77x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bfloat16` | `contiguous` | 0.0183 ms | 0.0116 ms | 1.57x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bfloat16` | `transposed` | 0.0214 ms | 0.0119 ms | 1.80x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bfloat16` | `sliced` | 0.0213 ms | 0.0118 ms | 1.80x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `int32` | `contiguous` | 0.0182 ms | 0.0130 ms | 1.40x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `int32` | `transposed` | 0.0217 ms | 0.0132 ms | 1.65x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `int32` | `sliced` | 0.0212 ms | 0.0128 ms | 1.66x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bool` | `contiguous` | 0.0187 ms | 0.0109 ms | 1.71x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bool` | `transposed` | 0.0214 ms | 0.0115 ms | 1.86x |
| `mixed_crop_4d` | `(2, 32, 64, 96)` | `(-2, 3, 1, -1)` | `bool` | `sliced` | 0.0209 ms | 0.0115 ms | 1.81x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `contiguous` | 0.0286 ms | 0.0074 ms | 3.86x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `transposed` | 0.0310 ms | 0.0107 ms | 2.90x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `sliced` | 0.0311 ms | 0.0101 ms | 3.09x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `contiguous` | 0.0284 ms | 0.0074 ms | 3.82x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `transposed` | 0.0313 ms | 0.0104 ms | 3.00x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `sliced` | 0.0310 ms | 0.0099 ms | 3.14x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `contiguous` | 0.0287 ms | 0.0075 ms | 3.85x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `transposed` | 0.0312 ms | 0.0105 ms | 2.98x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `sliced` | 0.0308 ms | 0.0095 ms | 3.26x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `contiguous` | 0.0288 ms | 0.0073 ms | 3.95x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `transposed` | 0.0309 ms | 0.0103 ms | 3.01x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `sliced` | 0.0312 ms | 0.0099 ms | 3.15x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `contiguous` | 0.0285 ms | 0.0073 ms | 3.92x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `transposed` | 0.0307 ms | 0.0101 ms | 3.04x |
| `wan_small_5d` | `(1, 48, 1, 16, 16)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `sliced` | 0.0309 ms | 0.0096 ms | 3.21x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `contiguous` | 0.1519 ms | 0.0430 ms | 3.54x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `transposed` | 0.2057 ms | 0.0644 ms | 3.20x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float32` | `sliced` | 0.1902 ms | 0.0693 ms | 2.74x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `contiguous` | 0.1059 ms | 0.0396 ms | 2.68x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `transposed` | 0.1534 ms | 0.0607 ms | 2.53x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `float16` | `sliced` | 0.1308 ms | 0.0609 ms | 2.15x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `contiguous` | 0.1057 ms | 0.0393 ms | 2.69x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `transposed` | 0.1533 ms | 0.0607 ms | 2.52x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bfloat16` | `sliced` | 0.1303 ms | 0.0609 ms | 2.14x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `contiguous` | 0.1522 ms | 0.0430 ms | 3.54x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `transposed` | 0.2045 ms | 0.0670 ms | 3.05x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `int32` | `sliced` | 0.1906 ms | 0.0684 ms | 2.79x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `contiguous` | 0.0973 ms | 0.0303 ms | 3.21x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `transposed` | 0.1432 ms | 0.0541 ms | 2.64x |
| `wan_mid_5d` | `(1, 512, 1, 64, 64)` | `(1, 1, 1, 1, 2, 0)` | `bool` | `sliced` | 0.1194 ms | 0.0545 ms | 2.19x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float32` | `contiguous` | 0.0461 ms | 0.0526 ms | 0.88x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float32` | `transposed` | 0.2299 ms | 0.0767 ms | 3.00x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float32` | `sliced` | 0.1857 ms | 0.0960 ms | 1.94x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float16` | `contiguous` | 0.0386 ms | 0.0279 ms | 1.38x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float16` | `transposed` | 0.2154 ms | 0.0699 ms | 3.08x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `float16` | `sliced` | 0.1240 ms | 0.0721 ms | 1.72x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bfloat16` | `contiguous` | 0.0384 ms | 0.0285 ms | 1.35x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bfloat16` | `transposed` | 0.2150 ms | 0.0710 ms | 3.03x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bfloat16` | `sliced` | 0.1256 ms | 0.0733 ms | 1.71x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `int32` | `contiguous` | 0.0514 ms | 0.0520 ms | 0.99x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `int32` | `transposed` | 0.2317 ms | 0.0753 ms | 3.08x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `int32` | `sliced` | 0.1884 ms | 0.1065 ms | 1.77x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bool` | `contiguous` | 0.0359 ms | 0.0174 ms | 2.07x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bool` | `transposed` | 0.2035 ms | 0.0635 ms | 3.21x |
| `zero_pad_5d` | `(1, 512, 4, 64, 64)` | `(0, 0, 0, 0, 0, 0)` | `bool` | `sliced` | 0.1162 ms | 0.0637 ms | 1.82x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float32` | `contiguous` | 0.6938 ms | 0.2953 ms | 2.35x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float32` | `transposed` | 1.2018 ms | 0.3505 ms | 3.43x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float32` | `sliced` | 1.1201 ms | 0.4372 ms | 2.56x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float16` | `contiguous` | 0.4209 ms | 0.1144 ms | 3.68x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float16` | `transposed` | 0.9549 ms | 0.1926 ms | 4.96x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `float16` | `sliced` | 0.7193 ms | 0.2155 ms | 3.34x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bfloat16` | `contiguous` | 0.4179 ms | 0.1097 ms | 3.81x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bfloat16` | `transposed` | 0.9514 ms | 0.1937 ms | 4.91x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bfloat16` | `sliced` | 0.7133 ms | 0.2131 ms | 3.35x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `int32` | `contiguous` | 0.6962 ms | 0.2960 ms | 2.35x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `int32` | `transposed` | 1.2045 ms | 0.3451 ms | 3.49x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `int32` | `sliced` | 1.1212 ms | 0.4381 ms | 2.56x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bool` | `contiguous` | 0.3444 ms | 0.0948 ms | 3.63x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bool` | `transposed` | 0.8468 ms | 0.1806 ms | 4.69x |
| `wan_large_5d` | `(1, 256, 6, 128, 128)` | `(1, 1, 1, 1, 0, 0)` | `bool` | `sliced` | 0.5935 ms | 0.1726 ms | 3.44x |

</details>
Pull Request resolved: pytorch#195368
Approved by: https://github.com/malfet
pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
…x overflow (#198471) (#198776)

 `F.nll_loss` / `F.cross_entropy` on MPS silently return 0 for any row where `row * C + target[row] >= 2**31`: the forward pass used MPSGraph's `gatherWithUpdatesTensor:`, which does 32-bit flat-index arithmetic. The MPSGraph path also failed outright for fp16 inputs with more than 65504 targets (`value cannot be converted to type c10::Half without overflow`), because it materialized the batch size as a tensor of the input dtype.

This change replace MPSGraph forward with a Metal kernel, `nllnd_loss_forward`, that uses 64-bit indexing and chunks the dispatch at `UINT32_MAX` threads like the existing backward kernel (#195153). It fuses target lookup, `ignore_index` masking, bounds checking and weighting, and writes per-sample weights used for `total_weight` and the `mean` reduction. Both `nll_loss` and `nll_loss2d` go through it; MPS now supports the same dtypes as CUDA.  the integer/bool inputs that MPSGraph happened to accept, and the OpInfo's dtypesIfMPS that codified them, are removed.

The forward and backward now share `NLLLossForwardParams`, filled by one `nllnd_loss_params` helper.
Also delete the redundant `*_offset` fields: both kernels bind tensors with `mtl_setArgs`, which already applies `storage_offset()` at bind time, so adding the offset again inside the kernel was unnecessary for the backward (it bound raw `MTLBuffer`s to compensate) and wrong for the forward (offsets applied twice for sliced inputs/targets/weights and `out=` views).

- New `test_nll_loss_large_tensor_indexing` in `test_mps.py` (fp16, ~4.3 GB, ~0.4 s) checks rows past the `2**31` boundary.
- Removed `@skipMPS` from the large-tensor `nll_loss` / `cross_entropy` tests in `test_nn.py`.
- `linear_cross_entropy`: replaced the MPS "Inconsistent accuracy" skips with fp16 tolerance overrides; the chunked variant keeps fp16/bf16 skipped since `acc_policy="auto"` accumulates in fp32 on CPU only.
- Removed the now-unneeded MPS integer/bool xfails.

### Performance

Apple M-series, 100 calls queued per sync, µs per call:

| shape | dtype | reduction | weight | fwd main | fwd PR | fwd+bwd main | fwd+bwd PR |
|---|---|---|---|---:|---:|---:|---:|
| (4096, 1000) | float32 | mean | yes | 53.2 | 15.7 | 118.2 | 72.6 |
| (4096, 32000) | float16 | none | no | 43.2 | 9.6 | 1070.4 | 1043.7 |
| (32768, 128) | float32 | mean | no | 50.6 | 20.9 | 132.9 | 87.3 |
| (262144, 10) | float16 | mean | yes | error | 36.0 | error | 92.2 |
| (8, 21, 128, 128) | float32 | mean | yes | 94.9 | 35.8 | 191.7 | 122.0 |
| (16, 19, 512, 512) | float32 | mean | yes | 1493.8 | 1008.4 | 5928.0 | 5247.0 |

Fixes #198471

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #198776
Approved by: https://github.com/malfet

Co-authored-by: Nikita Shulga <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…x overflow (pytorch#198471) (pytorch#198776)

 `F.nll_loss` / `F.cross_entropy` on MPS silently return 0 for any row where `row * C + target[row] >= 2**31`: the forward pass used MPSGraph's `gatherWithUpdatesTensor:`, which does 32-bit flat-index arithmetic. The MPSGraph path also failed outright for fp16 inputs with more than 65504 targets (`value cannot be converted to type c10::Half without overflow`), because it materialized the batch size as a tensor of the input dtype.

This change replace MPSGraph forward with a Metal kernel, `nllnd_loss_forward`, that uses 64-bit indexing and chunks the dispatch at `UINT32_MAX` threads like the existing backward kernel (pytorch#195153). It fuses target lookup, `ignore_index` masking, bounds checking and weighting, and writes per-sample weights used for `total_weight` and the `mean` reduction. Both `nll_loss` and `nll_loss2d` go through it; MPS now supports the same dtypes as CUDA.  the integer/bool inputs that MPSGraph happened to accept, and the OpInfo's dtypesIfMPS that codified them, are removed.

The forward and backward now share `NLLLossForwardParams`, filled by one `nllnd_loss_params` helper.
Also delete the redundant `*_offset` fields: both kernels bind tensors with `mtl_setArgs`, which already applies `storage_offset()` at bind time, so adding the offset again inside the kernel was unnecessary for the backward (it bound raw `MTLBuffer`s to compensate) and wrong for the forward (offsets applied twice for sliced inputs/targets/weights and `out=` views).

- New `test_nll_loss_large_tensor_indexing` in `test_mps.py` (fp16, ~4.3 GB, ~0.4 s) checks rows past the `2**31` boundary.
- Removed `@skipMPS` from the large-tensor `nll_loss` / `cross_entropy` tests in `test_nn.py`.
- `linear_cross_entropy`: replaced the MPS "Inconsistent accuracy" skips with fp16 tolerance overrides; the chunked variant keeps fp16/bf16 skipped since `acc_policy="auto"` accumulates in fp32 on CPU only.
- Removed the now-unneeded MPS integer/bool xfails.

### Performance

Apple M-series, 100 calls queued per sync, µs per call:

| shape | dtype | reduction | weight | fwd main | fwd PR | fwd+bwd main | fwd+bwd PR |
|---|---|---|---|---:|---:|---:|---:|
| (4096, 1000) | float32 | mean | yes | 53.2 | 15.7 | 118.2 | 72.6 |
| (4096, 32000) | float16 | none | no | 43.2 | 9.6 | 1070.4 | 1043.7 |
| (32768, 128) | float32 | mean | no | 50.6 | 20.9 | 132.9 | 87.3 |
| (262144, 10) | float16 | mean | yes | error | 36.0 | error | 92.2 |
| (8, 21, 128, 128) | float32 | mean | yes | 94.9 | 35.8 | 191.7 | 122.0 |
| (16, 19, 512, 512) | float32 | mean | yes | 1493.8 | 1008.4 | 5928.0 | 5247.0 |

Fixes pytorch#198471

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#198776
Approved by: https://github.com/malfet

Co-authored-by: Nikita Shulga <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/mps Run MPS tests (subset of trunk) ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: mps Release notes category topic: improvements topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants