Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / tools / io.py: 66%

394 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# Adapted from the indexed dataset implementations in: 

16# - NVIDIA NeMo AutoModel 

17# - NVIDIA Megatron-LM 

18 

19"""Load indexed datasets from paired binary and index files. 

20 

21Supports the original mmap and file-pointer readers for local *.bin / *.idx 

22pairs, plus optional streaming readers for object storage (S3 and MSC). 

23 

24All three calls below are equivalent for local data: 

25 

26 from hyper_parallel.data.tools.io import IndexedDataset 

27 

28 ds = IndexedDataset("/path/to/shard_00_text_document") 

29 print(len(ds), ds[0][:20]) 

30 

31 ds = IndexedDataset("/path/to/shard_00_text_document.bin") 

32 print(len(ds), ds[0][:20]) 

33 

34 ds = IndexedDataset("/path/to/shard_00_text_document.idx") 

35 print(len(ds), ds[0][:20]) 

36 

37For object-storage data, pass an :class:`ObjectStorageConfig`: 

38 

39 cfg = ObjectStorageConfig(path_to_idx_cache="/tmp/idx_cache") 

40 ds = IndexedDataset("s3://bucket/path/shard_00_text_document", object_storage_config=cfg) 

41""" 

42 

43from __future__ import annotations 

44 

45import gc 

46import os 

47import shutil 

48import struct 

49import tempfile 

50from abc import ABC, abstractmethod 

51from dataclasses import dataclass 

52from enum import Enum 

53from types import TracebackType 

54from typing import Any, Dict, List, Optional, Tuple, Type, Union 

55import importlib 

56import traceback 

57 

58import numpy 

59import torch 

60 

61from hyper_parallel.high_availability.group_registry import is_recovery_reboot 

62from hyper_parallel.data.constants import INDEX_HEADER, INDEX_VERSION, MSC_PREFIX, S3_PREFIX 

63from hyper_parallel.data.dataset_logging import get_dataset_logger 

64 

65logger = get_dataset_logger(__name__) 

66 

67 

68def safe_import( 

69 module: str, 

70 *, 

71 msg: Optional[str] = None, 

72 alt: Optional[Any] = None, 

73) -> Tuple[bool, Optional[Any]]: 

74 """ 

75 A function used to import modules that may not be available. 

76 

77 This function will attempt to import a module with the given name, but it 

78 will not throw an ImportError if the module is not found. Instead, it will 

79 return the configured alternate object or ``None``. 

80 

81 Args: 

82 module (str): The name of the module to import. 

83 msg (str or None): An optional error message to be displayed if this module is used 

84 after a failed import. 

85 alt (object): An optional module to be used in place of the given module if it 

86 fails to import 

87 

88 Returns: 

89 Tuple(bool, object): Whether the intended import succeeded and the imported module, 

90 configured alternate, or ``None``. 

91 """ 

92 try: 

93 return True, importlib.import_module(module) 

94 except ImportError: 

95 exception_text = traceback.format_exc() 

96 logger.debug(f"Import of {module} failed with: {exception_text}") 

97 if msg is None: 

98 msg = f"{module} could not be imported" 

99 if alt is None: 

100 logger.debug(msg) 

101 return False, None 

102 return False, alt 

103 

104 

105# Optional dependencies for object-storage support. Install via 

106# Install ``boto3`` for S3 or ``multi-storage-client`` for MSC support. 

107HAS_BOTO3, boto3 = safe_import("boto3") 

108HAS_MSC, multi_storage_client = safe_import("multi_storage_client") 

109 

110@dataclass 

111class ObjectStorageConfig: 

112 """Configuration for reading ``.bin``/``.idx`` files from object storage. 

113 

114 Attributes: 

115 path_to_idx_cache: Local directory where the ``.idx`` file is cached on 

116 first use. Reused across ranks via a per-host directory layout. 

117 bin_chunk_nbytes: Size in bytes of each chunked range read against the 

118 ``.bin`` object. Defaults to 256 MiB. Larger values reduce request 

119 count but increase per-rank memory footprint. 

120 """ 

121 

122 path_to_idx_cache: str 

123 bin_chunk_nbytes: int = 256 * 1024 * 1024 

124 

125 

126def _is_object_storage_path(path: str) -> bool: 

127 """Return ``True`` if ``path`` is an ``s3://`` or ``msc://`` URI.""" 

128 return path.startswith(S3_PREFIX) or path.startswith(MSC_PREFIX) 

129 

130 

131def _parse_s3_path(path: str) -> Tuple[str, str]: 

132 """Split an ``s3://bucket/key`` URI into ``(bucket, key)``.""" 

133 if not path.startswith(S3_PREFIX): 

134 raise ValueError(f"Not an S3 path: {path}") 

135 parts = path[len(S3_PREFIX) :].split("/") 

136 bucket = parts[0] 

137 key = "/".join(parts[1:]) if len(parts) > 1 else "" 

138 return bucket, key 

139 

140 

141def _get_index_cache_path(idx_path: str, object_storage_config: ObjectStorageConfig) -> str: 

142 """Return the local cache path for ``idx_path`` under ``path_to_idx_cache``.""" 

