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

331 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"""Build offline training Datasets from indexed tokens and prepared records.""" 

16 

17from __future__ import annotations 

18 

19import math 

20import os 

21from collections.abc import Callable, Mapping, Sequence 

22from enum import Enum 

23from functools import partial 

24from typing import Any, Literal, TypeAlias, cast 

25 

26import numpy as np 

27import torch.distributed as dist 

28 

29from hyper_parallel.data.dataset_logging import get_dataset_logger 

30from hyper_parallel.data.offline.blended_dataset import BlendedDataset, SimpleBlendedDataset 

31from hyper_parallel.data.offline.data_config import ( 

32 GPTDatasetConfig, 

33 build_gpt_dataset_config, 

34 resolve_dataset_type, 

35) 

36from hyper_parallel.data.offline.dataset import GPTDataset, MockGPTDataset, SFTFromMRDataset 

37from hyper_parallel.data.parallel import ( 

38 DataLoaderParallelContext, 

39 build_dataset_for_dataloader, 

40) 

41from hyper_parallel.high_availability.group_registry import is_recovery_enabled 

42 

43DataPath: TypeAlias = str | Sequence[str] 

44DatasetSplits: TypeAlias = tuple[Any | None, Any | None, Any | None] 

45SplitBuilder: TypeAlias = Callable[..., DatasetSplits] 

46InstructionSplitBuilder: TypeAlias = Callable[..., Sequence[Any | None]] 

47BlendMode: TypeAlias = Literal["no", "inter", "intra"] 

48SplitRange: TypeAlias = tuple[float, float] 

49SplitMatrix: TypeAlias = Sequence[SplitRange | None] 

50 

51logger = get_dataset_logger(__name__) 

52 

53 

54def build_indexed_dataset( 

55 *, 

56 data_path: DataPath = None, 

57 data_config: Mapping[str, Any], 

58 train_valid_test_num_samples: Sequence[int], 

59 dataloader_context: DataLoaderParallelContext | None = None, 

60) -> DatasetSplits: 

61 """Build indexed pretraining datasets through the dedicated builder. 

62 

63 Args: 

64 data_path: Indexed prefix, directory, or weighted paths. May be omitted 

65 when mock data is enabled. 

66 data_config: Indexed pretraining build options. 

67 train_valid_test_num_samples: Trainer-derived target sizes. 

68 dataloader_context: DataLoader ownership and synchronization policy. 

69 

70 Returns: 

71 Train, validation, and test datasets. 

72 """ 

73 builder = IndexedPretrainDatasetBuilder( 

74 data_path=data_path, 

75 data_config=data_config, 

76 train_valid_test_num_samples=train_valid_test_num_samples, 

77 dataloader_context=dataloader_context, 

78 ) 

79 datasets = builder.build() 

80 return datasets 

81 

82 

83class _Split(Enum): 

84 """Stable train, validation, and test identifiers used by Dataset caches.""" 

85 

86 TRAIN = 0 

87 VALID = 1 

88 TEST = 2 

89 

90 

91def _walk_data_directories(directories: Sequence[str], file_suffix: str) -> list[str]: 

92 """Recursively find source files below the assigned directories.""" 

93 file_paths = [] 

94 for directory in directories: 

95 for root, _, filenames in os.walk(directory): 

96 for filename in filenames: 

97 if filename.endswith(file_suffix): 

98 path = os.path.abspath(os.path.join(root, filename)) 

99 file_paths.append(os.path.splitext(path)[0] if file_suffix == ".bin" else path) 

100 return file_paths 

101 

102 

103def _discover_indexed_paths( 

104 current_path: str, 

105 rank: int, 

106 world_size: int, 

107 distributed_walk: bool, 

108 file_suffix: str, 

109) -> list[str]: 

110 """Discover indexed prefixes under one directory.""" 

111 if not distributed_walk: 

112 return _walk_data_directories([current_path], file_suffix) 

113 

114 root_layout = None 

115 if rank == 0: 

116 subdirectories = [] 

117 top_files = [] 

118 for name in os.listdir(current_path): 

119 path = os.path.join(current_path, name) 

120 if os.path.isdir(path): 

121 subdirectories.append(path) 

122 elif name.endswith(file_suffix): 

123 top_files.append(os.path.splitext(path)[0] if file_suffix == ".bin" else path) 

124 root_layout = (subdirectories, top_files) 

125 

126 gathered_layouts: list[tuple[list[str], list[str]] | None] = [None] * world_size 

127 dist.all_gather_object(gathered_layouts, root_layout) 

