from __future__ import annotations import math import glob from bisect import bisect_right from collections.abc import Sequence from pathlib import Path import numpy as np import torch class PackedTokenDataset: """Read fixed-length Hugging Face causal-LM samples from uint16 streams. Labels intentionally mirror ``input_ids`` because causal language-model heads such as ``LlamaForCausalLM`` perform the one-token label shift inside their loss function. """ def __init__( self, path: str | Path | Sequence[str | Path], sequence_length: int, ) -> None: if sequence_length <= 0: raise ValueError("sequence_length must be positive") raw_paths = [path] if isinstance(path, (str, Path)) else list(path) resolved: set[Path] = set() for raw_path in raw_paths: value = str(raw_path) matches = [Path(item) for item in glob.glob(value)] if matches: resolved.update(item.resolve() for item in matches if item.is_file()) else: candidate = Path(raw_path) if candidate.is_file(): resolved.add(candidate.resolve()) self.paths = sorted(resolved) if not self.paths: raise FileNotFoundError(f"No token binaries found for: {raw_paths}") self.path = self.paths[0] self.sequence_length = sequence_length self.token_streams = [ np.memmap(item, mode="r", dtype=np.uint16) for item in self.paths ] sequence_counts = [ max(0, (len(tokens) - 1) // self.sequence_length) for tokens in self.token_streams ] self.sequence_offsets: list[int] = [] running_total = 0 for count in sequence_counts: running_total += count self.sequence_offsets.append(running_total) self.num_sequences = running_total if self.num_sequences == 0: raise ValueError( f"{self.paths} need at least {self.sequence_length + 1} tokens" ) self._affine_cache: dict[int, tuple[int, int]] = {} def __len__(self) -> int: return self.num_sequences def sequence(self, index: int) -> np.ndarray: if not 0 <= index < self.num_sequences: raise IndexError(index) stream_index = bisect_right(self.sequence_offsets, index) previous_offset = ( self.sequence_offsets[stream_index - 1] if stream_index > 0 else 0 ) local_index = index - previous_offset start = local_index * self.sequence_length return np.asarray( self.token_streams[stream_index][ start : start + self.sequence_length + 1 ], dtype=np.int64, ) def _affine_parameters(self, epoch: int, seed: int) -> tuple[int, int]: cache_key = (seed << 32) ^ epoch if cache_key in self._affine_cache: return self._affine_cache[cache_key] rng = np.random.default_rng(seed + epoch * 1_000_003) multiplier = int(rng.integers(1, max(self.num_sequences, 2))) while math.gcd(multiplier, self.num_sequences) != 1: multiplier += 1 if multiplier >= self.num_sequences: multiplier = 1 offset = int(rng.integers(0, self.num_sequences)) self._affine_cache[cache_key] = (multiplier, offset) return multiplier, offset def training_batch( self, *, micro_step: int, batch_size: int, rank: int, world_size: int, seed: int, sample_offset: int = 0, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: if sample_offset < 0: raise ValueError("sample_offset must be non-negative") global_batch_size = batch_size * world_size first_ordinal = ( sample_offset + micro_step * global_batch_size + rank * batch_size ) rows: list[np.ndarray] = [] for local_index in range(batch_size): ordinal = first_ordinal + local_index epoch, position = divmod(ordinal, self.num_sequences) multiplier, offset = self._affine_parameters(epoch, seed) sequence_index = (multiplier * position + offset) % self.num_sequences rows.append(self.sequence(sequence_index)) return self._to_tensors(rows, device) def evaluation_batch( self, *, batch_index: int, batch_size: int, rank: int, world_size: int, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: first = (batch_index * world_size + rank) * batch_size rows = [ self.sequence((first + offset) % self.num_sequences) for offset in range(batch_size) ] return self._to_tensors(rows, device) @staticmethod def _to_tensors( rows: list[np.ndarray], device: torch.device ) -> tuple[torch.Tensor, torch.Tensor]: batch = torch.from_numpy(np.stack(rows, axis=0)) inputs = batch[:, :-1].to(device=device, dtype=torch.long, non_blocking=True) labels = inputs.clone() return inputs, labels