Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / activation_memory / pinned_memory_pool.py: 89%

183 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"""Framework-independent pool for reusable pinned host memory.""" 

16 

17import threading 

18from collections import defaultdict 

19from dataclasses import dataclass 

20from typing import Any, Dict, List, Optional, Tuple 

21 

22import torch 

23 

24from . import _backend 

25 

26_MIN_BUCKET_BYTES = 1024 

27_IN_USE = "in_use" 

28_AVAILABLE = "available" 

29_PENDING = "pending" 

30 

31 

32@dataclass 

33class _Block: 

34 """A complete allocation owned by :class:`PinnedMemoryPool`.""" 

35 

36 buffer: Any 

37 capacity: int 

38 state: str 

39 event: Optional[Any] = None 

40 storage_key: Optional[int] = None 

41 

42 

43def _valid_positive_int(value: int, name: str) -> None: 

44 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

45 raise ValueError(f"{name} must be a positive integer, but got {value!r}.") 

46 

47 

48def _storage_key(tensor: Any) -> int: 

49 """Return a stable identity for a tensor's underlying storage. 

50 

51 The key is the storage PyObject's identity, which stays distinct for the 

52 pool's unpinned CPU buffers under logical simulation. The pool owns every 

53 underlying buffer for its whole lifetime, so the id cannot be recycled 

54 while a key is registered. 

55 """ 

56 try: 

57 return id(tensor.untyped_storage()) 

58 except (AttributeError, TypeError, ValueError) as exc: 

59 raise ValueError("release() expects a tensor with an identifiable storage.") from exc 

60 

61 

62class PinnedMemoryPool: 

63 """Thread-safe, capacity-bounded pool of pinned CPU byte buffers. 

64 

65 The pool keeps complete one-dimensional ``uint8`` allocations and returns 

66 length-limited views from :meth:`acquire`. A returned view may be cast to 

67 another dtype by the caller, but no view may be used after :meth:`release`. 

68 When no reusable block is available and a new pinned allocation would 

69 exceed ``max_host_bytes``, :meth:`acquire` raises ``RuntimeError``. 

70 

71 Args: 

72 max_host_bytes: Maximum total capacity retained by the pool. 

73 align_limit: Largest size used by the power-of-two alignment policy. 

74 

75 Raises: 

76 ValueError: If a constructor or ``acquire`` argument is invalid. 

77 RuntimeError: If an allocation would exceed ``max_host_bytes`` and no 

78 sufficient reusable block exists. 

79 """ 

80 

81 def __init__(self, max_host_bytes: int, align_limit: int = 2 * 1024**3) -> None: 

82 _valid_positive_int(max_host_bytes, "max_host_bytes") 

83 _valid_positive_int(align_limit, "align_limit") 

84 self._max_host_bytes = max_host_bytes 

85 self._align_limit = align_limit 

86 self._available: Dict[int, List[_Block]] = defaultdict(list) 

87 self._pending: Dict[int, List[_Block]] = defaultdict(list) 

88 self._blocks: Dict[int, _Block] = {} 

89 self._total_allocated = 0 

90 self._lock = threading.Lock() 

91 

92 @property 

93 def total_allocated(self) -> int: 

94 """Return total aligned pinned capacity held by this pool.""" 

95 with self._lock: 

96 return self._total_allocated 

97 

98 @property 

99 def max_host_bytes(self) -> int: 

100 """Return the pool's hard capacity limit in bytes.""" 

101 return self._max_host_bytes 

102 

103 @property 

104 def align_limit(self) -> int: 

105 """Return the largest alignment bucket size in bytes.""" 

106 return self._align_limit 

107 

108 def _aligned_size(self, size: int) -> int: 

109 if size > self._align_limit: 

110 return size 

111 minimum = max(size, _MIN_BUCKET_BYTES) 

112 power = 1 << (minimum - 1).bit_length() 

113 aligned = min(power, self._align_limit) 

114 return max(aligned, size) 

115 

116 def _reclaim_completed_locked(self, minimum_capacity: int) -> None: 

117 """Move completed pending blocks into the available buckets.""" 

118 # A transfer batch may release many blocks with one event. Retain the 

119 # event objects so each runtime event is queried only once per scan. 

120 event_results: Dict[int, Tuple[Any, bool]] = {} 

121 for capacity in list(self._pending): 

122 if capacity < minimum_capacity: 

123 continue 

124 still_pending = [] 

125 for block in self._pending[capacity]: 

126 event = block.event 

127 event_key = id(event) 

128 event_result = event_results.get(event_key) 

129 if event_result is None: 

130 completed = event.query() 

131 event_results[event_key] = (event, completed) 

132 else: 

133 completed = event_result[1] 

134 if completed: 

135 block.event = None 

136 block.state = _AVAILABLE 

137 self._available[capacity].append(block) 

138 else: 

139 still_pending.append(block) 

140 if still_pending: 

141 self._pending[capacity] = still_pending 

142 else: 

143 del self._pending[capacity] 

144 

145 def _register_view_locked(self, block: _Block, view: Any) -> Any: 

