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