Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / online / mapping.py: 80%

350 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 finite integer-indexed Online sources.""" 

16 

17from __future__ import annotations 

18 

19import glob 

20import json 

21import os 

22from collections.abc import Callable, Mapping, Sequence 

23from contextlib import ExitStack 

24from typing import Any 

25 

26import numpy as np 

27from numpy.random import RandomState 

28 

29from hyper_parallel.data.constants import ONLINE_SOURCE_PATH_KEY, ONLINE_SPLIT_COUNT, ONLINE_SPLIT_NAMES 

30from hyper_parallel.data.dataset_logging import get_dataset_logger 

31from hyper_parallel.data.online.source import ( 

32 OnlineDataPath, 

33 OnlinePathSpec, 

34 _OnlineSourceBuilder, 

35) 

36 

37logger = get_dataset_logger(__name__) 

38 

39SampleTransform = Callable[[Any], list[Any]] 

40 

41 

42def build_online_mapping_source( 

43 *, 

44 data_config: Mapping[str, Any], 

45 data_path: OnlineDataPath | None = None, 

46 sample_filter: Callable[[Mapping[str, Any]], bool] | None = None, 

47 train_valid_test_num_samples: Sequence[int] | None = None, 

48 sampler_type: str = "single", 

49) -> Any: 

50 """Build a finite integer-indexed Online source. 

51 

52 Args: 

53 data_config: Online source options. 

54 data_path: Local path, Hub dataset ID, or pre-split path mapping. Use 

55 ``data_config.sources`` instead for multiple sources. 

56 sampler_type: Cyclic leaves shuffle and repetition across epochs to the sampler. 

57 sample_filter: Optional raw-sample predicate applied before indexing. 

58 train_valid_test_num_samples: Optional target sample count for each 

59 train, validation, and test split. 

60 

61 Returns: 

62 One Mapping Dataset or a train-valid-test tuple. 

63 """ 

64 dataset_builder = _OnlineMappingSourceBuilder(data_path, data_config, train_valid_test_num_samples, sampler_type) 

65 mapping_source = dataset_builder.build_source(sample_filter=sample_filter) 

66 return mapping_source 

67 

68 

69class MappingTransformDataset: 

70 """Apply a sample transform lazily to an integer-indexed source Dataset.""" 

71 

72 def __init__(self, source_dataset: Any, transform: SampleTransform) -> None: 

73 """Store the source Dataset and its lazy sample transform.""" 

74 self.source_dataset = source_dataset 

75 self.transform = transform 

76 

77 @classmethod 

78 def apply(cls, source_dataset: Any, transform: SampleTransform) -> Any: 

79 """Transform one Mapping Dataset or each available split. 

80 

81 Args: 

82 source_dataset: One Mapping Dataset or a train-valid-test tuple. 

83 transform: Transform from one RawSample to zero, one, or many ModelSamples. 

84 

85 Returns: 

86 A transformed Mapping Dataset or transformed split tuple. 

