okami.mom/strata

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

Niko1221Merge f-027-split: split serving (#4000), opt-in, first versionccf18ea14

main
21.7 KiB488 linesraw
1"""Split serving: one engine reads the prompt, another makes the answer (issue #4000, idea and manual setup by @MarcoTool).
2
3Two engines on the same PC, one card each, the same model files and the same session settings.  A long prompt is read by
4the prefill engine, which saves the session (the engine's own session file: SAVE <path>) into RAM; the decode engine
5restores it (RESTORE <path>) and makes the answer.  The server keeps its one HTTP front, its one Service and its one set of
6endpoints; `SplitEngine` stands in for the engine, as `ReplicaEngine` does for replicas.
7
8Opt-in, in the run config (nothing changes without it):
9
10    "split_serve": {"prefill_gpu": 0, "decode_gpu": 1}
11
12    prefill_gpu / decode_gpu   the card of each engine, numbered as nvidia-smi numbers them (required, different)
13    min_prompt_tokens          hand a request over only when the decode engine would read at least this many new tokens
14                               itself (default 2048); a shorter tail is read by the decode engine in place
15    dir                        where the session files go (default /dev/shm when it has room, else the temp folder)
16    shared_arena               true (default): one copy of the experts in RAM for both engines (Linux, a file in /dev/shm
17                               when the experts fit there); false: each engine keeps its own copy; a path: that file
18    prefill_args / decode_args extra engine arguments for one role (a bigger expert cache for the decode engine, say)
19
20What must match between the two engines is what the session file checks (docs/SPLIT_SERVE.md): the model files, the engine
21version, the backend, --kv, --max-context, --kv-resident, --mtp-window, the rope settings and the arithmetic switches.  They
22start from one config, so they do.  Every failure on the way (a prefill engine that died, a refused file) is not an error
23for the client: the decode engine reads the prompt itself, as it would without the option.
24
25Honest limit of this first version: one request at a time (the Service's FIFO), one conversation resident on the decode
26engine (a restore replaces what it held), no parallel slots (--batch), no layer split in an engine, no pictures (a request
27with pictures goes to the decode engine alone).
28"""
29from __future__ import annotations
30
31import os
32import shutil
33import tempfile
34import threading
35import time
36
37MIN_TOKENS = 2048                    # the decode engine's own tail below this is read in place
38KNOWN_KEYS = {"prefill_gpu", "decode_gpu", "min_prompt_tokens", "dir", "shared_arena", "prefill_args", "decode_args"}
39FORBIDDEN_ARGS = {                   # engine arguments that cannot be used in a split-serve engine, and why
40    "--layer-split": "an engine of the split runs on one card",
41    "--split-device": "an engine of the split runs on one card",
42    "--peer-device": "session files do not support --peer-device",
43    "--batch": "session files do not support --batch (parallel requests)",
44    "--slots": "session files do not support parallel slots",
45}
46HEAL_COOLDOWN_S = 60.0               # a prefill engine that died is started again at most this often
47HEARTBEAT_S = 5.0                    # a long file step sends a keep-alive this often
48
49
50class SplitConfigError(ValueError):
51    pass
52
53
54def split_spec(cfg: dict) -> dict | None:
55    """The checked "split_serve" section of the run config, or None when the option is off."""
56    raw = cfg.get("split_serve")
57    if raw is None or raw is False:
58        return None
59    if not isinstance(raw, dict):
60        raise SplitConfigError('"split_serve" must be {"prefill_gpu": N, "decode_gpu": M}, not ' + repr(raw))
61    unknown = sorted(set(raw) - KNOWN_KEYS)
62    if unknown:
63        raise SplitConfigError(f'"split_serve" has no key {unknown[0]!r} (keys: {", ".join(sorted(KNOWN_KEYS))})')
64    cards = []
65    for k in ("prefill_gpu", "decode_gpu"):
66        v = raw.get(k)
67        if isinstance(v, str) and v.strip().isdigit():
68            v = int(v.strip())
69        if isinstance(v, bool) or not isinstance(v, int) or v < 0:
70            raise SplitConfigError(f'"split_serve" needs "{k}": the number of a card (0, 1, ...), not {v!r}')
71        cards.append(v)
72    if cards[0] == cards[1]:
73        raise SplitConfigError(f'"split_serve": prefill_gpu and decode_gpu are both card {cards[0]}; each engine needs a '
74                               "card of its own")
75    out = {"prefill_gpu": cards[0], "decode_gpu": cards[1]}
76    n = raw.get("min_prompt_tokens", MIN_TOKENS)
77    if isinstance(n, bool) or not isinstance(n, int) or n < 0:
78        raise SplitConfigError(f'"split_serve": "min_prompt_tokens" must be a number of tokens (0 or more), not {n!r}')
79    out["min_prompt_tokens"] = n
80    d = raw.get("dir")
81    if d is not None and (not isinstance(d, str) or not d.strip()):
82        raise SplitConfigError(f'"split_serve": "dir" must be a folder name, not {d!r}')
83    out["dir"] = d
84    sa = raw.get("shared_arena", True)
85    if not (isinstance(sa, bool) or (isinstance(sa, str) and sa.strip())):
86        raise SplitConfigError(f'"split_serve": "shared_arena" must be true, false or a file name, not {sa!r}')
87    out["shared_arena"] = sa
88    for k in ("prefill_args", "decode_args"):
89        a = raw.get(k, [])
90        if not isinstance(a, list) or not all(isinstance(x, (str, int, float)) and not isinstance(x, bool) for x in a):
91            raise SplitConfigError(f'"split_serve": "{k}" must be a list of engine arguments')
92        out[k] = [str(x) for x in a]
93    return out
94
95
96def check_cfg(cfg: dict, spec: dict) -> None:
97    """Refuse (with the reason, in plain words) a config the split cannot run."""
98    if cfg.get("replicas") not in (None, False):
99        raise SplitConfigError('"split_serve" and "replicas" cannot be used together: both start engines on the cards')
100    args = [str(a) for a in cfg.get("args") or []] + spec["prefill_args"] + spec["decode_args"]
101    for flag, why in FORBIDDEN_ARGS.items():
102        if flag in args:
103            raise SplitConfigError(f'"split_serve" cannot be used with {flag} in the engine arguments: {why}')
104    for i, a in enumerate(args):
105        if a == "--prompt-cache" and i + 1 < len(args) and args[i + 1].strip() == "0":
106            raise SplitConfigError('"split_serve" needs the conversation cache (--prompt-cache 1 or more): the session '
107                                   "file is made from it")
108    if cfg.get("batch") or cfg.get("parallel"):
109        raise SplitConfigError('"split_serve" does not run parallel requests ("parallel"/"batch"): remove it')
110
111
112def _suffixed(path, tag: str):
113    if not isinstance(path, str) or not path:
114        return path
115    root, ext = os.path.splitext(path)
116    return f"{root}.{tag}{ext}"
117
118
119def role_cfg(cfg: dict, spec: dict, role: str) -> dict:
120    """The config of one engine of the split: its own card, log and learned-profile file; its role's extra arguments."""
121    import copy
122    c = copy.deepcopy(cfg)
123    c.pop("split_serve", None)
124    c["gpu"] = spec[f"{role}_gpu"]
125    c.pop("hip_ordinal", None)
126    c.pop("gpu_roles", None)                      # the roles were for a layer split over several cards
127    c["log"] = _suffixed(cfg.get("log"), role)
128    if cfg.get("expert_profile_save"):
129        c["expert_profile_save"] = _suffixed(cfg["expert_profile_save"], role)
130    extra = spec[f"{role}_args"]
131    if extra:
132        c["args"] = list(c["args"]) + extra
133    return c
134
135
136def _arg_value(args: list, flag: str):
137    for i, a in enumerate(args):
138        if a == flag and i + 1 < len(args):
139            return args[i + 1]
140    return None
141
142
143def arena_path(cfg: dict, spec: dict) -> tuple[str | None, str]:
144    """(file for --shared-expert-arena or None, a line for the log).  Only Linux can share the arena; the experts
145    file must fit /dev/shm (a tmpfs is half of the RAM by default) unless the config names another file."""
146    args = [str(a) for a in cfg.get("args") or []]
147    if "--shared-expert-arena" in args:
148        return None, "the config already names a shared expert arena"
149    sa = spec["shared_arena"]
150    if sa is False:
151        return None, "shared_arena is off: each engine keeps its own copy of the experts in RAM"
152    if os.name == "nt":
153        return None, ("this OS cannot share the expert arena between two engines (Linux only): each engine keeps its own "
154                      "copy of the experts in RAM, so the PC needs RAM for two")
155    if isinstance(sa, str):
156        return os.path.abspath(sa), f"shared expert arena in {os.path.abspath(sa)}"
157    pack = _arg_value(args, "--pack")
158    experts = os.path.join(pack, "experts.bin") if pack else None
159    if not experts or not os.path.isfile(experts):
160        return None, ("no experts.bin to size a shared arena from (a pack that reads the GGUF in place): each engine "
161                      "keeps its own copy of the experts; name a file in \"shared_arena\" to share one")
162    need = os.path.getsize(experts)
163    try:
164        free = shutil.disk_usage("/dev/shm").free
165    except OSError:
166        free = 0
167    if free < need + (1 << 30):
168        return None, (f"/dev/shm has {free / 2**30:.1f} GiB free and the experts are {need / 2**30:.1f} GiB: each engine "
169                      "keeps its own copy of the experts in RAM (two copies). To share one copy name a file in "
170                      "\"shared_arena\" (a file on disk works, it is written once) or make /dev/shm bigger")
171    return "/dev/shm/strata-split-arena.bin", f"one shared expert arena in /dev/shm ({need / 2**30:.1f} GiB)"
172
173
174def session_dir(spec: dict) -> str:
175    d = spec.get("dir")
176    if d:
177        os.makedirs(d, exist_ok=True)
178        return d
179    shm = "/dev/shm"
180    try:
181        if os.name != "nt" and os.path.isdir(shm) and os.access(shm, os.W_OK) and shutil.disk_usage(shm).free > (6 << 30):
182            return tempfile.mkdtemp(prefix="strata-split-", dir=shm)
183    except OSError:
184        pass
185    return tempfile.mkdtemp(prefix="strata-split-")
186
187
188def common_prefix(a, b) -> int:
189    n = min(len(a), len(b))
190    i = 0
191    while i < n and a[i] == b[i]:
192        i += 1
193    return i
194
195
196class SplitEngine:
197    """Stands in for one engine (the interface Service uses), over a prefill engine and a decode engine."""
198
199    NOT_HERE = {"session_file", "vram", "ctl", "slot_cv"}       # not offered: one conversation file / VRAM resize / control line
200    PROPAGATE = {"silence_s", "gpu_busy"}
201
202    def __init__(self, prefill, decode, *, min_tokens: int = MIN_TOKENS, work_dir: str | None = None,
203                 arena_file: str | None = None, say=print):
204        d = self.__dict__
205        d["prefill"], d["decode"] = prefill, decode
206        d["cur"] = decode                      # the engine the request is on now (progress, last)
207        d["min_tokens"] = int(min_tokens)
208        d["work_dir"] = work_dir or tempfile.mkdtemp(prefix="strata-split-")
209        d["arena_file"] = arena_file
210        d["say"] = say
211        d["held"] = []                         # the tokens the decode engine's session holds (an estimate: ids + answer)
212        d["seq"] = 0
213        d["heal_at"] = 0.0
214        d["healing"] = False
215        d["lock"] = threading.Lock()
216        d["stats"] = {"requests": 0, "handed_over": 0, "fallbacks": 0, "short": 0, "bytes": 0, "prefill_ms": 0.0,
217                      "save_ms": 0.0, "restore_ms": 0.0, "last": None}
218
219    # ---- attribute plumbing
220    def __getattr__(self, name):
221        if name in self.NOT_HERE or name.startswith("__"):
222            raise AttributeError(name)
223        return getattr(self.decode, name)
224
225    def __setattr__(self, name, value):
226        if name in self.PROPAGATE:
227            self.prefill.__setattr__(name, value)
228            self.decode.__setattr__(name, value)
229        else:
230            self.__dict__[name] = value
231
232    @property
233    def last(self):
234        return self.decode.last
235
236    @last.setter
237    def last(self, value):
238        self.decode.last = value
239
240    @property
241    def progress(self):
242        return self.cur.progress
243
244    @property
245    def prefill_tok_s_mean(self):
246        return self.cur.prefill_tok_s_mean
247
248    @property
249    def batch(self) -> int:
250        return 0
251
252    @property
253    def max_context(self) -> int:
254        v = [e.max_context for e in (self.prefill, self.decode) if getattr(e, "max_context", 0) and e.alive()]
255        return min(v) if v else 0
256
257    @property
258    def unloaded(self) -> bool:
259        return all(getattr(e, "unloaded", False) for e in (self.prefill, self.decode))
260
261    @property
262    def starting(self) -> bool:
263        return not self.alive() and any(getattr(e, "starting", False) for e in (self.prefill, self.decode))
264
265    @property
266    def info(self) -> dict:
267        i = dict(self.decode.info)
268        i["split_serve"] = True
269        i["split_prefill_alive"] = bool(self.prefill.alive())
270        return i
271
272    @info.setter
273    def info(self, value):
274        pass
275
276    def alive(self) -> bool:
277        return bool(self.decode.alive())
278
279    def exit_code(self):
280        return next((c for c in (e.exit_code() for e in (self.decode, self.prefill) if not e.alive()) if c is not None),
281                    None)
282
283    def death_note(self) -> str:
284        return next((e.death_note() for e in (self.decode, self.prefill) if not e.alive()), "")
285
286    def split_view(self) -> dict:
287        """For /metrics: how the two engines are used."""
288        s = dict(self.stats)
289        s.update(prefill_alive=bool(self.prefill.alive()), decode_alive=bool(self.decode.alive()),
290                 min_prompt_tokens=self.min_tokens)
291        return s
292
293    # ---- life cycle
294    def restart(self, tries: int = 3):
295        errors = {}
296        for name, e in (("decode", self.decode), ("prefill", self.prefill)):      # one at a time: the arena fills once
297            if e.alive():
298                continue
299            try:
300                e.restart(tries)
301            except BaseException as x:           # noqa: BLE001
302                errors[name] = x
303        if "decode" in errors:
304            raise errors["decode"]
305        for name, x in errors.items():
306            self.say(f"[strata] the {name} engine of the split did not start ({x}); the other one serves")
307        self.__dict__["held"] = []
308
309    def unload(self):
310        for e in (self.prefill, self.decode):
311            e.unload()
312        self.__dict__["held"] = []
313
314    def close(self):
315        err = None
316        for e in (self.prefill, self.decode):
317            try:
318                e.close()
319            except BaseException as x:           # noqa: BLE001
320                err = err or x
321        shutil.rmtree(self.work_dir, ignore_errors=True)
322        if self.arena_file and self.arena_file.startswith("/dev/shm/strata-split-"):
323            try:
324                os.unlink(self.arena_file)       # RAM until it is gone
325            except OSError:
326                pass
327        if err:
328            raise err
329
330    def heal(self) -> None:
331        """Start a prefill engine that died again, in the background (the decode engine serves meanwhile)."""
332        e = self.prefill
333        now = time.monotonic()
334        if e.alive() or getattr(e, "unloaded", False) or getattr(e, "starting", False) or self.healing or now < self.heal_at:
335            return
336        self.__dict__["heal_at"] = now + HEAL_COOLDOWN_S
337        self.__dict__["healing"] = True
338
339        def run():
340            try:
341                self.say("[strata] split: the prefill engine had stopped; starting it again")
342                e.restart()
343                self.say("[strata] split: the prefill engine is running again")
344            except BaseException as x:           # noqa: BLE001
345                self.say(f"[strata] split: the prefill engine did not start again: {x}")
346            finally:
347                self.__dict__["healing"] = False
348        threading.Thread(target=run, daemon=True).start()
349
350    # ---- the request
351    def wants_handover(self, ids) -> tuple[bool, int]:
352        """(hand the prompt to the prefill engine?, the tokens the decode engine would read itself)."""
353        n = len(ids)
354        if n < 2:
355            return False, 0
356        need = (n - 1) - min(common_prefix(self.held, ids), n - 1)
357        return need >= max(1, self.min_tokens) and self.prefill.alive(), need
358
359    def _wait(self, fn):
360        """Run a blocking engine call on a thread; yields None as a keep-alive while it runs.  -> its result."""
361        box = {}
362
363        def run():
364            try:
365                box["r"] = fn()
366            except BaseException as e:           # noqa: BLE001
367                box["e"] = e
368        th = threading.Thread(target=run, daemon=True)
369        th.start()
370        while th.is_alive():
371            th.join(HEARTBEAT_S)
372            if th.is_alive():
373                yield None
374        if "e" in box:
375            raise box["e"]
376        return box.get("r")
377
378    def _hand_over(self, ids, cancel, rec: dict):
379        """Prefill engine reads the prompt, saves the session; the decode engine restores it.  Yields keep-alives.
380        rec['ok'] is True when the decode engine now holds the prompt's first n-1 tokens."""
381        from serve.server import EngineDied, SessionRefused
382        P, D = self.prefill, self.decode
383        n = len(ids)
384        self.__dict__["seq"] += 1
385        path = os.path.join(self.work_dir, f"handover-{os.getpid()}-{self.seq}.session")
386        rec.update(ok=False)
387        t0 = time.monotonic()
388        self.__dict__["cur"] = P
389        try:
390            try:
391                for _ in P.generate(ids, 0, {}, cancel, prefill_only=True):
392                    yield None
393            except (EngineDied, ValueError) as e:
394                self.say(f"[strata] split: the prefill engine failed ({e}); the decode engine reads the prompt itself")
395                self.heal()
396                return
397            if cancel.is_set():
398                return
399            p_last = dict(P.last or {})
400            rec["prefill_ms"] = (time.monotonic() - t0) * 1000.0
401            rec["p_last"] = p_last
402            try:
403                saved = yield from self._wait(lambda: P.session_file("save", path))
404                self.__dict__["cur"] = D
405                restored = yield from self._wait(lambda: D.session_file("restore", path))
406            except SessionRefused as e:
407                self.say(f"[strata] split: the session file was refused ({e}); the decode engine reads the prompt itself")
408                return
409            except EngineDied as e:
410                if not D.alive():
411                    raise
412                self.say(f"[strata] split: the prefill engine failed while saving ({e}); the decode engine reads the prompt "
413                         "itself")
414                self.heal()
415                return
416            rec.update(save_ms=float(saved["ms"]), restore_ms=float(restored["ms"]), bytes=int(saved["bytes"]),
417                       tokens=int(restored["tokens"]), ok=restored["tokens"] == n - 1)
418            if not rec["ok"]:
419                self.say(f"[strata] split: the decode engine restored {restored['tokens']} tokens, not the {n - 1} the "
420                         "prompt needs; it reads the rest itself")
421                rec["ok"] = restored["tokens"] > 0
422        finally:
423            self.__dict__["cur"] = D
424            try:
425                os.unlink(path)
426            except OSError:
427                pass
428
429    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
430        D = self.decode
431        ids = list(ids)
432        st = self.stats
433        st["requests"] += 1
434        rec: dict = {}
435        use, need = (False, 0) if embeddings is not None else self.wants_handover(ids)
436        if not use:
437            st["short"] += 1
438        if use:
439            if not self.prefill.alive():
440                self.heal()
441            yield from self._hand_over(ids, cancel, rec)
442            if cancel.is_set():
443                self.__dict__["held"] = []
444                return
445            if rec.get("ok"):
446                st["handed_over"] += 1
447                st["bytes"] += rec["bytes"]
448                st["prefill_ms"] += rec["prefill_ms"]
449                st["save_ms"] += rec["save_ms"]
450                st["restore_ms"] += rec["restore_ms"]
451                self.__dict__["held"] = ids[:len(ids) - 1]
452            else:
453                st["fallbacks"] += 1
454        self.__dict__["cur"] = D
455        produced: list[int] = []
456        ok = False
457        try:
458            gen = D.generate(ids, max_new, sampling, cancel, embeddings=embeddings) if embeddings is not None \
459                else D.generate(ids, max_new, sampling, cancel)
460            for t in gen:
461                if t is not None:
462                    produced.append(t)
463                yield t
464            ok = True
465        finally:
466            self.__dict__["held"] = (ids + produced) if ok else []
467            if rec.get("ok") and ok:
468                self._account(ids, rec)
469
470    def _account(self, ids, rec: dict) -> None:
471        """The figures of the engine's last DONE, as the whole request: the prefill engine's read, the file steps and the
472        decode engine's own start are the prompt time; what the prefill engine reused is the cached part."""
473        D = self.decode
474        last = dict(D.last or {})
475        p = rec.get("p_last") or {}
476        total_prompt_ms = rec["prefill_ms"] + rec["save_ms"] + rec["restore_ms"] + float(last.get("prompt_ms") or 0.0)
477        p_read = p.get("prompt_read")
478        if p_read is None:
479            p_read = len(ids) - int(p.get("reused") or 0)
480        last.update(prompt_ms=total_prompt_ms, reused=int(p.get("reused") or 0),
481                    prompt_read=max(0, min(len(ids), int(p_read) + int(last.get("prompt_read") or 0))),
482                    split_prefill_ms=round(rec["prefill_ms"], 1), split_save_ms=round(rec["save_ms"], 1),
483                    split_restore_ms=round(rec["restore_ms"], 1), split_bytes=rec["bytes"])
484        D.last = last
485        self.stats["last"] = {k: last[k] for k in last if k.startswith("split_")}
486        self.say(f"[strata] split: prompt {len(ids)} tokens read on the prefill card in {rec['prefill_ms'] / 1000:.1f} s, "
487                 f"session {rec['bytes'] / 2**20:.0f} MiB saved in {rec['save_ms'] / 1000:.2f} s and restored in "
488                 f"{rec['restore_ms'] / 1000:.2f} s; the decode card makes the answer")