128 rank_zero_layout = gathered_layouts[0] 

129 if rank_zero_layout is None: 

130 raise ValueError("Rank 0 did not provide the indexed directory layout") 

131 subdirectories, file_paths = rank_zero_layout 

132 local_files = _walk_data_directories(subdirectories[rank::world_size], file_suffix) 

133 gathered_files: list[list[str] | None] = [None] * world_size 

134 dist.all_gather_object(gathered_files, local_files) 

135 for rank_files in gathered_files: 

136 if rank_files: 

137 file_paths.extend(rank_files) 

138 return file_paths 

139 

140 

141def resolve_data_paths( 

142 data_path: str | Sequence[str], 

143 *, 

144 distributed_walk: bool = True, 

145 file_suffix: str = ".bin", 

146) -> list[str]: 

147 """Discover independent data files and return source paths with optional weights. 

148 

149 Args: 

150 data_path: One indexed prefix, Arrow file, or sequence of directories/source paths. 

151 distributed_walk: Whether initialized ranks divide directory walking. 

152 file_suffix: Dataset storage suffix: .bin returns prefixes, .arrow keeps full file paths. 

153 

154 Returns: 

155 One prefix directly, or alternating weight/prefix values for multiple sources. If ``data_path`` is not a 

156 collection of discoverable indexed paths, return it unchanged so an explicit blend can be parsed. 

157 """ 

158 # 1. Normalize one path and multiple paths to the same traversal form. 

159 data_paths = [data_path] if isinstance(data_path, str) else list(data_path) 

160 

161 # 2. Use distributed walking only after the process group is available. 

162 # Before initialization, one process walks all configured directories. 

163 try: 

164 rank = int(dist.get_rank()) 

165 world_size = int(dist.get_world_size()) 

166 except (RuntimeError, ValueError): 

167 rank, world_size = 0, 1 

168 # Original and replacement workers need the same source order even when peers are parked. 

169 use_distributed_walk = distributed_walk and world_size > 1 and not is_recovery_enabled() 

170 

171 # 3. Accept a direct prefix, or recursively discover prefixes in a directory. 

172 file_paths: list[str] = [] 

173 for current_path in data_paths: 

174 if file_suffix == ".arrow" and current_path.endswith(file_suffix) and os.path.isfile(current_path): 

175 file_paths.append(current_path) 

176 continue 

177 if file_suffix == ".bin" and os.path.isfile(current_path + ".bin"): 

178 file_paths.append(current_path) 

179 continue 

180 if not os.path.isdir(current_path): 

181 # Keep args.data_path unchanged when filesystem discovery 

182 # returns no files. This preserves explicit forms such as 

183 # ["30", prefix_a, "70", prefix_b] for the blend parser. 

184 original_paths = list(data_paths) 

185 return original_paths 

186 

187 file_paths.extend(_discover_indexed_paths(current_path, rank, world_size, use_distributed_walk, file_suffix)) 

188 

189 if not file_paths: 

190 raise ValueError(f"data_path {data_paths!r} has no data file ending with {file_suffix}") 

191 

192 if len(file_paths) == 1: 

193 return file_paths 

194 

195 if file_suffix == ".arrow": 

196 # Every rank must blend files in the same order after directory discovery. 

197 file_paths.sort() 

198 else: 

199 # 4. Prefer the numeric shard order encoded by the corpus filenames. 

200 # Unknown naming schemes remain usable in their original walk order. 

201 try: 

202 def numeric_shard_key(path: str) -> tuple[int, int]: 

203 """Extract numeric corpus and shard identifiers from a path.""" 

204 path_parts = os.path.basename(path).split("_") 

205 return int(path_parts[2]), int(path_parts[-1]) 

206 

207 file_paths.sort(key=numeric_shard_key) 

208 except (IndexError, TypeError, ValueError): 

209 logger.warning("Cannot sort indexed files with the numeric filename rule; keeping walk order") 

210 

211 # 5. Automatically discovered sources use equal blend weights. 

212 weighted_paths = [value for path in file_paths for value in ("1", path)] 

213 return weighted_paths 

214 

215 

216class LazyDatasetProxy: 

217 """Construct and cache a Dataset when it is first accessed.""" 

218 

219 def __init__( 

220 self, 

221 dataset_factory: Callable[[], Any], 

222 *, 

223 unique_identifiers: Any, 

224 ) -> None: 

225 """Store lightweight metadata without constructing the Dataset. 

226 

227 Args: 

228 dataset_factory: Callable that constructs the real Dataset on first 

229 sample access. 

230 unique_identifiers: Stable Dataset cache identity assembled from 

231 construction inputs. 

232 """ 