87 """ 

88 if isinstance(source_dataset, tuple) and len(source_dataset) == ONLINE_SPLIT_COUNT: 

89 transformed_splits = [] 

90 for split_dataset in source_dataset: 

91 transformed_dataset = None 

92 if split_dataset is not None: 

93 transformed_dataset = cls(split_dataset, transform) 

94 transformed_splits.append(transformed_dataset) 

95 

96 mapping_splits = (transformed_splits[0], transformed_splits[1], transformed_splits[2]) 

97 return mapping_splits 

98 

99 if source_dataset is None: 

100 return None 

101 

102 mapping_dataset = cls(source_dataset, transform) 

103 return mapping_dataset 

104 

105 def __len__(self) -> int: 

106 """Return the source Dataset length.""" 

107 dataset_length = len(self.source_dataset) 

108 return dataset_length 

109 

110 def get_item(self, index: int) -> list[Any]: 

111 """Transform one source index into zero, one, or many output samples.""" 

112 dataset_length = len(self.source_dataset) 

113 

114 if index < 0: 

115 index += dataset_length 

116 

117 if index < 0 or index >= dataset_length: 

118 raise IndexError("Online Mapping Dataset index out of range") 

119 

120 # One raw record may expand into zero, one, or several model samples. 

121 raw_sample = self.source_dataset[index] 

122 transformed_samples = self.transform(raw_sample) 

123 logger.debug( 

124 "Online sample source_index=%s sample_id=%s", index, raw_sample.get("id"), 

125 enabled=True, 

126 ) 

127 

128 if not isinstance(transformed_samples, list): 

129 raise TypeError("Online Mapping sample transform must return a list") 

130 

131 return transformed_samples 

132 

133 def __getitem__(self, index: int) -> Any: 

134 """Return exactly one sample for fixed-size DataLoader consumers.""" 

135 transformed_samples = self.get_item(index) 

136 

137 if not transformed_samples: 

138 raise ValueError( 

139 "An empty transform result requires source filtering or TokenBatchLoader" 

140 ) 

141 

142 if len(transformed_samples) != 1: 

143 raise ValueError("A multi-sample transform result requires TokenBatchLoader") 

144 

145 transformed_sample = transformed_samples[0] 

146 return transformed_sample 

147 

148 

149class _JsonlMappingSource: 

150 """Read heterogeneous JSONL records without imposing an Arrow schema.""" 

151 

152 def __init__( 

153 self, 

154 data_files: Sequence[str], 

155 sample_filter: Callable[[Mapping[str, Any]], bool] | None, 

156 ) -> None: 

157 """Index non-empty JSONL records by file path and byte offset.""" 

158 self._record_locations: list[tuple[str, int]] = [] 

159 self._record_start = 0 

160 self._record_end = 0 

161 self._file_handles: dict[str, Any] = {} 

162 self._file_stack = ExitStack() 

163 self._reader_process_id = os.getpid() 

164 

165 for data_file in data_files: 

166 self._index_file(data_file, sample_filter) 

167 self._record_end = len(self._record_locations) 

168 

169 def __len__(self) -> int: 

170 """Return the number of indexed JSONL records.""" 

171 record_count = self._record_end - self._record_start 

172 return record_count 

173 

174 def __getitem__(self, index: int) -> dict[str, Any]: 

175 """Deserialize one record and attach its source file context.""" 

176 record_count = len(self) 

177 

178 if index < 0: 

179 index += record_count 

180 

181 if index < 0 or index >= record_count: 

182 raise IndexError("Online JSONL source index out of range") 

183 

184 record_index = self._record_start + index 

185 data_file, byte_offset = self._record_locations[record_index] 

186 file_handle = self._get_file_handle(data_file) 

187 file_handle.seek(byte_offset) 

188 raw_record = file_handle.readline() 

189 source_record = self._parse_record(raw_record, data_file) 

190 source_record[ONLINE_SOURCE_PATH_KEY] = data_file 

191 return source_record 

192 

193 def split_by_percentages( 

194 self, 

195 percentages: Sequence[int], 

196 ) -> tuple[_JsonlMappingSource | None, _JsonlMappingSource | None, _JsonlMappingSource | None]: 

197 """Create train, validation, and test views over the filtered index.""" 

198 record_count = len(self) 

199 train_end = int(round(percentages[0] * record_count / 100.0)) 

200 valid_end = int(round((percentages[0] + percentages[1]) * record_count / 100.0)) 

201 split_ranges = ((0, train_end), (train_end, valid_end), (valid_end, record_count)) 

202 

203 split_sources = [] 

204 for percentage, (split_start, split_end) in zip(percentages, split_ranges): 

205 split_source = None 

206 if percentage > 0: 

207 split_source = self._create_view( 

208 self._record_locations, 

209 self._record_start + split_start, 

210 self._record_start + split_end, 

211 ) 

212 split_sources.append(split_source) 

213 jsonl_splits = (split_sources[0], split_sources[1], split_sources[2]) 

214 return jsonl_splits 

215 

216 def __getstate__(self) -> dict[str, Any]: 

217 """Exclude process-local file handles when DataLoader workers pickle the source.""" 

218 source_state = dict(self.__dict__) 

219 source_state["_file_handles"] = {} 

220 source_state["_file_stack"] = ExitStack() 

221 source_state["_reader_process_id"] = None 

222 return source_state 

223 

224 def _index_file( 

225 self, 

226 data_file: str, 

227 sample_filter: Callable[[Mapping[str, Any]], bool] | None, 

228 ) -> None: 

229 """Record byte offsets and evaluate an optional raw-sample filter.""" 

230 with open(data_file, "rb") as file_handle: 

231 while True: 

232 byte_offset = file_handle.tell() 

233 raw_record = file_handle.readline() 

234 if not raw_record: 

235 break 

236 if not raw_record.strip(): 

237 continue 

238 if sample_filter is not None: 

239 source_record = self._parse_record(raw_record, data_file) 

240 if not sample_filter(source_record): 

241 continue 

242 self._record_locations.append((data_file, byte_offset)) 

243 

244 @classmethod 

245 def _create_view( 

246 cls, record_locations: list[tuple[str, int]], start: int, end: int, 

247 ) -> _JsonlMappingSource: 

248 """Create a zero-copy view over indexed records with independent readers.""" 

249 split_source = cls.__new__(cls) 

250 split_source._record_locations = record_locations 

251 split_source._record_start = start 

252 split_source._record_end = end 

253 split_source._file_handles = {} 

254 split_source._file_stack = ExitStack() 

255 split_source._reader_process_id = os.getpid() 

256 return split_source 

257 

258 def _get_file_handle(self, data_file: str) -> Any: 

259 """Return a binary reader owned by the current DataLoader process.""" 

260 process_id = os.getpid() 

261 if self._reader_process_id != process_id: 

262 self._close_file_handles() 

263 self._reader_process_id = process_id 

264 

265 file_handle = self._file_handles.get(data_file) 

266 if file_handle is None: 

267 file_handle = self._file_stack.enter_context(open(data_file, "rb")) 

268 self._file_handles[data_file] = file_handle 

269 return file_handle 

270 

271 def _close_file_handles(self) -> None: 

272 """Close readers inherited from another process or opened locally.""" 

273 self._file_stack.close() 

274 self._file_stack = ExitStack() 

275 self._file_handles = {} 

276 

277 @staticmethod 

278 def _parse_record(raw_record: bytes, data_file: str) -> dict[str, Any]: 

279 """Decode one JSON object while preserving heterogeneous nested values.""" 

280 try: 

281 source_record = json.loads(raw_record) 

282 except (UnicodeDecodeError, json.JSONDecodeError) as error: 

283 raise ValueError(f"Invalid JSONL record in {data_file}") from error 

284 

285 if not isinstance(source_record, dict): 

286 raise ValueError(f"Online JSONL records must be objects: {data_file}") 

287 

288 return source_record 

289 

290 

291class _OnlineBlendedMappingDataset: 

292 """Expose Mapping sources through Megatron-style deterministic indices.""" 

293 

294 def __init__( 

295 self, 

296 source_datasets: Sequence[Any], 

297 weights: Sequence[float], 

298 size: int, 

299 random_seed: int, 

300 shuffle: bool = True, 

301 ) -> None: 

302 """Build the source schedule and source-local shuffle indices.""" 

303 

304 if not source_datasets or len(source_datasets) != len(weights): 

305 raise ValueError("Mapping blend sources and weights must be non-empty and aligned") 

306 

307 if len(source_datasets) >= np.iinfo(np.int16).max: 

308 raise ValueError("Mapping blend supports fewer than 32767 sources") 

309 

310 if size <= 0: 

311 raise ValueError("Mapping blend size must be positive") 

312 

313 source_lengths = [] 

314 for source_dataset in source_datasets: 

315 source_length = len(source_dataset) 

316 

317 if source_length <= 0: 

318 raise ValueError("Mapping blend sources must not be empty") 

319 

320 source_lengths.append(source_length) 

321 

322 self.source_datasets = tuple(source_datasets) 

323 self.weights = self._normalize_weights(weights) 

324 self.size = size 

325 self.source_index, self.source_sample_index = self._build_blend_indices() 

326 self.source_shuffle_indices = self._build_source_shuffle_indices( 

327 source_lengths, 

328 random_seed, 

329 shuffle, 

330 ) 

331 

332 def __len__(self) -> int: 

333 """Return the requested global sample count.""" 

334 return self.size 

335 

336 def __getitem__(self, index: int) -> Any: 

337 """Resolve one global index to its source and shuffled source sample.""" 

338 source_id = int(self.source_index[index]) 

339 source_sample_id = int(self.source_sample_index[index]) 

340 shuffled_sample_id = int(self.source_shuffle_indices[source_id][source_sample_id]) 

341 source_sample = self.source_datasets[source_id][shuffled_sample_id] 

342 return source_sample 

343 

344 @staticmethod 

345 def _normalize_weights(weights: Sequence[float]) -> tuple[float, ...]: 

346 """Validate and normalize source weights.""" 

347 if not weights or any(weight <= 0.0 for weight in weights): 

348 raise ValueError("Mapping blend weights must be positive") 

349 

350 weight_sum = sum(weights) 

351 normalized_weights = [] 

352 for weight in weights: 

353 normalized_weights.append(float(weight) / weight_sum) 

354 return tuple(normalized_weights) 

355 

356 def _build_blend_indices(self) -> tuple[np.ndarray, np.ndarray]: 

357 """Build Megatron's deterministic largest-deficit source schedule.""" 

