Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / distributed / process_data.py: 77%

279 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"""Independent data collectives with native shared CPU tensor delivery.""" 

16 

17from __future__ import annotations 

18 

19import logging 

20import os 

21import pickle 

22import random 

23import re 

24import signal 

25import time 

26import traceback 

27import uuid 

28from concurrent.futures import Future 

29from contextlib import ExitStack 

30from datetime import timedelta 

31from multiprocessing.connection import Connection 

32from multiprocessing.process import BaseProcess 

33from multiprocessing.util import Finalize 

34from pathlib import Path 

35from tempfile import TemporaryDirectory 

36from typing import Any 

37 

38import numpy as np 

39import torch 

40import torch.distributed as dist 

41from torch.utils._import_utils import import_dill 

42 

43from hyper_parallel.data.distributed.balance_logging import logger as balance_logger 

44from hyper_parallel.data.distributed.transport import DataGroups, DataPlaneTransport 

45 

46_SOURCE_PICKLE = import_dill() or pickle 

47_REPLY_TIMEOUT = 300 

48 

49 

50def _serialize_source(value: tuple) -> bytes: 

51 """Capture callback globals for the fresh interpreter when dill is available.""" 

52 if _SOURCE_PICKLE is not pickle: 

53 return _SOURCE_PICKLE.dumps(value, recurse=True) 

54 try: 

55 return pickle.dumps(value) 

56 except (AttributeError, pickle.PicklingError) as exc: 

57 raise TypeError("Use callbacks from an importable module when dill is unavailable. " 

58 f"Could not serialize the data source: {exc}") from exc 

59 

60 

61def _store_descriptor() -> dict[str, Any]: 

62 """Reuse the launcher's rendezvous without reading launcher-specific variables.""" 

63 # There is no public accessor for an initialized group's rendezvous store. 

64 store = dist.distributed_c10d._get_default_store() # pylint: disable=protected-access 

65 while isinstance(store, dist.PrefixStore): 

66 store = store.underlying_store 

67 if isinstance(store, dist.TCPStore): 

68 return {"kind": "tcp", "address": store.host, "port": store.port} 

69 if isinstance(store, dist.FileStore): 

70 return {"kind": "file", "path": store.path} 

71 raise ValueError("Independent data processes require a TCPStore or FileStore rendezvous.") 

72 

73 

74def _child_environment(backends: tuple[str | None, ...]) -> dict[str, str]: 

75 """Build data-process environment overrides and validate its HCCL listener range.""" 

76 env = {"OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1"} 

77 if "hccl" not in backends: 

78 return env 

79 selected = os.environ.get("HP_DATA_HCCL_SOCKET_PORT_RANGE", "50000-50031") 

80 match = re.fullmatch(r"(\d+)-(\d+)", selected) 

81 if match is None or not 1024 <= int(match[1]) <= int(match[2]) <= 65535: 

82 raise ValueError("HP_DATA_HCCL_SOCKET_PORT_RANGE must be an inclusive range within 1024-65535.") 

83 for start, end in re.findall(r"(\d+)-(\d+)", os.environ.get("HCCL_NPU_SOCKET_PORT_RANGE", "16666-16666")): 

84 if max(int(start), int(match[1])) <= min(int(end), int(match[2])): 

85 raise ValueError("HP_DATA_HCCL_SOCKET_PORT_RANGE overlaps the training HCCL listener range.") 

86 env["HCCL_NPU_SOCKET_PORT_RANGE"] = selected 

87 return env 

88 

89 

90def _child_transport(bootstrap: dict[str, Any]) -> DataPlaneTransport: 

91 """Rebuild collectives while retaining logical sample-owner rank identities.""" 

92 device = bootstrap["device"] 

93 if device is not None and device.type != "cpu": 

94 getattr(torch, device.type).set_device(device) 

95 ranks = bootstrap["ranks"] 

96 control = payload = None 

97 if len(ranks) > 1: 

98 if bootstrap["kind"] == "tcp": 