143 if idx_path.startswith(S3_PREFIX): 

144 stripped = idx_path[len(S3_PREFIX) :] 

145 elif idx_path.startswith(MSC_PREFIX): 

146 stripped = idx_path[len(MSC_PREFIX) :] 

147 else: 

148 raise ValueError(f"Not an object storage path: {idx_path}") 

149 return os.path.join(object_storage_config.path_to_idx_cache, stripped) 

150 

151 

152def _cache_index_file(remote_path: str, local_path: str) -> None: 

153 """Download ``.idx`` from object storage to ``local_path``. 

154 

155 Rank 0 performs the download and other ranks wait on a ``torch.distributed`` 

156 barrier. A replacement worker downloads a missing local cache itself and 

157 publishes it atomically without waiting for parked training peers. 

158 

159 Raises: 

160 ImportError: If the relevant client library (``boto3`` for ``s3://`` or 

161 ``multi_storage_client`` for ``msc://``) is not installed. 

162 ValueError: If ``remote_path`` is neither an ``s3://`` nor an 

163 ``msc://`` URI. 

164 """ 

165 if remote_path.startswith(S3_PREFIX): 

166 if not HAS_BOTO3: 

167 raise ImportError("boto3 is required to read s3:// datasets. Install via `pip install boto3`.") 

168 elif remote_path.startswith(MSC_PREFIX): 

169 if not HAS_MSC: 

170 raise ImportError( 

171 "multi_storage_client is required to read msc:// datasets. " 

172 "Install via `pip install multi-storage-client`." 

173 ) 

174 else: 

175 raise ValueError(f"Unsupported object storage path: {remote_path}") 

176 

177 reboot = is_recovery_reboot() 

178 torch_dist_enabled = torch.distributed.is_initialized() and not reboot 

179 rank = torch.distributed.get_rank() if torch_dist_enabled else 0 

180 if not os.path.exists(local_path) and rank == 0: 

181 directory = os.path.dirname(local_path) or "." 

182 os.makedirs(directory, exist_ok=True) 

183 if reboot: 

184 with tempfile.TemporaryDirectory(prefix=".idx-recovery-", dir=directory) as temporary: 

185 staged = os.path.join(temporary, os.path.basename(local_path)) 

186 _download_index_file(remote_path, staged) 

187 os.replace(staged, local_path) 

188 else: 

189 _download_index_file(remote_path, local_path) 

190 if torch_dist_enabled: 

191 torch.distributed.barrier() 

192 if not os.path.exists(local_path): 

193 raise RuntimeError(f"Index cache file not found after download: {local_path}") 

194 

195 

196def _download_index_file(remote_path: str, local_path: str) -> None: 

197 """Download a validated object-storage index to one local destination.""" 

198 if remote_path.startswith(S3_PREFIX): 

199 bucket, key = _parse_s3_path(remote_path) 

200 client = boto3.client("s3") 

201 try: 

202 logger.info("Downloading %s -> %s", remote_path, local_path) 

203 client.download_file(bucket, key, local_path) 

204 finally: 

205 client.close() 

206 else: 

207 multi_storage_client.download_file(remote_path, local_path) 

208 

209 

210class DType(Enum): 

211 """The NumPy data type Enum for reading the IndexedDataset indices""" 

212 

213 UINT8 = 1 

214 INT8 = 2 

215 INT16 = 3 

216 INT32 = 4 

217 INT64 = 5 

218 FLOAT64 = 6 

219 FLOAT32 = 7 

220 UINT16 = 8 

221 

222 @classmethod 

223 def code_from_dtype(cls, value: Type[numpy.number]) -> int: 

224 """Get the code from the dtype 

225 

226 Args: 

227 value (Type[numpy.number]): The dtype 

228 

229 Returns: 

230 int: The code 

231 """ 

232 return cls[value.__name__.upper()].value 

233 

234 @classmethod 

235 def dtype_from_code(cls, value: int) -> Type[numpy.number]: 

236 """Get the dtype from the code 

237 

238 Args: 

239 value (int): The code 

240 

241 Returns: 

242 Type[numpy.number]: The dtype 

243 """ 

244 return getattr(numpy, cls(value).name.lower()) 

245 

246 @classmethod 

247 def size(cls, key: Union[int, Type[numpy.number]]) -> int: 

248 """Get the size of the dtype/code in bytes 

249 

250 Args: 

251 key (Union[int, Type[numpy.number]]): The dtype or code 

252 

253 Raises: 

254 ValueError: If the key is neither dtype nor integer code 

255 

256 Returns: 

257 int: The size of the dtype/code in bytes 

258 """ 

259 if isinstance(key, int): 

260 return cls.dtype_from_code(key)().itemsize 

261 if numpy.number in key.__mro__: 

262 return key().itemsize 

263 raise ValueError("Invalid key passed to DType.size()") 

264 

265 @classmethod 

266 def optimal_dtype(cls, cardinality: Optional[int]) -> Type[numpy.number]: 

267 """Get the dtype to use for an index of a certain cardinality 

268 

269 Args: 

270 cardinality (Optional[int]): The number of elements to be indexed 

271 

272 Returns: 

273 Type[numpy.number]: The dtype to use for the index 

274 """ 

