replica profile (opt-in): setup --replica-profile picks one engine per card + shared expert arena + the host stack when the RAM and VRAM check passes

This commit is contained in:
Niko1221 committed 2026-10-30 04:51:14 +01:00
1 parent 3782008944
commit 2f0d6a1c15
3 files changed
+276 -1

No files matched your search

+21 -1
View File
@@ -8953,6 +8953,11 @@ def main() -> int:
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("--replica-profile", action="store_true", default=False,
help="two or more GPUs, Qwen3.8 IQ3_S/IQ3_XXS/Q2_0: one engine per card behind the server instead of one "
"layer split, the experts shared in RAM, the batch switches on (opt-in; about 1.8 times the "
"throughput at 8-16 requests at once on 4 Radeon AI PRO R9700; needs about 61 GB of RAM for 2 "
"engines and 66 GB for 4; a layer split you chose, replicas or --parallel always win)")
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")
@@ -10095,7 +10100,22 @@ def main() -> int:
cfg["gpu_order"] = "as_given"
ok(f"layer split across GPUs {multi} ({cfg['layer_split']})")
recommend_remote_expert_opt(cfg, off=a.no_remote_expert_opt)
if hip and a.layer_split in (None, "auto"): # four Radeon AI PRO R9700 cards and Qwen3.8 IQ3_S: the measured serving profile
replica_done = False
if a.replicas is None and a.layer_split in (None, "auto") and (getattr(a, "replica_profile", False) or
os.environ.get("STRATA_REPLICA_PROFILE")):
try: # the opt-in replica profile (strata_control/replica_profile.py)
from strata_control import replica_profile
if getattr(a, "replica_profile", False):
cfg["replica_profile"] = True
lines = replica_profile.apply([{"name": c.get("name"), "vram_gb": c.get("vram_gb"), "vendor": c.get("vendor"),
"index": c.get("index")} for c in chosen], cfg, float(ram),
parallel_given=a.parallel is not None)
replica_done = bool(cfg.get("replicas"))
for line in lines:
(ok if replica_done else say)(line)
except Exception as e: # noqa: BLE001 - a profile is never a reason to stop setup
say(f" (the replica profile was not applied: {e})")
if hip and a.layer_split in (None, "auto") and not replica_done: # four Radeon AI PRO R9700 cards and Qwen3.8 IQ3_S: the measured serving profile
try: # (strata_control/amd_four_card.py); what the person chose always wins
from strata_control import amd_four_card
for line in amd_four_card.apply([{"name": c.get("name"), "vram_gb": c.get("vram_gb"), "vendor": "amd"} for c in chosen],
+131
View File
@@ -0,0 +1,131 @@
"""The replica serving profile (opt-in): on two or more GPUs, one engine per card behind the server instead of one layer split.
Measured on 4 x Radeon AI PRO R9700 (Qwen3.8-Flash-Next IQ3_S, 1k-token prompts, 128 tokens out, total tokens per second;
docs/BATCHING.md, "Replicas as a serving profile"):
* 2 cards: 2 engines of one card each reach 1.8 to 1.9 times what a layer split of the two cards does with `parallel` 8 or
16 (116.6 against 63.8 tok/s at 8 requests, 126.9 against 65.7 at 16);
* 4 cards: 4 engines reach 1.8 to 1.9 times the shipped four-card profile (190 against 107 at 8, 220 against 116 at 16).
Nothing is lost for one user: a request alone runs on one card at the same speed (13 ms a token on one card, 13 ms on four).
The price is host RAM: every engine keeps its own copy of the experts. The profile therefore turns on the shared expert
arena (serve/replicas.py: one memory object holds the experts for all engines, measured 61 GB for 2 engines and 66 GB for 4
instead of 109 and 211 GB) and chooses the number of engines the RAM allows. Without the shared arena (Windows) it needs the
private copies to fit.
Recommend, never force: this profile is opt-in (`setup.py --replica-profile`, STRATA_REPLICA_PROFILE=1, or
"replica_profile": true in the run config; "replica_profile": false or STRATA_REPLICA_PROFILE=0 turn it off), and what the
person chose (the config's `replicas`, `--parallel`, `--layer-split`, `--peer-device`, an environment variable) always wins.
It only touches the measured model class; every other computer gets exactly what it got before.
Pure functions, no I/O (the callers pass the cards, the RAM and the run config).
"""
from __future__ import annotations
import os
import sys
# the experts' size in RAM per quant (setup.py MODELS "arena_gb"): the shared arena holds this once
ARENA_GB = {"iq3_s": 50.3, "iq3_xxs": 42.9, "q2_0": 34.0}
PER_REPLICA_GB = 8.0 # measured: about 7 GB of private RAM per engine beside the arena (2 engines: 61 GB in all, 47 of them shared)
HEADROOM_GB = 12.0 # what the OS, the server and the page cache keep
MIN_CARD_GB = 24.0 # measured on 32 GB cards; a smaller card is not claimed (an A4000 16 GB is measured separately)
MIN_REPLICAS = 2
SWITCHES = {"STRATA_QSA_SLOTS": "1", "STRATA_BATCH_SELF_COMMIT": "1", "STRATA_SLOT_COPY_DIRECT": "1",
"STRATA_CKPT_POOL": "1", "STRATA_CKPT_POOL_READY": "4", "STRATA_SLOT_CKPT_MOVE": "1",
"STRATA_SLOT_COPY_BATCHSYNC": "1"}
OFF_VALUES = ("0", "off", "no", "false")
ON_VALUES = ("1", "on", "yes", "true")
def requested(cfg: dict | None = None, environ=None) -> bool:
"""Opt-in, and an explicit no wins: config "replica_profile" true/false, else STRATA_REPLICA_PROFILE."""
environ = os.environ if environ is None else environ
if cfg and cfg.get("replica_profile") is not None:
return cfg.get("replica_profile") is True
return str(environ.get("STRATA_REPLICA_PROFILE", "")).strip().lower() in ON_VALUES
def quant_of(cfg: dict) -> str | None:
"""The measured model: Qwen3.8-Flash-Next at a quant whose experts size is known."""
text = " ".join([str(cfg.get("model_name") or "")] + [str(a) for a in cfg.get("args") or []]).lower().replace("-", "_").replace(".", "_")
if "qwen3_8" not in text:
return None
for q in ARENA_GB:
if q in text:
return q
return None
def shared_arena_possible(platform: str | None = None) -> bool:
return (sys.platform if platform is None else platform).startswith("linux")
def replicas_for(n_cards: int, arena_gb: float, ram_gb: float, shared: bool) -> int:
"""How many one-card engines the RAM allows (at most one per card)."""
if shared:
room = ram_gb - HEADROOM_GB - arena_gb
k = int(room // PER_REPLICA_GB) if room > 0 else 0
else:
k = int((ram_gb - HEADROOM_GB) // (arena_gb + PER_REPLICA_GB))
return max(0, min(n_cards, k))
def applies(cards: list[dict], cfg: dict, ram_gb: float, *, platform: str | None = None, environ=None) -> tuple[bool, str]:
"""(True, "") when the profile would be applied; else (False, why not) - the reason is for the log, '' when nothing was asked."""
if not requested(cfg, environ):
return False, ""
args = [str(a) for a in cfg.get("args") or []]
if cfg.get("replicas") or cfg.get("arch") == "deepseek41" or "--peer-device" in args:
return False, "replica profile: the config already names replicas, a peer device or another model family"
if str(cfg.get("layer_split") or "auto") != "auto" or "--layer-split" in args:
return False, "replica profile: you chose a layer split; kept"
if len(cards) < MIN_REPLICAS:
return False, "replica profile: needs two or more GPUs"
q = quant_of(cfg)
if q is None:
return False, "replica profile: measured only for Qwen3.8-Flash-Next IQ3_S, IQ3_XXS and Q2_0"
if any(float(c.get("vram_gb") or 0.0) < MIN_CARD_GB for c in cards):
return False, f"replica profile: a card has under {MIN_CARD_GB:.0f} GB of VRAM (measured on 32 GB cards)"
shared = shared_arena_possible(platform)
k = replicas_for(len(cards), ARENA_GB[q], ram_gb, shared)
if k < MIN_REPLICAS:
need = HEADROOM_GB + ARENA_GB[q] + MIN_REPLICAS * PER_REPLICA_GB if shared else HEADROOM_GB + MIN_REPLICAS * (ARENA_GB[q] + PER_REPLICA_GB)
return False, (f"replica profile: {ram_gb:.0f} GB of RAM; two engines need about {need:.0f} GB"
f"{'' if shared else ' (this OS cannot share the experts between engines)'}; the layer split stays")
return True, ""
def apply(cards: list[dict], cfg: dict, ram_gb: float, *, parallel_given: bool = False, platform: str | None = None,
environ=None) -> list[str]:
"""Fill the profile into `cfg` (in place) where the person has not chosen; returns the plain lines to show."""
ok, why = applies(cards, cfg, ram_gb, platform=platform, environ=environ)
if not ok:
return [why] if why else []
environ = os.environ if environ is None else environ
q = quant_of(cfg)
shared = shared_arena_possible(platform)
k = replicas_for(len(cards), ARENA_GB[q], ram_gb, shared)
gpus = cfg.get("gpu") if isinstance(cfg.get("gpu"), list) else [c.get("index", i) for i, c in enumerate(cards)]
chosen = list(gpus)[:k]
cfg["gpu"] = chosen
cfg["replicas"] = [{"gpus": [g]} for g in chosen]
if shared:
cfg.setdefault("replica_shared_arena", True)
env = dict(cfg.get("env") or {})
for key, val in SWITCHES.items():
if key not in environ: # an environment variable of the person's own wins
env.setdefault(key, val)
cfg["env"] = env
notes = [f"{k} engines of one card each instead of one layer split of {len(cards)}: requests spread over them "
f"(about 1.8 times the throughput at 8 to 16 requests at once; one request alone is as fast as before)"]
if k < len(cards):
notes.append(f"{len(cards) - k} card(s) left out: the RAM ({ram_gb:.0f} GB) holds {k} engines")
notes.append("the experts are in RAM once for all engines (shared expert arena)" if shared else
"each engine keeps its own copy of the experts in RAM (this OS cannot share them)")
if not parallel_given and "parallel" not in cfg and not {"--batch", "--slots"} & set(str(a) for a in cfg.get("args") or []):
cfg["parallel"] = 8 if k == 2 else 4
notes.append(f"{cfg['parallel']} requests at once on each engine (--parallel N changes it)")
return notes
+124
View File
@@ -0,0 +1,124 @@
"""strata_control/replica_profile.py: the opt-in replica serving profile (one engine per card, shared expert arena)."""
from __future__ import annotations
import unittest
from strata_control import replica_profile as P
R9700 = {"name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "vendor": "amd"}
def cards(n, **kw):
return [{**R9700, **kw, "index": i} for i in range(n)]
def cfg(**kw):
c = {"model_name": "qwen3.8-flash-next-iq3_s", "gpu": [0, 1, 2, 3], "layer_split": "auto",
"args": ["--pack", "/p/iq3_s", "--spec", "4"], "replica_profile": True}
c.update(kw)
return c
class Request(unittest.TestCase):
def test_opt_in_only(self):
self.assertFalse(P.requested({}, {}))
self.assertTrue(P.requested({"replica_profile": True}, {}))
self.assertTrue(P.requested({}, {"STRATA_REPLICA_PROFILE": "1"}))
def test_an_explicit_no_wins(self):
self.assertFalse(P.requested({"replica_profile": False}, {"STRATA_REPLICA_PROFILE": "1"}))
def test_without_the_request_nothing_changes(self):
c = cfg(replica_profile=None)
c.pop("replica_profile")
before = dict(c)
self.assertEqual(P.apply(cards(4), c, 256.0, platform="linux", environ={}), [])
self.assertEqual(c, before)
class Count(unittest.TestCase):
def test_ram_sets_the_number_of_engines(self):
self.assertEqual(P.replicas_for(4, 50.3, 251.0, True), 4)
self.assertEqual(P.replicas_for(4, 50.3, 128.0, True), 4)
self.assertEqual(P.replicas_for(4, 50.3, 96.0, True), 4)
self.assertEqual(P.replicas_for(4, 50.3, 80.0, True), 2) # 80 - 12 - 50.3 = 17.7 -> 2
self.assertEqual(P.replicas_for(4, 50.3, 64.0, True), 0) # one engine's room only
self.assertEqual(P.replicas_for(2, 50.3, 251.0, False), 2) # private copies: 2 x 58.3 + 12
self.assertEqual(P.replicas_for(4, 50.3, 200.0, False), 3)
self.assertEqual(P.replicas_for(2, 50.3, 100.0, False), 1)
class Apply(unittest.TestCase):
def test_four_cards_with_plenty_of_ram(self):
c = cfg()
notes = P.apply(cards(4), c, 251.0, platform="linux", environ={})
self.assertTrue(notes)
self.assertEqual(c["replicas"], [{"gpus": [0]}, {"gpus": [1]}, {"gpus": [2]}, {"gpus": [3]}])
self.assertIs(c["replica_shared_arena"], True)
self.assertEqual(c["parallel"], 4)
self.assertEqual(c["env"]["STRATA_CKPT_POOL"], "1")
self.assertEqual(c["env"]["STRATA_QSA_SLOTS"], "1")
def test_two_cards_get_eight_slots_each(self):
c = cfg(gpu=[0, 1])
P.apply(cards(2), c, 128.0, platform="linux", environ={})
self.assertEqual(c["parallel"], 8)
self.assertEqual(len(c["replicas"]), 2)
def test_less_ram_drops_cards_and_says_so(self):
c = cfg()
notes = P.apply(cards(4), c, 80.0, platform="linux", environ={})
self.assertEqual(c["replicas"], [{"gpus": [0]}, {"gpus": [1]}])
self.assertEqual(c["gpu"], [0, 1])
self.assertTrue(any("left out" in n for n in notes))
def test_too_little_ram_keeps_the_layer_split(self):
c = cfg()
notes = P.apply(cards(4), c, 64.0, platform="linux", environ={})
self.assertNotIn("replicas", c)
self.assertEqual(c["layer_split"], "auto")
self.assertTrue(notes and "layer split stays" in notes[0])
def test_windows_cannot_share_so_the_private_copies_must_fit(self):
c = cfg(gpu=[0, 1])
self.assertEqual(P.apply(cards(2), c, 100.0, platform="win32", environ={})[0].split(":")[0], "replica profile")
self.assertNotIn("replicas", c)
c = cfg(gpu=[0, 1])
P.apply(cards(2), c, 160.0, platform="win32", environ={})
self.assertEqual(len(c["replicas"]), 2)
self.assertNotIn("replica_shared_arena", c)
def test_what_the_person_chose_wins(self):
for kw in ({"replicas": 2}, {"layer_split": "13,26,39"}, {"args": ["--pack", "/p/iq3_s", "--peer-device", "1"]},
{"args": ["--pack", "/p/iq3_s", "--layer-split", "20,40"]}, {"arch": "deepseek41"}):
c = cfg(**kw)
before = dict(c)
P.apply(cards(4), c, 251.0, platform="linux", environ={})
self.assertEqual(c.get("replicas"), before.get("replicas"), kw)
self.assertEqual(c.get("layer_split"), before.get("layer_split"), kw)
def test_parallel_and_environment_variables_of_the_person_win(self):
c = cfg(parallel=6)
P.apply(cards(4), c, 251.0, platform="linux", environ={"STRATA_CKPT_POOL": "0"})
self.assertEqual(c["parallel"], 6)
self.assertNotIn("STRATA_CKPT_POOL", c["env"])
c = cfg()
P.apply(cards(4), c, 251.0, parallel_given=True, platform="linux", environ={})
self.assertNotIn("parallel", c)
def test_only_the_measured_hardware_and_model(self):
for kw in ({"model_name": "qwen3.6-35b-a3b-q4"}, {"model_name": "qwen3.8-flash-next-iq2_xs", "args": ["--pack", "/p/x"]}):
c = cfg(**kw)
P.apply(cards(4), c, 251.0, platform="linux", environ={})
self.assertNotIn("replicas", c, kw)
c = cfg(gpu=[0, 1])
P.apply(cards(2, vram_gb=16.0), c, 251.0, platform="linux", environ={})
self.assertNotIn("replicas", c)
c = cfg(gpu=[0])
P.apply(cards(1), c, 251.0, platform="linux", environ={})
self.assertNotIn("replicas", c)
if __name__ == "__main__":
unittest.main()