99 store = dist.TCPStore(bootstrap["address"], bootstrap["port"], is_master=False, 

100 timeout=timedelta(seconds=_REPLY_TIMEOUT)) 

101 else: 

102 store = dist.FileStore(bootstrap["path"]) 

103 store = dist.PrefixStore(bootstrap["prefix"], store) 

104 dist.init_process_group(bootstrap["backend"], store=store, rank=bootstrap["rank"], 

105 world_size=len(ranks), timeout=timedelta(seconds=_REPLY_TIMEOUT)) 

106 control = dist.group.WORLD 

107 if bootstrap["payload_backend"] is not None: 

108 payload = control if bootstrap["payload_backend"] == bootstrap["backend"] else dist.new_group( 

109 backend=bootstrap["payload_backend"], timeout=timedelta(seconds=_REPLY_TIMEOUT), 

110 ) 

111 groups = DataGroups(ranks, control, payload, None, bootstrap["planner_rank"], len(ranks) > 1) 

112 return DataPlaneTransport(groups, ranks[bootstrap["rank"]], device, 

113 planner_process_rank=ranks.index(bootstrap["planner_rank"])) 

114 

115 

116def _worker_main(source_path: Path, bootstrap: dict[str, Any], connection: Connection) -> None: 

117 """Initialize the spawned data rank and serve requests on its parent connection.""" 

118 source = None 

119 try: 

120 os.setsid() 

121 os.environ.update(bootstrap["environment"]) 

122 torch.set_num_threads(1) 

123 with source_path.open("rb") as handle: 

124 source, rng_state = _SOURCE_PICKLE.load(handle) 

125 balance_logger.setLevel(logging.INFO if bootstrap["balance_logging"] else logging.WARNING) 

126 random.setstate(rng_state[0]) 

127 np.random.set_state(rng_state[1]) 

128 torch.random.set_rng_state(rng_state[2]) 

129 source.bind_transport(_child_transport(bootstrap)) 

130 connection.send(("READY", os.getpid())) 

131 while True: 

132 command, value = connection.recv() 

133 if command == "CLOSE": 

134 connection.send(("CLOSED", None)) 

135 break 

136 if command == "NEXT": 

137 try: 

138 batch = next(source) 

139 except StopIteration: 

140 connection.send(("EOF", None)) 

141 else: 

142 connection.send(("BATCH", batch)) 

143 elif command == "EPOCH": 

144 source.set_epoch(value) 

145 connection.send(("EPOCH", None)) 

146 elif command == "RESET": 

147 source.reset_iteration() 

148 connection.send(("RESET", None)) 

149 else: 

150 raise ValueError(f"Unknown data process command: {command}.") 

151 except BaseException: 

152 try: 

153 connection.send(("ERROR", traceback.format_exc())) 

154 except (BrokenPipeError, EOFError, OSError): 

155 pass 

156 raise 

157 finally: 

158 try: 

159 if source is not None: 

160 source.close() 

161 finally: 

162 connection.close() 

163 if dist.is_initialized(): 

164 dist.destroy_process_group() 

165 

166 

167def _reap_process(process: BaseProcess) -> None: 

168 """Stop the data process and any DataLoader workers still in its session.""" 

169 if process.pid is None: 

170 return 

171 for sig, stop, timeout in ((signal.SIGTERM, process.terminate, 10), (signal.SIGKILL, process.kill, None)): 

172 try: 

173 os.killpg(process.pid, sig) 

174 except ProcessLookupError: 

175 # Spawn may fail or time out before the target creates its session. 

176 if not process.is_alive(): 

177 return 

178 stop() 

179 process.join(timeout) 

180 

181 

182class ProcessDataWorker: 

183 """Keep one CPU result in flight on a private distributed producer.""" 

184 

185 def __init__(self, source: Any, transport: DataPlaneTransport) -> None: 

186 """Serialize an unstarted source and capture its data-group rendezvous.""" 

187 self._resources = ExitStack() 

188 # At interpreter shutdown multiprocessing joins non-daemonic children after running finalizers. 

189 self._finalize = Finalize(self, self._resources.close, exitpriority=10) 