233 self._dataset_factory = dataset_factory 

234 self._unique_identifiers = unique_identifiers 

235 self._dataset = None 

236 

237 def __len__(self) -> int: 

238 """Initialize the Dataset and return its length.""" 

239 return len(self._get_dataset()) 

240 

241 def __getitem__(self, index: int) -> Mapping[str, Any]: 

242 """Construct the Dataset if necessary and read one sample.""" 

243 dataset = self._get_dataset() 

244 sample = dataset[index] 

245 return sample 

246 

247 @property 

248 def unique_identifiers(self) -> Any: 

249 """Initialize the Dataset and return its cache identity.""" 

250 return self._get_dataset().unique_identifiers 

251 

252 def _get_dataset(self) -> Any: 

253 """Construct the Dataset once and reuse it for later accesses.""" 

254 if self._dataset is None: 

255 identifiers = self._unique_identifiers if isinstance(self._unique_identifiers, Mapping) else {} 

256 logger.debug( 

257 "Initializing lazy Dataset: class=%s, path=%s, split=%s, samples=%s", 

258 identifiers.get("class"), identifiers.get("dataset_path"), identifiers.get("index_split"), 

259 identifiers.get("num_samples"), 

260 ) 

261 self._dataset = self._dataset_factory() 

262 return self._dataset 

263 

264 

265def _get_prefixes_weights_and_sizes_for_blend( 

266 blend: Sequence[str], 

267 target_num_samples_per_split: Sequence[int], 

268 blend_mode: BlendMode, 

269 dataset_margin: float, 

270) -> tuple[list[str], list[float], list[list[int]]]: 

271 """Determine each source's contribution to the blended Dataset splits. 

272 

273 Args: 

274 blend: Alternating ``weight, prefix`` pairs for each data source. 

275 target_num_samples_per_split: Requested ``[train, validation, test]`` sample counts. 

276 blend_mode: ``"no"`` for normalized weighted blending; ``"inter"`` or ``"intra"`` for simple blending. 

277 dataset_margin: Extra sample margin applied only to normalized weighted blending. 

278 

279 Returns: 

280 ``(prefixes, weights, sizes_per_dataset)``, where ``sizes_per_dataset[source][split]`` is the number of 

281 samples requested from one source for the train, validation, or test split. 

282 

283 Example: 

284 Regular: ``["30", "/data/a", "70", "/data/b"]`` with sizes ``[1000, 100, 0]`` and margin ``1.005`` 

285 -> ``(["/data/a", "/data/b"], [0.3, 0.7], [[302, 31, 0], [704, 71, 0]])``. 

286 Simple: ``["1", "/data/a", "1", "/data/b"]`` with sizes ``[1000, 100, 0]`` 

287 -> ``(["/data/a", "/data/b"], [1, 1], [[500, 50, 0], [500, 50, 0]])``. 

288 """ 

289 if len(blend) % 2 != 0: 

290 raise ValueError("Dataset blend must contain alternating weight/prefix pairs") 

291 

292 # standard blend 

293 if blend_mode == "no": 

294 weights, prefixes = zip(*[(float(blend[index]), blend[index + 1].strip()) for index in range(0, len(blend), 2)]) 

295 weight_sum = float(sum(weights)) 

296 weights = [weight / weight_sum for weight in weights] 

297 sizes_per_dataset = [ 

298 [ 

299 int(math.ceil(target_num_samples * weight * dataset_margin)) 

300 for target_num_samples in target_num_samples_per_split 

301 ] 

302 for weight in weights 

303 ] 

304 return prefixes, weights, sizes_per_dataset 

305 

306 # inter/intra blend 

307 weights, prefixes = zip(*[(int(blend[index]), blend[index + 1].strip()) for index in range(0, len(blend), 2)]) 

308 sizes_per_dataset = [ 

309 [int(math.ceil(target_num_samples / len(weights))) for target_num_samples in target_num_samples_per_split] 

310 for _ in weights 

311 ] 

312 return prefixes, weights, sizes_per_dataset 

313 

314 

315def _build_low_level_dataset_and_split_indices( 

316 dataset_type: type, 

317 dataset_path: str, 

318 split_matrix: SplitMatrix, 

319 config: GPTDatasetConfig, 

320) -> tuple[Any, list[np.ndarray | None]]: 

321 """Build one low-level Dataset and calculate its requested split indices.""" 

322 low_level_dataset = dataset_type.build_low_level_dataset(dataset_path, config) 

