Skip to content

[Testcase Refactoring] Instantiate TestConverterDevice for all supported devices - #190296

Closed
SHIHAIFENG15 wants to merge 16 commits into
pytorch:mainfrom
SHIHAIFENG15:npu-device-agnostic-from-main
Closed

SHIHAIFENG15 wants to merge 16 commits into
pytorch:mainfrom
SHIHAIFENG15:npu-device-agnostic-from-main

Conversation

@SHIHAIFENG15

@SHIHAIFENG15 SHIHAIFENG15 commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Drop only_for=("cpu", "cuda", "xpu") from instantiate_device_type_tests(TestConverterDevice, ...), so the class instantiates for every supported device type, including PrivateUse1 backends such as NPU. allow_xpu=True is preserved, keeping the XPU class from #197113.

test_prim_device needs no changes for this: it creates its input on the injected device, and the module under test builds torch.ones(..., device=x.device).

Test plan

python -m pytest test/export/test_converter.py --collect-only -q

CPU collect: 47 tests, including TestConverterDeviceCPU::test_prim_device_cpu.

With a registered PrivateUse1 backend (for example NPU), TestConverterDevicePRIVATEUSE1::test_prim_device_npu is collected as well.

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Jul 17, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 1da7a61 with merge base ff30875 (image):

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

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

  • ✅ login: SHIHAIFENG15 / name: SHIHAIFENG15 (8b7979b)

@janeyx99
janeyx99 requested a review from angelayi July 17, 2026 22:04
@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 17, 2026
@janeyx99
janeyx99 requested a review from fffrog July 17, 2026 22:04
@fffrog fffrog moved this from Backlog to Ready for Review(Initial) in PyTorch Test Refactoring Jul 19, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

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

