diff --git a/sycl/serve/server_intel.py b/sycl/serve/server_intel.py index 7a4c7cc5..d34bc3ef 100644 --- a/sycl/serve/server_intel.py +++ b/sycl/serve/server_intel.py @@ -19,6 +19,7 @@ from __future__ import annotations import collections import json import sys +import time import urllib.parse import urllib.request from pathlib import Path @@ -223,6 +224,56 @@ def install_logprobs(): S.openai_collect = openai_collect +def install_narrator(): + """The start narrator of serve/server.py says the CUDA engine's thing - tens of GB read into RAM, "YOUR PC CAN BE + SLOW OR STOP RESPONDING" - at the experts' step. With --stream-experts the SYCL port reads them from the GGUF + into VRAM (and a pinned mirror), which does not do that: say that instead. Without it (an i915 card) the experts + do go into a RAM arena and the original text stands.""" + orig = S.narrate_start + + def narrate_start(log_path, offset, args, done, heartbeat=20.0): + if "--stream-experts" not in args: + return orig(log_path, offset, args, done, heartbeat) + t0 = last = time.time() + said = set() + + def say(key, text): + nonlocal last + if key not in said: + said.add(key) + last = time.time() + print(text, flush=True) + + say("weights", "[strata] starting the engine: reading the model's weights ...") + pos = offset + while not done.wait(0.5): + try: + with open(log_path, "rb") as f: + f.seek(pos) + chunk = f.read() + except OSError: + chunk = b"" + if chunk.count(b"\n"): + cut = chunk.rfind(b"\n") + 1 + pos += cut + for line in chunk[:cut].decode("utf-8", "replace").splitlines(): + if "PLE on" in line or "expert arena:" in line: + say("arena", "[strata] streaming the experts from the model files into the GPU's memory " + "(and a pinned RAM mirror for what does not fit); the first start takes a few minutes ...") + elif " loaded " in line and "GiB at" in line: + say("loaded", "[strata] experts loaded: " + line.split(" loaded ", 1)[1].strip() + + f" ({time.time() - t0:.0f} s so far)") + elif "expert cache " in line and " slots, " in line and "auto" not in line: + n = line.split("expert cache ", 1)[1].split(";")[0].replace(" slots,", " experts,").strip() + say("cache", f"[strata] filling the GPU's expert cache ({n}) ...") + elif "session is up" in line: + say("up", "[strata] almost ready ...") + if time.time() - last > heartbeat: + last = time.time() + print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True) + S.narrate_start = narrate_start + + def top_logprobs(req: dict): """The K for the engine's logprobs=K, or None when the request did not ask (OpenAI: logprobs=true, top_logprobs 0..20; the legacy completions form, logprobs=N, is taken as N).""" @@ -237,6 +288,7 @@ def top_logprobs(req: dict): if __name__ == "__main__": install_xe_reader() + install_narrator() install_switcher(sys.argv[1:]) install_logprobs() sys.exit(S.main()) diff --git a/sycl/serve/strata-sycl.sh b/sycl/serve/strata-sycl.sh index 6299a597..35d670af 100755 --- a/sycl/serve/strata-sycl.sh +++ b/sycl/serve/strata-sycl.sh @@ -7,7 +7,10 @@ # STRATA_SYCL_IMAGE the runtime image (default: strata-sycl-dev) # STRATA_SYCL_BIN the engine binary, relative to the repo (default: build-sycl-aot/strata) # STRATA_SYCL_NAME the container's name (default: strata-sycl-serve) -# ONEAPI_DEVICE_SELECTOR passed in when set (the image pins level_zero:0; level_zero:* for a two-card split, #423) +# Passed into the container: every variable of this script's environment that starts with STRATA_ (the config's +# "env" block arrives that way: the server puts it in the engine's environment), ONEAPI_ (level_zero:* for a +# two-card split, #423), UR_, IGC_, SYCL_ or ZES_. The port's own defaults (below) are overridden the same way, +# e.g. "env": {"STRATA_VERIFY_NO_HOST": "0"} in the config. set -euo pipefail here=$(cd "$(dirname "$0")/../.." && pwd) # the repo root=${STRATA_SYCL_ROOT:-$(dirname "$here")} @@ -16,12 +19,23 @@ name=${STRATA_SYCL_NAME:-strata-sycl-serve} docker rm -f "$name" >/dev/null 2>&1 || true # a container left behind by a killed server args="" for a in "$@"; do args+=" $(printf '%q' "$a")"; done -sel=() -[ -n "${ONEAPI_DEVICE_SELECTOR:-}" ] && sel=(-e "ONEAPI_DEVICE_SELECTOR=$ONEAPI_DEVICE_SELECTOR") -# the port's run-time switches: the device-built verify plan without host handshakes (docs/INTEL.md) +# the port's run-time switches: the device-built verify plan, and no host handshakes in it. NO_HOST is for a card on +# the xe driver (the host<->GPU flag stores are not visible there); an i915 card (Arc A-series) runs without it +# (docs/INTEL.md) +declare -A setting=([STRATA_VERIFY_DEVICE_PLAN]=1 [STRATA_VERIFY_NO_HOST]=1 [STRATA_STAGER_THREADS]=12) +while IFS= read -r k; do + case "$k" in + STRATA_SYCL_*) ;; # this script's own settings + STRATA_*|ONEAPI_*|UR_*|IGC_*|SYCL_*|ZES_*|NEOReadDebugKeys|OverrideDefaultFP64Settings) setting[$k]=${!k} ;; + esac +done < <(compgen -e) +envs=() +for k in "${!setting[@]}"; do + # the engine tests the switches by presence: a value of 0 (or empty) means "not set", so it is not passed on + case "${setting[$k]}" in 0|"") ;; *) envs+=(-e "$k=${setting[$k]}") ;; esac +done exec docker run --rm -i --name "$name" --device /dev/dri --oom-score-adj 1000 --stop-timeout 30 --no-healthcheck \ -v "$root:/work" \ - -e STRATA_VERIFY_DEVICE_PLAN=1 -e STRATA_VERIFY_NO_HOST=1 -e STRATA_STAGER_THREADS=12 \ - "${sel[@]}" \ + "${envs[@]}" \ "${STRATA_SYCL_IMAGE:-strata-sycl-dev}" \ "cd $repo_in && exec ${STRATA_SYCL_BIN:-build-sycl-aot/strata}$args" diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 900b1de7..86df7c67 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -1,6 +1,6 @@ """setup.py for an Intel Arc: upstream's installer, steered onto the SYCL port from outside. - python sycl/setup_intel.py [setup.py's options] + ./setup.sh --backend sycl [setup.py's options] (this file, run through setup.sh's virtual environment) The SYCL port keeps out of the shared files (upstream merges stay clean), so this does not edit setup.py: it imports it and replaces the few steps that are NVIDIA/AMD-specific, then runs setup's own main(). Everything else - the @@ -75,7 +75,7 @@ def intel_gpus(): vram = (int(end, 16) - int(start, 16) + 1) / 2**30 except (OSError, IndexError, ValueError): vram = 0.0 - found.append({"index": len(found), "name": f"Intel {name}", "vram_gb": vram, "arch": "xe", "driver": driver}) + found.append({"index": len(found), "name": f"Intel {name}", "vram_gb": vram, "arch": driver, "driver": driver}) return found @@ -85,7 +85,7 @@ def sycl_engine(): return None, "the SYCL port runs on Linux only" exe = next((b for b in (ROOT / "build-sycl-aot" / "strata", ROOT / "build-sycl" / "strata") if b.exists()), None) if exe is None: - return None, "it is not built (sycl/tools/build.sh; docs/INTEL.md)" + return None, "it is not built (docs/INTEL.md, \"How to build it\": Docker, then sycl/tools/build.sh in the image)" return exe, None @@ -115,11 +115,24 @@ def drop(args, name, value=False): del args[i:i + 1 + int(value)] -def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0) -> dict: +SMALL_CARD_GB = 12.0 # under this the engine's own advice is --vram-reserve-mib 300 (a 1024 MiB reserve leaves an + # 8 GB card no room for even one expert slot) and the English draft vocabulary +SMALL_RESERVE_MIB = 300 + + +def small_card(vram_gb: float, driver: str) -> bool: + return 0 < vram_gb < SMALL_CARD_GB or driver == "i915" + + +def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, driver: str = "xe") -> dict: """setup's config (written for its HIP path) -> the SYCL port's: the container's paths, experts streamed from the - GGUF into VRAM (every expert must fit, so the VRAM reserve is the smallest that leaves the KV and the prompt - buffers room - docs/INTEL.md), KV streaming from 64K up when the RAM holds the KV (the B70 at 256K decodes at - 40+ tok/s with it, 4-9 without).""" + GGUF into VRAM (--stream-experts: the engine reads them from the GGUF and keeps what does not fit in a pinned RAM + mirror; the VRAM reserve is the smallest that leaves the KV and the prompt buffers room - docs/INTEL.md), KV + streaming from 64K up when the RAM holds the KV (the B70 at 256K decodes at 40+ tok/s with it, 4-9 without). + A reserve the user asked for (--vram-reserve-mib) is kept. An i915 card (Alchemist, the A-series) cannot do that: + a single pinned host allocation above a few GB fails there, so the mirror cannot hold what the card does not, and + the config loads the experts into a RAM arena instead (no --stream-experts, --ple-io ram, and the device-built + verify plan's NO_HOST switch off - docs/INTEL.md, "Arc A750").""" args = list(cfg["args"]) for f in ("--resident-experts", "--mmap-experts"): # setup's low-RAM mode is the CUDA engine's drop(args, f) @@ -134,9 +147,17 @@ def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0) kv_ram = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9 if kv != "k8v4" and ctx >= 65536 and ram >= kv_ram + 6: args += ["--kv-resident", "32768"] - S.ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram:.1f} GB), every expert stays in VRAM") + asked_reserve = flag(args, "--vram-reserve-mib") # setup writes it only when the user gave it drop(args, "--vram-reserve-mib", True) - args += ["--stream-experts", "--vram-reserve-mib", "1024" if ctx <= 32768 else "2048"] + reserve = asked_reserve or (str(SMALL_RESERVE_MIB) if small_card(vram_gb, driver) else + "1024" if ctx <= 32768 else "2048") + host_arena = driver == "i915" + if host_arena: + if "--ple-io" not in args: + args += ["--ple-io", "ram"] + args += ["--vram-reserve-mib", reserve] + else: + args += ["--stream-experts", "--vram-reserve-mib", reserve] if ctx > 32768 or vram_gb >= 24: # long contexts: 4096-token chunks keep the prompt buffers small; a drop(args, "--prefill", True) # 24 GB+ card with part of the experts in the RAM mirror streams those args += ["--prefill", "4096"] # over PCIe once per chunk, so fewer, bigger chunks read the prompt @@ -145,8 +166,14 @@ def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0) out = {k: v for k, v in cfg.items() if k not in ("lib_dirs", "env", "vision", "gpus")} out.update({"backend": "sycl", "exe": str(SYCL_WRAPPER), "args": args, "sycl_root": str(MOUNT)}) env = {} + if host_arena: + env["STRATA_VERIFY_NO_HOST"] = "0" # strata-sycl.sh sets 1 unless told otherwise (xe, every expert in VRAM) + # an Alchemist has no FP64 hardware: a kernel that declares double (one is on the sampled path) is refused at its + # first launch - "'double' is not supported in ... device", the engine dies on the first request with a + # temperature - unless the driver emulates it (docs/INTEL.md) + env.update({"IGC_EnableDPEmulation": "1", "OverrideDefaultFP64Settings": "1", "NEOReadDebugKeys": "1"}) if exe != ROOT / "build-sycl-aot" / "strata": - env["STRATA_SYCL_BIN"] = str(exe.relative_to(ROOT)) + env["STRATA_SYCL_BIN"] = exe.relative_to(ROOT).as_posix() if MOUNT.resolve() != ROOT.parent.resolve(): env["STRATA_SYCL_ROOT"] = str(MOUNT) if env: @@ -185,8 +212,11 @@ def install(argv) -> None: def say_intel(msg=""): """setup's words for its AMD path and its RAM rule, said for the Intel card.""" msg = str(msg).replace("(AMD, experimental: docs/AMD_HIP.md)", "(Intel Arc: the SYCL port, docs/INTEL.md)") - msg = msg.replace("Your AMD GPUs:", "Your Intel GPUs:").replace("just run ./setup.sh", "just run sycl/setup_intel.py") - msg = msg.replace(f"RAM: {fake_ram:.0f} GB", f"RAM: {real_ram:.0f} GB (the experts are streamed into VRAM)") + msg = msg.replace("Your AMD GPUs:", "Your Intel GPUs:").replace("just run ./setup.sh", "just run ./setup.sh --backend sycl") + msg = re.sub(r"\b(xe|i915) \(AMD: docs/AMD_HIP\.md\)", r"\1 driver (Intel Arc: docs/INTEL.md)", msg) + where = ("the experts are loaded into RAM, the card computes the ones it holds" if intel[0]["driver"] == "i915" + else "the experts are streamed into VRAM") + msg = msg.replace(f"RAM: {fake_ram:.0f} GB", f"RAM: {real_ram:.0f} GB ({where})") if re.match(r"\s+\S+\s+needs ~\d+ GB RAM:", msg): # --check's CUDA verdicts: replaced by the Intel one m = msg.split()[0] d = S.MODELS.get(m, {}) @@ -205,11 +235,23 @@ def install(argv) -> None: S.hipblaslt_table = lambda *a, **k: None S.ram_gb = lambda: fake_ram # the experts are in VRAM: setup's RAM rule does not apply + bench_tips = S.bench_tips + + def bench_tips_intel(args, env, ram, *a, **k): + """The tips as written for the CUDA engine, said with the real RAM (the 1024 GB above is only for the RAM rule); + the --prefill auto:32768 one was measured on the CUDA engine and is left out.""" + return [t for t in bench_tips(args, env, real_ram, *a, **k) if "auto:32768" not in t] + S.bench_tips = bench_tips_intel + write = S.write_run_script def write_run_script(model, cfg_path, port, open_browser=True): # setup.write_run_script's signature (#870) cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8")) - cfg = to_sycl(cfg, exe, real_ram, keep.get(Path(cfg_path).name, {}), intel[0]["vram_gb"]) + cfg = to_sycl(cfg, exe, real_ram, keep.get(Path(cfg_path).name, {}), intel[0]["vram_gb"], intel[0]["driver"]) + need = S.MODELS.get(model, {}).get("ram_gb", 0) + if intel[0]["driver"] == "i915" and need and real_ram < need: + S.warn(f"{model} on this Arc loads its experts into RAM (about {need} GB; this PC has {real_ram:.0f} GB): " + "the start will be slow or fail - a smaller model (--model) fits better (docs/INTEL.md)") Path(cfg_path).write_text(json.dumps(cfg, indent=1), encoding="utf-8") script = write(model, cfg_path, port, open_browser) script.write_text(script.read_text().replace(str(ROOT / "serve" / "server.py"), str(SERVER))) @@ -227,6 +269,12 @@ def install(argv) -> None: os.execv("/bin/sh", ["/bin/sh", str(script)]) S.start = start_sycl + argv = list(argv) + if small_card(intel[0]["vram_gb"], intel[0]["driver"]): # the engine's own advice for a card this size + if "--draft-vocab" not in argv: + argv += ["--draft-vocab", "en"] # ~110 MiB less VRAM than the default CJK subset + if "--vram-reserve-mib" not in argv: + argv += ["--vram-reserve-mib", str(SMALL_RESERVE_MIB)] sys.argv = [str(ROOT / "setup.py"), *argv] if "--backend" not in argv: sys.argv += ["--backend", "hip"] diff --git a/tools/test_setup_sycl.py b/tools/test_setup_sycl.py index ede0bed1..173d0fdc 100644 --- a/tools/test_setup_sycl.py +++ b/tools/test_setup_sycl.py @@ -127,5 +127,54 @@ class IntelIds(unittest.TestCase): self.assertEqual(t["e221"][0], "Arc Pro B60") +class ToSycl(unittest.TestCase): + """The config sycl/setup_intel.py writes: an explicit --vram-reserve-mib is kept, the B-series streams its experts, + the A-series (i915) cannot (a single pinned host allocation above a few GB fails there) and loads them into RAM.""" + + @staticmethod + def mod(): + import importlib.util + spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py") + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + def cfg(self, m, extra=()): + base = m.MOUNT + return {"exe": "x", "cwd": "y", "args": ["--pack", str(base / "d" / "pack"), "--native", str(base / "d" / "a.gguf"), + "--expert-cache", "auto", "--prefill", "auto", "--max-context", "32768", + "--kv", "int8", *extra]} + + def test_b_series_streams_and_defaults_the_reserve(self): + m = self.mod() + c = m.to_sycl(self.cfg(m), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe") + self.assertIn("--stream-experts", c["args"]) + self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "1024") + self.assertNotIn("STRATA_VERIFY_NO_HOST", c.get("env", {})) + + def test_an_explicit_reserve_is_kept_on_both_drivers(self): + m = self.mod() + for vram, drv in ((32.0, "xe"), (8.0, "i915")): + c = m.to_sycl(self.cfg(m, ["--vram-reserve-mib", "500"]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, vram, drv) + self.assertEqual(c["args"].count("--vram-reserve-mib"), 1) + self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "500") + + def test_a_series_loads_experts_into_ram_and_leaves_no_host_off(self): + m = self.mod() + c = m.to_sycl(self.cfg(m), m.ROOT / "build-sycl" / "strata", 64.0, {}, 8.0, "i915") + self.assertNotIn("--stream-experts", c["args"]) + self.assertEqual(c["args"][c["args"].index("--ple-io") + 1], "ram") + self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "300") + self.assertEqual(c["env"]["STRATA_VERIFY_NO_HOST"], "0") + self.assertEqual(c["env"]["STRATA_SYCL_BIN"], "build-sycl/strata") + + def test_small_card_rule(self): + m = self.mod() + self.assertTrue(m.small_card(8.0, "i915")) + self.assertTrue(m.small_card(24.0, "i915")) + self.assertTrue(m.small_card(10.0, "xe")) + self.assertFalse(m.small_card(32.0, "xe")) + + if __name__ == "__main__": unittest.main()