358 source_index = np.empty(self.size, dtype=np.int16) 

359 source_logical_index = np.empty(self.size, dtype=np.int64) 

360 source_sample_counts = [0] * len(self.source_datasets) 

361 

362 for global_sample_index in range(self.size): 

363 scheduled_samples = max(global_sample_index, 1) 

364 selected_source = 0 

365 largest_deficit = self.weights[0] * scheduled_samples - source_sample_counts[0] 

366 for source_id in range(1, len(self.source_datasets)): 

367 source_deficit = ( 

368 self.weights[source_id] * scheduled_samples 

369 - source_sample_counts[source_id] 

370 ) 

371 if source_deficit > largest_deficit: 

372 selected_source = source_id 

373 largest_deficit = source_deficit 

374 

375 source_index[global_sample_index] = selected_source 

376 source_logical_index[global_sample_index] = source_sample_counts[selected_source] 

377 source_sample_counts[selected_source] += 1 

378 

379 return source_index, source_logical_index 

380 

381 def _build_source_shuffle_indices( 

382 self, 

383 source_lengths: Sequence[int], 

384 random_seed: int, 

385 shuffle: bool, 

386 ) -> tuple[np.ndarray, ...]: 

387 """Map source-local counters to repeated deterministic sample permutations.""" 

388 source_sample_counts = np.bincount( 

389 self.source_index, 

390 minlength=len(self.source_datasets), 

391 ) 