323 num_elements = dataset_type.numel_low_level_dataset(low_level_dataset) 

324 

325 split_indices = [] 

326 for split_range in split_matrix: 

327 if split_range is None: 

328 split_indices.append(None) 

329 continue 

330 

331 begin = int(round(split_range[0] * num_elements)) 

332 end = int(round(split_range[1] * num_elements)) 

333 split_indice = np.arange(start=begin, stop=end, step=1, dtype=np.int32) 

334 split_indices.append(split_indice) 

335 

336 # (low_level_dataset, [train_indices, valid_indices, test_indices]). 

337 dataset_and_split_indices = (low_level_dataset, split_indices) 

338 return dataset_and_split_indices 

339 

340 

341class IndexedDatasetSplitBuilder: 

342 """Build indexed Dataset splits with one shared distributed context.""" 

343 

344 def __init__(self, dataloader_context: DataLoaderParallelContext) -> None: 

345 """Store the DataLoader ownership policy once for all build steps.""" 

346 self.dataloader_context = dataloader_context 

347 

348 def build( 

349 self, 

350 dataset_type: type, 

351 train_valid_test_num_samples: Sequence[int] | None, 

352 config: GPTDatasetConfig, 

353 blend_mode: BlendMode, 

354 ) -> DatasetSplits: 

355 """Build mock, shared-blend, or independent-blend Dataset splits.""" 

356 if train_valid_test_num_samples is None: 

357 raise ValueError("train_valid_test_num_samples must be configured for indexed Datasets") 

358 

359 if len(train_valid_test_num_samples) != len(_Split): 

360 raise ValueError("train_valid_test_num_samples must contain exactly three values") 

361 

362 if any(size < 0 for size in train_valid_test_num_samples): 

363 raise ValueError("train_valid_test_num_samples must be non-negative") 

364 

365 if blend_mode not in {"no", "inter", "intra"}: 

366 raise ValueError(f"Unsupported blend mode: {blend_mode!r}") 

367 

368 if config.mock != (dataset_type is MockGPTDataset): 

369 raise ValueError("mock_data must match the selected MockGPTDataset class") 

370 

371 if not config.mock and (blend_mode == "no") != (dataset_type is GPTDataset): 

372 raise ValueError("simple_blend='no' is only for GPTDataset; other Datasets require inter/intra") 

373 

374 if dataset_type is GPTDataset: 

375 # Reject invalid options before cache builders and readers can diverge. 

376 GPTDataset.validate_config(config) 

377 

378 logger.debug( 

379 "Building indexed splits: dataset=%s, num_samples=%s, mock=%s, blend_mode=%s, lazy=%s", 

380 dataset_type.__name__, 

381 tuple(train_valid_test_num_samples), 

382 config.mock, 

383 blend_mode, 

384 config.data_lazy_load, 

385 ) 

386 if config.mock: 

387 return self._build_mock_dataset_splits(dataset_type, train_valid_test_num_samples, config) 

388 

389 if config.blend: 

390 if config.split_matrix is None: 

391 raise ValueError("A shared blend requires blend and split_matrix") 

392 

393 return self._build_splits_from_blend( 

394 dataset_type, config.blend, config.split_matrix, train_valid_test_num_samples, config, blend_mode 

395 ) 

396 

397 if config.blend_per_split: 

398 return self._build_splits_from_independent_blends( 

399 dataset_type, train_valid_test_num_samples, config, blend_mode 

400 ) 

401 raise ValueError("One of blend or blend_per_split must be configured") 

402 

403 def _build_mock_dataset_splits( 

404 self, 

405 dataset_type: type, 

406 sizes: Sequence[int], 

407 config: GPTDatasetConfig, 

408 ) -> DatasetSplits: 

409 """Build generated train, validation, and test Datasets.""" 

410 datasets = [] 

411 for split, size in zip(_Split, sizes): 

412 if size == 0: 

413 datasets.append(None) 

414 continue 

415 

416 dataset_factory = partial(dataset_type, None, None, None, int(size), split, config) 

417 mock_dataset = self._build_dataset_for_dataloader(dataset_factory, barrier_needed=False) 

418 datasets.append(mock_dataset) 

419 return cast(DatasetSplits, tuple(datasets)) 

420 

421 def _build_splits_from_blend( 

422 self, 

423 dataset_type: type, 

424 blend: Sequence[str], 

425 split_matrix: SplitMatrix, 

426 sizes: Sequence[int], 

427 config: GPTDatasetConfig, 

428 blend_mode: BlendMode, 

429 ) -> DatasetSplits: 

