File size: 5,431 Bytes
91ac3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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