已合并
fix lazy_init and api export #36705
fix lazy_init and api export #36705
已合并
bellatan创建于 5月26日
4 个文件变更+123-19
@@ -1,7 +1,5 @@
1# Owner(s): ["module: unknown"]1# Owner(s): ["module: unknown"]
2-import json
3import os2import os
4-import statistics
5import subprocess3import subprocess
6import sys4import sys
7import textwrap5import textwrap
@@ -28,13 +26,17 @@ EXPECTED_LOADED_MODULES = [
28 "torch_npu.profiler",26 "torch_npu.profiler",
29 "torch_npu.distributed",27 "torch_npu.distributed",
30 "torch_npu.distributed.rpc",28 "torch_npu.distributed.rpc",
29+ "torch_npu.distributed.nn",
30+ "torch_npu.distributed.nn.functional",
31 "torch_npu.op_plugin",31 "torch_npu.op_plugin",
32 "torch_npu.op_plugin.meta",32 "torch_npu.op_plugin.meta",
33 "torch_npu.op_plugin.meta._meta_registrations",33 "torch_npu.op_plugin.meta._meta_registrations",
34+ "torch_npu.asd.checksum",
34 "torch_npu.utils._dynamo",35 "torch_npu.utils._dynamo",
35 "torch_npu.utils._inductor",36 "torch_npu.utils._inductor",
36 "torch_npu.utils.custom_ops",37 "torch_npu.utils.custom_ops",
37 "torch_npu.utils.patch_getenv",38 "torch_npu.utils.patch_getenv",
39+ "torch_npu.utils.syncbatchnorm",
38]40]
39 41 
40EXPECTED_NOT_LOADED_MODULES = [42EXPECTED_NOT_LOADED_MODULES = [
@@ -486,6 +488,83 @@ class TestTorchNpuBootstrap(TestCase):
486 """488 """
487 )489 )
488 490 
491+ def test_09_legacy_submodule_attribute_compatibility(self):
492+ self._run_python(
493+ """
494+ import sys
495+ import torch_npu
496+ 
497+ # Old behavior: importing torch_npu also exposed these child modules
498+ # as attributes on their parent packages.
499+ 
500+ assert "torch_npu.asd.checksum" in sys.modules
501+ assert hasattr(torch_npu, "asd")
502+ assert hasattr(torch_npu.asd, "checksum")
503+ assert torch_npu.asd.checksum is sys.modules["torch_npu.asd.checksum"]
504+ assert hasattr(torch_npu.asd.checksum, "_matmul_checksum")
505+ 
506+ assert "torch_npu.utils.syncbatchnorm" in sys.modules
507+ assert hasattr(torch_npu.utils, "syncbatchnorm")
508+ assert torch_npu.utils.syncbatchnorm is (
509+ sys.modules["torch_npu.utils.syncbatchnorm"]
510+ )
511+ """
512+ )
513+ 
514+ def test_10_legacy_top_level_distributed_api_compatibility(self):
515+ self._run_python(
516+ """
517+ import torch_npu
518+ from torch.distributed.fsdp import sharded_grad_scaler
519+ from torch_npu._C._distributed_c10d import ParallelStore
520+ from torch_npu.npu.amp.sharded_grad_scaler import _ShardedGradScaler
521+ 
522+ # Old behavior: these names were visible on torch_npu top-level
523+ # due to module-scope imports in the old monolithic __init__.py.
524+ assert hasattr(torch_npu, "ParallelStore")
525+ assert torch_npu.ParallelStore is ParallelStore
526+ assert "ParallelStore" not in torch_npu.__all__
527+ 
528+ assert hasattr(torch_npu, "_ShardedGradScaler")
529+ assert torch_npu._ShardedGradScaler is _ShardedGradScaler
530+ assert "_ShardedGradScaler" not in torch_npu.__all__
531+ 
532+ # The FSDP patch behavior should still be preserved.
533+ assert sharded_grad_scaler.ShardedGradScaler is _ShardedGradScaler
534+ """
535+ )
536+ 
537+ def test_11_import_does_not_trigger_device_count(self):
538+ cases = [
539+ "import torch; import torch_npu",
540+ "import torch_npu",
541+ ]
542+ 
543+ for import_code in cases:
544+ self._run_python(
545+ f"""
546+ import os
547+ 
548+ {import_code}
549+ 
550+ assert torch_npu.npu.is_initialized() is False, (
551+ "import torch_npu unexpectedly triggered NPU lazy init"
552+ )
553+ 
554+ # Regression test for import-time low-level device probing.
555+ # If import torch_npu has already called low-level NPU device count,
556+ # changing ASCEND_RT_VISIBLE_DEVICES here will no longer take effect.
557+ os.environ["ASCEND_RT_VISIBLE_DEVICES"] = "32"
558+ 
559+ raw_count = torch_npu._C._npu_getDeviceCount()
560+ assert raw_count == 0, (
561+ f"import torch_npu unexpectedly triggered low-level NPU "
562+ f"device probing, raw_count={{raw_count}}"
563+ )
564+ 
565+ assert torch_npu.npu.is_initialized() is False
566+ """
567+ )
489 568 
490if __name__ == "__main__":569if __name__ == "__main__":
491 run_tests()570 run_tests()
@@ -30,15 +30,6 @@ os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"
30 30 
31import torch31import torch
32 32 
33-# Import-time env access logging patch. Keep early to capture initialization-time getenv.
34-import torch_npu.utils.patch_getenv
35-from torch_npu._init.core.module_loader import _load_core_modules
36-from torch_npu._init.core.optional_features import _enable_optional_features
37-from torch_npu._init.core.runtime_lifecycle import _initialize_runtime_lifecycle
38-from torch_npu._init.patches.patch_manager import _apply_all_patches
39-from torch_npu._init.registry.registry_manager import _register_components
40-from torch_npu.version import __version__ as __version__
41- 
42 33 
43def _check_device_conflict():34def _check_device_conflict():
44 acc = torch._C._get_accelerator()35 acc = torch._C._get_accelerator()
@@ -61,23 +52,33 @@ def _check_device_conflict():
61 )52 )
62 53 
63 54 
64-def _initialize():55+_check_device_conflict()
65- # 1. pre-init checks
66- _check_device_conflict()
67 56 
68- # 2. core modules, registration side effects and public API export57+ 
58+# Import-time env access logging patch. Keep early to capture initialization-time getenv.
59+import torch_npu.utils.patch_getenv
60+from torch_npu._init.core.module_loader import _load_core_modules
61+from torch_npu._init.core.optional_features import _enable_optional_features
62+from torch_npu._init.core.runtime_lifecycle import _initialize_runtime_lifecycle
63+from torch_npu._init.patches.patch_manager import _apply_all_patches
64+from torch_npu._init.registry.registry_manager import _register_components
65+from torch_npu.version import __version__ as __version__
66+ 
67+ 
68+def _initialize():
69+ # 1. core modules, registration side effects and public API export
69 _load_core_modules()70 _load_core_modules()
70 71 
71- # 3. backend and framework integration registration72+ # 2. backend and framework integration registration
72 _register_components()73 _register_components()
73 74 
74- # 4. apply patches75+ # 3. apply patches
75 _apply_all_patches()76 _apply_all_patches()
76 77 
77- # 5. final extension barrier and shutdown hook78+ # 4. final extension barrier and shutdown hook
78 _initialize_runtime_lifecycle()79 _initialize_runtime_lifecycle()
79 80 
80- # 6. optional runtime features81+ # 5. optional runtime features
81 _enable_optional_features()82 _enable_optional_features()
82 83 
83 84 
@@ -95,6 +95,20 @@ def _export_lazy_python_apis(globals_dict, all_list):
95 _append_unique(all_list, _LAZY_PYTHON_SYMBOLS.keys())95 _append_unique(all_list, _LAZY_PYTHON_SYMBOLS.keys())
96 96 
97 97 
98+def _export_legacy_distributed_apis(globals_dict):
99+ """
100+ Export legacy distributed-related top-level APIs.
101+ Rule:
102+ - torch_npu._C._distributed_c10d.ParallelStore -> torch_npu.ParallelStore
103+ - torch_npu.npu.amp.sharded_grad_scaler._ShardedGradScaler -> torch_npu._ShardedGradScaler
104+ """
105+ from torch_npu._C._distributed_c10d import ParallelStore
106+ from torch_npu.npu.amp.sharded_grad_scaler import _ShardedGradScaler
107+ 
108+ globals_dict["ParallelStore"] = ParallelStore
109+ globals_dict["_ShardedGradScaler"] = _ShardedGradScaler
110+ 
111+ 
98def _export_public_apis():112def _export_public_apis():
99 """113 """
100 Export torch_npu public APIs.114 Export torch_npu public APIs.
@@ -109,6 +123,10 @@ def _export_public_apis():
109 123 
110 3. DType symbols:124 3. DType symbols:
111 - torch_npu._C._cd.DType.<dtype_name> -> torch_npu.<dtype_name>125 - torch_npu._C._cd.DType.<dtype_name> -> torch_npu.<dtype_name>
126+ 
127+ 4. legacy distributed APIs:
128+ - torch_npu._C._distributed_c10d.ParallelStore -> torch_npu.ParallelStore
129+ - torch_npu.npu.amp.sharded_grad_scaler._ShardedGradScaler -> torch_npu._ShardedGradScaler
112 """130 """
113 131 
114 _export_dtype_symbols()132 _export_dtype_symbols()
@@ -120,3 +138,4 @@ def _export_public_apis():
120 _export_lazy_python_apis(globals_dict, all_list)138 _export_lazy_python_apis(globals_dict, all_list)
121 _export_npu_ops(globals_dict, all_list)139 _export_npu_ops(globals_dict, all_list)
122 _export_dtype_symbols()140 _export_dtype_symbols()
141+ _export_legacy_distributed_apis(globals_dict)
@@ -197,10 +197,15 @@ def _load_registration_modules():
197 import torch_npu.npu.aclnn # noqa: F401197 import torch_npu.npu.aclnn # noqa: F401
198 import torch_npu.op_plugin198 import torch_npu.op_plugin
199 import torch_npu.optim # noqa: F401199 import torch_npu.optim # noqa: F401
200+ 
200 from torch_npu.op_plugin.meta import _meta_registrations # noqa: F401201 from torch_npu.op_plugin.meta import _meta_registrations # noqa: F401
201 from torch_npu.utils import custom_ops # noqa: F401202 from torch_npu.utils import custom_ops # noqa: F401
202 from torch_npu.utils._afd_ops import initialize_afd_bindings203 from torch_npu.utils._afd_ops import initialize_afd_bindings
203 204 
205+ # export for submodule
206+ import torch_npu.asd.checksum # noqa: F401
207+ import torch_npu.utils.syncbatchnorm # noqa: F401
208+ 
OO
OopenLiBingCI5月27日

此条代码评论区间+200+208

【openlibing.ci】识别到代码检查告警抑制注释,匹配工具:flake8,请Committer检视其合理性。

likedislike
OopenLiBingCI5月27日

此条代码评论区间+200+208

【openlibing.ci】识别到代码检查告警抑制注释,匹配工具:flake8,请Committer检视其合理性。

likedislike
OopenLiBingCI5月27日

此条代码评论区间+205+208

【openlibing.ci】识别到代码检查告警抑制注释,匹配工具:flake8,请Committer检视其合理性。

likedislike
OopenLiBingCI5月27日

此条代码评论区间+205+208

【openlibing.ci】识别到代码检查告警抑制注释,匹配工具:flake8,请Committer检视其合理性。

likedislike
204 importlib.import_module("torch_npu._op_plugin_docs")209 importlib.import_module("torch_npu._op_plugin_docs")
205 if hasattr(torch_npu, "_op_plugin_docs"):210 if hasattr(torch_npu, "_op_plugin_docs"):
206 delattr(torch_npu, "_op_plugin_docs")211 delattr(torch_npu, "_op_plugin_docs")