Download kawk50m/sft_dataset.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 5.43 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/kawk50m/sft_dataset.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/kawk50m/sft_dataset.py
-
curl -L -o sft_dataset.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/kawk50m/sft_dataset.py
5.43 kB
| from __future__ import annotations | |
| import math | |
| from collections.abc import Sequence | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| class SFTPackedDataset: | |
| """Memory-map fixed-length input IDs and assistant-only loss masks.""" | |
| def __init__( | |
| self, | |
| prefixes: str | Path | Sequence[str | Path], | |
| sequence_length: int, | |
| ) -> None: | |
| if sequence_length <= 0: | |
| raise ValueError("sequence_length must be positive") | |
| raw_prefixes = ( | |
| [prefixes] if isinstance(prefixes, (str, Path)) else list(prefixes) | |
| ) | |
| self.sequence_length = sequence_length | |
| self.inputs: list[np.memmap] = [] | |
| self.masks: list[np.memmap] = [] | |
| self.sequence_offsets: list[int] = [] | |
| running_total = 0 | |
| for raw_prefix in raw_prefixes: | |
| prefix = Path(raw_prefix) | |
| input_path = Path(str(prefix) + ".input_ids.bin") | |
| mask_path = Path(str(prefix) + ".loss_mask.bin") | |
| if not input_path.is_file() or not mask_path.is_file(): | |
| raise FileNotFoundError( | |
| f"Missing SFT pair: {input_path} and {mask_path}" | |
| ) | |
| input_stream = np.memmap(input_path, mode="r", dtype=np.uint16) | |
| mask_stream = np.memmap(mask_path, mode="r", dtype=np.uint8) | |
| if len(input_stream) != len(mask_stream): | |
| raise ValueError(f"Input/mask length mismatch for {prefix}") | |
| if len(input_stream) % sequence_length != 0: | |
| raise ValueError(f"SFT data is not record-aligned: {prefix}") | |
| records = len(input_stream) // sequence_length | |
| if records == 0: | |
| raise ValueError(f"SFT data contains no records: {prefix}") | |
| self.inputs.append(input_stream) | |
| self.masks.append(mask_stream) | |
| running_total += records | |
| self.sequence_offsets.append(running_total) | |
| if not self.inputs: | |
| raise ValueError("At least one SFT data prefix is required") | |
| self.num_sequences = running_total | |
| self._affine_cache: dict[tuple[int, int], tuple[int, int]] = {} | |
| def __len__(self) -> int: | |
| return self.num_sequences | |
| def _locate(self, index: int) -> tuple[int, int]: | |
| if not 0 <= index < self.num_sequences: | |
| raise IndexError(index) | |
| previous = 0 | |
| for stream_index, end in enumerate(self.sequence_offsets): | |
| if index < end: | |
| return stream_index, index - previous | |
| previous = end | |
| raise IndexError(index) | |
| def sequence(self, index: int) -> tuple[np.ndarray, np.ndarray]: | |
| stream_index, local_index = self._locate(index) | |
| start = local_index * self.sequence_length | |
| stop = start + self.sequence_length | |
| return ( | |
| np.asarray(self.inputs[stream_index][start:stop], dtype=np.int64), | |
| np.asarray(self.masks[stream_index][start:stop], dtype=np.bool_), | |
| ) | |
| def _affine_parameters(self, epoch: int, seed: int) -> tuple[int, int]: | |
| key = (epoch, seed) | |
| if key in self._affine_cache: | |
| return self._affine_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[key] = (multiplier, offset) | |
| return multiplier, offset | |
| def training_batch( | |
| self, | |
| *, | |
| micro_step: int, | |
| batch_size: int, | |
| rank: int, | |
| world_size: int, | |
| seed: int, | |
| device: torch.device, | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| global_batch_size = batch_size * world_size | |
| first = micro_step * global_batch_size + rank * batch_size | |
| indices = [] | |
| for local_index in range(batch_size): | |
| ordinal = first + local_index | |
| epoch, position = divmod(ordinal, self.num_sequences) | |
| multiplier, offset = self._affine_parameters(epoch, seed) | |
| indices.append((multiplier * position + offset) % self.num_sequences) | |
| return self._to_tensors(indices, 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 | |
| indices = [ | |
| (first + local_index) % self.num_sequences | |
| for local_index in range(batch_size) | |
| ] | |
| return self._to_tensors(indices, device) | |
| def _to_tensors( | |
| self, | |
| indices: list[int], | |
| device: torch.device, | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| rows = [self.sequence(index) for index in indices] | |
| inputs = torch.from_numpy(np.stack([row[0] for row in rows])) | |
| masks = torch.from_numpy(np.stack([row[1] for row in rows])) | |
| inputs = inputs.to(device=device, dtype=torch.long, non_blocking=True) | |
| masks = masks.to(device=device, dtype=torch.bool, non_blocking=True) | |
| labels = inputs.clone() | |
| labels.masked_fill_(~masks, -100) | |
| return inputs, labels | |