190 directory = self._resources.enter_context(TemporaryDirectory(prefix="hp-data-process-")) 

191 self._process = None 

192 self._connection = None 

193 self._pending = False 

194 self._deadline = None 

195 self._closed = False 

196 self._failed = False 

197 self._source_path = Path(directory) / "source.pkl" 

198 try: 

199 bootstrap = {"ranks": transport.ranks, "planner_rank": transport.planner_rank, 

200 "rank": transport.ranks.index(source.global_rank), 

201 "backend": transport.communication_backend, "payload_backend": transport.payload_backend, 

202 "device": transport.communication_device, 

203 "balance_logging": balance_logger.isEnabledFor(logging.INFO)} 

204 rng = (random.getstate(), np.random.get_state(), torch.random.get_rng_state()) 

205 error = None 

206 try: 

207 bootstrap["environment"] = _child_environment((bootstrap["backend"], bootstrap["payload_backend"])) 

208 # Keep large datasets out of spawn's synchronous startup pipe. 

209 self._source_path.write_bytes(_serialize_source((source, rng))) 

210 except Exception as exc: # pylint: disable=broad-exception-caught 

211 # User-defined pickle hooks may raise any exception. All ranks must still enter the gather. 

212 error = f"{type(exc).__name__}: {exc}" 

213 statuses = transport.all_gather_object((uuid.uuid4().hex, error)) 

214 errors = [message for _, message in statuses if message is not None] 

215 if errors: 

216 raise ValueError("Data processes require a valid environment and serializable, unstarted CPU sources " 

217 "and callbacks: " 

218 + "; ".join(errors)) 

219 if len(transport.ranks) > 1: 

220 bootstrap.update(_store_descriptor(), prefix="hp-data-process-" + statuses[0][0]) 

221 self._bootstrap = bootstrap 

222 except BaseException: 

223 self.close() 

224 raise 

225 

226 def _start(self) -> None: 

227 """Spawn the producer once and wait until it has bound its data transport.""" 

228 if self._closed or self._failed: 

229 raise RuntimeError("Data process is closed or failed.") 

230 if self._process is not None: 

231 return 

232 context = torch.multiprocessing.get_context("spawn") 

233 parent, child = context.Pipe() 

234 self._connection = self._resources.enter_context(parent) 

235 try: 

236 with child: 

237 self._process = context.Process( 

238 target=_worker_main, args=(self._source_path, self._bootstrap, child), daemon=False, 

239 ) 

240 self._resources.callback(self._process.close) 

241 self._resources.callback(_reap_process, self._process) 

242 self._process.start() 

243 status, _ = self._receive() 

244 if status != "READY": 

245 raise RuntimeError(f"Expected a ready data process, received {status}.") 

246 except BaseException: 

247 self._failed = True 

248 self.close() 

249 raise 

250 

251 def _receive(self) -> tuple[str, Any]: 

252 """Wait for one reply and propagate a timeout, child exit or remote traceback.""" 

253 deadline = time.monotonic() + _REPLY_TIMEOUT 

254 try: 

255 while not self._connection.poll(0.1): 

256 if self._process.exitcode is not None: 

257 raise RuntimeError(f"Data process exited with status {self._process.exitcode}.") 

258 if time.monotonic() >= deadline: 

259 raise TimeoutError("Data process did not reply within the data timeout.") 

260 status, value = self._connection.recv() 

261 if status == "ERROR": 

262 raise RuntimeError(f"Data process failed:\n{value}") 

263 return status, value 

264 except EOFError as exc: 

265 self._failed = True 

266 raise RuntimeError("Data process closed its connection before replying.") from exc 

267 except BaseException: 

268 self._failed = True 

269 raise 

270 

271 def prefetch(self) -> None: 

272 """Start one CPU result without waiting for preparation or communication.""" 

273 self._start() 

274 if not self._pending: 

275 self._send("NEXT") 

276 self._pending = True 

277 self._deadline = time.monotonic() + _REPLY_TIMEOUT 

278 

279 def is_ready(self, timeout: float = 0.0) -> bool: 

