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
5.5 KiB117 linesraw
1"""Logprobs with "parallel" (batch slots): python -m unittest serve.test_logprobs_parallel.
2
3The fake engine of serve/test_parallel.py behind the real StrataEngine and Service, writing an LP line after each
4T line when the GEN / BGEN line asks for logprobs.  A typed decision (max_tokens 1) is read on the control lines
5(an admission: BGEN, one T, DONE, BADM 0) and gets its logprobs; longer replies are refused with a 400, since the
6slot's BT lines carry none.
7"""
8import json
9import threading
10import unittest
11import urllib.error
12import urllib.request
13from unittest import mock
14
15import serve.test_parallel as tp
16
17# LP after each T when asked: the token's log-probability is -(prompt length) / 1000 (so two requests can be told
18# apart) and "A" (65) is its one alternative at -1.5 -- or the named ids themselves, at -1, when the line carries
19# `allowed=` (the engine's own branch: it prints those and no top-K)
20_T_LINE = '            print(f"T {t}", flush=True)\n'
21assert tp.FAKE_BATCH.count(_T_LINE) == 1
22FAKE_LP = tp.FAKE_BATCH.replace(_T_LINE, _T_LINE + (
23    '            if " logprobs=" in line:\n'
24    '                al = [x[8:] for x in line.split() if x.startswith("allowed=")]\n'
25    '                cs = (" " + " ".join(i + ":-1.000000" for i in al[0].split(","))) if al else " 65:-1.500000"\n'
26    '                print(f"LP {-len(ids) / 1000:.6f}" + cs, flush=True)\n'))
27
28
29class LogprobsWithBatchSlots(unittest.TestCase):
30    start, tearDown, get = tp.ParallelService.start, tp.ParallelService.tearDown, tp.ParallelService.get
31
32    def start_lp(self, fake=FAKE_LP, slots=2):
33        with mock.patch.object(tp, "FAKE_BATCH", fake):
34            self.start(slots)
35
36    def chat(self, text, max_tokens=1, logprobs=True, allowed=None):
37        body = {"messages": [{"role": "user", "content": text}], "max_tokens": max_tokens,
38                "reasoning_effort": "none"}
39        if logprobs:
40            body |= {"logprobs": True, "top_logprobs": 1}
41        if allowed:
42            body["allowed_token_ids"] = allowed
43        req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
44                                     headers={"Content-Type": "application/json"})
45        with urllib.request.urlopen(req, timeout=60) as r:
46            return json.loads(r.read().decode())
47
48    @staticmethod
49    def entries(reply):
50        return ((reply["choices"][0].get("logprobs") or {}).get("content")) or []
51
52    def test_a_decision_gets_its_logprobs(self):
53        self.start_lp()
54        r = self.chat("Is it A or B?")
55        self.assertEqual(r["choices"][0]["message"]["content"], "o")
56        e = self.entries(r)
57        self.assertEqual(len(e), 1)
58        self.assertEqual(e[0]["token"], "o")
59        self.assertLess(e[0]["logprob"], 0)
60        self.assertEqual(e[0]["top_logprobs"], [{"token": "A", "logprob": -1.5, "bytes": [65]}])
61        self.assertTrue(any(x.startswith("BGEN") for x in self.log.read_text().splitlines()))   # an admission
62
63    def test_the_named_ids_reach_the_slot_and_are_what_is_reported(self):
64        # allowed_token_ids travels in the same BGEN keys as logprobs, so the engine's own branch answers with
65        # exactly those ids: the admission path carries the whole feature, not just the top-K one
66        self.start_lp()
67        e = self.entries(self.chat("Is it A or B?", allowed=[65]))
68        self.assertEqual(len(e), 1)
69        self.assertEqual([x["token"] for x in e[0]["top_logprobs"]], ["A"])
70        self.assertEqual(e[0]["top_logprobs"][0]["logprob"], 0)      # the whole distribution: just that id
71
72    def test_two_at_once_each_get_their_own(self):
73        self.start_lp()
74        short, long_ = "A or B?", "A or B? " + "x" * 300
75        alone = {t: self.entries(self.chat(t))[0]["logprob"] for t in (short, long_)}
76        self.assertNotEqual(alone[short], alone[long_])
77        for _ in range(5):
78            got, errs = {}, []
79
80            def run(t):
81                try:
82                    got[t] = self.entries(self.chat(t))[0]["logprob"]
83                except Exception as exc:          # noqa: BLE001 - reported below
84                    errs.append(repr(exc))
85            th = [threading.Thread(target=run, args=(t,)) for t in (short, long_, short, long_)]
86            for x in th:
87                x.start()
88            for x in th:
89                x.join(60)
90            self.assertEqual(errs, [])
91            self.assertEqual(got, alone)
92
93    def test_not_asked_nothing_changes(self):
94        self.start_lp()
95        r = self.chat("Is it A or B?", logprobs=False)
96        self.assertEqual(r["choices"][0]["message"]["content"], "o")
97        self.assertIsNone(r["choices"][0].get("logprobs"))
98
99    def test_longer_replies_are_refused_with_batch_slots(self):
100        self.start_lp()
101        with self.assertRaises(urllib.error.HTTPError) as cm:
102            self.chat("Is it A or B?", max_tokens=8)
103        self.assertEqual(cm.exception.code, 400)
104        self.assertIn("max_tokens 1", cm.exception.read().decode())
105        # the server is still serving, and a reply that does not ask is untouched
106        self.assertEqual(self.chat("still serving?", max_tokens=16, logprobs=False)["choices"][0]["message"]["content"],
107                         "ok, done.")
108
109    def test_an_engine_without_lp_lines(self):
110        self.start_lp(fake=tp.FAKE_BATCH)          # an older engine: the key is ignored, no LP line at all
111        r = self.chat("Is it A or B?")
112        self.assertEqual(r["choices"][0]["message"]["content"], "o")
113        self.assertEqual(self.entries(r), [])
114
115
116if __name__ == "__main__":
117    unittest.main()