1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Process-wide TorchNPU Level 3 policy shared by training and inference."""
16
17from __future__ import annotations
18
19import importlib
20import logging
21import os
22from collections.abc import Mapping
23from typing import Any
24
25import torch
26import torch.utils.deterministic
27
28_POLICY = {
29 "provider": "torch_npu_level3",
30 "fill_uninitialized_memory": False,
31 "level": 3,
32 "torch_version": "2.10.0",
33 "torch_npu_version": "2.10.0.post7",
34}
35_PROCESS_STATE: dict[str, Any] | None = None
36_LOGGER = logging.getLogger(__name__)
37
38
39def normalize_policy(policy: Mapping[str, Any]) -> dict[str, Any]:
40 """Validate a policy without importing or initializing the optional NPU backend.
41
42 Args:
43 policy: User fields or an already normalized, versioned worker policy.
44
45 Returns:
46 The requested fill policy and fixed supported provider/version identity.
47
48 Raises:
49 ValueError: The policy requests an unsupported field, provider, fill or version.
50 """
51 if not isinstance(policy, Mapping):
52 raise ValueError("batch_invariant policy must be a mapping")
53 unknown = set(policy) - set(_POLICY)
54 if unknown:
55 raise ValueError(f"Unknown batch_invariant policy fields: {sorted(unknown, key=str)}")
56 normalized = dict(_POLICY)
57 for name, value in policy.items():
58 expected = _POLICY[name]
59 if name == "fill_uninitialized_memory" and isinstance(value, bool):
60 normalized[name] = value
61 continue
62 if type(value) is not type(expected) or value != expected:
63 raise ValueError(f"batch_invariant {name} must be {expected!r}; got {value!r}")
64 return normalized
65
66
67def _read_snapshot(state: dict[str, Any]) -> dict[str, Any]:
68 backend = state["backend"]
69 # The Python getter may synchronize by writing the level. This pinned C getter is read-only.
70 level = backend._C._npu_get_deterministic_level() # pylint: disable=protected-access
71 return {
72 "provider": state["policy"]["provider"],
73 "level": int(level),
74 "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(),
75 "fill_uninitialized_memory": torch.utils.deterministic.fill_uninitialized_memory,
76 "torch_version": state["torch_version"],
77 "torch_npu_version": state["torch_npu_version"],
78 "pid": state["pid"],
79 "device": f"npu:{backend.npu.current_device()}",
80 }
81
82
83def _verify_state(state: dict[str, Any]) -> dict[str, Any]:
84 snapshot = _read_snapshot(state)
85 expected = {"level": 3, "deterministic_algorithms": True,
86 "fill_uninitialized_memory": state["policy"]["fill_uninitialized_memory"], "device": state["device"]}
87 drift = {name: (value, snapshot[name]) for name, value in expected.items() if snapshot[name] != value}
88 if drift:
89 raise RuntimeError(f"batch_invariant process state drift (expected, actual): {drift}")
90 return snapshot
91
92
93def initialize_batch_invariant(policy: Mapping[str, Any]) -> dict[str, Any]:
94 """Install Level 3 once after selecting the worker's NPU device.
95
96 Args:
97 policy: The shared requested policy, normalized without optional dependencies.
98
99 Returns:
100 Actual process state after a native GEMM forces CANN option application.
101
102 Raises:
103 RuntimeError: Version, device or previously installed state disagree.
104
105 Note:
106 The native setter checks CANN runtime/operator support. Its errors propagate.
107 The startup GEMM checks option application, not numerical batch invariance.
108 """
109 global _PROCESS_STATE # pylint: disable=global-statement
110 normalized = normalize_policy(policy)
111 pid = os.getpid()
112 if _PROCESS_STATE is not None and _PROCESS_STATE["pid"] == pid:
113 return verify_batch_invariant(normalized)
114
115 # TorchNPU is optional in configuration-only and CPU processes.
116 backend = importlib.import_module("torch_npu")
117 versions = {"torch_version": str(torch.__version__), "torch_npu_version": str(backend.__version__)}
118 for name, version in versions.items():
119 if version.split("+", 1)[0] != normalized[name]:
120 raise RuntimeError(f"batch_invariant requires {name}={normalized[name]}, got {version}")
121 if not backend.npu.is_available() or not backend.npu.is_initialized():
122 raise RuntimeError("batch_invariant requires an available NPU device selected before initialization")
123 device = f"npu:{backend.npu.current_device()}"
124 _PROCESS_STATE = {"pid": pid, "policy": normalized, "backend": backend,
125 "device": device, "ready": False, **versions}
126 backend.npu.set_deterministic_level(3)
127 torch.utils.deterministic.fill_uninitialized_memory = normalized["fill_uninitialized_memory"]
128 with torch.no_grad():
129 left = torch.ones((1, 16), dtype=torch.bfloat16, device=device)
130 right = torch.ones((16, 16), dtype=torch.bfloat16, device=device)
131 torch.mm(left, right)
132 backend.npu.synchronize()
133 snapshot = _verify_state(_PROCESS_STATE)
134 _PROCESS_STATE["ready"] = True
135 _LOGGER.info("Installed batch_invariant policy=%s actual_state=%s", normalized, snapshot)
136 return snapshot
137
138
139def verify_batch_invariant(policy: Mapping[str, Any]) -> dict[str, Any]:
140 """Read the current process policy and reject drift without modifying any state.
141
142 Args:
143 policy: The shared policy expected by this model or lifecycle boundary.
144
145 Returns:
146 Actual Level, Torch deterministic flag, fill, versions, PID and device.
147
148 Raises:
149 RuntimeError: Installation is missing, incomplete or no longer matches the policy.
150 """
151 normalized = normalize_policy(policy)
152 state = _PROCESS_STATE
153 if state is None or state["pid"] != os.getpid() or not state["ready"]:
154 raise RuntimeError("batch_invariant policy has not completed initialization in this process")
155 if normalized != state["policy"]:
156 raise RuntimeError("batch_invariant policy conflicts with the policy already installed in this process")
157 return _verify_state(state)