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

569 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"""CPU control, direct tensor broadcast, and configurable payload data planes.""" 

16# This distributed-data package is intentionally PyTorch-only. 

17 

18from __future__ import annotations 

19 

20import math 

21import pickle 

22import struct 

23from contextlib import contextmanager 

24from dataclasses import dataclass, field as dataclass_field 

25from typing import Any, Iterator, Mapping, Sequence 

26 

27import torch 

28import torch.distributed as dist 

29 

30from hyper_parallel.data.distributed.model_batch import ModelBatchLayout 

31from hyper_parallel.data.distributed.schema import SampleKey 

32from hyper_parallel.data.distributed.topology import DataTopology 

33 

34 

35@dataclass 

36class DataGroups: 

37 """Control, payload, and model-consumer groups for distributed data.""" 

38 

39 data_plane_ranks: tuple[int, ...] 

40 control_group: Any 

41 payload_group: Any 

42 model_parallel_group: Any 

43 planner_rank: int 

44 distributed: bool 

45 model_parallel_tensor_group: Any = None 

46 _owned: list[Any] = dataclass_field(default_factory=list, init=False, repr=False, compare=False) 

47 

48 def new_group(self, ranks: tuple[int, ...], backend: str | None) -> Any: 

49 """Create a subgroup and register member handles for rollback and explicit close. 

50 

51 Args: 

52 ranks: Global ranks in collective order. 

53 backend: Backend for the new subgroup. 

54 """ 

55 group = dist.new_group(ranks=list(ranks), backend=backend) 

56 if group != dist.GroupMember.NON_GROUP_MEMBER: 

57 self._owned.append(group) 

58 return group 

59 

60 @contextmanager 

61 def close_on_error(self) -> Iterator[None]: 

62 """Release acquired groups if construction fails before ownership transfers to the loader.""" 

63 try: 

64 yield 

65 except BaseException: 

66 self.close() 

67 raise 

68 

69 def close(self) -> None: 

70 """Destroy owned handles in creation order and drop all their transport aliases.""" 

71 while self._owned: 

72 group = self._owned[0] 

73 if dist.is_initialized(): 

74 dist.destroy_process_group(group) 

75 self._owned.pop(0) 

76 for name in ("control_group", "payload_group", "model_parallel_group", "model_parallel_tensor_group"): 

77 if getattr(self, name) is group: 

78 setattr(self, name, None) 

79 

80 

81@dataclass(frozen=True) 

82class PreparedPayloadExchange: 

83 """Serialized host payload and collective tensor for one payload A2A.""" 

84 

85 input_splits: tuple[int, ...] 

86 send_storage: bytearray 

87 send_tensor: torch.Tensor 

88 local_segment: bytes 

89 

90 

91@dataclass 

92class ControlGatherWork: 

93 """Retain control buffers until the consumer waits and decodes on the launch stream.""" 

94 

95 encoded: torch.Tensor | None = None 

96 sizes: tuple[int, ...] = () 

97 gathered: torch.Tensor | None = None 

98 data_work: Any = None 

99 completed_values: tuple[Any, ...] | None = None 

100 

101 def wait(self) -> tuple[Any, ...]: 

102 """Wait for gathered bytes and decode them with the launch device and stream bound.""" 

103 if self.completed_values is None: 

104 if self.data_work is not None: 

105 self.data_work.wait() 

106 rows = self.gathered.cpu().view(len(self.sizes), -1).numpy() 

107 self.completed_values = tuple(pickle.loads(row[:size].tobytes()) 

108 for row, size in zip(rows, self.sizes)) 

109 return self.completed_values 

110 

111 

112@dataclass 

113class PayloadExchangeWork: 

114 """Asynchronous payload exchange owned by the launching device stream. 

115 

116 Waiting and decoding must use the launch stream and its rank-local device. 

117 Retaining the prepared send tensor keeps its backing storage valid until 

118 the accelerator has consumed it. 

119 """ 

120 

121 prepared: PreparedPayloadExchange 

122 output_splits: tuple[int, ...] 

123 received_tensor: torch.Tensor | None 

124 data_work: Any = None 

125 completed_payloads: dict[SampleKey, Any] | None = None 

126 

127 def wait(self) -> dict[SampleKey, Any]: 

128 """Wait and decode on the launch stream with its rank-local device bound.""" 

129 if self.completed_payloads is not None: 

130 return self.completed_payloads 

131 if self.data_work is not None: 

132 self.data_work.wait() 

133 if self.received_tensor is None: 

134 received_bytes = b"" 

135 else: 

136 received_bytes = self.received_tensor.cpu().numpy().tobytes() 

137 self.completed_payloads = _decode_received_payloads(received_bytes, self.output_splits) 

138 return self.completed_payloads 

139 

140 

141def _is_accelerator_backend(backend: str) -> bool: 

142 return "hccl" in backend.lower() or "nccl" in backend.lower() 

143 

144 

145def _control_backend(group: Any, backend: str | None = None) -> str: 

146 if backend is not None: 

147 return backend.lower() 

148 try: 

149 return str(dist.get_backend(group)).lower() 

150 except (RuntimeError, ValueError): 

151 # Lightweight unit-test groups and single-process fakes represent Gloo 

152 # groups with opaque sentinels rather than registered ProcessGroups. 

153 return "gloo" 

154 

155 

156def _require_control_device(device: Any, backend: str) -> torch.device: 

157 if device is None: 

158 raise ValueError(f"{backend} control collectives require an accelerator communication_device.") 

159 resolved = torch.device(device) 

160 expected = "npu" if "hccl" in backend else "cuda" 

161 if resolved.type != expected: 

162 raise ValueError(f"{backend} control collectives require a {expected} device, got {resolved}.") 

163 return resolved 

164 

165 

166def _encode_control(value: Any, device: Any) -> tuple[torch.Tensor, int]: 

