File size: 14,576 Bytes
f35e9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Request validation and rendering: a /v1/systemone request -> the token layout the model reads.

Pure Python + the `tokenizers` library (no torch, no transformers), so every backend (torch, MLX) shares it.
It reproduces kev's serving path token for token for a Verdin checkpoint's render settings:

    request JSON --validate--> (state, typed questions) --date facts--> rendered text --tokenize--> Encoded
                 (kev.api.SystemOneRequest)   (kev.api.with_date_facts)  (kev.api.to_record)   (kev.model.encode)

The text rules (render, option_text, date_facts, question keys) and the layout (delimiters, schema-first block, caps)
are ported from kev (jaredpalmer/kev, Apache-2.0: kev/api.py, kev/model.py) including our patches
(KEV_SCHEMA_FIRST, KEV_MAX_STATE/BRANCH/PACKED). Parity with kev was tested record by record during development.

Layout (one record):  [<state> schema... state...] then per question k: [<q> instr... (<opt> option... </opt>)... <decide>]
The state prefix is shared by every question; each question's branch continues the state's positions and never sees
another question, so the backend runs the state once and every branch as its own causal row from that prefix.
Readouts: the <decide> token of each branch and the </opt> token of each option.

Caps are hard: a request over a cap raises Unsupported ("too many tokens: ..."), never a silent truncation.
"""
from __future__ import annotations

import json
import re
from dataclasses import dataclass, field
from datetime import datetime

MAX_OPTIONS = 255
QUESTION_TYPES = ("noul", "choice", "score")


class RequestError(ValueError):
    """The request is malformed or violates the wire format (HTTP 422)."""


class Unsupported(RequestError):
    """A valid request this model cannot take (over a token cap): HTTP 422 with the 'too many tokens' capacity marker
    the Decision Index http engine and JevBench recognise as an explicit refusal."""

    def __init__(self, message):
        super().__init__(message if message.startswith("too many tokens") else "too many tokens: " + message)


# ---------------------------------------------------------------------------------------------------------------------
# Text rules (kev/api.py, verbatim semantics)

def render(v, indent: int = 0) -> str:
    """Flatten str | object | array into the text the model sees. Field names are kept as labels."""
    pad = "  " * indent
    if v is None: return ""
    if isinstance(v, (str, int, float, bool)): return str(v)
    if isinstance(v, list): return "\n".join(f"{pad}- {render(x, indent + 1).lstrip()}" for x in v)
    return "\n".join(f"{pad}{k}:\n{render(x, indent + 1)}" if isinstance(x, (dict, list)) else f"{pad}{k}: {render(x)}" for k, x in v.items())


def option_text(name: str, desc) -> str:
    return name if desc is None or desc == "" else f"{name}: {render(desc)}"


MONTHS = "January|February|March|April|May|June|July|August|September|October|November|December"
_DATE = re.compile(rf"\b(?:{MONTHS}) \d{{1,2}}, \d{{4}}\b|\b\d{{4}}-\d{{2}}-\d{{2}}\b")


def date_facts(text: str) -> str:
    """Every pair of absolute dates found in `text`, one sentence each ("August 3, 2026 is 12 days after July 22,
    2026."), in order of first appearance; "" with fewer than two dates."""
    found = []
    for m in _DATE.finditer(text):
        raw = m.group(0)
        try: d = datetime.strptime(raw, "%B %d, %Y") if "," in raw else datetime.strptime(raw, "%Y-%m-%d")
        except ValueError: continue
        if raw not in [r for r, _ in found]: found.append((raw, d))
    facts = []
    for i in range(len(found)):
        for j in range(i + 1, len(found)):
            n = (found[j][1] - found[i][1]).days
            facts.append(f"{found[j][0]} is {abs(n)} day{'s' if abs(n) != 1 else ''} {'after' if n > 0 else 'before'} {found[i][0]}." if n else f"{found[j][0]} is the same day as {found[i][0]}.")
    return " ".join(facts)


def with_date_facts(state):
    """The state with a `date_facts` field (object), an appended item (array) or paragraph (string) when two or more
    absolute dates appear in its rendered text; unchanged otherwise."""
    facts = date_facts(render(state))
    if not facts: return state
    if isinstance(state, dict): return {**state, "date_facts": facts}
    if isinstance(state, list): return state + [{"date_facts": facts}]
    return f"{state}\n\ndate_facts: {facts}"


def question_keys(qtype: str, criteria) -> list[str]:
    """The keys a question's probabilities are reported under, in option order: the criteria names (choice),
    ["false", "true"] (noul), the level indices as strings (score)."""
    if qtype == "choice": return list(criteria)
    if qtype == "noul": return ["false", "true"]
    return [str(i) for i in range(len(criteria))]


# ---------------------------------------------------------------------------------------------------------------------
# Validation (the constraints of kev.api.SystemOneRequest's pydantic model, without pydantic)

@dataclass
class Question:
    id: str
    type: str
    instructions: object
    criteria: object

    @property
    def keys(self) -> list[str]:
        return question_keys(self.type, self.criteria)


def validate_request(body) -> tuple[object, list[Question]]:
    """-> (state, questions in request order). Accepts exactly what kev's SystemOneRequest accepts: any JSON value as
    state / instructions / criteria values; choice = object of 1..255 options, score = array of 2..255 levels, noul =
    optional object (keys "false"/"true" describe the options). Unknown fields are ignored (as pydantic does)."""
    if not isinstance(body, dict):
        raise RequestError("invalid request: the body must be a JSON object")
    if "state" not in body:
        raise RequestError("invalid request: state is required")
    qs = body.get("questions")
    if not isinstance(qs, dict) or not qs:
        raise RequestError("invalid request: questions must be a non-empty object")
    out = []
    for qid, q in qs.items():
        where = f"questions.{qid}"
        if not isinstance(q, dict):
            raise RequestError(f"invalid request: {where} must be an object")
        t = q.get("type")
        if t not in QUESTION_TYPES:
            raise RequestError(f"invalid request: {where}.type must be one of noul, choice, score (got {t!r})")
        if "instructions" not in q:
            raise RequestError(f"invalid request: {where}.instructions is required")
        c = q.get("criteria")
        if t == "choice":
            if not isinstance(c, dict):
                raise RequestError(f"invalid request: {where}.criteria must be an object of options")
            if not c:
                raise RequestError(f"invalid request: {where}.criteria must have 1..{MAX_OPTIONS} options (got 0)")
            if len(c) > MAX_OPTIONS:
                raise RequestError(f"invalid request: {where}: too many options per choice ({len(c)}; at most {MAX_OPTIONS})")
        elif t == "score":
            if not isinstance(c, list):
                raise RequestError(f"invalid request: {where}.criteria must be an array of levels")
            if not 2 <= len(c) <= MAX_OPTIONS:
                raise RequestError(f"invalid request: {where}: a score takes 2 to {MAX_OPTIONS} levels (got {len(c)})")
        elif c is not None and not isinstance(c, dict):
            raise RequestError(f"invalid request: {where}.criteria must be an object or null for noul")
        out.append(Question(str(qid), t, q["instructions"], c))
    return body["state"], out


def to_record(state, questions: list[Question]) -> dict:
    """kev.api.to_record: the internal record {"state": text, "questions": [{"instr", "options"}]}."""
    qs = []
    for q in questions:
        if q.type == "noul":
            c = q.criteria or {}
            opts = [option_text("no", c.get("false")), option_text("yes", c.get("true"))]
        elif q.type == "choice":
            opts = [option_text(k, v) for k, v in q.criteria.items()]
        else:
            opts = [render(x) for x in q.criteria]
        qs.append({"instr": render(q.instructions), "options": opts})
    return {"state": render(state), "questions": qs}


# ---------------------------------------------------------------------------------------------------------------------
# Tokenization and layout (kev/model.py encode, option_isolation off, strict)

_SPECIAL_RE = re.compile(r"<\|([A-Za-z0-9_]+)\|>")
SPECIAL_NAMES = ("state", "question", "option", "option_end", "decide")


class Tokenizer:
    """The checkpoint's tokenizer.json through the `tokenizers` library, plus kev's rule for caller-supplied text:
    `<|name|>` is rewritten to `<¦name¦>` first, so user text can never produce a delimiter/control token."""

    def __init__(self, path, specials: dict[str, str]):
        from tokenizers import Tokenizer as _T
        self.tk = _T.from_file(str(path))
        self.specials = dict(specials)
        self.ids = {}
        for name in SPECIAL_NAMES:
            i = self.tk.token_to_id(specials[name])
            if i is None:
                raise ValueError(f"tokenizer has no token {specials[name]!r} ({name})")
            self.ids[name] = i

    @staticmethod
    def escape(text: str) -> str:
        return _SPECIAL_RE.sub(r"<¦\1¦>", text)

    def user_tokens(self, text: str) -> list[int]:
        return self.tk.encode(self.escape(text), add_special_tokens=False).ids

    def user_tokens_batch(self, texts: list[str]) -> list[list[int]]:
        if not texts: return []
        return [e.ids for e in self.tk.encode_batch([self.escape(t) for t in texts], add_special_tokens=False)]


@dataclass
class Row:
    """One question's branch: its tokens (positions continue the state's), the <decide> offset and the </opt> offsets
    within the branch."""
    ids: list[int]
    decide: int
    opts: list[int]


@dataclass
class Encoded:
    state_ids: list[int]
    rows: list[Row]
    questions: list[Question] = field(default_factory=list)

    @property
    def n_state(self) -> int:
        return len(self.state_ids)

    @property
    def n_tokens(self) -> int:
        """Tokens of the packed record (kev's len(enc["ids"])): state once + every branch."""
        return len(self.state_ids) + sum(len(r.ids) for r in self.rows)

    def packed(self) -> dict:
        """kev.model.encode's packed form (ids, seg, pos, decide_idx, opt_idx) for parity tests."""
        ids, seg, pos = list(self.state_ids), [0] * self.n_state, list(range(self.n_state))
        decide_idx, opt_idx = [], []
        for k, r in enumerate(self.rows, start=1):
            base = len(ids)
            ids += r.ids; seg += [k] * len(r.ids); pos += list(range(self.n_state, self.n_state + len(r.ids)))
            decide_idx.append(base + r.decide); opt_idx.append([base + o for o in r.opts])
        return {"ids": ids, "seg": seg, "pos": pos, "decide_idx": decide_idx, "opt_idx": opt_idx}


@dataclass
class RenderConfig:
    schema_first: bool
    date_facts: bool
    max_state: int
    max_branch: int
    max_packed: int
    schema_max: int = 512
    lead_ids: tuple = ()          # tokens before <state> (Gemma's <bos>; empty for Qwen)

    @classmethod
    def from_dict(cls, d):
        return cls(schema_first=bool(d["schema_first"]), date_facts=bool(d["date_facts"]), max_state=int(d["max_state"]),
                   max_branch=int(d["max_branch"]), max_packed=int(d["max_packed"]), schema_max=int(d.get("schema_max", 512)),
                   lead_ids=tuple(d.get("lead_ids", ())))


class Renderer:
    def __init__(self, tokenizer: Tokenizer, cfg: RenderConfig):
        self.tok, self.cfg = tokenizer, cfg
        self._newline = tokenizer.user_tokens("\n")[-1:]

    def encode_request(self, body) -> Encoded:
        """Wire request (parsed JSON) -> Encoded, applying the checkpoint's date-facts setting. Raises RequestError /
        Unsupported."""
        state, questions = validate_request(body)
        if self.cfg.date_facts:
            state = with_date_facts(state)
        enc = self.encode_record(to_record(state, questions))
        enc.questions = questions
        return enc

    def encode_record(self, rec: dict) -> Encoded:
        """kev.model.encode(tok, rec, strict=True) for a rendered record + the packed-length check of kev's predictors."""
        c, tok, sp = self.cfg, self.tok, self.tok.ids
        questions = rec["questions"]
        # one batched tokenizer call for the state, the schema and every instruction/option string
        texts = [rec["state"]]
        if c.schema_first:
            text = "Questions to answer about the state below:\n" + "\n".join(
                f"{k}. {q['instr']} Options: " + " | ".join(q["options"]) for k, q in enumerate(questions, start=1))
            texts.append(text + "\nState:\n")
        for q in questions:
            texts.append(q["instr"]); texts.extend(q["options"])
        toks = tok.user_tokens_batch(texts)
        state_tokens, i = toks[0], 1
        schema = []
        if c.schema_first:
            schema = toks[1]; i = 2
            if len(schema) > c.schema_max:
                schema = schema[: c.schema_max - 1] + self._newline
        lead = list(c.lead_ids)
        kept = c.max_state - 1 - len(lead) - len(schema)
        if len(state_tokens) > kept:
            raise Unsupported(f"state exceeds {c.max_state} tokens: {len(state_tokens) + 1 + len(lead) + len(schema)}")
        S = lead + [sp["state"]] + schema + state_tokens
        rows, total = [], len(S)
        for q in questions:
            instr = [sp["question"]] + toks[i]; i += 1
            spans = []
            for _ in q["options"]:
                spans.append([sp["option"]] + toks[i] + [sp["option_end"]]); i += 1
            br = instr + [t for s in spans for t in s] + [sp["decide"]]
            if len(br) > c.max_branch - len(S):
                raise Unsupported(f"branch too long: {len(br)}")
            ends, cursor = [], len(instr)
            for s in spans:
                cursor += len(s); ends.append(cursor - 1)
            rows.append(Row(br, len(br) - 1, ends)); total += len(br)
        if total > c.max_packed:
            raise Unsupported(f"packed request exceeds frozen {c.max_packed}-token limit")
        return Encoded(S, rows)


def parse_body(raw: bytes):
    """JSON body -> object (RequestError on malformed JSON). Python's json, as FastAPI/kev use."""
    try:
        return json.loads(raw)
    except (ValueError, UnicodeDecodeError) as e:
        raise RequestError(f"invalid JSON body: {e}") from None