"""DeepSeek-V4.1's in-engine vision tower, the server's half (serve/ds4_vision.py): pictures sized as DeepSeek's inference/image_processor.py sizes them, each placeholder widened to its span, and the DSI1 file strata-dsv41 reads.""" import io import struct import tempfile import unittest from pathlib import Path from serve import ds4_vision from serve.server import ds4_engine_vision try: from PIL import Image except ImportError: Image = None GEO = {"vision.num_hidden_layers": "32", "vision.patch_size": "14", "vision.downsample_ratio": "3", "vision.max_image_tokens": "1024", "vision.min_pixels": "295936", "image_token_id": "129264"} TOK = 129264 def vision(d): return ds4_vision.Ds4Vision(GEO, Path(d), lambda src: Path(src).read_bytes()) def png(size, mode="RGB", color=(200, 30, 30)): out = io.BytesIO() Image.new(mode, size, color).save(out, format="PNG") return out.getvalue() class Plan(unittest.TestCase): def test_deepseeks_examples(self): v = vision(tempfile.mkdtemp()) self.assertEqual(v.plan(1024, 701), (17, 25, 714, 1036)) # carrots.jpeg: 444 tokens self.assertEqual(v.plan(450, 308), (11, 16, 462, 658)) # corn.jpeg, under min_pixels: scaled up, 189 self.assertEqual(v.span(17, 25), 444) def test_a_large_picture_is_cut_to_the_token_limit(self): v = vision(tempfile.mkdtemp()) n_h, n_w, h, w = v.plan(4000, 3000) self.assertEqual((n_h, n_w, h, w), (27, 36, 1134, 1512)) for size in ((4000, 3000), (8000, 60), (60, 8000), (20000, 20000)): n_h, n_w, h, w = v.plan(*size) self.assertLessEqual(v.span(n_h, n_w), 1024, size) self.assertEqual((h % 14, w % 14), (0, 0), size) @unittest.skipIf(Image is None, "Pillow is not installed") class Files(unittest.TestCase): def test_spans_and_the_dsi1_file(self): d = tempfile.mkdtemp() v = vision(d) a, b = v.encode(png((1024, 701))), v.encode(png((450, 308), "RGBA", (0, 0, 0, 0))) self.assertEqual((a[1], b[1]), (444, 189)) self.assertEqual(v.encode(png((1024, 701))), a) # the same picture: sized once self.assertEqual(len(list(Path(d).glob("*.dsp"))), 2) ids, starts = v.expand([1, TOK, 2, 3, TOK, 4], [a, b]) self.assertEqual(starts, [1, 447]) self.assertEqual(ids[:1] + ids[445:447] + ids[-1:], [1, 2, 3, 4]) self.assertEqual(ids.count(TOK), 444 + 189) with self.assertRaises(ValueError): v.expand([1, TOK, 2], [a, b]) f = Path(d) / "req.dsi" v.write(f, [a, b], starts) raw = f.read_bytes() self.assertEqual(raw[:8], b"DSI1" + struct.pack("