167 encoded = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL) 

168 resolved = torch.device(device) 

169 payload = torch.frombuffer(bytearray(encoded), dtype=torch.uint8).to(resolved) 

170 return payload, len(encoded) 

171 

172 

173def _decode_control(payload: torch.Tensor, size: int) -> Any: 

174 encoded = payload[:size].cpu().numpy().tobytes() 

175 return pickle.loads(encoded) 

176 

177 

178def all_gather_control_object( 

179 value: Any, 

180 *, 

181 group: Any = None, 

182 device: Any = None, 

183 backend: str | None = None, 

184) -> tuple[Any, ...]: 

185 """Gather a small control object with Gloo or an accelerator backend. 

186 

187 Args: 

188 value: Rank-local serializable control value. 

189 group: Process group whose ranks participate in the gather. 

190 device: Rank-local accelerator used by HCCL/NCCL. 

191 backend: Explicit backend for startup calls that use WORLD. 

192 

193 Returns: 

194 Gathered values in process-group rank order. 

195 """ 

196 return _begin_all_gather_control_object(value, group=group, device=device, backend=backend).wait() 

197 

198 

199def _begin_all_gather_control_object( 

200 value: Any, 

201 *, 

202 group: Any = None, 

203 device: Any = None, 

204 backend: str | None = None, 

205) -> ControlGatherWork: 

206 """Exchange lengths on the caller, then launch accelerator bytes without decoding.""" 

207 effective_backend = _control_backend(group, backend) 

208 if not _is_accelerator_backend(effective_backend): 

209 gathered = [None] * dist.get_world_size(group) 

210 dist.all_gather_object(gathered, value, group=group) 

211 return ControlGatherWork(completed_values=tuple(gathered)) 

212 resolved = _require_control_device(device, effective_backend) 

213 encoded, encoded_size = _encode_control(value, resolved) 

214 local_size = torch.tensor([encoded_size], dtype=torch.int64, device=resolved) 

215 sizes = torch.empty(dist.get_world_size(group), dtype=torch.int64, device=resolved) 

216 dist.all_gather_into_tensor(sizes, local_size, group=group) 

217 host_sizes = tuple(sizes.cpu().tolist()) 

218 max_size = max(host_sizes) 

219 if encoded.numel() < max_size: 

220 padded = torch.zeros((max_size,), dtype=torch.uint8, device=resolved) 

221 padded[:encoded.numel()] = encoded 

222 encoded = padded 

223 gathered = torch.empty(len(host_sizes) * max_size, dtype=torch.uint8, device=resolved) 

224 work = dist.all_gather_into_tensor(gathered, encoded, group=group, async_op=True) 

225 return ControlGatherWork(encoded=encoded, sizes=host_sizes, gathered=gathered, data_work=work) 

226 

227 

228def broadcast_control_object( 

229 value: Any, 

230 *, 

231 src: int, 

232 group: Any = None, 

233 device: Any = None, 

234) -> Any: 

235 """Broadcast a small control object with Gloo or an accelerator backend. 

236 

237 Args: 

238 value: Source value or a placeholder on receivers. 

239 src: Global source rank. 

240 group: Process group whose ranks participate in the broadcast. 

241 device: Rank-local accelerator used by HCCL/NCCL. 

242 

243 Returns: 

244 The source value on every participating rank. 

245 """ 

246 effective_backend = _control_backend(group) 

247 if not _is_accelerator_backend(effective_backend): 

248 payload = [value] 

249 dist.broadcast_object_list(payload, src=src, group=group) 

250 return payload[0] 

251 resolved = _require_control_device(device, effective_backend) 

252 rank = dist.get_rank() 

253 encoded, encoded_size = _encode_control(value, resolved) if rank == src else ( 

254 torch.zeros((1,), dtype=torch.uint8, device=resolved), 0 

255 ) 

256 size = torch.tensor([encoded_size], dtype=torch.int64, device=resolved) 

257 dist.broadcast(size, src=src, group=group) 

258 target_size = int(size.item()) 

259 if encoded.numel() < max(1, target_size): 

260 encoded = torch.zeros((max(1, target_size),), dtype=torch.uint8, device=resolved) 

261 dist.broadcast(encoded, src=src, group=group) 

262 return _decode_control(encoded, target_size) 

263 

264 

265def create_data_groups( 

266 topology: DataTopology, 

267 dataset_reader_ranks: tuple[int, ...], 

268 planner_rank: int, 

269 *, 

270 cpu_backend: str, 

271 payload_backend: str | None, 

272 communication_device: Any, 

273 enable_payload_exchange: bool, 

274 model_device: Any = None, 

275) -> DataGroups: 

276 """Create control, optional payload, and model groups deterministically. 

277 

278 Args: 

279 topology: Constructor and model-consumer topology. 

280 dataset_reader_ranks: Global ranks that materialize raw samples. 

281 planner_rank: Global rank that creates loading plans. 

282 cpu_backend: Backend used for control and model-parallel batch broadcast. 

283 payload_backend: Optional backend for online payload A2A. When omitted 

284 with an accelerator communication device, the WORLD backend is used. 

285 communication_device: Optional rank-local device for payload tensors. 

286 enable_payload_exchange: Whether the online path needs a payload group. 

287 model_device: Training device for direct model-peer tensor broadcast, 

288 independent of the raw payload backend. 

289 

290 Returns: 

291 Groups relevant to the current rank. 

292 """ 

293 data_plane_ranks = tuple(sorted(set(dataset_reader_ranks) | set(topology.constructor_ranks))) 

294 if planner_rank not in data_plane_ranks: 

295 raise ValueError(f"planner_rank {planner_rank} must belong to data-plane ranks {data_plane_ranks}.") 

296 distributed = dist.is_available() and dist.is_initialized() 

297 if not distributed: 

