Data-parallel replicas (opt-in): N engines on their own card groups behind one server, requests spread least-loaded and a conversation routed back to its replica; replicas in the config, --replicas in the server and setup

This commit is contained in:
Niko1221 committed 2026-10-09 03:15:34 +02:00
1 parent 7d771bb028
commit 8d276c1997
4 files changed
+726 -6

No files matched your search

+415
View File
@@ -0,0 +1,415 @@
"""Data-parallel replicas: N independent engines, each on its own group of cards, behind one server.
A model that fits two cards (IQ3_S on two R9700s) runs better as two 2-card engines than as one 4-card layer split:
the split runs one pipeline whose stages wait on each other, two replicas run two pipelines. The server keeps its one
HTTP front, its one Service and its one set of endpoints; `ReplicaEngine` stands in for the engine and spreads the
requests over the replicas.
Opt-in, in the run config:
"replicas": 2 the "gpu" list cut into 2 equal groups ([0,1] and [2,3])
"replicas": [{"gpus": [0, 1]}, {"gpus": [2, 3]}] the groups named; an entry may add "env" and "args"
or `serve/server.py --replicas 2`. Nothing changes without it.
Routing. Each request goes to the replica with the lowest cost, cost = prompt tokens the replica would have to read
again (it holds the start of a conversation in its cache) + LOAD_TOKENS for every request already running there. A
conversation's next turn therefore goes back to its replica, until that replica is so much busier than another that
reading the prompt again is cheaper than waiting. What each replica holds is tracked as hashes of 64-token blocks of
the prompts and answers it served (the engine itself checks the real prefix, as it always does).
CPU cores. On Linux the replicas get disjoint physical cores (serve/cpu_affinity.py, from PR #1436 by agorevski), so
the host threads of the engines (the expert workers) do not compete. "replica_cpus": false turns it off.
"""
from __future__ import annotations
import collections
import copy
import os
import threading
import time
BLOCK = 64 # tokens per hashed block of a prompt
LOAD_TOKENS = 3000 # the cost of one request already running on a replica, in prompt tokens
INDEX_MAX = 262144 # block hashes kept (about 17M tokens of prompts)
HEAL_COOLDOWN_S = 60.0 # a replica that died is started again at most this often
class ReplicaConfigError(ValueError):
pass
def gpu_groups(cfg: dict) -> list[list[int]]:
"""The cards of each replica, from the config's "replicas" (see the module doc); [] when there are none or one."""
spec = cfg.get("replicas")
if spec is None or spec is False:
return []
cards = _cards(cfg.get("gpu"))
if isinstance(spec, bool) or (not isinstance(spec, (int, list))):
raise ReplicaConfigError(f'"replicas" must be a number or a list of {{"gpus": [...]}}, not {spec!r}')
if isinstance(spec, int):
if spec <= 1:
return []
if not cards:
raise ReplicaConfigError(f'"replicas": {spec} needs the "gpu" list to cut into groups (e.g. "gpu": [0, 1, 2, 3])')
if len(cards) % spec:
raise ReplicaConfigError(f'"replicas": {spec} does not divide the {len(cards)} cards {cards} evenly: name the '
f'groups ("replicas": [{{"gpus": [0, 1]}}, ...]) or change the count')
n = len(cards) // spec
return [cards[i * n:(i + 1) * n] for i in range(spec)]
groups = []
for e in spec:
g = e.get("gpus") if isinstance(e, dict) else e
groups.append(_cards(g))
if any(not g for g in groups):
raise ReplicaConfigError('every replica needs its cards: {"gpus": [0, 1]}')
flat = [c for g in groups for c in g]
if len(set(flat)) != len(flat):
raise ReplicaConfigError(f"a card is in two replicas: {groups}")
if len(groups) < 2:
return []
return groups
def _cards(g) -> list[int]:
if g is None or g == "":
return []
items = g if isinstance(g, (list, tuple)) else str(g).split(",")
try:
return [int(str(x).strip()) for x in items if str(x).strip() != ""]
except ValueError:
raise ReplicaConfigError(f"cards must be numbers, not {g!r}") from None
def _suffixed(path, i: int):
if not isinstance(path, str) or not path:
return path
root, ext = os.path.splitext(path)
return f"{root}.r{i}{ext}"
def replica_cfg(cfg: dict, i: int, gpus: list[int]) -> dict:
"""The config of replica i: its own cards, log and learned-profile file; the entry's "env" and "args" added."""
c = copy.deepcopy(cfg)
spec = cfg.get("replicas")
entry = spec[i] if isinstance(spec, list) and isinstance(spec[i], dict) else {}
c.pop("replicas", None)
c["gpu"] = gpus if len(gpus) > 1 else gpus[0]
c.pop("hip_ordinal", None) # a one-card config's Windows ordinal: not for a group
c["log"] = _suffixed(cfg.get("log"), i)
if cfg.get("expert_profile_save"):
c["expert_profile_save"] = _suffixed(cfg["expert_profile_save"], i)
if entry.get("env"):
c["env"] = {**(c.get("env") or {}), **{str(k): str(v) for k, v in entry["env"].items()}}
if entry.get("args"):
c["args"] = list(c["args"]) + [str(x) for x in entry["args"]]
return c
def cpu_sets(n: int, enabled: bool = True):
"""n disjoint sets of CPUs (whole physical cores, SMT siblings together), or None (off, not Linux, or the topology
cannot be read: the engines then share the cores as they would without replicas)."""
if not enabled or n < 2 or not hasattr(os, "sched_getaffinity"):
return None
try:
from serve.cpu_affinity import partition_cpu_sets
return partition_cpu_sets(n, set(os.sched_getaffinity(0)))
except (ValueError, OSError, ImportError) as e:
print(f"[strata] replicas: no separate CPU cores ({e})", flush=True)
return None
class Router:
"""Which replica holds the start of a prompt: chained hashes of its 64-token blocks, each with the set of replicas
that served it (a bit mask)."""
def __init__(self, n: int, cap: int = INDEX_MAX):
self.n, self.cap = n, cap
self.blocks: collections.OrderedDict[int, int] = collections.OrderedDict()
self.lock = threading.Lock()
@staticmethod
def chain(ids) -> list[int]:
out, h = [], 0
for k in range(len(ids) // BLOCK):
h = hash((h, tuple(ids[k * BLOCK:(k + 1) * BLOCK])))
out.append(h)
return out
def matched(self, ids) -> list[int]:
"""Per replica: how many leading tokens of `ids` it holds (a multiple of BLOCK)."""
got = [0] * self.n
alive = (1 << self.n) - 1
with self.lock:
for k, h in enumerate(self.chain(ids)):
m = self.blocks.get(h, 0) & alive
if not m:
break
alive = m
for r in range(self.n):
if m >> r & 1:
got[r] = (k + 1) * BLOCK
return got
def note(self, r: int, ids) -> None:
with self.lock:
for h in self.chain(ids):
self.blocks[h] = self.blocks.pop(h, 0) | (1 << r)
while len(self.blocks) > self.cap:
self.blocks.popitem(last=False)
def forget(self, r: int) -> None:
"""Replica r lost its cache (it restarted)."""
with self.lock:
bit = ~(1 << r)
for h in [h for h, m in self.blocks.items() if m >> r & 1]:
m = self.blocks[h] & bit
if m:
self.blocks[h] = m
else:
del self.blocks[h]
class ReplicaEngine:
"""Stands in for one engine (the interface Service uses), over several."""
NOT_HERE = {"session_file", "vram", "ctl", "slot_cv"} # not offered: one conversation file / VRAM resize / control line
PROPAGATE = {"silence_s", "gpu_busy"}
def __init__(self, engines: list, load_tokens: int = LOAD_TOKENS):
if len(engines) < 2:
raise ValueError("ReplicaEngine needs two or more engines")
d = self.__dict__
d["engines"] = list(engines)
d["router"] = Router(len(engines))
d["load_tokens"] = load_tokens
d["inflight"] = [0] * len(engines)
d["run_locks"] = [threading.Lock() for _ in engines] # an engine without batch slots: one request at a time
d["lock"] = threading.Lock()
d["tl"] = threading.local()
d["healing"] = {}
d["heal_at"] = [0.0] * len(engines)
d["routed"] = [0] * len(engines)
d["gen_seen"] = [getattr(e, "gen", 0) for e in engines]
# ---- attribute plumbing
@property
def current(self):
return getattr(self.tl, "cur", None) or self.engines[0]
def __getattr__(self, name):
if name in self.NOT_HERE or name.startswith("__"):
raise AttributeError(name)
return getattr(self.current, name)
def __setattr__(self, name, value):
if name in self.PROPAGATE:
for e in self.engines:
setattr(e, name, value)
else:
self.__dict__[name] = value
@property
def last(self):
return self.current.last
@last.setter
def last(self, value):
self.current.last = value
@property
def batch(self) -> int:
"""Parallel slots, in total: the Service lets this many requests run at once (it holds no FIFO). An engine
without slots counts one."""
return sum(max(1, int(getattr(e, "batch", 0) or 0)) for e in self.engines)
@property
def waiting(self) -> int:
return sum(int(getattr(e, "waiting", 0) or 0) for e in self.engines)
@property
def max_context(self) -> int:
v = [e.max_context for e in self.engines if getattr(e, "max_context", 0) and e.alive()]
return min(v) if v else 0
@property
def known_ctx(self) -> int:
v = [getattr(e, "known_ctx", 0) for e in self.engines]
return min(x for x in v if x) if any(v) else 0
@property
def unloaded(self) -> bool:
return all(getattr(e, "unloaded", False) for e in self.engines)
@property
def starting(self) -> bool:
return not self.alive() and any(getattr(e, "starting", False) for e in self.engines)
@property
def info(self) -> dict:
i = dict(self.engines[0].info)
i["replicas"] = len(self.engines)
i["replicas_alive"] = sum(1 for e in self.engines if e.alive())
return i
@info.setter
def info(self, value):
pass
@property
def spawn(self):
return self.engines[0].spawn
@property
def log_path(self):
return self.engines[0].log_path
@property
def progress(self):
c = getattr(self.tl, "cur", None)
if c is not None:
return c.progress
return next((e.progress for e in self.engines if getattr(e, "progress", None)), None)
@property
def prefill_tok_s_mean(self):
c = getattr(self.tl, "cur", None)
if c is not None:
return c.prefill_tok_s_mean
return next((e.prefill_tok_s_mean for e in self.engines if getattr(e, "prefill_tok_s_mean", None)), None)
def alive(self) -> bool:
return any(e.alive() for e in self.engines)
def exit_code(self):
return next((c for c in (e.exit_code() for e in self.engines if not e.alive()) if c is not None), None)
def death_note(self) -> str:
return next((e.death_note() for e in self.engines if not e.alive()), "")
def slots_view(self) -> list[dict]:
out, base = [], 0
for k, e in enumerate(self.engines):
n = int(getattr(e, "batch", 0) or 0)
view = e.slots_view() if n and hasattr(e, "slots_view") else \
[{"slot": 0, "state": "busy" if self.inflight[k] else "idle", "held_tokens": 0}]
for s in view:
out.append({**s, "slot": base + s["slot"], "replica": k})
base += max(1, n)
return out
def replica_view(self) -> list[dict]:
"""For /metrics: each replica's state, requests running, and requests routed to it so far."""
return [{"replica": k, "alive": e.alive(), "running": self.inflight[k], "routed": self.routed[k],
"batch": int(getattr(e, "batch", 0) or 0)} for k, e in enumerate(self.engines)]
# ---- life cycle
def restart(self, tries: int = 3):
dead = [k for k, e in enumerate(self.engines) if not e.alive()]
errors: dict[int, BaseException] = {}
def one(k):
try:
self.engines[k].restart(tries)
self.router.forget(k)
except BaseException as e: # noqa: BLE001
errors[k] = e
ts = [threading.Thread(target=one, args=(k,), daemon=True) for k in dead]
for t in ts:
t.start()
for t in ts:
t.join()
if errors and not self.alive():
raise next(iter(errors.values()))
for k, e in errors.items():
print(f"[strata] replica {k} did not start ({e}); the others serve", flush=True)
def unload(self):
for e in self.engines:
e.unload()
for k in range(len(self.engines)):
self.router.forget(k)
def close(self):
err = None
for e in self.engines:
try:
e.close()
except BaseException as x: # noqa: BLE001
err = err or x
if err:
raise err
# ---- routing
def route(self, ids) -> int:
"""The replica for this prompt (and its running count raised): lowest cost among the living ones."""
got = self.router.matched(ids)
with self.lock:
alive = [k for k, e in enumerate(self.engines) if e.alive()]
if not alive:
return -1
cost = {k: (len(ids) - got[k]) + self.load_tokens * self.inflight[k] for k in alive}
# the least loaded wins a tie of cost (equal cards, nothing cached): spread, do not pile on replica 0
k = min(alive, key=lambda k: (cost[k], self.inflight[k], self.routed[k]))
self.inflight[k] += 1
self.routed[k] += 1
if len(alive) < len(self.engines):
self.heal()
return k
def heal(self) -> None:
"""Start a replica that died again, in the background (the others keep serving)."""
now = time.monotonic()
for k, e in enumerate(self.engines):
if e.alive() or getattr(e, "unloaded", False) or getattr(e, "starting", False) or self.healing.get(k):
continue
if now < self.heal_at[k]:
continue
self.heal_at[k] = now + HEAL_COOLDOWN_S
self.healing[k] = True
def run(k=k):
try:
print(f"[strata] replica {k} had stopped; starting it again", flush=True)
self.engines[k].restart()
self.router.forget(k)
print(f"[strata] replica {k} is running again", flush=True)
except BaseException as x: # noqa: BLE001
print(f"[strata] replica {k} did not start again: {x}", flush=True)
finally:
self.healing[k] = False
threading.Thread(target=run, daemon=True).start()
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
# imported here: serve.server imports this module
from serve.server import EngineDied
k = self.route(ids)
if k < 0:
raise EngineDied("no replica is running; this request was not sent")
e = self.engines[k]
self.tl.cur = e
produced: list[int] = []
held = False
try:
self.router.note(k, ids)
if not int(getattr(e, "batch", 0) or 0): # no slots: this replica takes one request at a time
lock = self.run_locks[k]
while not lock.acquire(timeout=0.25):
if cancel is not None and cancel.is_set():
return
held = True
if embeddings is not None:
gen = e.generate(ids, max_new, sampling, cancel, embeddings=embeddings)
else:
gen = e.generate(ids, max_new, sampling, cancel)
for t in gen:
if t is not None:
produced.append(t)
yield t
finally:
if held:
self.run_locks[k].release()
with self.lock:
self.inflight[k] -= 1
if produced:
self.router.note(k, list(ids) + produced)
+71 -6
View File
@@ -601,8 +601,8 @@ class StrataEngine:
tl.last = value
def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None,
env: dict | None = None, lazy: bool = False):
self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27)
env: dict | None = None, lazy: bool = False, cpus: list[int] | None = None):
self.spawn = (exe, list(args), cwd, log, env, False, cpus) # to start it again after it died (issue #27)
paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")}
self.model_path = paths.get("--native") or paths.get("--pack", "pack/full")
self.log_path = log
@@ -644,8 +644,11 @@ class StrataEngine:
except OSError:
pass
self.max_context = 0 # before the new process is visible: never its predecessor's
pin = {}
if cpus and hasattr(os, "sched_setaffinity"): # replicas: this engine's own physical cores (serve/replicas.py)
pin["preexec_fn"] = lambda: os.sched_setaffinity(0, cpus)
self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env)
stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env, **pin)
contain(self.proc) # ends with the server, however it ends (Windows)
# the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream
# stays for _pump (one reader at a time)
@@ -3095,6 +3098,8 @@ class Service:
waiting=int(getattr(self.engine, "waiting", 0) or 0))
if running and state == "idle":
live["state"] = "generating"
if hasattr(self.engine, "replica_view"): # opt-in replicas: each one's state and requests routed to it
live["replicas"] = self.engine.replica_view()
engine = {"model": self.model, "max_context": self.reported_ctx(), "images": self.vision is not None,
**dict(getattr(self.engine, "info", {}) or {})}
tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}}
@@ -5608,6 +5613,49 @@ def sampling_defaults_from_config(cfg: dict) -> dict:
return out
def start_replicas(cfg: dict, groups: list[list[int]], exe: str, effort_end: list[str], lazy: bool):
"""Opt-in data-parallel replicas (serve/replicas.py): one StrataEngine per card group, each with its own cards, log
and CPU cores, started together; the ReplicaEngine in front spreads the requests."""
from serve import replicas as rp
n = len(groups)
cpus = rp.cpu_sets(n, cfg.get("replica_cpus") is not False)
print(f"[strata] {n} replicas on the cards {' | '.join(','.join(map(str, g)) for g in groups)}"
f"{' (own CPU cores each)' if cpus else ''}: requests go to the least busy one, a conversation back to its own",
flush=True)
engines: list = [None] * n
errors: list = []
def one(i: int):
rc = rp.replica_cfg(cfg, i, groups[i])
try:
engines[i] = StrataEngine(exe, engine_args(rc) + effort_end, cwd=rc.get("cwd"), log=rc.get("log"),
env=child_env(rc), lazy=lazy, cpus=cpus[i] if cpus else None)
except BaseException as e: # noqa: BLE001
errors.append((i, e))
rc0 = rp.replica_cfg(cfg, 0, groups[0])
warn_budget_over_ram(engine_args(rc0) if "args" in rc0 else [])
if os.environ.get("STRATA_REPLICA_START", "") == "serial":
for i in range(n):
one(i)
else:
ts = [threading.Thread(target=one, args=(i,)) for i in range(n)]
for t in ts:
t.start()
for t in ts:
t.join()
if errors:
for e in engines:
if e is not None:
try:
e.close()
except Exception: # noqa: BLE001
pass
i, e = errors[0]
raise SystemExit(f"[strata] replica {i} did not start: {e}")
load = int(cfg.get("replica_load_tokens") or rp.LOAD_TOKENS)
return rp.ReplicaEngine(engines, load_tokens=load)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--engine", choices=["mock", "strata"], default="mock")
@@ -5650,8 +5698,14 @@ def main() -> int:
ap.add_argument("--slot-save-path", default=None, metavar="DIR",
help="enable POST /slots/0?action=save|restore {\"filename\": NAME} (llama-server's API): the "
"conversation the engine holds, to or from DIR/NAME (also \"slot_save_path\" in the config)")
ap.add_argument("--replicas", type=int, default=None, metavar="N",
help="data-parallel replicas (opt-in): cut the \"gpu\" list into N equal groups and run one engine on "
"each, requests spread over them (also \"replicas\" in the config: a number, or "
"[{\"gpus\": [0, 1]}, {\"gpus\": [2, 3]}])")
a = ap.parse_args()
cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {} # Notepad adds a BOM
if a.replicas is not None:
cfg["replicas"] = a.replicas
if a.gpu is not None:
cfg["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu
a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can
@@ -5717,12 +5771,20 @@ def main() -> int:
effort_end = effort_end_args(cfg, exe, tok) # #458
except ValueError as e:
raise SystemExit(f"[strata] config {e}")
engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"),
env=env, lazy=lazy)
from serve import replicas as rp
try:
groups = rp.gpu_groups(cfg)
except rp.ReplicaConfigError as e:
raise SystemExit(f"[strata] config {e}")
if groups:
engine = start_replicas(cfg, groups, exe, effort_end or [], lazy)
else:
engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"),
env=env, lazy=lazy)
engine.silence_s = silence # an attribute of its own: restart() keeps it
warn_tight_ram(engine.info.get("arena_mib"))
note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1],
linux_desktop())
linux_desktop()) if not groups else None
if note: # #560 #516: before --open starts a browser on that card
print(note, flush=True)
else:
@@ -5821,6 +5883,9 @@ def main() -> int:
svc.reasoning_loop_recovery = recovery
svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)
svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)
if a.engine == "strata" and groups: # replicas: every card of every group
svc.gpu_indices = [c for g in groups for c in g]
svc.gpu_index = svc.gpu_indices[0]
svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301)
if a.config:
svc.config_path = a.config # #564: the web page's Settings view
+222
View File
@@ -0,0 +1,222 @@
"""Data-parallel replicas (serve/replicas.py): the config, the router, and the real Service over HTTP with two fake
engines (the fake of test_parallel.py) behind a ReplicaEngine."""
import json
import sys
import tempfile
import threading
import unittest
import urllib.request
from pathlib import Path
from unittest import mock
from serve.frontend import ChatTemplate
from serve.replicas import BLOCK, ReplicaConfigError, ReplicaEngine, Router, cpu_sets, gpu_groups, replica_cfg
from serve.server import ByteTokenizer, Service, StrataEngine, serve
from serve.test_parallel import FAKE_BATCH
class Config(unittest.TestCase):
def test_a_number_cuts_the_gpu_list(self):
self.assertEqual(gpu_groups({"gpu": [0, 1, 2, 3], "replicas": 2}), [[0, 1], [2, 3]])
self.assertEqual(gpu_groups({"gpu": "0,1,2,3", "replicas": 4}), [[0], [1], [2], [3]])
self.assertEqual(gpu_groups({"gpu": [0, 1], "replicas": 1}), [])
self.assertEqual(gpu_groups({"gpu": [0, 1]}), [])
def test_named_groups(self):
self.assertEqual(gpu_groups({"replicas": [{"gpus": [0, 1]}, {"gpus": [2]}]}), [[0, 1], [2]])
self.assertEqual(gpu_groups({"replicas": [{"gpus": [0, 1]}]}), [])
def test_mistakes_are_said(self):
for cfg in ({"gpu": [0, 1, 2], "replicas": 2}, {"replicas": 2}, {"replicas": "2"},
{"replicas": [{"gpus": [0, 1]}, {"gpus": [1, 2]}]}, {"replicas": [{"gpus": []}, {"gpus": [1]}]}):
with self.assertRaises(ReplicaConfigError, msg=cfg):
gpu_groups(cfg)
def test_replica_cfg(self):
cfg = {"gpu": [0, 1, 2, 3], "args": ["--x"], "log": "/l/strata.log", "hip_ordinal": 1, "env": {"A": "1"},
"expert_profile_save": "/p/prof.bin",
"replicas": [{"gpus": [0, 1], "env": {"B": 2}}, {"gpus": [2, 3], "args": ["--y"]}]}
a, b = replica_cfg(cfg, 0, [0, 1]), replica_cfg(cfg, 1, [2, 3])
self.assertEqual((a["gpu"], b["gpu"]), ([0, 1], [2, 3]))
self.assertEqual((a["log"], b["log"]), ("/l/strata.r0.log", "/l/strata.r1.log"))
self.assertEqual(a["env"], {"A": "1", "B": "2"})
self.assertEqual(b["args"], ["--x", "--y"])
self.assertNotIn("replicas", a)
self.assertNotIn("hip_ordinal", a)
self.assertEqual(a["expert_profile_save"], "/p/prof.r0.bin")
self.assertEqual(cfg["args"], ["--x"]) # the original is untouched
self.assertEqual(replica_cfg({"gpu": [0, 1], "args": []}, 0, [3])["gpu"], 3)
def test_cpu_sets_off(self):
self.assertIsNone(cpu_sets(2, enabled=False))
self.assertIsNone(cpu_sets(1))
class Routing(unittest.TestCase):
def test_matched_prefix_per_replica(self):
r = Router(3)
a = list(range(BLOCK * 4))
r.note(0, a)
r.note(1, a[:BLOCK * 2])
self.assertEqual(r.matched(a + [9] * 70), [BLOCK * 4, BLOCK * 2, 0])
self.assertEqual(r.matched([7] * 200), [0, 0, 0])
r.forget(0)
self.assertEqual(r.matched(a), [0, BLOCK * 2, 0])
def test_the_index_is_bounded(self):
r = Router(2, cap=10)
for i in range(50):
r.note(i % 2, [i] * (BLOCK * 2))
self.assertLessEqual(len(r.blocks), 10)
class FakeEngine:
def __init__(self, n=4):
self.batch, self.up = n, True
self.max_context = 4096
self.info = {}
self.last = {}
def alive(self):
return self.up
class RouteChoice(unittest.TestCase):
def test_least_loaded_then_affinity(self):
e = ReplicaEngine([FakeEngine(), FakeEngine()], load_tokens=3000)
picks = [e.route([i] * 100) for i in range(4)] # nothing cached: spread
self.assertEqual(sorted(picks), [0, 0, 1, 1])
ids = list(range(BLOCK * 8))
e.inflight = [0, 0]
k = e.route(ids)
e.router.note(k, ids)
e.inflight = [0, 0]
self.assertEqual(e.route(ids + [5] * 10), k) # the conversation goes back
e.inflight = [0, 0]
e.inflight[k] = 1 # 512 tokens held < 3000 per running request
self.assertNotEqual(e.route(ids + [5] * 10), k)
def test_a_long_prefix_outweighs_load(self):
e = ReplicaEngine([FakeEngine(), FakeEngine()], load_tokens=3000)
ids = list(range(BLOCK * 200)) # 12,800 tokens held on replica 0
e.router.note(0, ids)
e.inflight = [2, 0]
self.assertEqual(e.route(ids + [1]), 0)
e.inflight = [5, 0]
self.assertEqual(e.route(ids + [1]), 1)
def test_a_dead_replica_is_skipped(self):
a, b = FakeEngine(), FakeEngine()
e = ReplicaEngine([a, b])
e.heal = lambda: None
ids = list(range(BLOCK * 3))
e.router.note(0, ids)
a.up = False
self.assertEqual(e.route(ids), 1)
b.up = False
self.assertEqual(e.route(ids), -1)
def test_batch_is_the_sum(self):
self.assertEqual(ReplicaEngine([FakeEngine(4), FakeEngine(4)]).batch, 8)
self.assertEqual(ReplicaEngine([FakeEngine(0), FakeEngine(0)]).batch, 2)
class ReplicaService(unittest.TestCase):
def start(self, slots=4, n=2):
import serve.server as server
self.tmp = tempfile.TemporaryDirectory()
script = Path(self.tmp.name) / "fake_strata.py"
script.write_text(FAKE_BATCH, encoding="utf-8")
real = server.subprocess.Popen
self.logs = [Path(self.tmp.name) / f"r{i}.log" for i in range(n)]
engines = []
for i in range(n):
extra = (["--batch", str(slots)] if slots else []) + ["--log", str(self.logs[i])]
with mock.patch.object(server.subprocess, "Popen",
lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
engines.append(StrataEngine("strata", extra))
self.engine = ReplicaEngine(engines)
self.svc = Service(self.engine, ByteTokenizer(), ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
self.httpd = serve(self.svc, port=0)
self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
def tearDown(self):
if getattr(self, "httpd", None):
self.httpd.shutdown()
self.httpd.server_close()
if getattr(self, "engine", None):
self.engine.unload()
if getattr(self, "tmp", None):
self.tmp.cleanup()
def post(self, messages, max_tokens=64):
body = {"messages": messages, "max_tokens": max_tokens, "reasoning_effort": "none"}
req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read().decode())["choices"][0]["message"]["content"]
def chat(self, text, max_tokens=64):
return self.post([{"role": "user", "content": text}], max_tokens)
def served(self):
return [sum(1 for l in p.read_text().splitlines() if l.split()[0] in ("GEN", "BGEN")) if p.exists() else 0
for p in self.logs]
def burst(self, prompts):
out = [None] * len(prompts)
def one(i):
out[i] = self.chat(prompts[i])
ts = [threading.Thread(target=one, args=(i,)) for i in range(len(prompts))]
for t in ts:
t.start()
for t in ts:
t.join()
return out
def test_requests_spread_over_both_and_answers_are_the_solo_answer(self):
self.start()
solo = self.chat("hello there")
before = self.served()
out = self.burst([f"request number {i} " + "x" * 300 for i in range(6)])
got = [b - a for a, b in zip(before, self.served())]
self.assertTrue(all(g >= 2 for g in got), got)
self.assertEqual(set(out), {solo})
def test_metrics_and_status_see_all_slots(self):
self.start()
self.assertEqual(self.svc.v1_status()["concurrency"]["serving"], 8)
m = self.svc.metrics()
self.assertEqual(len(m["live"]["slots"]), 8)
self.assertEqual([r["replica"] for r in m["live"]["replicas"]], [0, 1])
self.assertEqual(m["engine"]["replicas"], 2)
def test_engines_without_slots_run_one_each_at_once(self):
self.start(slots=0)
out = self.burst(["a" * 40, "b" * 40])
self.assertEqual(self.served(), [1, 1])
self.assertEqual(len(set(out)), 1)
def test_a_conversation_goes_back_to_its_replica(self):
self.start()
first = "begin " + "lorem ipsum " * 40
reply = self.chat(first)
k = self.served().index(1)
self.post([{"role": "user", "content": first}, {"role": "assistant", "content": reply},
{"role": "user", "content": "and then?"}], 16)
self.assertEqual(self.served()[k], 2)
def test_a_replica_that_died_is_skipped(self):
self.start()
self.engine.heal = lambda: None
self.engine.engines[0].proc.kill()
self.engine.engines[0].proc.wait()
self.assertTrue(self.engine.alive())
for i in range(3):
self.assertIn("ok, done.", self.chat(f"after the loss {i}"))
self.assertEqual(self.served()[1], 3)
if __name__ == "__main__":
unittest.main()
+18
View File
@@ -4661,6 +4661,10 @@ def main() -> int:
ap.add_argument("--parallel", type=int, metavar="N",
help="up to N requests decode together (batch slots, opt-in; default: one at a time, the others "
"wait). Each slot takes VRAM from the expert cache; setup says what it recommends")
ap.add_argument("--replicas", type=int, metavar="N",
help="several GPUs: run N independent engines, each on its own equal group of the chosen cards (2 "
"replicas on 4 cards = two 2-card engines), requests spread over them (opt-in; more total "
"throughput for a model that fits fewer cards; each replica holds its own copy of the model)")
ap.add_argument("--kv-streaming", choices=["auto", "on", "off"], default="auto",
help="from a 64K context: keep the KV cache in RAM and only the attention's window in VRAM (more "
"experts fit on the GPU); auto: when the RAM has room for it")
@@ -5476,6 +5480,20 @@ def main() -> int:
cfg["layer_split"] = a.layer_split or "auto"
ok(f"layer split across GPUs {multi} ({cfg['layer_split']})")
recommend_remote_expert_opt(cfg, off=a.no_remote_expert_opt)
if a.replicas is not None and a.replicas >= 2: # data-parallel replicas (serve/replicas.py), opt-in
cards = multi if multi else []
if not cards or len(cards) % a.replicas:
warn(f"--replicas {a.replicas}: needs the chosen GPUs ({cards or 'one'}) to divide into {a.replicas} equal "
"groups; not set (choose the cards with --gpu 0,1,2,3, or write the groups into the config: "
'"replicas": [{"gpus": [0, 1]}, {"gpus": [2, 3]}])')
else:
cfg["replicas"] = a.replicas
per = len(cards) // a.replicas
ok(f"{a.replicas} replicas of {per} GPU(s) each: {' | '.join(','.join(map(str, cards[i * per:(i + 1) * per])) for i in range(a.replicas))}")
if per > 1 and a.layer_split not in (None, "auto"):
warn("--layer-split is one engine's value; with replicas every group would get it: leave it at auto")
if (os.cpu_count() or 0) < 8 * a.replicas:
warn("each replica loads its own copy of the model into RAM and runs its own host threads: check the RAM")
if a.host:
cfg["host"] = a.host
if a.api_key: