okami.mom/strata

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

Niko1221Merge f-0213-tuicfg (final c6dda74bf) into f-0213-int049ae1c67

main
16.1 KiB358 linesraw
1"""serve/server.py for an Intel Arc: the same server, with the Intel pieces added from outside.
2
3    python sycl/serve/server_intel.py --engine strata --config strata-<model>.json --port 8080 [...]
4
5Every argument is serve/server.py's.  Nothing in serve/ is edited (the SYCL port keeps out of the shared files so
6upstream merges stay clean); this wrapper adds, at run time:
7
8  - the Monitor tab's GPU readings on an Intel Arc (sycl/serve/xe_telemetry.py) (also on a PC with an NVIDIA card: the engine runs on the Intel one);
9  - a model menu in the web app's header, for a host that swaps models on one GPU: the config names the RPC that
10    does the swap as "model_switcher" (it takes {"mode": m} and answers {"mode", "up", "starting", "choices",
11    "urls"}); the menu offers the models served on this server's port.  Without that key nothing changes;
12  - OpenAI `logprobs` / `top_logprobs` on /v1/chat/completions (streamed or not): the engine (the SYCL port,
13    `logprobs=K` on its GEN line) writes an `LP` line after each `T` line, which upstream's server would ignore.
14    The values are the model's log-probabilities from the verify window's logits, before sampling, temperature and
15    penalties; with thinking on, the thinking tokens are listed too (in order, under `reasoning_content`).
16"""
17from __future__ import annotations
18
19import collections
20import json
21import sys
22import time
23import urllib.parse
24import urllib.request
25from pathlib import Path
26
27HERE = Path(__file__).resolve().parent
28ROOT = HERE.parent.parent
29sys.path.insert(0, str(ROOT))
30sys.path.insert(0, str(HERE))
31
32import serve.server as S  # noqa: E402
33import serve.telemetry as T  # noqa: E402
34from xe_telemetry import _XeGpu  # noqa: E402
35
36
37def install_xe_reader():
38    """telemetry.gpu_reader -> the xe reader whenever an Intel Arc is there.  #2001: this server runs the SYCL engine,
39    so the cards it reports are the Intel ones; before, an NVIDIA card in the same PC answered first and the Monitor
40    (and the benchmark report, which takes the card's name from it) showed the GeForce the engine never used."""
41    orig = T.gpu_reader
42
43    def gpu_reader(index=0, amd=False):
44        xe = _XeGpu(index)
45        return xe if xe.ok() else orig(index, amd)
46
47    T.gpu_reader = gpu_reader
48
49
50def install_shared_embeddings():
51    """Pictures: the engine runs in a container, and a request's image embeddings reach it as a file named on its GENI line.
52    serve/server.py writes that file to /dev/shm when that has room, and strata-sycl.sh shares the host's /dev/shm with the
53    container, so the path means the same on both sides.  Anywhere else (a full /dev/shm) the container cannot see the file:
54    said once, in the log, in plain words."""
55    orig = S.combined_embeddings_path
56    said = []
57
58    def path(vision_dir, nbytes):
59        p = orig(vision_dir, nbytes)
60        if not str(p).startswith("/dev/shm/") and not said:
61            said.append(1)
62            print("[strata] /dev/shm has no room for this picture: the engine runs in a container that sees only the host's /dev/shm, so it "
63                  "cannot read the picture. Free /dev/shm (or enlarge it: mount -o remount,size=4G /dev/shm) and send it again.", flush=True)
64        return p
65    S.combined_embeddings_path = path
66
67
68def model_switcher(url: str, port, model, mode: str = "") -> dict:
69    """The host's model swapper: the models it serves on THIS port, which one holds the card, whether one is loading.
70    With `mode`, asks for that one first; this server is then usually the one stopped, so the web app waits for
71    /health to name the new model."""
72    try:
73        body = json.dumps({"mode": mode} if mode else {}).encode()
74        req = urllib.request.Request(url, body, {"Content-Type": "application/json"})
75        with urllib.request.urlopen(req, timeout=10) as r:
76            res = json.load(r)
77        st = res.get("result", res)
78    except (OSError, ValueError) as e:
79        return {"enabled": True, "error": f"the model switcher did not answer ({e})"}
80    urls = st.get("urls") or {}
81    mine = {k: v for k, v in (st.get("choices") or {}).items()
82            if not urls or str(urllib.parse.urlsplit(str(urls.get(k, ""))).port) == str(port)}
83    return {"enabled": True, "mode": st.get("mode"), "up": st.get("up"), "starting": st.get("starting"),
84            "choices": mine, "model": model}
85
86
87def install_switcher(argv):
88    """Wraps make_handler: GET/POST /switcher, the menu's script and style, and the index page that loads them."""
89    def arg(name, default=None):
90        return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else default
91
92    try:
93        cfg = json.loads(Path(arg("--config")).read_text(encoding="utf-8-sig")) if arg("--config") else {}
94    except (OSError, ValueError):
95        cfg = {}
96    url = cfg.get("model_switcher")
97    if not url:
98        return
99    port = arg("--port", "8080")
100    web = HERE / "web"
101    types = {".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8"}
102    make_handler = S.make_handler
103
104    def make(svc):
105        base = make_handler(svc)
106
107        class Handler(base):
108            def _send(self, body: bytes, ctype: str):
109                self.send_response(200)
110                self.send_header("Content-Type", ctype)
111                self.send_header("Cache-Control", "no-cache")
112                self.send_header("Content-Length", str(len(body)))
113                self.end_headers()
114                self.wfile.write(body)
115
116            def do_GET(self):
117                path = self.path.split("?")[0].rstrip("/")
118                if path == "/switcher":
119                    if self._authorized():
120                        self._json(200, model_switcher(url, port, svc.model))
121                    return
122                if path.startswith("/sycl-web/"):
123                    f = web / path[len("/sycl-web/"):]
124                    if f.parent != web or f.suffix not in types or not f.is_file():
125                        self._json(404, {"error": {"message": "not found"}})
126                        return
127                    self._send(f.read_bytes(), types[f.suffix])
128                    return
129                if path == "":
130                    page = (ROOT / "serve" / "web" / "index.html").read_text(encoding="utf-8")
131                    page = page.replace("</head>", '<link rel="stylesheet" href="sycl-web/switcher.css">\n</head>', 1)
132                    page = page.replace("</body>", '<script src="sycl-web/switcher.js"></script>\n</body>', 1)
133                    self._send(page.encode("utf-8"), "text/html; charset=utf-8")
134                    return
135                super().do_GET()
136
137            def do_POST(self):
138                path = self.path.split("?")[0].rstrip("/")
139                if path == "/switcher":
140                    if not self._authorized():
141                        return
142                    req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
143                    self._json(200, model_switcher(url, port, svc.model, str(req.get("mode") or "")))
144                    return
145                super().do_POST()
146
147        return Handler
148
149    S.make_handler = make
150
151
152def install_logprobs():
153    """`LP` lines next to their tokens, the request's `logprobs` to the engine, OpenAI's `logprobs` in the reply."""
154    Eng = S.StrataEngine
155
156    def _pump(self):   # serve/server.py's StrataEngine._pump, plus: an LP line goes beside its token, not in the queue
157        proc, lines = self.proc, self.lines
158        slot_q = self.slot_q
159        lp = self.__dict__.setdefault("lp_lines", collections.deque())
160        last_t = None
161        line = None
162        for line in proc.stdout:
163            if line.startswith(S.FATAL_PREFIXES):   # as serve/server.py: never a slot's own line
164                if self.proc is proc:
165                    self.silent_note = "Unrecoverable native verification failure: " + line[4:].strip()
166                    self.ended = True
167                try:
168                    proc.terminate()
169                except OSError:
170                    pass
171                break
172            if line.startswith(("BT ", "BDONE ")) and slot_q:   # --batch ("parallel"): a batch slot's own lines
173                try:
174                    slot_q[int(line.split()[1])].put(line)
175                    continue
176                except (IndexError, ValueError):
177                    pass
178            if line.startswith("LP "):
179                lp.append((last_t, line))
180                continue
181            if line.startswith("T "):
182                try:
183                    last_t = int(line[2:])
184                except ValueError:
185                    last_t = None
186            lines.put(line)
187        if self.proc is proc:
188            self.ended = True
189            if line and line.startswith("ERR"):
190                self.last_err = line[4:].strip()
191        lines.put(None)
192        for q in slot_q:
193            q.put(None)
194    Eng._pump = _pump
195
196    keys = Eng.sampling_keys
197
198    def sampling_keys(sampling):
199        k = top_logprobs(sampling or {})
200        return keys(sampling) + (f" logprobs={k}" if k is not None else "")
201    Eng.sampling_keys = staticmethod(sampling_keys)
202
203    generate = Eng.generate
204
205    def gen(self, *a, **kw):
206        self.__dict__.setdefault("lp_lines", collections.deque()).clear()   # this request's lines only
207        return generate(self, *a, **kw)
208    Eng.generate = gen
209
210    def entry(tok, t, line):
211        f = line.split()
212        if len(f) < 2 or f[1] == "nan":
213            return None
214
215        def item(i, lp):
216            b = tok.token_bytes(i) if hasattr(tok, "token_bytes") else tok.decode([i]).encode()
217            return {"token": b.decode("utf-8", "replace"), "logprob": lp, "bytes": list(b)}
218        e = item(t, float(f[1])) if t is not None else {"token": "", "logprob": float(f[1]), "bytes": []}
219        e["top_logprobs"] = [item(int(i), float(v)) for i, _, v in (x.partition(":") for x in f[2:])]
220        return e
221
222    chunks = S.openai_chunks
223
224    def openai_chunks(svc, req, *a, **kw):
225        if top_logprobs(req) is None:
226            yield from chunks(svc, req, *a, **kw)
227            return
228        eng = svc.engine
229        for c in chunks(svc, req, *a, **kw):
230            lp = getattr(eng, "lp_lines", None)
231            if c and c.get("choices") and lp:
232                got = []
233                while lp:
234                    t, line = lp.popleft()
235                    if t in svc.stop_ids:   # the stop token ends the reply; OpenAI does not list it
236                        continue
237                    e = entry(svc.tok, t, line)
238                    if e is not None:
239                        got.append(e)
240                if got:
241                    d = c["choices"][0].get("delta") or {}
242                    key = "reasoning_content" if d.get("reasoning_content") and not d.get("content") else "content"
243                    c["choices"][0]["logprobs"] = {key: got}
244            yield c
245    S.openai_chunks = openai_chunks
246
247    collect = S.openai_collect
248
249    def openai_collect(cs):
250        merged = {"content": [], "reasoning_content": []}
251
252        def tap():
253            for c in cs:
254                if c and c.get("choices") and c["choices"][0].get("logprobs"):
255                    for k, v in c["choices"][0]["logprobs"].items():
256                        merged[k].extend(v)
257                yield c
258        out = collect(tap())
259        if merged["content"] or merged["reasoning_content"]:
260            out["choices"][0]["logprobs"] = {k: v for k, v in merged.items() if v} | {"content": merged["content"]}
261        return out
262    S.openai_collect = openai_collect
263
264
265def install_narrator():
266    """The start narrator of serve/server.py says the CUDA engine's thing - tens of GB read into RAM, "YOUR PC CAN BE
267    SLOW OR STOP RESPONDING" - at the experts' step. With --stream-experts the SYCL port reads them from the GGUF
268    into VRAM (and a pinned mirror), which does not do that: say that instead. Without it (an i915 card) the experts
269    do go into a RAM arena and the original text stands."""
270    orig = S.narrate_start
271
272    def narrate_start(log_path, offset, args, done, heartbeat=20.0):
273        if "--stream-experts" not in args:
274            return orig(log_path, offset, args, done, heartbeat)
275        t0 = last = time.time()
276        said = set()
277
278        def say(key, text):
279            nonlocal last
280            if key not in said:
281                said.add(key)
282                last = time.time()
283                print(text, flush=True)
284
285        say("weights", "[strata] starting the engine: reading the model's weights ...")
286        pos = offset
287        while not done.wait(0.5):
288            try:
289                with open(log_path, "rb") as f:
290                    f.seek(pos)
291                    chunk = f.read()
292            except OSError:
293                chunk = b""
294            if chunk.count(b"\n"):
295                cut = chunk.rfind(b"\n") + 1
296                pos += cut
297                for line in chunk[:cut].decode("utf-8", "replace").splitlines():
298                    if "PLE on" in line or "expert arena:" in line:
299                        say("arena", "[strata] streaming the experts from the model files into the GPU's memory "
300                                     "(and a pinned RAM mirror for what does not fit); the first start takes a few minutes ...")
301                    elif " loaded " in line and "GiB at" in line:
302                        say("loaded", "[strata] experts loaded: " + line.split(" loaded ", 1)[1].strip() +
303                            f" ({time.time() - t0:.0f} s so far)")
304                    elif "expert cache " in line and " slots, " in line and "auto" not in line:
305                        n = line.split("expert cache ", 1)[1].split(";")[0].replace(" slots,", " experts,").strip()
306                        say("cache", f"[strata] filling the GPU's expert cache ({n}) ...")
307                    elif "session is up" in line:
308                        say("up", "[strata] almost ready ...")
309            if time.time() - last > heartbeat:
310                last = time.time()
311                print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True)
312    S.narrate_start = narrate_start
313
314
315def top_logprobs(req: dict):
316    """The K for the engine's logprobs=K, or None when the request did not ask (OpenAI: logprobs=true, top_logprobs
317    0..20; the legacy completions form, logprobs=N, is taken as N)."""
318    lp = req.get("logprobs")
319    if lp is True:
320        k = req.get("top_logprobs")
321        return max(0, min(20, int(k))) if isinstance(k, int) and not isinstance(k, bool) else 0
322    if isinstance(lp, int) and not isinstance(lp, bool) and lp >= 0:
323        return min(20, lp)
324    return None
325
326
327def install_two_card_spec():
328    """engine_args -> the config's --spec 2 on exactly two Arc B-series cards (strata_control/intel_spec.py), at every start: a
329    config written before (by an older setup, or by the launcher) gets what a new setup run would write.  The person's own
330    --spec ("user_args", or a value other than setup's 4) is never touched; one plain line says what changed."""
331    from strata_control import intel_spec
332    original = S.engine_args
333
334    def engine_args(cfg, exe=None, *, announce=True):      # the base signature (serve/server.py engine_args): start calls it with exe, the budget check with announce=False
335        args = original(cfg, exe, announce=announce)
336        try:
337            if cfg.get("backend") == "sycl" and S.layer_split_of(cfg):
338                sysfs = intel_spec.sysfs_cards()
339                cards = [sysfs[i] for i in S.gpu_list(cfg) if isinstance(i, int) and 0 <= i < len(sysfs)]
340                new, note = intel_spec.plan(args, cfg.get("user_args"), cards, mtp_off=cfg.get("mtp") is False)
341                if note:
342                    if announce:                                   # (announce=False builds the arguments without any line)
343                        print("[strata] " + note, flush=True)
344                    return new
345        except Exception as exc:  # noqa: BLE001 - a rule that cannot be read leaves the config's own args
346            print(f"[strata] two-card --spec rule skipped: {exc}", flush=True)
347        return args
348    S.engine_args = engine_args
349
350
351if __name__ == "__main__":
352    install_two_card_spec()
353    install_xe_reader()
354    install_shared_embeddings()
355    install_narrator()
356    install_switcher(sys.argv[1:])
357    install_logprobs()
358    sys.exit(S.main())