okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fe0b0b39a
main
1"""serve/ds4_vision.py - pictures for DeepSeek-V4.1's own vision tower, which runs inside strata-dsv41 (the pack's 2vision.* / aligner.* tensors: pack_gguf.py --mmproj). There is no encoder process: the server sizes each picture as 3DeepSeek's inference/image_processor.py does, puts its span of image tokens in the prompt, and hands the engine the 4pixels in a DSI1 file (`GENI <max_new> [keys] <file> <ids>`); the engine encodes them and caches the spans itself. 5 6A picture's span is n_h * (n_w + 1) + 2 positions of image_token_id (start, each row of the 3 x 3 patch grid and its 7newline, end); the V4.1 chat template (serve/fixtures/deepseek41) writes one <|deepseek_image|> per picture, which the 8prompt's tokens carry as image_token_id, and expand() widens each to its span. 9""" 10from __future__import annotations 11 12import collections 13import hashlib 14import io 15import math 16import os 17import shutil 18import struct 19import threading 20from pathlib import Path 21 22CACHE_MAX = 64 # pictures kept sized (a conversation sends its pictures with every turn) 23 24 25def pack_geometry (pack :str | os .PathLike )-> dict | None : 26"""The vision keys of a pack's ds4.txt (vision.*, image_token_id), or None when the pack has no vision tower.""" 27try : 28lines = (Path (pack )/ "ds4.txt" ).read_text (encoding = "utf-8" ).splitlines () 29except OSError : 30return None 31geo = {} 32for line in lines : 33k ,_ ,v = line .partition (" " ) 34if k .startswith ("vision." )or k == "image_token_id" : 35geo [k ]= v .strip () 36if not int (float (geo .get ("vision.num_hidden_layers" ,0 )or 0 ))or "image_token_id" not in geo : 37return None 38return geo 39 40 41class Ds4Vision : 42"""The server side of the engine's vision tower: picture sizing and the DSI1 file. `load(source) -> bytes` reads 43a data: URL, an http(s) URL or a local file (server.Vision.load).""" 44 45elastic = False 46 47def __init__ (self ,geo :dict ,work_dir :Path ,load ): 48num = lambda k ,d :float (geo .get (k )or d )# noqa: E731 49self .patch = int (num ("vision.patch_size" ,14 )) 50self .merge = int (num ("vision.downsample_ratio" ,3 )) 51self .min_pixels = int (num ("vision.min_pixels" ,0 )) 52self .max_tokens = int (num ("vision.max_image_tokens" ,1024 )) 53ratio = geo .get ("vision.max_wh_ratio" ) 54self .max_wh_ratio = float (ratio )if ratio not in (None ,"" ,"None" ,"null" )and float (ratio )> 0 else None 55self .image_token = int (geo ["image_token_id" ]) 56self .dir = Path (work_dir ) 57self .load = load 58self .lock = threading .Lock () 59self .cache :collections .OrderedDict [str ,tuple [Path ,int ]]= collections .OrderedDict () 60 61# the encoder interface Service uses (Vision's): nothing to start or stop, the engine holds the tower 62def alive (self )-> bool : 63return True 64 65def restart (self ): 66pass 67 68def unload (self ): 69pass 70 71def shutdown (self ): 72"""The server ends: the sized pictures' folder goes with it (Vision.shutdown's #914).""" 73shutil .rmtree (self .dir ,ignore_errors = True ) 74 75def span (self ,n_h :int ,n_w :int )-> int : 76return n_h * (n_w + 1 )+ 2 77 78def plan (self ,width :int ,height :int )-> tuple [int ,int ,int ,int ]: 79"""image_processor.plan_image_grid: (n_h, n_w, pixel height, pixel width) for a picture of this size.""" 80p ,r = self .patch ,self .merge 81if self .max_wh_ratio is not None and width > height * self .max_wh_ratio : 82width = height * self .max_wh_ratio 83if 0 < width * height < self .min_pixels : 84k = (self .min_pixels / (width * height ))** 0.5 85width ,height = int (width * k ),int (height * k ) 86bw ,bh = math .ceil (width / p )* p ,math .ceil (height / p )* p 87 88def grid (h ,w ): 89return math .ceil ((h // p )/ r ),math .ceil ((w // p )/ r ) 90n_h ,n_w = grid (bh ,bw ) 91if self .span (n_h ,n_w )> self .max_tokens :# safe_resize / solve_resize_ratio 92ar = height / width 93mw = math .sqrt ((self .max_tokens - 2 )/ ar + 0.25 )- 0.5 94mh = mw * ar 95cell = p * r 96if mw < 1.0 : 97bh ,bw = (self .max_tokens - 2 )// 2 * cell ,cell 98elif mh < 1.0 : 99bh ,bw = cell , (self .max_tokens - 3 )* cell 100else : 101beta = min (math .floor (mw )* cell / width ,math .floor (mh )* cell / height ) 102bh ,bw = math .floor (height * beta / p )* p ,math .floor (width * beta / p )* p 103n_h ,n_w = grid (bh ,bw ) 104return n_h ,n_w ,bh ,bw 105 106def pixels (self ,data :bytes )-> tuple [int ,int ,bytes ,int ]: 107"""(width, height, RGB bytes, span) of a picture, sized for the tower: padded with grey to the planned size, 108or stretched to it for a picture wider than max_wh_ratio (image_processor.load_image). The camera's EXIF 109orientation is applied first and transparent areas become white, as the other readers do.""" 110try : 111from PIL import Image ,ImageOps 112except ImportError : 113raise ValueError ("pictures need Pillow (python -m pip install pillow)" )from None 114try : 115im = Image .open (io .BytesIO (data )) 116im .load () 117im = ImageOps .exif_transpose (im ) 118except Exception as e :# noqa: BLE001 - any decoder failure is the picture's 119raise ValueError (f"the image could not be read ( { e } )" )from None 120if im .mode in ("RGBA" ,"LA" )or im .mode == "P" and "transparency" in im .info : 121im = im .convert ("RGBA" ) 122bg = Image .new ("RGB" ,im .size , (255 ,255 ,255 )) 123bg .paste (im ,mask = im .split ()[- 1 ]) 124im = bg 125elif im .mode != "RGB" : 126im = im .convert ("RGB" ) 127n_h ,n_w ,bh ,bw = self .plan (im .width ,im .height ) 128if self .max_wh_ratio is not None and im .width >= self .max_wh_ratio * im .height : 129im = im .resize ((bw ,bh )) 130else : 131im = ImageOps .pad (im , (bw ,bh ),color = (127 ,127 ,127 )) 132return bw ,bh ,im .tobytes (),self .span (n_h ,n_w ) 133 134def encode (self ,source :str | bytes ,keep = ())-> tuple [Path ,int ]: 135"""-> (the picture's file: int32 width, int32 height, its RGB bytes; its span in image tokens).""" 136data = source if isinstance (source ,bytes )else self .load (source ) 137key = hashlib .sha256 (data ).hexdigest ()[:32 ] 138with self .lock : 139if key in self .cache and self .cache [key ][0 ].is_file (): 140self .cache .move_to_end (key ) 141return self .cache [key ] 142w ,h ,rgb ,n = self .pixels (data ) 143self .dir .mkdir (parents = True ,exist_ok = True ) 144path = self .dir / f" { key } .dsp" 145path .write_bytes (struct .pack ("<ii" ,w ,h )+ rgb ) 146with self .lock : 147self .cache [key ]= (path ,n ) 148held = {str (p )for p in keep }| {str (path )} 149for old in list (self .cache ): 150if len (self .cache )<= CACHE_MAX : 151break 152if str (self .cache [old ][0 ])not in held : 153self .cache .pop (old )[0 ].unlink (missing_ok = True ) 154return path ,n 155 156def expand (self ,ids :list [int ],encoded :list [tuple [Path ,int ]])-> tuple [list [int ],list [int ]]: 157"""The prompt with each picture's placeholder token widened to its span, and the spans' starts.""" 158out ,starts ,k = [], [],0 159for t in ids : 160if t != self .image_token : 161out .append (t ) 162continue 163if k == len (encoded ): 164raise ValueError ("the prompt and its images do not match" ) 165starts .append (len (out )) 166out += [self .image_token ]* encoded [k ][1 ] 167k += 1 168if k != len (encoded ): 169raise ValueError ("the prompt and its images do not match" ) 170return out ,starts 171 172@staticmethod 173def write (path :Path ,encoded :list [tuple [Path ,int ]],starts :list [int ])-> None : 174"""GENI's DSI1 file: 'DSI1', int32 count, then per picture int64 start and its file (width, height, RGB).""" 175flags = os .O_WRONLY | os .O_CREAT | os .O_TRUNC | getattr (os ,"O_BINARY" ,0 )| getattr (os ,"O_SHORT_LIVED" ,0 ) 176with os .fdopen (os .open (path ,flags ,0o600 ),"wb" )as f : 177f .write (b"DSI1" + struct .pack ("<i" ,len (encoded ))) 178for (p ,_ ),start in zip (encoded ,starts ): 179f .write (struct .pack ("<q" ,start )+ Path (p ).read_bytes ())