275 if cardinality is not None and cardinality < 65500: 

276 return numpy.uint16 

277 return numpy.int32 

278 

279 

280class _IndexWriter: 

281 """Object class to write the index (.idx) file 

282 

283 Args: 

284 idx_path (str): The path to the index file 

285 

286 dtype (Type[numpy.number]): The dtype of the index file 

287 """ 

288 

289 def __init__(self, idx_path: str, dtype: Type[numpy.number]) -> None: 

290 """Initialize the _IndexWriter 

291 

292 Args: 

293 idx_path (str): The path to the index file. 

294 

295 dtype (Type[numpy.number]): The dtype of the index file. 

296 """ 

297 self.idx_path = idx_path 

298 self.dtype = dtype 

299 self.idx_writer = None 

300 

301 def __enter__(self) -> "_IndexWriter": 

302 """Enter the context introduced by the 'with' keyword 

303 

304 Returns: 

305 _IndexWriter: The instance 

306 """ 

307 self.idx_writer = open(self.idx_path, "wb") 

308 # fixed, vestigial practice 

309 self.idx_writer.write(INDEX_HEADER) 

310 # fixed, vestigial practice 

311 self.idx_writer.write(struct.pack("<Q", INDEX_VERSION)) 

312 # the numeric code for the dtype 

313 self.idx_writer.write(struct.pack("<B", DType.code_from_dtype(self.dtype))) 

314 return self 

315 

316 def __exit__( 

317 self, 

318 exc_type: Optional[Type[BaseException]], 

319 exc_val: Optional[BaseException], 

320 exc_tb: Optional[TracebackType], 

321 ) -> Optional[bool]: 

322 """Exit the context introduced by the 'with' keyword 

323 

324 Args: 

325 exc_type (Optional[Type[BaseException]]): Exception type 

326 

327 exc_val (Optional[BaseException]): Exception value 

328 

329 exc_tb (Optional[TracebackType]): Exception traceback object 

330 

331 Returns: 

332 Optional[bool]: Whether to silence the exception 

333 """ 

334 self.idx_writer.close() 

335 

336 def write( 

337 self, 

338 sequence_lengths: List[int], 

339 sequence_modes: Optional[List[int]], 

340 document_indices: List[int], 

341 ) -> None: 

342 """Write the index (.idx) file 

343 

344 Args: 

345 sequence_lengths (List[int]): The length of each sequence 

346 

347 sequence_modes (Optional[List[int]]): The mode of each sequences 

348 

349 document_indices (List[int]): The seqyebce indices demarcating the end of each document 

350 """ 

351 sequence_pointers = self._sequence_pointers(sequence_lengths) 

352 

353 # the number of sequences in the dataset 

354 sequence_count = len(sequence_lengths) 

355 self.idx_writer.write(struct.pack("<Q", sequence_count)) 

356 

357 # the number of documents in the dataset 

358 document_count = len(document_indices) 

359 self.idx_writer.write(struct.pack("<Q", document_count)) 

360 

361 # the number of tokens per sequence 

362 self.idx_writer.write(numpy.array(sequence_lengths, dtype=numpy.int32).tobytes(order="C")) 

363 

364 # the byte offsets for all sequences 

365 self.idx_writer.write(numpy.array(sequence_pointers, dtype=numpy.int64).tobytes(order="C")) 

366 

367 # the sequence indices marking the end of each document 

368 self.idx_writer.write(numpy.array(document_indices, dtype=numpy.int64).tobytes(order="C")) 

369 

370 # the mode per sequence 

371 if sequence_modes is not None: 

372 self.idx_writer.write(numpy.array(sequence_modes, dtype=numpy.int8).tobytes(order="C")) 

373 

374 def _sequence_pointers(self, sequence_lengths: List[int]) -> List[int]: 

375 """Build the sequence pointers per the sequence lengths and dtype size 

376 

377 Args: 

378 sequence_lengths (List[int]): The length of each sequence 

379 

380 Returns: 

381 List[int]: The pointer to the beginning of each sequence 

382 """ 

383 itemsize = DType.size(self.dtype) 

384 curr_ptr = 0 

385 list_ptr = [] 

386 for length in sequence_lengths: 

387 list_ptr.append(curr_ptr) 

388 curr_ptr += length * itemsize 

389 return list_ptr 

390 

391 

392class _IndexReader: 

393 """Object class to read the index (.idx) file 

394 

395 Args: 

396 idx_path (str): The path to the index file 

397 

398 multimodal (bool): Whether the dataset is multimodal 

399 """ 

400 

401 def __init__(self, idx_path: str, multimodal: bool) -> None: 

402 """Initialize the _IndexReader 

403 

404 Args: 

405 idx_path (str): The path to the index file. 

406 

407 multimodal (bool): Whether the dataset is multimodal. 

408 """ 

409 logger.info("Loading index file %s", idx_path) 

410 

411 with open(idx_path, "rb") as f: 

412 header = f.read(len(INDEX_HEADER)) 

413 assert header == INDEX_HEADER, f"Bad header in {idx_path}" 

414 

415 version = struct.unpack("<Q", f.read(8))[0] 