298 return _single_rank_data_groups(topology, data_plane_ranks, planner_rank) 

299 _validate_distributed_topology(topology) 

300 _validate_group_backends(cpu_backend, payload_backend, enable_payload_exchange) 

301 effective_payload_backend, reuse_control_group = _resolve_payload_backend( 

302 data_plane_ranks=data_plane_ranks, 

303 cpu_backend=cpu_backend, 

304 payload_backend=payload_backend, 

305 communication_device=communication_device, 

306 enable_payload_exchange=enable_payload_exchange, 

307 ) 

308 groups = DataGroups(data_plane_ranks, None, None, None, planner_rank, True) 

309 with groups.close_on_error(): 

310 groups.control_group, groups.payload_group = _create_data_plane_process_groups( 

311 groups=groups, 

312 topology=topology, 

313 data_plane_ranks=data_plane_ranks, 

314 cpu_backend=cpu_backend, 

315 payload_backend=effective_payload_backend, 

316 reuse_control_group=reuse_control_group, 

317 enable_payload_exchange=enable_payload_exchange, 

318 ) 

319 tensor_backend = _resolve_model_tensor_backend(communication_device, payload_backend) 

320 model_device = torch.device(model_device) if model_device is not None else None 

321 if model_device is not None and model_device.type in ("cuda", "npu"): 

322 tensor_backend = "nccl" if model_device.type == "cuda" else "hccl" 

323 groups.model_parallel_group, groups.model_parallel_tensor_group = _create_model_parallel_process_groups( 

324 groups, topology, cpu_backend, tensor_backend, 

325 ) 

326 return groups 

327 

328 

329def _single_rank_data_groups( 

330 topology: DataTopology, 

331 data_plane_ranks: tuple[int, ...], 

332 planner_rank: int, 

333) -> DataGroups: 

334 if len(topology.rank_list) != 1: 

335 raise ValueError("torch.distributed must be initialized for a mesh containing more than one rank.") 

336 return DataGroups(data_plane_ranks, None, None, None, planner_rank, False, None) 

337 

338 

339def _validate_distributed_topology(topology: DataTopology) -> None: 

340 world_ranks = tuple(range(dist.get_world_size())) 

341 if set(topology.rank_list) != set(world_ranks): 

342 raise ValueError( 

343 "The distributed data root mesh must contain every torch.distributed world rank so all ranks create " 

344 "service groups in the same order." 

345 ) 

346 if dist.get_rank() != topology.global_rank: 

347 raise ValueError("Topology global_rank does not match torch.distributed rank.") 

348 

349 

350def _validate_group_backends( 

351 cpu_backend: str, 

352 payload_backend: str | None, 

353 enable_payload_exchange: bool, 

354) -> None: 

355 """Validate control and payload backend options before creating process groups.""" 

356 if not isinstance(cpu_backend, str) or not cpu_backend: 

357 raise ValueError("cpu_backend must be a non-empty backend name.") 

358 if cpu_backend.lower() not in ("gloo", "hccl"): 

359 raise ValueError("cpu_backend must be 'gloo' or 'hccl'.") 

360 if payload_backend is not None and (not isinstance(payload_backend, str) or not payload_backend): 

361 raise ValueError("payload_backend must be a non-empty backend name or None.") 

362 if not isinstance(enable_payload_exchange, bool): 

363 raise ValueError("enable_payload_exchange must be boolean.") 

364 

365 

366def _resolve_payload_backend( 

367 *, 

368 data_plane_ranks: tuple[int, ...], 

369 cpu_backend: str, 

370 payload_backend: str | None, 

371 communication_device: Any, 

372 enable_payload_exchange: bool, 

373) -> tuple[str | None, bool]: 

374 """Choose a compatible payload backend and whether it can reuse the control group.""" 

375 if not enable_payload_exchange or len(data_plane_ranks) == 1: 

376 return None, False 

377 device = torch.device(communication_device) if communication_device is not None else None 

378 effective_backend = payload_backend or _default_payload_backend(device, cpu_backend) 

379 normalized_backend = effective_backend.lower() 

380 _validate_payload_device(normalized_backend, effective_backend, device) 

381 reuse_control_group = normalized_backend == cpu_backend.lower() and (device is None or device.type == "cpu") 

382 return effective_backend, reuse_control_group 

383 

384 

385def _default_payload_backend(device: torch.device | None, cpu_backend: str) -> str: 

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

387 return str(dist.get_backend()) 

388 return cpu_backend 

389 

390 

391def _validate_payload_device( 

392 normalized_backend: str, 

393 effective_backend: str, 

394 device: torch.device | None, 

395) -> None: 

396 """Require the communication device type expected by the payload backend.""" 

397 accelerator_backend = "hccl" in normalized_backend or "nccl" in normalized_backend 

398 if accelerator_backend and (device is None or device.type == "cpu"): 

399 raise ValueError( 

400 f"Payload backend {effective_backend!r} requires a rank-local accelerator communication_device." 

401 ) 

402 expected_device_type = None 

403 if "nccl" in normalized_backend: 

404 expected_device_type = "cuda" 

405 elif "hccl" in normalized_backend: 

406 expected_device_type = "npu" 

407 if expected_device_type is not None and device is not None and device.type != expected_device_type: 

408 raise ValueError( 

409 f"Payload backend {effective_backend!r} requires a {expected_device_type} device, but got {device}." 

410 ) 

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

412 raise ValueError(f"Payload backend {effective_backend!r} cannot exchange tensors on device {device}.") 

413 

414 

415def _create_data_plane_process_groups( 

416 *, 

417 groups: DataGroups, 

418 topology: DataTopology, 

419 data_plane_ranks: tuple[int, ...], 

420 cpu_backend: str, 

421 payload_backend: str | None, 

422 reuse_control_group: bool, 

423 enable_payload_exchange: bool, 

424) -> tuple[Any, Any]: 