146 """Associate a checked-out view with its owning allocation.""" 

147 key = _storage_key(view) 

148 owner = self._blocks.get(key) 

149 if owner is not None and owner is not block: 

150 raise RuntimeError("Two host buffers exposed the same storage identity.") 

151 old_key = block.storage_key 

152 if old_key is not None and old_key != key and self._blocks.get(old_key) is block: 

153 del self._blocks[old_key] 

154 self._blocks[key] = block 

155 block.storage_key = key 

156 return view 

157 

158 def _checkout_locked(self, block: _Block, size: int) -> Any: 

159 """Create and register the exact view returned by :meth:`acquire`.""" 

160 view = block.buffer if size == block.capacity else block.buffer[:size] 

161 return self._register_view_locked(block, view) 

162 

163 def _find_available_locked(self, minimum_capacity: int) -> Optional[_Block]: 

164 for capacity in sorted(self._available): 

165 if capacity >= minimum_capacity and self._available[capacity]: 

166 block = self._available[capacity].pop() 

167 if not self._available[capacity]: 

168 del self._available[capacity] 

169 block.state = _IN_USE 

170 return block 

171 return None 

172 

173 def _find_pending_locked(self, minimum_capacity: int) -> Optional[_Block]: 

174 for capacity in sorted(self._pending): 

175 if capacity >= minimum_capacity and self._pending[capacity]: 

176 block = self._pending[capacity].pop(0) 

177 if not self._pending[capacity]: 

178 del self._pending[capacity] 

179 block.state = _IN_USE 

180 return block 

181 return None 

182 

183 def acquire(self, size: int) -> Any: 

184 """Acquire a pooled pinned CPU ``uint8`` view.""" 

185 _valid_positive_int(size, "size") 

186 aligned_size = self._aligned_size(size) 

187 

188 with self._lock: 

189 self._reclaim_completed_locked(aligned_size) 

190 block = self._find_available_locked(aligned_size) 

191 if block is not None: 

192 try: 

193 return self._checkout_locked(block, size) 

194 except Exception: 

195 block.state = _AVAILABLE 

196 self._available[block.capacity].append(block) 

197 raise 

198 

199 if self._total_allocated + aligned_size <= self._max_host_bytes: 

200 self._total_allocated += aligned_size 

201 reserved = True 

202 else: 

203 reserved = False 

204 block = self._find_pending_locked(aligned_size) 

205 if block is None: 

206 raise RuntimeError( 

207 "PinnedMemoryPool capacity exceeded: " 

208 f"requested_bytes={size}, aligned_bytes={aligned_size}, " 

209 f"pooled_bytes={self._total_allocated}, " 

210 f"max_host_bytes={self._max_host_bytes}." 

211 ) 

212 

213 if reserved: 

214 try: 

215 buffer = _backend.alloc_tensor_buffer( 

216 aligned_size, 

217 torch.uint8, 

218 device="cpu", 

219 pin_memory=True, 

220 ) 

221 except Exception: 

222 with self._lock: 

223 self._total_allocated -= aligned_size 

224 raise 

225 block = _Block(buffer, aligned_size, _IN_USE) 

226 try: 

227 with self._lock: 

228 view = self._checkout_locked(block, size) 

229 except Exception: 

230 with self._lock: 

231 self._total_allocated -= aligned_size 

232 raise 

233 return view 

234 

235 event = block.event 

236 try: 

237 event.synchronize() 

238 except Exception: 

239 with self._lock: 

240 block.state = _PENDING 

241 block.event = event 

242 self._pending[block.capacity].insert(0, block) 

243 raise 

244 block.event = None 

245 try: 

246 with self._lock: 

247 return self._checkout_locked(block, size) 

248 except Exception: 

249 with self._lock: 

250 block.state = _AVAILABLE 

251 self._available[block.capacity].append(block) 

252 raise 

253 

254 def reset_after_device_restart(self) -> None: 

255 """Recycle pending buffers after the caller has quiesced all device transfers. 

256 

257 Old device events must not be queried after recovery. Checked-out buffers 

258 remain owned by their callers; only already-released blocks are recycled. 

259 """ 

260 with self._lock: 

261 for blocks in self._pending.values(): 

262 for block in blocks: 

263 block.event = None 

264 block.state = _AVAILABLE 

265 self._available[block.capacity].append(block) 

266 self._pending.clear() 

267 

268 def release(self, tensor: Any, event: Optional[Any] = None) -> None: 

269 """Return an acquired view to the pool, optionally after an async event.""" 

270 key = _storage_key(tensor) 

271 with self._lock: 

272 block = self._blocks.get(key) 

273 if block is None: 

274 raise ValueError("The tensor does not belong to this PinnedMemoryPool.") 

275 if block.state != _IN_USE: 

276 raise ValueError("The tensor has already been released to this PinnedMemoryPool.") 

277 if event is None: 

278 block.state = _AVAILABLE 

279 self._available[block.capacity].append(block) 

280 else: 

281 block.state = _PENDING 

282 block.event = event 

283 self._pending[block.capacity].append(block)