416 assert version == INDEX_VERSION, f"Unsupported index version {version} in {idx_path}" 

417 

418 code = struct.unpack("<B", f.read(1))[0] 

419 self.dtype = DType.dtype_from_code(code) 

420 self.dtype_size = DType.size(self.dtype) 

421 

422 self.sequence_count = struct.unpack("<Q", f.read(8))[0] 

423 self.document_count = struct.unpack("<Q", f.read(8))[0] 

424 payload_offset = f.tell() 

425 

426 # memory-map the whole file for fast zero-copy slicing 

427 self._mmap = numpy.memmap(idx_path, mode="r", order="C") 

428 self._buffer = memoryview(self._mmap) 

429 

430 # extract views 

431 logger.info("Extracting sequence lengths") 

432 self.sequence_lengths = numpy.frombuffer( 

433 self._buffer, dtype=numpy.int32, count=self.sequence_count, offset=payload_offset 

434 ) 

435 logger.info("Extracting sequence pointers") 

436 self.sequence_pointers = numpy.frombuffer( 

437 self._buffer, 

438 dtype=numpy.int64, 

439 count=self.sequence_count, 

440 offset=payload_offset + self.sequence_lengths.nbytes, 

441 ) 

442 logger.info("Extracting document indices") 

443 self.document_indices = numpy.frombuffer( 

444 self._buffer, 

445 dtype=numpy.int64, 

446 count=self.document_count, 

447 offset=payload_offset + self.sequence_lengths.nbytes + self.sequence_pointers.nbytes, 

448 ) 

449 

450 self.sequence_modes: Optional[numpy.ndarray] = None 

451 if multimodal: 

452 logger.info("Extracting sequence modes") 

453 self.sequence_modes = numpy.frombuffer( 

454 self._buffer, 

455 dtype=numpy.int8, 

456 count=self.sequence_count, 

457 offset=payload_offset 

458 + self.sequence_lengths.nbytes 

459 + self.sequence_pointers.nbytes 

460 + self.document_indices.nbytes, 

461 ) 

462 

463 sequence_length_count = self.sequence_lengths.shape[0] 

464 if sequence_length_count != len(self): 

465 raise ValueError("Sequence length count does not match the dataset length") 

466 if sequence_length_count != self.sequence_count: 

467 raise ValueError("Sequence length count does not match the index sequence count") 

468 if sequence_length_count != self.document_indices[-1]: 

469 raise ValueError("Sequence length count does not match the final document index") 

470 

471 logger.info("Sequences: %d | Documents: %d", len(self), self.document_indices.shape[0] - 1) 

472 

473 def close(self) -> None: 

474 """Release memory-mapped index resources.""" 

475 if getattr(self, "_mmap", None) is None: 

476 return 

477 

478 self.sequence_lengths = None 

479 self.sequence_pointers = None 

480 self.document_indices = None 

481 self.sequence_modes = None 

482 if getattr(self, "_buffer", None) is not None: 

483 self._buffer.release() 

484 self._buffer = None 

485 

486 self._mmap = None 

487 

488 def __del__(self) -> None: 

489 """Clean up the object.""" 

490 try: 

491 self.close() 

492 except (AttributeError, BufferError, ValueError): 

493 pass 

494 

495 def __len__(self) -> int: 

496 """Get the number of sequences in the dataset 

497 

498 Returns: 

499 int: The number of sequences in the dataset 

500 """ 

501 return self.sequence_count 

502 

503 def __getitem__(self, idx: int) -> Tuple[numpy.int32, numpy.int64, Optional[numpy.int8]]: 

504 """Return the pointer, length, and mode at the index 

505 

506 Args: 

507 idx (int): The index into the dataset 

508 

509 Returns: 

510 Tuple[numpy.int32, numpy.int64, Optional[numpy.int8]]: The pointer, length and mode 

511 at the index 

512 """ 

513 return ( 

514 self.sequence_pointers[idx], 

515 self.sequence_lengths[idx], 

516 self.sequence_modes[idx] if self.sequence_modes is not None else None, 

517 ) 

518 

519 

520class _BinReader(ABC): 

521 """Abstract class to read the data (.bin) file""" 

522 

523 @abstractmethod 

524 def read(self, dtype: Type[numpy.number], count: int, offset: int) -> numpy.ndarray: 

525 """Read bytes into a numpy array. 

526 

527 Args: 

528 dtype (Type[numpy.number]): Data-type of the returned array. 

529 

530 count (int): Number of items to read. 

531 

532 offset (int): Start reading from this offset (in bytes). 

533 

534 Returns: 

535 numpy.ndarray: An array with `count` items and data-type `dtype` constructed from 

536 reading bytes from the data file starting at `offset`. 

537 """ 

538 

539 

540class _MMapBinReader(_BinReader): 

541 """A _BinReader that memory maps the data (.bin) file""" 

542 

543 def __init__(self, bin_path: str) -> None: 

544 """Initialize the _MMapBinReader 

545 

546 Args: 

547 bin_path (str): The path to the data (.bin) file. 

548 """ 

549 # The file must stay open for the reader's lifetime; it is closed in __del__. 

550 self._file = open(bin_path, "rb") # pylint: disable=R1732 

