Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / memory_tracker.py: 93%

170 statements  

« 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"""Model-independent logical storage tracking with native snapshot output.""" 

16 

17import copy 

18import functools 

19import importlib 

20import os 

21import pickle 

22import sys 

23import tempfile 

24import weakref 

25from pathlib import Path 

26from typing import Any, Iterable 

27 

28import torch 

29from torch._guards import active_fake_mode 

30from torch.distributed._tools.common_utils import get_untyped_storages 

31from torch.utils._python_dispatch import TorchDispatchMode 

32from torch.utils._pytree import tree_flatten 

33 

34# Register shape-only collective implementations for FakeTensor execution. 

35importlib.import_module("torch.distributed._tools.fake_collectives") 

36_ADDRESS_BASE = 0xF00000000000 

37_ADDRESS_ALIGNMENT = 512 

38 

39 

40class LogicalMemoryTracker(TorchDispatchMode): 

41 """Observe storage capacity and lifetime without classifying tensor roles. 

42 

43 Args: 

44 device_type: Logical device type of tensors being simulated. 

45 device_index: Device index used for CPU FakeTensor fallback. 

46 

47 Note: 

48 Segments are synthetic, one per live allocation. There is no caching, 

49 fragmentation, workspace, or asynchronous stream simulation. Only 

50 FakeTensor storages on the simulated target device are tracked. 

51 """ 

52 

53 def __init__( 

54 self, 

55 device_type: str, 

56 device_index: int = 0, 

57 *, 

58 stack_depth: int = 64, 

59 ) -> None: 

60 """Initialize empty storage identities, allocation history, and totals.""" 

61 super().__init__() 

62 if device_index < 0: 

63 raise ValueError("device_index must be non-negative") 

64 if stack_depth < 0: 

65 raise ValueError("stack_depth must be non-negative") 

66 self.device_type = device_type 

67 self.device_index = device_index 

68 self.stack_depth = stack_depth 

69 self._allocations: dict[int, dict[str, Any]] = {} 

70 self._storage_refs: dict[int, Any] = {} 

71 self._traces: list[list[dict[str, Any]]] = [] 

72 self._current: dict[int, int] = {} 

73 self._peaks: dict[int, int] = {} 

74 self._peak_bytes = 0 

75 self._next_address = _ADDRESS_BASE 

76 self._previous_resize = None 

77 self._recording = False 

78 self._stack_cache: dict[tuple, list[dict[str, Any]]] = {} 

79 

80 def __enter__(self) -> "LogicalMemoryTracker": 

81 """Start dispatch tracking and observe direct storage resizes.""" 

82 if self._recording: 

83 raise RuntimeError("LogicalMemoryTracker is already recording") 

84 super().__enter__() 

85 self._recording = True 

86 self._previous_resize = torch.UntypedStorage.resize_ 

87 previous_resize = self._previous_resize 

88 

89 @functools.wraps(previous_resize) 

90 def resize(storage: Any, size: int) -> Any: 

91 """Record capacity transitions after the storage resize completes. 

92 

93 Args: 

94 storage: Storage whose capacity changed. 

95 size: New capacity in bytes. 

96 """ 

97 result = previous_resize(storage, size) 

98 key = int(storage._cdata) # pylint: disable=protected-access 

99 allocation = self._allocations.get(key) 

100 if allocation is not None: 

101 self._observe_storage(storage, allocation["device"]) 

102 return result 

103 

104 torch.UntypedStorage.resize_ = resize 

105 return self 

106 

107 def __exit__(self, *args: Any) -> Any: 

108 """Restore the storage resize hook and freeze the recorded state.""" 

109 torch.UntypedStorage.resize_ = self._previous_resize 

110 self._previous_resize = None 

111 self._recording = False 

112 return super().__exit__(*args) 

113 

114 def _frames(self) -> list[dict[str, Any]]: 

115 """Return the capture stack for the current allocation site.""" 

116 if self.stack_depth == 0: 

117 return [] 

118 frame = sys._getframe().f_back # pylint: disable=protected-access 

119 frames = [] 

120 while frame is not None and len(frames) < self.stack_depth: 

121 code = frame.f_code 

122 if code.co_filename != __file__: 

123 frames.append((code.co_filename, frame.f_lineno, code.co_name)) 

124 frame = frame.f_back 

125 key = tuple(frames) 

