Skip to content

[MPS] Migrate nll_loss forward to Metal kernel to fix 2**31 flat-index overflow (#198471) - #198776

Closed
FaizPalwala wants to merge 6 commits into
pytorch:mainfrom
FaizPalwala:fix-mps-nll-loss-overflow
Closed

FaizPalwala wants to merge 6 commits into
pytorch:mainfrom
FaizPalwala:fix-mps-nll-loss-overflow

Conversation

@FaizPalwala

@FaizPalwala FaizPalwala commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

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 MTLBuffers 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

@pytorch-bot

pytorch-bot Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 09dbcfb with merge base 3dbf4ec (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 Sep 27, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

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

@malfet

malfet commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

And how about performance? And may be a regression test?

FaizPalwala added a commit to FaizPalwala/pytorch that referenced this pull request Sep 28, 2026
…torch#198776)

- Embed NLLLossForwardParams inside NLLLossBackwardParams to eliminate parameter duplication
- Remove redundant thread bounds check in nllnd_loss_forward
- Pass Tensor directly to mtl_setArgs without getMTLBufferStorage
- Add #include <ATen/ops/sum.h> for modular ATen headers
- Fix clang-format line length in LossOps.metal and remove extra blank line in LossOps.mm
- Add functional correctness and 2^31 indexing regression tests in test_mps.py
@FaizPalwala

Copy link
Copy Markdown
Contributor Author

Thanks for the review @malfet! Pushed an update addressing all points:

  1. Performance: Tested on Apple M4 Pro across standard classification batch/vocab sizes (B=64..4096, C=10..32000). Because the custom Metal kernel avoids graph creation/caching overhead and fuses target lookup, mask check, bounds checking, and scaling in a single dispatch pass, execution time is fast and steady (~50–70 µs total per dispatch on MPS stream, matching or slightly edging out MPSGraph on smaller batches, while resolving the 32-bit overflow on large ones).

  2. Regression & Correctness Tests: Added two tests to test/test_mps.py:

    • test_nll_loss_forward_correctness: checks F.nll_loss across dtypes (float32, half, bfloat16), reductions (none, mean, sum), class weights, and ignore_index masking against CPU reference.
    • test_nll_loss_large_tensor_indexing: regression test using @largeMPSBufferTest with float16 on (2**23 + 2**16, 256) elements verifying target index lookups past $2^{31}$ succeed correctly without returning zero.
  3. Struct Sharing (LossOps.h): NLLLossBackwardParams now embeds NLLLossForwardParams forward; (following the GridSampler.h precedent), eliminating duplicate field declarations.

  4. Non-uniform Grids (LossOps.metal): Dropped the redundant if (index >= params.num_outputs) check since non-uniform threadgroups guarantee exact thread counts, and removed num_outputs from the params struct.

  5. mtl_setArgs Clean-up (LossOps.mm): Passed Tensor arguments directly instead of calling getMTLBufferStorage (which was carried over from the original backward implementation precedent; oops 😅).

  6. CI Fixes: Added #include for selective ATen headers and wrapped lines in LossOps.metal to adhere to clang-format rules.

@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 30, 2026
@malfet

malfet commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

…torch#198776)

- Embed NLLLossForwardParams inside NLLLossBackwardParams to eliminate parameter duplication
- Remove redundant thread bounds check in nllnd_loss_forward
- Pass Tensor directly to mtl_setArgs without getMTLBufferStorage
- Add #include <ATen/ops/sum.h> for modular ATen headers
- Fix clang-format line length in LossOps.metal and remove extra blank line in LossOps.mm
- Add functional correctness and 2^31 indexing regression tests in test_mps.py
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased fix-mps-nll-loss-overflow onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout fix-mps-nll-loss-overflow && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the fix-mps-nll-loss-overflow branch from 285baf1 to d89889f Compare October 2, 2026 06:01
malfet and others added 2 commits October 1, 2026 23:16
Rebasing onto main picked up the chunked dispatch in nllnd_loss_backward_impl, which sets `dispatch_params.tid_offset`. This PR moved `tid_offset` into the nested `NLLLossBackwardParams::forward` struct, so the merged code failed to compile with "no member named 'tid_offset' in 'NLLLossBackwardParams<>'". Point it at `forward.tid_offset`. Also apply clang-format to LossOps.mm.

Test Plan:
```
cd build && ninja torch_python
```

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… unskip tests

The forward kernel bound tensors with `mtl_setArgs` (which already applies `storage_offset() * element_size()` at bind time) and then added `storage_offset()` again inside the kernel, so any input, target, weight or `out=` view with a non-zero offset read/wrote the wrong elements (the `out=` case writes past the end of the view). Backward was correct only because it bound raw `MTLBuffer`s via `getMTLBufferStorage` and re-added the offset by hand. Both now bind tensors and all `*_offset` fields are gone from the params; a `nllnd_loss_params` helper fills the shared forward params for both impls.

The MPSGraph path accepted integer and bool inputs, which the OpInfo lists as supported on MPS, so instantiate the forward kernel for long/int/short/char/uchar/bool. uint8 now matches the Python reference, so narrow those MPS xfails to bool.

`test_nll_loss_forward_correctness` duplicated what `TestConsistencyMPS` already checks via the nll_loss OpInfo, so drop it. Remove `@skipMPS` from the large-tensor nll_loss/cross_entropy tests in test_nn. For `linear_cross_entropy`, replace the MPS "Inconsistent accuracy" skips with fp16 tolerance overrides (errors went from ~0.89 relative to ~1 ulp); the chunked variant keeps fp16/bf16 skipped because `acc_policy="auto"` accumulates in fp32 on CPU only.

Test Plan:
```
cd build && ninja torch_python
python -m pytest test/test_mps.py -k "nll or cross_entropy"
python -m pytest test/test_ops.py -k "mps and (nll_loss or cross_entropy)"
python -m pytest test/test_nn.py -k "mps and (nll or cross_entropy or NLL or CrossEntropy)"
python -m pytest test/test_mps.py -k "linear_cross_entropy and (output_match or output_grad_match)"
```
plus an ad-hoc script comparing forward and backward against CPU with a non-zero storage_offset on every argument (1D/2D/4D inputs, all reductions, `out=` view).

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@malfet malfet changed the title [MPS] Migrate nll_loss forward from MPSGraph to a native Metal kernel to fix 2**31 flat-index overflow (#198471) [MPS] Migrate nll_loss forward to Metal kernel to fix 2**31 flat-index overflow (#198471) Oct 2, 2026
@malfet

malfet commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

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

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

The forward impl only validated the weight dtype when `has_weight` (defined and non-empty), so an empty weight of the wrong dtype was silently accepted. The MPSGraph implementation checked whenever the weight was defined, and so does the backward impl and the other backends; `TestModuleMPS::test_errors_nn_NLLLoss` relies on it. Check on `weight_arg.defined()` again.

Test Plan:
```
cd build && ninja torch_python
python -m pytest test/test_modules.py -k "mps and (NLLLoss or CrossEntropy)"
```

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: New commits were pushed while merging. Please rerun the merge command.

Details for Dev Infra team Raised by workflow job

CPU and CUDA only dispatch nll_loss for floating types; MPS accepted integer and bool inputs only because the old MPSGraph implementation happened to, and the OpInfo's `dtypesIfMPS` codified that. Drop the integer/bool kernel instantiations, raise NotImplementedError for non-floating inputs (which also covers complex), remove `dtypesIfMPS` so MPS uses the same dtype list as other backends, and delete the now-unneeded MPS xfails for those dtypes.

Test Plan:
```
cd build && ninja torch_python
python -m pytest test/test_ops.py -k "mps and (nll_loss or cross_entropy)"
python -m pytest test/test_mps.py -k "nll or cross_entropy"
python -m pytest test/test_modules.py -k "mps and (NLLLoss or CrossEntropy)"
```

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@malfet

malfet commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

@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

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 triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MPS] nll_loss / cross_entropy silently return 0 for rows whose target element lies at flat index 2**31 or beyond

5 participants