430 """ 

431 Parse one blend and dispatch it to the single- or multiple-source path. 

432 Low level: Index -> Mid level: GPTDataset -> Final: Blend. 

433 """ 

434 if len(blend) == 1: 

435 return self._build_mid_level_dataset_splits(dataset_type, blend[0], split_matrix, sizes, config) 

436 

437 prefixes, weights, sizes_per_dataset = _get_prefixes_weights_and_sizes_for_blend( 

438 blend, sizes, blend_mode, config.dataset_margin 

439 ) 

440 logger.debug( 

441 "Resolved blend: mode=%s, sources=%d, first_weight=%s, first_source_sizes=%s", 

442 blend_mode, 

443 len(prefixes), 

444 weights[0], 

445 sizes_per_dataset[0], 

446 ) 

447 dataset_splits = self._build_multiple_source_splits( 

448 dataset_type, prefixes, weights, sizes_per_dataset, split_matrix, config, blend_mode 

449 ) 

450 return dataset_splits 

451 

452 def _build_splits_from_independent_blends( 

453 self, 

454 dataset_type: type, 

455 sizes: Sequence[int], 

456 config: GPTDatasetConfig, 

457 blend_mode: BlendMode, 

458 ) -> DatasetSplits: 

459 """Build each split from its own data-source distribution.""" 

460 if config.blend_per_split is None or len(config.blend_per_split) != len(_Split): 

461 raise ValueError("Independent blends require one blend per split") 

462 

463 datasets = [] 

464 for split_index, blend in enumerate(config.blend_per_split): 

465 if not blend: 

466 datasets.append(None) 

467 continue 

468 

469 split_matrix: list[SplitRange | None] = [None] * len(_Split) 

470 split_matrix[split_index] = (0.0, 1.0) 

471 split_sizes = [0] * len(_Split) 

472 split_sizes[split_index] = int(sizes[split_index]) 

473 split_datasets = self._build_splits_from_blend( 

474 dataset_type, blend, split_matrix, split_sizes, config, blend_mode 

475 ) 

476 datasets.append(split_datasets[split_index]) 

477 return cast(DatasetSplits, tuple(datasets)) 

478 

479 def _build_multiple_source_splits( 

480 self, 

481 dataset_type: type, 

482 prefixes: Sequence[str], 

483 weights: Sequence[float], 

484 sizes_per_dataset: Sequence[Sequence[int]], 

485 split_matrix: SplitMatrix, 

486 config: GPTDatasetConfig, 

487 blend_mode: BlendMode, 

488 ) -> DatasetSplits: 

489 """Build each source's mid-level splits and assemble top-level blends. 

490 

491 Example with two sources:: 

492 

493 prefixes = ["/data/books", "/data/code"] 

494 sizes_per_dataset = [[80, 10, 0], [20, 5, 0]] 

495 

496 Offline preparation, tokenize and optionally pre-pack raw records: 

497 books.jsonl -> tokenizer -> token IDs -> pack to 2049-token records 

498 -> /data/books.idx + /data/books.bin 

499 code.jsonl -> tokenizer -> token IDs -> pack to 2049-token records 

500 -> /data/code.idx + /data/code.bin 

501 

502 Low-level, open one IndexedDataReader per prefix and read one sequence (uint16 example): 

503 books.idx: sequence_lengths[1] = 2049, sequence_pointers[1] = 4098 

504 books_reader[1] -> books.bin[offset=4098, count=2049] -> text token IDs 

505 

506 Mid-level, organize tokens into training records (input_ids, labels, and masks), 

507 with one GPTDataset/GPTFromMRDataset per source and split: 

508 books_train[0] -> split indices[0] = 1 -> books_reader[1] 

509 -> input_ids = text[:-1], labels = text[1:] 

510 datasets_per_source = [ 

511 (books_train[80], books_valid[10], None), 

512 (code_train[20], code_valid[5], None), 

513 ] 

514 

515 Transpose source-major tuples into split-major components: 

516 train components = [books_train, code_train], total size = 100 

517 valid components = [books_valid, code_valid], total size = 15 

518 test components = [], size = 0 

519 

520 Blend-level, select the source and source-local sample for each train index, for example: 

521 dataset_index = [0, 1, ...] 

522 dataset_sample_index = [0, 0, ...] 

523 global sample 0 -> (dataset_id=0, sample_id=0) -> books_train[0] 

524 global sample 1 -> (dataset_id=1, sample_id=0) -> code_train[0] 

525 

526 ``BlendedDataset[i]`` reads ``dataset_index[i]`` and ``dataset_sample_index[i]``; 

527 ``SimpleBlendedDataset[i]`` reads ``_locations[i] = (dataset_id, sample_id)``. 

528 Both return ``datasets[dataset_id][sample_id]``. 

529 

530 final result = (blended_train[100], blended_valid[15], None) 

531 """ 

