Skip to content

[Testcase Refactoring] Label test_fsdp_backward_prefetch ACCELERATOR and switch to device-type instantiation - #192945

Closed
twthighd wants to merge 4 commits into
pytorch:mainfrom
twthighd:test/decouple-test_fsdp_backward_prefetch
Closed

twthighd wants to merge 4 commits into
pytorch:mainfrom
twthighd:test/decouple-test_fsdp_backward_prefetch

Conversation

@twthighd

@twthighd twthighd commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Label TestBackwardPrefetch as ACCELERATOR, switch it to instantiate_device_type_tests with method-level @onlyAccelerator gating, migrate the test from the module-level device_type constant to the per-variant self.device_type class attribute, and replace an engine-thread assertEqual arity check with a direct raise AssertionError.

Changes

  • test/distributed/fsdp/test_fsdp_backward_prefetch.py:
    • Add hw_classification = HardwareClassification.ACCELERATOR and import HardwareClassification.
    • Add instantiate_device_type_tests(TestBackwardPrefetch, globals(), allow_xpu=True) with a method-level @onlyAccelerator gate on the test method (previously plain FSDPTestContinuous with no instantiation). The CPU variant is generated and collected on every host and skips cleanly at the method level.
    • The @onlyAccelerator decorator sits above the retained @skip_if_lt_x_gpu(2): on CPU-only hosts the multi-card guard skips the CPU variant before the fixture starts, and on accelerator hosts the CPU variant initializes the class fixture and then skips with reason onlyAccelerator: doesn't run on CPU or meta devices, returned by the workers as a skip result rather than wrapped in an exception.
    • Migrate from the module-level device_type = torch.device(getdevtype()) to the per-variant class attribute self.device_type; delete the module-level constant and the getdevtype import. _test_backward_prefetch and _dist_train keep their original zero-device-arg signatures — the device type flows from the class attribute rather than a parameter chain, so the framework-injected device parameter stays on the test method only.
    • FSDP device_id, nn.Transformer(device=...), and torch.randn(device=...) use the type-only self.device_type: passing the bare injected device (an indexed string, e.g. "cuda:0") to FSDP device_id forces all ranks onto device 0 and silently degrades the multi-device test into a single-device run, while the type-only form lets FSDP resolve the per-rank current device.
    • The arity check inside patched_get_handle_to_prefetch raises AssertionError directly instead of calling self.assertEqual: the check runs inside the FSDP backward hook on the autograd engine thread, where the per-thread test state (DeviceTypeTestBase._tls) is empty, so an assertEqual there fails with AttributeError on rel_tol instead of reporting the intended arity failure. This keeps the change test-file-only; no common_device_type.py modification is needed.
  • tools/linter/adapters/test_linter_allowlist.json: removed the single test/distributed/fsdp/test_fsdp_backward_prefetch.py entry — this PR migrates that file to the linter's requirements.

Motivation

