okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""Pictures for DeepSeek-V4.1-Flash through the engine's OWN vision tower (strata-dsv41 --vision on, the default). 2 3The Qwen engines get pictures from a separate reader process (strata-vision): it turns a picture into embeddings and the server writes 4those into the file a `GENI` line names. strata-dsv41 carries its own 319 MiB tower, so the server only has to 51. decode each picture to RGB and bring it to a size the tower takes (both sides a multiple of 42 = patch 14 x merge 3, at most 6`vision.max_image_tokens` image tokens, at least `vision.min_pixels` pixels), 72. put one run of image tokens into the prompt where the template wrote its single `<|deepseek_image|>` placeholder: the run is 8n_h * (n_w + 1) + 2 positions long (the picture's rows, a newline marker per row, the start and end markers), and 93. write the pictures into the file of a `GENI` line (`DSI1`: int32 count, then per picture int64 start, int32 width, int32 height 10and its height x width x 3 RGB bytes), which the engine reads and encodes on its own GPU. 11Decoding needs Pillow (the server asks for it by name when it is missing). Nothing here starts a process or touches a GPU. 12""" 13from __future__import annotations 14 15import io 16import os 17import struct 18import tempfile 19from pathlib import Path 20 21#: The picture formats Pillow is allowed to open (docs/DETAILS.md: JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF; a phone's MPO file 22#: is opened by the JPEG entry). Pillow picks the decoder from the file's first bytes, never from its name or the client's 23#: Content-Type, so without this list a crafted JPEG 2000 (GHSA-78g4-xqwv-q3g8: OpenJPEG heap overflow in Pillow 24#: 11.1.0 to 12.3.0) or any other rarely used decoder was reachable from a picture request. Pillow 13 has the fix; 25#: Python 3.10 stays on 12.3.0, and this list keeps that install out of the decoder too. 26PICTURE_FORMATS = ("JPEG" ,"PNG" ,"GIF" ,"BMP" ,"WEBP" ,"TIFF" ,"AVIF" ) 27 28PATCH = 14 29MERGE = 3 30MAX_TOKENS = 1024 31MIN_PIXELS = 0 32OFF_WORDS = ("off" ,"no" ,"false" ,"0" ) 33 34 35def pack_keys (pack_dir )-> dict : 36"""The pack's ds4.txt as {key: value-string} ({} when it cannot be read).""" 37out = {} 38try : 39for line in (Path (pack_dir )/ "ds4.txt" ).read_text (encoding = "utf-8" ,errors = "replace" ).splitlines (): 40k ,_ ,v = line .partition (" " ) 41if k : 42out [k ]= v .strip () 43except OSError : 44pass 45return out 46 47 48def args_after (args ,flag ): 49"""The value that follows `flag` in an engine argument list (None when absent).""" 50for i ,a in enumerate (args or []): 51if a == flag and i + 1 < len (args ): 52return str (args [i + 1 ]) 53return None 54 55 56def vision_wanted (args )-> bool : 57"""`--vision off` (or no/false/0) turns pictures off; everything else, including no flag at all, leaves them on.""" 58v = args_after (args ,"--vision" ) 59return v is None or v .strip ().lower ()not in OFF_WORDS 60 61 62def span_length (width :int ,height :int ,patch :int = PATCH ,merge :int = MERGE )-> int : 63"""The image tokens one picture takes in the prompt: n_h * (n_w + 1) + 2 (the engine's own count, ds4_model.cu encode).""" 64gh ,gw = height // patch ,width // patch 65n_h ,n_w = - (- gh // merge ),- (- gw // merge ) 66return n_h * (n_w + 1 )+ 2 67 68 69def fit_size (width :int ,height :int ,max_tokens :int = MAX_TOKENS ,min_pixels :int = MIN_PIXELS , 70patch :int = PATCH ,merge :int = MERGE )-> tuple [int ,int ]: 71"""The size to resize a width x height picture to: its own shape, both sides a multiple of patch * merge, scaled down until its 72span is within `max_tokens` and up until it has `min_pixels` (when that fits the budget). Never smaller than one cell.""" 73cell = patch * merge 74if width <= 0 or height <= 0 : 75raise ValueError ("the picture has no size" ) 76 77def snap (scale :float )-> tuple [int ,int ]: 78return max (cell ,int (round (width * scale / cell ))* cell ),max (cell ,int (round (height * scale / cell ))* cell ) 79 80scale = 1.0 81if width * height < min_pixels : 82scale = (min_pixels / (width * height ))** 0.5 83w ,h = snap (scale ) 84while span_length (w ,h ,patch ,merge )> max_tokens :# shrink in small steps until the span fits the engine's limit 85scale *= 0.95 86w ,h = snap (scale ) 87if w == cell and h == cell : 88break 89return w ,h 90 91 92class DsPictures : 93"""What the Service holds as `vision` for a DeepSeek-V4.1 engine that reads pictures itself. It has the few members the 94Service asks of a picture encoder (alive, elastic, restart, unload, dir) and does the DeepSeek-specific work in build().""" 95 96elastic = False 97elastic_mib = 0 98 99def __init__ (self ,image_token :int ,max_tokens :int = MAX_TOKENS ,min_pixels :int = MIN_PIXELS ,tmp_dir = None , 100patch :int = PATCH ,merge :int = MERGE ): 101self .image_token = int (image_token ) 102self .max_tokens = int (max_tokens ) 103self .min_pixels = int (min_pixels ) 104self .patch ,self .merge = int (patch ),int (merge ) 105self .dir = Path (tmp_dir )if tmp_dir else Path (tempfile .gettempdir ()) 106 107@classmethod 108def from_config (cls ,cfg :dict ,tmp_dir = None ): 109"""-> DsPictures, or None: pictures are off (`--vision off`), or the pack has no vision tower (no vision.* keys / image token).""" 110args = cfg .get ("args" )or [] 111if not vision_wanted (args ): 112return None 113pack = args_after (args ,"--pack" ) 114if not pack : 115return None 116k = pack_keys (pack ) 117try : 118if int (k .get ("vision.num_hidden_layers" ,"0" ))<= 0 or "image_token_id" not in k : 119return None 120return cls (int (k ["image_token_id" ]),int (k .get ("vision.max_image_tokens" ,MAX_TOKENS )), 121int (float (k .get ("vision.min_pixels" ,MIN_PIXELS ))),tmp_dir , 122int (k .get ("vision.patch_size" ,PATCH )),int (k .get ("vision.downsample_ratio" ,MERGE ))) 123except ValueError : 124return None 125 126# ---- the members the Service asks of any picture encoder 127def alive (self )-> bool : 128return True 129 130def restart (self )-> None : 131pass 132 133def unload (self )-> None : 134pass 135 136def stop (self )-> None : 137pass 138 139# ---- the work 140@staticmethod 141def decode (data :bytes ): 142"""-> a Pillow RGB image (upright by its EXIF tag; transparency over white).""" 143try : 144from PIL import Image ,ImageOps 145except ImportError : 146raise ValueError ("DeepSeek reads pictures with Pillow, which is not installed here (python -m pip install pillow)" )from None 147try : 148im = Image .open (io .BytesIO (data ),formats = PICTURE_FORMATS ) 149im .load () 150im = ImageOps .exif_transpose (im ) 151except Exception as e :# noqa: BLE001 - any decoder failure is the picture's 152raise ValueError (f"the image could not be read ( { e } )" )from None 153if im .mode in ("RGBA" ,"LA" )or (im .mode == "P" and "transparency" in im .info ): 154im = im .convert ("RGBA" ) 155bg = Image .new ("RGB" ,im .size , (255 ,255 ,255 )) 156bg .paste (im ,mask = im .split ()[- 1 ]) 157return bg 158return im if im .mode == "RGB" else im .convert ("RGB" ) 159 160def prepare (self ,data :bytes )-> tuple [int ,int ,bytes ]: 161"""-> (width, height, RGB bytes) of the picture at the size the tower takes.""" 162im = self .decode (data ) 163w ,h = fit_size (im .width ,im .height ,self .max_tokens ,self .min_pixels ,self .patch ,self .merge ) 164if (w ,h )!= im .size : 165from PIL import Image 166im = im .resize ((w ,h ),Image .LANCZOS ) 167return w ,h ,im .tobytes () 168 169def encode (self ,source )-> None : 170"""Checks that a picture can be read and sized (the Service's pre-check of tool pictures); nothing is stored.""" 171data = source if isinstance (source ,bytes )else None 172if data is None : 173from serve .server import Vision 174data = Vision .load (source ) 175self .prepare (data ) 176 177def build (self ,ids :list [int ],pictures :list [bytes ])-> tuple [list [int ],str ]: 178"""The prompt ids with each placeholder expanded to its picture's span, and the path of the DSI1 file for the GENI line. 179`pictures`: the bytes of every image of the request, in prompt order.""" 180marks = [i for i ,t in enumerate (ids )if t == self .image_token ] 181if len (marks )!= len (pictures ): 182raise ValueError ("the prompt and its images do not match" ) 183out :list [int ]= [] 184entries = [] 185last = 0 186for pos ,data in zip (marks ,pictures ): 187w ,h ,rgb = self .prepare (data ) 188out += ids [last :pos ] 189entries .append ((len (out ),w ,h ,rgb )) 190out += [self .image_token ]* span_length (w ,h ,self .patch ,self .merge ) 191last = pos + 1 192out += ids [last :] 193self .dir .mkdir (parents = True ,exist_ok = True ) 194fd ,path = tempfile .mkstemp (prefix = "strata-ds-pics-" ,suffix = ".dsi" ,dir = str (self .dir )) 195try : 196with os .fdopen (fd ,"wb" )as f : 197f .write (b"DSI1" + struct .pack ("<i" ,len (entries ))) 198for start ,w ,h ,rgb in entries : 199f .write (struct .pack ("<qii" ,start ,w ,h )+ rgb ) 200except Exception : 201try : 202os .unlink (path ) 203except OSError : 204pass 205raise 206return out ,path