280 """Poll delivery so staging can continue while another CPU window is prepared. 

281 

282 Args: 

283 timeout: Maximum seconds to wait for a ready result. 

284 """ 

285 if self._connection.poll(timeout): 

286 return True 

287 if self._process.exitcode is not None: 

288 self._failed = True 

289 raise RuntimeError(f"Data process exited with status {self._process.exitcode}.") 

290 if time.monotonic() >= self._deadline: 

291 self._failed = True 

292 raise TimeoutError("Data process did not reply within the data timeout.") 

293 return False 

294 

295 def __next__(self) -> Any: 

296 """Receive one result through PyTorch's CPU shared-storage reducers.""" 

297 self.prefetch() 

298 status, result = self._receive() 

299 self._pending = False 

300 if status == "EOF": 

301 raise StopIteration 

302 if status != "BATCH": 

303 raise RuntimeError(f"Expected a CPU batch, received {status}.") 

304 return result 

305 

306 def _send(self, command: str, value: Any = None) -> None: 

307 try: 

308 self._connection.send((command, value)) 

309 except BaseException: 

310 self._failed = True 

311 raise 

312 

313 def _command(self, command: str, value: Any = None) -> None: 

314 self._start() 

315 if self._pending: 

316 self._receive() 

317 self._pending = False 

318 self._send(command, value) 

319 status, _ = self._receive() 

320 if status != command: 

321 raise RuntimeError(f"Expected {command}, received {status}.") 

322 

323 def set_epoch(self, epoch: int) -> None: 

324 """Reset the source after all prefetched results have been drained. 

325 

326 Args: 

327 epoch: Non-negative epoch to select before the next source read. 

328 """ 

329 self._command("EPOCH", epoch) 

330 

331 def reset_iteration(self) -> None: 

332 """Re-enter the external source without replacing its process-owned state.""" 

333 self._command("RESET") 

334 

335 def close(self) -> None: 

336 """Drain a published CPU result and terminate only the owned process session.""" 

337 if self._closed: 

338 return 

339 self._closed = True 

340 try: 

341 if self._process is not None and not self._failed and self._process.is_alive(): 

342 if self._pending: 

343 self._receive() 

344 self._connection.send(("CLOSE", None)) 

345 self._receive() 

346 self._process.join(timeout=30) 

347 if self._process.is_alive(): 

348 raise TimeoutError("Data process did not exit after acknowledging CLOSE.") 

349 finally: 

350 self._finalize() 

351 self._process = None 

352 

353 

354class DataRequest: 

355 """One child reply, received on demand and retained across explicit drains.""" 

356 

357 def __init__(self, worker: Any) -> None: 

358 """Start one request on the persistent data worker.""" 

359 self._worker = worker 

360 self._reply = Future() 

361 try: 

362 worker.prefetch() 

363 except BaseException as error: # pylint: disable=broad-exception-caught 

364 # A successor's startup failure belongs to that request, after any batch already prepared. 

365 self._reply.set_exception(error) 

366 

367 def is_ready(self) -> bool: 

368 """Poll without consuming the reply or waiting for the child.""" 

369 return self._reply.done() or self._worker.is_ready() 

370 

371 def result(self) -> Any: 

372 """Receive once, including EOF or a producer error.""" 

373 if not self._reply.done(): 

374 try: 

375 self._reply.set_result(next(self._worker)) 

376 except BaseException as error: # pylint: disable=broad-exception-caught 

377 # Cache the original failure so drains and delivery observe the same outcome. 

378 self._reply.set_exception(error) 

379 return self._reply.result() 

380 

381 

382def create_data_worker(source: Any, transport: DataPlaneTransport) -> Any: 

383 """Spawn data-plane members; model-only peers retain their empty local cursor. 

384 

385 Args: 

386 source: Serializable, unstarted CPU source with native or external preparation. 

387 transport: Data-plane collectives owned by this source process. 

388 """ 

389 if transport.is_member: 

390 return ProcessDataWorker(source, transport) 

391 source.bind_transport(transport) 

392 return source