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

303 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"""Public builder for sample-balanced distributed dynamic packing. 

16 

17Source modes and buffering 

18-------------------------- 

19Online mode without ``batch_sampler`` requires ``external_step_source``. 

20The source emits one complete local step of raw-sample bins. HP derives 

21metadata, balances the selected samples across Data Constructors, and routes 

22payloads when necessary. With an external window greater than one, each bin 

23represents a micro-batch and consecutive bins are planned together within that 

24source yield. The iterator returns the complete collated step. 

25Metadata mode requires ``batch_sampler`` to define step/sample boundaries. 

26It looks up ``metadata[index]`` before any Dataset read; target constructors 

27then directly read their assigned indices from the shared Dataset and skip 

28payload A2A. Metadata-only streaming selection is not supported. 

29 

30With ``batch_sampler``, native HP sampling owns step selection: 

31``balance_window_size`` consecutive sampler yields per DP Constructor are 

32planned together, stopping at optimizer and epoch boundaries. Each iterator 

33yield still returns exactly one forward/backward round. The current window 

34and at most one future window are double-buffered on Host by default. Device staging 

35independently retains up to ``device_prefetch_depth`` future micro-batches; 

36model-parallel input broadcast runs when the current batch is consumed. 

37Checkpoints advance only at complete optimizer-step boundaries. 

38Dataset outputs stay whole by default. Online ``split_fn`` decomposes each 

39selected output into independent sequences; ``pack_fn`` rebuilds the planned 

40bins without changing the original sampler window's sample membership. 

41Set ``config.repack_sequences=True`` to use built-in text callbacks instead 

42of supplying split_fn/pack_fn. ``config.pad_token_id`` controls source PAD 

43trimming and new PAD; ``config.log_balance`` enables balancing reports. 

44 

45Checkpoint and distributed contracts 

46----------------------------------- 

47Native sampler checkpoint replay requires a deterministic Dataset stream 

48for a given epoch; arbitrary worker-side RNG state is not captured. Metadata and 

49Dataset lengths must agree across all Data Constructor ranks; the caller 

50must ensure this consistency because the builder only validates local inputs. Metadata 

51entries must describe deterministic, rank-independent Dataset outputs. 

52An external_step_source uses pure DP, node-local 

53communication and buffered H2D. Every step evaluates a candidate; sample 

54exchange occurs only when its objective improves by more than 

55min_balance_gain. HCCL is the default backend; Gloo transports control 

56and CPU payloads on the host. HCCL transports control and payload 

57tensors on the rank-local NPU. 

58Checkpoint/resume remains available only on the sampler path, at complete 

59optimizer-step boundaries. Save training state after the optimizer update; 

60an incomplete step retains its starting cursor and replays in full. 

61The caller must keep topology, configuration and custom policies 

62consistent across ranks and compatible with restored checkpoints. 

63""" 

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

65 

66from __future__ import annotations 

67 

68import math 

69from collections.abc import Callable, Mapping, Sequence 

70from dataclasses import dataclass 

71from functools import partial 

72from multiprocessing.context import BaseContext 

73from typing import Any, Literal 

74 

75import torch 

76 

77from hyper_parallel.data.distributed.batch_sampler import ( 

78 BatchSamplerReader, 

79 preserve_sample, 

80 validate_native_sampler, 

81) 

82from hyper_parallel.data.distributed.data_constructor import ( 

83 PackingDataConstructor, 

84 default_collate_fn, 

85 default_pack_fn, 

86) 

87from hyper_parallel.data.distributed.device_prefetch import _create_device_prefetcher, _resolve_device 

88from hyper_parallel.data.distributed.distributed_dataloader import DistributedDataLoader 

89from hyper_parallel.data.distributed.balancing_algorithm import BalancingAlgorithm 

90from hyper_parallel.data.distributed.cost_model import CausalAttentionCostModel, CostModel 

91from hyper_parallel.data.distributed.model_batch import TensorFieldSpec 

92from hyper_parallel.data.distributed.indexed_text import ( 

93 _validate_pad_token_id, 

94 collate_indexed_text_sequences, 

95 pack_indexed_text_samples, 

96 split_packed_text_sample, 

97) 

98from hyper_parallel.data.distributed.packed_balancing import LocalBalancingDataLoader, build_local_balancing_dataloader 

99from hyper_parallel.data.distributed.external_step import ExternalStepSource 

100from hyper_parallel.data.distributed.planner import DynamicPackingPlanner, OversizedPolicy 

101from hyper_parallel.data.distributed.schema import PackingConstraints, SampleMetadata 

102from hyper_parallel.data.distributed.metadata import PlannedSampleLoader 

103from hyper_parallel.data.distributed.dataset_reader import _validate_worker_options 

104from hyper_parallel.data.distributed.topology import DataTopology 

105from hyper_parallel.data.distributed.transport import ( 

106 DataPlaneTransport, 

107 ModelParallelTransport, 

108 create_data_groups, 

109) 

110 

111_DEFAULT_DATALOADER_KWARGS = { 

112 "num_workers": 0, 

113 "pin_memory": False, 

114 "prefetch_factor": None, 

115 "persistent_workers": False, 

116} 

117_OPTIONAL_DATALOADER_KWARGS = frozenset({ 

118 "in_order", 

119 "multiprocessing_context", 

120 "pin_memory_device", 

121 "timeout", 

122 "worker_init_fn", 

123}) 

