okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
29.6 KiB541 linesraw
1"""OpenAI logprobs on /v1/chat/completions, from the engine's LP lines: python -m unittest serve.test_logprobs.
2
3The engine (src/program/generate.cpp) writes an `LP <logprob> [id:logprob ...]` line right after
4each `T <id>` when the request carries `logprobs=K`; this is the server half that turns those
5lines into OpenAI's logprobs, and the parts that are easy to get wrong:
6
7  - `allowed_token_ids`: only the named ids, renormalised over them (vLLM's semantics).
8  - `response_format: json_schema` rewrites the content, so the tokens no longer spell what is
9    returned; the entries are re-aligned or dropped, never returned wrong.
10"""
11from __future__ import annotations
12
13import json
14import math
15import queue
16import threading
17import unittest
18import urllib.request
19from pathlib import Path
20from types import SimpleNamespace
21
22from serve.frontend import ChatTemplate
23from serve.server import (ByteTokenizer, LogprobEntries, LPLines, MockEngine, Service, StrataEngine, batch_slots_on,
24                          logprob_span, serve, top_logprobs, allowed_ids)
25
26ROOT = Path(__file__).resolve().parent.parent
27TEMPLATE = ChatTemplate(ROOT / "serve" / "chat_template.jinja")
28
29
30class Tokenizer(ByteTokenizer):
31    def token_bytes(self, token):
32        return self.SPECIALS[token - 256].encode() if token >= 256 else bytes([token])
33
34
35class ThinkTokenizer(Tokenizer):
36    # two extra special tokens that decode as the thinking marks; ALWAYS so the byte-level
37    # encode() maps them wherever they appear ("" would loop forever in startswith, so they
38    # are real strings, like the engine's own think tokens are)
39    SPECIALS = ByteTokenizer.SPECIALS + ["<think>", "</think>"]
40    ALWAYS = ("<think>", "</think>")
41
42
43class LpEngine(MockEngine):
44    """MockEngine with the LP line of each token on lp_lines before the token is yielded, as the
45    engine leaves it; token i has the log-probability -(i + 1) / 100 and four named alternatives."""
46
47    def __init__(self, tok, script, lines=True):
48        super().__init__(tok, script, max_context=16384)
49        self.with_lines, self.sampling = lines, None
50
51    def line(self, i, t):
52        """The LP line of token t, the i-th of the reply: the same four ids whatever was asked."""
53        return (f"LP {-(i + 1) / 100:.6f} 65:-0.500000 72:-1.250000 "
54                f"88:-3.000000 91:-4.200000\n")
55
56    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
57        self.sampling, self.lp_lines = dict(sampling or {}), LPLines(cancel)
58        for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)):
59            if self.with_lines:
60                self.lp_lines.append((t, self.line(i, t)))
61            yield t
62
63
64class NamedEngine(LpEngine):
65    """LpEngine that prints the request's own `allowed_token_ids`, as the engine's emit_lp_line does:
66    `LP <logprob> <named id>:<logprob> ...`, the chosen id left out (it is on the head)."""
67
68    def line(self, i, t):
69        named = [int(x) for x in (self.sampling or {}).get("allowed_token_ids") or [] if int(x) != t]
70        alts = "".join(f" {x}:{-0.700000 - 0.010000 * j:.6f}" for j, x in enumerate(named))
71        return f"LP {-(i + 1) / 100:.6f}{alts}\n"
72
73
74class NextEngine(LpEngine):
75    """LpEngine for two requests: the second one stops after its first token (its LP line is in lp_lines)
76    until the first request's reply has been read."""
77
78    def __init__(self, tok, scripts, first_out):
79        super().__init__(tok, scripts)
80        self.first_out, self.calls = first_out, 0
81        self.first_in, self.first_generated, self.second_started = (threading.Event(), threading.Event(),
82                                                                    threading.Event())
83
84    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
85        self.calls += 1
86        mine = self.calls
87        if mine == 1:
88            self.first_in.set()
89        try:
90            for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)):
91                if mine == 2 and i == 0:
92                    self.second_started.set()
93                    self.first_out.wait(10)
94                yield t
95        finally:
96            if mine == 1:
97                self.first_generated.set()
98
99
100class HandOver:
101    """Service.fifo that, once the first request has generated, lets its turn go and then waits until the
102    next request is generating before the first one goes on."""
103
104    def __init__(self, engine):
105        self.lock, self.engine, self.waited = threading.Lock(), engine, False
106
107    def acquire(self, *a, **k):
108        return self.lock.acquire(*a, **k)
109
110    def release(self):
111        self.lock.release()
112        if self.engine.first_generated.is_set() and not self.waited:
113            self.waited = True
114            self.engine.second_started.wait(10)
115
116    def locked(self):
117        return self.lock.locked()
118
119    def __enter__(self):
120        self.acquire()
121        return self
122
123    def __exit__(self, *exc):
124        self.release()
125
126
127SCHEMA = {"type": "json_schema", "json_schema": {"name": "a", "strict": True, "schema": {
128    "type": "object", "properties": {"rent": {"type": "string"}, "quote": {"type": "string"}},
129    "required": ["rent", "quote"], "additionalProperties": False}}}
130
131
132class Keys(unittest.TestCase):
133    """What the request asks for, and what reaches the engine line."""
134
135    def test_what_the_request_asks(self):
136        self.assertEqual(top_logprobs({"logprobs": True}), 0)
137        self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 3}), 3)
138        self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 50}), 20)
139        self.assertEqual(top_logprobs({"logprobs": 2}), 2)          # the legacy completions form
140        for req in ({}, {"logprobs": False}, {"logprobs": None}, {"top_logprobs": 3}):
141            self.assertIsNone(top_logprobs(req))
142
143    def test_allowed_ids(self):
144        self.assertEqual(allowed_ids({"allowed_token_ids": [1, 2, 3]}), [1, 2, 3])
145        for req in ({}, {"allowed_token_ids": "1,2"}, {"allowed_token_ids": [True]}, {"allowed_token_ids": [-1]}):
146            self.assertEqual(allowed_ids(req), [])
147
148    def test_the_engine_key_only_when_asked(self):
149        self.assertIn(" logprobs=0", StrataEngine.sampling_keys({"logprobs": True}))
150        self.assertIn(" logprobs=5", StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 5}))
151        self.assertNotIn("logprobs", StrataEngine.sampling_keys({}))
152        self.assertNotIn("logprobs", StrataEngine.sampling_keys({"logprobs": False, "temperature": 0}))
153
154    def test_allowed_reaches_the_engine_line(self):
155        keys = StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 2,
156                                           "allowed_token_ids": [7, 8, 9]})
157        self.assertIn(" logprobs=2 ", keys)
158        self.assertIn(" allowed=7,8,9", keys)
159
160    def test_unreadable_lines_give_no_entry(self):
161        a = threading.Event()
162        eng = SimpleNamespace(lp_lines=LPLines(a))
163        for line in ("LP nan", "LP -nan(ind)", "LP inf", "LP -0.1 65:x", "LP -0.1 65:-inf", "LP -0.1 65",
164                     "LP -0.200000 65:-1.0"):
165            eng.lp_lines.append((72, line))
166        got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), owner=a).take(eng)
167        self.assertEqual([e["logprob"] for e in got], [-0.2])
168
169    def test_a_filtered_line_with_nothing_left_keeps_its_token(self):
170        # none of the named ids on the line: the entry keeps the chosen token and its own logprob, and no
171        # alternatives.  It used to be None, appended all the same, and the reply failed on e["token"].
172        a = threading.Event()
173        eng = SimpleNamespace(lp_lines=LPLines(a))
174        eng.lp_lines.append((72, "LP -0.300000 65:-0.500000"))
175        got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [70], a).take(eng)
176        self.assertEqual([(e["token"], e["logprob"], e["top_logprobs"]) for e in got], [("H", -0.3, [])])
177
178    def test_a_named_token_the_line_does_not_repeat_is_its_own_distribution(self):
179        # the engine prints the chosen token's logprob on the head and the named ids after it, never repeating
180        # the chosen one: naming only that id leaves it alone in the distribution, at 1 (logprob 0)
181        a = threading.Event()
182        eng = SimpleNamespace(lp_lines=LPLines(a))
183        eng.lp_lines.append((72, "LP -0.300000 65:-0.500000"))
184        got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [72], a).take(eng)
185        self.assertEqual(got[0]["top_logprobs"], [{"token": "H", "logprob": 0.0, "bytes": [72]}])
186        self.assertEqual(got[0]["logprob"], 0.0)
187
188
189class Generate(unittest.TestCase):
190    """The token's LP line is read next to it, and only when it was asked for."""
191
192    def engine(self, *lines):
193        e = StrataEngine.__new__(StrataEngine)
194        e.proc = __import__("types").SimpleNamespace(
195            stdin=__import__("io").StringIO(), poll=lambda: None)
196        e.lines, e.can_stop, e.max_context, e.silence_s = queue.Queue(), False, 262144, 0
197        for line in lines:
198            e.lines.put(line)
199        return e
200
201    def test_a_token_is_yielded_with_its_lp_line_read(self):
202        e = self.engine("PP 3 3", "T 72", "LP -0.100000 72:-0.1 65:-2.5", "T 105",
203                        "LP -0.200000 105:-0.2 65:-3", "T 257", "LP -0.010000",
204                        "DONE 3 3 0 3 stop 0 0 0")
205        seen = []
206        for t in e.generate([1, 2, 3], 8, {"logprobs": True, "top_logprobs": 2}, threading.Event()):
207            if t is not None:
208                seen.append((t, [x[0] for x in e.lp_lines]))
209        self.assertEqual(seen, [(72, [72]), (105, [72, 105]), (257, [72, 105, 257])])
210        self.assertIn(" logprobs=2 ", e.proc.stdin.getvalue())
211        self.assertEqual(e.lp_lines[1][1], "LP -0.200000 105:-0.2 65:-3")
212
213    def test_an_engine_without_lp_lines(self):
214        e = self.engine("T 72", "T 105", "DONE 3 3 0 2 stop 0 0 0")
215        toks = [t for t in e.generate([1], 8, {"logprobs": True}, threading.Event()) if t is not None]
216        self.assertEqual(toks, [72, 105])
217        self.assertEqual(list(e.lp_lines), [])
218        self.assertEqual(e.last["finish"], "stop")
219
220    def test_not_asked_reads_as_before(self):
221        e = self.engine("T 72", "LP -0.1", "T 105", "DONE 3 3 0 2 stop 0 0 0")
222        toks = [t for t in e.generate([1], 8, {}, threading.Event()) if t is not None]
223        self.assertEqual(toks, [72, 105])
224        self.assertEqual(list(e.lp_lines), [])
225
226    def test_a_consumer_that_stops_early_does_not_lose_the_done_read_after_the_token(self):
227        # the DONE line was read while looking for the token's LP line: the drain must take it,
228        # not wait for another
229        e = self.engine("T 72", "DONE 3 3 0 1 length 0 0 0", None)
230        gen = e.generate([1], 1, {"logprobs": True}, threading.Event())
231        self.assertEqual(next(gen), 72)
232        gen.close()
233        self.assertEqual(e.last["finish"], "length")
234
235
236class Api(unittest.TestCase):
237    def setUp(self):
238        self.tok = Tokenizer()
239        self.engine = LpEngine(self.tok, "Café costs €5.")
240        self.svc = Service(self.engine, self.tok, TEMPLATE)
241        self.httpd = serve(self.svc, port=0)
242        self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
243
244    def tearDown(self):
245        self.httpd.shutdown()
246        self.httpd.server_close()
247
248    def post(self, body, stream=False):
249        body = {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 200,
250                "chat_template_kwargs": {"enable_thinking": False}, **body}
251        if stream:
252            body["stream"] = True
253        req = urllib.request.Request(self.base + "/v1/chat/completions", json.dumps(body).encode(),
254                                     {"Content-Type": "application/json"})
255        with urllib.request.urlopen(req, timeout=30) as r:
256            raw = r.read().decode()
257        if not stream:
258            return json.loads(raw)
259        return [json.loads(x[6:]) for x in raw.splitlines() if x.startswith("data: {")]
260
261    def test_the_tokens_spell_the_content(self):
262        out = self.post({"logprobs": True, "top_logprobs": 1})
263        choice = out["choices"][0]
264        content = choice["message"]["content"]
265        lps = choice["logprobs"]["content"]
266        self.assertEqual(content, "Café costs €5.")
267        self.assertEqual("".join(e["token"] for e in lps), content)
268        self.assertEqual(len(lps), len(content.encode()))       # one per byte token; no stop token
269        self.assertEqual(b"".join(bytes(e["bytes"]) for e in lps), content.encode())
270        e_acute = [e for e in lps if len(e["bytes"]) == 1 and e["bytes"][0] >= 0x80]
271        self.assertEqual([e["token"] for e in e_acute[:2]], ["", "é"])   # split across two tokens
272        self.assertEqual(lps[0]["logprob"], -0.01)
273        self.assertEqual(lps[0]["top_logprobs"][0]["token"], "A")
274        self.assertEqual(self.engine.sampling.get("logprobs"), True)
275
276    def test_a_request_reads_only_its_own_lines(self):
277        # A's last "." is held by its stop string and sent after A has left the queue, when B is
278        # already generating on the same engine: each reply's tokens must spell that reply
279        first_out = threading.Event()
280        engine = NextEngine(self.tok, ["Café costs €5.", "Bonjour!"], first_out)
281        svc = Service(engine, self.tok, TEMPLATE)
282        svc.fifo = HandOver(engine)
283        httpd = serve(svc, port=0)
284        got = {}
285        try:
286            self.base = f"http://127.0.0.1:{httpd.server_address[1]}"
287            a = threading.Thread(target=lambda: got.update(a=self.post({"logprobs": True, "stop": [".!"]})))
288            b = threading.Thread(target=lambda: got.update(b=self.post({"logprobs": True})))
289            a.start()
290            self.assertTrue(engine.first_in.wait(10))
291            b.start()
292            a.join(30)
293            first_out.set()
294            b.join(30)
295        finally:
296            first_out.set()
297            httpd.shutdown()
298            httpd.server_close()
299        for key, text in (("a", "Café costs €5."), ("b", "Bonjour!")):
300            choice = got[key]["choices"][0]
301            self.assertEqual(choice["message"]["content"], text)
302            self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), text, key)
303
304    def test_logprobs_take_any_max_tokens(self):
305        # No cap of our own: the reply is already bounded by max_tokens (the rest of the context when it is not
306        # sent), which is the only bound OpenAI and vLLM put on it too -- openai-node's max_tokens is optional
307        # and vLLM's defaults to 16 or None, neither tying it to logprobs.
308        for max_tokens in (200, 5000, 0, -1, None):        # 0 / -1: "the rest of the context"; None: not sent
309            choice = self.post({"logprobs": True, "top_logprobs": 1, "max_tokens": max_tokens})["choices"][0]
310            self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]),
311                             "Café costs €5.", max_tokens)
312        self.assertNotIn("logprobs", self.post({"max_tokens": 0})["choices"][0])   # not asked: as before
313
314    def test_a_streamed_reply_needs_no_bound(self):
315        # A streamed reply hands each entry out with its chunk and keeps none, so it is bounded by the reply's own
316        # length.  OpenAI itself bounds a reply only by the model's context, and its SDKs send no max_tokens by
317        # default.  5000 and "the rest of the context" must both be answered, as they are without logprobs.
318        for max_tokens in (5000, 0, None):                 # None: the field is not sent at all
319            chunks = self.post({"logprobs": True, "max_tokens": max_tokens}, stream=True)
320            text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices"))
321            toks = [e["token"] for c in chunks if c.get("choices")
322                    for e in (c["choices"][0].get("logprobs") or {}).get("content", [])]
323            self.assertEqual(text, "Café costs €5.", max_tokens)
324            self.assertEqual("".join(toks), text, max_tokens)   # an entry for every token, streamed or not
325
326    def test_a_json_schema_reply_takes_any_max_tokens(self):
327        # structured_chunks buffers the reply to validate it, logprobs included: it holds the entries until the
328        # end, as a reply that is not streamed does.  That memory is bounded by max_tokens, not by a cap of ours.
329        written = '```json\n{"rent": "$1,250", "quote": "x"}\n```'
330        self.engine = self.svc.engine = LpEngine(self.tok, written)
331        content = '{"rent": "$1,250", "quote": "x"}'
332        for max_tokens in (200, 0, 5000):
333            choice = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA})["choices"][0]
334            self.assertEqual(choice["message"]["content"], content, max_tokens)
335            self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content, max_tokens)
336            chunks = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA}, stream=True)
337            toks = [e["token"] for c in chunks if c.get("choices")
338                    for e in (c["choices"][0].get("logprobs") or {}).get("content", [])]
339            self.assertEqual("".join(toks), content, (max_tokens, "streamed"))
340
341    def test_logprobs_are_refused_on_the_batch_path(self):
342        # --parallel/--batch: the engine's batched loop prints "BT <slot> <id>" and never calls emit_lp_line
343        # (src/program/generate.cpp), so no LP line reaches the server and the field would simply be absent.
344        # Refused up front instead, before anything is generated; a request that does not ask is untouched.
345        self.engine.batch = 2
346        with self.assertRaises(urllib.error.HTTPError) as cm:
347            self.post({"logprobs": True})
348        self.assertEqual(cm.exception.code, 400)
349        self.assertIn("--parallel", cm.exception.read().decode())
350        self.engine.batch = 0
351        self.assertIn("logprobs", self.post({"logprobs": True})["choices"][0])
352
353    def test_allowed_token_ids_outside_the_vocabulary_is_a_400(self):
354        # emit_lp_line indexes its logits row with each named id, so an id past the vocabulary would read out of
355        # bounds; the request is refused before anything is generated
356        self.tok.tokens = [str(i) for i in range(300)]      # a tokenizer that knows its vocabulary
357        with self.assertRaises(urllib.error.HTTPError) as cm:
358            self.post({"logprobs": True, "top_logprobs": 1, "allowed_token_ids": [300]})
359        self.assertEqual(cm.exception.code, 400)
360        self.assertIn("allowed_token_ids", cm.exception.read().decode())
361        self.assertIn("logprobs", self.post({"logprobs": True, "top_logprobs": 1,
362                                            "allowed_token_ids": [299]})["choices"][0])
363
364    def test_streamed(self):
365        chunks = self.post({"logprobs": True}, stream=True)
366        content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices"))
367        toks = [e["token"] for c in chunks if c.get("choices")
368                for e in (c["choices"][0].get("logprobs") or {}).get("content", [])]
369        self.assertEqual(content, "Café costs €5.")
370        self.assertEqual("".join(toks), content)
371
372    def test_with_thinking_each_part_is_spelled_by_its_tokens(self):
373        tok = ThinkTokenizer()
374        svc = Service(LpEngine(tok, "Two times three.</think>\n\nSix."), tok,
375                      TEMPLATE)
376        httpd = serve(svc, port=0)
377        try:
378            self.base = f"http://127.0.0.1:{httpd.server_address[1]}"
379            for stream in (False, True):
380                out = self.post({"logprobs": True, "chat_template_kwargs": {"enable_thinking": True}},
381                                 stream)
382                chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"],
383                                                           "logprobs": out["choices"][0]["logprobs"]}]}]
384                for key in ("content", "reasoning_content"):
385                    text = "".join(c["choices"][0]["delta"].get(key) or "" for c in chunks if c.get("choices"))
386                    toks = "".join(e["token"] for c in chunks if c.get("choices")
387                                   for e in (c["choices"][0].get("logprobs") or {}).get(key, []))
388                    self.assertTrue(text)
389                    self.assertEqual(toks, text, (key, stream))
390                    self.assertNotIn("think>", toks)
391        finally:
392            httpd.shutdown()
393            httpd.server_close()
394
395    def test_not_asked_no_logprobs(self):
396        out = self.post({})
397        self.assertNotIn("logprobs", out["choices"][0])
398
399    def test_an_engine_without_lp_lines_gives_none(self):
400        self.engine.with_lines = False
401        out = self.post({"logprobs": True})
402        self.assertEqual(out["choices"][0]["message"]["content"], "Café costs €5.")
403        self.assertNotIn("logprobs", out["choices"][0])
404
405    def test_allowed_token_ids_are_renormalised_over_the_named_ids(self):
406        out = self.post({"logprobs": True, "allowed_token_ids": [65, 72]})
407        lps = out["choices"][0]["logprobs"]["content"]
408        self.assertTrue(lps)
409        for e in lps:
410            ids = [t["token"] for t in e["top_logprobs"]]
411            self.assertEqual(ids, ["A", "H"])                    # only the named ones
412        import math
413        total = sum(math.exp(t["logprob"]) for t in lps[0]["top_logprobs"])
414        self.assertAlmostEqual(total, 1.0, places=6)             # renormalised: they sum to 1
415
416    def test_allowed_token_ids_with_nothing_to_renormalise(self):
417        # the mock's alternatives are 65/72/88/91: naming another id leaves every line with no survivor.  Each
418        # token keeps its own logprob and an empty candidate list, and the reply still comes back whole (this
419        # used to be a 400 on the unstreamed path and a reply cut after the role chunk when streamed).
420        for body in ({"logprobs": True, "allowed_token_ids": [66]},
421                     {"logprobs": True, "allowed_token_ids": [66, 70, 71]}):
422            choice = self.post(body)["choices"][0]
423            lps = choice["logprobs"]["content"]
424            self.assertEqual(choice["message"]["content"], "Café costs €5.")
425            self.assertEqual("".join(e["token"] for e in lps), "Café costs €5.")
426            self.assertEqual([e["top_logprobs"] for e in lps], [[]] * len(lps))
427            self.assertEqual(lps[0]["logprob"], -0.01)           # the token's own, as the engine reported it
428            streamed = self.post(body, stream=True)
429            toks = [e["token"] for c in streamed if c.get("choices")
430                    for e in (c["choices"][0].get("logprobs") or {}).get("content", [])]
431            self.assertEqual("".join(toks), "Café costs €5.")
432
433    def test_a_named_token_the_model_chose_is_in_its_distribution(self):
434        # 46 is the reply's final ".": the engine does not repeat the chosen token among the named ids, so
435        # naming only it used to leave nothing to normalise over.  It is the whole distribution now, at 0.
436        lps = self.post({"logprobs": True, "allowed_token_ids": [46]})["choices"][0]["logprobs"]["content"]
437        dot = [e for e in lps if e["token"] == "."]
438        self.assertEqual(len(dot), 1)
439        self.assertEqual(dot[0]["top_logprobs"], [{"token": ".", "logprob": 0.0, "bytes": [46]}])
440        self.assertEqual(dot[0]["logprob"], 0.0)
441        self.assertEqual([e["top_logprobs"] for e in lps if e["token"] != "."], [[]] * (len(lps) - 1))
442
443    def test_a_choice_of_ten_that_only_the_ended_reply_settles(self):
444        # ten named ids, and a reply that is two of them: "1" alone is already one of the choices, so which
445        # one was picked is only known when the reply ends.  Here "11": each token's entries cover the ten
446        # named ids (the chosen one included, because the engine never repeats it), and they sum to 1.
447        self.engine = self.svc.engine = NamedEngine(self.tok, "11")
448        digits = [ord(c) for c in "0123456789"]
449        for stream in (False, True):
450            out = self.post({"logprobs": True, "top_logprobs": 10, "allowed_token_ids": digits}, stream)
451            chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"],
452                                                       "logprobs": out["choices"][0]["logprobs"]}]}]
453            content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices"))
454            lps = [e for c in chunks if c.get("choices")
455                   for e in (c["choices"][0].get("logprobs") or {}).get("content", [])]
456            self.assertEqual(content, "11")
457            self.assertEqual([e["token"] for e in lps], ["1", "1"])     # the first token alone is a choice too
458            self.assertEqual("".join(e["token"] for e in lps), content)
459            for e in lps:
460                ids = [t["token"] for t in e["top_logprobs"]]
461                self.assertEqual(sorted(ids), sorted("0123456789"))    # the ten named ids, and only them
462                self.assertIn(e["token"], ids)                         # the chosen one is one of them
463                self.assertEqual(ids[0], e["token"])                   # ... and the most likely, here
464                self.assertEqual([t["logprob"] for t in e["top_logprobs"]],
465                                 sorted((t["logprob"] for t in e["top_logprobs"]), reverse=True))
466                self.assertAlmostEqual(sum(math.exp(t["logprob"]) for t in e["top_logprobs"]), 1.0, places=6)
467
468    def test_a_held_tail_of_more_than_one_token(self):
469        # "5." is the start of the stop string, so the parser holds two tokens and sends them as one piece
470        # after the request has left the queue: both entries come from this request's own lines all the same
471        chunks = self.post({"logprobs": True, "stop": ["5.!"]}, stream=True)
472        content = [c for c in chunks if c.get("choices") and c["choices"][0]["delta"].get("content")]
473        self.assertEqual(content[-1]["choices"][0]["delta"]["content"], "5.")      # held, then flushed whole
474        self.assertEqual([e["token"] for e in content[-1]["choices"][0]["logprobs"]["content"]], ["5", "."])
475        text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices"))
476        self.assertEqual(text, "Café costs €5.")
477        self.assertEqual("".join(e["token"] for c in chunks if c.get("choices")
478                                 for e in (c["choices"][0].get("logprobs") or {}).get("content", [])), text)
479        choice = self.post({"logprobs": True, "stop": ["5.!"]})["choices"][0]         # and not streamed
480        self.assertEqual(choice["message"]["content"], "Café costs €5.")
481        self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), "Café costs €5.")
482        self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"][-2:]), "5.")
483
484    def test_json_schema_answer_as_written_with_its_logprobs(self):
485        # MockEngine appends the stop token to the script it is built with, and reports
486        # finish_reason=length when it runs out -- so the engine is rebuilt with this answer
487        # rather than re-pointed at a raw token list (which would drop the stop token).
488        written = '```json\n{"rent": "$1,250", "quote": "x"}\n```'
489        self.engine = self.svc.engine = LpEngine(self.tok, written)
490        out = self.post({"logprobs": True, "temperature": 0, "response_format": SCHEMA})
491        choice = out["choices"][0]
492        content = choice["message"]["content"]
493        self.assertEqual(content, '{"rent": "$1,250", "quote": "x"}')   # the JSON as written
494        self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content)
495        streamed = self.post({"logprobs": True, "response_format": SCHEMA}, stream=True)
496        toks = [e["token"] for c in streamed if c.get("choices")
497                for e in (c["choices"][0].get("logprobs") or {}).get("content", [])]
498        self.assertEqual("".join(toks), content)
499        plain = self.post({"temperature": 0, "response_format": SCHEMA})    # not asked: as before
500        self.assertEqual(plain["choices"][0]["message"]["content"],
501                         '{"rent":"$1,250","quote":"x"}')
502        self.assertNotIn("logprobs", plain["choices"][0])
503
504
505class Replicas(unittest.TestCase):
506    """`--replicas`: a ReplicaEngine's own `batch` is how many requests its engines run at once and counts a replica
507    without slots as one, so asking it "does this engine use batch slots" refused logprobs on a server that has
508    none -- one that reads every reply by the GEN path, which does write LP lines."""
509
510    @staticmethod
511    def replica(*batches):
512        from serve.replicas import ReplicaEngine
513        return ReplicaEngine([SimpleNamespace(gen=1, batch=b) for b in batches])
514
515    def test_no_slots_behind_replicas(self):
516        self.assertFalse(batch_slots_on(self.replica(0, 0)))
517        self.assertFalse(batch_slots_on(SimpleNamespace(batch=0)))      # no replicas: the engine's own figure
518
519    def test_slots_behind_replicas(self):
520        self.assertTrue(batch_slots_on(self.replica(2, 3)))             # every one of them
521        self.assertTrue(batch_slots_on(self.replica(0, 2)))             # one is enough
522        self.assertTrue(batch_slots_on(SimpleNamespace(batch=4)))
523
524
525class Span(unittest.TestCase):
526    def entries(self, *toks):
527        return [{"token": t} for t in toks]
528
529    def test_span(self):
530        es = self.entries("```", "json", "\n", "{", "}", "\n", "```")
531        self.assertEqual([e["token"] for e in logprob_span("```json\n{}\n```", "{}", es)], ["{", "}"])
532        self.assertEqual(len(logprob_span("{}", "{}", self.entries("{", "}"))), 2)
533
534    def test_no_span(self):
535        self.assertIsNone(logprob_span("x{}", "{}", self.entries("x{", "}")))   # no boundary at the start
536        self.assertIsNone(logprob_span("{}x", "{}", self.entries("{", "}x")))   # none at the end
537        self.assertIsNone(logprob_span("{}", "{}", self.entries("{")))           # do not spell it
538
539
540if __name__ == "__main__":
541    unittest.main()