551 self._mmap = numpy.memmap(self._file, mode="r", order="C") 

552 self._buffer = memoryview(self._mmap.data) 

553 

554 def read(self, dtype: Type[numpy.number], count: int, offset: int) -> numpy.ndarray: 

555 """Read bytes into a numpy array. 

556 

557 Args: 

558 dtype (Type[numpy.number]): Data-type of the returned array. 

559 

560 count (int): Number of items to read. 

561 

562 offset (int): Start reading from this offset (in bytes). 

563 

564 Returns: 

565 numpy.ndarray: An array with `count` items and data-type `dtype` constructed from 

566 reading bytes from the data file starting at `offset`. 

567 """ 

568 return numpy.frombuffer(self._buffer, dtype=dtype, count=count, offset=offset) 

569 

570 def close(self) -> None: 

571 """Close the backing file without invalidating arrays returned from mmap.""" 

572 file_obj = getattr(self, "_file", None) 

573 if file_obj is not None: 

574 file_obj.close() 

575 self._file = None 

576 

577 def __del__(self) -> None: 

578 """Clean up the object.""" 

579 try: 

580 self.close() 

581 except (AttributeError, BufferError, ValueError): 

582 pass 

583 

584 

585class _FileBinReader(_BinReader): 

586 """A _BinReader that reads from the data (.bin) file using a file pointer""" 

587 

588 def __init__(self, bin_path: str) -> None: 

589 """Initialize the _FileBinReader 

590 

591 Args: 

592 bin_path (str): The path to the data (.bin) file. 

593 """ 

594 self._bin_path = bin_path 

595 

596 def read(self, dtype: Type[numpy.number], count: int, offset: int) -> numpy.ndarray: 

597 """Read bytes into a numpy array. 

598 

599 Args: 

600 dtype (Type[numpy.number]): Data-type of the returned array. 

601 

602 count (int): Number of items to read. 

603 

604 offset (int): Start reading from this offset (in bytes). 

605 

606 Returns: 

607 numpy.ndarray: An array with `count` items and data-type `dtype` constructed from 

608 reading bytes from the data file starting at `offset`. 

609 """ 

610 out = numpy.empty(count, dtype=dtype) 

611 with open(self._bin_path, "rb", buffering=0) as f: 

612 f.seek(offset) 

613 byte_view = out.view(numpy.uint8) 

614 nbytes = f.readinto(byte_view) 

615 if nbytes != out.nbytes: 

616 raise ValueError( 

617 f"Short read from {self._bin_path}: requested {out.nbytes} bytes at offset {offset}, " 

618 f"read {nbytes or 0} bytes" 

619 ) 

620 return out 

621 

622 

623class _S3BinReader(_BinReader): 

624 """Stream ``.bin`` data from S3 via chunked ranged ``GetObject`` calls. 

625 

626 A single in-memory chunk (sized by 

627 :attr:`ObjectStorageConfig.bin_chunk_nbytes`) is cached so consecutive 

628 reads within the same chunk avoid network round-trips. Random-access 

629 reads outside the current chunk trigger a new ranged ``GetObject``. 

630 """ 

631 

632 def __init__(self, bin_path: str, object_storage_config: ObjectStorageConfig) -> None: 

633 """Initialize the _S3BinReader 

634 

635 Args: 

636 bin_path (str): The ``s3://bucket/key`` URI of the data (.bin) object. 

637 

638 object_storage_config (ObjectStorageConfig): Chunked-read configuration. 

639 """ 

640 if not HAS_BOTO3: 

641 raise ImportError("boto3 is required to read s3:// datasets. Install via `pip install boto3`.") 

642 if object_storage_config.bin_chunk_nbytes <= 0: 

643 raise ValueError(f"bin_chunk_nbytes must be positive, got {object_storage_config.bin_chunk_nbytes}") 

644 self._client = boto3.client("s3") 

645 self._s3_bucket, self._s3_key = _parse_s3_path(bin_path) 

646 self._cache_nbytes = object_storage_config.bin_chunk_nbytes 

647 self._cache_bytes_start: int = 0 

648 self._cache_bytes_end: int = 0 

649 self._cache: Optional[bytes] = None 

650 

651 def _extract_from_cache(self, offset: int, size: int) -> bytes: 

652 """Return a requested byte range from the active S3 cache window.""" 

653 if self._cache is None: 

654 raise RuntimeError("Cache is empty; cannot extract before first read") 

655 start = offset - self._cache_bytes_start 

656 end = start + size 

657 if start < 0 or end > len(self._cache): 

658 raise IndexError( 

659 f"Cache window [{self._cache_bytes_start}, {self._cache_bytes_end}) " 

660 f"does not contain requested range [{offset}, {offset + size})" 

661 ) 

662 return self._cache[start:end] 

663 

664 def read(self, dtype: Type[numpy.number], count: int, offset: int) -> numpy.ndarray: 

665 """Read ``count`` elements of ``dtype`` starting at byte ``offset``.""" 

666 size = count * DType.size(dtype) 

667 if self._cache is not None and offset >= self._cache_bytes_start and offset + size <= self._cache_bytes_end: 