124_SUPPORTED_DATALOADER_KWARGS = frozenset(_DEFAULT_DATALOADER_KWARGS) | _OPTIONAL_DATALOADER_KWARGS 

125_MANAGED_DATALOADER_KWARGS = frozenset({ 

126 "batch_sampler", 

127 "batch_size", 

128 "collate_fn", 

129 "dataset", 

130 "drop_last", 

131 "generator", 

132 "sampler", 

133 "shuffle", 

134}) 

135 

136 

137@dataclass(frozen=True) 

138class DistributedDatasetConfig: 

139 """Configure sample planning, dynamic packing, and data-plane communication. 

140 

141 ``seq_len`` and ``local_batch_size`` are the only required sizing inputs. 

142 One iterator yield contains ``local_batch_size`` packed sequences on each 

143 DP rank. Native sampler global batch size defines optimizer boundaries. 

144 

145 Args: 

146 seq_len: Maximum token count in one non-oversized packed sequence. 

147 local_batch_size: Packed sequences constructed per DP rank and yield. 

148 balance_window_size: Maximum consecutive micro-batches planned together. 

149 Native windows end at the sampler's optimizer or epoch boundary. 

150 For an external source, one (the default) retains the original 

151 whole-step, per-rank objective. Larger values group consecutive bins 

152 within one source yield, with one bin per rank per micro-batch. 

153 The final window uses the remaining bins. Each yield still returns 

154 one complete optimizer step. 

155 device_prefetch_depth: Future native NPU/CUDA micro-batches copied ahead 

156 on Constructors. Model peers receive each batch only at delivery. 

157 Defaults to one. Zero stages only on demand. Must be a non-negative 

158 integer and identical across ranks. Independent of balance_window_size; 

159 ignored on CPU. External-step sources support only the default value. 

160 use_data_process: Prepare Host data in a separate process on data-plane 

161 ranks (default True). With False, the caller prepares windows or 

162 external steps on demand. Native H2D lookahead can use the remaining 

163 batches in the current window. Configure the same value on every rank. 

164 dp_dim_names: Named mesh dimensions that define DP coordinates. 

165 balance_group_size: Optional number of DP ranks in each independent 

166 local-balancing group. ``None`` preserves launcher/node grouping. 

167 This applies only to external-step 

168 loading; native ``batch_sampler`` loading remains global. 

169 dataset_reader_ranks: Optional Dataset Reader ranks. They read raw 

170 samples online or metadata only in metadata mode. Defaults to the 

171 Data Constructor ranks. 

172 dataset_already_sharded: Legacy sharding configuration flag. 

173 Native BatchSampler requires False because it owns DP slicing; 

174 external sources manage their own partitioning. 

175 planner_rank: Optional centralized Planner rank. Defaults to the lowest 

176 Data Constructor rank. 

177 oversized_policy: ``error`` by default; ``single`` explicitly permits 

178 one oversized sample to occupy a bin alone. 

179 drop_last: Whether to drop a tail with fewer than one sample per global 

180 packing bin. Only ``True`` is supported in this first version. 

181 seed: DataLoader worker seed. Sampling order is configured on the sampler 

182 or external step producer. 

183 min_balance_gain: Minimum relative improvement in the algorithm's 

184 objective. A candidate is accepted only when its gain is strictly 

185 greater; zero rejects equal or worse placements. 

186 packing_budgets: Optional per-packed-sequence additive hard limits. 

187 Each configured stage must 

188 occur in every sample's packing_costs. These limits are independent 

189 of cost-model balancing scores. 

190 communication_backend: Backend for HP data-plane collectives. ``hccl`` 

191 is the default for NPU training and serializes control objects into 

192 accelerator tensors. ``gloo`` keeps control and CPU payload 

193 communication on Gloo. HCCL requires an NPU communication device. 

194 metadata_mode: Whether metadata is precomputed and available by Dataset 

195 index. ``False`` means the Dataset Reader loads samples and calls 

196 ``metadata_fn`` during native sampler planning. 

197 broadcast_plan: Whether one Planner computes and broadcasts each plan. 

198 Defaults to ``True``. If ``False``, every data-plane rank computes 

199 the plan from gathered metadata. Configuration and deterministic 

200 cost/assignment policies must produce identical plans across ranks. 

201 log_balance: Whether to emit INFO-level balancing reports. Defaults to 

202 ``False``; enabling INFO logging alone does not enable these reports. 

203 repack_sequences: Use built-in text splitting and packing on the native 

204 online sampler path. Defaults to ``False``. Records must contain 

205 input_ids, pre-shifted labels and explicit cu_seq_lens. Cannot be 

206 combined with custom split_fn or pack_fn. Unless overridden, use 

207 the text collator and causal Attention square cost including new PAD. 

208 pad_token_id: Optional non-negative source PAD ID for built-in repacking. 

209 Only trailing matching tokens with labels=-100 are removed. The same 

210 ID fills new PAD. ``None`` preserves source tokens and fills with 0. 

211 Has no effect when repack_sequences is false. 

212 """ 

213 

214 seq_len: int 

215 local_batch_size: int 

216 dp_dim_names: tuple[str, ...] | None = None 

217 dataset_reader_ranks: tuple[int, ...] | None = None 

218 dataset_already_sharded: bool = False 

219 planner_rank: int | None = None 

220 oversized_policy: OversizedPolicy = "error" 

221 drop_last: bool = True 

222 seed: int = 1234 

