Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Merge remote-tracking branch 'origin/main' into b70

maxfridbeac14e76bf5cf
diff --cc setup.py
index 477e550ad,0c30e2441..380d53d00
--- a/setup.py
+++ b/setup.py
@@@ -1349,8 -1485,48 +1572,48 @@@ def start(cfg_path: Path, port: int | N
return subprocess.call(cmd)
+ # the draft subsets setup copied before (sha256): replaced by the current one, a subset made by hand is kept
+ OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens
+
+
+ def refresh_draft_vocab(rt: Path) -> None:
+ """The draft layer's token subset (data/draft_vocab.bin) in the MTP folder: copied when missing, and an older
+ shipped one is replaced, so an update reaches existing installs (0.1.27 added the CJK scripts, #137)."""
+ new, dst = ROOT / "data" / "draft_vocab.bin", rt / "draft_vocab.bin"
+ if not new.exists() or not rt.is_dir():
+ return
+ if dst.exists():
+ old = hashlib.sha256(dst.read_bytes()).hexdigest()
+ if old not in OLD_DRAFT_VOCABS or old == hashlib.sha256(new.read_bytes()).hexdigest():
+ return
+ ok("draft layer: the token subset now includes Chinese, Japanese and Korean")
+ shutil.copyfile(new, dst)
+
+
+ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict:
+ """The installed engine must have code for every card the model starts on: a card added later (--gpus with an
+ older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a
+ card gets the engine compiled for all of them, before the start."""
+ missing = [g for g in cards if not engine_runs_on(g)]
+ if not missing:
+ return cfg
+ info = ROOT / "engine" / "BUILD.json"
+ meta = json.loads(info.read_text())
+ say()
+ say(" The installed engine has no code for " + ", ".join(f"{g['name']} (sm_{g['arch']})" for g in missing) +
+ ": it is compiled for " + ("these cards" if len(cards) > 1 else "it") + " now.")
+ main = gpu_info(cards[0]["index"])
+ archs = sorted({int(x) for x in meta.get("archs", [])} | {int(g["arch"]) for g in cards})
+ vision = meta.get("vision") or ("gpu" if (ROOT / "engine" / VEXE).exists() else "none")
+ build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp())
+ dirs = json.loads(info.read_text()).get("cuda_dirs") or []
+ cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs]
+ cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
+ return cfg
+
+
-def write_run_script(model, cfg_path, port):
- serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
+def write_run_script(model, cfg_path, port, engine="strata"):
+ serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", engine, "--config", str(cfg_path),
"--port", str(port), "--open"]
if WIN:
script = ROOT / f"run-{model.lower()}.bat"
@@@ -1370,12 -1546,9 +1633,12 @@@ def main() -> int
ap.add_argument("--family", choices=list(FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5")
ap.add_argument("--model", choices=list(MODELS))
ap.add_argument("--context", type=int)
- ap.add_argument("--kv", choices=["int8", "q4_0"],
- help="KV cache precision above 8K context: int8 (default) or q4_0 (half the memory, a little less "
- "precise)")
+ ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"],
+ help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less "
+ "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)")
+ ap.add_argument("--llama-server", metavar="PATH|IMAGE",
+ help="Intel Arc only: the llama-server to run the model with (a binary built with -DGGML_SYCL=ON, "
+ "or a container image); default: one on PATH, else the B70 image via docker")
ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"],
help="let the model read images (yes = the encoder on the GPU)")
ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF",
@@@ -1475,29 -1654,49 +1744,65 @@@
# ---- 1. the PC
step(1, "checking your PC")
found = gpus()
+ backend = "cuda"
- if not found:
- intel = intel_gpus()
- if intel:
- backend = "llama"
- g = max(intel, key=lambda x: x["vram_gb"])
- ok(f"Intel {g['name']} ({g['vram_gb']:.0f} GB): using llama.cpp's SYCL backend instead of the CUDA engine")
- if a.vision not in (None, "no", "none"):
- warn("images are not wired on the llama.cpp engine yet: continuing without vision")
- a.vision = "none"
- found = intel
+ amd = [] if WIN else amd_gpus()
+ nv_ok = any(gpu_problem(g) is None for g in found)
+ amd_ok = [g for g in amd if amd_problem(g) is None]
+ hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok))
++ intel = [] if found or a.backend == "hip" or WIN else intel_gpus() # no NVIDIA card: an Intel Arc runs llama.cpp
++ if intel:
++ backend = "llama"
++ g = max(intel, key=lambda x: x["vram_gb"])
++ ok(f"Intel {g['name']} ({g['vram_gb']:.0f} GB): using llama.cpp's SYCL backend instead of the CUDA engine")
++ if a.vision not in (None, "no", "none"):
++ warn("images are not wired on the llama.cpp engine yet: continuing without vision")
++ a.vision = "none"
++ found = intel
+ if a.backend is None and nv_ok and amd_ok:
+ # both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon)
+ say()
+ say(" This PC has NVIDIA and AMD cards Strata can use:")
+ say(" 1) NVIDIA: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in found if gpu_problem(g) is None)
+ + " (recommended)")
+ say(" 2) AMD: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in amd_ok)
+ + " (experimental: compiled here, one GPU, no images - docs/AMD_HIP.md)")
+ hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2"
+ if a.check and not hip:
+ say(" (the AMD card: ./setup.sh --backend hip)")
+ if hip: # AMD (experimental): one card, compiled here
+ if WIN:
+ fail("Strata's AMD backend runs on Linux only", "use an NVIDIA RTX 20 series or newer card on Windows")
+ say(" Your AMD GPUs:" if amd else " No AMD GPU found (the amdgpu driver's KFD topology is empty).")
+ for g in amd:
+ say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + (amd_problem(g) or "can be used"))
+ usable = [g for g in amd if amd_problem(g) is None]
+ if not usable:
+ fail("no AMD GPU Strata can use", "the AMD backend runs on the RX 7900 XT / XTX (gfx1100) on Linux")
+ if a.gpus:
+ fail("several GPUs sharing one model: NVIDIA only for now", "use one AMD card (--gpu N)")
+ if a.gpu is not None:
+ gpu = next((g for g in usable if g["index"] == a.gpu), None)
+ if gpu is None:
+ fail(f"AMD GPU {a.gpu} cannot be used", "use one of: " + ", ".join(f"--gpu {g['index']}" for g in usable))
else:
- fail("no NVIDIA or Intel Arc GPU found (nvidia-smi did not answer, sycl-ls/lspci show no Arc)",
- "install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC")
- if backend != "llama" and (len(found) > 1 or gpu_problem(found[0]) is not None):
- gpu_table(found) # CUDA compute-capability checks; not for an Intel card
- if backend == "llama":
+ gpu = max(usable, key=lambda x: (round(x["vram_gb"]), -x["index"]))
+ gpu = {**gpu, "count": len(amd), "archs": [gpu["arch"]]}
+ sel, multi, chosen = [gpu["index"]], [], [gpu]
+ a.gpu = gpu["index"] if len(amd) > 1 else a.gpu
+ ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, {gpu['arch']} (AMD, experimental: docs/AMD_HIP.md)")
++ elif backend == "llama":
+ sel, multi = [found[0]["index"]], []
+ a.gpu = sel[0]
+ GPU_PICK = a.gpu
+ gpu = {**found[0], "count": len(found), "archs": ["sycl"]}
+ chosen = [gpu] # the one card the model runs on (no layer split here)
else:
+ if not found:
- fail("no NVIDIA GPU found (nvidia-smi did not answer)",
++ fail("no NVIDIA or Intel Arc GPU found (nvidia-smi did not answer, sycl-ls/lspci show no Arc)",
+ "install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC"
+ + ("; an AMD RX 7900 XT/XTX: --backend hip" if amd else ""))
+ if len(found) > 1 or gpu_problem(found[0]) is not None:
+ gpu_table(found)
sel = choose_gpus(a, found) # asked when two or more cards can share the model
multi = sel if len(sel) > 1 else []
a.gpu = sel[0] # the main GPU: the checks and the sizing below are its
@@@ -1505,11 -1704,8 +1810,11 @@@
gpu = gpu_info(a.gpu)
chosen = [gpu_info(i) for i in sel]
gpu["archs"] = sorted({x["arch"] for x in chosen}) # the engine needs code for every one of them
- if multi:
- ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")
+ if multi:
+ ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")
+ if backend == "llama":
+ ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, {gpu['driver']} driver, SYCL via llama.cpp")
- else:
++ elif not hip:
ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}")
if driver_major(gpu) < MIN_DRIVER:
fail(f"the NVIDIA driver is too old ({gpu['driver']}; {MIN_DRIVER} or newer is needed)",
@@@ -1519,20 -1715,8 +1824,21 @@@
ram = ram_gb()
cpu, avx2, avx512 = cpu_info()
need = min(d["ram_gb"] for d in MODELS.values())
- low_ok = low_ram_fits("IQ1_M", ram, gpu["vram_gb"]) and a.low_ram != "off" # the smallest model, mapped
+ if backend == "llama":
+ # The CUDA engine keeps every expert in RAM. llama.cpp puts the whole first shard on the card and only
+ # the second shard's lookup table (28.8 GB, read by row) in host memory as page cache, so the fit is a
+ # VRAM question: shard 1 = the download minus that table. Below that, experts spill to RAM (slower).
+ need = 8
+ fit = {m: round(d["download_gb"] - 28.8, 1) for m, d in MODELS.items()}
+ best = [m for m, g in fit.items() if g + 1.5 <= gpu["vram_gb"]]
+ if best:
+ ok(f"VRAM: {gpu['vram_gb']:.0f} GB fits the whole model for " + ", ".join(best) +
+ f" (shard 1: " + ", ".join(f"{m} {g} GB" for m, g in fit.items() if m in best) + ")")
+ else:
+ warn(f"VRAM: {gpu['vram_gb']:.0f} GB is less than any shard 1 (" +
+ ", ".join(f"{m} {g} GB" for m, g in fit.items()) + "): experts will spill to RAM and it will be slow")
- if ram < need - 4 and not a.check:
++ low_ok = backend != "llama" and low_ram_fits("IQ1_M", ram, gpu["vram_gb"]) and a.low_ram != "off" # the smallest model, mapped
+ if ram < need - 4 and not a.check and not low_ok:
# every model keeps ALL its experts in RAM (23+ GB); VRAM only holds a copy of the most-used ones, so a
# bigger GPU does not lower this
fail(f"RAM: {ram:.0f} GB - the smallest model (the Coder) needs about {need} GB",
@@@ -1575,22 -1763,34 +1885,34 @@@
fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names))
for i, m in enumerate(names, 1):
d = MODELS[m]
- fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"
- if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":
+ fit = "" if ram >= d["ram_gb"] or backend == "llama" else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"
++ if backend != "llama" and low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":
+ fit = f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%)"
say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}")
rec = str(names.index("IQ3_XXS") + 1) if ram >= 60 and "IQ3_XXS" in names else "1"
model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1]
- if backend != "llama": # the CUDA engine's experts-in-RAM rule; on llama.cpp the fit is VRAM (step 1)
- if ram < MODELS[model]["ram_gb"] - 4:
- # #125: a warning and a question, not a stop: the user may accept paging (asked, "no" by default, so an
- # unattended --yes install still stops here)
- need_gb, arena = MODELS[model]["ram_gb"], MODELS[model]["arena_gb"]
- warn(f"{model} needs about {need_gb} GB of RAM and this PC has {ram:.0f} GB: its experts alone are "
- f"{arena:.0f} GB and must stay in RAM, so Windows/Linux will page part of them from disk. Expect it "
- "to be much slower, and it may not start at all.")
- say(" A smaller size (Q2_0 or IQ2_XS) fits; more RAM fixes it.")
- if ask(" Install it anyway?", ["y", "n"], "n", a.yes) != "y":
- fail(f"{model} needs about {need_gb} GB of RAM; this PC has {ram:.0f} GB",
- "choose Q2_0 or IQ2_XS, or add RAM")
- low_ram = a.low_ram == "on" or (a.low_ram == "auto" and low_ram_needed(model, ram))
++ low_ram = backend != "llama" and (a.low_ram == "on" or (a.low_ram == "auto" and low_ram_needed(model, ram)))
+ if low_ram and multi:
+ warn("the low-RAM mode runs on one GPU: using " + gpu_name(gpu) + " only")
+ multi, sel, chosen = [], [gpu["index"]], [gpu]
+ if low_ram:
+ share = low_ram_gpu_share(model, gpu["vram_gb"])
+ ok(f"low-RAM mode: {model}'s experts ({MODELS[model]['arena_gb']:.0f} GB) are read from the model folder "
+ f"through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPU holds ~{100 * share:.0f}% of them")
+ if share < 0.6:
+ warn("most of the experts are read from the SSD while it answers: expect it to be much slower than with "
+ "enough RAM (a faster SSD and a smaller size help)")
- elif ram < MODELS[model]["ram_gb"] - 4:
++ elif backend != "llama" and ram < MODELS[model]["ram_gb"] - 4: # the CUDA engine's experts-in-RAM rule; on llama.cpp the fit is VRAM (step 1)
+ # #125: a warning and a question, not a stop: the user may accept paging (asked, "no" by default, so an
+ # unattended --yes install still stops here)
+ need_gb, arena = MODELS[model]["ram_gb"], MODELS[model]["arena_gb"]
+ warn(f"{model} needs about {need_gb} GB of RAM and this PC has {ram:.0f} GB: its experts alone are "
+ f"{arena:.0f} GB and must stay in RAM, so Windows/Linux will page part of them from disk. Expect it "
+ "to be much slower, and it may not start at all.")
+ say(" A smaller size (Q2_0 or IQ2_XS) fits; more RAM fixes it.")
+ if ask(" Install it anyway?", ["y", "n"], "n", a.yes) != "y":
+ fail(f"{model} needs about {need_gb} GB of RAM; this PC has {ram:.0f} GB",
+ "choose Q2_0 or IQ2_XS, or add RAM")
warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose")
ok(f"size: {model}")
tag = fam["tag"] + model # names of the pack, config and start script
@@@ -1671,28 -1876,23 +1998,34 @@@
step(4, "the Strata engine")
llama = get_llama_cpp()
ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)")
- eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision)
+ if backend == "llama":
+ kind, server = find_llama_server(a.llama_server)
+ if kind is None:
+ fail("no llama-server found for the Intel card",
+ "build llama.cpp with -DGGML_SYCL=ON and put llama-server on PATH, pass --llama-server PATH, "
+ f"or install docker so the image {LLAMA_IMAGE} can run it")
+ ok(f"engine: llama-server ({'container ' if kind == 'image' else ''}{server})")
+ eng, lib_dirs = None, []
+ else:
+ kind = server = None
- eng = None if a.build else get_prebuilt(a.prebuilt, gpu, vision)
++ eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision)
if eng is not None and json.loads((eng / "BUILD.json").read_text()).get("source") != "local":
pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)")
if vision != "none" and not (eng / VEXE).exists():
warn("the ready-made engine has no image encoder: compiling it")
eng = None
+ elif vision == "gpu": # the encoder can cover fewer cards than the engine (RTX 20)
+ m = json.loads((eng / "BUILD.json").read_text())
+ va = [int(x) for x in m.get("vision_archs", m.get("archs", []))]
+ if va and int(gpu["arch"]) not in va and not (m.get("ptx") and int(gpu["arch"]) > max(va)):
+ warn(f"the ready-made image encoder has no code for your GPU (sm_{gpu['arch']}): compiling it")
+ eng = None
- if eng is None:
- eng = build_engine_hip(gpu, llama) if hip else build_engine(gpu, vision, a.yes, llama)
- meta = json.loads((eng / "BUILD.json").read_text())
- lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs()
- ok(f"engine: {eng / EXE}")
+ if backend != "llama":
+ if eng is None:
- eng = build_engine(gpu, vision, a.yes, llama)
++ eng = build_engine_hip(gpu, llama) if hip else build_engine(gpu, vision, a.yes, llama)
+ meta = json.loads((eng / "BUILD.json").read_text())
- lib_dirs = meta.get("cuda_dirs") or cuda_lib_dirs()
++ lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs()
+ ok(f"engine: {eng / EXE}")
# ---- 5. the model files
step(5, f"downloading {fam['title']} {model}")
@@@ -1746,23 -1941,24 +2079,26 @@@
elif not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists():
# every tensor as the GGUF stores it; the experts are read from the GGUF at start (seconds to build)
run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack)], env=env)
+ if low_ram and not (pack / "experts.bin").exists():
+ say(f" Writing the experts into one file for the low-RAM mode (one time, {MODELS[model]['arena_gb']:.0f} GB) ...")
+ run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack),
+ "--experts-bin"], env=env)
ok(f"model prepared: {pack}")
- mtp = (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent
- rt = mtp / "rt"
- if not (rt / "experts.bin").exists():
- say(" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:")
- say(" only its ~5 GB of MTP tensors are downloaded.")
- run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], env=env)
- run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0",
- "--out", str(mtp / "mtp-q2_0.gguf")], env=env)
- run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)],
- env=env)
- refresh_draft_vocab(rt)
- ok(f"MTP draft layer: {rt}")
-
+ if backend == "llama":
+ ok("MTP draft layer: not used by the llama.cpp engine (no speculative decoding for this model there)")
+ else:
+ mtp = (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent
+ rt = mtp / "rt"
+ if not (rt / "experts.bin").exists():
+ say(" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:")
+ say(" only its ~5 GB of MTP tensors are downloaded.")
+ run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], env=env)
+ run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0",
+ "--out", str(mtp / "mtp-q2_0.gguf")], env=env)
+ run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)],
+ env=env)
- if not (rt / "draft_vocab.bin").exists():
- shutil.copyfile(ROOT / "data" / "draft_vocab.bin", rt / "draft_vocab.bin")
++ refresh_draft_vocab(rt)
+ ok(f"MTP draft layer: {rt}")
# ---- 7. the start script
step(7, "writing the start script")
sys.path.insert(0, str(ROOT / "tools"))
@@@ -1770,39 -1966,45 +2106,52 @@@
ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None)
if ple is None:
fail("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)")
- args = ["--pack", str(pack), "--native", str(shards[0]), "--ple-gguf", str(ple),
- "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto",
- "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt),
- "--max-context", str(ctx)]
- if ctx > 8192:
- args += ["--kv", kv]
- if low_ram:
- args += ["--mmap-experts"] # the experts from the pack's experts.bin, not copied into RAM
- # KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions
- # per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It
- # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits.
- kv_ram_gb = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9 # 12 QSA layers + the draft layer
- # Hybrid K8V4 never streams its KV (mode 0 only, layer.hpp), so it is excluded from the WHOLE streaming
- # decision rather than one threshold at a time - a future tier added to this chain cannot reintroduce the
- # combination the engine refuses (PR review).
- if kv == "k8v4":
- if ctx >= 65536:
- ok("KV streaming off: not supported with --kv k8v4; the KV cache stays in VRAM")
- elif is_wsl() and ctx >= 65536:
- ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM")
- elif ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1:
- args += ["--kv-resident", "32768"]
- ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM")
- if vision != "none":
- args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])]
- if esp is not None:
- # the package's profile, with llama.cpp's flags (the engine takes the same ones)
- args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44",
- "--cvec-mode", "project", "--cvec-dir", "per-layer"]
- cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
- "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"),
- "lib_dirs": lib_dirs, "port": port}
- if hip:
- cfg["backend"] = "hip"
- # the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60%
- # prompt speed on the 7900 XTX); the engine refuses a table made for another hipBLASLt version and falls back
- tables = sorted((ROOT / "tools" / "hip").glob(f"{gpu['arch']}-hipblaslt-*.txt"))
- if tables:
- cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(tables[-1])}
+ args = []
+ if backend != "llama": # the CUDA engine's command line; nothing here applies to llama-server
+ args = ["--pack", str(pack), "--native", str(shards[0]), "--ple-gguf", str(ple),
+ "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto",
+ "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt),
+ "--max-context", str(ctx)]
+ if ctx > 8192:
+ args += ["--kv", kv]
++ if low_ram:
++ args += ["--mmap-experts"] # the experts from the pack's experts.bin, not copied into RAM
+ # KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions
+ # per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It
+ # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits.
+ kv_ram_gb = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9 # 12 QSA layers + the draft layer
- # the RAM copy must be pinned, and under WSL the NVIDIA driver pins only about 1 GB in all
- if is_wsl() and ctx >= 65536:
++ # Hybrid K8V4 never streams its KV (mode 0 only, layer.hpp), so it is excluded from the WHOLE streaming
++ # decision rather than one threshold at a time - a future tier added to this chain cannot reintroduce the
++ # combination the engine refuses (PR review).
++ if kv == "k8v4":
++ if ctx >= 65536:
++ ok("KV streaming off: not supported with --kv k8v4; the KV cache stays in VRAM")
++ elif is_wsl() and ctx >= 65536:
+ ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM")
+ elif ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1:
+ args += ["--kv-resident", "32768"]
+ ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM")
+ if vision != "none":
+ args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])]
+ if esp is not None:
+ # the package's profile, with llama.cpp's flags (the engine takes the same ones)
+ args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44",
+ "--cvec-mode", "project", "--cvec-dir", "per-layer"]
-
+ if backend == "llama":
+ cfg = {"engine": "llama", "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
+ "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"),
+ "port": port, "llama": llama_block(kind, server, shards[0], a.context or 32768, port + 1)}
+ else:
+ cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
+ "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"),
+ "lib_dirs": lib_dirs, "port": port}
++ if hip:
++ cfg["backend"] = "hip"
++ # the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60%
++ # prompt speed on the 7900 XTX); the engine refuses a table made for another hipBLASLt version and falls back
++ tables = sorted((ROOT / "tools" / "hip").glob(f"{gpu['arch']}-hipblaslt-*.txt"))
++ if tables:
++ cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(tables[-1])}
if gpu["count"] > 1 or a.gpu is not None:
cfg["gpu"] = gpu["index"] # the engine is told this card (issue #51)
cfg["gpus_asked"] = True # chosen at setup: not asked again at start
@@@ -1820,16 -2022,16 +2169,16 @@@
if vision == "cpu":
cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2)
cfg_path = ROOT / f"strata-{tag.lower()}.json"
- cal = None if backend == "llama" else saved_calibration(cfg)
- cal = None if hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now
++ cal = None if backend == "llama" or hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now
if cal is not None:
sys.path.insert(0, str(ROOT / "tools"))
import calibrate as CAL
cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {})
ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else ""))
cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
- script = write_run_script(tag, cfg_path, port)
+ script = write_run_script(tag, cfg_path, port, engine="llama" if backend == "llama" else "strata")
# offered only when someone answers: --yes installs and adopted earlier installs are not held up by it
- if cal is None and backend != "llama" and not a.no_start and not a.yes and ask(
- if cal is None and not hip and not a.no_start and not a.yes and ask(
++ if cal is None and backend != "llama" and not hip and not a.no_start and not a.yes and ask(
"Tune Strata for this PC now? It measures a few engine settings (about 5-10 minutes; the PC is busy "
"meanwhile; later: START-HERE --calibrate)", ["y", "n"], "y", a.yes) == "y":
calibrate_config(cfg_path)