Skip to content

[MPS] Fix nll_loss_backward for 1D (no batch dim) input - #195411

Closed
malfet wants to merge 1 commit into
mainfrom
malfet/mps-nll-loss-1d-backward
Closed

malfet wants to merge 1 commit into
mainfrom
malfet/mps-nll-loss-1d-backward

Conversation

@malfet

@malfet malfet commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

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:

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

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 OOB read is zero so the result happens to match; when the
caching allocator hands back a dirty buffer it is garbage (e.g. FLT_MAX),
which is why test_nll_loss_backward_1d_input_mps was flaky.

Fix: dispatch a single thread for 1D input, matching the CPU and
decomposition semantics. The 2D and 2D-loss paths are unchanged since
target.numel() already equals the number of loss elements there.

The regression test 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.

Test Plan:
```
python test/test_nn.py -k test_nll_loss_1d_input_backward
python test/inductor/test_torchinductor.py GPUTests.test_nll_loss_backward_1d_input_mps
python test/test_mps.py -k nll_loss
```

Fixes #195391
Fixes #195392

Authored with assistance from Claude (AI).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 65e93bf with merge base 74ee2f4 (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 31, 2026
@malfet
malfet marked this pull request as ready for review August 31, 2026 05:52
@malfet malfet added the topic: bug fixes topic category label Aug 31, 2026

@Isalia20 Isalia20 left a comment

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.

Does this happen in training? Or if user invokes backward function directly?

@malfet malfet added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 31, 2026
@malfet

malfet commented Aug 31, 2026

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

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]>
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]>
@github-actions
github-actions Bot deleted the malfet/mps-nll-loss-1d-backward branch November 12, 2026 01:49
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: bug fixes topic category

Projects

None yet

5 participants