223 min_balance_gain: float = 0.0 

224 packing_budgets: dict[str, float] | None = None 

225 communication_backend: Literal["gloo", "hccl"] = "hccl" 

226 balance_group_size: int | None = None 

227 metadata_mode: bool = False 

228 broadcast_plan: bool = True 

229 balance_window_size: int = 1 

230 log_balance: bool = False 

231 repack_sequences: bool = False 

232 pad_token_id: int | None = None 

233 device_prefetch_depth: int = 1 

234 use_data_process: bool = True 

235 

236 def __post_init__(self) -> None: 

237 """Validate topology-independent configuration boundaries.""" 

238 self._validate_integer_fields() 

239 self._validate_policy_and_flags() 

240 if self.pad_token_id is not None: 

241 _validate_pad_token_id(self.pad_token_id) 

242 if self.repack_sequences and self.metadata_mode: 

243 raise ValueError("repack_sequences requires online metadata (metadata_mode=False).") 

244 self._validate_rank_tuple(self.dataset_reader_ranks, "dataset_reader_ranks") 

245 self._validate_name_tuple(self.dp_dim_names, "dp_dim_names") 

246 self._validate_planner_rank() 

247 PackingConstraints(self.seq_len, self.oversized_policy, self.packing_budgets) 

248 

249 def _validate_integer_fields(self) -> None: 

250 """Validate window sizes, batch dimensions and non-negative integer options.""" 

251 for name in ("seq_len", "local_batch_size", "balance_window_size"): 

252 value = getattr(self, name) 

253 if not isinstance(value, int) or isinstance(value, bool) or value < 1: 

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

255 for name in ("seed", "device_prefetch_depth"): 

256 value = getattr(self, name) 

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

258 raise ValueError(f"{name} must be a non-negative integer, but got {value!r}.") 

259 if ( 

260 self.balance_group_size is not None 

261 and ( 

262 not isinstance(self.balance_group_size, int) 

263 or isinstance(self.balance_group_size, bool) 

264 or self.balance_group_size < 1 

265 ) 

266 ): 

267 raise ValueError("balance_group_size must be a positive integer or None.") 

268 

269 def _validate_policy_and_flags(self) -> None: 

270 """Validate policy names, boolean flags and the relative-gain threshold.""" 

271 if self.oversized_policy not in ("error", "single"): 

272 raise ValueError("oversized_policy must be 'error' or 'single'.") 

273 for name in ( 

274 "dataset_already_sharded", 

275 "drop_last", 

276 "metadata_mode", 

277 "broadcast_plan", 

278 "log_balance", 

279 "repack_sequences", 

280 "use_data_process", 

281 ): 

282 if not isinstance(getattr(self, name), bool): 

283 raise ValueError(f"{name} must be boolean.") 

284 if ( 

285 not isinstance(self.min_balance_gain, (int, float)) 

286 or isinstance(self.min_balance_gain, bool) 

287 or not math.isfinite(self.min_balance_gain) 

288 or not 0.0 <= self.min_balance_gain < 1.0 

289 ): 

290 raise ValueError("min_balance_gain must be in [0, 1).") 

291 if self.communication_backend not in ("gloo", "hccl"): 

292 raise ValueError("communication_backend must be 'gloo' or 'hccl'.") 

293 if not self.drop_last: 

294 raise ValueError( 

295 "Dynamic distributed packing currently requires drop_last=True so every DP rank receives the " 

296 "same number of non-empty packing bins." 

297 ) 

298 

299 def _validate_planner_rank(self) -> None: 

300 if self.planner_rank is not None and ( 

301 not isinstance(self.planner_rank, int) 

302 or isinstance(self.planner_rank, bool) 

303 or self.planner_rank < 0 

304 ): 

305 raise ValueError("planner_rank must be a non-negative integer or None.") 

306 

307 @staticmethod 

308 def _validate_rank_tuple(value: tuple[int, ...] | None, name: str) -> None: 

309 if value is None: 

310 return 

311 if not isinstance(value, tuple) or not value: 

312 raise ValueError(f"{name} must be a non-empty tuple or None.") 

313 if any(not isinstance(rank, int) or isinstance(rank, bool) or rank < 0 for rank in value): 

314 raise ValueError(f"{name} must contain non-negative integer ranks.") 

315 if len(value) != len(set(value)): 

316 raise ValueError(f"{name} must not contain duplicate ranks.") 

317 

318 @staticmethod 

319 def _validate_name_tuple(value: tuple[str, ...] | None, name: str) -> None: 

320 if value is None: 

321 return 

322 if not isinstance(value, tuple) or not value or any(not isinstance(item, str) or not item for item in value): 

323 raise ValueError(f"{name} must be a non-empty tuple of strings or None.") 

324 if len(value) != len(set(value)): 

325 raise ValueError(f"{name} must not contain duplicate names.") 

326 

327 

328def _resolve_service_ranks( 

329 topology: DataTopology, 

330 config: DistributedDatasetConfig, 

331) -> tuple[tuple[int, ...], int]: 

332 """Resolve Reader and planner ownership within the root mesh.""" 

333 dataset_reader_ranks = config.dataset_reader_ranks or topology.constructor_ranks 

334 unknown_ranks = set(dataset_reader_ranks) - set(topology.rank_list) 

335 if unknown_ranks: 

336 raise ValueError(f"dataset_reader_ranks are outside the root mesh: {sorted(unknown_ranks)}.") 

