"""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 config switch, the prompt expansion and the DSI1 file the engine reads. CPU only; the decode tests need Pillow and skip without it.""" import io import os import struct import sys import tempfile import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve import ds_pictures as D # noqa: E402 try: from PIL import Image except ImportError: # pragma: no cover Image = None IMG = 129264 def png(w, h, color=(220, 20, 20)) -> bytes: im = Image.new("RGB", (w, h), color) out = io.BytesIO() im.save(out, format="PNG") return out.getvalue() class Geometry(unittest.TestCase): def test_span_matches_the_engine(self): # mkimg.py's 672 x 672 picture: 16 x 17 + 2 = 274 positions self.assertEqual(D.span_length(672, 672), 274) self.assertEqual(D.span_length(42, 42), 1 * 2 + 2) self.assertEqual(D.span_length(14, 14), 1 * 2 + 2) # a partial merge cell still counts one def test_sizes_are_multiples_of_42_within_the_budget(self): for w, h in ((100, 100), (672, 672), (4000, 3000), (3000, 4000), (1920, 1080), (50, 3000)): nw, nh = D.fit_size(w, h) self.assertEqual((nw % 42, nh % 42), (0, 0), (w, h)) self.assertLessEqual(D.span_length(nw, nh), D.MAX_TOKENS, (w, h)) self.assertGreaterEqual(min(nw, nh), 42) def test_small_pictures_grow_to_min_pixels(self): w, h = D.fit_size(200, 200, min_pixels=295936) self.assertGreaterEqual(w * h, 295936 * 0.8) # rounded to the 42 grid def test_a_huge_picture_shrinks_to_the_limit(self): w, h = D.fit_size(8000, 6000, 1024) self.assertLessEqual(D.span_length(w, h), 1024) self.assertGreater(D.span_length(w, h), 800) # but not far below it class Config(unittest.TestCase): def pack(self, tower=True): d = tempfile.mkdtemp() lines = ["hidden_size 5120"] if tower: lines += ["vision.num_hidden_layers 32", "vision.patch_size 14", "vision.downsample_ratio 3", "vision.max_image_tokens 1024", "vision.min_pixels 295936", f"image_token_id {IMG}"] Path(d, "ds4.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") return d def test_on_by_default(self): p = D.DsPictures.from_config({"args": ["--pack", self.pack(), "--max-context", "8192"]}) self.assertIsNotNone(p) self.assertEqual((p.image_token, p.max_tokens, p.min_pixels), (IMG, 1024, 295936)) def test_vision_on_flag(self): self.assertIsNotNone(D.DsPictures.from_config({"args": ["--pack", self.pack(), "--vision", "on"]})) def test_vision_off_turns_it_off(self): for word in ("off", "OFF", "no", "false", "0"): self.assertIsNone(D.DsPictures.from_config({"args": ["--pack", self.pack(), "--vision", word]}), word) def test_a_pack_without_a_tower_has_none(self): self.assertIsNone(D.DsPictures.from_config({"args": ["--pack", self.pack(tower=False)]})) self.assertIsNone(D.DsPictures.from_config({"args": []})) self.assertIsNone(D.DsPictures.from_config({"args": ["--pack", "/nonexistent"]})) @unittest.skipIf(Image is None, "Pillow is not installed") class Build(unittest.TestCase): def setUp(self): self.tmp = tempfile.mkdtemp() self.p = D.DsPictures(IMG, 1024, 0, self.tmp) def read(self, path): raw = Path(path).read_bytes() self.assertEqual(raw[:4], b"DSI1") n = struct.unpack("", parse_special=True)[0] def start(self, pictures=True): engine = SeenEngine(self.tok, "ok") vision = D.DsPictures(self.img, 1024, 0, tempfile.mkdtemp()) if pictures else None svc = Service(engine, self.tok, ChatTemplate(TEMPLATE), model_name=default_model_name({"arch": "deepseek41"}), vision=vision) svc.model_arch = "deepseek41" svc.set_family("deepseek41") httpd = serve(svc, port=0) self.addCleanup(httpd.server_close) self.addCleanup(httpd.shutdown) self.addCleanup(frontend.use_family, None) self.engine, self.svc = engine, svc self.base = f"http://127.0.0.1:{httpd.server_address[1]}" def post(self, body): req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=60) as r: return r.status, json.loads(r.read().decode()) except urllib.error.HTTPError as e: return e.code, json.loads(e.read().decode()) def picture_body(self): url = "data:image/png;base64," + base64.b64encode(png(672, 672)).decode() return {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url}}, {"type": "text", "text": "What colour is this?"}]}], "max_tokens": 8} def test_a_picture_reaches_the_engine_as_a_geni_file(self): self.start() code, out = self.post(self.picture_body()) self.assertEqual(code, 200, out) self.assertEqual(self.engine.seen_ids.count(self.img), 274) raw = self.engine.seen_file self.assertEqual(raw[:4], b"DSI1") n, = struct.unpack("