okami.mom/strata

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

waveringanaserve: the config sampling block takes a default logit_bias (a request's own logit_bias still wins)a89b97898

main
7.6 KiB155 linesraw
1import json
2from pathlib import Path
3from types import SimpleNamespace
4import unittest
5import urllib.error
6import urllib.request
7
8from serve.logit_bias import engine_key, normalize, validate_request
9from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve
10from serve.frontend import ChatTemplate
11
12
13class LogitBias(unittest.TestCase):
14    def test_forms_and_transport(self):
15        self.assertEqual(normalize({"7": -100, "9": 2.5}, 10), normalize([[7, False], [9, 2.5]], 10))
16        self.assertEqual(engine_key([[9, 2.5], [7, False]]), " logit_bias=7:-100,9:2.5")
17        self.assertEqual(StrataEngine.sampling_keys({"logit_bias": {"7": -100}}), " logit_bias=7:-100")
18        for value in [None, {}, []]:
19            self.assertEqual(engine_key(value), "")
20
21    def test_invalid(self):
22        bad = [True, 1, "x", [1], [[1]], [[1, 0, 2]], {"-1": 0}, {"1.0": 0}, {"10": 0},
23               {"1": False}, [[1, True]], [[1.0, 0]], [[True, 0]], [[1, 0], ["1", 2]],
24               {"1": 101}, {"1": -101}, {"1": float('nan')}, {"1": float('inf')}, {"1": 10**1000}]
25        for value in bad:
26            with self.subTest(value=str(value)[:50]), self.assertRaises(ValueError):
27                normalize(value, 10)
28        with self.assertRaises(ValueError):
29            normalize({str(i): -100 for i in range(10)}, 10)
30
31    def test_large_list(self):
32        entries = [[i, False] for i in range(103215)]
33        self.assertEqual(len(normalize(entries, 248320)), 103215)
34        self.assertEqual(engine_key(entries).count(':-100'), 103215)
35
36    def test_capability_and_batch(self):
37        for engine in [SimpleNamespace(info={})]:
38            with self.assertRaises(ValueError):
39                validate_request({'logit_bias': {'1': -100}}, engine, 10)
40            self.assertEqual(validate_request({}, engine, 10), {})
41        # --batch: a slot keeps its request's own bias (Verifier::set_slot_logit_bias)
42        self.assertEqual(validate_request({'logit_bias': {'1': -100}}, SimpleNamespace(info={'logit_bias': 1}, batch=2), 10), {1: -100})
43        self.assertEqual(validate_request({'logit_bias': {'1': -100}}, SimpleNamespace(info={'logit_bias': 1}), 10), {1: -100})
44
45    def test_http_rejects_before_stream(self):
46        tok = ByteTokenizer()
47        engine = MockEngine(tok, 'ok', max_context=4096)
48        service = Service(engine, tok, ChatTemplate(Path(__file__).parent/'chat_template.jinja'))
49        httpd = serve(service, port=0)
50        try:
51            for bias in [True, {'1': -100}, [[1, True]]]:
52                data = json.dumps({'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 2,
53                                   'stream': True, 'logit_bias': bias}).encode()
54                req = urllib.request.Request(f'http://127.0.0.1:{httpd.server_address[1]}/v1/chat/completions',
55                                             data=data, headers={'Content-Type': 'application/json'})
56                with self.assertRaises(urllib.error.HTTPError) as caught:
57                    urllib.request.urlopen(req, timeout=10)
58                with caught.exception as response:
59                    self.assertEqual(response.code, 400)
60                    self.assertIn('logit_bias', json.loads(response.read())['error']['message'])
61        finally:
62            httpd.shutdown()
63            httpd.server_close()
64
65
66class LogitBiasCache(unittest.TestCase):
67    """A long list is normalized once; the cache must not change what a call returns or raises."""
68
69    def setUp(self):
70        from serve import logit_bias
71        logit_bias._cache.clear()
72        logit_bias._last = None
73
74    def test_same_answers_as_the_plain_function(self):
75        from serve.logit_bias import _normalize
76        forms = [{str(i): -100 for i in range(200)},
77                 [[i, False] for i in range(200)],
78                 {str(i): (i % 7) - 3.5 for i in range(200)},
79                 [[str(i), 2] for i in range(200)]]
80        for vocab in (None, 1000):
81            for form in forms:
82                want = _normalize(form, vocab)
83                for _ in range(3):                   # the first call fills the cache, the others read it
84                    self.assertEqual(normalize(form, vocab), want)
85                self.assertEqual(normalize(json.loads(json.dumps(form)), vocab), want)   # an equal list, another object
86        for form in forms:
87            ref = " logit_bias=" + ",".join(f"{i}:{b:g}" for i, b in sorted(_normalize(form).items()))
88            self.assertEqual(engine_key(form), ref)
89            self.assertEqual(engine_key(form), ref)
90
91    def test_false_is_not_zero(self):
92        ban = [[i, False] for i in range(100)]
93        zero = [[i, 0] for i in range(100)]
94        self.assertTrue(ban == zero)                  # Python calls them equal, so an == key would mix them up
95        for first, second in [(ban, zero), (zero, ban)]:
96            self.setUp()
97            self.assertEqual(set(normalize(first).values()), {-100.0 if first is ban else 0.0})
98            self.assertEqual(set(normalize(second).values()), {-100.0 if second is ban else 0.0})
99
100    def test_a_bad_list_is_never_stored(self):
101        good = {str(i): -1 for i in range(100)}
102        normalize(good, 1000)
103        for bad in [{**good, "5": True}, {**good, "5": 101}, {**good, "5": float("nan")}, {**good, "5": "x"}]:
104            for _ in range(2):
105                with self.assertRaises(ValueError):
106                    normalize(bad, 1000)
107        pairs = [[i, 1] for i in range(100)]
108        normalize(pairs)
109        with self.assertRaises(ValueError):           # True == 1, but a bool is not a bias
110            normalize([[i, 1] for i in range(99)] + [[99, True]])
111        with self.assertRaises(ValueError):           # a duplicate ID
112            normalize([[i, 1] for i in range(100)] + [[0, 1]])
113
114    def test_vocabulary_size_is_part_of_the_key(self):
115        ids = {str(i): -1 for i in range(100)}
116        self.assertEqual(len(normalize(ids, 1000)), 100)
117        with self.assertRaises(ValueError):
118            normalize(ids, 50)
119        self.assertEqual(len(normalize(ids)), 100)
120        with self.assertRaises(ValueError):
121            normalize(ids, 50)
122
123    def test_the_result_is_a_copy(self):
124        ids = {str(i): -1 for i in range(100)}
125        first = normalize(ids)
126        first[0] = 99.0
127        self.assertEqual(normalize(ids)[0], -1.0)
128        self.assertEqual(validate_request({"logit_bias": ids}, SimpleNamespace(info={"logit_bias": 1}), 1000)[0], -1.0)
129
130    def test_an_equal_list_in_a_later_request_is_a_hit(self):
131        from serve import logit_bias
132        a = {str(i): -100 for i in range(100)}
133        b = json.loads(json.dumps(a))
134        self.assertIsNot(a, b)
135        key_a = engine_key(a)
136        logit_bias._last = None                       # a later request: the previous object is gone
137        key_b = engine_key(b)
138        self.assertIs(key_a, key_b)                   # one entry, one key string
139        self.assertEqual(len(logit_bias._cache), 1)
140
141    def test_the_cache_is_bounded(self):
142        from serve import logit_bias
143        for n in range(logit_bias._CACHE_MAX + 3):
144            normalize({str(i): -(n + 1) for i in range(100)})
145        self.assertEqual(len(logit_bias._cache), logit_bias._CACHE_MAX)
146
147class ConfigLogitBias(unittest.TestCase):
148    def test_config_default_bias_is_normalized(self):
149        from serve.server import sampling_defaults_from_config
150        self.assertEqual(sampling_defaults_from_config({"sampling": {"logit_bias": {"9008": -100, 25414: 2}}})["logit_bias"], {9008: -100.0, 25414: 2.0})
151
152    def test_bad_config_bias_refuses_to_start(self):
153        from serve.server import sampling_defaults_from_config
154        with self.assertRaises(SystemExit):
155            sampling_defaults_from_config({"sampling": {"logit_bias": {"x": -100}}})