425 """Create control and payload groups in common rank order, returning owned handles.""" 

426 if len(data_plane_ranks) == 1: 

427 return None, None 

428 created_control_group = groups.new_group(data_plane_ranks, cpu_backend) 

429 is_member = topology.global_rank in data_plane_ranks 

430 control_group = created_control_group if is_member else None 

431 if not enable_payload_exchange: 

432 return control_group, None 

433 if reuse_control_group: 

434 return control_group, control_group 

435 created_payload_group = groups.new_group(data_plane_ranks, payload_backend) 

436 return control_group, created_payload_group if is_member else None 

437 

438 

439def _resolve_model_tensor_backend(communication_device: Any, payload_backend: str | None) -> str | None: 

440 """Select an accelerator backend for tensor model-group broadcasts when available.""" 

441 if communication_device is None: 

442 return None 

443 device = torch.device(communication_device) 

444 if device.type == "cpu": 

445 return None 

446 candidate = payload_backend or str(dist.get_backend()) 

447 normalized = candidate.lower() 

448 if "hccl" not in normalized and "nccl" not in normalized: 

449 return None 

450 return candidate 

451 

452 

453def _create_model_parallel_process_groups( 

454 groups: DataGroups, 

455 topology: DataTopology, 

456 cpu_backend: str, 

457 tensor_backend: str | None, 

458) -> tuple[Any, Any]: 

459 """Create model-parallel control and tensor groups in common rank order.""" 

460 model_parallel_group = None 

461 model_parallel_tensor_group = None 

462 for rank_group in topology.model_parallel_rank_groups: 

463 if len(rank_group) == 1: 

464 continue 

465 is_member = topology.global_rank in rank_group 

466 created_group = groups.new_group(rank_group, cpu_backend) 

467 if is_member: 

468 model_parallel_group = created_group 

469 if tensor_backend is not None: 

470 created_tensor_group = groups.new_group(rank_group, tensor_backend) 

471 if is_member: 

472 model_parallel_tensor_group = created_tensor_group 

473 return model_parallel_group, model_parallel_tensor_group 

474 

475 

476def _encode_payload_segment(items: Sequence[tuple[SampleKey, Any]]) -> bytes: 

477 """Serialize an internal route with metadata and a contiguous binary buffer. 

478 

479 Tensor and byte leaves are kept out of the metadata pickle. The metadata 

480 contains only the nested sample structure and descriptors pointing into a 

481 contiguous byte region. A legacy pickle route remains available for 

482 payloads without binary leaves so old scalar-only unit/test routes retain 

483 their wire compatibility. 

484 """ 

485 if not items: 

486 return b"" 

487 if not any(_payload_contains_binary(payload) for _, payload in items): 

488 return pickle.dumps(tuple(items), protocol=pickle.HIGHEST_PROTOCOL) 

489 encoded_items = [] 

490 binary_chunks: list[bytes] = [] 

491 binary_offset = 0 

492 for key, payload in items: 

493 schema, binary_offset = _encode_payload_value(payload, binary_chunks, binary_offset) 

494 encoded_items.append((key, schema)) 

495 metadata = pickle.dumps(tuple(encoded_items), protocol=pickle.HIGHEST_PROTOCOL) 

496 binary = b"".join(binary_chunks) 

497 return _PAYLOAD_HEADER.pack(_PAYLOAD_MAGIC, len(metadata), len(binary)) + metadata + binary 

498 

499 

500def _decode_payload_segment(frame: bytes) -> tuple[tuple[SampleKey, Any], ...]: 

501 """Deserialize a route produced by peers running the same codec.""" 

502 if not frame: 

503 return () 

504 if not frame.startswith(_PAYLOAD_MAGIC): 

505 # Preserve compatibility with routes produced before the tensor-buffer 

506 # codec was introduced. This path is used only for scalar-only routes. 

507 return pickle.loads(frame) 

508 if len(frame) < _PAYLOAD_HEADER.size: 

509 raise ValueError("Payload frame is truncated before its header.") 

510 _, metadata_size, binary_size = _PAYLOAD_HEADER.unpack_from(frame) 

511 payload_offset = _PAYLOAD_HEADER.size 

512 payload_size = metadata_size + binary_size 

513 if payload_offset + payload_size != len(frame): 

514 raise ValueError( 

515 "Payload frame size does not match its metadata and binary descriptors." 

516 ) 

517 metadata_end = payload_offset + metadata_size 

518 encoded_items = pickle.loads(frame[payload_offset:metadata_end]) 

519 binary = bytearray(frame[metadata_end:]) 

520 decoded_items = [] 

521 for key, schema in encoded_items: 

522 decoded_items.append((key, _decode_payload_value(schema, binary))) 

523 return tuple(decoded_items) 

524 

525 

526_PAYLOAD_MAGIC = b"HPB1" 

527_PAYLOAD_HEADER = struct.Struct("!4sQQ") 

528_TENSOR_TAG = "__hp_tensor__" 

529_BYTES_TAG = "__hp_bytes__" 

530_BYTEARRAY_TAG = "__hp_bytearray__" 

531 

532 

533def _payload_contains_binary(value: Any) -> bool: 

534 """Return whether a payload contains a tensor or raw byte leaf.""" 

535 if torch.is_tensor(value) or isinstance(value, (bytes, bytearray)): 

536 return True 

537 if isinstance(value, Mapping): 

538 return any(_payload_contains_binary(child) for child in value.values()) 

539 if isinstance(value, (tuple, list)): 

540 return any(_payload_contains_binary(child) for child in value) 

541 return False 

542 

543 

544def _encode_payload_value( 

545 value: Any, 

546 binary_chunks: list[bytes], 

547 binary_offset: int, 

548) -> tuple[Any, int]: 

549 """Replace binary leaves with descriptors and append their bytes.""" 

