Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / offline / dataset.py: 74%
403 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« 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"""Runtime Dataset types selected by the indexed pretraining builder."""
17from __future__ import annotations
19import hashlib
20import json
21import os
22import time
23from abc import ABC, abstractmethod
24from collections import OrderedDict
25from collections.abc import Mapping
26from typing import Any
28import numpy as np
29from numpy.random import RandomState
31from hyper_parallel.data.constants import IGNORE_INDEX, PAD_TOKEN_ID
32from hyper_parallel.data.dataset_logging import get_dataset_logger
33from hyper_parallel.data.offline.data_config import GPTDatasetConfig
34from hyper_parallel.data.offline.data_reader import ArrowDataReader, IndexedDataReader
36logger = get_dataset_logger(__name__)
39def _build_document_index(
40 documents: np.ndarray,
41 num_epochs: int,
42 random_state: RandomState,
43 separate_final_epoch: bool,
44) -> np.ndarray:
45 """Repeat and shuffle the exposed sequence indices for every epoch."""
46 if not separate_final_epoch or num_epochs == 1:
47 document_index = np.mgrid[0:num_epochs, 0:len(documents)][1]
48 document_index[:] = documents
49 document_index = document_index.reshape(-1).astype(np.int32)
50 random_state.shuffle(document_index)
51 return document_index
53 first_epochs = _build_document_index(documents, num_epochs - 1, random_state, False)
54 final_epoch = _build_document_index(documents, 1, random_state, False)
55 document_index = np.concatenate((first_epochs, final_epoch))
56 return document_index
59def _build_shuffle_index(
60 num_samples: int,
61 total_size: int,
62 random_state: RandomState,
63) -> np.ndarray:
64 """Shuffle the main epoch range separately from a small final epoch."""
65 dtype = np.uint32 if total_size < np.iinfo(np.uint32).max - 1 else np.int64
66 first_range = np.arange(0, num_samples, dtype=dtype)
67 random_state.shuffle(first_range)
68 if num_samples == total_size:
69 return first_range
71 final_range = np.arange(num_samples, total_size, dtype=dtype)
72 random_state.shuffle(final_range)
73 shuffle_index = np.concatenate((first_range, final_range))
74 return shuffle_index
77class _IndexedPretrainDataset(ABC):
78 """Store the common state used by all indexed pretraining Datasets."""
80 def __init__(
81 self,
82 dataset: IndexedDataReader | None,
83 dataset_path: str | None,
84 indices: np.ndarray | None,
85 num_samples: int,
86 index_split: Any,
87 config: GPTDatasetConfig,
88 ) -> None:
89 """Store common construction inputs and finalize the concrete Dataset."""
90 self.dataset = dataset
91 self.dataset_path = dataset_path
92 self.indices = indices
93 self.num_samples = num_samples
94 self.index_split = index_split
95 self.config = config
96 self._ltor_fields_cacheable = not any(
97 (
98 self.config.reset_position_ids,
99 self.config.reset_attention_mask,
100 self.config.eod_mask_loss,
101 self.config.inter_document_masking,
102 )
103 )
104 self._cached_ltor_fields = None
106 # Handle pad token id provided by the tokenizer.
107 try:
108 pad_token_id = getattr(self.config.tokenizer, "pad_token_id", None)
110 if pad_token_id is None:
111 pad_token_id = self.config.tokenizer.pad
113 self._pad_token_id = (
114 PAD_TOKEN_ID if pad_token_id is None or callable(pad_token_id) else int(pad_token_id)
115 )
116 except (AttributeError, NotImplementedError):
117 self._pad_token_id = PAD_TOKEN_ID
119 try:
120 special_token_ids = [
121 token_id
122 for token_name, token_id in self.config.tokenizer.special_tokens_dict.items()
123 if token_name != "pad_token"
124 ]
125 except (AttributeError, IndexError, ValueError):
126 special_token_ids = []
127 if not special_token_ids:
128 for token_name in ("eos", "eod"):
129 try:
130 special_token_ids.append(getattr(self.config.tokenizer, token_name))
131 except (AttributeError, NotImplementedError):
132 pass
134 if self._pad_token_id in special_token_ids:
135 if self.config.allow_ambiguous_pad_tokens:
136 logger.warning(
137 "The tokenizer PAD ID collides with another special token ID; matching tokens will also be "
138 "masked as padding"
139 )
140 else:
141 self._pad_token_id = PAD_TOKEN_ID
142 logger.warning(
143 "The tokenizer PAD ID collides with another special token ID; using an internal padding sentinel"
144 )
146 if not self.config.mock:
147 self.unique_identifiers = type(self).build_unique_identifiers(
148 self.dataset_path,
149 self.num_samples,
150 self.index_split,
151 self.config,
152 )
154 self.unique_description = json.dumps(
155 self.unique_identifiers,
156 indent=4,
157 default=lambda value: value.unique_identifiers,
158 )
159 self.unique_description_hash = hashlib.md5(
160 self.unique_description.encode("utf-8")
161 ).hexdigest()
163 self._finalize()
165 def _build_ltor_fields(
166 self,
167 tokens: np.ndarray,
168 labels: np.ndarray,
169 document_boundaries: np.ndarray | None = None,
170 ) -> dict[str, np.ndarray]:
171 """Build LTR masks and position IDs when explicitly enabled."""
173 if not self.config.create_ltor_fields:
175 return {}
177 # Final document-specific masks and positions may differ even for
178 # samples with the same token length, so they cannot share this cache.
179 cacheable = self._ltor_fields_cacheable and document_boundaries is None
180 cached_fields = self._cached_ltor_fields if cacheable else None
182 if cached_fields is not None:
183 fields = cached_fields
185 elif document_boundaries is not None:
186 fields = _get_ltor_masks_and_position_ids_from_boundaries(tokens, self.config, document_boundaries)
188 else:
189 fields = _get_ltor_masks_and_position_ids_from_eod(tokens, self.config)
191 if cacheable and cached_fields is None:
192 self._cached_ltor_fields = fields
194 attention_mask, loss_mask, position_ids = fields
195 loss_mask = loss_mask.copy()
196 loss_mask[labels == self._pad_token_id] = 0.0
197 ltor_fields = {
198 "loss_mask": loss_mask,
199 "position_ids": position_ids,
200 "attention_mask": attention_mask,
201 }
203 return ltor_fields
205 def _finalize(self) -> None:
206 """Build indices or validate the low-level Dataset."""
208 @staticmethod
209 def numel_low_level_dataset(low_level_dataset: IndexedDataReader) -> int:
210 """Return the number of elements used to construct split indices."""
211 del low_level_dataset
212 raise NotImplementedError
214 @staticmethod
215 def build_low_level_dataset(
216 dataset_path: str,
217 config: GPTDatasetConfig,
218 ) -> IndexedDataReader:
219 """Build the low-level Dataset used by a concrete pretraining Dataset."""
220 del dataset_path, config
221 raise NotImplementedError
223 @staticmethod
224 def _key_config_attributes() -> list[str]:
225 """Return config fields that contribute to the Dataset cache identity."""
226 return [
227 "random_seed",
228 "sequence_length",
229 "split",
230 "split_matrix",
231 "tokenizer",
232 "drop_last_partial_validation_sequence",
233 "add_extra_token_to_sequence",
234 ]
236 @classmethod
237 def build_unique_identifiers(
238 cls,
239 dataset_path: str | None,
240 num_samples: int,
241 index_split: Any,
242 config: GPTDatasetConfig,
243 ) -> OrderedDict[str, Any]:
244 """Build the stable cache identity without constructing a Dataset.
246 Args:
247 dataset_path: Prefix of the indexed Dataset files.
248 num_samples: Requested number of samples.
249 index_split: Train, validation, or test split identifier.
250 config: Indexed GPT Dataset configuration.
252 Returns:
253 Ordered cache identity matching an instantiated Dataset.
254 """
255 identifiers = OrderedDict()
256 identifiers["class"] = cls.__name__
257 identifiers["dataset_path"] = dataset_path
258 identifiers["num_samples"] = num_samples
259 identifiers["index_split"] = index_split.name.lower()
260 for attribute in cls._key_config_attributes():
261 identifiers[attribute] = getattr(config, attribute)
262 return identifiers
264 @abstractmethod
265 def __len__(self) -> int:
266 """Return the number of samples exposed by the Dataset."""
268 @abstractmethod
269 def __getitem__(self, index: int) -> Mapping[str, Any]:
270 """Return one raw pretraining sample."""
273class _MockDataset(_IndexedPretrainDataset):
274 """Base class for mock Datasets that do not use a low-level reader."""
276 def __init__(
277 self,
278 dataset: IndexedDataReader | None,
279 dataset_path: str | None,
280 indices: np.ndarray | None,
281 num_samples: int,
282 index_split: Any,
283 config: GPTDatasetConfig,
284 ) -> None:
285 """Validate mock mode and initialize the common Dataset state."""
286 self.config = config
287 if not self.config.mock:
288 raise ValueError("config.mock must be True for MockDataset")
289 super().__init__(dataset, dataset_path, indices, num_samples, index_split, config)
291 def __len__(self) -> int:
292 """Return the configured number of mock samples."""
293 return self.num_samples
296class MockGPTDataset(_MockDataset):
297 """Generate deterministic, fixed-length mock GPT samples."""
299 def _finalize(self) -> None:
300 """Require the EOD token inserted into each generated sample."""
302 if getattr(self.config.tokenizer, "eod", None) is None:
303 raise ValueError("MockGPTDataset requires a tokenizer with an EOD token ID")
305 def __getitem__(self, index: int) -> Mapping[str, Any]:
306 """Generate a deterministic mock sample for one split and index."""
307 token = 1
308 pad = self._pad_token_id
309 eod = self.config.tokenizer.eod
311 if index >= self.num_samples:
312 raise ValueError(
313 f"Exceeded the available number of samples ({self.num_samples}); got {index}"
314 )
316 rng = np.random.default_rng(seed=[self.index_split.value, index])
317 length = rng.integers(low=0, high=self.config.sequence_length)
318 sample_tokens = np.zeros(length) + token
319 sample_pads = np.zeros(self.config.sequence_length - length - 1) + pad
320 sample = np.int64(np.concatenate([[length], sample_tokens, [eod], sample_pads]))
321 tokens = sample[:-1].copy()
322 labels = sample[1:].copy()
323 ltor_fields = self._build_ltor_fields(tokens, labels)
324 tokens[tokens == self._pad_token_id] = 0
325 labels[labels == self._pad_token_id] = IGNORE_INDEX
327 raw_sample = {
328 "input_ids": tokens,
329 "labels": labels,
330 }
331 raw_sample.update(ltor_fields)
333 return raw_sample
336class GPTDataset(_IndexedPretrainDataset):
337 """Build fixed-length GPT samples from an indexed token stream."""
339 @staticmethod
340 def validate_config(config: GPTDatasetConfig) -> None:
341 """Require an EOD token ID when document boundaries come from tokens.
343 Args:
344 config: Indexed GPT Dataset configuration.
346 Raises:
347 ValueError: If EOD-based boundaries are selected without an EOD token ID.
348 """
350 if not config.inter_document_masking and getattr(config.tokenizer, "eod", None) is None:
351 raise ValueError("GPTDataset requires an EOD token ID when inter_document_masking=False")
353 def _finalize(self) -> None:
354 """Build the document, sample, and shuffle indices for the token stream."""
355 if self.dataset is None or self.indices is None:
356 raise ValueError("GPTDataset requires a low-level Dataset and split indices")
358 self.validate_config(self.config)
359 self.document_index, self.sample_index, self.shuffle_index = self._build_document_sample_shuffle_indices()
361 def _plan_epochs(self, num_tokens_per_epoch: int) -> tuple[int, bool, int]:
362 """Choose the epoch count and whether to shuffle a short final epoch separately."""
363 num_epochs = 0
364 accumulated_tokens = 0
365 extra_token = int(self.config.add_extra_token_to_sequence)
366 requested_tokens = self.num_samples * self.config.sequence_length + extra_token
367 while accumulated_tokens < requested_tokens:
368 num_epochs += 1
369 accumulated_tokens += num_tokens_per_epoch
371 if num_epochs == 1:
372 separate_final_epoch = False
373 samples_without_final_epoch = 0
374 else:
375 samples_without_final_epoch = (
376 (num_epochs - 1) * num_tokens_per_epoch - extra_token
377 ) // self.config.sequence_length
378 samples_from_final_epoch = self.num_samples - samples_without_final_epoch
379 samples_per_epoch = (num_tokens_per_epoch - extra_token) // self.config.sequence_length
381 # Keep a small final epoch separate from the main shuffled range.
382 threshold = 0.80
383 separate_final_epoch = samples_from_final_epoch < int(threshold * samples_per_epoch)
384 return num_epochs, separate_final_epoch, samples_without_final_epoch
386 def _build_document_sample_shuffle_indices(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
387 """Build or load the document, sample, and shuffle indices.
389 The document index:
390 -- 1-D
391 -- An ordered array of document ids
393 The sample index:
394 -- 2-D
395 -- The document indices and offsets which mark the start of every sample
397 The shuffle index:
398 -- 1-D
399 -- A random permutation of index range of the sample index
401 Returns:
402 The document, sample, and shuffle index arrays.
403 """
404 # pylint: disable=too-many-locals
405 cache_directory = self.config.path_to_cache
406 if cache_directory is None:
407 cache_directory = os.path.join(self.dataset.path_prefix, "cache", f"{type(self).__name__}_indices")
408 cache_key = f"{self.unique_description_hash}-{type(self).__name__}"
410 # drop last for train/test, valid drop depended on config
411 if self.index_split.name.lower() == "valid":
412 drop_last_partial_sequence = self.config.drop_last_partial_validation_sequence
413 else:
414 drop_last_partial_sequence = True
416 cache_paths = {
417 "description": os.path.join(cache_directory, f"{cache_key}-description.txt"),
418 "document": os.path.join(cache_directory, f"{cache_key}-document_index.npy"),
419 "sample": os.path.join(cache_directory, f"{cache_key}-sample_index.npy"),
420 "shuffle": os.path.join(cache_directory, f"{cache_key}-shuffle_index.npy"),
421 }
423 # read from cache
424 cache_hit = all(os.path.isfile(path) for path in cache_paths.values())
425 if cache_hit:
426 logger.debug("Loading indexed sample cache: key=%s, directory=%s", cache_key, cache_directory, enabled=True)
427 document_index = np.load(cache_paths["document"], mmap_mode="r")
428 sample_index = np.load(cache_paths["sample"], mmap_mode="r")
429 shuffle_index = np.load(cache_paths["shuffle"], mmap_mode="r")
431 return document_index, sample_index, shuffle_index
433 # build cache
434 start_time = time.time()
435 num_tokens_per_epoch = int(np.sum(self.dataset.sequence_lengths[self.indices]))
436 if num_tokens_per_epoch <= 1:
437 raise ValueError("The selected indexed split must contain at least two tokens")
439 num_epochs, separate_final_epoch, samples_without_final_epoch = self._plan_epochs(num_tokens_per_epoch)
440 random_state = RandomState(self.config.random_seed)
442 # Shuffle the repeated document IDs, optionally isolating the final epoch.
443 document_index = _build_document_index(self.indices, num_epochs, random_state, separate_final_epoch)
445 # Convert the shuffled token stream into fixed-length sample boundaries in C++.
446 # Keep the optional C++ extension out of the pre-packed MindRecord path.
447 from hyper_parallel.data.offline.helpers import build_sample_index # pylint: disable=C0415
449 sample_index = build_sample_index(
450 self.dataset.sequence_lengths,
451 document_index,
452 self.config.sequence_length,
453 num_epochs,
454 num_tokens_per_epoch,
455 drop_last_partial_sequence,
456 self.config.add_extra_token_to_sequence,
457 )
459 # Shuffle samples without mixing an isolated final epoch into the main range.
460 if separate_final_epoch:
461 shuffle_index = _build_shuffle_index(samples_without_final_epoch, sample_index.shape[0] - 1, random_state)
462 else:
463 shuffle_index = _build_shuffle_index(sample_index.shape[0] - 1, sample_index.shape[0] - 1, random_state)
465 os.makedirs(cache_directory, exist_ok=True)
466 np.save(cache_paths["document"], document_index)
467 np.save(cache_paths["sample"], sample_index)
468 np.save(cache_paths["shuffle"], shuffle_index)
469 # Write the description last so readers treat it as the cache completion marker.
470 with open(cache_paths["description"], "w", encoding="utf-8") as description_file:
471 description_file.write(self.unique_description)
473 logger.debug(
474 "Built indexed sample cache: samples=%d, epochs=%d, elapsed=%.4f seconds",
475 self.num_samples, num_epochs, time.time() - start_time,
476 )
477 return document_index, sample_index, shuffle_index
479 @staticmethod
480 def numel_low_level_dataset(low_level_dataset: IndexedDataReader) -> int:
481 """Return the number of low-level sequences available for splitting."""
482 return int(low_level_dataset.sequence_lengths.shape[0])
484 @staticmethod
485 def build_low_level_dataset(
486 dataset_path: str,
487 config: GPTDatasetConfig,
488 ) -> IndexedDataReader:
489 """Open the low-level indexed token reader."""
490 return IndexedDataReader(dataset_path, mmap=config.mmap_bin_files)
492 def __len__(self) -> int:
493 """Return the number of complete fixed-length samples."""
494 return int(self.sample_index.shape[0] - 1)
496 def __getitem__(self, index: int) -> Mapping[str, Any]:
497 """Read, shift, and mask one shuffled GPT sample."""
498 text, _, document_lengths = self._query_document_sample_shuffle_indices(index)
500 if self.config.add_extra_token_to_sequence:
501 tokens = text[:-1].copy()
502 labels = text[1:].copy()
503 else:
504 tokens = text.copy()
505 labels = np.roll(text, shift=-1)
506 labels[-1] = self._pad_token_id
508 document_boundaries = None
509 if self.config.inter_document_masking:
510 document_lengths = [length for length in document_lengths if length > 0]
512 # The extra token produces the shifted labels. Subtract it if it was
513 # read from the last document part so cu_seq_lens indexes the input
514 # tokens. An extra token supplied by padding is outside document_lengths.
515 if self.config.add_extra_token_to_sequence and sum(document_lengths) > tokens.size:
516 document_lengths[-1] -= 1
517 if document_lengths[-1] == 0:
518 document_lengths.pop()
520 # Fold sample padding into the last document so cu_seq_lens[-1]
521 # equals the input sequence length.
522 shortfall = tokens.size - sum(document_lengths)
523 if shortfall > 0:
524 if document_lengths:
525 document_lengths[-1] += shortfall
526 else:
527 document_lengths.append(shortfall)
528 document_boundaries = np.cumsum([0] + document_lengths, dtype=np.int32)
530 ltor_fields = self._build_ltor_fields(tokens, labels, document_boundaries)
532 # For padded sequences, ensure the embedding layer can map the token ID
533 tokens[tokens == self._pad_token_id] = 0
534 labels[labels == self._pad_token_id] = IGNORE_INDEX
536 if np.any(tokens < 0) or np.any(tokens >= len(self.config.tokenizer)):
537 raise ValueError("An input token is out of bounds of the tokenizer vocabulary")
539 raw_sample = {
540 "input_ids": tokens,
541 "labels": labels,
542 }
543 raw_sample.update(ltor_fields)
545 if document_boundaries is not None:
546 # Pad cu_seq_lens to a fixed length so default_collate can stack
547 # samples with different numbers of documents. The boundary resolver
548 # strips trailing entries that repeat the sequence length.
549 boundaries = np.full(tokens.size + 1, tokens.size, dtype=np.int32)
550 boundaries[:document_boundaries.size] = document_boundaries
551 raw_sample["cu_seq_lens"] = boundaries
553 return raw_sample
555 def _query_document_sample_shuffle_indices(
556 self,
557 index: int,
558 ) -> tuple[np.ndarray, np.ndarray, list[int]]:
559 """Get the text (token ids) and document ids for a given index
561 Args:
562 index (int): The index into the dataset
564 Returns:
565 The text ids, document ids, and per-document token counts (before any padding).
566 """
567 shuffled_index = int(self.shuffle_index[index])
568 begin_document, begin_offset = self.sample_index[shuffled_index]
569 end_document, end_offset = self.sample_index[shuffled_index + 1]
571 document_ids = []
572 sample_parts = []
574 # Read one contiguous slice when the sample stays within a document.
575 if begin_document == end_document:
576 document_id = int(self.document_index[begin_document])
577 document_ids.append(document_id)
578 sample_parts.append(
579 self.dataset.get(
580 document_id,
581 offset=int(begin_offset),
582 length=int(end_offset - begin_offset + self.config.add_extra_token_to_sequence),
583 )
584 )
586 # Concatenate slices when the sample crosses document boundaries.
587 else:
588 for document_position in range(int(begin_document), int(end_document) + 1):
589 document_id = int(self.document_index[document_position])
590 document_ids.append(document_id)
591 offset = 0 if document_position > begin_document else int(begin_offset)
592 length = (
593 None
594 if document_position < end_document
595 else int(end_offset + self.config.add_extra_token_to_sequence)
596 )
597 sample_parts.append(self.dataset.get(document_id, offset=offset, length=length))
599 # Retained partial samples still need the configured fixed length.
600 length = sum(map(len, sample_parts))
601 document_lengths = [len(p) for p in sample_parts]
603 if length < (self.config.sequence_length + self.config.add_extra_token_to_sequence):
604 sample_parts.append(
605 [self._pad_token_id]
606 * (self.config.sequence_length + self.config.add_extra_token_to_sequence - length)
607 )
609 text = np.asarray(np.concatenate(sample_parts), dtype=np.int64)
611 return text, np.asarray(document_ids, dtype=np.int64), document_lengths
614class GPTFromMRDataset(_IndexedPretrainDataset):
615 """GPT Dataset for pre-packed samples converted from MindRecord.
617 Each entry in the underlying indexed Dataset represents a complete pre-packed
618 training sample. Samples are read directly without rebuilding document, sample,
619 or shuffle indices.
621 Args:
622 dataset: The indexed Dataset containing pre-packed samples converted from MindRecord.
624 dataset_path: The path to the underlying indexed Dataset.
626 indices: The indices of the pre-packed samples exposed by this Dataset.
628 num_samples: The number of pre-packed samples to draw from the indexed Dataset.
630 index_split: The Dataset split associated with ``indices``.
632 config: The GPT-specific Dataset configuration.
633 """
635 def _finalize(self) -> None:
636 """Validate the low-level Dataset and the pre-cut record lengths."""
637 if self.dataset is None or self.indices is None:
638 raise ValueError("GPTFromMRDataset requires a low-level Dataset and split indices")
640 if not isinstance(self.config, GPTDatasetConfig):
641 raise ValueError("GPTFromMRDataset requires GPTDatasetConfig")
643 if not self.config.skip_data_check:
644 expected_length = self.config.sequence_length + self.config.add_extra_token_to_sequence
645 if not np.all(self.dataset.sequence_lengths == expected_length):
646 raise ValueError(
647 "All pre-cut records must match sequence_length + add_extra_token_to_sequence; "
648 f"expected {expected_length}, got {self.dataset.sequence_lengths.tolist()}"
649 )
650 if self.num_samples > len(self.indices):
651 raise ValueError(
652 "Requested samples exceed the pre-cut records in this split: "
653 f"requested {self.num_samples}, available {len(self.indices)}"
654 )
656 @staticmethod
657 def numel_low_level_dataset(low_level_dataset: IndexedDataReader) -> int:
658 """Return the number of pre-cut records available for splitting."""
659 return int(low_level_dataset.sequence_lengths.shape[0])
661 @staticmethod
662 def is_multimodal() -> bool:
663 """Return whether records contain multimodal sequence modes."""
664 return False
666 @staticmethod
667 def is_split_by_sequence() -> bool:
668 """Return whether train/validation/test boundaries use sequence indices."""
669 return True
671 @staticmethod
672 def build_low_level_dataset(
673 dataset_path: str,
674 config: GPTDatasetConfig,
675 ) -> IndexedDataReader:
676 """Open a low-level reader for pre-cut records."""
677 return IndexedDataReader(
678 dataset_path,
679 mmap=config.mmap_bin_files,
680 reuse_index=config.reuse_idx,
681 )
683 def __len__(self) -> int:
684 """Return the requested number of pre-cut records in this split."""
685 return self.num_samples
687 def __getitem__(self, index: int) -> Mapping[str, Any]:
688 """Read and shift one pre-cut record without dynamic concatenation."""
689 sequence_id = int(self.indices[index])
690 text = np.asarray(self.dataset[sequence_id], dtype=np.int64)
691 if np.any(text == self._pad_token_id):
692 raise ValueError("Pre-cut indexed Dataset records must be packed without padding")
694 if self.config.add_extra_token_to_sequence:
695 tokens = text[:-1].copy()
696 labels = text[1:].copy()
697 else:
698 tokens = text.copy()
699 labels = np.roll(text, shift=-1)
700 labels[-1] = self._pad_token_id
702 if np.any(tokens < 0) or np.any(tokens >= len(self.config.tokenizer)):
703 raise ValueError("An input token is out of bounds of the tokenizer vocabulary")
705 ltor_fields = self._build_ltor_fields(tokens, labels)
707 tokens[tokens == self._pad_token_id] = 0
708 labels[labels == self._pad_token_id] = IGNORE_INDEX
710 raw_sample = {
711 "input_ids": tokens,
712 "labels": labels,
713 }
714 raw_sample.update(ltor_fields)
716 return raw_sample
719def _get_ltor_masks_and_position_ids_from_eod(
720 tokens: np.ndarray,
721 config: GPTDatasetConfig,
722) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
723 """Build LTR fields by locating EOD tokens in the input sequence.
725 Args:
726 tokens: Token IDs for one fixed-length Indexed sample.
727 config: Indexed Dataset runtime-field configuration.
729 Returns:
730 Attention mask, loss mask, and position IDs.
731 """
732 seq_length = tokens.size
733 eod_token = getattr(config.tokenizer, "eod", None)
734 attention_mask = np.tril(np.ones((seq_length, seq_length)))[None, :, :]
736 # Loss mask.
737 loss_mask = np.ones(seq_length, dtype=np.float32)
738 if config.eod_mask_loss and eod_token is not None:
739 loss_mask[tokens == eod_token] = 0.0
741 # Position ids.
742 position_ids = np.arange(seq_length, dtype=np.int64)
743 if (config.reset_position_ids or config.reset_attention_mask) and eod_token is not None:
744 next_indices = np.flatnonzero(tokens == eod_token) + 1
745 prev_index = 0
747 for next_index in next_indices:
748 next_index = int(next_index)
750 if config.reset_attention_mask:
751 attention_mask[0, next_index:, :next_index] = 0
753 if config.reset_position_ids:
754 position_ids[next_index:] -= next_index - prev_index
755 prev_index = next_index
757 # Convert attention mask to binary:
758 attention_mask = attention_mask < 0.5
760 return attention_mask, loss_mask, position_ids
763def _get_ltor_masks_and_position_ids_from_boundaries(
764 tokens: np.ndarray,
765 config: GPTDatasetConfig,
766 document_boundaries: np.ndarray,
767) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
768 """Build document-isolated LTR fields for Indexed packing without EOD tokens.
770 Args:
771 tokens: Token IDs for one fixed-length Indexed sample.
772 config: Indexed Dataset runtime-field configuration.
773 document_boundaries: Leading-zero input boundaries built from Indexed lengths.
775 Returns:
776 Attention mask, loss mask, and positions reset within each document.
777 """
778 seq_length = tokens.size
779 attention_mask = np.tril(np.ones((seq_length, seq_length)))[None, :, :]
780 loss_mask = np.ones(seq_length, dtype=np.float32)
781 eod_token = getattr(config.tokenizer, "eod", None)
783 if config.eod_mask_loss and eod_token is not None:
784 loss_mask[tokens == eod_token] = 0.0
786 # Reset position IDs per document.
787 position_ids = np.empty(seq_length, dtype=np.int64)
788 for start, end in zip(document_boundaries[:-1], document_boundaries[1:]):
789 attention_mask[0, start:end, :start] = 0
790 position_ids[start:end] = np.arange(end - start, dtype=np.int64)
792 attention_mask = attention_mask < 0.5
794 return attention_mask, loss_mask, position_ids
797class SFTFromMRDataset:
798 """Prepared Arrow records with authoritative next-token labels and boundaries.
800 Each row is kept intact, without tokenization, shifting, EOS insertion or
801 truncation. Field names can be mapped inside ``low_level_dataset`` using
802 input_ids_key, labels_key, boundaries_key and loss_mask_key. Missing boundaries
803 mean one document. Optional binary loss_mask is folded into owned labels.
804 """
806 def __init__(
807 self, dataset: ArrowDataReader, dataset_path: str, indices: np.ndarray,
808 num_samples: int, index_split: Any, config: GPTDatasetConfig,
809 ) -> None:
810 """Store whole-record sampling inputs without building GPT packing caches."""
811 self.dataset = dataset
812 self.indices = indices
813 self.num_samples = num_samples
814 self.config = config
815 self.unique_identifiers = self.build_unique_identifiers(dataset_path, num_samples, index_split, config)
816 if self.config.simple_blend not in ("inter", "intra"):
817 raise ValueError("Prepared Arrow datasets require simple_blend='inter' or 'intra'")
818 if self.num_samples > len(self.indices):
819 raise ValueError("Requested samples exceed prepared records in this split")
821 @staticmethod
822 def numel_low_level_dataset(low_level_dataset: ArrowDataReader) -> int:
823 """Split by complete records rather than by inner documents."""
824 return len(low_level_dataset)
826 @staticmethod
827 def build_low_level_dataset(dataset_path: str, config: GPTDatasetConfig) -> ArrowDataReader:
828 """Open the Arrow reader used by the existing split builder."""
829 del config
830 return ArrowDataReader(dataset_path)
832 @classmethod
833 def build_unique_identifiers(
834 cls, dataset_path: str, num_samples: int, index_split: Any, config: GPTDatasetConfig,
835 ) -> dict[str, Any]:
836 """Identify the record view without opening Arrow files during lazy setup."""
837 return {"class": cls.__name__, "dataset_path": dataset_path, "num_samples": num_samples,
838 "index_split": index_split.name.lower(), "split": config.split,
839 "dataset_options": config.dataset_options}
841 def __len__(self) -> int:
842 """Return the requested record count."""
843 return self.num_samples
845 def __getitem__(self, index: int) -> Mapping[str, Any]:
846 """Read labels unchanged except for explicit binary mask suppression."""
847 sample = self.dataset[int(self.indices[index])]
848 fields = self.config.dataset_options
849 tokens = np.asarray(sample[fields.get("input_ids_key", "input_ids")])
850 labels = np.asarray(sample[fields.get("labels_key", "labels")])
851 boundaries = np.asarray(sample.get(fields.get("boundaries_key", "cu_seq_lens"), [0, tokens.size]))
852 boundaries = self._validate_record_layout(tokens, labels, boundaries, int(self.indices[index]))
853 if (np.any(tokens < 0) or np.any(tokens >= self.config.tokenizer.vocab_size)
854 or np.any((labels < 0) & (labels != IGNORE_INDEX))
855 or np.any(labels >= self.config.tokenizer.vocab_size)):
856 raise ValueError("Prepared token/label IDs must fit the vocabulary; ignored labels must be -100")
857 # Arrow buffers may be shared/read-only; never modify their supervision in place.
858 labels = labels.astype(np.int64, copy=True)
859 mask = sample.get(fields.get("loss_mask_key", "loss_mask"))
860 if mask is not None:
861 mask = np.asarray(mask)
862 if mask.shape != labels.shape or not np.isin(mask, (0, 1)).all():
863 raise ValueError("loss_mask must be binary and match labels")
864 labels[mask == 0] = IGNORE_INDEX
865 if not np.any(labels != IGNORE_INDEX):
866 raise ValueError("Prepared record has no effective targets")
867 return {"input_ids": tokens.astype(np.int64), "labels": labels,
868 "cu_seq_lens": boundaries.astype(np.int32)}
870 def _validate_record_layout(
871 self, tokens: np.ndarray, labels: np.ndarray, boundaries: np.ndarray, record_index: int,
872 ) -> np.ndarray:
873 """Check record shapes, configured length and internal document boundaries."""
874 if (tokens.ndim != 1 or not tokens.size or labels.shape != tokens.shape
875 or tokens.dtype.kind not in "iu" or labels.dtype.kind not in "iu"):
876 raise ValueError("Prepared tokens and labels must be matching nonempty 1D integer arrays")
877 if not self.config.skip_data_check and tokens.size != self.config.sequence_length:
878 raise ValueError(
879 "Prepared record must match seq_length; "
880 f"record {record_index}: expected {self.config.sequence_length}, got {tokens.size}"
881 )
882 boundaries = boundaries[boundaries != -1] if boundaries.ndim == 1 else boundaries
883 if (boundaries.ndim != 1 or boundaries.dtype.kind not in "iu" or boundaries.size < 2
884 or boundaries[0] != 0 or boundaries[-1] != tokens.size
885 or np.any(boundaries[1:] <= boundaries[:-1]) or tokens.size > np.iinfo(np.int32).max):
886 raise ValueError("Document boundaries must strictly increase from zero to token count")
887 return boundaries