File size: 6,608 Bytes
643267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Document-local framing, fixed chunks, and next-token supervision.

Input pieces contain content IDs, followed by EOD only when the original
document ends. Each piece gets one BOS; PAT also appends summary rows after
each chunk. Targets follow the original token stream across chunk boundaries,
and never cross a piece boundary or train the appended summary rows.
"""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass

import torch

from .config import BOS_ID, EOC_ID, EOD_ID, PATConfig


@dataclass
class PackedBatch:
    token_ids: torch.Tensor
    lexical_positions: torch.Tensor
    source_indices: torch.Tensor
    targets: torch.Tensor
    piece_lengths: tuple[int, ...]
    row_lengths: tuple[int, ...]
    row_content_lengths: tuple[int, ...]
    row_offsets: tuple[int, ...]
    chunk_piece_ids: tuple[int, ...]
    piece_chunk_bases: tuple[int, ...]
    chunks_per_piece: tuple[int, ...]
    eoc_positions: tuple[tuple[int, ...], ...]

    @property
    def token_count(self) -> int:
        return self.targets.numel()

    @property
    def lexical_token_count(self) -> int:
        return int(self.targets.ne(EOD_ID).sum().item())

    def geometry(self, config: PATConfig):
        from .kernels.attention import FixedGeometry

        device = self.token_ids.device
        tensor = lambda values: torch.tensor(values, device=device, dtype=torch.long)
        key = (
            "packed_training",
            True,
            len(self.row_lengths),
            max(self.row_lengths),
            self.token_ids.numel(),
            config.chunk_size,
            config.memory_slots[0],
            config.max_memory_size,
            self.chunks_per_piece,
            tuple(
                (i, size)
                for i, size in enumerate(self.row_content_lengths)
                if size != config.chunk_size
            ),
        )
        return FixedGeometry(
            row_offsets=tensor(self.row_offsets),
            row_lengths=tensor(self.row_lengths),
            row_content_lengths=tensor(self.row_content_lengths),
            chunk_piece_id=tensor(self.chunk_piece_ids),
            piece_chunk_base=tensor(self.piece_chunk_bases),
            eoc_abs_idx=tensor(self.eoc_positions),
            token_count=self.token_ids.numel(),
            max_row_length=max(self.row_lengths),
            max_chunk_index=max(self.chunks_per_piece) - 1,
            planner_cache_key=key,
        )


def pack_pieces(
    pieces: Sequence[torch.Tensor],
    config: PATConfig,
    *,
    device: torch.device,
    document_ends: Sequence[bool] | None = None,
    for_inference: bool = False,
) -> PackedBatch:
    if not pieces:
        raise ValueError("at least one document piece is required")
    if document_ends is not None and len(document_ends) != len(pieces):
        raise ValueError("document_ends needs one flag per piece")
    token_parts, targets, sources, lexical_positions = [], [], [], []
    (
        row_lengths,
        row_contents,
        row_offsets,
        chunk_piece_ids,
        piece_bases,
        chunk_counts,
        eoc_positions,
    ) = [], [], [], [], [], [], []
    piece_lengths = []
    physical_cursor = lexical_cursor = 0
    slots = config.memory_slots[0]
    for index, piece in enumerate(pieces):
        if piece.ndim != 1 or piece.dtype not in {torch.int32, torch.int64}:
            raise ValueError("pieces must be rank-one integer tensors")
        piece = piece.to(device=device, dtype=torch.long)
        # Every input token is either content or the final EOD. This prevents
        # accidental double framing when importing tokenized corpora.
        if piece.numel() and bool(((piece < 0) | (piece > EOD_ID)).any().item()):
            raise ValueError("input pieces may contain only content IDs and terminal EOD")
        ends = bool(piece.numel() and piece[-1].item() == EOD_ID)
        if piece.numel() > 1 and bool(piece[:-1].eq(EOD_ID).any().item()):
            raise ValueError("EOD may appear only at a document's end")
        if document_ends is not None and bool(document_ends[index]) != ends:
            raise ValueError("document_ends must agree with the terminal EOD token")
        if piece.numel() - int(ends) > config.context_length:
            raise ValueError("piece exceeds context_length; split it before batching")
        if config.architecture == "FA" and not for_inference:
            if not piece.numel():
                raise ValueError("FA training needs at least one target per piece")
            # The final target has no following target of its own. Omitting
            # that unused input preserves the producer's FlashAttention and
            # projection shapes, including their finite-precision arithmetic.
            framed = torch.cat((piece.new_tensor([BOS_ID]), piece[:-1]))
        else:
            framed = torch.cat((piece.new_tensor([BOS_ID]), piece))
        length = framed.numel()
        piece_lengths.append(length)
        targets.append(piece)
        sources.extend(range(lexical_cursor, lexical_cursor + piece.numel()))
        lexical_cursor += length
        piece_bases.append(len(row_lengths))
        count = 0
        step = config.chunk_size if config.architecture == "PAT" else length
        for start in range(0, length, step):
            row = framed[start : start + step]
            size = row.numel()
            row_offsets.append(physical_cursor)
            row_contents.append(size)
            row_lengths.append(size + slots)
            chunk_piece_ids.append(index)
            lexical_positions.extend(range(physical_cursor, physical_cursor + size))
            tail = tuple(range(physical_cursor + size, physical_cursor + size + slots))
            eoc_positions.append(tail)
            token_parts.append(torch.cat((row, row.new_full((slots,), EOC_ID))))
            physical_cursor += size + slots
            count += 1
        chunk_counts.append(count)
    return PackedBatch(
        token_ids=torch.cat(token_parts),
        lexical_positions=torch.tensor(lexical_positions, device=device),
        source_indices=torch.tensor(sources, device=device, dtype=torch.long),
        targets=torch.cat(targets),
        piece_lengths=tuple(piece_lengths),
        row_lengths=tuple(row_lengths),
        row_content_lengths=tuple(row_contents),
        row_offsets=tuple(row_offsets),
        chunk_piece_ids=tuple(chunk_piece_ids),
        piece_chunk_bases=tuple(piece_bases),
        chunks_per_piece=tuple(chunk_counts),
        eoc_positions=tuple(eoc_positions),
    )