Repository navigation
[MPS] Migrate nll_loss forward to Metal kernel to fix 2**31 flat-index overflow (#198471) - #198776
FaizPalwala wants to merge 6 commits into
Conversation
🔗 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 FailuresAs of commit 09dbcfb with merge base 3dbf4ec ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
And how about performance? And may be a regression test? |
…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
|
Thanks for the review @malfet! Pushed an update addressing all points:
|
|
@pytorchbot rebase |
|
@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
|
Successfully rebased |
285baf1 to
d89889f
Compare
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]>
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
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]>
Merge failedReason: New commits were pushed while merging. Please rerun the merge command. Details for Dev Infra teamRaised 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]>
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…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]>
F.nll_loss/F.cross_entropyon MPS silently return 0 for any row whererow * C + target[row] >= 2**31: the forward pass used MPSGraph'sgatherWithUpdatesTensor:, 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 atUINT32_MAXthreads like the existing backward kernel (#195153). It fuses target lookup,ignore_indexmasking, bounds checking and weighting, and writes per-sample weights used fortotal_weightand themeanreduction. Bothnll_lossandnll_loss2dgo 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 onenllnd_loss_paramshelper.Also delete the redundant
*_offsetfields: both kernels bind tensors withmtl_setArgs, which already appliesstorage_offset()at bind time, so adding the offset again inside the kernel was unnecessary for the backward (it bound rawMTLBuffers to compensate) and wrong for the forward (offsets applied twice for sliced inputs/targets/weights andout=views).test_nll_loss_large_tensor_indexingintest_mps.py(fp16, ~4.3 GB, ~0.4 s) checks rows past the2**31boundary.@skipMPSfrom the large-tensornll_loss/cross_entropytests intest_nn.py.linear_cross_entropy: replaced the MPS "Inconsistent accuracy" skips with fp16 tolerance overrides; the chunked variant keeps fp16/bf16 skipped sinceacc_policy="auto"accumulates in fp32 on CPU only.Performance
Apple M-series, 100 calls queued per sync, µs per call:
Fixes #198471
🤖 Generated with Claude Code