Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / runtime.py: 90%
90 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
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"""Runtime resource, device, and virtual process-group management for dry-run."""
17import logging
18import os
19from contextlib import contextmanager
20from dataclasses import dataclass
21from typing import Iterator, Optional
23import torch
24import torch.distributed as dist
25from torch._subclasses.fake_tensor import FakeTensorMode
27from hyper_parallel.models.build_options import get_device_type
28from hyper_parallel.tools.dryrun.simulation import (
29 is_device_runtime_simulated,
30 release_simulated_stream_holds,
31 simulate_device_runtime,
32 simulated_accelerator,
33)
34from hyper_parallel.trainer.runtime.distributed import (
35 destroy_process_group as destroy_distributed_runtime,
36)
38logger = logging.getLogger(__name__)
41@dataclass(frozen=True)
42class DryRunRuntime:
43 """Distributed worker identity supplied by ``torchrun`` for one dry-run rank."""
45 rank: int
46 world_size: int
47 local_rank: int
49 @classmethod
50 def from_torchrun_env(cls) -> "DryRunRuntime":
51 """Build and validate the current worker identity from ``torchrun`` env vars.
53 Returns:
54 Validated :class:`DryRunRuntime` identity.
56 Raises:
57 RuntimeError: If the process was not launched by ``torchrun``.
58 ValueError: If a launcher variable is outside its valid range.
59 """
60 required_names = ("RANK", "WORLD_SIZE", "LOCAL_RANK")
61 missing_names = [name for name in required_names if name not in os.environ]
62 if missing_names:
63 raise RuntimeError(
64 "Multi-rank HyperDryRun must be launched with torchrun; "
65 f"missing environment variables: {missing_names}"
66 )
67 rank = int(os.environ["RANK"])
68 world_size = int(os.environ["WORLD_SIZE"])
69 local_rank = int(os.environ["LOCAL_RANK"])
70 if world_size < 1:
71 raise ValueError(f"WORLD_SIZE must be >= 1, got {world_size}")
72 if rank < 0 or rank >= world_size:
73 raise ValueError(f"RANK must be in [0, {world_size}), got {rank}")
74 if local_rank < 0:
75 raise ValueError(f"LOCAL_RANK must be >= 0, got {local_rank}")
76 return cls(rank=rank, world_size=world_size, local_rank=local_rank)
78 def torch_device(self, simulation_device: str) -> torch.device:
79 """Return the rank-local logical device used by FakeTensor execution.
81 Args:
82 simulation_device: Logical device type (``"cpu"``, ``"cuda"``, or ``"npu"``).
84 Returns:
85 ``torch.device`` corresponding to this rank on ``simulation_device``.
86 """
87 if simulation_device == "cpu":
88 return torch.device("cpu")
89 return torch.device(simulation_device, self.local_rank)
92def resolve_target_device(configured_device: Optional[str]) -> str:
93 """Resolve the target accelerator type without binding a real device.
95 ``dry_run.target_device`` declares the accelerator the plan targets; host
96 detection is only a fallback so capacity planning can run on hosts without
97 that accelerator.
99 Args:
100 configured_device: Device configured in ``DryRunConfig.target_device``.
102 Returns:
103 ``"cuda"`` or ``"npu"``.
104 """
105 target_device = configured_device
106 if target_device not in ("cuda", "npu"):
107 target_device = get_device_type()
108 if target_device not in ("cuda", "npu"):
109 raise RuntimeError(
110 "HyperModels Dry-run requires dry_run.target_device or an "
111 f"available CUDA or NPU runtime; detected {target_device!r}"
112 )
113 return target_device
116def neutralize_device_capability_probes(target_device: str) -> None:
117 """Answer global accelerator capability queries without initializing hardware.
119 ``torch.utils.checkpoint`` recompute preserves per-backend autocast state,
120 and ``torch_npu.npu.is_bf16_supported`` unconditionally lazy-initializes the
121 NPU runtime, which aborts when zero devices are visible.
123 Args:
124 target_device: Simulated target accelerator type.
125 """
126 if target_device != "npu" or not hasattr(torch, "npu"):
127 return
128 torch.npu.is_bf16_supported = ( # type: ignore[attr-defined]
129 lambda including_emulation=False: True
130 )
133def select_simulation_device(target_device: str) -> str:
134 """Select a registered FakeTensor device without probing real hardware.
136 Args:
137 target_device: Desired accelerator type (``"cuda"`` or ``"npu"``).
139 Returns:
140 ``target_device`` when its backend is registered with visible devices,
141 otherwise ``"cpu"`` for CPU FakeTensor fallback simulation.
142 """
143 backend_registered = (
144 torch.version.cuda is not None
145 if target_device == "cuda"
146 else hasattr(torch, "npu")
147 )
148 if not backend_registered:
149 logger.info(
150 "PyTorch has no %s device guard; using CPU FakeTensor simulation",
151 target_device,
152 )
153 return "cpu"
154 try:
155 # A backend with zero visible devices aborts inside its lazy device
156 # binding on the first device-typed op; fall back to CPU simulation.
157 device_module = getattr(torch, target_device)
158 if int(device_module.device_count()) < 1:
159 logger.info(
160 "No visible %s device; using CPU FakeTensor simulation",
161 target_device,
162 )
163 neutralize_device_capability_probes(target_device)
164 return "cpu"
165 target = torch.device(target_device)
166 with FakeTensorMode():
167 torch.empty((), device=target)
168 return target_device
169 except (AttributeError, RuntimeError):
170 logger.info(
171 "FakeTensor device %s is not registered; using CPU simulation",
172 target_device,
173 )
174 return "cpu"
177def init_fake_process_group(runtime: DryRunRuntime) -> None:
178 """Initialize PyTorch's ``Backend.FAKE`` process group for ``runtime``.
180 Args:
181 runtime: Worker identity providing ``rank`` and ``world_size``.
182 """
183 if dist.is_initialized():
184 raise RuntimeError("Dry-run must start before any process group is initialized")
185 # Import registers the version-matched fake backend factory on demand.
186 # pylint: disable-next=import-outside-toplevel,unused-import
187 from torch.testing._internal.distributed import fake_pg
189 dist.init_process_group(
190 backend="fake",
191 store=dist.HashStore(),
192 world_size=runtime.world_size,
193 rank=runtime.rank,
194 )
197@contextmanager
198def fake_process_group(runtime: DryRunRuntime) -> Iterator[None]:
199 """Manage a ``Backend.FAKE`` process group across one dry-run execution.
201 Args:
202 runtime: Worker identity providing ``rank`` and ``world_size``.
203 """
204 init_fake_process_group(runtime)
205 try:
206 yield
207 finally:
208 destroy_distributed_runtime()
211@contextmanager
212def simulation_runtime_context(simulation_device: str) -> Iterator[None]:
213 """Activate device-runtime simulation and disable FakeTensor dispatch cache.
215 Disabling ``torch._dynamo.config.fake_tensor_cache_enabled`` prevents cache
216 keys from retaining released storages and distorting logical lifetimes.
218 Args:
219 simulation_device: Logical device type selected for simulation.
220 """
221 was_simulated = is_device_runtime_simulated()
222 previous_accelerator = simulated_accelerator()
223 previous_cache_enabled = torch._dynamo.config.fake_tensor_cache_enabled # pylint: disable=protected-access
224 simulate_device_runtime(
225 True,
226 accelerator=None if simulation_device == "cpu" else simulation_device,
227 )
228 torch._dynamo.config.fake_tensor_cache_enabled = False # pylint: disable=protected-access
229 try:
230 yield
231 finally:
232 release_simulated_stream_holds()
233 torch._dynamo.config.fake_tensor_cache_enabled = previous_cache_enabled # pylint: disable=protected-access
234 simulate_device_runtime(was_simulated, accelerator=previous_accelerator)
237__all__ = [
238 "DryRunRuntime",
239 "fake_process_group",
240 "init_fake_process_group",
241 "neutralize_device_capability_probes",
242 "resolve_target_device",
243 "select_simulation_device",
244 "simulation_runtime_context",
245]