392 source_random = RandomState(random_seed) 

393 source_shuffle_indices = [] 

394 for source_length, requested_samples in zip(source_lengths, source_sample_counts): 

395 repeated_epochs = int(np.ceil(int(requested_samples) / source_length)) 

396 source_sample_index = np.tile( 

397 np.arange(source_length, dtype=np.int64), 

398 repeated_epochs, 

399 ) 

400 

401 if shuffle: 

402 source_random.shuffle(source_sample_index) 

403 

404 source_shuffle_indices.append(source_sample_index[:requested_samples]) 

405 return tuple(source_shuffle_indices) 

406 

407 

408class _OnlineMappingSourceBuilder(_OnlineSourceBuilder): 

409 """Build split-local, DP-global Mapping sample indices.""" 

410 

411 def __init__( 

412 self, 

413 data_path: OnlineDataPath | None, 

414 data_config: Mapping[str, Any], 

415 train_valid_test_num_samples: Sequence[int] | None, 

416 sampler_type: str = "single", 

417 ) -> None: 

418 """Store source configuration and optional training sample targets.""" 

419 super().__init__(data_path, data_config) 

420 

421 if sampler_type not in ("single", "cyclic"): 

422 raise ValueError(f"Unsupported Mapping sampler_type: {sampler_type!r}") 

423 

424 self.sampler_type = sampler_type 