TestBackwardPrefetch runs FSDP device-tensor paths guarded by @skip_if_lt_x_gpu(2) and is not CPU-runnable, so ACCELERATOR is the correct classification; the original class had no instantiation — a classification/mechanism mismatch. The self.device_type migration is required because instantiate_device_type_tests generates per-device variants whose cls.device_type differs and a module-level constant cannot follow. The method-level @onlyAccelerator gating (rather than except_for=("cpu",)) makes the CPU variant visible in CPU-only CI collection instead of suppressed, matching the landed gating form of test_fsdp_freezing_weights.py (#192712, same FSDPTestContinuous base).

Test Plan

  • Verified end-to-end on an 8-device out-of-tree accelerator backend with per-rank devices (FSDP device_id resolves the per-rank current device):
python test/distributed/fsdp/test_fsdp_backward_prefetch.py
# Ran 2 tests — OK (skipped=1): the accelerator variant executes the full
# backward-prefetch training and passes; the CPU variant skips with reason
# "onlyAccelerator: doesn't run on CPU or meta devices"
  • On the same accelerator host, running only the CPU variant (TestBackwardPrefetchCPU) shows the class fixture initializing the workers and the process group before the method-level skip is returned as a skip result (Ran 1 test ... OK (skipped=1)) — the exact path the old except_for form avoided by not generating the CPU variant.
  • With the accelerator backend disabled (simulating a CPU-only runner), the CPU variant is collected and skips at the multi-card guard before the fixture starts.
  • lintrunner reports no lint issues.
  • With the entry removed, the TEST_LINTER full re-check passes for the migrated file: python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json — rc=0, zero lint messages for test/distributed/fsdp/test_fsdp_backward_prefetch.py.

Notes

@pytorch-bot

pytorch-bot Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 8b8ee4d with merge base a4b3692 (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 the topic: not user facing topic category label Aug 11, 2026
@twthighd

Copy link
Copy Markdown
Contributor Author

@twthighd

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: tests/distributed"

kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Sep 7, 2026
@twthighd
twthighd force-pushed the test/decouple-test_fsdp_backward_prefetch branch from a8ec222 to cf1c4dc Compare September 15, 2026 02:49

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.

Suggested change
if len(args) != 2:
raise AssertionError(
"expect _get_handle_to_prefetch(state, current_handle)"
)

We can explicitly raise the error here so that we don't need to modify common_device_type.py

@twthighd twthighd Oct 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 927015faa — the arity check inside patched_get_handle_to_prefetch now raises AssertionError directly instead of calling self.assertEqual, so no assertion machinery runs on the autograd engine thread. I also reverted the precision/rel_tol getter fallback in common_device_type.py since the test-local raise makes it unnecessary — the PR is test-file-only again.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

@twthighd
twthighd force-pushed the test/decouple-test_fsdp_backward_prefetch branch from 927015f to 47f8ac9 Compare October 16, 2026 02:49
@twthighd
twthighd marked this pull request as ready for review October 20, 2026 06:23
@github-actions
github-actions Bot requested a review from fffrog October 20, 2026 06:25
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 20, 2026
@twthighd

Copy link
Copy Markdown
Contributor Author

Hi @d4l3k, please help to review this PR, thank you!

@twthighd
twthighd force-pushed the test/decouple-test_fsdp_backward_prefetch branch from 47f8ac9 to 19edc75 Compare October 31, 2026 08:11
@twthighd

twthighd commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@d4l3k gentle re-ping — the head has been updated (2ebda94). The gating is now the same shape you approved in #191905: CPU variants are collected and skip via the @onlyAccelerator

…and switch to device-type instantiation

Summary:
- Add `hw_classification = HardwareClassification.ACCELERATOR` to
  `TestBackwardPrefetch` and import `HardwareClassification` to align
  with the hardware classification methodology and the TEST_LINTER rules.
- Switch from plain `FSDPTestContinuous` (no instantiation) to
  `instantiate_device_type_tests(..., except_for=("cpu",), allow_xpu=True)`
  so the class is instantiated as a device-type test, generating
  per-accelerator variants (including PrivateUse1 out-of-tree backends)
  instead of running only against the current accelerator.
- Migrate `test_backward_prefetch` from the module-level
  `device_type = torch.device(getdevtype())` to the per-variant class
  attribute `self.device_type`. Delete the module-level `device_type` and
  the `getdevtype` import. `_test_backward_prefetch` and `_dist_train`
  keep their original zero-device-arg signatures: the device type flows
  from the class attribute rather than a parameter chain, so the
  framework-injected `device` parameter stays on the test method only.
- FSDP `device_id` and tensor creation use the type-only
  `self.device_type`: passing the bare injected device to FSDP
  `device_id` forces all ranks to device 0 (silent single-device
  degradation), while the type-only form lets FSDP resolve the per-rank
  current device.
- Fix a latent thread-local initialization gap that this migration
  exposes: `DeviceTypeTestBase.precision`/`rel_tol` read a
  `threading.local` initialized at class-body time, which only covers the
  importing thread. The class's `assertEqual` calls that run inside FSDP
  backward hooks execute on the autograd engine thread, where the local
  is empty and the read raised `AttributeError`. The getters now fall
  back to the class defaults (`getattr(self._tls, ..., TestCase._...)`),
  matching what the class-body initialization assigns.

This aligns the class mechanism with its ACCELERATOR classification and
unblocks instantiating `MultiProcContinuousTest`-based classes whose
assertions run off the main test thread (e.g. inside backward hooks).

This is part of the test case refactoring initiative tracked in pytorch#185590.
…t raise per review

Summary:
- test_fsdp_backward_prefetch.py: the arity check inside
  patched_get_handle_to_prefetch now raises AssertionError directly
  instead of calling self.assertEqual, so no assertEqual runs on the
  autograd engine thread (where DeviceTypeTestBase._tls is empty).
- Revert the precision/rel_tol getter fallback in
  common_device_type.py: the test-local raise makes the framework
  change unnecessary, so the PR is test-file-only again.

This allows the backward-prefetch hook check to run without touching
per-thread test state, keeping test infrastructure unchanged.
…EST_LINTER allowlist

Summary:
- This PR migrates test/distributed/fsdp/test_fsdp_backward_prefetch.py to the TEST_LINTER's
  requirements (hw_classification on every test class plus the per-classification
  structure rules), and the file currently sits in test_linter_allowlist.json.
  Drop its one-line entry in the same PR: the allowlist is a regenerated snapshot
  of non-compliant files, and a migration landing without the deletion leaves a
  silently-stale exemption (canonical: pytorch#191905 needed the follow-up pytorch#202866).

This lets the linter enforce its requirements on future changes to this file
as part of the same change, instead of a separate cleanup PR later.
…evel @onlyAccelerator

Summary:
- Drop except_for=("cpu",) from instantiate_device_type_tests and gate the
  test method with @onlyAccelerator instead, so the CPU variant is generated
  and collected on every host and gated at the method level.
- The baseline MultiProcContinuousTest worker loop already forwards a
  method-level unittest.SkipTest to the parent as a skip result, so the CPU
  variant skips cleanly on hosts with enough devices instead of surfacing
  as an exception-in-worker failure.

This aligns the file with the default ACCELERATOR gating form (same form as
the landed test_fsdp_freezing_weights.py, pytorch#192712) and makes the CPU-only
collection visible on CPU-only CI runners instead of suppressed.
@twthighd
twthighd force-pushed the test/decouple-test_fsdp_backward_prefetch branch from 2ebda94 to 8b8ee4d Compare November 9, 2026 01:37
@twthighd

twthighd commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 9, 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

@github-project-automation github-project-automation Bot moved this from Backlog to Done in PyTorch Test Refactoring Nov 9, 2026
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…and switch to device-type instantiation (pytorch#192945)

## Summary

Label `TestBackwardPrefetch` as `ACCELERATOR`, switch it to `instantiate_device_type_tests` with method-level `@onlyAccelerator` gating, migrate the test from the module-level `device_type` constant to the per-variant `self.device_type` class attribute, and replace an engine-thread `assertEqual` arity check with a direct `raise AssertionError`.

## Changes

- **`test/distributed/fsdp/test_fsdp_backward_prefetch.py`**:
  - Add `hw_classification = HardwareClassification.ACCELERATOR` and import `HardwareClassification`.
  - Add `instantiate_device_type_tests(TestBackwardPrefetch, globals(), allow_xpu=True)` with a method-level `@onlyAccelerator` gate on the test method (previously plain `FSDPTestContinuous` with no instantiation). The CPU variant is generated and collected on every host and skips cleanly at the method level.
  - The `@onlyAccelerator` decorator sits above the retained `@skip_if_lt_x_gpu(2)`: on CPU-only hosts the multi-card guard skips the CPU variant before the fixture starts, and on accelerator hosts the CPU variant initializes the class fixture and then skips with reason `onlyAccelerator: doesn't run on CPU or meta devices`, returned by the workers as a skip result rather than wrapped in an exception.
  - Migrate from the module-level `device_type = torch.device(getdevtype())` to the per-variant class attribute `self.device_type`; delete the module-level constant and the `getdevtype` import. `_test_backward_prefetch` and `_dist_train` keep their original zero-device-arg signatures — the device type flows from the class attribute rather than a parameter chain, so the framework-injected `device` parameter stays on the test method only.
  - FSDP `device_id`, `nn.Transformer(device=...)`, and `torch.randn(device=...)` use the type-only `self.device_type`: passing the bare injected device (an indexed string, e.g. `"cuda:0"`) to FSDP `device_id` forces all ranks onto device 0 and silently degrades the multi-device test into a single-device run, while the type-only form lets FSDP resolve the per-rank current device.
  - The arity check inside `patched_get_handle_to_prefetch` raises `AssertionError` directly instead of calling `self.assertEqual`: the check runs inside the FSDP backward hook on the autograd engine thread, where the per-thread test state (`DeviceTypeTestBase._tls`) is empty, so an `assertEqual` there fails with `AttributeError` on `rel_tol` instead of reporting the intended arity failure. This keeps the change test-file-only; no `common_device_type.py` modification is needed.
- **`tools/linter/adapters/test_linter_allowlist.json`**: removed the single `test/distributed/fsdp/test_fsdp_backward_prefetch.py` entry — this PR migrates that file to the linter's requirements.

## Motivation

`TestBackwardPrefetch` runs FSDP device-tensor paths guarded by `@skip_if_lt_x_gpu(2)` and is not CPU-runnable, so `ACCELERATOR` is the correct classification; the original class had no instantiation — a classification/mechanism mismatch. The `self.device_type` migration is required because `instantiate_device_type_tests` generates per-device variants whose `cls.device_type` differs and a module-level constant cannot follow. The method-level `@onlyAccelerator` gating (rather than `except_for=("cpu",)`) makes the CPU variant visible in CPU-only CI collection instead of suppressed, matching the landed gating form of `test_fsdp_freezing_weights.py` (pytorch#192712, same `FSDPTestContinuous` base).

## Test Plan

- Verified end-to-end on an 8-device out-of-tree accelerator backend with per-rank devices (FSDP `device_id` resolves the per-rank current device):

```bash
python test/distributed/fsdp/test_fsdp_backward_prefetch.py
# Ran 2 tests — OK (skipped=1): the accelerator variant executes the full
# backward-prefetch training and passes; the CPU variant skips with reason
# "onlyAccelerator: doesn't run on CPU or meta devices"
```

- On the same accelerator host, running only the CPU variant (`TestBackwardPrefetchCPU`) shows the class fixture initializing the workers and the process group before the method-level skip is returned as a skip result (`Ran 1 test ... OK (skipped=1)`) — the exact path the old `except_for` form avoided by not generating the CPU variant.
- With the accelerator backend disabled (simulating a CPU-only runner), the CPU variant is collected and skips at the multi-card guard before the fixture starts.
- `lintrunner` reports no lint issues.
- With the entry removed, the TEST_LINTER full re-check passes for the migrated file: `python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json` — rc=0, zero lint messages for `test/distributed/fsdp/test_fsdp_backward_prefetch.py`.

## Notes
- This is part of the test case refactoring initiative tracked in pytorch#185590.

Pull Request resolved: pytorch#192945
Approved by: https://github.com/jialinw77, https://github.com/can-gaa-hou, https://github.com/d4l3k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/trunk Trigger trunk jobs on your pull request Merged module: tests/distributed This label covers all test cases within the Distributed sheet. open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

6 participants