126 if key not in self._stack_cache: 

127 self._stack_cache[key] = [ 

128 {"filename": filename, "line": line, "name": name} 

129 for filename, line, name in frames 

130 ] 

131 return self._stack_cache[key] 

132 

133 def _event(self, action: str, allocation: dict[str, Any]) -> None: 

134 device = allocation["device"] 

135 while len(self._traces) <= device: 

136 self._traces.append([]) 

137 trace = self._traces[device] 

138 trace.append({ 

139 "action": action, 

140 "addr": allocation["address"], 

141 "size": allocation["size"], 

142 "stream": 0, 

143 "frames": allocation["frames"], 

144 "pool_id": (0, 0), 

145 }) 

146 

147 def _release(self, key: int) -> None: 

148 """Close one allocation and record its free events.""" 

149 allocation = self._allocations.pop(key, None) 

150 self._storage_refs.pop(key, None) 

151 if allocation is None: 

152 return 

153 if allocation["size"] == 0: 

154 return 

155 allocation = {**allocation, "frames": self._frames()} 

156 self._event("free_requested", allocation) 

157 self._event("free_completed", allocation) 

158 self._event("segment_free", allocation) 

159 self._current[allocation["device"]] -= allocation["size"] 

160 

161 def release_if_current(self, key: int, storage_ref: Any) -> None: 

162 """Close one allocation only if ``storage_ref`` is still its live weakref. 

163 

164 Args: 

165 key: Storage handle key registered in ``_allocations``. 

166 storage_ref: Weak reference that triggered the finalizer. 

167 """ 

168 if self._recording and self._storage_refs.get(key) is storage_ref: 

169 self._release(key) 

170 

171 def _observe_storage(self, storage: Any, device: Any) -> None: 

172 """Record an allocation, resize or release for one storage.""" 

173 key = int(storage._cdata) # pylint: disable=protected-access 

174 size = int(storage.nbytes()) 

175 allocation = self._allocations.get(key) 

176 if allocation is not None: 

177 if allocation["size"] == size and allocation["device"] == device: 

178 return 

179 # A size change is a reallocation; a device change migrates the 

180 # ledger (a storage first seen as device, then marked host by an 

181 # offload seam, must not stay on the device account). 

182 self._release(key) 

183 tracker_ref = weakref.ref(self) 

184 

185 def released(storage_ref: Any) -> None: 

186 """Close the allocation only if this is its current storage reference. 

187 

188 Args: 

189 storage_ref: Weak reference that is being collected. 

190 """ 

191 tracker = tracker_ref() 

192 if tracker is not None: 

193 tracker.release_if_current(key, storage_ref) 

194 

195 # Keep zero-capacity storage identities so a later resize can be observed. 

196 self._storage_refs[key] = weakref.ref(storage, released) 

197 if size == 0: 

198 self._allocations[key] = { 

199 "device": device, "size": 0, "address": 0, "frames": [], 

200 } 

201 return 

202 address = self._next_address 