550 if torch.is_tensor(value): 

551 tensor = value.detach() 

552 if tensor.device.type != "cpu": 

553 tensor = tensor.cpu() 

554 tensor = tensor.contiguous() 

555 # Flatten first: PyTorch does not permit a scalar tensor to change 

556 # dtype via ``view`` directly because it has no dimension to resize. 

557 raw = tensor.reshape(-1).view(torch.uint8).numpy().tobytes() 

558 descriptor = ( 

559 _TENSOR_TAG, 

560 str(tensor.dtype), 

561 tuple(tensor.shape), 

562 binary_offset, 

563 len(raw), 

564 ) 

565 binary_chunks.append(raw) 

566 return descriptor, binary_offset + len(raw) 

567 if isinstance(value, (bytes, bytearray)): 

568 raw = bytes(value) 

569 tag = _BYTES_TAG if isinstance(value, bytes) else _BYTEARRAY_TAG 

570 descriptor = (tag, binary_offset, len(raw)) 

571 binary_chunks.append(raw) 

572 return descriptor, binary_offset + len(raw) 

573 if isinstance(value, Mapping): 

574 encoded_items = [] 

575 for key, child in value.items(): 

576 encoded_child, binary_offset = _encode_payload_value(child, binary_chunks, binary_offset) 

577 encoded_items.append((key, encoded_child)) 

578 return ("__hp_mapping__", tuple(encoded_items)), binary_offset 

579 if isinstance(value, (tuple, list)): 

580 encoded_items = [] 

581 for child in value: 

582 encoded_child, binary_offset = _encode_payload_value(child, binary_chunks, binary_offset) 

583 encoded_items.append(encoded_child) 

584 tag = "__hp_tuple__" if isinstance(value, tuple) else "__hp_list__" 

585 return (tag, tuple(encoded_items)), binary_offset 

586 if value is None or isinstance(value, (bool, int, float, str)): 

587 return ("__hp_value__", value), binary_offset 

588 raise TypeError( 

589 "Payload tensor-buffer codec does not support a non-metadata value of " 

590 f"type {type(value).__qualname__}." 

591 ) 

592 

593 

594def _decode_payload_value(schema: Any, binary: bytearray) -> Any: 

595 """Reconstruct one sample from metadata descriptors and binary storage.""" 

596 if not isinstance(schema, tuple) or not schema: 

597 raise ValueError("Payload metadata contains an invalid schema node.") 

598 tag = schema[0] 

599 if tag == _TENSOR_TAG: 

600 return _decode_tensor_payload(schema, binary) 

601 if tag in (_BYTES_TAG, _BYTEARRAY_TAG): 

602 return _decode_bytes_payload(schema, binary) 

603 if tag == "__hp_mapping__": 

604 return { 

605 key: _decode_payload_value(child, binary) 

606 for key, child in schema[1] 

607 } 

608 if tag == "__hp_tuple__": 

609 return tuple(_decode_payload_value(child, binary) for child in schema[1]) 

610 if tag == "__hp_list__": 

611 return [_decode_payload_value(child, binary) for child in schema[1]] 

612 if tag == "__hp_value__": 

613 return schema[1] 

614 raise ValueError(f"Unknown payload metadata schema tag: {tag!r}.") 

615 

616 

617def _decode_tensor_payload(schema: tuple, binary: bytearray) -> torch.Tensor: 

618 """Reconstruct a tensor view after validating its descriptor.""" 

619 if len(schema) != 5: 

620 raise ValueError("Tensor payload descriptor has an invalid field count.") 

621 _, dtype_name, shape, offset, size = schema 

622 dtype = _payload_dtype(dtype_name) 

623 shape = tuple(shape) 

624 if any(not isinstance(dim, int) or dim < 0 for dim in shape): 

625 raise ValueError(f"Tensor payload descriptor has an invalid shape: {shape!r}.") 

626 if not isinstance(offset, int) or not isinstance(size, int) or offset < 0 or size < 0: 

627 raise ValueError("Tensor payload descriptor has an invalid byte range.") 

628 end = offset + size 

629 if end > len(binary): 

630 raise ValueError("Tensor payload descriptor points outside the binary buffer.") 

631 element_count = 1 

632 for dim in shape: 

633 element_count *= dim 

634 expected_size = element_count * torch.empty((), dtype=dtype).element_size() 

635 if expected_size != size: 

636 raise ValueError( 

637 f"Tensor payload byte size mismatch: expected {expected_size}, got {size}." 

638 ) 

639 if size == 0: 

640 return torch.empty(shape, dtype=dtype) 

641 tensor = torch.frombuffer(memoryview(binary)[offset:end], dtype=dtype, count=element_count) 

642 return tensor.reshape(shape) 

643 

644 

645def _decode_bytes_payload(schema: tuple, binary: bytearray) -> bytes | bytearray: 

646 """Reconstruct a byte sequence after validating its descriptor.""" 

647 if len(schema) != 3: 

648 raise ValueError("Byte payload descriptor has an invalid field count.") 

649 tag, offset, size = schema 

650 if not isinstance(offset, int) or not isinstance(size, int) or offset < 0 or size < 0: 

651 raise ValueError("Byte payload descriptor has an invalid byte range.") 

652 end = offset + size 

653 if end > len(binary): 

654 raise ValueError("Byte payload descriptor points outside the binary buffer.") 

655 raw = bytes(binary[offset:end]) 

656 return bytearray(raw) if tag == _BYTEARRAY_TAG else raw 

657 

658 

659def _payload_dtype(dtype_name: Any) -> torch.dtype: 

660 """Resolve the stable string form emitted by ``str(torch.dtype)``.""" 

661 if not isinstance(dtype_name, str) or not dtype_name.startswith("torch."): 

662 raise ValueError(f"Payload tensor descriptor has an invalid dtype: {dtype_name!r}.") 