337 planner_rank = min(topology.constructor_ranks) if config.planner_rank is None else config.planner_rank 

338 data_plane_ranks = set(dataset_reader_ranks) | set(topology.constructor_ranks) 

339 if planner_rank not in data_plane_ranks: 

340 raise ValueError(f"planner_rank {planner_rank} must be a Dataset Reader or Data Constructor rank.") 

341 return dataset_reader_ranks, planner_rank 

342 

343 

344def _normalize_dataloader_kwargs( 

345 dataloader_kwargs: Mapping[str, Any] | None, 

346) -> dict[str, Any]: 

347 """Resolve validated DataLoader execution options.""" 

348 if dataloader_kwargs is None: 

349 supplied_options = {} 

350 elif not isinstance(dataloader_kwargs, Mapping): 

351 raise ValueError("dataloader_kwargs must be a mapping or None.") 

352 else: 

353 try: 

354 supplied_options = dict(dataloader_kwargs) 

355 except Exception as exc: 

356 raise ValueError(f"dataloader_kwargs cannot be copied: {exc}") from exc 

357 _validate_dataloader_option_keys(supplied_options) 

358 options = dict(_DEFAULT_DATALOADER_KWARGS) 

359 options.update(supplied_options) 

360 _validate_worker_options(options) 

361 _validate_dataloader_timeout(options) 

362 worker_init_fn = options.get("worker_init_fn") 

363 if worker_init_fn is not None and not callable(worker_init_fn): 

364 raise ValueError("dataloader_kwargs worker_init_fn must be callable or None.") 

365 _validate_multiprocessing_context(options) 

366 pin_memory_device = options.get("pin_memory_device", "") 

367 if not isinstance(pin_memory_device, str): 

368 raise ValueError("dataloader_kwargs pin_memory_device must be a string.") 

369 return options 

370 

371 

372def _validate_dataloader_option_keys(supplied_options: Mapping[str, Any]) -> None: 

373 """Reject unsupported keys and overrides of internally managed DataLoader options.""" 

374 non_string_keys = [key for key in supplied_options if not isinstance(key, str)] 

375 if non_string_keys: 

376 raise ValueError(f"dataloader_kwargs keys must be strings, but got {non_string_keys!r}.") 

377 managed_keys = sorted(set(supplied_options) & _MANAGED_DATALOADER_KWARGS) 

378 if managed_keys: 

379 raise ValueError( 

380 f"dataloader_kwargs cannot override distributed sampling, batching, collation, or deterministic " 

381 f"worker-seeding options " 

382 f"{managed_keys}." 

383 ) 

384 unsupported_keys = sorted(set(supplied_options) - _SUPPORTED_DATALOADER_KWARGS) 

385 if unsupported_keys: 

386 raise ValueError(f"dataloader_kwargs contains unsupported options {unsupported_keys}.") 

387 

388 

389def _validate_dataloader_timeout(options: Mapping[str, Any]) -> None: 

390 """Require a finite timeout compatible with the configured worker count.""" 

391 num_workers = options["num_workers"] 

392 timeout = options.get("timeout", 0) 

393 try: 

394 normalized_timeout = float(timeout) 

395 except (TypeError, ValueError, OverflowError): 

396 normalized_timeout = math.nan 

397 if ( 

398 not isinstance(timeout, (int, float)) 

399 or isinstance(timeout, bool) 

400 or not math.isfinite(normalized_timeout) 

401 or normalized_timeout < 0 

402 ): 

403 raise ValueError(f"dataloader_kwargs timeout must be finite and non-negative, but got {timeout!r}.") 

404 if num_workers == 0 and timeout != 0: 

405 raise ValueError("dataloader_kwargs timeout must be zero when num_workers=0.") 

406 

407 

408def _validate_multiprocessing_context(options: Mapping[str, Any]) -> None: 

409 """Check that the worker context uses a supported multiprocessing start method.""" 

410 multiprocessing_context = options.get("multiprocessing_context") 

411 if multiprocessing_context is None: 

412 return 

413 if options["num_workers"] == 0: 

414 raise ValueError("dataloader_kwargs multiprocessing_context requires num_workers > 0.") 

415 if not isinstance(multiprocessing_context, (str, BaseContext)): 

416 raise ValueError("dataloader_kwargs multiprocessing_context is invalid.") 

417 start_method = multiprocessing_context 

418 if isinstance(multiprocessing_context, BaseContext): 

419 try: 

420 start_method = multiprocessing_context.get_start_method() 

421 except Exception as exc: 

422 raise ValueError( 

423 f"dataloader_kwargs multiprocessing_context cannot report its start method: {exc}" 

424 ) from exc 

425 if start_method not in torch.multiprocessing.get_all_start_methods(): 

426 raise ValueError(f"dataloader_kwargs multiprocessing_context={start_method!r} is not supported.") 

427 

428 

429def _normalize_communication_device(communication_device: Any) -> torch.device | None: 

430 """Normalize a rank-local A2A device.""" 

431 if communication_device is None: 

432 return None 

433 try: 

434 return torch.device(communication_device) 

435 except Exception as exc: 

436 raise ValueError(f"communication_device is invalid: {communication_device!r}.") from exc 

437 

438 

439class _BuildState: 

440 """Validated rank-local components needed to assemble a distributed DataLoader.""" 

441 

