Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / runtime / device.py: 43%
72 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 2025-2026 Bytedance Ltd. and/or its affiliates
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.
15# Following codes are inspired from https://github.com/volcengine/verl/blob/main/verl/utils/device.py
17# This file keeps its upstream copyright header.
18# pylint: disable=missing-apache-license-header
19"""Trainer-side runtime device API.
21Split out of the former ``auto_models/components/utils/device.py`` in stage 7
22(05 §10.4): runtime device selection belongs to the Trainer. The
23accelerator-discovery primitives (``get_device_type`` / ``get_torch_device``
24/ ``get_device_id`` and the availability flags) are single-sourced in
25``hyper_parallel.models.build_options`` — the Trainer-independent home
26that model construction uses when no explicit device option is given — and
27re-exported here so Trainer consumers have one import site.
28"""
30__all__ = [
31 "IS_CUDA_AVAILABLE",
32 "IS_NPU_AVAILABLE",
33 "get_device_type",
34 "get_device_name",
35 "get_torch_device",
36 "get_device_id",
37 "get_dist_comm_backend",
38 "synchronize",
39 "stream_synchronize",
40 "empty_cache",
41 "set_device",
42 "simulate_device_runtime",
43 "is_device_runtime_simulated",
44 "get_device_rng_state",
45 "set_device_rng_state",
46 "is_nccl_backend",
47 "is_hccl_backend",
48 "get_gpu_compute_capability",
49 "is_sm90_or_above",
50 "get_compute_units",
51]
53import logging
54from typing import Any, Optional, Union
56import torch
58# Logical-simulation mode: when enabled (by the dry-run tool before it drives
59# real Trainer code over FakeTensors), every device-side effect in this module
60# becomes a no-op so the process never binds an accelerator, initializes its
61# runtime, or appears on device tooling. Pure queries (device type, flags)
62# stay live — simulation intentionally reports the real accelerator topology.
63# The switch is shared with core components (activation swap, optimizer swap,
64# FSDP offload) so they consult the same process-wide simulation state.
65from hyper_parallel.tools.dryrun.simulation import (
66 is_device_runtime_simulated,
67 simulate_device_runtime,
68)
69from hyper_parallel.models.build_options import (
70 IS_CUDA_AVAILABLE,
71 IS_NPU_AVAILABLE,
72 get_device_id,
73 get_device_type,
74 get_torch_device,
75)
78logger = logging.getLogger(__name__)
81def get_device_name() -> str:
82 """Get real device name, e.g. A100, H100"""
83 return get_torch_device().get_device_name()
86def get_dist_comm_backend() -> str:
87 """Return distributed communication backend type based on device type."""
88 if IS_CUDA_AVAILABLE:
89 return "nccl"
90 if IS_NPU_AVAILABLE:
91 return "hccl"
92 raise RuntimeError(f"No available distributed communication backend found on device type {get_device_type()}.")
95def synchronize() -> None:
96 """Execute the accelerator synchronize operation."""
97 if is_device_runtime_simulated():
98 return
99 get_torch_device().synchronize()
102def stream_synchronize() -> None:
103 """Execute device stream synchronize operation."""
104 if is_device_runtime_simulated():
105 return
106 if IS_CUDA_AVAILABLE:
107 torch.cuda.current_stream().synchronize()
108 elif IS_NPU_AVAILABLE:
109 torch.npu.current_stream().synchronize()
110 else:
111 synchronize()
114def empty_cache() -> None:
115 """Execute the accelerator empty cache operation."""
116 if is_device_runtime_simulated():
117 return
118 get_torch_device().empty_cache()
121def set_device(device: torch.types.Device) -> None:
122 """Execute set device operation.
124 Args:
125 device: Device the process should bind to.
126 """
127 if is_device_runtime_simulated():
128 return
129 get_torch_device().set_device(device)
132def get_device_rng_state() -> Any:
133 """Return the current accelerator RNG state, or ``None`` when unavailable.
135 Checkpointing needs the device RNG alongside the CPU one: dropout,
136 ``torch.randn`` initializers and any device-side sampling draw from it, so a
137 resume that only restores ``torch.get_rng_state()`` diverges from the
138 original run.
139 """
140 if get_device_type() == "cpu":
141 return None
142 get_rng_state = getattr(get_torch_device(), "get_rng_state", None)
143 if get_rng_state is None:
144 return None
145 return get_rng_state()
148def set_device_rng_state(state: Any) -> None:
149 """Restore an accelerator RNG state captured by :func:`get_device_rng_state`."""
150 if state is None or get_device_type() == "cpu":
151 return
152 set_rng_state = getattr(get_torch_device(), "set_rng_state", None)
153 if set_rng_state is None:
154 logger.warning("Device namespace has no set_rng_state; device RNG not restored.")
155 return
156 set_rng_state(state)
159def is_nccl_backend(backend: Optional[str] = None) -> bool:
160 """Check if the distributed communication backend is NCCL."""
161 return (backend or get_dist_comm_backend()) == "nccl"
164def is_hccl_backend() -> bool:
165 """Check if the distributed communication backend is HCCL."""
166 return get_dist_comm_backend() == "hccl"
169def get_gpu_compute_capability(
170 device: Optional[Union[torch.types.Device, int]] = None,
171) -> int:
172 """Return the compute capability as an integer (e.g. 70, 80, 90), or 0 if no GPU."""
173 if not IS_CUDA_AVAILABLE:
174 return 0
175 major, minor = torch.cuda.get_device_capability(device)
176 return major * 10 + minor
179def is_sm90_or_above() -> bool:
180 """Check if the current CUDA device has SM90+ capability."""
181 return get_gpu_compute_capability() >= 90
184def get_compute_units() -> int:
185 """
186 Returns the number of streaming multiprocessors (SMs) or equivalent compute units
187 for the available accelerator.
188 """
189 device_type = getattr(torch.accelerator.current_accelerator(), "type", "cpu")
191 if device_type == "cuda":
192 device_properties = torch.cuda.get_device_properties(0)
193 num_compute_units = device_properties.multi_processor_count
194 elif device_type == "xpu":
195 device_properties = torch.xpu.get_device_properties(0)
196 num_compute_units = device_properties.max_compute_units
197 else:
198 logger.warning("No CUDA or XPU device available. Using CPU.")
199 num_compute_units = torch.get_num_threads()
201 return num_compute_units