663 dtype = getattr(torch, dtype_name[6:], None) 

664 if not isinstance(dtype, torch.dtype): 

665 raise ValueError(f"Unsupported payload tensor dtype: {dtype_name!r}.") 

666 return dtype 

667 

668 

669def _exchange_payload_sizes( 

670 input_splits: Sequence[int], 

671 control_group: Any, 

672 device: Any = None, 

673) -> list[int]: 

674 """Exchange per-peer byte counts and wait before reading receive sizes on Host.""" 

675 backend = _control_backend(control_group) 

676 size_device = _require_control_device(device, backend) if _is_accelerator_backend(backend) else torch.device("cpu") 

677 size_input = torch.tensor(tuple(input_splits), dtype=torch.int64, device=size_device) 

678 size_output = torch.empty_like(size_input) 

679 size_work = dist.all_to_all_single(size_output, size_input, group=control_group, async_op=True) 

680 if size_work is not None: 

681 size_work.wait() 

682 return [int(size) for size in size_output.tolist()] 

683 

684 

685def _decode_received_payloads( 

686 received_bytes: bytes, 

687 output_splits: Sequence[int], 

688) -> dict[SampleKey, Any]: 

689 """Merge routes without silently overwriting duplicate sample occurrences.""" 

690 payloads: dict[SampleKey, Any] = {} 

691 cursor = 0 

692 for segment_size in output_splits: 

693 segment_items = _decode_payload_segment(received_bytes[cursor:cursor + segment_size]) 

694 for key, payload in segment_items: 

695 if key in payloads: 

696 raise ValueError(f"Data Constructor received duplicate payload for {key}.") 

697 payloads[key] = payload 

698 cursor += segment_size 

699 return payloads 

700 

701 

702class DataPlaneTransport: 

703 """Metadata/control collectives and variable-byte sample all-to-all. 

704 

705 The coordinator calls these methods only on data-plane members. Group 

706 topology is fixed at build time; it is not revalidated for each collective. 

707 """ 

708 

709 def __init__(self, groups: DataGroups, global_rank: int, communication_device: Any = None, 

710 *, planner_process_rank: int | None = None) -> None: 

711 """Store service-group membership.""" 

712 self._ranks = groups.data_plane_ranks 

713 self._groups = groups 

714 self._planner_rank = groups.planner_rank 

715 self._planner_process_rank = groups.planner_rank if planner_process_rank is None else planner_process_rank 

716 self._global_rank = global_rank 

717 self._is_member = global_rank in self._ranks 

718 self._local_index = self._ranks.index(global_rank) if self._is_member else None 

719 if self._is_member and len(self._ranks) > 1 and (not groups.distributed or self._groups.control_group is None): 

720 raise ValueError("Multi-rank data-plane communication requires an initialized process group.") 

721 self._communication_device = ( 

722 torch.device(communication_device) if communication_device is not None else None 

723 ) 

724 

725 @property 

726 def is_member(self) -> bool: 

727 """Return whether this rank participates in Dataset Reader/Planner communication.""" 

728 return self._is_member 

729 

730 @property 

731 def planner_rank(self) -> int: 

732 """Return the global Planner rank.""" 

733 return self._planner_rank 

734 

735 @property 

736 def ranks(self) -> tuple[int, ...]: 

737 """Return data-plane ranks in collective order.""" 

738 return self._ranks 

739 

740 @property 

741 def communication_device(self) -> torch.device | None: 

742 """Return the rank-local accelerator used by payload collectives.""" 

743 return self._communication_device 

744 

745 @property 

746 def communication_backend(self) -> str: 

747 """Return the backend used by this data-plane control group.""" 

748 return _control_backend(self._groups.control_group) 

749 

750 @property 

751 def payload_backend(self) -> str | None: 

752 """Return the payload backend for rebuilding an independent data group.""" 

753 return _control_backend(self._groups.payload_group) if self._groups.payload_group is not None else None 

754 

755 def all_gather_object(self, value: Any) -> tuple[Any, ...]: 

756 """Gather small control objects on every data-plane rank. 

757 

758 Args: 

759 value: Rank-local control value. 

760 

761 Returns: 

762 Values in data-plane rank order. 

763 """ 

764 return self.begin_all_gather_object(value).wait() 

765 

766 def begin_all_gather_object(self, value: Any) -> ControlGatherWork: 

767 """Launch control gathering and defer accelerator result decoding to the consumer. 

768 

769 Args: 

770 value: Rank-local control value. 

771 

772 Returns: 

773 Work retaining communication buffers. Wait on the launch device and 

774 stream before using the result. Accelerator length exchange remains 

775 synchronous; Gloo and single-rank results are already complete. 

776 """ 

777 if len(self._ranks) == 1: 

778 return ControlGatherWork(completed_values=(value,)) 

779 return _begin_all_gather_control_object( 

780 value, 

781 group=self._groups.control_group, 

782 device=self._communication_device, 

783 ) 

784 

785 def all_ranks_true(self, value: bool) -> bool: 

786 """Return whether every data-plane rank supplied ``True``. 

787 

788 Args: 

789 value: Rank-local boolean value. 

790 

791 Returns: 

792 Whether every participating rank supplied ``True``. 

793 """ 

794 if len(self._ranks) == 1: 

795 return value 

796 backend = _control_backend(self._groups.control_group) 

797 flag_device = ( 

798 _require_control_device(self._communication_device, backend) 

799 if _is_accelerator_backend(backend) 

800 else torch.device("cpu") 

801 ) 

802 flag = torch.tensor([int(value)], dtype=torch.int32, device=flag_device) 

803 dist.all_reduce(flag, op=dist.ReduceOp.MIN, group=self._groups.control_group) 

804 return bool(flag.item()) 

805 

806 def gather_object_to_planner(self, value: Any) -> tuple[Any, ...] | None: 