442 def __init__( 

443 self, 

444 dataset: Any | None, 

445 mesh: Any, 

446 config: DistributedDatasetConfig, 

447 metadata_fn: Callable[[Any], SampleMetadata] | None, 

448 metadata: Sequence[SampleMetadata] | None, 

449 dataloader_kwargs: Mapping[str, Any] | None, 

450 pack_fn: Callable[[Sequence[Any], int], Any] | None, 

451 collate_fn: Callable[[Sequence[Any]], Any] | None, 

452 communication_device: Any, 

453 batch_sampler: Any = None, 

454 *, 

455 split_fn: Callable[[Any], Sequence[Any]] | None = None, 

456 model_config: Any = None, 

457 cost_model: CostModel | None = None, 

458 balancing_algorithm: BalancingAlgorithm | None = None, 

459 ) -> None: 

460 """Validate inputs and construct all rank-local components. 

461 

462 Args: 

463 dataset: Mapping Dataset on each Reader rank. 

464 mesh: Named root device mesh. 

465 config: Explicit loading mode, topology and packing options. 

466 metadata_fn: Derives metadata from loaded samples in online mode. 

467 metadata: Indexed precomputed metadata in metadata mode. 

468 dataloader_kwargs: Rank-local sample loading options. 

469 pack_fn: Optional packed-sequence constructor. 

470 collate_fn: Optional local-batch collator. 

471 communication_device: Rank-local control and payload device. 

472 batch_sampler: Native sampler defining each local batch. 

473 split_fn: Optional decomposition of each selected record into independent sequences. 

474 model_config: Backbone dimensions for the default cost model. 

475 cost_model: Optional workload estimator. 

476 balancing_algorithm: Optional assignment and objective policy. 

477 """ 

478 if not isinstance(config, DistributedDatasetConfig): 

479 raise ValueError(f"config must be DistributedDatasetConfig, but got {type(config)}.") 

480 _validate_builder_callbacks(metadata_fn, metadata, pack_fn, collate_fn) 

481 split_fn, pack_fn, collate_fn = _resolve_repacking_callbacks( 

482 config, batch_sampler, split_fn, pack_fn, collate_fn, 

483 ) 

484 if split_fn is not None and (not callable(split_fn) or config.metadata_mode): 

485 raise ValueError("split_fn requires online metadata and must be callable.") 

486 normalized_options = _normalize_dataloader_kwargs(dataloader_kwargs) 

487 loader_options = {name: normalized_options[name] for name in _DEFAULT_DATALOADER_KWARGS} 

488 loader_options["dataloader_kwargs"] = { 

489 name: value 

490 for name, value in normalized_options.items() 

491 if name not in _DEFAULT_DATALOADER_KWARGS 

492 } 

493 self.communication_device = _normalize_communication_device(communication_device) 

494 if batch_sampler is None: 

495 if config.metadata_mode: 

496 raise ValueError("Metadata mode requires batch_sampler to define step/sample boundaries.") 

497 raise ValueError("Online mode requires batch_sampler or external_step_source to define complete steps.") 

498 effective_pack_fn, effective_collate_fn = _resolve_constructor_callbacks( 

499 pack_fn, collate_fn, split_fn, 

500 ) 

501 self.topology = DataTopology.from_mesh(mesh, dp_dim_names=config.dp_dim_names) 

502 self.dataset_reader_ranks, self.planner_rank = _resolve_service_ranks(self.topology, config) 

503 self.dataset_reader: BatchSamplerReader | None = None 

504 self.metadata_reader: BatchSamplerReader | None = None 

505 self.direct_sample_loader: PlannedSampleLoader | None = None 

506 if config.metadata_mode: 

507 if metadata_fn is not None: 

508 raise ValueError("metadata_mode=True requires precomputed metadata, not metadata_fn.") 

509 if metadata is None: 

510 raise ValueError("metadata_mode=True requires metadata.") 

511 elif metadata is not None: 

512 raise ValueError("metadata_mode=False requires metadata_fn, not precomputed metadata.") 

513 elif metadata_fn is None: 

514 raise ValueError("metadata_mode=False requires metadata_fn.") 

515 self._configure_batch_sampler_sources( 

516 dataset, metadata_fn, metadata, config, batch_sampler, loader_options, split_fn, 

517 ) 

518 self.planner, self.constructor = self._build_components( 

519 config, 

520 effective_pack_fn, 

521 effective_collate_fn, 

522 model_config, 

523 cost_model, 

524 balancing_algorithm, 

525 ) 

526 

527 @property 

528 def is_reader(self) -> bool: 

529 """Return whether this rank owns a Dataset Reader.""" 

530 return self.topology.global_rank in self.dataset_reader_ranks 

531 

532 def _configure_batch_sampler_sources( 

533 self, 

534 dataset: Any, 

535 metadata_fn: Callable[[Any], SampleMetadata] | None, 

536 metadata: Sequence[SampleMetadata] | None, 

537 config: DistributedDatasetConfig, 

538 batch_sampler: Any, 

539 loader_options: dict[str, Any], 

540 split_fn: Callable[[Any], Sequence[Any]] | None, 

541 ) -> None: 

542 """Use native DP sampler owners as Readers without applying a second stride.""" 

543 if self.dataset_reader_ranks != self.topology.constructor_ranks: 

544 raise ValueError("Native batch_sampler currently requires Dataset Readers on the Data Constructor ranks.") 

545 if config.dataset_already_sharded: 

