okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
9.2 KiB206 linesraw
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
5  1. 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),
7  2. put one run of image tokens into the prompt where the template wrote its single `<|deepseek_image|>` placeholder: the run is
8     n_h * (n_w + 1) + 2 positions long (the picture's rows, a newline marker per row, the start and end markers), and
9  3. write the pictures into the file of a `GENI` line (`DSI1`: int32 count, then per picture int64 start, int32 width, int32 height
10     and 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)."""
37    out = {}
38    try:
39        for line in (Path(pack_dir) / "ds4.txt").read_text(encoding="utf-8", errors="replace").splitlines():
40            k, _, v = line.partition(" ")
41            if k:
42                out[k] = v.strip()
43    except OSError:
44        pass
45    return out
46
47
48def args_after(args, flag):
49    """The value that follows `flag` in an engine argument list (None when absent)."""
50    for i, a in enumerate(args or []):
51        if a == flag and i + 1 < len(args):
52            return str(args[i + 1])
53    return 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."""
58    v = args_after(args, "--vision")
59    return 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)."""
64    gh, gw = height // patch, width // patch
65    n_h, n_w = -(-gh // merge), -(-gw // merge)
66    return 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,
70             patch: 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
72    span is within `max_tokens` and up until it has `min_pixels` (when that fits the budget).  Never smaller than one cell."""
73    cell = patch * merge
74    if width <= 0 or height <= 0:
75        raise ValueError("the picture has no size")
76
77    def snap(scale: float) -> tuple[int, int]:
78        return max(cell, int(round(width * scale / cell)) * cell), max(cell, int(round(height * scale / cell)) * cell)
79
80    scale = 1.0
81    if width * height < min_pixels:
82        scale = (min_pixels / (width * height)) ** 0.5
83    w, h = snap(scale)
84    while span_length(w, h, patch, merge) > max_tokens:       # shrink in small steps until the span fits the engine's limit
85        scale *= 0.95
86        w, h = snap(scale)
87        if w == cell and h == cell:
88            break
89    return 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
94    Service asks of a picture encoder (alive, elastic, restart, unload, dir) and does the DeepSeek-specific work in build()."""
95
96    elastic = False
97    elastic_mib = 0
98
99    def __init__(self, image_token: int, max_tokens: int = MAX_TOKENS, min_pixels: int = MIN_PIXELS, tmp_dir=None,
100                 patch: int = PATCH, merge: int = MERGE):
101        self.image_token = int(image_token)
102        self.max_tokens = int(max_tokens)
103        self.min_pixels = int(min_pixels)
104        self.patch, self.merge = int(patch), int(merge)
105        self.dir = Path(tmp_dir) if tmp_dir else Path(tempfile.gettempdir())
106
107    @classmethod
108    def 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)."""
110        args = cfg.get("args") or []
111        if not vision_wanted(args):
112            return None
113        pack = args_after(args, "--pack")
114        if not pack:
115            return None
116        k = pack_keys(pack)
117        try:
118            if int(k.get("vision.num_hidden_layers", "0")) <= 0 or "image_token_id" not in k:
119                return None
120            return cls(int(k["image_token_id"]), int(k.get("vision.max_image_tokens", MAX_TOKENS)),
121                       int(float(k.get("vision.min_pixels", MIN_PIXELS))), tmp_dir,
122                       int(k.get("vision.patch_size", PATCH)), int(k.get("vision.downsample_ratio", MERGE)))
123        except ValueError:
124            return None
125
126    # ---- the members the Service asks of any picture encoder
127    def alive(self) -> bool:
128        return True
129
130    def restart(self) -> None:
131        pass
132
133    def unload(self) -> None:
134        pass
135
136    def stop(self) -> None:
137        pass
138
139    # ---- the work
140    @staticmethod
141    def decode(data: bytes):
142        """-> a Pillow RGB image (upright by its EXIF tag; transparency over white)."""
143        try:
144            from PIL import Image, ImageOps
145        except ImportError:
146            raise ValueError("DeepSeek reads pictures with Pillow, which is not installed here (python -m pip install pillow)") from None
147        try:
148            im = Image.open(io.BytesIO(data), formats=PICTURE_FORMATS)
149            im.load()
150            im = ImageOps.exif_transpose(im)
151        except Exception as e:  # noqa: BLE001 - any decoder failure is the picture's
152            raise ValueError(f"the image could not be read ({e})") from None
153        if im.mode in ("RGBA", "LA") or (im.mode == "P" and "transparency" in im.info):
154            im = im.convert("RGBA")
155            bg = Image.new("RGB", im.size, (255, 255, 255))
156            bg.paste(im, mask=im.split()[-1])
157            return bg
158        return im if im.mode == "RGB" else im.convert("RGB")
159
160    def prepare(self, data: bytes) -> tuple[int, int, bytes]:
161        """-> (width, height, RGB bytes) of the picture at the size the tower takes."""
162        im = self.decode(data)
163        w, h = fit_size(im.width, im.height, self.max_tokens, self.min_pixels, self.patch, self.merge)
164        if (w, h) != im.size:
165            from PIL import Image
166            im = im.resize((w, h), Image.LANCZOS)
167        return w, h, im.tobytes()
168
169    def 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."""
171        data = source if isinstance(source, bytes) else None
172        if data is None:
173            from serve.server import Vision
174            data = Vision.load(source)
175        self.prepare(data)
176
177    def 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."""
180        marks = [i for i, t in enumerate(ids) if t == self.image_token]
181        if len(marks) != len(pictures):
182            raise ValueError("the prompt and its images do not match")
183        out: list[int] = []
184        entries = []
185        last = 0
186        for pos, data in zip(marks, pictures):
187            w, h, rgb = self.prepare(data)
188            out += ids[last:pos]
189            entries.append((len(out), w, h, rgb))
190            out += [self.image_token] * span_length(w, h, self.patch, self.merge)
191            last = pos + 1
192        out += ids[last:]
193        self.dir.mkdir(parents=True, exist_ok=True)
194        fd, path = tempfile.mkstemp(prefix="strata-ds-pics-", suffix=".dsi", dir=str(self.dir))
195        try:
196            with os.fdopen(fd, "wb") as f:
197                f.write(b"DSI1" + struct.pack("<i", len(entries)))
198                for start, w, h, rgb in entries:
199                    f.write(struct.pack("<qii", start, w, h) + rgb)
200        except Exception:
201            try:
202                os.unlink(path)
203            except OSError:
204                pass
205            raise
206        return out, path