425 self.train_valid_test_num_samples = self._validate_split_sizes(train_valid_test_num_samples) 

426 

427 def build_source( 

428 self, 

429 *, 

430 sample_filter: Callable[[Mapping[str, Any]], bool] | None = None, 

431 ) -> Any: 

432 """Load Mapping sources and compose their global split graphs.""" 

433 source_loaders, weights = self._create_source_loaders() 

434 source_results = [] 

435 for source_loader in source_loaders: 

436 source_result = self._build_leaf_source(source_loader, sample_filter) 

437 source_results.append(source_result) 

438 

439 # Cyclic sampling owns epoch shuffle and repetition, including explicit single sources. 

440 if self.sampler_type == "cyclic" and len(source_results) == 1: 

441 source = source_results[0] 

442 

443 if isinstance(source, tuple): 

444 return tuple(split if split is not None and len(split) else None for split in source) 

445 

446 return source if len(source) else None 

447 

448 # Example: source A returns Dataset, while source B returns (train, valid, test). 

449 # The combined result follows B's split structure, and A contributes only to train. 

450 has_split_result = False 

451 for source_result in source_results: 

452 if isinstance(source_result, tuple): 

453 has_split_result = True 

454 break 

455 

456 if not has_split_result: 

457 target_size = self._get_target_size(0, source_results) 

458 mapping_dataset = self._build_blended_split(source_results, weights, target_size) 

459 return mapping_dataset 

460 

461 # source of train, valid, test => each source blend 

462 blended_splits = [] 

463 for split_index in range(ONLINE_SPLIT_COUNT): 

464 split_datasets = [] 

465 split_weights = [] 

466 for source_result, weight in zip(source_results, weights): 

467 if isinstance(source_result, tuple): 

468 split_dataset = source_result[split_index] 

469 elif split_index == 0: 

470 split_dataset = source_result 

471 else: 

472 split_dataset = None 

473 

474 if split_dataset is not None: 

475 split_datasets.append(split_dataset) 

476 split_weights.append(weight) 

477 

478 target_size = self._get_target_size(split_index, split_datasets) 

479 blended_split = self._build_blended_split( 

480 split_datasets, 

481 split_weights, 

482 target_size, 

483 ) 

484 blended_splits.append(blended_split) 

485 

486 # train, valid, test 

487 mapping_splits = (blended_splits[0], blended_splits[1], blended_splits[2]) 

488 return mapping_splits 

489 

490 @classmethod 

491 def _build_leaf_source( 

492 cls, 

493 source_loader: Any, 

494 sample_filter: Callable[[Mapping[str, Any]], bool] | None, 

495 ) -> Any: 

496 """Build one leaf through native JSONL indexing or the general loader.""" 

497 data_path = source_loader.data_path 

498 split_config = source_loader.data_config.get("split") 

499 

500 if isinstance(data_path, Mapping) and split_config is None: 

501 jsonl_split_sources = cls._try_build_presplit_jsonl_sources( 

502 data_path, 

503 sample_filter, 

504 ) 

505 

506 if jsonl_split_sources is not None: 

507 return jsonl_split_sources 

508 

509 if not isinstance(data_path, Mapping): 

510 jsonl_files = cls._resolve_native_jsonl_files(data_path) 

511 logger.debug("Resolved native JSONL files: %s", jsonl_files) 

512 

513 if jsonl_files is not None: 

514 jsonl_source = _JsonlMappingSource(jsonl_files, sample_filter) 

515 

516 if split_config is not None: 

517 split_percentages = source_loader.parse_split_percentages(split_config) 

518 jsonl_splits = jsonl_source.split_by_percentages(split_percentages) 

519 return jsonl_splits 

520 

521 return jsonl_source 

522 

523 mapping_source = source_loader.load( 

524 streaming=False, 

525 sample_filter=sample_filter, 

526 ) 

527 return mapping_source 

528 

529 @classmethod 

530 def _try_build_presplit_jsonl_sources( 

531 cls, 

532 data_path: Mapping[str, OnlinePathSpec], 

533 sample_filter: Callable[[Mapping[str, Any]], bool] | None, 

534 ) -> tuple[Any, Any, Any] | None: 