546 raise ValueError( 

547 "Native batch_sampler owns DP slicing; disable dataset_already_sharded." 

548 ) 

549 validate_native_sampler( 

550 batch_sampler, data_rank=self.topology.data_rank, 

551 dp_size=self.topology.data_parallel_size, local_batch_size=config.local_batch_size, 

552 ) 

553 if not self.is_reader: 

554 return 

555 if dataset is None: 

556 raise ValueError("Native batch_sampler requires a mapping Dataset on each Data Constructor.") 

557 sample_loader = PlannedSampleLoader(dataset, seed=config.seed, **loader_options) 

558 sample_loader.set_epoch(batch_sampler.epoch) 

559 if config.metadata_mode: 

560 if not callable(getattr(metadata, "__getitem__", None)) or len(metadata) != len(dataset): 

561 raise ValueError("Native batch_sampler metadata must align with the mapping Dataset.") 

562 self.direct_sample_loader = sample_loader 

563 reader = BatchSamplerReader( 

564 batch_sampler, reader_rank=self.topology.global_rank, 

565 metadata=metadata, metadata_fn=metadata_fn, 

566 sample_loader=None if config.metadata_mode else sample_loader, 

567 split_fn=split_fn, 

568 ) 

569 if config.metadata_mode: 

570 self.metadata_reader = reader 

571 else: 

572 self.dataset_reader = reader 

573 

574 def _build_components( 

575 self, 

576 config: DistributedDatasetConfig, 

577 effective_pack_fn: Callable[[Sequence[Any], int], Any], 

578 effective_collate_fn: Callable[[Sequence[Any]], Any], 

579 model_config: Any, 

580 cost_model: CostModel | None, 

581 balancing_algorithm: BalancingAlgorithm | None, 

582 ) -> tuple[DynamicPackingPlanner, PackingDataConstructor]: 

583 """Create the planner and data constructor.""" 

584 if cost_model is None and config.repack_sequences: 

585 cost_model = CausalAttentionCostModel() 

586 planner = DynamicPackingPlanner( 

587 data_parallel_size=self.topology.data_parallel_size, 

588 seq_len=config.seq_len, 

589 local_batch_size=config.local_batch_size, 

590 oversized_policy=config.oversized_policy, 

591 packing_budgets=config.packing_budgets, 

592 min_balance_gain=config.min_balance_gain, 

593 model_config=model_config, 

594 cost_model=cost_model, 

595 balancing_algorithm=balancing_algorithm, 

596 ) 

597 return planner, PackingDataConstructor(effective_pack_fn, effective_collate_fn, seq_len=config.seq_len) 

598 

599 

600def _validate_builder_callbacks( 

601 metadata_fn: Callable[[Any], SampleMetadata] | None, 

602 metadata: Sequence[SampleMetadata] | None, 

603 pack_fn: Callable[[Sequence[Any], int], Any] | None, 

604 collate_fn: Callable[[Sequence[Any]], Any] | None, 

605) -> None: 

606 """Validate callback types and mutually exclusive metadata providers.""" 

607 if metadata_fn is not None and not callable(metadata_fn): 

608 raise ValueError("metadata_fn must be callable or None.") 

609 if metadata_fn is not None and metadata is not None: 

610 raise ValueError("Provide either metadata or metadata_fn, but not both.") 

611 if pack_fn is not None and not callable(pack_fn): 

612 raise ValueError("pack_fn must be callable or None.") 

613 if collate_fn is not None and not callable(collate_fn): 

614 raise ValueError("collate_fn must be callable or None.") 

615 

616 

617def _resolve_repacking_callbacks( 

618 config: DistributedDatasetConfig, 

619 batch_sampler: Any, 

620 split_fn: Callable[[Any], Sequence[Any]] | None, 

621 pack_fn: Callable[[Sequence[Any], int], Any] | None, 

622 collate_fn: Callable[[Sequence[Any]], Any] | None, 

623) -> tuple[ 

624 Callable[[Any], Sequence[Any]] | None, 

625 Callable[[Sequence[Any], int], Any] | None, 

626 Callable[[Sequence[Any]], Any] | None, 

627]: 

628 """Select built-in text callbacks without mixing packing contracts.""" 

629 if not config.repack_sequences: 

630 return split_fn, pack_fn, collate_fn 

631 if batch_sampler is None: 

632 raise ValueError("repack_sequences requires a native batch_sampler.") 

633 if split_fn is not None or pack_fn is not None: 

634 raise ValueError("repack_sequences cannot be combined with custom split_fn or pack_fn.") 

635 return ( 

636 partial(split_packed_text_sample, pad_token_id=config.pad_token_id), 

637 partial(pack_indexed_text_samples, pad_token_id=0 if config.pad_token_id is None else config.pad_token_id), 

638 collate_indexed_text_sequences if collate_fn is None else collate_fn, 

639 ) 

640 

641 

642def _resolve_constructor_callbacks( 

643 pack_fn: Callable[[Sequence[Any], int], Any] | None, 

644 collate_fn: Callable[[Sequence[Any]], Any] | None, 

645 split_fn: Callable[[Any], Sequence[Any]] | None = None, 

646) -> tuple[Callable[[Sequence[Any], int], Any], Callable[[Sequence[Any]], Any]]: 

647 """Resolve constructor callbacks for a native BatchSampler source.""" 

648 if split_fn is not None and pack_fn is None: 

649 raise ValueError("Native split_fn requires pack_fn to rebuild the planned sequences.") 

