okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
10.8 KiB253 linesraw
1"""serve/test_ds_pictures.py: DeepSeek-V4.1 pictures through the engine's own tower (serve/ds_pictures.py): the size rule, the span, the
2config switch, the prompt expansion and the DSI1 file the engine reads.  CPU only; the decode tests need Pillow and skip without it."""
3import io
4import os
5import struct
6import sys
7import tempfile
8import unittest
9from pathlib import Path
10
11sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
12from serve import ds_pictures as D  # noqa: E402
13
14try:
15    from PIL import Image
16except ImportError:                       # pragma: no cover
17    Image = None
18
19IMG = 129264
20
21
22def png(w, h, color=(220, 20, 20)) -> bytes:
23    im = Image.new("RGB", (w, h), color)
24    out = io.BytesIO()
25    im.save(out, format="PNG")
26    return out.getvalue()
27
28
29class Geometry(unittest.TestCase):
30    def test_span_matches_the_engine(self):
31        # mkimg.py's 672 x 672 picture: 16 x 17 + 2 = 274 positions
32        self.assertEqual(D.span_length(672, 672), 274)
33        self.assertEqual(D.span_length(42, 42), 1 * 2 + 2)
34        self.assertEqual(D.span_length(14, 14), 1 * 2 + 2)             # a partial merge cell still counts one
35
36    def test_sizes_are_multiples_of_42_within_the_budget(self):
37        for w, h in ((100, 100), (672, 672), (4000, 3000), (3000, 4000), (1920, 1080), (50, 3000)):
38            nw, nh = D.fit_size(w, h)
39            self.assertEqual((nw % 42, nh % 42), (0, 0), (w, h))
40            self.assertLessEqual(D.span_length(nw, nh), D.MAX_TOKENS, (w, h))
41            self.assertGreaterEqual(min(nw, nh), 42)
42
43    def test_small_pictures_grow_to_min_pixels(self):
44        w, h = D.fit_size(200, 200, min_pixels=295936)
45        self.assertGreaterEqual(w * h, 295936 * 0.8)                   # rounded to the 42 grid
46
47    def test_a_huge_picture_shrinks_to_the_limit(self):
48        w, h = D.fit_size(8000, 6000, 1024)
49        self.assertLessEqual(D.span_length(w, h), 1024)
50        self.assertGreater(D.span_length(w, h), 800)                   # but not far below it
51
52
53class Config(unittest.TestCase):
54    def pack(self, tower=True):
55        d = tempfile.mkdtemp()
56        lines = ["hidden_size 5120"]
57        if tower:
58            lines += ["vision.num_hidden_layers 32", "vision.patch_size 14", "vision.downsample_ratio 3", "vision.max_image_tokens 1024",
59                      "vision.min_pixels 295936", f"image_token_id {IMG}"]
60        Path(d, "ds4.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
61        return d
62
63    def test_on_by_default(self):
64        p = D.DsPictures.from_config({"args": ["--pack", self.pack(), "--max-context", "8192"]})
65        self.assertIsNotNone(p)
66        self.assertEqual((p.image_token, p.max_tokens, p.min_pixels), (IMG, 1024, 295936))
67
68    def test_vision_on_flag(self):
69        self.assertIsNotNone(D.DsPictures.from_config({"args": ["--pack", self.pack(), "--vision", "on"]}))
70
71    def test_vision_off_turns_it_off(self):
72        for word in ("off", "OFF", "no", "false", "0"):
73            self.assertIsNone(D.DsPictures.from_config({"args": ["--pack", self.pack(), "--vision", word]}), word)
74
75    def test_a_pack_without_a_tower_has_none(self):
76        self.assertIsNone(D.DsPictures.from_config({"args": ["--pack", self.pack(tower=False)]}))
77        self.assertIsNone(D.DsPictures.from_config({"args": []}))
78        self.assertIsNone(D.DsPictures.from_config({"args": ["--pack", "/nonexistent"]}))
79
80
81@unittest.skipIf(Image is None, "Pillow is not installed")
82class Build(unittest.TestCase):
83    def setUp(self):
84        self.tmp = tempfile.mkdtemp()
85        self.p = D.DsPictures(IMG, 1024, 0, self.tmp)
86
87    def read(self, path):
88        raw = Path(path).read_bytes()
89        self.assertEqual(raw[:4], b"DSI1")
90        n = struct.unpack("<i", raw[4:8])[0]
91        pos, out = 8, []
92        for _ in range(n):
93            start, w, h = struct.unpack("<qii", raw[pos:pos + 16])
94            pos += 16
95            out.append((start, w, h, raw[pos:pos + w * h * 3]))
96            pos += w * h * 3
97        self.assertEqual(pos, len(raw))
98        return out
99
100    def test_one_picture(self):
101        ids = [5, 6, IMG, 7, 8]
102        out, path = self.p.build(ids, [png(672, 672)])
103        self.assertEqual(out[:2], [5, 6])
104        self.assertEqual(out.count(IMG), 274)
105        self.assertEqual(out[2 + 274:], [7, 8])
106        (start, w, h, rgb), = self.read(path)
107        self.assertEqual((start, w, h), (2, 672, 672))
108        self.assertEqual(rgb[:3], bytes((220, 20, 20)))
109        self.assertEqual(out[start], IMG)
110
111    def test_two_pictures_keep_their_order_and_starts(self):
112        ids = [1, IMG, 2, 3, IMG, 4]
113        out, path = self.p.build(ids, [png(42, 42, (0, 255, 0)), png(84, 42, (0, 0, 255))])
114        a, b = self.read(path)
115        self.assertEqual((a[1], a[2]), (42, 42))
116        self.assertEqual((b[1], b[2]), (84, 42))
117        self.assertEqual(a[0], 1)
118        self.assertEqual(b[0], 1 + D.span_length(42, 42) + 2)
119        self.assertEqual(a[3][:3], bytes((0, 255, 0)))
120        self.assertEqual(b[3][-3:], bytes((0, 0, 255)))
121        self.assertEqual(out[-1], 4)
122
123    def test_counts_must_match(self):
124        with self.assertRaises(ValueError):
125            self.p.build([1, IMG, 2], [png(42, 42), png(42, 42)])
126        with self.assertRaises(ValueError):
127            self.p.build([1, 2], [png(42, 42)])
128
129    def test_odd_sizes_and_transparency_are_brought_to_the_grid(self):
130        im = Image.new("RGBA", (100, 61), (0, 0, 0, 0))                # fully transparent: white
131        buf = io.BytesIO()
132        im.save(buf, format="PNG")
133        w, h, rgb = self.p.prepare(buf.getvalue())
134        self.assertEqual((w % 42, h % 42), (0, 0))
135        self.assertEqual(rgb[:3], b"\xff\xff\xff")
136
137    def test_a_bad_image_is_a_value_error(self):
138        with self.assertRaises(ValueError):
139            self.p.prepare(b"not an image")
140
141    def test_a_jpeg_2000_picture_is_refused_before_it_is_decoded(self):
142        """#4220: JPEG 2000 is outside D.PICTURE_FORMATS (GHSA-78g4-xqwv-q3g8)."""
143        buf = io.BytesIO()
144        try:
145            Image.new("RGB", (16, 16)).save(buf, format="JPEG2000")
146        except (KeyError, OSError, ValueError):
147            self.skipTest("this Pillow cannot write JPEG 2000")
148        with self.assertRaises(ValueError):
149            self.p.prepare(buf.getvalue())
150
151    def test_the_engine_limit_holds_for_a_huge_picture(self):
152        w, h, rgb = self.p.prepare(png(3000, 2000))
153        self.assertLessEqual(D.span_length(w, h), 1024)
154        self.assertEqual(len(rgb), w * h * 3)
155
156
157# ---- the server side: a picture reaches the engine as a GENI file, text requests are untouched, pictures off is the old 400
158import base64  # noqa: E402
159import json  # noqa: E402
160import urllib.error  # noqa: E402
161import urllib.request  # noqa: E402
162
163from serve import frontend  # noqa: E402
164from serve.frontend import ChatTemplate  # noqa: E402
165from serve.server import Service, default_model_name, serve  # noqa: E402
166from serve.test_dsv41 import TEMPLATE, DsEngine, mini_tokenizer  # noqa: E402
167
168
169class SeenEngine(DsEngine):
170    """Keeps the picture file's bytes while the engine is 'reading' it (the server deletes the file after the run)."""
171
172    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
173        self.seen_file = Path(embeddings).read_bytes() if embeddings else None
174        self.seen_ids = list(ids)
175        yield from super().generate(ids, max_new, sampling, cancel, embeddings)
176
177
178@unittest.skipIf(Image is None, "Pillow is not installed")
179class Serve(unittest.TestCase):
180    @classmethod
181    def setUpClass(cls):
182        cls.tok = mini_tokenizer()
183        cls.img = cls.tok.encode("<|deepseek_image|>", parse_special=True)[0]
184
185    def start(self, pictures=True):
186        engine = SeenEngine(self.tok, "ok")
187        vision = D.DsPictures(self.img, 1024, 0, tempfile.mkdtemp()) if pictures else None
188        svc = Service(engine, self.tok, ChatTemplate(TEMPLATE), model_name=default_model_name({"arch": "deepseek41"}), vision=vision)
189        svc.model_arch = "deepseek41"
190        svc.set_family("deepseek41")
191        httpd = serve(svc, port=0)
192        self.addCleanup(httpd.server_close)
193        self.addCleanup(httpd.shutdown)
194        self.addCleanup(frontend.use_family, None)
195        self.engine, self.svc = engine, svc
196        self.base = f"http://127.0.0.1:{httpd.server_address[1]}"
197
198    def post(self, body):
199        req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
200                                     headers={"Content-Type": "application/json"})
201        try:
202            with urllib.request.urlopen(req, timeout=60) as r:
203                return r.status, json.loads(r.read().decode())
204        except urllib.error.HTTPError as e:
205            return e.code, json.loads(e.read().decode())
206
207    def picture_body(self):
208        url = "data:image/png;base64," + base64.b64encode(png(672, 672)).decode()
209        return {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url}},
210                                                          {"type": "text", "text": "What colour is this?"}]}], "max_tokens": 8}
211
212    def test_a_picture_reaches_the_engine_as_a_geni_file(self):
213        self.start()
214        code, out = self.post(self.picture_body())
215        self.assertEqual(code, 200, out)
216        self.assertEqual(self.engine.seen_ids.count(self.img), 274)
217        raw = self.engine.seen_file
218        self.assertEqual(raw[:4], b"DSI1")
219        n, = struct.unpack("<i", raw[4:8])
220        start, w, h = struct.unpack("<qii", raw[8:24])
221        self.assertEqual((n, w, h), (1, 672, 672))
222        self.assertEqual(self.engine.seen_ids[start], self.img)
223        self.assertEqual(len(raw), 24 + 672 * 672 * 3)
224        left = [p for p in Path(self.svc.vision.dir).glob("strata-ds-pics-*.dsi")]
225        self.assertEqual(left, [], "the picture file is removed after the run")
226
227    def test_text_requests_are_the_same_with_pictures_on(self):
228        body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}
229        self.start(pictures=True)
230        self.assertEqual(self.post(body)[0], 200)
231        with_pics = list(self.engine.seen_ids)
232        self.assertIsNone(self.engine.seen_file)
233        self.start(pictures=False)
234        self.assertEqual(self.post(body)[0], 200)
235        self.assertEqual(self.engine.seen_ids, with_pics)
236
237    def test_pictures_off_keeps_the_400(self):
238        self.start(pictures=False)
239        code, out = self.post(self.picture_body())
240        self.assertEqual(code, 400)
241        self.assertIn("without pictures for DeepSeek", json.dumps(out))
242
243    def test_a_follow_up_with_the_picture_in_history_works(self):
244        self.start()
245        body = self.picture_body()
246        body["messages"] += [{"role": "assistant", "content": "red and blue"}, {"role": "user", "content": "and the middle?"}]
247        code, out = self.post(body)
248        self.assertEqual(code, 200, out)
249        self.assertEqual(self.engine.seen_ids.count(self.img), 274)
250
251
252if __name__ == "__main__":
253    unittest.main()