807 """Gather Dataset Reader metadata only on the Planner rank. 

808 

809 Args: 

810 value: Rank-local metadata control value. 

811 

812 Returns: 

813 Gathered values on the Planner rank, otherwise ``None``. 

814 """ 

815 gathered = self.all_gather_object(value) 

816 return gathered if self._global_rank == self._planner_rank else None 

817 

818 def broadcast_from_planner(self, value: Any) -> Any: 

819 """Broadcast one control object from the configured Planner. 

820 

821 Args: 

822 value: Planner value or a placeholder on other ranks. 

823 

824 Returns: 

825 The Planner value on every data-plane rank. 

826 """ 

827 if len(self._ranks) == 1: 

828 return value 

829 return broadcast_control_object( 

830 value if self._global_rank == self._planner_rank else None, 

831 src=self._planner_process_rank, 

832 group=self._groups.control_group, 

833 device=self._communication_device, 

834 ) 

835 

836 def prepare_exchange( 

837 self, 

838 outgoing: Mapping[int, Sequence[tuple[SampleKey, Any]]], 

839 ) -> PreparedPayloadExchange: 

840 """Serialize and allocate the send buffer before collective entry. 

841 

842 Args: 

843 outgoing: Per-target sample keys and payloads. 

844 

845 Returns: 

846 Serialized payload splits and their send tensor. 

847 """ 

848 unexpected = outgoing.keys() - self._ranks 

849 if unexpected: 

850 raise ValueError(f"Payload routes target ranks outside the data plane: {sorted(unexpected)}.") 

851 segments = tuple(_encode_payload_segment(outgoing.get(rank, ())) for rank in self._ranks) 

852 input_splits = tuple(len(segment) for segment in segments) 

853 send_storage = bytearray(sum(input_splits)) 

854 cursor = 0 

855 for segment in segments: 

856 send_storage[cursor:cursor + len(segment)] = segment 

857 cursor += len(segment) 

858 if send_storage: 

859 send_tensor = torch.frombuffer(send_storage, dtype=torch.uint8) 

860 else: 

861 send_tensor = torch.empty((0,), dtype=torch.uint8) 

862 if self._communication_device is not None: 

863 send_tensor = send_tensor.to(self._communication_device) 

864 return PreparedPayloadExchange( 

865 input_splits=input_splits, 

866 send_storage=send_storage, 

867 send_tensor=send_tensor, 

868 local_segment=segments[self._local_index], 

869 ) 

870 

871 def exchange_prepared( 

872 self, 

873 prepared: PreparedPayloadExchange, 

874 ) -> dict[SampleKey, Any]: 

875 """Exchange serialized sample payloads with variable-split payload A2A. 

876 

877 Args: 

878 prepared: Preallocated payload exchange state. 

879 

880 Returns: 

881 Received payloads keyed by their source identities. 

882 """ 

883 return self.begin_exchange_prepared(prepared).wait() 

884 

885 def begin_exchange_prepared( 

886 self, 

887 prepared: PreparedPayloadExchange, 

888 ) -> PayloadExchangeWork: 

889 """Launch payload A2A from the caller's accelerator stream. 

890 

891 Args: 

892 prepared: Serialized payload buffers and input split sizes. 

893 

894 Returns: 

895 A handle that waits for and decodes the bulk payload exchange. 

896 

897 The split-size exchange is completed before the data A2A is launched, 

898 because its result determines the receive allocation. The bulk byte 

899 exchange itself remains in flight when this method returns. This 

900 method is intentionally separate from :meth:`exchange_prepared` so a 

901 training thread can launch the next step's HCCL transfer and then 

902 continue model computation while a CPU producer waits and decodes it. 

903 """ 

904 if len(self._ranks) == 1: 

905 return PayloadExchangeWork( 

906 prepared=prepared, 

907 output_splits=tuple(prepared.input_splits), 

908 received_tensor=None, 

909 completed_payloads=_decode_received_payloads( 

910 prepared.local_segment, 

911 prepared.input_splits, 

912 ), 

913 ) 

914 if self._groups.payload_group is None: 

915 raise ValueError("Sample payload exchange requires a payload process group.") 

916 

917 input_splits = list(prepared.input_splits) 

918 output_splits = _exchange_payload_sizes( 

919 input_splits, 

920 self._groups.control_group, 

921 device=self._communication_device, 

922 ) 

923 received_tensor = torch.empty( 

924 (sum(output_splits),), 

925 dtype=torch.uint8, 

926 device=prepared.send_tensor.device, 

927 ) 

928 data_work = dist.all_to_all_single( 

929 received_tensor, 

930 prepared.send_tensor, 

931 output_split_sizes=output_splits, 

932 input_split_sizes=input_splits, 

933 group=self._groups.payload_group, 

934 async_op=True, 

935 ) 

936 return PayloadExchangeWork( 

937 prepared=prepared, 

938 output_splits=tuple(output_splits), 

939 received_tensor=received_tensor, 

940 data_work=data_work, 

941 ) 

942 

943 

944class ModelParallelTransport: 

945 """Broadcast a locally declared tensor batch using tensor collectives only.""" 

946 

947 def __init__( 

948 self, topology: DataTopology, groups: DataGroups, communication_device: Any = None, 

949 *, model_batch_spec: Any = None, device: Any = None, 

950 ) -> None: 

951 """Bind model peers, communication devices and the local batch declaration.""" 

952 self._ranks = topology.model_parallel_ranks 

953 self._groups = groups 

954 self._constructor_rank = topology.constructor_rank 

955 self._global_rank = topology.global_rank 

956 self._communication_device = torch.device(communication_device) if communication_device is not None else None 

957 self._device = torch.device(device or communication_device or "cpu") 

958 self._layout = None if model_batch_spec is None else ModelBatchLayout(model_batch_spec) 