650 if split_fn is None and pack_fn is not None: 

651 raise ValueError("Native batch_sampler preserves Dataset outputs; pack_fn must be omitted.") 

652 effective_pack_fn = preserve_sample if split_fn is None else pack_fn 

653 effective_collate_fn = default_collate_fn if collate_fn is None else collate_fn 

654 return effective_pack_fn, effective_collate_fn 

655 

656 

657def build_distributed_dataloader( 

658 dataset: Any | None, 

659 mesh: Any, 

660 config: DistributedDatasetConfig, 

661 *, 

662 metadata_fn: Callable[[Any], SampleMetadata] | None = None, 

663 metadata: Sequence[SampleMetadata] | None = None, 

664 dataloader_kwargs: Mapping[str, Any] | None = None, 

665 pack_fn: Callable[[Sequence[Any], int], Any] | None = None, 

666 split_fn: Callable[[Any], Sequence[Any]] | None = None, 

667 collate_fn: Callable[[Sequence[Any]], Any] | None = None, 

668 device: Any = None, 

669 model_batch_spec: Any = None, 

670 batch_sampler: Any = None, 

671 external_step_source: ExternalStepSource | None = None, 

672 model_config: Any = None, 

673 cost_model: CostModel | None = None, 

674 balancing_algorithm: BalancingAlgorithm | None = None, 

675) -> DistributedDataLoader | LocalBalancingDataLoader: 

676 """Build a sample-balanced loader using the source and checkpoint contracts above. 

677 

678 Args: 

679 dataset: Shared mapping Dataset on native Data Constructors. External sources 

680 own loading and may pass None; other ranks may also pass None. 

681 mesh: Named root HyperParallel or native DeviceMesh. 

682 config: Packing, repacking, logging, service-rank and communication options. 

683 metadata_fn: Derive metadata from each native Dataset output or external raw 

684 sample. With splitting, receives each independent sequence instead. 

685 metadata: Explicit indexable metadata on native Dataset Reader ranks in metadata 

686 mode. Must implement __len__ and __getitem__; metadata[index] must describe 

687 the corresponding deterministic, rank-independent dataset[index]. 

688 dataloader_kwargs: Native worker options: num_workers=0, pin_memory=False, 

689 prefetch_factor=None, persistent_workers=False by default. Sampling, 

690 batching, shuffling and DataLoader collation cannot be overridden. 

691 pack_fn: Build one packed sequence; the external default preserves a bin as a 

692 raw-sample tuple. Omit when config.repack_sequences selects text packing. 

693 split_fn: Online native callback returning independent sequences in original 

694 order. Requires pack_fn. Each original record must fit one bin and its 

695 sequences retain their fallback grouping. Preserve tokens, targets and 

696 attention isolation; contextual slices are not independent. Omit with 

697 config.repack_sequences; unsupported in metadata mode. 

698 collate_fn: Collate local_batch_size planned bins. Defaults to text collation 

699 with config.repack_sequences, otherwise a tuple; an explicit callback wins. 

700 device: Rank-local training device. HCCL uses its NPU for control, payload and 

701 final H2D. Gloo communicates on Host and defaults to CPU; pass an explicit 

702 NPU/CUDA device to enable H2D with Gloo. 

703 model_batch_spec: Identical layout on every MP rank: nested dict/list/tuple 

704 leaves are TensorFieldSpec or static scalars. Dynamic values must be tensors; 

705 fields and dtypes are not broadcast. Defaults to collate_fn.model_batch_spec 

706 or the built-in text layout. Required for custom MP batches, unnecessary for DP. 

707 batch_sampler: Native HP BatchSampler supplied on every rank; only Constructors 

708 advance it. Readers must coincide with Constructors and drop_last must be 

709 true. Dataset outputs stay whole unless split_fn/pack_fn or online text 

710 repacking is enabled. Metadata indexes outputs, not underlying documents. 

711 Checkpoint via this loader, not the sampler's speculative cursor. 

712 external_step_source: Online pure-DP iterable emitting one complete local step 

713 of local_batch_size raw-sample bins. Optional set_epoch is forwarded; 

714 exhaustion ends iteration. The caller owns recovery and step limits. 

715 model_config: Backbone dimensions for the default cost model when repacking 

716 is disabled and cost_model is omitted. 

717 cost_model: Optional workload callback. Text repacking defaults to 

718 CausalAttentionCostModel including new PAD; otherwise DefaultCostModel. 

719 balancing_algorithm: Optional assignment/objective policy receiving scored 

720 samples. HyperParallel enforces capacity and the gain gate. 

721 

722 Returns: 

723 Collective iterator yielding one constructed local batch per micro-batch. 

724 """ 

725 if external_step_source is not None: 

726 if model_batch_spec is not None: 

727 raise ValueError("model_batch_spec is only supported with a native batch_sampler.") 

728 if split_fn is not None: 

729 raise ValueError("split_fn is only supported with a native batch_sampler.") 

730 if config.metadata_mode: 

731 raise ValueError("external_step_source requires metadata_mode=False for online metadata.") 

732 if batch_sampler is not None or metadata is not None: 

733 raise ValueError("external_step_source cannot be combined with a sampler or metadata sequence.") 

734 if dataloader_kwargs: 

735 raise ValueError("Configure source worker options on external_step_source, not the balancing wrapper.") 

