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 upstream main (engine 0.1.31) into b70
maxfridbee533380d9822
diff --cc serve/server.pyindex 4dbf76c06,af6665701..dc5466d4b--- a/serve/server.py+++ b/serve/server.py@@@ -1402,16 -1614,21 +1640,29 @@@ def make_handler(svc: Service)if path == "/settings":self._settings()return+ if path == "/switcher": # the web app's model menu: ask the host to swap models+ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")+ self._json(200, model_switcher(svc, str(req.get("mode") or "")))+ return+ if path == "/unload": # give the GPU back now (between requests)+ r = svc.unload()+ self._json(409 if r == "busy" else 200, {"status": r})+ return+ if path == "/load": # load now, e.g. ahead of a request+ try:+ svc.load()+ self._json(200, {"status": "loaded"})+ except GpuBusy as e:+ self._json(503, {"error": {"type": "server_error", "message": str(e)}})+ returntry:req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")- if path in ("/v1/chat/completions", "/v1/messages"): # who asked: a later "disconnect" names its client+ if path in ("/v1/chat/completions", "/v1/messages"):++ # who asked: a later "disconnect" names its client+ print(f"[strata] request {path} from {self.client_address[0]} "+ f"({self.headers.get('User-Agent', '?')[:60]}), stream={bool(req.get('stream'))}, "+ f"max_tokens={req.get('max_tokens') or req.get('max_completion_tokens')}", flush=True)+ svc.load() # unloaded: load first (or 503 while the GPU is busy)if path == "/v1/chat/completions":self._openai(req)elif path == "/v1/messages":@@@ -1810,10 -2023,19 +2074,23 @@@ def main() -> intfile=sys.stderr)return 2svc.api_key = a.api_key or cfg.get("api_key", "")+ # A host that runs one model at a time and swaps them (a GPU shared with other work) can name the RPC that does+ # the swap: the web app then offers the models served on this port. {"mode": m} switches, {} only reports.+ svc.switcher = cfg.get("model_switcher") or None+ svc.port = a.port+ svc.idle_unload_s = a.idle_unload if a.idle_unload is not None else float(cfg.get("idle_unload_s") or 0)+ svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \+ int(cfg.get("min_free_vram_mib") or 0)+ svc.before_load = a.before_load or cfg.get("before_load") or None+ if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request+ try:+ svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"]+ budget = svc.reasoning_budget({})+ except ValueError as e:+ raise SystemExit(f"[strata] config {e}")+ if budget:+ print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)",+ flush=True)svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)if a.config: # the Chat settings shared with other apps, from last timediff --cc setup.pyindex c0431365d,eac1f554d..47e0c8b69--- a/setup.py+++ b/setup.py@@@ -1883,23 -2066,24 +2217,30 @@@ def main() -> intgpu = 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))+ chosen = [gpu]else: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]+ chosen = [gpu]+ # the engine is compiled for every chosen card's architecture+ gpu = {**gpu, "count": len(amd), "archs": sorted({g["arch"] for g in chosen})}+ chosen = [gpu] + chosen[1:]+ sel = [g["index"] for g in chosen]+ multi = sel if len(sel) > 1 else []a.gpu = gpu["index"] if len(amd) > 1 else a.gpu+ if multi:+ ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, {gpu['arch']} (AMD, experimental: docs/AMD_HIP.md)")+ elif backend in ("llama", "sycl"):+ 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 ""))+ + (f"; AMD ({', '.join(AMD_ARCHS)}): --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@@@ -1985,35 -2153,22 +2327,25 @@@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 in ("llama", "sycl") else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"+ if backend not in ("llama", "sycl") 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}%)"+ fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%, "+ + ("the rest in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) else "the rest from the SSD)"))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]- low_ram = backend not in ("llama", "sycl") and (a.low_ram == "on" or (a.low_ram == "auto" and low_ram_needed(model, ram)))- low_ram = a.low_ram in ("on", "resident", "mmap") or (a.low_ram == "auto" and low_ram_needed(model, ram))++ # the low-RAM mode is the CUDA/HIP engines' (experts in RAM); on Intel the experts live in VRAM (step 1)++ low_ram = backend not in ("llama", "sycl") and (++ a.low_ram in ("on", "resident", "mmap") 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")+ for line in low_ram_one_gpu_why(model, ram, a.low_ram):+ say(" " + line)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 backend not in ("llama", "sycl") 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")- # (the low-RAM mode's variant is decided once the context is known, below)- if not low_ram and ram < MODELS[model]["ram_gb"] - 4:++ # (the low-RAM mode's variant is decided once the context is known, below). The experts-in-RAM rule is the CUDA++ # engine's; on llama.cpp and the SYCL port the fit is VRAM (step 1)++ if not low_ram and backend not in ("llama", "sycl") and ram < MODELS[model]["ram_gb"] - 4:+ confirm_paging(model, ram, a.low_ram, a.yes)ok(f"size: {model}")tag = fam["tag"] + model # names of the pack, config and start scriptsmall = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context@@@ -2219,74 -2399,55 +2599,85 @@@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 scaling is not None: # the resolved config: explicit flags as given, or the automatic yarn+factor- args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"]- if ctx > 8192:- args += ["--kv", kv]- engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())- if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE:- resident = False # an engine from before --resident-experts would refuse it- ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through "- "the OS file cache (run setup again after the next engine update)")- if low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped- args += ["--resident-experts" if resident else "--mmap-experts"]- # 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): only a table for this card's arch AND the installed hipBLASLt version (the- # engine refuses any other one and falls back to plain hipBLAS)- table = hipblaslt_table(gpu["arch"], lib_dirs)- if table:- cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)}- if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable- cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0"+ args = []- if backend != "llama": # the CUDA engine's command line; nothing here applies to llama-server++ if backend != "llama": # the 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 scaling is not None: # the resolved config: explicit flags as given, or the automatic yarn+factor++ args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"]+ if ctx > 8192:+ args += ["--kv", kv]- if low_ram:- args += ["--mmap-experts"] # the experts from the pack's experts.bin, not copied into RAM++ engine_ver = (tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())++ if resident else ()) # `meta` is the CUDA/HIP engine's build stamp (no SYCL/llama.cpp counterpart)++ if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE:++ resident = False # an engine from before --resident-experts would refuse it++ ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through "++ "the OS file cache (run setup again after the next engine update)")++ if low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped++ args += ["--resident-experts" if resident else "--mmap-experts"]+ # 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"]+ if backend == "sycl":+ # the container's paths, experts read from the GGUF (no host copy: every expert must fit VRAM, so the reserve+ # is the smallest that leaves the KV and the prompt buffers room - docs/INTEL.md). KV streaming from 64K up- # keeps them all there: the B70 at 256K decodes at 31 tok/s with it, 4-5 without. Its RAM check above is the++ # keeps them all there: the B70 at 256K decodes at 54 tok/s with it, 4-9 without. Its RAM check above is the+ # CUDA engine's (experts in RAM); here the experts are in VRAM, so only the KV copy and the engine count.+ kv_ram = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9+ if kv != "k8v4" and ctx >= 65536 and "--kv-resident" not in args and ram >= kv_ram + 6:+ args += ["--kv-resident", "32768"]+ ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram:.1f} GB), every expert stays in VRAM")+ for flag in ("--pack", "--native", "--ple-gguf", "--expert-profile", "--mtp"):+ if flag in args:+ args[args.index(flag) + 1] = sycl_path(args[args.index(flag) + 1])+ args += ["--stream-experts", "--vram-reserve-mib", "1024" if ctx <= 32768 else "2048"]+ if ctx > 32768:+ args += ["--prefill", "4096"] if "--prefill" not in args else []+ args[args.index("--prefill") + 1] = "4096" # long contexts: 4096-token chunks keep the borrowed slots small+ cfg = {"engine": "strata", "backend": "sycl", "exe": str(SYCL_WRAPPER), "args": args, "cwd": str(ROOT),+ "sycl_root": str(ROOT.parent), "tokenizer": str(pack / "tokenizer"),+ "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"),+ "port": port}+ if sycl_exe != ROOT / "build-sycl-aot" / "strata":+ cfg["env"] = {"STRATA_SYCL_BIN": str(sycl_exe.relative_to(ROOT))}+ elif 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])}++ # prompt speed on the 7900 XTX): only a table for this card's arch AND the installed hipBLASLt version (the++ # engine refuses any other one and falls back to plain hipBLAS)++ table = hipblaslt_table(gpu["arch"], lib_dirs)++ if table:++ cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)}++ if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable++ cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0"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