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
27.3 KiB632 linesraw
1"""Data-parallel replicas: N independent engines, each on its own group of cards, behind one server.
2
3A model that fits two cards (IQ3_S on two R9700s) runs better as two 2-card engines than as one 4-card layer split:
4the split runs one pipeline whose stages wait on each other, two replicas run two pipelines.  The server keeps its one
5HTTP front, its one Service and its one set of endpoints; `ReplicaEngine` stands in for the engine and spreads the
6requests over the replicas.
7
8Opt-in, in the run config:
9
10    "replicas": 2                                     the "gpu" list cut into 2 equal groups ([0,1] and [2,3])
11    "replicas": [{"gpus": [0, 1]}, {"gpus": [2, 3]}]  the groups named; an entry may add "env" and "args"
12
13or `serve/server.py --replicas 2`.  Nothing changes without it.
14
15Routing.  Each request goes to the replica with the lowest cost, cost = prompt tokens the replica would have to read
16again (it holds the start of a conversation in its cache) + LOAD_TOKENS for every request already running there.  A
17conversation's next turn therefore goes back to its replica, until that replica is so much busier than another that
18reading the prompt again is cheaper than waiting.  What each replica holds is tracked as hashes of 64-token blocks of
19the prompts and answers it served (the engine itself checks the real prefix, as it always does).
20
21Host RAM.  Every engine keeps its own copy of the experts in RAM (about 47 GiB for Qwen3.8-Flash-Next IQ3_S), so two
22replicas need two copies and four need four.  "replica_shared_arena": true (or STRATA_REPLICA_SHARED_ARENA=1; opt-in)
23backs the experts' arena of all replicas with ONE shared memory object (the engine's --shared-expert-arena, MAP_SHARED):
24the experts are in RAM once, whatever the number of replicas.  On Linux the object is a memfd the server creates
25(os.memfd_create): it is not a file on a mount, so the size of /dev/shm does not limit it; the engines open it as
26/proc/<server pid>/fd/<n>.  On Windows it is a named section (CreateFileMapping) the engines open by name.  Without memfd (an old kernel, a sandbox that refuses it) a file in /dev/shm is used instead.
27The pack hash in the header refuses another model; the first engine to start reads the experts into it and the others
28wait for it and skip the read (a state word in the header: nobody / a pid reading / filled; an engine whose reader died
29takes the read over); the server closes the memfd (or unlinks the file) when it ends - an engine that still maps it
30keeps its pages, the kernel frees them with the last mapping - and a /dev/shm file whose server is gone is removed at
31the next start.  See shared_arena_plan.
32
33CPU cores.  On Linux the replicas get disjoint physical cores (serve/cpu_affinity.py, from PR #1436 by agorevski), so
34the host threads of the engines (the expert workers) do not compete.  "replica_cpus": false turns it off.
35"""
36from __future__ import annotations
37
38import collections
39import copy
40import os
41import sys
42import threading
43import time
44
45BLOCK = 64                          # tokens per hashed block of a prompt
46LOAD_TOKENS = 3000                  # the cost of one request already running on a replica, in prompt tokens
47INDEX_MAX = 262144                  # block hashes kept (about 17M tokens of prompts)
48HEAL_COOLDOWN_S = 60.0              # a replica that died is started again at most this often
49
50
51class ReplicaConfigError(ValueError):
52    pass
53
54
55def gpu_groups(cfg: dict) -> list[list[int]]:
56    """The cards of each replica, from the config's "replicas" (see the module doc); [] when there are none or one."""
57    spec = cfg.get("replicas")
58    if spec is None or spec is False:
59        return []
60    cards = _cards(cfg.get("gpu"))
61    if isinstance(spec, bool) or (not isinstance(spec, (int, list))):
62        raise ReplicaConfigError(f'"replicas" must be a number or a list of {{"gpus": [...]}}, not {spec!r}')
63    if isinstance(spec, int):
64        if spec <= 1:
65            return []
66        if not cards:
67            raise ReplicaConfigError(f'"replicas": {spec} needs the "gpu" list to cut into groups (e.g. "gpu": [0, 1, 2, 3])')
68        if len(cards) % spec:
69            raise ReplicaConfigError(f'"replicas": {spec} does not divide the {len(cards)} cards {cards} evenly: name the '
70                                     f'groups ("replicas": [{{"gpus": [0, 1]}}, ...]) or change the count')
71        n = len(cards) // spec
72        return [cards[i * n:(i + 1) * n] for i in range(spec)]
73    groups = []
74    for e in spec:
75        g = e.get("gpus") if isinstance(e, dict) else e
76        groups.append(_cards(g))
77    if any(not g for g in groups):
78        raise ReplicaConfigError('every replica needs its cards: {"gpus": [0, 1]}')
79    flat = [c for g in groups for c in g]
80    if len(set(flat)) != len(flat):
81        raise ReplicaConfigError(f"a card is in two replicas: {groups}")
82    if len(groups) < 2:
83        return []
84    return groups
85
86
87def _cards(g) -> list[int]:
88    if g is None or g == "":
89        return []
90    items = g if isinstance(g, (list, tuple)) else str(g).split(",")
91    try:
92        return [int(str(x).strip()) for x in items if str(x).strip() != ""]
93    except ValueError:
94        raise ReplicaConfigError(f"cards must be numbers, not {g!r}") from None
95
96
97ARENA_PREFIX = "strata-replicas-"
98_MEMFDS: dict = {}                   # the memfds this server created: path (/proc/<pid>/fd/<n>) -> fd
99ARENA_MIN_RAM = 8 << 30              # a memfd arena: at least this much free RAM to try (the engine reserves the real size)
100ARENA_MIN_FREE = 8 << 30             # /dev/shm must have at least this much free to try (the engine reserves the real size)
101ARENA_INCOMPATIBLE = ("--mmap-experts", "--resident-experts", "--shared-expert-arena", "--resident-budget-gib")
102
103
104def _pid_alive(pid: int) -> bool:
105    try:
106        os.kill(pid, 0)
107    except ProcessLookupError:
108        return False
109    except PermissionError:
110        return True
111    return True
112
113
114def sweep_stale_arenas(shm: str = "/dev/shm", uid: int | None = None) -> list[str]:
115    """Remove the arena files of servers that no longer run (a killed server cannot unlink its own).  A file of a living
116    server, or of another user, is never touched; a mapping an engine still holds stays valid either way."""
117    if uid is None:
118        uid = os.getuid() if hasattr(os, "getuid") else 0
119    gone = []
120    try:
121        names = os.listdir(shm)
122    except OSError:
123        return gone
124    head = f"{ARENA_PREFIX}{uid}-"
125    for n in names:
126        if not (n.startswith(head) and n.endswith(".bin")):
127            continue
128        try:
129            pid = int(n[len(head):-4])
130        except ValueError:
131            continue
132        if _pid_alive(pid):
133            continue
134        try:
135            os.unlink(os.path.join(shm, n))
136            gone.append(n)
137        except OSError:
138            pass
139    return gone
140
141
142def _free(path: str) -> int:
143    try:
144        st = os.statvfs(path)
145        return st.f_bavail * st.f_frsize
146    except OSError:
147        return 0
148
149
150def _mem_available() -> int:
151    try:
152        with open("/proc/meminfo") as f:
153            for line in f:
154                if line.startswith("MemAvailable:"):
155                    return int(line.split()[1]) * 1024
156    except (OSError, ValueError, IndexError):
157        pass
158    return 0
159
160
161def shared_arena_plan(cfg: dict, n_replicas: int, *, shm: str = "/dev/shm", platform: str | None = None,
162                      environ=None, free_bytes=None, use_memfd: bool | None = None) -> tuple[str | None, str]:
163    """(the file for --shared-expert-arena or None, a line for the log).  Opt-in: "replica_shared_arena": true (or
164    STRATA_REPLICA_SHARED_ARENA=1).  Only on Linux (the engine's MAP_SHARED backing), for Qwen's arena (not DeepSeek,
165    not the mapped or budgeted RAM modes, which have no arena), and with room in /dev/shm.  The engine checks the real
166    size and reserves it before it loads (a tmpfs that is too small is an error at start, not a bus error later)."""
167    environ = os.environ if environ is None else environ
168    platform = sys.platform if platform is None else platform
169    want = cfg.get("replica_shared_arena")
170    if want is None:
171        want = str(environ.get("STRATA_REPLICA_SHARED_ARENA", "")).strip().lower() in ("1", "true", "on", "yes")
172    if not want or n_replicas < 2:
173        return None, ""
174    if platform.startswith("win"):
175        # a named pagefile-backed section the engines open by name (src/core/pinned.cu); it lives while any engine holds it
176        name = f"Local{chr(92)}strata-replicas-{os.getpid()}"
177        return f"win:{name}", (f"one shared expert arena for {n_replicas} replicas (a Windows section, {name}): "
178                               "the experts are in RAM once")
179    if not platform.startswith("linux"):
180        return None, "shared expert arena: Linux and Windows only; each replica keeps its own copy of the experts in RAM"
181    args = [str(a) for a in cfg.get("args") or []]
182    if isinstance(cfg.get("replicas"), list):
183        for e in cfg["replicas"]:
184            if isinstance(e, dict):
185                args += [str(a) for a in e.get("args") or []]
186    if cfg.get("arch") == "deepseek41" or any(a in args for a in ARENA_INCOMPATIBLE):
187        return None, "shared expert arena: this model/config has no private expert arena to share; each replica as before"
188    if use_memfd is None:
189        use_memfd = hasattr(os, "memfd_create") and str(cfg.get("replica_shared_arena")).lower() != "devshm"
190    if use_memfd:
191        avail = free_bytes if free_bytes is not None else _mem_available()
192        if avail < ARENA_MIN_RAM:
193            return None, (f"shared expert arena: only {avail / 2**30:.1f} GiB of RAM is free; each replica keeps its own "
194                          "copy of the experts in RAM")
195        try:
196            fd = os.memfd_create("strata-replicas-arena", os.MFD_CLOEXEC)
197        except OSError:
198            fd = -1
199        if fd >= 0:
200            path = f"/proc/{os.getpid()}/fd/{fd}"
201            _MEMFDS[path] = fd
202            warn = ""
203            try:                 # the arena once plus about 7 GB of private RAM per engine (measured); a warning, never a refusal
204                from strata_control import replica_profile as _rp
205                q = _rp.quant_of(cfg)
206                if q:
207                    need = _rp.ARENA_GB[q] + n_replicas * _rp.PER_REPLICA_GB
208                    if avail / 2**30 < need + 4:
209                        warn = (f" WARNING: about {need:.0f} GB are needed for {n_replicas} engines and {avail / 2**30:.0f} GB "
210                                "are free: the last engine may not fit (fewer replicas, or the layer split, is safer)")
211            except Exception:    # noqa: BLE001
212                pass
213            return path, (f"one shared expert arena for {n_replicas} replicas (memory object of the server, not limited by "
214                          f"the size of /dev/shm): the experts are in RAM once.{warn}")
215    if not (os.path.isdir(shm) and os.access(shm, os.W_OK)):
216        return None, f"shared expert arena: {shm} is not usable; each replica keeps its own copy of the experts in RAM"
217    free = free_bytes if free_bytes is not None else _free(shm)
218    if free < ARENA_MIN_FREE:
219        return None, (f"shared expert arena: {shm} has only {free / 2**30:.1f} GiB free (a tmpfs is half the RAM by "
220                      "default); each replica keeps its own copy of the experts in RAM")
221    sweep_stale_arenas(shm)
222    uid = os.getuid() if hasattr(os, "getuid") else 0
223    path = os.path.join(shm, f"{ARENA_PREFIX}{uid}-{os.getpid()}.bin")
224    return path, f"one shared expert arena for {n_replicas} replicas ({path}): the experts are in RAM once"
225
226
227def remove_arena(path: str | None) -> None:
228    """Close the memfd / unlink the arena file (the server's end, or a start that fell back): engines that map it keep
229    their pages."""
230    if not path or path.startswith("win:"):      # (a Windows section goes with its last handle)
231        return
232    fd = _MEMFDS.pop(path, None)
233    if fd is not None:
234        try:
235            os.close(fd)
236        except OSError:
237            pass
238        return
239    try:
240        os.unlink(path)
241    except OSError:
242        pass
243
244
245def _suffixed(path, i: int):
246    if not isinstance(path, str) or not path:
247        return path
248    root, ext = os.path.splitext(path)
249    return f"{root}.r{i}{ext}"
250
251
252def replica_cfg(cfg: dict, i: int, gpus: list[int]) -> dict:
253    """The config of replica i: its own cards, log and learned-profile file; the entry's "env" and "args" added."""
254    c = copy.deepcopy(cfg)
255    spec = cfg.get("replicas")
256    entry = spec[i] if isinstance(spec, list) and isinstance(spec[i], dict) else {}
257    c.pop("replicas", None)
258    c["gpu"] = gpus if len(gpus) > 1 else gpus[0]
259    c.pop("hip_ordinal", None)                 # a one-card config's Windows ordinal: not for a group
260    c["log"] = _suffixed(cfg.get("log"), i)
261    if cfg.get("expert_profile_save"):
262        c["expert_profile_save"] = _suffixed(cfg["expert_profile_save"], i)
263    if entry.get("env"):
264        c["env"] = {**(c.get("env") or {}), **{str(k): str(v) for k, v in entry["env"].items()}}
265    if entry.get("args"):
266        c["args"] = list(c["args"]) + [str(x) for x in entry["args"]]
267    return c
268
269
270def cpu_sets(n: int, enabled: bool = True):
271    """n disjoint sets of CPUs (whole physical cores, SMT siblings together), or None (off, not Linux, or the topology
272    cannot be read: the engines then share the cores as they would without replicas)."""
273    if not enabled or n < 2 or not hasattr(os, "sched_getaffinity"):
274        return None
275    try:
276        from serve.cpu_affinity import partition_cpu_sets
277        return partition_cpu_sets(n, set(os.sched_getaffinity(0)))
278    except (ValueError, OSError, ImportError) as e:
279        print(f"[strata] replicas: no separate CPU cores ({e})", flush=True)
280        return None
281
282
283class Router:
284    """Which replica holds the start of a prompt: chained hashes of its 64-token blocks, each with the set of replicas
285    that served it (a bit mask)."""
286
287    def __init__(self, n: int, cap: int = INDEX_MAX):
288        self.n, self.cap = n, cap
289        self.blocks: collections.OrderedDict[int, int] = collections.OrderedDict()
290        self.lock = threading.Lock()
291
292    @staticmethod
293    def chain(ids) -> list[int]:
294        out, h = [], 0
295        for k in range(len(ids) // BLOCK):
296            h = hash((h, tuple(ids[k * BLOCK:(k + 1) * BLOCK])))
297            out.append(h)
298        return out
299
300    def matched(self, ids) -> list[int]:
301        """Per replica: how many leading tokens of `ids` it holds (a multiple of BLOCK)."""
302        got = [0] * self.n
303        alive = (1 << self.n) - 1
304        with self.lock:
305            for k, h in enumerate(self.chain(ids)):
306                m = self.blocks.get(h, 0) & alive
307                if not m:
308                    break
309                alive = m
310                for r in range(self.n):
311                    if m >> r & 1:
312                        got[r] = (k + 1) * BLOCK
313        return got
314
315    def note(self, r: int, ids) -> None:
316        with self.lock:
317            for h in self.chain(ids):
318                self.blocks[h] = self.blocks.pop(h, 0) | (1 << r)
319            while len(self.blocks) > self.cap:
320                self.blocks.popitem(last=False)
321
322    def forget(self, r: int) -> None:
323        """Replica r lost its cache (it restarted)."""
324        with self.lock:
325            bit = ~(1 << r)
326            for h in [h for h, m in self.blocks.items() if m >> r & 1]:
327                m = self.blocks[h] & bit
328                if m:
329                    self.blocks[h] = m
330                else:
331                    del self.blocks[h]
332
333
334class ReplicaEngine:
335    """Stands in for one engine (the interface Service uses), over several."""
336
337    NOT_HERE = {"session_file", "vram", "ctl", "slot_cv"}       # not offered: one conversation file / VRAM resize / control line
338    PROPAGATE = {"silence_s", "gpu_busy"}
339
340    def __init__(self, engines: list, load_tokens: int = LOAD_TOKENS):
341        if len(engines) < 2:
342            raise ValueError("ReplicaEngine needs two or more engines")
343        d = self.__dict__
344        d["engines"] = list(engines)
345        d["router"] = Router(len(engines))
346        d["load_tokens"] = load_tokens
347        d["inflight"] = [0] * len(engines)
348        d["run_locks"] = [threading.Lock() for _ in engines]    # an engine without batch slots: one request at a time
349        d["lock"] = threading.Lock()
350        d["tl"] = threading.local()
351        d["healing"] = {}
352        d["heal_at"] = [0.0] * len(engines)
353        d["routed"] = [0] * len(engines)
354        d["gen_seen"] = [getattr(e, "gen", 0) for e in engines]
355
356    # ---- attribute plumbing
357    @property
358    def current(self):
359        return getattr(self.tl, "cur", None) or self.engines[0]
360
361    def __getattr__(self, name):
362        if name in self.NOT_HERE or name.startswith("__"):
363            raise AttributeError(name)
364        return getattr(self.current, name)
365
366    def __setattr__(self, name, value):
367        if name in self.PROPAGATE:
368            for e in self.engines:
369                setattr(e, name, value)
370        else:
371            self.__dict__[name] = value
372
373    @property
374    def last(self):
375        """The DONE figures of the calling thread's own request (#2892).  An unbatched engine has one shared `last`
376        that the next request overwrites the moment the replica's lock is free, so generate() copies the figures of
377        this caller's DONE while it still owns the replica; until the thread has had one, the engine's own object."""
378        tl = self.tl
379        if not hasattr(tl, "last"):
380            tl.last = self.current.last
381        return tl.last
382
383    @last.setter
384    def last(self, value):
385        self.current.last = value
386        self.tl.last = value
387
388    @property
389    def batch(self) -> int:
390        """Parallel slots, in total: the Service lets this many requests run at once (it holds no FIFO).  An engine
391        without slots counts one."""
392        return sum(max(1, int(getattr(e, "batch", 0) or 0)) for e in self.engines)
393
394    @property
395    def waiting(self) -> int:
396        return sum(int(getattr(e, "waiting", 0) or 0) for e in self.engines)
397
398    @property
399    def max_context(self) -> int:
400        v = [e.max_context for e in self.engines if getattr(e, "max_context", 0) and e.alive()]
401        return min(v) if v else 0
402
403    @property
404    def known_ctx(self) -> int:
405        v = [getattr(e, "known_ctx", 0) for e in self.engines]
406        return min(x for x in v if x) if any(v) else 0
407
408    @property
409    def unloaded(self) -> bool:
410        return all(getattr(e, "unloaded", False) for e in self.engines)
411
412    @property
413    def starting(self) -> bool:
414        return not self.alive() and any(getattr(e, "starting", False) for e in self.engines)
415
416    @property
417    def info(self) -> dict:
418        i = dict(self.engines[0].info)
419        i["replicas"] = len(self.engines)
420        i["replicas_alive"] = sum(1 for e in self.engines if e.alive())
421        return i
422
423    @info.setter
424    def info(self, value):
425        pass
426
427    @property
428    def spawn(self):
429        return self.engines[0].spawn
430
431    @property
432    def log_path(self):
433        return self.engines[0].log_path
434
435    @property
436    def progress(self):
437        c = getattr(self.tl, "cur", None)
438        if c is not None:
439            return c.progress
440        return next((e.progress for e in self.engines if getattr(e, "progress", None)), None)
441
442    @property
443    def prefill_tok_s_mean(self):
444        c = getattr(self.tl, "cur", None)
445        if c is not None:
446            return c.prefill_tok_s_mean
447        return next((e.prefill_tok_s_mean for e in self.engines if getattr(e, "prefill_tok_s_mean", None)), None)
448
449    def alive(self) -> bool:
450        return any(e.alive() for e in self.engines)
451
452    def exit_code(self):
453        return next((c for c in (e.exit_code() for e in self.engines if not e.alive()) if c is not None), None)
454
455    def death_note(self) -> str:
456        return next((e.death_note() for e in self.engines if not e.alive()), "")
457
458    def slots_view(self) -> list[dict]:
459        out, base = [], 0
460        for k, e in enumerate(self.engines):
461            n = int(getattr(e, "batch", 0) or 0)
462            view = e.slots_view() if n and hasattr(e, "slots_view") else \
463                [{"slot": 0, "state": "busy" if self.inflight[k] else "idle", "held_tokens": 0}]
464            for s in view:
465                out.append({**s, "slot": base + s["slot"], "replica": k})
466            base += max(1, n)
467        return out
468
469    def replica_view(self) -> list[dict]:
470        """For /metrics: each replica's state, requests running, and requests routed to it so far."""
471        return [{"replica": k, "alive": e.alive(), "running": self.inflight[k], "routed": self.routed[k],
472                 "batch": int(getattr(e, "batch", 0) or 0)} for k, e in enumerate(self.engines)]
473
474    # ---- life cycle
475    def restart(self, tries: int = 3):
476        dead = [k for k, e in enumerate(self.engines) if not e.alive()]
477        errors: dict[int, BaseException] = {}
478
479        def one(k):
480            try:
481                self.engines[k].restart(tries)
482                self.router.forget(k)
483            except BaseException as e:           # noqa: BLE001
484                errors[k] = e
485        ts = [threading.Thread(target=one, args=(k,), daemon=True) for k in dead]
486        for t in ts:
487            t.start()
488        for t in ts:
489            t.join()
490        if errors and not self.alive():
491            raise next(iter(errors.values()))
492        for k, e in errors.items():
493            print(f"[strata] replica {k} did not start ({e}); the others serve", flush=True)
494
495    def unload(self):
496        for e in self.engines:
497            e.unload()
498        for k in range(len(self.engines)):
499            self.router.forget(k)
500
501    def close(self):
502        err = None
503        for e in self.engines:
504            try:
505                e.close()
506            except BaseException as x:           # noqa: BLE001
507                err = err or x
508        remove_arena(self.__dict__.get("arena_file"))   # (an engine that still maps it keeps its pages)
509        if err:
510            raise err
511
512    # ---- routing
513    def route(self, ids) -> int:
514        """The replica for this prompt (and its running count raised): lowest cost among the living ones."""
515        got = self.router.matched(ids)
516        with self.lock:
517            alive = [k for k, e in enumerate(self.engines) if e.alive()]
518            if not alive:
519                return -1
520            cost = {k: (len(ids) - got[k]) + self.load_tokens * self.inflight[k] for k in alive}
521            # the least loaded wins a tie of cost (equal cards, nothing cached): spread, do not pile on replica 0
522            k = min(alive, key=lambda k: (cost[k], self.inflight[k], self.routed[k]))
523            self.inflight[k] += 1
524            self.routed[k] += 1
525        if len(alive) < len(self.engines):
526            self.heal()
527        return k
528
529    def heal(self) -> None:
530        """Start a replica that died again, in the background (the others keep serving)."""
531        now = time.monotonic()
532        for k, e in enumerate(self.engines):
533            if e.alive() or getattr(e, "unloaded", False) or getattr(e, "starting", False) or self.healing.get(k):
534                continue
535            if now < self.heal_at[k]:
536                continue
537            self.heal_at[k] = now + HEAL_COOLDOWN_S
538            self.healing[k] = True
539
540            def run(k=k):
541                try:
542                    print(f"[strata] replica {k} had stopped; starting it again", flush=True)
543                    self.engines[k].restart()
544                    self.router.forget(k)
545                    print(f"[strata] replica {k} is running again", flush=True)
546                except BaseException as x:       # noqa: BLE001
547                    print(f"[strata] replica {k} did not start again: {x}", flush=True)
548                finally:
549                    self.healing[k] = False
550            threading.Thread(target=run, daemon=True).start()
551
552    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
553        # imported here: serve.server imports this module
554        from serve.server import EngineDied, EngineNonFinite
555        k = self.route(ids)
556        if k < 0:
557            raise EngineDied("no replica is running; this request was not sent")
558        e = self.engines[k]
559        self.tl.cur = e
560        _ = self.last                                         # the caller's figures exist before this request (#2892)
561        produced: list[int] = []
562        held = False
563        gen = None
564        native_before = None
565        nonfinite = False
566        try:
567            selected = getattr(cancel, "_strata_replica_selected", None)
568            if selected is not None:
569                selected(k)
570            self.router.note(k, ids)
571            if not int(getattr(e, "batch", 0) or 0):          # no slots: this replica takes one request at a time
572                lock = self.run_locks[k]
573                while not lock.acquire(timeout=0.25):
574                    if cancel is not None and cancel.is_set():
575                        return
576                held = True
577            native_before = e.last
578            if embeddings is not None:
579                gen = e.generate(ids, max_new, sampling, cancel, embeddings=embeddings)
580            else:
581                gen = e.generate(ids, max_new, sampling, cancel)
582            for t in gen:
583                if t is not None:
584                    produced.append(t)
585                yield t
586        except EngineNonFinite:
587            nonfinite = True
588            raise
589        finally:
590            # #2892: the replica's pipe belongs to this request until its native exchange is over.  The child
591            # generator sends STOP and reads to its DONE when it is closed; that has to happen HERE, before the lock is
592            # given back - left to the garbage collector it ran after the next request had sent its GEN, and the two
593            # read each other's tokens and DONE.  A close that fails (the engine never answered its STOP) ends the
594            # replica: it is not handed on (heal() starts it again), and the error is not lost.
595            try:
596                if gen is not None:
597                    try:
598                        gen.close()
599                    except BaseException:                     # noqa: BLE001 - the pipe cannot be trusted any more
600                        self.quarantine(k)
601                        raise
602            finally:
603                try:
604                    # the figures of the DONE this caller's request read, copied while it still owns the replica; with
605                    # no new DONE the caller's earlier object stays, so Service does not record an old result as new
606                    if gen is not None and e.last is not native_before:
607                        self.tl.last = dict(e.last)
608                finally:
609                    if held:
610                        self.run_locks[k].release()
611                    with self.lock:
612                        self.inflight[k] -= 1
613                    if nonfinite:                       # #879: the engine dropped every cached conversation
614                        self.router.forget(k)
615                    elif produced:
616                        self.router.note(k, list(ids) + produced)
617
618    def quarantine(self, k: int) -> None:
619        """A replica whose pipe could not be drained is out of the routing until it has been started again: its process
620        is ended (nothing it still prints can reach a later request) and heal() restarts it."""
621        e = self.engines[k]
622        try:
623            e.ended = True
624        except AttributeError:
625            pass
626        proc = getattr(e, "proc", None)
627        try:
628            if proc is not None and proc.poll() is None:
629                proc.kill()
630        except (OSError, AttributeError, ValueError):
631            pass
632        self.router.forget(k)