736 return build_local_balancing_dataloader( 

737 external_step_source, mesh, config, metadata_fn=metadata_fn, 

738 pack_fn=default_pack_fn if pack_fn is None else pack_fn, 

739 collate_fn=default_collate_fn if collate_fn is None else collate_fn, 

740 model_config=model_config, cost_model=cost_model, 

741 balancing_algorithm=balancing_algorithm, device=device, 

742 ) 

743 return _build_distributed_dataloader_impl( 

744 dataset, mesh, config, metadata_fn=metadata_fn, metadata=metadata, 

745 dataloader_kwargs=dataloader_kwargs, pack_fn=pack_fn, collate_fn=collate_fn, 

746 split_fn=split_fn, communication_device=device, model_batch_spec=model_batch_spec, 

747 batch_sampler=batch_sampler, model_config=model_config, 

748 cost_model=cost_model, balancing_algorithm=balancing_algorithm, 

749 ) 

750 

751 

752def _build_distributed_dataloader_impl( 

753 dataset: Any | None, 

754 mesh: Any, 

755 config: DistributedDatasetConfig, 

756 *, 

757 metadata_fn: Callable[[Any], SampleMetadata] | None, 

758 metadata: Sequence[SampleMetadata] | None, 

759 dataloader_kwargs: Mapping[str, Any] | None, 

760 pack_fn: Callable[[Sequence[Any], int], Any] | None, 

761 collate_fn: Callable[[Sequence[Any]], Any] | None, 

762 communication_device: Any, 

763 model_batch_spec: Any = None, 

764 batch_sampler: Any = None, 

765 split_fn: Callable[[Any], Sequence[Any]] | None = None, 

766 model_config: Any = None, 

767 cost_model: CostModel | None = None, 

768 balancing_algorithm: BalancingAlgorithm | None = None, 

769) -> DistributedDataLoader: 

770 """Build native sampler readers, planning, transport and device staging for this rank.""" 

771 if communication_device is None: 

772 communication_device = _resolve_device(communication_backend=getattr(config, "communication_backend", "hccl")) 

773 if getattr(config, "balance_group_size", None) is not None: 

774 raise ValueError("balance_group_size is only supported for local balancing paths.") 

775 state = _BuildState( 

776 dataset, 

777 mesh, 

778 config, 

779 metadata_fn, 

780 metadata, 

781 dataloader_kwargs, 

782 pack_fn, 

783 collate_fn, 

784 communication_device, 

785 batch_sampler, 

786 split_fn=split_fn, 

787 model_config=model_config, 

788 cost_model=cost_model, 

789 balancing_algorithm=balancing_algorithm, 

790 ) 

791 device = state.communication_device 

792 # Validate device/stream support on every rank before any group is created. 

793 device_prefetch = _create_device_prefetcher(device) 

794 communication_device = device if config.communication_backend == "hccl" else None 

795 if model_batch_spec is None: 

796 model_batch_spec = getattr(collate_fn, "model_batch_spec", None) 

797 if model_batch_spec is None and ( 

798 collate_fn is collate_indexed_text_sequences or (config.repack_sequences and collate_fn is None) 

799 ): 

800 shape = (config.local_batch_size, config.seq_len) 

801 model_batch_spec = { 

802 "input_ids": TensorFieldSpec(shape, torch.int64), 

803 "labels": TensorFieldSpec(shape, torch.int64), 

804 "cu_seq_lens": TensorFieldSpec((None,), torch.int32), 

805 } 

806 if model_batch_spec is None and len(state.topology.model_parallel_ranks) > 1: 

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

808 groups = create_data_groups( 

809 state.topology, 

810 state.dataset_reader_ranks, 

811 state.planner_rank, 

812 cpu_backend=config.communication_backend, 

813 payload_backend=config.communication_backend, 

814 communication_device=communication_device, 

815 enable_payload_exchange=not config.metadata_mode, 

816 model_device=device, 

817 ) 

818 

819 with groups.close_on_error(): 

820 accumulation_steps = batch_sampler.global_batch_size // batch_sampler.global_micro_batch_size 

821 return DistributedDataLoader( 

822 groups=groups, 

823 accumulation_steps=accumulation_steps, 

824 balance_window_size=config.balance_window_size, 

825 device_prefetch_depth=config.device_prefetch_depth, 

826 use_data_process=config.use_data_process, 

827 device=device, 

828 initial_epoch=batch_sampler.epoch, 

829 initial_consumed_samples=batch_sampler.consumed_samples, 

830 topology=state.topology, 

831 dataset_reader_ranks=state.dataset_reader_ranks, 

832 dataset_reader=state.dataset_reader, 

833 metadata_reader=state.metadata_reader, 

834 direct_sample_loader=state.direct_sample_loader, 

835 metadata_mode=config.metadata_mode, 

836 broadcast_plan=config.broadcast_plan, 

837 log_balance=config.log_balance, 

838 planner=state.planner, 

839 data_constructor=state.constructor, 

840 data_plane=DataPlaneTransport( 

841 groups, 

842 state.topology.global_rank, 

843 communication_device=communication_device, 

844 ), 

845 model_transport=ModelParallelTransport( 

846 state.topology, 

847 groups, 

848 model_batch_spec=model_batch_spec, 

849 device=device, 

850 communication_device=communication_device, 

851 ), 

852 device_prefetch=device_prefetch if state.topology.is_constructor else None, 

853 ) 

854 

855 

856__all__ = ["DistributedDatasetConfig", "build_distributed_dataloader"]