959 if len(self._ranks) > 1: 

960 if not groups.distributed or self._groups.model_parallel_group is None: 

961 raise ValueError("Multi-rank model broadcast requires an initialized process group.") 

962 if self._layout is None: 

963 raise ValueError("Model-parallel loading requires the same model_batch_spec on every rank.") 

964 

965 def _control_tensor(self, values: list[int]) -> torch.Tensor: 

966 backend = _control_backend(self._groups.model_parallel_group) 

967 device = ( 

968 _require_control_device(self._communication_device, backend) if _is_accelerator_backend(backend) else "cpu" 

969 ) 

970 return torch.tensor(values, dtype=torch.int64, device=device) 

971 

972 def broadcast(self, batch: Any, *, error: BaseException | None = None) -> Any: 

973 """Broadcast EOF/dynamic dimensions and payload tensors, never Python objects. 

974 

975 Every rank must configure an identical model_batch_spec. Static values 

976 come from that local declaration. Source validation failures are signaled 

977 in the header before peers allocate or enter payload collectives. 

978 

979 Args: 

980 batch: Constructed input on the source; None on receivers or at EOF. 

981 error: Optional source preparation failure to signal before payload transfer. 

982 

983 Returns: 

984 The declared batch on each model peer, or None at EOF. 

985 """ 

986 if len(self._ranks) == 1: 

987 if error is not None: 

988 raise error 

989 return batch 

990 is_constructor = self._global_rank == self._constructor_rank 

991 tensors = [] 

992 values = [0] * (1 + self._layout.dynamic_dimensions) 

993 if is_constructor: 

994 try: 

995 if error is not None: 

996 raise error 

997 if batch is not None: 

998 tensors = self._layout.flatten(batch) 

999 values = [1, *self._layout.dimensions(tensors)] 

1000 except BaseException as exc: # pylint: disable=broad-exception-caught 

1001 # Notify peers even on interrupts before re-raising the original failure. 

1002 error = exc 

1003 values[0] = -1 

1004 header = self._control_tensor(values) 

1005 dist.broadcast(header, src=self._constructor_rank, group=self._groups.model_parallel_group) 

1006 if not is_constructor: 

1007 values = header.cpu().tolist() 

1008 if values[0] == -1: 

1009 if error is not None: 

1010 raise error 

1011 raise RuntimeError("The Data Constructor failed to prepare the declared tensor batch.") 

1012 if values[0] == 0: 

1013 return None 

1014 if values[0] != 1: 

1015 raise ValueError("Invalid model batch status header.") 

1016 shapes = self._layout.shapes(values[1:]) 

1017 received = self._broadcast_tensors(shapes, tensors) 

1018 return self._layout.rebuild(received) 

1019 

1020 def _broadcast_tensors(self, shapes: list[tuple[int, ...]], sources: list[torch.Tensor]) -> list[torch.Tensor]: 

1021 """Coalesce fields with the same dtype and destination placement.""" 

1022 buckets = {} 

1023 for index, field in enumerate(self._layout.fields): 

1024 buckets.setdefault((field.dtype, field.device), []).append(index) 

1025 received = [None] * len(shapes) 

1026 for indices in buckets.values(): 

1027 field = self._layout.fields[indices[0]] 

1028 bucket_shapes = [shapes[index] for index in indices] 

1029 local = [sources[index] for index in indices] if sources else [] 

1030 for index, tensor in zip(indices, self._broadcast_bucket(field, bucket_shapes, local)): 

1031 received[index] = tensor 

1032 return received 

1033 

1034 def _broadcast_bucket(self, field: Any, shapes: list[tuple[int, ...]], 

1035 sources: list[torch.Tensor]) -> list[torch.Tensor]: 

1036 """Broadcast one packed payload while retaining independent leaf storage.""" 

1037 if len(shapes) == 1: 

1038 return [self._broadcast_tensor(field, shapes[0], sources[0] if sources else None)] 

1039 target = torch.device("cpu") if field.device == "cpu" else self._device 

1040 local = [tensor.to(target).contiguous() for tensor in sources] 

1041 sizes = [math.prod(shape) for shape in shapes] 

1042 packed = torch.cat([tensor.reshape(-1) for tensor in local]) if local else None 

1043 packed = self._broadcast_tensor(field, (sum(sizes),), packed) 

1044 if local: 

1045 return local 

1046 return [part.reshape(shape).clone() for part, shape in zip(packed.split(sizes), shapes)] 

1047 

1048 def _broadcast_tensor(self, field: Any, shape: tuple[int, ...], source: Any) -> torch.Tensor: 

1049 """Broadcast one declared tensor using a backend-compatible transfer device.""" 

1050 target = torch.device("cpu") if field.device == "cpu" else self._device 

1051 group = self._group_for_tensor(target.type) 

1052 backend = _control_backend(group) 

1053 transfer_device = _require_control_device(self._communication_device, backend) if ( 

1054 target.type == "cpu" and _is_accelerator_backend(backend) 

1055 ) else target 

1056 tensor = torch.empty(shape, dtype=field.dtype, device=transfer_device) if source is None else ( 

1057 source.to(transfer_device).contiguous() 

1058 ) 

1059 if tensor.numel(): 

1060 dist.broadcast(tensor, src=self._constructor_rank, group=group) 

1061 return tensor.to(target) 

1062 

1063 def _group_for_tensor(self, device_type: str) -> Any: 

1064 if device_type == "cpu" or self._groups.model_parallel_tensor_group is None: 

1065 return self._groups.model_parallel_group 

1066 return self._groups.model_parallel_tensor_group 

1067 

1068 

1069__all__ = [ 

1070 "DataGroups", 

1071 "DataPlaneTransport", 

1072 "ModelParallelTransport", 

1073 "PreparedPayloadExchange", 

1074 "create_data_groups", 

1075]