diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 6e0b0d96..2e9d975f 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -56,6 +56,11 @@ Or edit an existing config (`strata-*.json`), then restart: "layer_split": "auto" ``` +`"layer_split"` is `"auto"` (placed by each card's free VRAM) or the **first layer of each later card**: one rising +number per card after the first, not a count of layers per card. With 4 cards and a 48-layer model, `"24,36,42"` +(or `[24, 36, 42]`) puts layers 0-23 on the first card, 24-35 on the second, 36-41 on the third and 42-47 on the last. +The server checks it before the start and says what is wrong (0.1.39, #644). + **Skip the split when the first card holds everything** (opt-in, 0.1.31): `"split_skip_if_fits": true` in the config (engine flag `--split-skip-if-fits`, with `--layer-split auto`) runs on the first card alone when it holds every profiled expert plus the context's KV, the draft layer and the reserve, and says so in the log; otherwise the split diff --git a/serve/server.py b/serve/server.py index 46e3fc36..c143a6b8 100644 --- a/serve/server.py +++ b/serve/server.py @@ -789,12 +789,46 @@ def engine_silence_s(cfg: dict) -> float: return float(v) +def layer_split_value(cfg: dict) -> str: + """#644: the config's "layer_split" as the engine's --layer-split value: "auto" (the default), or the FIRST LAYER of + each later GPU's share - one rising number per GPU after the first, e.g. "24,36,42" for 4 GPUs (layers 0-23 on the + first card, 24-35, 36-41, 42 to the end) - as a string or a JSON list ([24, 36, 42]). ValueError with the format + and an example for anything else, such as per-card layer counts ("24,16,12,12").""" + v = cfg.get("layer_split") + if v is None or (isinstance(v, str) and v.strip().lower() in ("", "auto")): + return "auto" + n = len(gpu_list(cfg)) + items = v if isinstance(v, (list, tuple)) else str(v).split(",") if isinstance(v, (str, int)) else None + vals = [] + for x in items or []: + try: + if isinstance(x, bool) or isinstance(x, float): + raise ValueError + vals.append(int(str(x).strip())) + except ValueError: + vals = None + break + want = max(n - 1, 1) + example = ",".join(str(round(48 * (i + 1) / (want + 1))) for i in range(want)) + hint = (f'"layer_split" is the first layer of each later GPU, one rising number per GPU after the first ' + f'({want} for {n} GPUs), not a count of layers per card - e.g. "{example}" (or [{example.replace(",", ", ")}])' + f' for an even share of 48 layers, or "auto" (the default) to place them by each card\'s free VRAM') + if not vals: + raise ValueError(f"{hint}; got {v!r}") + if n > 1 and len(vals) != n - 1: + raise ValueError(f"{hint}; got {len(vals)} number(s) ({v!r}) for {n} GPUs") + if vals[0] < 2 or any(b <= a for a, b in zip(vals, vals[1:])): + raise ValueError(f"{hint}; got {v!r}, which does not rise from 2 or more") + return ",".join(str(x) for x in vals) + + def engine_args(cfg: dict) -> list[str]: """The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in the - config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32").""" + config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32"; see + layer_split_value).""" args = list(cfg["args"]) if len(gpu_list(cfg)) > 1 and "--layer-split" not in args: - args += ["--layer-split", str(cfg.get("layer_split") or "auto")] + args += ["--layer-split", layer_split_value(cfg)] # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV if len(gpu_list(cfg)) > 1 and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args: args.append("--split-skip-if-fits") @@ -2914,7 +2948,11 @@ def main() -> int: print("model unloaded; the first request loads it ..." if lazy else "loading the model (the first start takes a minute or two) ...", flush=True) if len(gpu_list(cfg)) > 1: - print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True) + try: + split = layer_split_value(cfg) # #644: before the (minutes-long) start + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({split})", flush=True) # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing # it is told about (WinError 2), so it is made absolute here exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"])) diff --git a/serve/test_server.py b/serve/test_server.py index 60a19269..0a8e15a1 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -21,7 +21,8 @@ from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402 - engine_args, prompt_tokens_seen, request_timings, serve, start_failure_hint) + engine_args, layer_split_value, prompt_tokens_seen, request_timings, serve, + start_failure_hint) from types import SimpleNamespace # noqa: E402 ROOT = Path(__file__).resolve().parents[1] @@ -847,6 +848,38 @@ class LearnedProfile(unittest.TestCase): self.assertEqual(engine_args(cfg), ["--native", "x", "--expert-profile-save", "learned.bin"]) +class LayerSplit(unittest.TestCase): + """#644: "layer_split" is the first layer of each later GPU; a list is accepted, counts per card are not.""" + + def cfg(self, split, gpus=(2, 0, 1, 3)): + c = {"args": ["--native", "x"], "gpu": list(gpus)} + if split is not ...: + c["layer_split"] = split + return c + + def test_auto_and_absent(self): + for v in (..., None, "", "auto", "AUTO"): + self.assertEqual(engine_args(self.cfg(v))[-2:], ["--layer-split", "auto"]) + + def test_string_and_list(self): + self.assertEqual(engine_args(self.cfg("24,36,42"))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg(" 24, 36 ,42 "))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg([24, 36, 42]))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg(18, gpus=(0, 1)))[-2:], ["--layer-split", "18"]) + self.assertEqual(engine_args(self.cfg([18], gpus=(0, 1)))[-2:], ["--layer-split", "18"]) + + def test_counts_per_card_are_refused_with_the_format(self): + for bad in ("24,16,12,12", [24, 16, 12, 12], "24,16,12", "24,36", "x", [24.5, 30, 40], "1,20,30", [True]): + with self.assertRaises(ValueError) as e: + layer_split_value(self.cfg(bad)) + self.assertIn("first layer of each later GPU", str(e.exception)) + self.assertIn('"12,24,36"', str(e.exception)) # the example for 4 GPUs + + def test_one_gpu_ignores_it(self): + self.assertEqual(engine_args({"args": ["--native", "x"], "gpu": [0], "layer_split": "24,16"}), + ["--native", "x"]) + + class DraftHeadHint(unittest.TestCase): """#474: a start that stopped at "the draft head does not fit" says what to change, from this start's log lines.""" diff --git a/setup.py b/setup.py index c1990b7d..69624a11 100644 --- a/setup.py +++ b/setup.py @@ -2943,8 +2943,9 @@ def main() -> int: ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " "them): \"0,2\", or \"all\" (every card that can); the first is the main one. " "Saved, also when starting (see docs/MULTI_GPU.md)") - ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"); " - "default auto, placed from each GPU's free VRAM") + ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"), one " + "rising number per GPU after the first - not layers per card; default " + "auto, placed from each GPU's free VRAM") ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " "devices on your network (issue #26; set --api-key too)") ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") diff --git a/src/program/generate.cpp b/src/program/generate.cpp index cb991841..ac250f79 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1416,7 +1416,9 @@ int main(int argc, char** argv) { } if (!ok) { std::fprintf(stderr, "strata generate: --layer-split K[,K2..]|auto needs --serve, rising K from 2, and one " - "distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU)\n", n_dev - 1); + "distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU). K is the " + "FIRST LAYER of each later GPU, not a count of layers per card: \"24,36,42\" for 4 " + "GPUs, not \"24,12,6,6\" (got \"%s\")\n", n_dev - 1, o.layer_split.c_str()); return 2; } }