Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / runtime / memory_profiler.py: 97%
174 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"""Process-local allocator memory profiler used by Trainer runtimes."""
17from __future__ import annotations
19import logging
20import os
21import stat
22import sys
23import time
24from typing import Any, Optional
26from hyper_parallel.trainer.config.training import MemoryConfig
27from hyper_parallel.trainer.runtime.device import get_device_type, get_torch_device
30logger = logging.getLogger(__name__)
33class MemoryProfiler:
34 """Manage one allocator-history profiling session in the current process.
36 Note:
37 The module owns one singleton, so only one Trainer profiling session
38 may be active in a process at a time.
39 """
41 def __init__(self) -> None:
42 """Initialize an inactive profiler."""
43 self.enable = False
44 self.mem_info = False
45 self.current_step = 0
46 self.start_step = 0
47 self.end_step = 0
48 self.save_path = ""
49 self.dump_ranks: list[int] = []
50 self.stacks = "all"
51 self.global_rank = 0
52 self.tp_rank = 0
53 self.dp_rank = 0
54 self._session_active = False
55 self._history_started = False
56 self._device_api: Any = None
57 self._memory_api: Any = None
59 def reset(
60 self,
61 config: Optional[MemoryConfig],
62 *,
63 global_rank: int,
64 tp_rank: int,
65 dp_rank: int,
66 ) -> None:
67 """Replace the process-local session with a Trainer configuration.
69 Args:
70 config: Memory profiler configuration, or ``None`` to disable it.
71 global_rank: Rank in the global process group.
72 tp_rank: Rank in the tensor-parallel group.
73 dp_rank: Rank in the data-parallel group.
74 """
75 self._discard_previous_session()
76 if config is None:
77 self.enable = False
78 self.mem_info = False
79 return
81 self._validate(config)
82 self.enable = config.enable
83 self.mem_info = config.mem_info
84 self.current_step = 0
85 self.start_step = config.start_step
86 self.end_step = config.end_step
87 self.save_path = config.save_path
88 self.dump_ranks = list(config.dump_ranks)
89 self.stacks = config.stacks
90 self.global_rank = global_rank
91 self.tp_rank = tp_rank
92 self.dp_rank = dp_rank
93 self._session_active = self.enable or self.mem_info
95 if self.enable:
96 self._resolve_device_apis(require_history=True)
97 # Match MindSpeed's session-relative control point: step zero runs
98 # after distributed setup and before model construction.
99 self.step()
101 def state_dict(self) -> dict[str, int]:
102 """Protect recording progress; configuration and history remain local."""
103 return {"current_step": self.current_step}
105 def load_state_dict(self, state: dict[str, int]) -> None:
106 """Restore recording progress; the next step reopens any remaining window.
108 The caller must have restarted the device and selected this worker's
109 local device before discarding the previous allocator history.
111 Args:
112 state: Committed session-relative recording progress.
113 """
114 self._discard_previous_session()
115 self.current_step = state["current_step"]
116 self._session_active = self.mem_info or (self.enable and self.current_step <= self.end_step)
118 def step(self) -> None:
119 """Advance the state machine before a Trainer training step starts."""
120 if not self._session_active:
121 return
123 try:
124 if self.enable:
125 if self.start_step <= self.current_step <= self.end_step and not self._history_started:
126 self._record()
127 # The control point precedes training, so dump after the inclusive end step.
128 if self.current_step == self.end_step + 1:
129 try:
130 if self._history_started:
131 self._dump_and_stop_history()
132 finally:
133 if not self.mem_info and not self._history_started:
134 self._session_active = False
136 if self.mem_info:
137 self._log_memory_info()
138 except BaseException:
139 self.abort()
140 raise
141 finally:
142 self.current_step += 1
144 def stop(self) -> None:
145 """Dump an active partial window and end a normal training session."""
146 if not self._session_active and not self._history_started:
147 return
149 try:
150 try:
151 if self._history_started:
152 self._dump_and_stop_history()
153 finally:
154 self._session_active = False
155 except BaseException:
156 self.abort()
157 raise
159 def abort(self) -> None:
160 """Stop allocator history without dumping or masking a Trainer error."""
161 self._session_active = False
162 try:
163 self._stop_history()
164 except Exception: # pylint: disable=broad-exception-caught
165 logger.exception("Failed to stop allocator memory history while aborting training.")
167 def _discard_previous_session(self) -> None:
168 if self._history_started:
169 self._stop_history()
170 self._session_active = False
172 @staticmethod
173 def _validate(config: MemoryConfig) -> None:
174 MemoryProfiler._validate_bool(config.enable, "enable")
175 MemoryProfiler._validate_bool(config.mem_info, "mem_info")
176 MemoryProfiler._validate_steps(config.start_step, config.end_step)
177 MemoryProfiler._validate_save_path(config.save_path)
178 MemoryProfiler._validate_dump_ranks(config.dump_ranks)
179 MemoryProfiler._validate_stacks(config.stacks)
181 @staticmethod
182 def _validate_bool(value: bool, name: str) -> None:
183 if not isinstance(value, bool):
184 raise TypeError(f"memory.{name} must be a bool")
186 @staticmethod
187 def _validate_steps(start_step: int, end_step: int) -> None:
188 for name, value in (("start_step", start_step), ("end_step", end_step)):
189 if isinstance(value, bool) or not isinstance(value, int):
190 raise TypeError(f"memory.{name} must be an int")
191 if start_step < 0:
192 raise ValueError("memory.start_step must be non-negative")
193 if end_step < start_step:
194 raise ValueError("memory.end_step must be greater than or equal to memory.start_step")
196 @staticmethod
197 def _validate_save_path(save_path: str) -> None:
198 if not isinstance(save_path, str) or not save_path:
199 raise ValueError("memory.save_path must be a non-empty string")
201 @staticmethod
202 def _validate_dump_ranks(dump_ranks: list[int]) -> None:
203 if not isinstance(dump_ranks, list):
204 raise ValueError("memory.dump_ranks must be a list of non-negative integers")
205 if any(
206 isinstance(rank, bool) or not isinstance(rank, int) or rank < 0
207 for rank in dump_ranks
208 ):
209 raise ValueError("memory.dump_ranks must be a list of non-negative integers")
211 @staticmethod
212 def _validate_stacks(stacks: str) -> None:
213 if stacks not in ("python", "all"):
214 raise ValueError("memory.stacks must be 'python' or 'all'")
216 def _record(self) -> None:
217 """Start allocator memory history recording."""
218 self._history_started = True
219 try:
220 # Allocator history has no public API in Torch or torch-npu.
221 self._memory_api._record_memory_history( # pylint: disable=protected-access
222 stacks=self.stacks,
223 max_entries=sys.maxsize,
224 )
225 except Exception:
226 # The private allocator API does not expose whether a failed call
227 # enabled history, so make a best-effort stop before propagating.
228 self.abort()
229 raise
231 def _dump_and_stop_history(self) -> None:
232 try:
233 self._dump()
234 finally:
235 self._stop_history()
237 def _dump(self) -> None:
238 """Dump the allocator snapshot for a configured rank."""
239 if self.global_rank not in self.dump_ranks:
240 return
241 os.makedirs(self.save_path, exist_ok=True)
242 timestamp = time.strftime("%Y-%m-%d-%H-%M-%S")
243 file_path = os.path.join(
244 self.save_path,
245 f"snapshot_{timestamp}_{self.global_rank}.pickle",
246 )
247 # Allocator snapshots have no public API in Torch or torch-npu.
248 self._memory_api._dump_snapshot(file_path) # pylint: disable=protected-access
249 # Some torch-npu releases create snapshots with owner-write permission only.
250 os.chmod(file_path, stat.S_IRUSR | stat.S_IWUSR)
251 logger.info("Memory snapshot dumped to %s", file_path)
253 def _stop_history(self) -> None:
254 if not self._history_started:
255 return
256 self._memory_api._record_memory_history(enabled=None) # pylint: disable=protected-access
257 self._history_started = False
259 def _log_memory_info(self) -> None:
260 """Log and reset peak allocator statistics for the current step."""
261 self._resolve_device_apis(require_history=False)
262 logger.info(
263 "Memory usage step=%s global_rank=%s tp_rank=%s dp_rank=%s "
264 "max_memory_reserved=%s max_memory_allocated=%s",
265 self.current_step,
266 self.global_rank,
267 self.tp_rank,
268 self.dp_rank,
269 self._device_api.max_memory_reserved(),
270 self._device_api.max_memory_allocated(),
271 )
272 self._device_api.reset_peak_memory_stats()
274 def _resolve_device_apis(self, *, require_history: bool) -> None:
275 """Resolve and validate the active device memory APIs."""
276 if self._device_api is None:
277 device_type = get_device_type()
278 if device_type not in ("cuda", "npu"):
279 raise RuntimeError(
280 "memory profiling requires a CUDA or NPU device, "
281 f"but the active device type is {device_type!r}"
282 )
283 self._device_api = get_torch_device()
285 if not require_history or self._memory_api is not None:
286 return
287 self._memory_api = getattr(self._device_api, "memory", None)
288 required_methods = ("_record_memory_history", "_dump_snapshot")
289 missing = [
290 method
291 for method in required_methods
292 if self._memory_api is None
293 or not callable(getattr(self._memory_api, method, None))
294 ]
295 if missing:
296 raise RuntimeError(
297 "memory profiling backend is missing allocator API(s): "
298 + ", ".join(missing)
299 )
302memory_profiler = MemoryProfiler()
305__all__ = ["memory_profiler"]