pytorch/test/dynamo/imports_non_circular_repro.py
Lucas Kabela efc810c7d0 [Bugfix] Fix circular import between export and dynamo from tensor fn map (#158931)
Fixes #158120

The issue was caused by populating a builtin tensor fn map at import time; if torch.export.export was called before any dynamo imports with the `meta` device, this map would not be populated, and so would populate on import time which would try to call `torch.disable`, which would not yet be initialized

Fix is to populate this map lazily

```
python test/dynamo/imports_non_circular_repro.py TestImports.test_circular_import_with_export_meta
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/158931
Approved by: https://github.com/StrongerXi, https://github.com/mlazos, https://github.com/anijain2305
2025-07-24 22:24:57 +00:00

30 lines
813 B
Python

# Owner(s): ["module: dynamo"]
"""
This file is aimed at providing a simple testcase to reproduce
https://github.com/pytorch/pytorch/issues/158120
This means that we cannot rely on torch.dynamo before importing
torch.export, so we can't add this to a file that is a dynamo testcase
"""
import unittest
import torch
class TestImports(unittest.TestCase):
def test_circular_import_with_export_meta(self):
from torch.export import export
conv = torch.nn.Conv2d(3, 64, 3, padding=1)
# Note: we want to validate that export within
# torch.device("meta") does not fail due to circular
# import
with torch.device("meta"):
ep = export(conv, (torch.zeros(64, 3, 1, 1),))
self.assertIsNotNone(ep)
if __name__ == "__main__":
unittest.main()