668 return numpy.frombuffer(self._extract_from_cache(offset, size), dtype=dtype) 

669 

670 bytes_start = (offset // self._cache_nbytes) * self._cache_nbytes 

671 bytes_end = max(bytes_start + self._cache_nbytes, offset + size) 

672 self._cache = self._client.get_object( 

673 Bucket=self._s3_bucket, 

674 Key=self._s3_key, 

675 Range=f"bytes={bytes_start}-{bytes_end - 1}", 

676 )["Body"].read() 

677 self._cache_bytes_start = bytes_start 

678 self._cache_bytes_end = bytes_start + len(self._cache) 

679 return numpy.frombuffer(self._extract_from_cache(offset, size), dtype=dtype) 

680 

681 def __del__(self) -> None: 

682 try: 

683 self._client.close() 

684 except (AttributeError, RuntimeError): 

685 pass 

686 

687 

688class _MultiStorageClientBinReader(_BinReader): 

689 """Read ``.bin`` data via NVIDIA's :mod:`multi_storage_client`.""" 

690 

691 def __init__(self, bin_path: str, object_storage_config: ObjectStorageConfig) -> None: 

692 """Initialize the _MultiStorageClientBinReader 

693 

694 Args: 

695 bin_path (str): The ``msc://`` URI of the data (.bin) object. 

696 

697 object_storage_config (ObjectStorageConfig): Accepted for constructor 

698 parity with the other object-storage bin readers; unused here. 

699 """ 

700 del object_storage_config 

701 if not HAS_MSC: 

702 raise ImportError( 

703 "multi_storage_client is required to read msc:// datasets. " 

704 "Install via `pip install multi-storage-client`." 

705 ) 

706 self._client, self._bin_path = multi_storage_client.resolve_storage_client(bin_path) 

707 

708 def read(self, dtype: Type[numpy.number], count: int, offset: int) -> numpy.ndarray: 

709 """Read ``count`` elements of ``dtype`` starting at byte ``offset``.""" 

710 size = count * DType.size(dtype) 

711 buffer = self._client.read( 

712 path=self._bin_path, 

713 byte_range=multi_storage_client.types.Range(offset=offset, size=size), 

714 ) 

715 return numpy.frombuffer(buffer, dtype=dtype) 

716 

717 

718OBJECT_STORAGE_BIN_READERS: Dict[str, Type[_BinReader]] = { 

719 "s3": _S3BinReader, 

720 "msc": _MultiStorageClientBinReader, 

721} 

722 

723 

724class IndexedDataset(torch.utils.data.Dataset): 

725 """A fast, on-disk dataset backed by paired index and binary files.""" 

726 

727 def __init__( 

728 self, 

729 path_prefix: str, 

730 multimodal: bool = False, 

731 mmap: bool = True, 

732 object_storage_config: Optional[ObjectStorageConfig] = None, 

733 ) -> None: 

734 """Initialize the IndexedDataset 

735 

736 Args: 

737 path_prefix (str): The index (.idx) and data (.bin) prefix. May be an S3 URI 

738 (``s3://bucket/key``) when ``object_storage_config`` is provided. 

739 multimodal (bool): Whether the dataset is multimodal. Defaults to False. 

740 mmap (bool): Whether to mmap the .bin files. Defaults to True. Must be False 

741 for object-storage paths. 

742 object_storage_config (Optional[ObjectStorageConfig]): When provided and 

743 ``path_prefix`` is an S3/MSC URI, the .idx file is downloaded to 

744 ``object_storage_config.path_to_idx_cache`` and the .bin file is streamed 

745 via chunked GETs. 

746 """ 

747 super().__init__() 

748 normalized_prefix = _normalize_prefix(path_prefix) 

749 if _is_object_storage_path(normalized_prefix) and object_storage_config is not None: 

750 if mmap: 

751 raise ValueError( 

752 "mmap must be False for object-storage prefixes; " 

753 "set mmap=False (or set `mmap_bin_files: false` in the recipe)." 

754 ) 

755 idx_path = get_idx_path(normalized_prefix) 

756 cache_idx_path = _get_index_cache_path(idx_path, object_storage_config) 

757 _cache_index_file(idx_path, cache_idx_path) 

758 self.initialize(normalized_prefix, multimodal, mmap, object_storage_config) 

759 

760 def initialize( 

761 self, 

762 path_prefix: str, 

763 multimodal: bool, 

764 mmap: bool, 

765 object_storage_config: Optional[ObjectStorageConfig] = None, 

766 ) -> None: 

767 """Open the index and data readers for a dataset prefix. 

768 

769 Args: 

770 path_prefix (str): The index (.idx) and data (.bin) prefix. 

771 multimodal (bool): Whether the dataset is multimodal. 

772 mmap (bool): Whether to mmap the .bin files. 

773 object_storage_config (Optional[ObjectStorageConfig]): Object-storage 

774 configuration used for ``s3://``/``msc://`` prefixes. 

775 """ 

776 idx_path = get_idx_path(path_prefix) 

777 bin_path = get_bin_path(path_prefix) 

778 

779 if _is_object_storage_path(path_prefix) and object_storage_config is not None: 

780 # .idx is already cached locally; determine local path for _IndexReader 

781 local_idx_path = _get_index_cache_path(idx_path, object_storage_config) 

782 if not os.path.exists(local_idx_path): 

783 raise RuntimeError(f"Cached .idx not found: {local_idx_path}") 

784 access = "s3" if path_prefix.startswith(S3_PREFIX) else "msc" 

785 bin_reader: _BinReader = OBJECT_STORAGE_BIN_READERS[access](bin_path, object_storage_config) 

786 index_reader = _IndexReader(local_idx_path, multimodal) 

787 else: 

788 if not os.path.exists(idx_path) or not os.path.exists(bin_path): 

789 raise FileNotFoundError(f"Missing .idx or .bin at prefix {path_prefix}") 

790 bin_reader = _MMapBinReader(bin_path) if mmap else _FileBinReader(bin_path) 

791 index_reader = _IndexReader(idx_path, multimodal) 

792 

793 self.path_prefix = path_prefix 

794 self.multimodal = multimodal 

795 self.mmap = mmap 

796 self.object_storage_config = object_storage_config 

797 self.bin_reader = bin_reader 

798 self.index = index_reader 

799 

800 def __len__(self) -> int: 

801 """Get the number of sequences in the dataset 

802 

803 Returns: 

804 int: The number of sequences in the dataset 

805 """ 

806 return len(self.index) 

807 

808 def __getitem__( 

809 self, idx: Union[int, numpy.integer, slice] 

810 ) -> Union[ 

811 numpy.ndarray, 

812 Tuple[numpy.ndarray, Any], # mode attached 

813 List[numpy.ndarray], 

814 Tuple[List[numpy.ndarray], numpy.ndarray], 

815 ]: 

816 """Read one sequence or a contiguous slice of sequences. 

817 

818 Args: 

819 idx (Union[int, numpy.integer, slice]): The index or contiguous 

820 (step=1) slice into the dataset. 

821 

822 Returns: 

823 Union[numpy.ndarray, Tuple[numpy.ndarray, Any], List[numpy.ndarray], 

824 Tuple[List[numpy.ndarray], numpy.ndarray]]: The sequence(s), each 

825 paired with its mode when the dataset is multimodal. 

826 """ 

827 if isinstance(idx, (int, numpy.integer)): 

828 ptr, length, mode = self.index[idx] 

829 seq = self.bin_reader.read(self.index.dtype, length, ptr) 

830 return (seq, mode) if mode is not None else seq 

831 

832 if isinstance(idx, slice): 

833 start, _, step = idx.indices(len(self)) 

834 if step != 1: 

835 raise ValueError("Slices into IndexedDataset must be contiguous (step=1)") 

836 lengths = self.index.sequence_lengths[idx] 

837 modes = self.index.sequence_modes[idx] if self.multimodal else None 

838 offsets = numpy.cumsum(lengths, dtype=numpy.int64) 

839 token_count = int(offsets[-1]) if offsets.size else 0 

840 buffer = self.bin_reader.read( 

841 self.index.dtype, 

842 token_count, 

843 int(self.index.sequence_pointers[start]), 

844 ) 

845 sequences = numpy.split(buffer, offsets[:-1]) 

846 return (sequences, modes) if modes is not None else sequences 

847 

848 raise TypeError(f"Unexpected index type {type(idx)}") 

849 

850 def get( 

851 self, idx: int, offset: int = 0, length: Optional[int] = None 

852 ) -> Union[numpy.ndarray, Tuple[numpy.ndarray, Any]]: 

853 """Read a sub-range of one sequence. 

854 

855 Args: 

856 idx (int): The index into the dataset. 

857 offset (int): Number of leading elements to skip. Defaults to 0. 

858 length (Optional[int]): Number of elements to read; defaults to the 

859 remainder of the sequence. 

860 

861 Returns: 

862 Union[numpy.ndarray, Tuple[numpy.ndarray, Any]]: The sequence 

863 sub-range, paired with its mode for multimodal datasets. 

864 """ 

865 ptr, seq_len, mode = self.index[idx] 

866 length = seq_len - offset if length is None else length 

867 ptr += offset * DType.size(self.index.dtype) 

868 seq = self.bin_reader.read(self.index.dtype, length, ptr) 

869 return (seq, mode) if mode is not None else seq 

870 

871 @property 

872 def sequence_lengths(self) -> numpy.ndarray: 

873 """The length of each sequence in the dataset (numpy.int32 array).""" 

874 return self.index.sequence_lengths 

875 

876 @property 

877 def document_indices(self) -> numpy.ndarray: 

878 """The sequence indices demarcating documents (numpy.int64 array).""" 

879 return self.index.document_indices 

880 

881 @staticmethod 

882 def exists(path_prefix: str) -> bool: 

883 """Return whether the .idx and .bin files exist for a dataset prefix. 

884 

885 Args: 

886 path_prefix (str): The index (.idx) and data (.bin) prefix. 

887 

888 Returns: 

889 bool: Whether both files exist; object-storage prefixes always 

890 return ``True`` and defer the check to download time. 

891 """ 

892 if _is_object_storage_path(path_prefix): 

893 return True # existence check deferred to download time 

894 return os.path.exists(get_idx_path(path_prefix)) and os.path.exists(get_bin_path(path_prefix)) 

895 

896 

897class IndexedDatasetBuilder: 

898 """Builder class for the IndexedDataset class 

899 

900 Args: 

901 bin_path (str): The path to the data (.bin) file 

902 

903 dtype (Type[numpy.number], optional): The dtype of the index file. Defaults to numpy.int32. 

904 

905 multimodal (bool, optional): Whether the dataset is multimodal. Defaults to False. 

906 """ 

907 

908 def __init__(self, bin_path: str, dtype: Type[numpy.number] = numpy.int32, multimodal: bool = False) -> None: 

909 """Initialize the IndexedDatasetBuilder 

910 

911 Args: 

912 bin_path (str): The path to the data (.bin) file. 

913 

914 dtype (Type[numpy.number], optional): The dtype of the index file. 

915 Defaults to numpy.int32. 

916 

917 multimodal (bool, optional): Whether the dataset is multimodal. 

918 Defaults to False. 

919 """ 

920 # The data file must stay open until finalize(); it is closed there. 

921 self.data_file = open(bin_path, "wb") # pylint: disable=R1732 

922 self.dtype = dtype 

923 self.multimodal = multimodal 

924 

925 self.sequence_lengths = [] 

926 self.document_indices = [0] 

927 self.sequence_modes = [] if self.multimodal else None 

928 

929 def add_item(self, tensor: torch.Tensor, mode: int = 0) -> None: 

930 """Add a single item to the dataset 

931 

932 Args: 

933 tensor (torch.Tensor): The item to add to the data file 

934 

935 mode (int, optional): The mode for the item. Defaults to 0. 

936 """ 

937 np_array = numpy.array(tensor.numpy(), dtype=self.dtype) 

938 self.data_file.write(np_array.tobytes(order="C")) 

939 self.sequence_lengths.append(np_array.size) 

940 if self.multimodal: 

941 self.sequence_modes.append(mode) 

942 

943 def add_document(self, tensor: torch.Tensor, lengths: List[int], modes: Optional[List[int]] = None) -> None: 

944 """Add an entire document to the dataset 

945 

946 Args: 

947 tensor: The tensor, array or token list containing the document. 

948 

949 lengths (List[int]): The lengths of each item in the document 

950 

951 modes (Optional[List[int]], optional): The modes for each item in the document. 

952 Defaults to None. 

953 """ 

954 np_array = numpy.asarray(tensor, dtype=self.dtype) 

955 self.data_file.write(np_array.tobytes(order="C")) 

956 self.sequence_lengths.extend(lengths) 

957 self.document_indices.append(len(self.sequence_lengths)) 

958 if self.multimodal: 

959 self.sequence_modes.extend(modes if modes is not None else [0] * lengths) 

960 

961 def end_document(self) -> None: 

962 """Finalize the document, for use with IndexedDatasetBuilder.add_item""" 

963 self.document_indices.append(len(self.sequence_lengths)) 

964 

965 def add_index(self, path_prefix: str) -> None: 

966 """Add an entire IndexedDataset to the dataset 

967 

968 Args: 

969 path_prefix (str): The index (.idx) and data (.bin) prefix 

970 """ 

971 # Concatenate index 

972 index = _IndexReader(get_idx_path(path_prefix), multimodal=self.multimodal) 

973 if index.dtype != self.dtype: 

974 raise ValueError(f"Index dtype {index.dtype} does not match builder dtype {self.dtype}") 

975 

976 offset = len(self.sequence_lengths) 

977 self.sequence_lengths.extend(index.sequence_lengths) 

978 self.document_indices.extend((offset + index.document_indices)[1:]) 

979 

980 if self.multimodal: 

981 if index.sequence_modes is None: 

982 raise ValueError("sequence_modes cannot be None for a multimodal dataset") 

983 self.sequence_modes.extend(index.sequence_modes) 

984 

985 # Free up memory to make space for new indices 

986 del index 

987 gc.collect() 

988 

989 # Concatenate data 

990 with open(get_bin_path(path_prefix), "rb") as f: 

991 shutil.copyfileobj(f, self.data_file) 

992 

993 def finalize(self, idx_path: str) -> None: 

994 """Clean up and write the index (.idx) file 

995 

996 Args: 

997 idx_path (str): The path to the index file 

998 """ 

999 self.data_file.close() 

1000 with _IndexWriter(idx_path, self.dtype) as writer: 

1001 writer.write(self.sequence_lengths, self.sequence_modes, self.document_indices) 

1002 

1003 

1004def get_idx_path(path_prefix: str) -> str: 

1005 """Return the index-file path for an indexed dataset prefix.""" 

1006 return path_prefix + ".idx" 

1007 

1008 

1009def get_bin_path(path_prefix: str) -> str: 

1010 """Return the binary-data path for an indexed dataset prefix.""" 

1011 return path_prefix + ".bin" 

1012 

1013 

1014def _normalize_prefix(path_prefix: str) -> str: 

1015 if path_prefix.endswith(".bin") or path_prefix.endswith(".idx"): 

1016 return path_prefix[:-4] 

1017 return path_prefix