Skip to content

[MPS] Handle 1D inputs for NLL - #81290

Closed
kulinseth wants to merge 1 commit into
pytorch:masterfrom
kulinseth:1d_fix
Closed

kulinseth wants to merge 1 commit into
pytorch:masterfrom
kulinseth:1d_fix

Conversation

@kulinseth

Copy link
Copy Markdown
Collaborator
  • Add test for NLL 1d
  • Fix forward NLL for 1D case
  • Handle NLL backward for 1d

@facebook-github-bot

facebook-github-bot commented Jul 11, 2022 •

Copy link
Copy Markdown
Contributor

🔗 Helpful links

❌ 1 New Failures

As of commit 3580c64 (more details on the Dr. CI page):

Expand to see more
  • 1/1 failures introduced in this PR

🕵️ 1 new failure recognized by patterns

The following CI failures do not appear to be due to upstream breakages

See GitHub Actions build trunk / linux-focal-rocm5.1-py3.7 / test (default, 2, 2, linux.rocm.gpu) (1/1)

Step: "Test" (full log | diagnosis details | 🔁 rerun)

2022-07-12T18:56:51.4795383Z RuntimeError: test_nestedtensor failed! Received signal: SIGIOT
2022-07-12T18:56:51.2321479Z   test_to_padded_tensor_output_size_cuda_float16 (__main__.TestNestedTensorDeviceTypeCUDA) ... ok (0.004s)
2022-07-12T18:56:51.2357313Z   test_to_padded_tensor_output_size_cuda_float32 (__main__.TestNestedTensorDeviceTypeCUDA) ... ok (0.003s)
2022-07-12T18:56:51.2390366Z   test_to_padded_tensor_simple_cuda_float16 (__main__.TestNestedTensorDeviceTypeCUDA) ... Memory exception on virtual address 0x7f9c023b7000, node id 4 : Page not present
2022-07-12T18:56:51.2391991Z Address does not belong to a known buffer
2022-07-12T18:56:51.2395171Z Memory access fault by GPU node-4 (Agent handle: 0x561f40ae6510) on address 0x7f9c023b7000. Reason: Page not present or supervisor privilege.
2022-07-12T18:56:51.4783962Z Traceback (most recent call last):
2022-07-12T18:56:51.4784852Z   File "test/run_test.py", line 940, in <module>
2022-07-12T18:56:51.4789151Z     main()
2022-07-12T18:56:51.4789826Z   File "test/run_test.py", line 918, in main
2022-07-12T18:56:51.4794479Z     raise RuntimeError(err_message)
2022-07-12T18:56:51.4795383Z RuntimeError: test_nestedtensor failed! Received signal: SIGIOT
2022-07-12T18:56:53.4224189Z 
2022-07-12T18:56:53.4224675Z real	98m53.361s
2022-07-12T18:56:53.4225286Z user	165m10.411s
2022-07-12T18:56:53.4225894Z sys	23m32.367s
2022-07-12T18:56:53.4351137Z ##[error]Process completed with exit code 1.
2022-07-12T18:56:53.4416305Z ##[group]Run # copy test results back to the mounted workspace, needed sudo, resulting permissions were correct
2022-07-12T18:56:53.4416882Z �[36;1m# copy test results back to the mounted workspace, needed sudo, resulting permissions were correct�[0m
2022-07-12T18:56:53.4417622Z �[36;1mdocker exec -t "ee09b81c2ae995185c5c5cac979ee54f341a8fae4f082a9bcaff564d67065d5d" sh -c "cd ../pytorch && sudo cp -R test/test-reports ../workspace/test"�[0m
2022-07-12T18:56:53.4457966Z shell: /bin/bash -e {0}
2022-07-12T18:56:53.4458237Z env:

This comment was automatically generated by Dr. CI (expand for details).

Please report bugs/suggestions to the (internal) Dr. CI Users group.

Click here to manually regenerate this comment.

@kulinseth
kulinseth requested a review from razarmehr July 11, 2022 23:24
@kulinseth kulinseth added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 11, 2022

@razarmehr razarmehr 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.

Looks good

@kulinseth

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a merge job. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed due to Refusing to merge as mandatory check(s) pull failed for rule MPS
Raised by https://github.com/pytorch/pytorch/actions/runs/2653506462

@kulinseth

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a rebase job. Check the current status here

* Add test for NLL 1d

* Fix forward NLL for 1D case

* Handle NLL backward for 1d

* Fix handling of 0D target; remove newlines
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased 1d_fix onto refs/remotes/origin/master, please pull locally before adding more changes (for example, via git checkout 1d_fix && git pull --rebase)

@kulinseth

Copy link
Copy Markdown
Collaborator Author

The failure is not related to this:

test_to_padded_tensor_simple_cuda_float16 (__main__.TestNestedTensorDeviceTypeCUDA) ... Memory exception on virtual address 0x7f9c023b7000, node id 4 : Page not present
[78029](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78030)
Address does not belong to a known buffer
[78030](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78031)
Memory access fault by GPU node-4 (Agent handle: 0x561f40ae6510) on address 0x7f9c023b7000. Reason: Page not present or supervisor privilege.
[78031](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78032)
Traceback (most recent call last):
[78032](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78033)
  File "test/run_test.py", line 940, in <module>
[78033](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78034)
    main()
[78034](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78035)
  File "test/run_test.py", line 918, in main
[78035](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78036)
    raise RuntimeError(err_message)
[78036](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78037)
RuntimeError: test_nestedtensor failed! Received signal: SIGIOT
[78037](https://github.com/pytorch/pytorch/runs/7307362222?check_suite_focus=true#step:7:78038)

@kulinseth

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a merge job. Check the current status here

@github-actions

Copy link
Copy Markdown
Contributor

Hey @kulinseth.
You've committed this PR, but it does not have both a 'release notes: ...' and 'topics: ...' label. Please add one of each to the PR. The 'release notes: ...' label should represent the part of PyTorch that this PR changes (fx, autograd, distributed, etc) and the 'topics: ...' label should represent the kind of PR it is (not user facing, new feature, bug fix, perf improvement, etc). The list of valid labels can be found here for the 'release notes: ...' and here for the 'topics: ...'.
For changes that are 'topic: not user facing' there is no need for a release notes label.

facebook-github-bot pushed a commit that referenced this pull request Jul 13, 2022
Summary:
* Add test for NLL 1d
* Fix forward NLL for 1D case
* Handle NLL backward for 1d

Pull Request resolved: #81290
Approved by: https://github.com/razarmehr

Test Plan: contbuild & OSS CI, see https://hud.pytorch.org/commit/pytorch/pytorch/ae83e44c5fe5c58d9077f7ac82724bf766a75b57

Reviewed By: DanilBaibak

Differential Revision: D37813284

Pulled By: DanilBaibak

fbshipit-source-id: cb111ed1d141f29bf9079eeb1c9b1c9d44ad2400
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
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request cla signed Merged open source

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants