okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: DeepSeek-V4.1 pictures through the engine's own vision tower (a pack with vision.*: pack_gguf --mmproj) - sized as DeepSeek's image_processor.py, spans of image tokens, DSI1 file in GENI; images on without a vision section, --vision off turns them offfe0b0b39a

main
8.2 KiB179 linesraw
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."""
27    try:
28        lines = (Path(pack) / "ds4.txt").read_text(encoding="utf-8").splitlines()
29    except OSError:
30        return None
31    geo = {}
32    for line in lines:
33        k, _, v = line.partition(" ")
34        if k.startswith("vision.") or k == "image_token_id":
35            geo[k] = v.strip()
36    if not int(float(geo.get("vision.num_hidden_layers", 0) or 0)) or "image_token_id" not in geo:
37        return None
38    return 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
43    a data: URL, an http(s) URL or a local file (server.Vision.load)."""
44
45    elastic = False
46
47    def __init__(self, geo: dict, work_dir: Path, load):
48        num = lambda k, d: float(geo.get(k) or d)  # noqa: E731
49        self.patch = int(num("vision.patch_size", 14))
50        self.merge = int(num("vision.downsample_ratio", 3))
51        self.min_pixels = int(num("vision.min_pixels", 0))
52        self.max_tokens = int(num("vision.max_image_tokens", 1024))
53        ratio = geo.get("vision.max_wh_ratio")
54        self.max_wh_ratio = float(ratio) if ratio not in (None, "", "None", "null") and float(ratio) > 0 else None
55        self.image_token = int(geo["image_token_id"])
56        self.dir = Path(work_dir)
57        self.load = load
58        self.lock = threading.Lock()
59        self.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
62    def alive(self) -> bool:
63        return True
64
65    def restart(self):
66        pass
67
68    def unload(self):
69        pass
70
71    def shutdown(self):
72        """The server ends: the sized pictures' folder goes with it (Vision.shutdown's #914)."""
73        shutil.rmtree(self.dir, ignore_errors=True)
74
75    def span(self, n_h: int, n_w: int) -> int:
76        return n_h * (n_w + 1) + 2
77
78    def 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."""
80        p, r = self.patch, self.merge
81        if self.max_wh_ratio is not None and width > height * self.max_wh_ratio:
82            width = height * self.max_wh_ratio
83        if 0 < width * height < self.min_pixels:
84            k = (self.min_pixels / (width * height)) ** 0.5
85            width, height = int(width * k), int(height * k)
86        bw, bh = math.ceil(width / p) * p, math.ceil(height / p) * p
87
88        def grid(h, w):
89            return math.ceil((h // p) / r), math.ceil((w // p) / r)
90        n_h, n_w = grid(bh, bw)
91        if self.span(n_h, n_w) > self.max_tokens:          # safe_resize / solve_resize_ratio
92            ar = height / width
93            mw = math.sqrt((self.max_tokens - 2) / ar + 0.25) - 0.5
94            mh = mw * ar
95            cell = p * r
96            if mw < 1.0:
97                bh, bw = (self.max_tokens - 2) // 2 * cell, cell
98            elif mh < 1.0:
99                bh, bw = cell, (self.max_tokens - 3) * cell
100            else:
101                beta = min(math.floor(mw) * cell / width, math.floor(mh) * cell / height)
102                bh, bw = math.floor(height * beta / p) * p, math.floor(width * beta / p) * p
103            n_h, n_w = grid(bh, bw)
104        return n_h, n_w, bh, bw
105
106    def 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,
108        or stretched to it for a picture wider than max_wh_ratio (image_processor.load_image).  The camera's EXIF
109        orientation is applied first and transparent areas become white, as the other readers do."""
110        try:
111            from PIL import Image, ImageOps
112        except ImportError:
113            raise ValueError("pictures need Pillow (python -m pip install pillow)") from None
114        try:
115            im = Image.open(io.BytesIO(data))
116            im.load()
117            im = ImageOps.exif_transpose(im)
118        except Exception as e:  # noqa: BLE001 - any decoder failure is the picture's
119            raise ValueError(f"the image could not be read ({e})") from None
120        if im.mode in ("RGBA", "LA") or im.mode == "P" and "transparency" in im.info:
121            im = im.convert("RGBA")
122            bg = Image.new("RGB", im.size, (255, 255, 255))
123            bg.paste(im, mask=im.split()[-1])
124            im = bg
125        elif im.mode != "RGB":
126            im = im.convert("RGB")
127        n_h, n_w, bh, bw = self.plan(im.width, im.height)
128        if self.max_wh_ratio is not None and im.width >= self.max_wh_ratio * im.height:
129            im = im.resize((bw, bh))
130        else:
131            im = ImageOps.pad(im, (bw, bh), color=(127, 127, 127))
132        return bw, bh, im.tobytes(), self.span(n_h, n_w)
133
134    def 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)."""
136        data = source if isinstance(source, bytes) else self.load(source)
137        key = hashlib.sha256(data).hexdigest()[:32]
138        with self.lock:
139            if key in self.cache and self.cache[key][0].is_file():
140                self.cache.move_to_end(key)
141                return self.cache[key]
142        w, h, rgb, n = self.pixels(data)
143        self.dir.mkdir(parents=True, exist_ok=True)
144        path = self.dir / f"{key}.dsp"
145        path.write_bytes(struct.pack("<ii", w, h) + rgb)
146        with self.lock:
147            self.cache[key] = (path, n)
148            held = {str(p) for p in keep} | {str(path)}
149            for old in list(self.cache):
150                if len(self.cache) <= CACHE_MAX:
151                    break
152                if str(self.cache[old][0]) not in held:
153                    self.cache.pop(old)[0].unlink(missing_ok=True)
154        return path, n
155
156    def 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."""
158        out, starts, k = [], [], 0
159        for t in ids:
160            if t != self.image_token:
161                out.append(t)
162                continue
163            if k == len(encoded):
164                raise ValueError("the prompt and its images do not match")
165            starts.append(len(out))
166            out += [self.image_token] * encoded[k][1]
167            k += 1
168        if k != len(encoded):
169            raise ValueError("the prompt and its images do not match")
170        return out, starts
171
172    @staticmethod
173    def 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)."""
175        flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) | getattr(os, "O_SHORT_LIVED", 0)
176        with os.fdopen(os.open(path, flags, 0o600), "wb") as f:
177            f.write(b"DSI1" + struct.pack("<i", len(encoded)))
178            for (p, _), start in zip(encoded, starts):
179                f.write(struct.pack("<q", start) + Path(p).read_bytes())