@SHIHAIFENG15
SHIHAIFENG15 force-pushed the npu-device-agnostic-from-main branch from e8cec13 to 46b160e Compare July 20, 2026 09:41
@SHIHAIFENG15 SHIHAIFENG15 changed the title [Test] Make export converter/draft_export device checks device-agnostic [Test] Make export converter/draft_export/ExportDB device checks device-agnostic Jul 20, 2026
@SHIHAIFENG15
SHIHAIFENG15 force-pushed the npu-device-agnostic-from-main branch from 46b160e to a7da3c2 Compare July 20, 2026 09:54
SHIHAIFENG15 added a commit to SHIHAIFENG15/pytorch that referenced this pull request Jul 21, 2026
Stack on npu-device-agnostic-from-main (PR pytorch#190296). Continue
device-agnosticizing Export/AOTI tests with instantiate_device_type_tests
and injected device, without using GPU_TYPE/HAS_GPU as the NPU entry path.

Includes accelerator/Triton splits for export+serialize, MoveToDevicePass,
nativert/experimental non-Flex coverage, dynamic AOTI runner selection,
torchbind instantiate+Triton helper, plus MoveToDeviceIndex and
AutocastException device classes (except_for=cpu).

Test Plan:
```
./run_test.sh cpu test/export/test_converter.py -v -k prim_device
./run_test.sh npu test/export/test_export.py -v -k assert_tensor_metadata_device_index
./run_test.sh npu test/export/test_export.py -v -k TestExportAutocastException
```

Co-authored-by: Cursor <[email protected]>
SHIHAIFENG15 added a commit to SHIHAIFENG15/pytorch that referenced this pull request Jul 22, 2026
Stack on npu-device-agnostic-from-main (PR pytorch#190296). Continue
device-agnosticizing Export/AOTI tests with instantiate_device_type_tests
and injected device, without using GPU_TYPE/HAS_GPU as the NPU entry path.

Includes accelerator/Triton splits for export+serialize, MoveToDevicePass,
nativert coverage, FlexAttention/BlockMask export instantiate classes,
dynamic AOTI runner selection, shared ensure_triton helper, torchbind
instantiate+Triton gate, plus MoveToDeviceIndex and AutocastException
device classes (except_for=cpu).

Test Plan:
```
./run_test.sh cpu test/export/test_export.py -v -k test_flex_attention_export
./run_test.sh npu test/export/test_export.py -v -k test_flex_attention_export
./run_test.sh cpu test/export/test_experimental.py -v -k TestExperimentFlex
./run_test.sh npu test/export/test_experimental.py -v -k TestExperimentFlex
./run_test.sh npu test/export/test_export.py -v -k TestExportAutocastException
```

Co-authored-by: Cursor <[email protected]>
SHIHAIFENG15 added a commit to SHIHAIFENG15/pytorch that referenced this pull request Jul 24, 2026
Stack on npu-device-agnostic-from-main (PR pytorch#190296). Continue
device-agnosticizing Export/AOTI tests with instantiate_device_type_tests
and injected device, without using GPU_TYPE/HAS_GPU as the NPU entry path.

Includes accelerator/Triton splits for export+serialize, MoveToDevicePass,
nativert coverage, FlexAttention/BlockMask export instantiate classes,
dynamic AOTI runner selection, shared ensure_triton helper, torchbind
instantiate+Triton gate, plus MoveToDeviceIndex and AutocastException
device classes (except_for=cpu).

Test Plan:
```
./run_test.sh cpu test/export/test_export.py -v -k test_flex_attention_export
./run_test.sh npu test/export/test_export.py -v -k test_flex_attention_export
./run_test.sh cpu test/export/test_experimental.py -v -k TestExperimentFlex
./run_test.sh npu test/export/test_experimental.py -v -k TestExperimentFlex
./run_test.sh npu test/export/test_export.py -v -k TestExportAutocastException
```

Co-authored-by: Cursor <[email protected]>
SHIHAIFENG15 added a commit to SHIHAIFENG15/pytorch that referenced this pull request Jul 24, 2026
Stack on npu-device-agnostic-from-main (PR pytorch#190296). Continue
device-agnosticizing Export/AOTI tests with instantiate_device_type_tests
and injected device, without using GPU_TYPE/HAS_GPU as the NPU entry path.

Includes accelerator/Triton splits for export+serialize, MoveToDevicePass,
nativert coverage, FlexAttention/BlockMask export instantiate classes,
dynamic AOTI runner selection, shared ensure_triton helper, torchbind
instantiate+Triton gate, plus MoveToDeviceIndex and AutocastException
device classes (except_for=cpu).

Test Plan:
```
./run_test.sh cpu test/export/test_export.py -v -k test_flex_attention_export
./run_test.sh npu test/export/test_export.py -v -k test_flex_attention_export
./run_test.sh cpu test/export/test_experimental.py -v -k TestExperimentFlex
./run_test.sh npu test/export/test_experimental.py -v -k TestExperimentFlex
./run_test.sh npu test/export/test_export.py -v -k TestExportAutocastException
```

Co-authored-by: Cursor <[email protected]>
@SHIHAIFENG15

Copy link
Copy Markdown
Contributor Author

@fffrog

@SHIHAIFENG15

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: tests/graph"

@pytorch-bot pytorch-bot Bot added the module: tests/graph This label covers all test cases within the Graph sheet. label Jul 25, 2026
@SHIHAIFENG15 SHIHAIFENG15 changed the title [Test] Make export converter/draft_export/ExportDB device checks device-agnostic [Testcase Refactoring] Make export converter/draft_export/ExportDB device checks device-agnostic Jul 28, 2026
@SHIHAIFENG15

Copy link
Copy Markdown
Contributor Author

Follow-up: added hw_classification — instantiate device classes as ACCELERATOR, remaining suites as GENERIC, and moved test_cuda_memory_usage into TestDraftExportCuda (CUDA), per #186918.

@fffrog could you please take a look and kick CI when convenient? Thanks!

Comment thread test/export/test_converter.py Outdated
from torch.testing._internal.common_quantized import override_quantized_engine
from torch.testing._internal.common_utils import IS_WINDOWS, run_tests, xfailIfS390X
from torch.testing._internal.common_utils import HardwareClassification, IS_WINDOWS, run_tests, xfailIfS390X

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The line is too long. You are advised to split it into multiple lines.

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.

Thanks — fixed.

Comment thread test/export/test_converter.py Outdated
return torch.ones(2, 3, device=device)

inp = (torch.rand((3, 4), device=device),)
TestConverter()._check_equal_ts_ep_converter(Module(), inp)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The TestConverter object is directly instantiated and the method is called. As a result, the original setUp is not triggered, and init_torchbind_implementations is skipped. It is recommended that a public base class be extracted, and setUp and other methods be placed in the base class. TestConverter and TestConverterPrimDevice inherit the new base class.

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.

Fixed — added _ConverterCheckMixin with the shared helpers; TestConverterPrimDevice now calls self._check_equal_ts_ep_converter(...). Verified on CPU/NPU.

Comment thread test/export/test_draft_export.py Outdated
@@ -12,7 +12,8 @@
from torch.export._draft_export import DraftExportReport, FailureReport, FailureType
from torch.fx.experimental.symbolic_shapes import ShapeEnv
from torch.testing import FileCheck
from torch.testing._internal.common_utils import IS_WINDOWS, run_tests, TestCase
from torch.testing._internal.common_device_type import instantiate_device_type_tests
from torch.testing._internal.common_utils import HardwareClassification, IS_WINDOWS, run_tests, TestCase

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The same question as above.

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.

Fixed.

Comment thread test/export/test_draft_export.py Outdated
@@ -767,6 +762,11 @@ def forward(self, x, y):
package_path=f.name,
)



class TestDraftExportCuda(TestCase):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

There are three blank lines before the class definition.

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.

Fixed.

return x
def forward(self, x, y=None):
# Tensor default args are always created on CPU; build on x.device instead.
if y is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The semantics has changed. When y is None, x is returned. Now, when y is None, y is automatically created as y = torch.ones_like(x), and x + y is returned.

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.

Fixed — restored return x when y is None and kept y in example_args for device-safe tracing.

Comment thread test/export/test_draft_export.py Outdated
@@ -767,6 +762,11 @@ def forward(self, x, y):
package_path=f.name,
)



class TestDraftExportCuda(TestCase):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The TestDraftExportCuda class is not registered using instantiate_device_type_tests.

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.

Fixed — registered with instantiate_device_type_tests(..., only_for="cuda").

Comment thread test/export/test_db.py Outdated
dynamic_shapes=rewrite_case.dynamic_shapes,
strict=True,
)


instantiate_parametrized_tests(ExampleTests)
instantiate_device_type_tests(ExampleTests, globals())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Should allow_mps=True and allow_xpu=True be added? Originally, there was no constraint, and it only supported CPU and CUDA.

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.

Addressed — kept default instantiate (CPU/CUDA/PrivateUse1). No other test/export/* file opts into MPS/XPU via allow_mps/allow_xpu; this PR follows the same pattern. Enabling them would expand test scope beyond this refactor task.

@SHIHAIFENG15
SHIHAIFENG15 force-pushed the npu-device-agnostic-from-main branch from a9e8d7f to 071e1f0 Compare August 12, 2026 07:00
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
@can-gaa-hou

Copy link
Copy Markdown
Collaborator

@claude review this pr with pr review skill

@claude

claude Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Claude finished @can-gaa-hou's task in 28m 52s —— View job


Test-only refactor that moves CUDA-hardcoded export tests to instantiate_device_type_tests; I found one real robustness regression (get_memory_info hard-errors instead of skipping on a privateuse1 backend without memory hooks) and an internally-inconsistent hw_classification label that makes a generated CPU class claim to be ACCELERATOR.

Full review — PR #190296

PR Review: #190296

Summary

Converts CUDA-gated / CPU-only device checks in test/export/test_converter.py, test_draft_export.py, and test_db.py into instantiate_device_type_tests classes with an injected device, plus hw_classification annotations. Two substantive problems below (memory-API error mode, mislabeled CPU class) plus two consistency items.

Testing

  • test_draft_export.py:744 — get_memory_info turns an unsupported backend into a test ERROR, not a skip. The old gate was torch.cuda.get_device_properties(0).total_memory evaluated inside unittest.skipIf, so it only ever ran on CUDA. The new call is in the test body and reaches at::getDeviceAllocator(device_type)->getMemoryInfo(...), whose base implementation is TORCH_CHECK_NOT_IMPLEMENTED(false, "getMemoryInfo is not implemented for this allocator yet.") (c10/core/CachingDeviceAllocator.h:262-265). A PrivateUse1 backend that registers hooks but has not implemented getMemoryInfo — which is the exact audience this PR is written for — will fail this test with a NotImplementedError rather than skipping. getMemoryInfo is the only one of the four APIs used here that is not pure-virtual, so it is the only one that can do this. Wrap the query and skip on NotImplementedError, e.g.

    try:
        total_memory = torch.accelerator.get_memory_info(device)[1]
    except NotImplementedError:
        self.skipTest(f"{device} allocator does not implement getMemoryInfo")

    Two secondary consequences of the same gap, resolved by the same guard:

    • torch.accelerator.memory_stats() short-circuits to an empty OrderedDict when the allocator is not yet initialized (torch/accelerator/memory.py:115-116), so ...["allocated_bytes.all.peak"] at line 765 is a bare KeyError rather than an informative failure. It happens to be safe today only because torch.randn(..., device=device) on line 760 initializes the allocator first — that is an undocumented ordering dependency the reader has to reconstruct.
    • reset_peak_memory_stats (line 756) and memory_allocated (line 757) run before that allocation and are silent no-ops / return 0 when the allocator is uninitialized (memory.py:231-232, memory.py:140). The old torch.cuda.reset_peak_memory_stats had no such guard and always reset. The assertion still holds because peak is ~0 in that state, but the "measure base usage" comment now describes something that may not have happened.

    Fix this →

  • test_draft_export.py:738-741 — the @unittest.skipIf(not torch.accelerator.is_available(), ...) decorator gates on the wrong device. torch.accelerator.is_available() reports on the current accelerator, not the device the generated class is parametrized over. Combined with except_for="cpu" at line 818 — where every remaining base (CUDATestBase, XPUTestBase, HPUTestBase, PrivateUse1TestBase) is only added to device_type_test_bases when that specific device is available (common_device_type.py:1025-1131) — this decorator adds no coverage the instantiation does not already provide, while implying a check it does not perform. Drop it and rely on the in-body device-specific gate from the previous item.

Infrastructure

  • test_converter.py:1500 vs test_draft_export.py:817-818 — the two halves of this PR label hw_classification inconsistently, and one of them is wrong. TestConverterPrimDevice is marked HardwareClassification.ACCELERATOR but instantiated with no except_for, so CPUTestBase is included (common_device_type.py:1024) and a TestConverterPrimDeviceCPU class is generated. Non-test class attributes are copied verbatim onto every generated class (common_device_type.py:1304-1306), so that CPU class carries hw_classification = ACCELERATOR. Running --hw-classification ACCELERATOR then executes a pure-CPU test, and --hw-classification CPU skips it — the opposite of the intent documented at common_utils.py:135-142. The sibling change in the same PR gets this right by passing except_for="cpu".

    Note that CPU coverage here is load-bearing: the original test_prim_device was CPU-only, so except_for="cpu" cannot simply be added without losing it. Either (a) keep the CPU instantiation and label the class GENERIC, or (b) split it as the draft-export half does — except_for="cpu" on an ACCELERATOR class, and leave a plain CPU test_prim_device on TestConverter. Whichever you pick, the two files in this PR should agree. (There is prior art for the mislabeled form at test/export/test_torchbind.py:1578-1579,1644, so if you believe the label is correct as-is, please say so explicitly — but the PR should not ship both conventions at once.)

    Fix this →

Code Quality

  • test_converter.py:33 — class _ConverterCheckMixin(TestCase) inherits TestCase, unlike every comparable helper in the repo. The established pattern for a shared-assertion helper is a bare mixin whose concrete subclasses supply TestCase: _AutogradFunctionalHelpers (test/autograd/test_functional.py:104, consumed as class TestAutogradFunctional(_AutogradFunctionalHelpers, TestCase) at line 129 and TestAutogradFunctionalDevice at line 1730), _SetKeyCoercionMixin (test/dynamo/test_sets.py:809), _SubclassCompileCheckMixin (test/dynamo/test_subclasses.py:503), _TraceValidatorE2EMixin (test/profiler/test_trace_validator.py:223) — none of them subclass TestCase. As written the mixin is itself a module-scope unittest.TestCase subclass, which unittest.TestLoader.loadTestsFromModule collects regardless of the leading underscore (it collects zero tests, so this is latent rather than broken today). Prefer class _ConverterCheckMixin: with class TestConverter(_ConverterCheckMixin, TestCase) and class TestConverterPrimDevice(_ConverterCheckMixin, TestCase).

  • Renamed tests silently orphan any existing disable/flaky entries. test_cuda_memory_usage becomes test_memory_usage_cuda (TestDraftExportDeviceCUDA), test_missing_meta_kernel_guard becomes test_missing_meta_kernel_guard_cuda, and test_prim_device_cuda disappears in favor of test_prim_device_cuda on a new class. PyTorch's disable-test and TD machinery keys on the exact test_name (class_path) string, so any tracking issue for the old names stops matching. I found no in-repo references to the old names, so nothing needs a code update — just be aware if any of these have open disable issues.

Recommendation

Request Changes

The get_memory_info error mode is the substantive one: it makes the test hard-fail on precisely the class of backend this PR exists to support, where the old code would not have run at all. The hw_classification inconsistency is a one-line fix but is worth resolving before merge, since shipping both conventions in a single PR cements the ambiguity for whoever copies this next. The mixin base class and the redundant is_available() decorator are cleanups that can ride along.

| Branch: `npu-device-agnostic-from-main`

@SHIHAIFENG15
SHIHAIFENG15 force-pushed the npu-device-agnostic-from-main branch from 9a2e875 to 1ae6fc3 Compare September 3, 2026 08:02
Keep TestConverterPrimDevice as ACCELERATOR with except_for="cpu",
and restore CPU test_prim_device on TestConverter. _ConverterCheckMixin
no longer subclasses TestCase; both classes take (mixin, TestCase).
Skip draft-export memory measurement when getMemoryInfo is missing.

Test Plan:
```
python test/export/test_converter.py -k prim_device
python test/export/test_draft_export.py -k memory_usage
```

Authored with an AI assistant.
@SHIHAIFENG15
SHIHAIFENG15 force-pushed the npu-device-agnostic-from-main branch from 1ae6fc3 to 4fbf82e Compare September 3, 2026 08:17
@SHIHAIFENG15

Copy link
Copy Markdown
Contributor Author

Claude finished @can-gaa-hou's task in 28m 52s —— View job

Test-only refactor that moves CUDA-hardcoded export tests to instantiate_device_type_tests; I found one real robustness regression (get_memory_info hard-errors instead of skipping on a privateuse1 backend without memory hooks) and an internally-inconsistent hw_classification label that makes a generated CPU class claim to be ACCELERATOR.

Full review — PR #190296

PR Review: #190296

Summary

Converts CUDA-gated / CPU-only device checks in test/export/test_converter.py, test_draft_export.py, and test_db.py into instantiate_device_type_tests classes with an injected device, plus hw_classification annotations. Two substantive problems below (memory-API error mode, mislabeled CPU class) plus two consistency items.

Testing

  • test_draft_export.py:744 — get_memory_info turns an unsupported backend into a test ERROR, not a skip. The old gate was torch.cuda.get_device_properties(0).total_memory evaluated inside unittest.skipIf, so it only ever ran on CUDA. The new call is in the test body and reaches at::getDeviceAllocator(device_type)->getMemoryInfo(...), whose base implementation is TORCH_CHECK_NOT_IMPLEMENTED(false, "getMemoryInfo is not implemented for this allocator yet.") (c10/core/CachingDeviceAllocator.h:262-265). A PrivateUse1 backend that registers hooks but has not implemented getMemoryInfo — which is the exact audience this PR is written for — will fail this test with a NotImplementedError rather than skipping. getMemoryInfo is the only one of the four APIs used here that is not pure-virtual, so it is the only one that can do this. Wrap the query and skip on NotImplementedError, e.g.

    try:
        total_memory = torch.accelerator.get_memory_info(device)[1]
    except NotImplementedError:
        self.skipTest(f"{device} allocator does not implement getMemoryInfo")

    Two secondary consequences of the same gap, resolved by the same guard:

    • torch.accelerator.memory_stats() short-circuits to an empty OrderedDict when the allocator is not yet initialized (torch/accelerator/memory.py:115-116), so ...["allocated_bytes.all.peak"] at line 765 is a bare KeyError rather than an informative failure. It happens to be safe today only because torch.randn(..., device=device) on line 760 initializes the allocator first — that is an undocumented ordering dependency the reader has to reconstruct.
    • reset_peak_memory_stats (line 756) and memory_allocated (line 757) run before that allocation and are silent no-ops / return 0 when the allocator is uninitialized (memory.py:231-232, memory.py:140). The old torch.cuda.reset_peak_memory_stats had no such guard and always reset. The assertion still holds because peak is ~0 in that state, but the "measure base usage" comment now describes something that may not have happened.

    Fix this →

  • test_draft_export.py:738-741 — the @unittest.skipIf(not torch.accelerator.is_available(), ...) decorator gates on the wrong device. torch.accelerator.is_available() reports on the current accelerator, not the device the generated class is parametrized over. Combined with except_for="cpu" at line 818 — where every remaining base (CUDATestBase, XPUTestBase, HPUTestBase, PrivateUse1TestBase) is only added to device_type_test_bases when that specific device is available (common_device_type.py:1025-1131) — this decorator adds no coverage the instantiation does not already provide, while implying a check it does not perform. Drop it and rely on the in-body device-specific gate from the previous item.

Infrastructure

  • test_converter.py:1500 vs test_draft_export.py:817-818 — the two halves of this PR label hw_classification inconsistently, and one of them is wrong. TestConverterPrimDevice is marked HardwareClassification.ACCELERATOR but instantiated with no except_for, so CPUTestBase is included (common_device_type.py:1024) and a TestConverterPrimDeviceCPU class is generated. Non-test class attributes are copied verbatim onto every generated class (common_device_type.py:1304-1306), so that CPU class carries hw_classification = ACCELERATOR. Running --hw-classification ACCELERATOR then executes a pure-CPU test, and --hw-classification CPU skips it — the opposite of the intent documented at common_utils.py:135-142. The sibling change in the same PR gets this right by passing except_for="cpu".
    Note that CPU coverage here is load-bearing: the original test_prim_device was CPU-only, so except_for="cpu" cannot simply be added without losing it. Either (a) keep the CPU instantiation and label the class GENERIC, or (b) split it as the draft-export half does — except_for="cpu" on an ACCELERATOR class, and leave a plain CPU test_prim_device on TestConverter. Whichever you pick, the two files in this PR should agree. (There is prior art for the mislabeled form at test/export/test_torchbind.py:1578-1579,1644, so if you believe the label is correct as-is, please say so explicitly — but the PR should not ship both conventions at once.)
    Fix this →

Code Quality

  • test_converter.py:33 — class _ConverterCheckMixin(TestCase) inherits TestCase, unlike every comparable helper in the repo. The established pattern for a shared-assertion helper is a bare mixin whose concrete subclasses supply TestCase: _AutogradFunctionalHelpers (test/autograd/test_functional.py:104, consumed as class TestAutogradFunctional(_AutogradFunctionalHelpers, TestCase) at line 129 and TestAutogradFunctionalDevice at line 1730), _SetKeyCoercionMixin (test/dynamo/test_sets.py:809), _SubclassCompileCheckMixin (test/dynamo/test_subclasses.py:503), _TraceValidatorE2EMixin (test/profiler/test_trace_validator.py:223) — none of them subclass TestCase. As written the mixin is itself a module-scope unittest.TestCase subclass, which unittest.TestLoader.loadTestsFromModule collects regardless of the leading underscore (it collects zero tests, so this is latent rather than broken today). Prefer class _ConverterCheckMixin: with class TestConverter(_ConverterCheckMixin, TestCase) and class TestConverterPrimDevice(_ConverterCheckMixin, TestCase).
  • Renamed tests silently orphan any existing disable/flaky entries. test_cuda_memory_usage becomes test_memory_usage_cuda (TestDraftExportDeviceCUDA), test_missing_meta_kernel_guard becomes test_missing_meta_kernel_guard_cuda, and test_prim_device_cuda disappears in favor of test_prim_device_cuda on a new class. PyTorch's disable-test and TD machinery keys on the exact test_name (class_path) string, so any tracking issue for the old names stops matching. I found no in-repo references to the old names, so nothing needs a code update — just be aware if any of these have open disable issues.

Recommendation

Request Changes

The get_memory_info error mode is the substantive one: it makes the test hard-fail on precisely the class of backend this PR exists to support, where the old code would not have run at all. The hw_classification inconsistency is a one-line fix but is worth resolving before merge, since shipping both conventions in a single PR cements the ambiguity for whoever copies this next. The mixin base class and the redundant is_available() decorator are cleanups that can ride along.

| Branch: npu-device-agnostic-from-main

Thanks for the review.

On hw_classification: going with option (b). TestConverterPrimDevice stays ACCELERATOR and is instantiated with except_for="cpu". The CPU coverage is restored as TestConverter.test_prim_device (GENERIC), next to test_prim_dtype. GENERIC vs ACCELERATOR here is the CI --hw-classification label; instantiate_device_type_tests is what generates the per-device classes and injects device.

On test_memory_usage: get_memory_info now skips on NotImplementedError (PrivateUse1 without allocator hooks). The skipIf(not torch.accelerator.is_available()) decorator is gone; instantiate + except_for="cpu" already keeps this off CPU. We touch the allocator with torch.empty(1, device=device) before the baseline, and read peak via memory_stats(device).get("allocated_bytes.all.peak"), skipping if that key is missing.

Cleanup: _ConverterCheckMixin no longer subclasses TestCase. TestConverter and TestConverterPrimDevice are both (_ConverterCheckMixin, TestCase).

Locally on NPU: TestConverter.test_prim_device, TestConverterPrimDevicePRIVATEUSE1.test_prim_device_npu, and TestDraftExportDevicePRIVATEUSE1.test_memory_usage_npu all passed.

kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Sep 7, 2026
@fffrog
fffrog dismissed their stale review September 13, 2026 13:26

Dismissing my approval to avoid accidental merging. Another maintainer’s approval is still required before merging.

@SHIHAIFENG15 SHIHAIFENG15 changed the title [Testcase Refactoring] Make export converter/draft_export/ExportDB device checks device-agnostic [Testcase Refactoring] Make export converter and draft_export device checks accelerator-generic Sep 20, 2026
pytorch#197113 already moved prim_device into TestConverterDevice for CPU, CUDA, and XPU. Keep that class and drop only_for, so the default bases also instantiate privateuse1 while allow_xpu=True stays. The draft-export device tests and the ExportDB GENERIC tag are unchanged.

Test Plan:
```
python -m pytest test/export/test_converter.py test/export/test_db.py test/export/test_draft_export.py --collect-only -q
# 106 tests collected on CPU. TestConverterDeviceCPU::test_prim_device_cpu is generated. TestDraftExportDevice is not, which matches except_for="cpu".
```
test_db.py and test_draft_export.py move to their own branches. This branch now only drops only_for on TestConverterDevice so the default bases also instantiate privateuse1, while allow_xpu=True stays.

Test Plan:

```
python -m pytest test/export/test_converter.py --collect-only -q
# 47 tests collected on CPU, including TestConverterDeviceCPU::test_prim_device_cpu.
```
@SHIHAIFENG15 SHIHAIFENG15 changed the title [Testcase Refactoring] Make export converter and draft_export device checks accelerator-generic [Testcase Refactoring] Open TestConverterDevice to privateuse1 Oct 13, 2026
Test Plan:
```
.venv/bin/lintrunner -a test/export/test_converter.py
```
lintrunner reported no lint issues. Comment-only change.

Authored with an AI assistant.
@SHIHAIFENG15 SHIHAIFENG15 changed the title [Testcase Refactoring] Open TestConverterDevice to privateuse1 [Testcase Refactoring] Instantiate TestConverterDevice for all supported devices Oct 15, 2026
@SHIHAIFENG15

Copy link
Copy Markdown
Contributor Author

Hi @fffrog @KarhouTam Most changes in this PR have already been split out and merged. What's left is now just a small change. So Could you have a look when you have time? Thanks!

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

Thanks.
cc @fffrog

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

SGTM

@fffrog fffrog moved this from Ready for Review(Definitive) to Ready for Merge in PyTorch Test Refactoring Oct 16, 2026
@fffrog fffrog added the module: tests/simple This label covers all the testcase that are very straightforward label Oct 16, 2026
@fffrog

fffrog commented Oct 16, 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 16, 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 Ready for Merge to Done in PyTorch Test Refactoring Oct 16, 2026
majing921201 pushed a commit to majing921201/pytorch that referenced this pull request Nov 16, 2026
…ted devices (pytorch#190296)

## Summary

Drop `only_for=("cpu", "cuda", "xpu")` from `instantiate_device_type_tests(TestConverterDevice, ...)`, so the class instantiates for every supported device type, including PrivateUse1 backends such as NPU. `allow_xpu=True` is preserved, keeping the XPU class from pytorch#197113.

`test_prim_device` needs no changes for this: it creates its input on the injected `device`, and the module under test builds `torch.ones(..., device=x.device)`.

## Test plan

```bash
python -m pytest test/export/test_converter.py --collect-only -q
```

CPU collect: 47 tests, including `TestConverterDeviceCPU::test_prim_device_cpu`.

With a registered PrivateUse1 backend (for example NPU), `TestConverterDevicePRIVATEUSE1::test_prim_device_npu` is collected as well.
Pull Request resolved: pytorch#190296
Approved by: https://github.com/lizhihai137, https://github.com/fffrog, https://github.com/KarhouTam

Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged module: tests/graph This label covers all test cases within the Graph sheet. module: tests/simple This label covers all the testcase that are very straightforward 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.

8 participants