File size: 12,800 Bytes
127ebd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""Scoring engine: requests in, option scores and probabilities out.

A request is ``{"id", "state", "questions"}``. Two scoring paths read the same prompts and agree up to kernel rounding:

- fork (default): a request is one tree. The state prefix runs once, every question continues it, every option
  continues its question. With a ``PrefixCache`` the state prefix also continues from the longest cached checkpoint of
  a previous request (token-exact, by the hash of the ids).
- no fork (``fork=False``): one prefill per question (state + that question) with a branch per option, so a request
  with K questions reads its state K times.

Admission: a question whose prefill plus its longest option is over ``max_length`` makes the request unsupported; a
question whose tokens (prefill + all options) are over ``token_budget`` is skipped and reported as such.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

import torch

from .config import HeadConfig
from .fork import ForkTree, Past, chain_past, segment_of, tree_forward
from .head import MLPHead, probabilities
from .packed import Packed, packed_forward
from .prefix_cache import PrefixCache
from .prompt import MAX_OPTIONS, PromptBuilder, option_keys


@dataclass
class Question:
    key: str
    options: list[str]          # answer keys, in prompt order
    suffix: list[int]           # tokens after the shared prefix
    branches: list[list[int]]   # one per option

    @property
    def tokens(self) -> int:
        return len(self.suffix) + sum(len(b) for b in self.branches)


@dataclass
class Prepared:
    """One request after tokenization: the shared prefix and the questions that fit the budget."""
    id: str
    prefix: list[int] = field(default_factory=list)
    questions: list[Question] = field(default_factory=list)
    skipped: list[str] = field(default_factory=list)
    error: str | None = None
    kind: str | None = None    # "context": over max_length; "invalid": a question this model cannot take

    @property
    def tokens(self) -> int:
        return len(self.prefix) + sum(q.tokens for q in self.questions)


@dataclass
class Result:
    id: str
    error: str | None = None
    kind: str | None = None
    skipped: list[str] = field(default_factory=list)
    scores: dict[str, dict[str, float]] = field(default_factory=dict)   # question -> option -> raw head score z
    probs: dict[str, dict[str, float]] = field(default_factory=dict)    # question -> option -> probability
    input_tokens: int = 0
    prefills: int = 0

    @property
    def ok(self) -> bool:
        return self.error is None and not self.skipped


def groups_of(prepared: Prepared, budget: int) -> list[tuple[Prepared, list[Question]]]:
    """The request's questions in groups whose tree (prefix + questions + options) fits ``budget``."""
    out, cur, used = [], [], len(prepared.prefix)
    for q in prepared.questions:
        if cur and used + q.tokens > budget:
            out.append((prepared, cur))
            cur, used = [], len(prepared.prefix)
        cur.append(q)
        used += q.tokens
    out.append((prepared, cur))
    return out