535 """Try to preserve configured splits with native JSONL sources.""" 

536 

537 if not data_path: 

538 return None 

539 

540 resolved_split_files = {} 

541 for split_name, split_path in data_path.items(): 

542 if split_name not in ONLINE_SPLIT_NAMES: 

543 return None 

544 

545 jsonl_files = cls._resolve_native_jsonl_files(split_path) 

546 

547 if jsonl_files is None: 

548 return None 

549 

550 resolved_split_files[split_name] = jsonl_files 

551 

552 split_sources = [] 

553 for split_name in ONLINE_SPLIT_NAMES: 

554 split_source = None 

555 jsonl_files = resolved_split_files.get(split_name) 

556 

557 if jsonl_files is not None: 

558 split_source = _JsonlMappingSource(jsonl_files, sample_filter) 

559 

560 split_sources.append(split_source) 

561 jsonl_split_sources = (split_sources[0], split_sources[1], split_sources[2]) 

562 return jsonl_split_sources 

563 

564 @staticmethod 

565 def _resolve_native_jsonl_files(data_path: OnlinePathSpec) -> list[str] | None: 

566 """Resolve a local JSONL file, glob, directory, or ordered file list.""" 

567 configured_paths = [data_path] if isinstance(data_path, str) else list(data_path) 

568 data_files = [] 

569 for configured_path in configured_paths: 

570 matched_paths = sorted(glob.glob(configured_path)) 

571 

572 if os.path.isdir(configured_path): 

573 matched_paths = sorted(glob.glob(os.path.join(configured_path, "*.jsonl"))) 

574 

575 if not matched_paths: 

576 return None 

577 

578 data_files.extend(matched_paths) 

579 

580 if not data_files: 

581 return None 

582 

583 for data_file in data_files: 

584 if not os.path.isfile(data_file) or os.path.splitext(data_file)[1].lower() != ".jsonl": 

585 return None 

586 

587 return data_files 

588 

589 def _get_target_size(self, split_index: int, source_datasets: Sequence[Any]) -> int: 

590 """Size raw documents independently of the packed optimizer-step budget.""" 

591 del split_index 

592 natural_size = 0 

593 for source_dataset in source_datasets: 

594 natural_size += len(source_dataset) 

595 return natural_size 

596 

597 def _build_blended_split( 

598 self, 

599 source_datasets: Sequence[Any], 

600 weights: Sequence[float], 

601 target_size: int, 

602 ) -> Any: 

603 """Build one deterministic source and sample index graph.""" 

604 nonempty_datasets = [] 

605 nonempty_weights = [] 

606 for source_dataset, weight in zip(source_datasets, weights): 

607 if len(source_dataset) == 0: 

608 continue 

609 nonempty_datasets.append(source_dataset) 

610 nonempty_weights.append(weight) 

611 

612 if not nonempty_datasets or target_size == 0: 

613 return None 

614 

615 blended_dataset = _OnlineBlendedMappingDataset( 

616 nonempty_datasets, 

617 nonempty_weights, 

618 target_size, 

619 self._random_seed, 

620 shuffle=self.sampler_type != "cyclic", 

621 ) 

622 return blended_dataset 

623 

624 @staticmethod 

625 def _validate_split_sizes(split_sizes: Sequence[int] | None) -> tuple[int, int, int] | None: 

626 """Validate optional train, validation, and test sample targets.""" 

627 

628 if split_sizes is None: 

629 return None 

630 

631 if len(split_sizes) != ONLINE_SPLIT_COUNT: 

632 raise ValueError("Online Mapping sample targets must contain train, validation, and test sizes") 

633 

634 normalized_sizes = (int(split_sizes[0]), int(split_sizes[1]), int(split_sizes[2])) 

635 

636 if any(size < 0 for size in normalized_sizes): 

637 raise ValueError("Online Mapping sample targets must be non-negative") 

638 

639 return normalized_sizes 

640 

641 

642__all__ = [ 

643 "build_online_mapping_source", 

644 "MappingTransformDataset", 

645]