203 self._next_address += ((size + _ADDRESS_ALIGNMENT - 1) // _ADDRESS_ALIGNMENT) * _ADDRESS_ALIGNMENT 

204 allocation = {"device": device, "size": size, "address": address, "frames": self._frames()} 

205 self._allocations[key] = allocation 

206 self._event("segment_alloc", allocation) 

207 self._event("alloc", allocation) 

208 self._current[device] = self._current.get(device, 0) + size 

209 self._peaks[device] = max(self._peaks.get(device, 0), self._current[device]) 

210 self._peak_bytes = max(self._peak_bytes, sum(self._current.values())) 

211 

212 def track(self, tensors: Iterable[torch.Tensor]) -> None: 

213 """Register existing tensors without retaining them or their storages. 

214 

215 Args: 

216 tensors: Existing inputs, state, or newly returned tensors. 

217 """ 

218 if not self._recording: 

219 raise RuntimeError("Enter LogicalMemoryTracker before registering tensors") 

220 for tensor in tensors: 

221 if not hasattr(tensor, "fake_mode"): 

222 continue 

223 if tensor.device.type != self.device_type: 

224 continue 

225 device = tensor.device.index 

226 if device is None: 

227 device = self.device_index 

228 for storage in get_untyped_storages(tensor): 

229 self._observe_storage(storage, device) 

230 

231 def __torch_dispatch__(self, func: Any, types: Any, args: tuple = (), kwargs: Any = None) -> Any: 

232 del types 

233 input_values, _ = tree_flatten((args, kwargs)) 

234 # FakeTensor constant propagation must not execute collective kernels 

235 # on tiny materialized scalars in the virtual process group. 

236 if str(func).startswith("c10d."): 

237 for value in input_values: 

238 if isinstance(value, torch.Tensor) and hasattr(value, "fake_mode"): 

239 value.constant = None 

240 self.track(value for value in input_values if isinstance(value, torch.Tensor)) 

241 # Fake wait_tensor's Meta kernel returns a new storage, unlike a real wait. 

242 if func is torch.ops._c10d_functional.wait_tensor.default and active_fake_mode() is not None: # pylint: disable=protected-access 

243 result = args[0] 

244 else: 

245 result = func(*args, **(kwargs or {})) 

246 output_values, _ = tree_flatten(result) 

247 self.track(value for value in (*input_values, *output_values) if isinstance(value, torch.Tensor)) 

248 return result 

249 

250 def snapshot(self) -> dict[str, Any]: 

251 """Return an independent native-compatible snapshot of logical memory. 

252 

253 Returns: 

254 Native segments and device traces, with logical summary and 

255 simulation assumptions. Event list order is the logical timeline. 

256 """ 

257 segments = [] 

258 for allocation in self._allocations.values(): 

259 size = allocation["size"] 

260 if size == 0: 

261 continue 

262 segments.append({ 

263 "device": allocation["device"], 

264 "address": allocation["address"], 

265 "total_size": size, 

266 "allocated_size": size, 

267 "active_size": size, 

268 "requested_size": size, 

269 "stream": 0, 

270 "segment_type": "small" if size <= 2 ** 20 else "large", 

271 "segment_pool_id": (0, 0), 

272 "is_expandable": False, 

273 "frames": allocation["frames"], 

274 "blocks": [{ 

275 "address": allocation["address"], 

276 "size": size, 

277 "requested_size": size, 

278 "state": "active_allocated", 

279 "frames": allocation["frames"], 

280 }], 

281 }) 

282 # Copies isolate saved snapshots from subsequent events and releases. 

283 return copy.deepcopy({ 

284 "segments": sorted(segments, key=lambda segment: (segment["device"], segment["address"])), 

285 "device_traces": self._traces, 

286 "summary": { 

287 "current_bytes": sum(self._current.values()), 

288 "peak_bytes": self._peak_bytes, 

289 "peak_gib": self._peak_bytes / 2 ** 30, 

290 "devices": { 

291 device: {"current_bytes": current_bytes, "peak_bytes": self._peaks[device]} 

292 for device, current_bytes in self._current.items() 

293 }, 

294 }, 

295 "simulation": { 

296 "memory": "logical storage bytes", 

297 "segments": "synthetic, one per allocation, immediately returned on free", 

298 "timeline": "event order, not wall-clock time", 

299 "streams": "synchronous, stream 0", 

300 "workspace": "not simulated", 

301 "fragmentation": "not simulated", 

302 }, 

303 }) 

304 

305 

306def write_memory_snapshot(snapshot: dict[str, Any], output_path: str) -> str: 

307 """Atomically write a native-compatible pickle snapshot. 

308 

309 Args: 

310 snapshot: LogicalMemoryTracker snapshot, optionally with run metadata. 

311 output_path: Destination pickle path. 

312 

313 Returns: 

314 Absolute destination path. 

315 """ 

316 destination = Path(output_path).expanduser().resolve() 

317 destination.parent.mkdir(parents=True, exist_ok=True) 

318 descriptor, temporary_path = tempfile.mkstemp(prefix=f".{destination.name}.", dir=str(destination.parent)) 

319 try: 

320 with os.fdopen(descriptor, "wb") as snapshot_file: 

321 # The browser viewer supports a subset of pickle, with protocol 4 

322 # also accepted by older deployed MemoryViz versions. 

323 pickle.dump(snapshot, snapshot_file, protocol=4) 

324 os.replace(temporary_path, destination) 

325 except Exception: 

326 if os.path.exists(temporary_path): 

327 os.unlink(temporary_path) 

328 raise 

329 return str(destination) 

330 

331 

332__all__ = ["LogicalMemoryTracker", "write_memory_snapshot"]