File size: 8,637 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""Single-document PAT decoding with bounded summaries and one exact chunk.

Each lexical append projects only the new token. A completed chunk publishes
its EOC summaries for deeper layers and preserves its final lexical prediction
as the bridge into the following chunk. Canonical checkpoint tensors are never
modified by the cache.
"""

from __future__ import annotations

import torch
from torch.nn import functional as F

from .config import BOS_ID, EOC_ID, EOD_ID
from .kernels.decoding import attend, prepare_one
from .rotary import normalize_key


class PATCache:
    """Cached inference state for a single PAT document; use BF16 autocast."""

    @classmethod
    def prefill(cls, model, prompt_ids, *, capacity):
        if model.config.architecture != "PAT":
            raise ValueError("PATCache requires a PAT checkpoint")
        device = model.token_embed.weight.device
        if device.type != "cuda":
            raise RuntimeError("PAT cached decoding requires CUDA")
        prompt = torch.as_tensor(prompt_ids, device=device)
        if prompt.ndim != 1 or prompt.dtype not in {torch.int32, torch.int64}:
            raise ValueError("The prompt must be a one-dimensional integer sequence")
        if not prompt.numel() or bool(((prompt < 0) | (prompt >= EOD_ID)).any().item()):
            raise ValueError("The prompt must contain text without document or packing markers")
        if (
            type(capacity) is not int
            or not prompt.numel() + 1 <= capacity <= model.config.context_length
        ):
            raise ValueError("Cache capacity must fit BOS and the prompt within context_length")
        self = cls()
        self.model, self.capacity = model, capacity
        self.token_count = self.chunk_index = self.offset = 0
        self.device = device
        config = model.config
        geometry = (config.n_heads, config.head_dim)

        def arena(length):
            return torch.empty((length, *geometry), device=device, dtype=torch.bfloat16)

        self.keys = [arena(config.chunk_size + slots) for slots in config.memory_slots]
        self.values = [torch.empty_like(key) for key in self.keys]
        self.memory_keys = [arena(0)] + [
            arena(
                min(capacity // config.chunk_size, config.max_memory_size - 1)
                * config.memory_slots[index - 1]
            )
            for index in range(1, config.n_layers)
        ]
        self.memory_values = [torch.empty_like(key) for key in self.memory_keys]
        self.exact_keys = [arena(0) for _ in model.layers]
        self.exact_values = [arena(0) for _ in model.layers]
        # The published inference residual starts from a BF16 embedding shadow
        # converted back to FP32, while checkpoint parameters remain FP32.
        self.embedding = model.token_embed.weight.to(torch.bfloat16)
        self._append(BOS_ID)
        for token in prompt.tolist():
            self._append(int(token))
        return self

    def _embed(self, ids):
        tokens = torch.tensor(ids, device=self.device, dtype=torch.long)
        return F.embedding(tokens, self.embedding).to(self.model.token_embed.weight.dtype)

    def _positions(self, count, *, tail=False):
        chunk = self.model.config.chunk_size
        base = 0 if self.chunk_index == 0 else self.chunk_index + chunk - 1
        query = torch.arange(count, device=self.device, dtype=torch.long) + base + self.offset
        key = torch.full_like(query, base + chunk) if tail else query
        return query, key

    def _project_memory(self, layer, hidden):
        normalized = layer.norm1(hidden)
        width = self.model.config.d_model
        projected = F.linear(normalized, layer.qkv_proj.weight[width:], layer.qkv_proj.bias[width:])
        raw, value = projected.split(width, dim=-1)
        raw = raw.view(-1, layer.n_heads, layer.head_dim)
        value = value.view_as(raw)
        positions = torch.full(
            (raw.size(0),), self.chunk_index, device=self.device, dtype=torch.long
        )
        key = normalize_key(layer.rope(raw, positions), layer.qk_norm_eps)
        return key.contiguous(), value.contiguous()

    def _forward(self, hidden, *, tail):
        config = self.model.config
        pending = None
        updates = []
        for index, layer in enumerate(self.model.layers):
            positions, key_positions = self._positions(hidden.size(0), tail=tail)
            if tail:
                query, key, value, raw = type(layer).prepare(
                    layer, hidden, positions, key_positions
                )
                self.keys[index][self.offset : self.offset + key.size(0)].copy_(key)
                self.values[index][self.offset : self.offset + value.size(0)].copy_(value)
                if index:
                    if pending is not None:
                        updates.append(pending)
                        pending = None
                    else:
                        global_positions = torch.full_like(positions, self.chunk_index)
                        global_key = normalize_key(
                            layer.rope(raw, global_positions), layer.qk_norm_eps
                        )
                        updates.append((global_key.contiguous(), value.contiguous()))
            else:
                packed = layer.qkv_proj(layer.norm1(hidden))
                query = prepare_one(
                    packed, layer, positions, self.keys[index], self.values[index], self.offset
                )
            slots = config.memory_slots[max(0, index - 1)]
            used = self.chunk_index * slots if index else 0
            exact = (self.exact_keys[index], self.exact_values[index])
            context = attend(
                query,
                (self.memory_keys[index][:used], self.memory_values[index][:used]),
                exact,
                (self.keys[index], self.values[index]),
                offset=self.offset,
                lexical_count=self.offset if tail else self.offset + hidden.size(0),
                global_slots=slots,
                chunk_size=config.chunk_size,
                max_memory_size=config.max_memory_size,
                tail=tail,
            )
            hidden = type(layer).finish(layer, hidden, context, 0 if tail else hidden.size(0))
            if tail and str(index) in self.model.transitions:
                pending = self._project_memory(self.model.layers[index + 1], hidden)
                transition = self.model.transitions[str(index)]
                hidden = type(transition).forward(transition, hidden.unsqueeze(0)).squeeze(0)
        return hidden, updates

    def _append(self, token):
        hidden, _ = self._forward(self._embed([token]), tail=False)
        normalized = type(self.model.final_norm).forward(self.model.final_norm, hidden[-1])
        self.next_token_logits = F.linear(normalized, self.embedding).detach().contiguous()
        self.offset += 1
        self.token_count += 1
        if self.offset == self.model.config.chunk_size and self.token_count < self.capacity:
            _, updates = self._forward(
                self._embed([EOC_ID] * self.model.config.memory_slots[0]), tail=True
            )
            for index, (key, value) in enumerate(updates, start=1):
                start = self.chunk_index * key.size(0)
                self.memory_keys[index][start : start + key.size(0)].copy_(key)
                self.memory_values[index][start : start + value.size(0)].copy_(value)
            # The first completed chunk moves by -1; subsequent exact chunks
            # move by -C in the next reader's chronological coordinate system.
            delta = -1 if self.chunk_index == 0 else -self.model.config.chunk_size
            positions = torch.full((self.offset,), delta, device=self.device, dtype=torch.long)
            for index, layer in enumerate(self.model.layers):
                self.exact_keys[index] = layer.rope(
                    self.keys[index][: self.offset], positions
                ).contiguous()
                self.exact_values[index] = self.values[index][: self.offset].clone()
            self.chunk_index += 1
            self.offset = 0
        return self.next_token_logits

    def append(self, token_id: int):
        """Encode one lexical token; stop rather than append a selected EOD."""
        if type(token_id) is not int or not 0 <= token_id < EOD_ID:
            raise ValueError("Append requires a text token; stop generation on EOD")
        if self.token_count >= self.capacity:
            raise ValueError("PAT cache capacity exhausted")
        return self._append(token_id)