532 # pylint: disable=too-many-locals 

533 datasets_per_source = [] 

534 logger.debug("Building %d indexed Dataset sources", len(prefixes)) 

535 # TODO: Add a separate cache-prebuild phase that assigns source_index % world_size to each rank, 

536 # synchronizes failures, and atomically writes a completion manifest before Dataset construction. 

537 

538 # books -> (books_train, books_valid, None), then code -> (code_train, code_valid, None). 

539 for prefix, sizes_for_source in zip(prefixes, sizes_per_dataset): 

540 source_datasets = self._build_mid_level_dataset_splits( 

541 dataset_type, prefix, split_matrix, sizes_for_source, config 

542 ) 

543 datasets_per_source.append(source_datasets) 

544 

545 blended_sizes = [sum(split_sizes) for split_sizes in zip(*sizes_per_dataset)] 

546 blended_splits = [] 

547 for split_index, (split_range, size) in enumerate(zip(split_matrix, blended_sizes)): 

548 if split_range is None or size == 0: 

549 blended_splits.append(None) 

550 continue 

551 

552 component_datasets = [datasets[split_index] for datasets in datasets_per_source] 

553 missing_datasets = [dataset is None for dataset in component_datasets] 

554 if any(missing_datasets) and not all(missing_datasets): 

555 raise ValueError("Enabled sources must either all build or all remain None on a rank") 

556 

557 component_datasets = [dataset for dataset in component_datasets if dataset is not None] 

558 if blend_mode == "no": 

559 dataset_factory = partial(BlendedDataset, component_datasets, weights, int(size), config) 

560 else: 

561 dataset_factory = partial(SimpleBlendedDataset, component_datasets, int(size), blend_mode) 

562 blended_dataset = self._build_dataset_for_dataloader(dataset_factory, barrier_needed=True) 

563 blended_splits.append(blended_dataset) 

564 

565 dataset_splits = cast(DatasetSplits, tuple(blended_splits)) 

566 split_types = tuple(type(split).__name__ if split is not None else None for split in dataset_splits) 

567 logger.debug("Built blended splits=%s", split_types) 

568 return dataset_splits 

569 

570 def _build_mid_level_dataset_splits( 

571 self, 

572 dataset_type: type, 

573 dataset_path: str, 

574 split_matrix: SplitMatrix, 

575 sizes_for_source: Sequence[int], 

576 config: GPTDatasetConfig, 

577 ) -> DatasetSplits: 

578 """Build each mid-level split from one low-level indexed Dataset.""" 

579 # pylint: disable=too-many-locals 

580 if ( 

581 config.data_lazy_load 

582 and self.dataloader_context.distributed_enabled 

583 and not ( 

584 self.dataloader_context.data_index_cache 

585 or self.dataloader_context.build_on_rank() 

586 ) 

587 ): 

588 return cast(DatasetSplits, (None, None, None)) 

589 

590 low_level_dataset = None 

591 split_indices: list[np.ndarray | None] = [None] * len(split_matrix) 

592 if not config.data_lazy_load: 

593 low_level_dataset, split_indices = _build_low_level_dataset_and_split_indices( 

594 dataset_type, dataset_path, split_matrix, config 

595 ) 

596 

597 datasets = [] 

598 for split, split_range, indices, size in zip(_Split, split_matrix, split_indices, sizes_for_source): 

599 if split_range is None or size == 0: 

600 datasets.append(None) 

601 continue 

602 

603 size = int(size) 

604 if config.data_lazy_load: 

605 lazy_builder = self._build_lazy_mid_level_dataset_split 

606 dataset_factory = partial(lazy_builder, dataset_type, dataset_path, split, split_range, size, config) 

607 unique_identifiers = dataset_type.build_unique_identifiers(dataset_path, size, split, config) 

608 mid_level_dataset = LazyDatasetProxy(dataset_factory, unique_identifiers=unique_identifiers) 

609 else: 

610 dataset_factory = partial(dataset_type, low_level_dataset, dataset_path, indices, size, split, config) 

611 mid_level_dataset = self._build_dataset_for_dataloader( 

612 dataset_factory, barrier_needed=dataset_type is GPTDataset 

613 ) 

