"""serve/ds4_vision.py - pictures for DeepSeek-V4.1's own vision tower, which runs inside strata-dsv41 (the pack's vision.* / aligner.* tensors: pack_gguf.py --mmproj). There is no encoder process: the server sizes each picture as DeepSeek's inference/image_processor.py does, puts its span of image tokens in the prompt, and hands the engine the pixels in a DSI1 file (`GENI [keys] `); the engine encodes them and caches the spans itself. A 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 newline, end); the V4.1 chat template (serve/fixtures/deepseek41) writes one <|deepseek_image|> per picture, which the prompt's tokens carry as image_token_id, and expand() widens each to its span. """ from __future__ import annotations import collections import hashlib import io import math import os import shutil import struct import threading from pathlib import Path CACHE_MAX = 64 # pictures kept sized (a conversation sends its pictures with every turn) def pack_geometry(pack: str | os.PathLike) -> dict | None: """The vision keys of a pack's ds4.txt (vision.*, image_token_id), or None when the pack has no vision tower.""" try: lines = (Path(pack) / "ds4.txt").read_text(encoding="utf-8").splitlines() except OSError: return None geo = {} for line in lines: k, _, v = line.partition(" ") if k.startswith("vision.") or k == "image_token_id": geo[k] = v.strip() if not int(float(geo.get("vision.num_hidden_layers", 0) or 0)) or "image_token_id" not in geo: return None return geo class Ds4Vision: """The server side of the engine's vision tower: picture sizing and the DSI1 file. `load(source) -> bytes` reads a data: URL, an http(s) URL or a local file (server.Vision.load).""" elastic = False def __init__(self, geo: dict, work_dir: Path, load): num = lambda k, d: float(geo.get(k) or d) # noqa: E731 self.patch = int(num("vision.patch_size", 14)) self.merge = int(num("vision.downsample_ratio", 3)) self.min_pixels = int(num("vision.min_pixels", 0)) self.max_tokens = int(num("vision.max_image_tokens", 1024)) ratio = geo.get("vision.max_wh_ratio") self.max_wh_ratio = float(ratio) if ratio not in (None, "", "None", "null") and float(ratio) > 0 else None self.image_token = int(geo["image_token_id"]) self.dir = Path(work_dir) self.load = load self.lock = threading.Lock() self.cache: collections.OrderedDict[str, tuple[Path, int]] = collections.OrderedDict() # the encoder interface Service uses (Vision's): nothing to start or stop, the engine holds the tower def alive(self) -> bool: return True def restart(self): pass def unload(self): pass def shutdown(self): """The server ends: the sized pictures' folder goes with it (Vision.shutdown's #914).""" shutil.rmtree(self.dir, ignore_errors=True) def span(self, n_h: int, n_w: int) -> int: return n_h * (n_w + 1) + 2 def plan(self, width: int, height: int) -> tuple[int, int, int, int]: """image_processor.plan_image_grid: (n_h, n_w, pixel height, pixel width) for a picture of this size.""" p, r = self.patch, self.merge if self.max_wh_ratio is not None and width > height * self.max_wh_ratio: width = height * self.max_wh_ratio if 0 < width * height < self.min_pixels: k = (self.min_pixels / (width * height)) ** 0.5 width, height = int(width * k), int(height * k) bw, bh = math.ceil(width / p) * p, math.ceil(height / p) * p def grid(h, w): return math.ceil((h // p) / r), math.ceil((w // p) / r) n_h, n_w = grid(bh, bw) if self.span(n_h, n_w) > self.max_tokens: # safe_resize / solve_resize_ratio ar = height / width mw = math.sqrt((self.max_tokens - 2) / ar + 0.25) - 0.5 mh = mw * ar cell = p * r if mw < 1.0: bh, bw = (self.max_tokens - 2) // 2 * cell, cell elif mh < 1.0: bh, bw = cell, (self.max_tokens - 3) * cell else: beta = min(math.floor(mw) * cell / width, math.floor(mh) * cell / height) bh, bw = math.floor(height * beta / p) * p, math.floor(width * beta / p) * p n_h, n_w = grid(bh, bw) return n_h, n_w, bh, bw def pixels(self, data: bytes) -> tuple[int, int, bytes, int]: """(width, height, RGB bytes, span) of a picture, sized for the tower: padded with grey to the planned size, or stretched to it for a picture wider than max_wh_ratio (image_processor.load_image). The camera's EXIF orientation is applied first and transparent areas become white, as the other readers do.""" try: from PIL import Image, ImageOps except ImportError: raise ValueError("pictures need Pillow (python -m pip install pillow)") from None try: im = Image.open(io.BytesIO(data)) im.load() im = ImageOps.exif_transpose(im) except Exception as e: # noqa: BLE001 - any decoder failure is the picture's raise ValueError(f"the image could not be read ({e})") from None if im.mode in ("RGBA", "LA") or im.mode == "P" and "transparency" in im.info: im = im.convert("RGBA") bg = Image.new("RGB", im.size, (255, 255, 255)) bg.paste(im, mask=im.split()[-1]) im = bg elif im.mode != "RGB": im = im.convert("RGB") n_h, n_w, bh, bw = self.plan(im.width, im.height) if self.max_wh_ratio is not None and im.width >= self.max_wh_ratio * im.height: im = im.resize((bw, bh)) else: im = ImageOps.pad(im, (bw, bh), color=(127, 127, 127)) return bw, bh, im.tobytes(), self.span(n_h, n_w) def encode(self, source: str | bytes, keep=()) -> tuple[Path, int]: """-> (the picture's file: int32 width, int32 height, its RGB bytes; its span in image tokens).""" data = source if isinstance(source, bytes) else self.load(source) key = hashlib.sha256(data).hexdigest()[:32] with self.lock: if key in self.cache and self.cache[key][0].is_file(): self.cache.move_to_end(key) return self.cache[key] w, h, rgb, n = self.pixels(data) self.dir.mkdir(parents=True, exist_ok=True) path = self.dir / f"{key}.dsp" path.write_bytes(struct.pack(" tuple[list[int], list[int]]: """The prompt with each picture's placeholder token widened to its span, and the spans' starts.""" out, starts, k = [], [], 0 for t in ids: if t != self.image_token: out.append(t) continue if k == len(encoded): raise ValueError("the prompt and its images do not match") starts.append(len(out)) out += [self.image_token] * encoded[k][1] k += 1 if k != len(encoded): raise ValueError("the prompt and its images do not match") return out, starts @staticmethod def write(path: Path, encoded: list[tuple[Path, int]], starts: list[int]) -> None: """GENI's DSI1 file: 'DSI1', int32 count, then per picture int64 start and its file (width, height, RGB).""" flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) | getattr(os, "O_SHORT_LIVED", 0) with os.fdopen(os.open(path, flags, 0o600), "wb") as f: f.write(b"DSI1" + struct.pack("