okami.mom/strata

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

Niko1221Merge f-agent-turn 018f0d659 into f-p4-int4cf79d5dc

main
6.7 KiB113 linesraw
1"""The GEN keys serve/server.py can send an engine, against the keys the all-cards split engine's parser (src/split/tools/sfnx.cpp, parse_gen) accepts.
2
3A key the split engine does not know ends the request with "GEN: unknown key ..." (an HTTP 503 in the middle of a reply: pen_from was found that way on the AMD package
4gate). Every key the server can send is classified here; a new one fails this test until it is sent to the split engine safely, dropped for it, or refused with a 400."""
5
6from __future__ import annotations
7
8import re
9import unittest
10from pathlib import Path
11
12ROOT = Path(__file__).resolve().parents[2]
13
14# keys the split engine's parse_gen accepts (some only note that they change nothing: pin, pcie_frac, spec_min_p, pipe, aux_cpus, cvec)
15ACCEPTED = {"temperature", "top_p", "top_k", "min_p", "penalty_repeat", "penalty_freq", "penalty_present", "penalty_last_n", "seed", "keep", "ckpt", "pin",
16            "pcie_frac", "spec_min_p", "pipe", "aux_cpus", "cvec", "img_keys"}
17# keys the server does not send to a split engine: pen_from is dropped (StrataEngine.pen_from_key), logprobs / allowed / logit_bias are refused with a 400 first
18# (refuse_for_split, logit_bias.validate_request)
19DROPPED = {"pen_from"}
20REFUSED = {"logprobs", "allowed", "logit_bias"}
21# keys only other engines are sent: the prefill-only request of serve/split.py,
22# and hold (the thinking budget's GEN hold=N:ID): the server sends it only to an engine whose READY line says "hold" (a --batch engine: "holdb" too), which is the
23# single-card engine (src/program/generate.cpp prints "READY <ctx> stop hold holdb"); the split engine says "READY <ctx> stop" (sfnx.cpp), so it is never sent it, and
24# the server also refuses it for a split engine by name (Service._run).  Sent to a split engine anyway, parse_gen would end the request with "GEN: unknown key hold".
25OTHER_ENGINES = {"prefill", "hold"}
26
27
28def server_keys() -> set[str]:
29    text = (ROOT / "serve" / "server.py").read_text(encoding="utf-8")
30    keys = set(re.findall(r'keys \+= f?" (\w+)=', text))
31    keys |= set(re.findall(r'keys \+= " (\w+)="', text))
32    for tup in re.findall(r'for k in \(((?:"\w+",? ?)+)\):\n\s+v = tune\.get\(k\)', text):
33        keys |= set(re.findall(r'"(\w+)"', tup))
34    keys |= set(re.findall(r'f" (pen_from)=', text))
35    keys |= set(re.findall(r'" (prefill)=1', text))
36    keys |= set(re.findall(r'f" (cvec)=', text))
37    keys |= set(re.findall(r'"(logit_bias)="', (ROOT / "serve" / "logit_bias.py").read_text(encoding="utf-8")))
38    keys |= set(re.findall(r'" (\w+)=" \+', (ROOT / "serve" / "logit_bias.py").read_text(encoding="utf-8")))
39    keys |= set(re.findall(r'keys \+= f" (\w+)=', text))
40    keys |= set(re.findall(r'keys0 \+ f" (\w+)=', text))   # generate_batched adds the thinking budget's hold per leg (P2b)
41    return keys
42
43
44def parser_keys() -> set[str]:
45    text = (ROOT / "src" / "split" / "tools" / "sfnx.cpp").read_text(encoding="utf-8")
46    body = text.split("static GenReq parse_gen", 1)[-1] if "static GenReq parse_gen" in text else text
47    return set(re.findall(r'k == "(\w+)"', body))
48
49
50class SplitGenKeys(unittest.TestCase):
51    def test_every_key_the_server_can_send_is_classified(self):
52        sent = server_keys()
53        known = ACCEPTED | DROPPED | REFUSED | OTHER_ENGINES
54        self.assertEqual(sorted(sent - known), [], "a GEN key the server sends that nobody classified for the split engine")
55        for must in ("pen_from", "logprobs", "allowed", "temperature", "penalty_last_n", "seed"):
56            self.assertIn(must, sent, f"{must}: the parse of serve/server.py no longer finds it (update this test)")
57
58    def test_hold_is_only_for_an_engine_that_says_hold_and_the_split_engine_never_does(self):
59        """The server sends `hold` only to an engine whose READY line says "hold" (the --batch slots: "holdb"); the split engine's READY line says neither, and
60        its parser does not know the key (it would end the request: "GEN: unknown key hold")."""
61        split = (ROOT / "src" / "split" / "tools" / "sfnx.cpp").read_text(encoding="utf-8")
62        readys = re.findall(r'say\("READY "[^;]*;', split)
63        self.assertTrue(readys, "the split engine's READY line is no longer found (update this test)")
64        for line in readys:
65            self.assertNotIn("hold", line)
66        self.assertNotIn("hold", parser_keys())
67        gen = (ROOT / "src" / "program" / "generate.cpp").read_text(encoding="utf-8")
68        self.assertIn('"READY %lld stop hold holdb\\n"', gen)      # the engine that does take it says both
69        self.assertIn('"hold" in f[2:]', (ROOT / "serve" / "server.py").read_text(encoding="utf-8"))   # and the server reads the word, not the engine's name
70
71    def test_the_keys_sent_to_a_split_engine_are_accepted_by_its_parser(self):
72        parser = parser_keys()
73        self.assertEqual(sorted(ACCEPTED - parser), [], "a key the split engine is sent but its parse_gen does not know")
74
75    def test_pen_from_is_not_sent_to_a_split_engine_and_is_to_the_others(self):
76        from serve import server
77
78        split = object.__new__(server.StrataEngine)
79        split.split_engine = True
80        other = object.__new__(server.StrataEngine)
81        other.split_engine = False
82        self.assertEqual(split.pen_from_key(100, 130), "")
83        self.assertEqual(other.pen_from_key(100, 130), " pen_from=99")
84        self.assertEqual(other.pen_from_key(100, 100), "")
85
86    def test_a_split_engine_name_is_found_by_its_executable(self):
87        from serve import server
88
89        for exe, want in (("/x/strata-split-4-amd", True), ("/x/strata-split-2-sm86", True), ("C:/x/strata-split-2", True), ("/x/strata", False),
90                          ("/x/strata-vision", False)):
91            e = object.__new__(server.StrataEngine)
92            e.split_engine = __import__("os").path.basename(exe).startswith("strata-split")
93            self.assertEqual(e.split_engine, want, exe)
94
95    def test_logprobs_and_logit_bias_are_refused_with_a_400_for_a_split_engine(self):
96        from serve import logit_bias, server
97
98        e = object.__new__(server.StrataEngine)
99        e.split_engine = True
100        with self.assertRaises(ValueError) as cm:
101            server.refuse_for_split(e, {"logprobs": True, "top_logprobs": 3})
102        self.assertIn("--split-engine off", str(cm.exception))
103        server.refuse_for_split(e, {"temperature": 0.7})          # an ordinary request goes on
104        with self.assertRaises(ValueError) as cm:
105            logit_bias.validate_request({"logit_bias": {"5": 1.0}}, e, 1000)
106        self.assertIn("--split-engine off", str(cm.exception))
107        other = object.__new__(server.StrataEngine)
108        other.split_engine = False
109        server.refuse_for_split(other, {"logprobs": True, "top_logprobs": 3})   # other engines unchanged
110
111
112if __name__ == "__main__":
113    unittest.main()