614 datasets.append(mid_level_dataset) 

615 return cast(DatasetSplits, tuple(datasets)) 

616 

617 def _build_lazy_mid_level_dataset_split( 

618 self, 

619 dataset_type: type, 

620 dataset_path: str, 

621 split: _Split, 

622 split_range: SplitRange, 

623 size: int, 

624 config: GPTDatasetConfig, 

625 ) -> Any | None: 

626 """Apply distributed construction when a lazy split is first accessed.""" 

627 

628 def _dataset_factory() -> Any: 

629 """Build the low-level Dataset and one lazy split on first access.""" 

630 low_level_dataset, split_indices = _build_low_level_dataset_and_split_indices( 

631 dataset_type, dataset_path, [split_range], config 

632 ) 

633 mid_level_dataset = dataset_type(low_level_dataset, dataset_path, split_indices[0], size, split, config) 

634 return mid_level_dataset 

635 

636 local_dataset = self._build_dataset_for_dataloader(_dataset_factory, barrier_needed=False) 

637 return local_dataset 

638 

639 def _build_dataset_for_dataloader( 

640 self, 

641 dataset_factory: Callable[[], Any], 

642 *, 

643 barrier_needed: bool, 

644 ) -> Any | None: 

645 """Build one Dataset with the shared DataLoader context.""" 

646 local_dataset = build_dataset_for_dataloader( 

647 dataset_factory, 

648 self.dataloader_context, 

649 barrier_needed=barrier_needed, 

650 ) 

651 return local_dataset 

652 

653 

654class IndexedPretrainDatasetBuilder: 

655 """Build GPT pretraining datasets from indexed token files. 

656 

657 Its ``build`` method keeps the indexed provider flow visible while each 

658 private step can be implemented and reviewed independently. 

659 """ 

660 

661 def __init__( 

662 self, 

663 *, 

664 data_path: DataPath, 

665 data_config: Mapping[str, Any], 

666 train_valid_test_num_samples: Sequence[int], 

667 dataloader_context: DataLoaderParallelContext | None = None, 

668 ) -> None: 

669 """Store the inputs required by the indexed pretraining build. 

670 

671 Args: 

672 data_path: Indexed prefix, directory, or weighted paths. May be 

673 omitted when mock data is enabled. 

674 data_config: Indexed pretraining build options. 

675 train_valid_test_num_samples: Trainer-derived target sizes. 

676 dataloader_context: DataLoader ownership and synchronization policy. 

677 """ 

678 self.data_path = data_path 

679 self.data_config = data_config 

680 self.train_valid_test_num_samples = train_valid_test_num_samples 

681 self.dataloader_context = dataloader_context or DataLoaderParallelContext( 

682 data_index_cache=bool(data_config.get("data_index_cache", False)) 

683 ) 

684 self.split_builder = IndexedDatasetSplitBuilder(self.dataloader_context) 

685 

686 def build(self) -> DatasetSplits: 

687 """Build train, validation, and test indexed datasets. 

688 

689 Returns: 

690 Train, validation, and test datasets. 

691 """ 

692 # Discover indexed files and add their default blend weights. 

693 # Mock Datasets generate their samples and do not need filesystem 

694 # discovery. Real indexed Datasets still require an explicit path. 

695 mock_data = bool(self.data_config.get("mock_data", False)) 

696 logger.debug("Building indexed Dataset: mock=%s, data_path=%s", mock_data, self.data_path) 

697 if mock_data: 

698 data_paths = [] 

699 else: 

700 if self.data_path is None: 

701 raise ValueError("data_path is required when mock_data is false") 

702 

703 data_paths = self._resolve_data_paths() 

704 

705 # Normalize Dataset options. Sample counts remain separate and are 

706 # passed directly to the split builder. 

707 config = self._build_gpt_dataset_config(data_paths) 

708 logger.debug( 

709 "Indexed Dataset config: simple_blend=%s, lazy=%s, shared_blend=%s, independent_blends=%s", 

710 config.simple_blend, config.data_lazy_load, bool(config.blend), bool(config.blend_per_split), 

711 ) 

712 

713 # Follow the Provider boundary: instruction and pretraining datasets 

714 # share one public entry but own separate construction pipelines. 

715 dataset_splits = self._build_dataset_splits(config) 

716 split_types = tuple(type(split).__name__ if split is not None else None for split in dataset_splits) 

717 logger.debug("Built indexed Dataset splits=%s", split_types) 

718 return dataset_splits 

719 

720 def _build_dataset_splits(self, config: GPTDatasetConfig) -> DatasetSplits: 

