okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
8.1 KiB137 linesraw
1"""The replica serving profile (opt-in): on two or more GPUs, one engine per card behind the server instead of one layer split.
2
3Measured on 4 x Radeon AI PRO R9700 (Qwen3.8-Flash-Next IQ3_S, 1k-token prompts, 128 tokens out, total tokens per second;
4docs/BATCHING.md, "Replicas as a serving profile"):
5
6* 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
7  16 (116.6 against 63.8 tok/s at 8 requests, 126.9 against 65.7 at 16);
8* 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).
9
10Nothing 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).
11
12The price is host RAM: every engine keeps its own copy of the experts.  The profile therefore turns on the shared expert
13arena (serve/replicas.py: one memory object holds the experts for all engines, measured 61 GB for 2 engines and 66 GB for 4
14instead of 109 and 211 GB) and chooses the number of engines the RAM allows.  Without the shared arena (Windows) it needs the
15private copies to fit.
16
17Recommend, never force: this profile is opt-in (`setup.py --replica-profile`, STRATA_REPLICA_PROFILE=1, or
18"replica_profile": true in the run config; "replica_profile": false or STRATA_REPLICA_PROFILE=0 turn it off), and what the
19person chose (the config's `replicas`, `--parallel`, `--layer-split`, `--peer-device`, an environment variable) always wins.
20It only touches the measured model class; every other computer gets exactly what it got before.
21
22Pure functions, no I/O (the callers pass the cards, the RAM and the run config).
23"""
24
25from __future__ import annotations
26
27import os
28import sys
29
30# the experts' size in RAM per quant (setup.py MODELS "arena_gb"): the shared arena holds this once
31ARENA_GB = {"iq3_s": 50.3, "iq3_xxs": 42.9, "q2_0": 34.0}
32PER_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)
33HEADROOM_GB = 12.0          # what the OS, the server and the page cache keep
34MIN_CARD_GB = 24.0          # measured on 32 GB cards; a smaller card is not claimed (an A4000 16 GB is measured separately)
35MIN_REPLICAS = 2
36REPLICA_RESERVE_MIB = 2500   # VRAM each one-card engine keeps free (the draft head's prompt capture needs ~2 GB at 14K tokens)
37SWITCHES = {"STRATA_QSA_SLOTS": "1", "STRATA_BATCH_SELF_COMMIT": "1", "STRATA_SLOT_COPY_DIRECT": "1",
38            "STRATA_CKPT_POOL": "1", "STRATA_CKPT_POOL_READY": "4", "STRATA_SLOT_CKPT_MOVE": "1",
39            "STRATA_SLOT_COPY_BATCHSYNC": "1"}
40OFF_VALUES = ("0", "off", "no", "false")
41ON_VALUES = ("1", "on", "yes", "true")
42
43
44def requested(cfg: dict | None = None, environ=None) -> bool:
45    """Opt-in, and an explicit no wins: config "replica_profile" true/false, else STRATA_REPLICA_PROFILE."""
46    environ = os.environ if environ is None else environ
47    if cfg and cfg.get("replica_profile") is not None:
48        return cfg.get("replica_profile") is True
49    return str(environ.get("STRATA_REPLICA_PROFILE", "")).strip().lower() in ON_VALUES
50
51
52def quant_of(cfg: dict) -> str | None:
53    """The measured model: Qwen3.8-Flash-Next at a quant whose experts size is known."""
54    text = " ".join([str(cfg.get("model_name") or "")] + [str(a) for a in cfg.get("args") or []]).lower().replace("-", "_").replace(".", "_")
55    if "qwen3_8" not in text:
56        return None
57    for q in ARENA_GB:
58        if q in text:
59            return q
60    return None
61
62
63def shared_arena_possible(platform: str | None = None) -> bool:
64    return (sys.platform if platform is None else platform).startswith(("linux", "win"))
65
66
67def replicas_for(n_cards: int, arena_gb: float, ram_gb: float, shared: bool) -> int:
68    """How many one-card engines the RAM allows (at most one per card)."""
69    if shared:
70        room = ram_gb - HEADROOM_GB - arena_gb
71        k = int(room // PER_REPLICA_GB) if room > 0 else 0
72    else:
73        k = int((ram_gb - HEADROOM_GB) // (arena_gb + PER_REPLICA_GB))
74    return max(0, min(n_cards, k))
75
76
77def applies(cards: list[dict], cfg: dict, ram_gb: float, *, platform: str | None = None, environ=None) -> tuple[bool, str]:
78    """(True, "") when the profile would be applied; else (False, why not) - the reason is for the log, '' when nothing was asked."""
79    if not requested(cfg, environ):
80        return False, ""
81    args = [str(a) for a in cfg.get("args") or []]
82    if cfg.get("replicas") or "--peer-device" in args:
83        return False, "replica profile: the config already names replicas, a peer device or another model family"
84    if str(cfg.get("layer_split") or "auto") != "auto" or "--layer-split" in args:
85        return False, "replica profile: you chose a layer split; kept"
86    if len(cards) < MIN_REPLICAS:
87        return False, "replica profile: needs two or more GPUs"
88    q = quant_of(cfg)
89    if q is None:
90        return False, "replica profile: measured only for Qwen3.8-Flash-Next IQ3_S, IQ3_XXS and Q2_0"
91    if any(float(c.get("vram_gb") or 0.0) < MIN_CARD_GB for c in cards):
92        return False, f"replica profile: a card has under {MIN_CARD_GB:.0f} GB of VRAM (measured on 32 GB cards)"
93    shared = shared_arena_possible(platform)
94    k = replicas_for(len(cards), ARENA_GB[q], ram_gb, shared)
95    if k < MIN_REPLICAS:
96        need = HEADROOM_GB + ARENA_GB[q] + MIN_REPLICAS * PER_REPLICA_GB if shared else HEADROOM_GB + MIN_REPLICAS * (ARENA_GB[q] + PER_REPLICA_GB)
97        return False, (f"replica profile: {ram_gb:.0f} GB of RAM; two engines need about {need:.0f} GB"
98                       f"{'' if shared else ' (this OS cannot share the experts between engines)'}; the layer split stays")
99    return True, ""
100
101
102def apply(cards: list[dict], cfg: dict, ram_gb: float, *, parallel_given: bool = False, platform: str | None = None,
103          environ=None) -> list[str]:
104    """Fill the profile into `cfg` (in place) where the person has not chosen; returns the plain lines to show."""
105    ok, why = applies(cards, cfg, ram_gb, platform=platform, environ=environ)
106    if not ok:
107        return [why] if why else []
108    environ = os.environ if environ is None else environ
109    q = quant_of(cfg)
110    shared = shared_arena_possible(platform)
111    k = replicas_for(len(cards), ARENA_GB[q], ram_gb, shared)
112    gpus = cfg.get("gpu") if isinstance(cfg.get("gpu"), list) else [c.get("index", i) for i, c in enumerate(cards)]
113    chosen = list(gpus)[:k]
114    cfg["gpu"] = chosen
115    cfg["replicas"] = [{"gpus": [g]} for g in chosen]
116    if shared:
117        cfg.setdefault("replica_shared_arena", True)
118    env = dict(cfg.get("env") or {})
119    for key, val in SWITCHES.items():
120        if key not in environ:                              # an environment variable of the person's own wins
121            env.setdefault(key, val)
122    cfg["env"] = env
123    # 0.2.10 (QUAL-PAR): with the expert cache on auto each engine fills its card and keeps ~300 MiB; a 14K-token read with the draft head
124    # then ran out of memory in the prompt capture and the engine died.  2.5 GB kept free (2,111 MiB left on a 48 GB card) ran
125    # the 61-task suite and 48 minutes of soak with no error.  A reserve the person gave wins.
126    if "--vram-reserve-mib" not in {str(x) for x in cfg.get("args") or []}:
127        cfg["args"] = list(cfg.get("args") or []) + ["--vram-reserve-mib", str(REPLICA_RESERVE_MIB)]
128    notes = [f"{k} engines of one card each instead of one layer split of {len(cards)}: requests spread over them "
129             f"(about 1.8 times the throughput at 8 to 16 requests at once; one request alone is as fast as before)"]
130    if k < len(cards):
131        notes.append(f"{len(cards) - k} card(s) left out: the RAM ({ram_gb:.0f} GB) holds {k} engines")
132    notes.append("the experts are in RAM once for all engines (shared expert arena)" if shared else
133                 "each engine keeps its own copy of the experts in RAM (this OS cannot share them)")
134    if not parallel_given and "parallel" not in cfg and not {"--batch", "--slots"} & set(str(a) for a in cfg.get("args") or []):
135        cfg["parallel"] = 8 if k == 2 else 4
136        notes.append(f"{cfg['parallel']} requests at once on each engine (--parallel N changes it)")
137    return notes