class Engine:
    def __init__(self, lm, head: MLPHead, tokenizer, config: HeadConfig, device, *, token_budget: int = 16384,
                 max_length: int | None = None, attention: str = "flash", fork: bool = True,
                 cache: PrefixCache | None = None):
        self.lm, self.head, self.config, self.device = lm, head, config, torch.device(device)
        self.prompts = PromptBuilder(tokenizer)
        self.token_budget = token_budget
        self.max_length = max_length or token_budget
        if self.max_length > self.token_budget:
            raise ValueError("max_length must not exceed token_budget")
        self.attention, self.fork, self.cache = attention, fork, cache

    # ------------------------------------------------------------------------------------------ admission
    def prepare(self, request: dict[str, Any]) -> Prepared:
        """Tokenize a request; one that cannot be taken comes back with ``error`` set instead of raising."""
        rid, questions = str(request["id"]), request["questions"]
        try:
            return self._prepare(rid, request["state"], questions)
        except ValueError as exc:
            names = list(questions) if isinstance(questions, dict) else []
            return Prepared(rid, skipped=names, error=str(exc), kind="invalid")

    def _prepare(self, rid: str, state: Any, questions: dict[str, Any]) -> Prepared:
        if not isinstance(questions, dict) or not questions:
            raise ValueError("questions must be a non-empty object")
        specs = {}
        for key, spec in questions.items():
            if not isinstance(spec, dict):
                raise ValueError(f"question {key!r}: not an object")
            try:
                keys = option_keys(spec)
            except ValueError as exc:
                raise ValueError(f"question {key!r}: {exc}") from exc
            if not 1 <= len(keys) <= MAX_OPTIONS:
                raise ValueError(f"question {key!r}: {len(keys)} options; 1 to {MAX_OPTIONS} are supported")
            specs[key] = (spec, keys)
        prefix = self.prompts.prefix_ids(state)
        built = []
        for key, (spec, keys) in specs.items():
            suffix, branches = self.prompts.question_ids(spec)
            if len(prefix) + len(suffix) + max(len(b) for b in branches) > self.max_length:
                return Prepared(rid, skipped=list(specs), error=f"a prefill is over max_length {self.max_length}",
                                kind="context")
            built.append(Question(key, keys, suffix, branches))
        kept = [q for q in built if len(prefix) + q.tokens <= self.token_budget]
        skipped = [q.key for q in built if len(prefix) + q.tokens > self.token_budget]
        return Prepared(rid, prefix, kept, skipped)

    # ------------------------------------------------------------------------------------------ scoring
    @torch.no_grad()
    def run(self, requests: list[dict[str, Any]]) -> list[Result]:
        """One ``Result`` per request, in order. A request that cannot be scored carries ``error``/``skipped``."""
        prepared = [self.prepare(r) for r in requests]
        results = [Result(p.id, p.error, p.kind, list(p.skipped), input_tokens=p.tokens,
                          prefills=len(p.questions) if not self.fork else int(bool(p.questions))) for p in prepared]
        by_id = {id(p): r for p, r in zip(prepared, results)}
        if self.fork:
            items = [g for p in prepared if p.questions for g in groups_of(p, self.token_budget)]
            size = lambda g: len(g[0].prefix) + sum(q.tokens for q in g[1])  # noqa: E731
        else:   # one unit per question; its prefix is repeated
            items = [(p, [q]) for p in prepared for q in p.questions]
            size = lambda g: len(g[0].prefix) + g[1][0].tokens  # noqa: E731
        items.sort(key=size, reverse=True)
        bins: list[list] = []
        sizes: list[int] = []
        for item in items:   # first fit, largest first
            n = size(item)
            for i, used in enumerate(sizes):
                if used + n <= self.token_budget:
                    bins[i].append(item)
                    sizes[i] += n
                    break
            else:
                bins.append([item])
                sizes.append(n)
        for b in bins:
            z = (self._run_fork_bin if self.fork else self._run_packed_bin)(b)
            at = 0
            for p, qs in b:
                result = by_id[id(p)]
                for q in qs:
                    zq = z[at:at + len(q.branches)]
                    at += len(q.branches)
                    probs = probabilities(zq, self.config.temperature, self.config.readout).tolist()
                    result.scores[q.key] = dict(zip(q.options, zq.tolist()))
                    result.probs[q.key] = dict(zip(q.options, probs))
        for request, r in zip(requests, results):   # restore the request's question order
            order = [k for k in request["questions"] if k in r.scores]
            r.scores = {k: r.scores[k] for k in order}
            r.probs = {k: r.probs[k] for k in order}
        return results

    @torch.no_grad()
    def _run_packed_bin(self, bin_) -> torch.Tensor:
        """No fork: every unit is a prefill (prefix + question) with its options as branches."""
        sequences, owners, readouts = [], [], []
        units = [(p.prefix + q.suffix, q.branches) for p, qs in bin_ for q in qs]
        sequences += [list(prefill) for prefill, _ in units]
        owners += [-1] * len(units)
        for root, (_, branches) in enumerate(units):
            for b in branches:
                owners.append(root)
                sequences.append(list(b))
        batch = Packed.build(sequences, self.device, owners)
        starts = batch.starts
        at = len(units)
        for _, branches in units:
            for b in branches:
                readouts.append(starts[at] + len(b) - 1)
                at += 1
        index = torch.tensor(readouts, dtype=torch.long, device=self.device)
        hidden = packed_forward(self.lm, batch, attention=self.attention, readout=index)
        return self.head(hidden)[:, 0].float().cpu()

    @torch.no_grad()
    def _run_fork_bin(self, bin_) -> torch.Tensor:
        """Raw head scores [options of every question, in bin order] (fp32, on the CPU)."""
        nodes: list[tuple[int, list[int]]] = []
        pasts: dict[int, Past] = {}
        capture_roots: list[tuple[int, list[int], Any]] = []   # (root node, prefix ids, the checkpoint it continues)
        leaves: list[tuple[int, int]] = []                      # (node, last position) per option, in bin order
        for p, qs in bin_:
            hit_len, past, parent_key = (0, None, None)
            if self.cache is not None:
                hit_len, past, parent_key = self._extend_cache(p.prefix)
            if past is not None and hit_len == len(p.prefix):   # fully cached: each question is a root on the past
                for q in qs:
                    q_node = len(nodes)
                    nodes.append((-1, q.suffix))
                    pasts[q_node] = past
                    for b in q.branches:
                        leaves.append((len(nodes), len(b) - 1))
                        nodes.append((q_node, b))
                continue
            root = len(nodes)
            nodes.append((-1, p.prefix[hit_len:]))
            if past is not None:
                pasts[root] = past
            if self.cache is not None:
                capture_roots.append((root, p.prefix, parent_key))
            for q in qs:
                q_node = len(nodes)
                nodes.append((root, q.suffix))
                for b in q.branches:
                    leaves.append((len(nodes), len(b) - 1))
                    nodes.append((q_node, b))
        tree = ForkTree.build(nodes, self.device, pasts=pasts)
        readout = torch.tensor([tree.node_start[n] + last for n, last in leaves], dtype=torch.long,
                               device=self.device)
        out = tree_forward(self.lm, tree, attention=self.attention, capture=bool(capture_roots), readout=readout)
        hidden, captured = out if capture_roots else (out, None)
        for root, prefix, parent_key in capture_roots:
            self.cache.put(prefix, len(prefix), segment_of(tree, captured, root), parent_key)
        return self.head(hidden)[:, 0].float().cpu()

    @torch.no_grad()
    def _extend_cache(self, prefix: list[int]) -> tuple[int, Past | None, Any]:
        """Longest cached checkpoint of ``prefix``, after first computing and storing checkpoints every
        ``cache.every`` tokens of what is not cached yet; -> (length, past, key)."""
        cache = self.cache
        length, past, key = cache.lookup(prefix)
        if length == len(prefix):
            return length, past, key
        target = (len(prefix) - 1) // cache.every * cache.every   # last multiple of ``every`` strictly inside
        while length < target:
            end = min(target, (length // cache.every + 1) * cache.every)
            tree = ForkTree.build([(-1, prefix[length:end])], self.device, pasts={0: past} if past is not None else None)
            _, captured = tree_forward(self.lm, tree, attention=self.attention, capture=True,
                                       readout=torch.zeros(1, dtype=torch.long, device=self.device))
            seg = segment_of(tree, captured, 0)
            key = cache.put(prefix, end, seg, key)
            past = chain_past([past, seg]) if past is not None else seg
            length = end
        return length, past, key