721 """Select the instruction or indexed-pretraining Dataset pipeline.""" 

722 if bool(self.data_config.get("is_instruction_dataset", False)): 

723 logger.debug("Selecting instruction Dataset pipeline") 

724 dataset_splits = self._build_instruction_dataset_splits(config) 

725 return dataset_splits 

726 

727 dataset_splits = self._build_pretrain_dataset_splits(config) 

728 return dataset_splits 

729 

730 def _build_pretrain_dataset_splits(self, config: GPTDatasetConfig) -> DatasetSplits: 

731 """Build GPT pretraining splits through the selected Dataset and blend types.""" 

732 # Select GPTDataset / MockGPTDataset / GPTFromMRDataset. 

733 dataset_type = self._select_dataset_type(config) 

734 

735 # Select the standard or simple blended Dataset builder. 

736 split_builder = self._select_split_builder(config) 

737 logger.debug("Selected indexed Dataset: type=%s, split_mode=%s", dataset_type.__name__, config.simple_blend) 

738 

739 # Build train, validation, and test datasets. 

740 datasets = split_builder( 

741 dataset_type=dataset_type, 

742 train_valid_test_num_samples=self.train_valid_test_num_samples, 

743 config=config, 

744 ) 

745 return datasets 

746 

747 def _build_instruction_dataset_splits(self, config: GPTDatasetConfig) -> DatasetSplits: 

748 """Build packed instruction splits through the configured implementation. 

749 

750 The concrete packed-dataset implementation remains outside this provider. 

751 

752 Raises: 

753 NotImplementedError: If no instruction Dataset builder is configured. 

754 ValueError: If the configured builder does not return three splits. 

755 """ 

756 instruction_builder = self.data_config.get("instruction_dataset_builder") 

757 if not callable(instruction_builder): 

758 raise NotImplementedError( 

759 "is_instruction_dataset=True requires an instruction_dataset_builder" 

760 ) 

761 

762 instruction_split_builder: InstructionSplitBuilder = instruction_builder 

763 

764 data_prefix = config.blend if config.blend is not None else self.data_path 

765 datasets = instruction_split_builder( 

766 data_prefix=data_prefix, 

767 splits_string=config.split, 

768 train_valid_test_num_samples=self.train_valid_test_num_samples, 

769 seq_length=config.sequence_length, 

770 seed=config.random_seed, 

771 tokenizer=config.tokenizer, 

772 ) 

773 if not isinstance(datasets, Sequence) or len(datasets) != 3: 

774 raise ValueError("instruction_dataset_builder must return train, validation, and test") 

775 

776 dataset_splits = (datasets[0], datasets[1], datasets[2]) 

777 return dataset_splits 

778 

779 def _resolve_data_paths(self) -> list[str]: 

780 """Discover source paths for the selected offline Dataset type.""" 

781 if self.data_path is None: 

782 raise ValueError("data_path is required when mock_data is false") 

783 

784 dataset_type = resolve_dataset_type(self.data_config["low_level_dataset"]) 

785 data_paths = resolve_data_paths( 

786 self.data_path, 

787 distributed_walk=bool(self.data_config["distributed_walk"]), 

788 file_suffix=".arrow" if issubclass(dataset_type, SFTFromMRDataset) else ".bin", 

789 ) 

790 return data_paths 

791 

792 def _build_gpt_dataset_config(self, data_paths: Sequence[str]) -> GPTDatasetConfig: 

793 """Delegate GPT Dataset option normalization.""" 

794 config = build_gpt_dataset_config(data_paths, self.data_config) 

795 return config 

796 

797 @staticmethod 

798 def _select_dataset_type(config: GPTDatasetConfig) -> type: 

799 """Select GPT, Mock GPT, or MR GPT Dataset.""" 

800 return config.low_level_dataset 

801 

802 def _select_split_builder(self, config: GPTDatasetConfig) -> SplitBuilder: 

803 """ 

804 Select the standard or simple train/valid/test builder. 

805 "no": BlendedDataset 

806 "inter/intra": SimpleBlendedDataset 

807 """ 

808 if config.simple_blend == "no": 

809 split_builder = partial(self.split_builder.build, blend_mode="no") 

810 return split_builder 

811 

812 if config.simple_blend not in {"inter", "intra"}: 

813 raise ValueError("simple_blend must be one of 'no', 'inter', or 'intra'; " 

814 f"got {config.simple_blend!r}" 

815 ) 

816 

817 split_builder = partial(self.split_builder.build, blend_mode=config.simple_blend) 

818 return split_builder