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 f-mac-rel (Mac Metal support) into f-144-rel

Niko12216a74320caa0a
diff --cc setup.py
index daa5e0612,9c8031ee1..c6a36766d
--- a/setup.py
+++ b/setup.py
@@@ -5389,243 -4867,12 +5396,245 @@@ def sycl_setup(argv) -> int
return subprocess.call([sys.executable, str(script), *rest])
+def engine_step(a, gpu, hip, amd, cuda_tk, vision):
+ """Step 4: llama.cpp's sources and the engine (ready-made, or compiled here). Returns (llama, engine folder, its
+ BUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice)."""
+ llama = get_llama_cpp()
+ ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)")
+ if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler)
+ eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu)
+ if eng is None:
+ fail("no ready-made AMD engine for this Strata version" + (" (--build)" if a.build else ""),
+ "compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run "
+ "START-HERE.bat --backend hip --prebuilt <its dist folder> (docs/AMD_HIP.md)")
+ gpu = hip_card(eng, gpu, amd)
+ a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu
+ else:
+ eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12
+ else {}))
+ if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local":
+ pip_cuda_libs(cuda_tk)
+ if vision != "none" and not (eng / VEXE).exists():
+ warn("the ready-made engine has no image encoder: compiling it")
+ eng = None
+ else:
+ vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text(encoding="utf-8")), gpu, vision)
+ if eng is None:
+ eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk)
+ meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8"))
+ if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH
+ lib_dirs = [str(d) for d in hip_lib_dirs(eng)]
+ else:
+ lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk)
+ return llama, eng, meta, lib_dirs, gpu, vision
+
+
+def engine_families(eng: Path) -> set:
+ """The model families an engine runs (`strata --families`; an engine from before it: Flash-Next's only)."""
+ try:
+ text = subprocess.run([str(eng / EXE), "--families"], capture_output=True, text=True, timeout=60).stdout
+ except (OSError, subprocess.SubprocessError):
+ return {"qwen4exp"}
+ names = set(text.split())
+ return names if "qwen4exp" in names else {"qwen4exp"}
+
+
+def own_path_context(fam: dict, vram_gb: float) -> int:
+ """The recommended context for an own-path family: its KV cache (VRAM) beside the dense weights and the most-used
+ experts - 32K up to 16 GB, 64K up to 24 GB, 128K above."""
+ return 32768 if vram_gb <= 16.5 else 65536 if vram_gb <= 24.5 else 131072
+
+
+def own_path_size(fam: dict, ram: float) -> str:
+ """The recommended size: the largest file whose RAM need this PC has (the smallest when none fits)."""
+ fits = [m for m, d in fam["models"].items() if ram >= d["ram_gb"]]
+ return max(fits, key=lambda m: fam["sha256"][fam["file"].format(q=m)][0]) if fits else next(iter(fam["models"]))
+
+
+def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
+ """Steps 2-7 for a family with its own engine path (OWN_PATH_FAMILIES: Qwen3.6-35B-A3B): the size, the context, the
+ engine, the GGUF (pinned revision, size and SHA-256), the tokenizer from the GGUF, the config and the start
+ script. The engine places the experts itself (every one in VRAM when they fit, else the most-used ones there and
+ the rest on the CPU), so there is no pack, profile or RAM budget to choose."""
+ fam = OWN_PATH_FAMILIES[family]
+ say()
+ say(f" {fam['title']} - {fam['by']}: {fam['about']}")
+ ok(f"model: {fam['title']}")
+ if fam.get("license"):
+ say(f" Its license: {fam['license']}")
+ if multi:
+ warn(f"{fam['title']} runs on one GPU so far: using GPU {gpu.get('index', 0)} ({gpu_name(gpu)}) only")
+ names = list(fam["models"])
+ if a.model and a.model not in names:
+ fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names))
+ say()
+ for i, m in enumerate(names, 1):
+ d = fam["models"][m]
+ size = fam["sha256"][fam["file"].format(q=m)][0]
+ fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"
+ say(f" {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}")
+ rec = own_path_size(fam, ram)
+ if not a.model:
+ say(f" Recommended for {ram:.0f} GB of RAM: {rec} (the largest that fits; any size can be chosen)")
+ model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)],
+ str(names.index(rec) + 1), a.yes)) - 1]
+ if ram < fam["models"][model]["ram_gb"]:
+ confirm_risk(f"{model} needs about {fam['models'][model]['ram_gb']} GB of RAM; this PC has {ram:.0f} GB: the "
+ "OS may page and it may not start", bool(a.model), a.yes,
+ f"{model} needs about {fam['models'][model]['ram_gb']} GB of RAM",
+ f"choose a smaller size, or --model {model} --yes to install it anyway", " Install it anyway?")
+ warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose")
+ ok(f"size: {model}")
+ tag = fam["tag"] + model
+ rec_ctx = own_path_context(fam, gpu.get("vram_gb", 0.0))
+ if a.context:
+ ctx = a.context
+ else:
+ ctxs = [c for c in CONTEXTS if c <= 262144] # the model's trained length; no rope scaling on this path yet
+ say()
+ say(" Context length = how much text the model can see at once. Its cache takes "
+ f"{fam['kv_bytes_per_token'] * 32768 / 2**30:.1f} GB of VRAM per 32K tokens, room the experts would use:")
+ for i, c in enumerate(ctxs, 1):
+ say(f" {i}) {c // 1024}K tokens" + (" (recommended for your GPU)" if c == rec_ctx else ""))
+ ctx = ctxs[int(ask("Context?", [str(i) for i in range(1, len(ctxs) + 1)], str(ctxs.index(rec_ctx) + 1),
+ a.yes)) - 1]
+ if ctx > 262144:
+ warn(f"{ctx // 1024}K is past {fam['title']}'s trained 262,144 positions and this engine path has no rope "
+ "scaling yet: kept as you chose, but answers past 256K are untested")
+ ok(f"context: {ctx} tokens")
+ if a.vision not in (None, "no", "none"):
+ warn(f"images are not available with {fam['title']} yet: off")
+ if a.rope_scaling or a.rope_scale or a.kv or a.resident_budget_gib is not None or a.low_ram not in (None, "auto"):
+ warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} "
+ "does not use them")
+ folder = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag
+ gguf = folder / fam["file"].format(q=model)
+ size = fam["sha256"][gguf.name][0]
+ part = gguf.with_name(gguf.name + ".part")
+ left = 0 if gguf.exists() and done(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9
+ if left and free_gb(folder) < left + 1:
+ fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive")
+
+ step(3, "Python packages")
+ pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES,
+ "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil")
+
+ step(4, "the Strata engine")
+ llama, eng, meta, lib_dirs, gpu, _ = engine_step(a, gpu, hip, amd, cuda_tk, "none")
+ if fam["arch"] not in engine_families(eng):
+ fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet",
+ "update Strata, or compile the engine with --build, and run setup again")
+ ok(f"engine: {eng / EXE}")
+
+ step(5, f"downloading {fam['title']} {model}")
+ if gguf.exists() and done(gguf):
+ ok(f"{gguf.name} already downloaded")
+ else:
+ if a.gguf_dir:
+ fail(f"{gguf} is missing", f"put {gguf.name} in {folder}, or drop --gguf-dir to download it")
+ download(fam["hf"] + gguf.name, gguf)
+ verify_sha256(gguf, *fam["sha256"][gguf.name])
+ ok(f"model file: {gguf}")
+
+ step(6, "preparing the model for Strata")
+ data, _ = data_folder(a.data_dir)
+ pack = data / "packs" / tag.lower() # only the tokenizer: the engine reads the GGUF itself
+ if not (pack / "tokenizer" / "vocab.json").exists():
+ run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(gguf), "--out", str(pack)],
+ env=dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py")))
+ ok(f"tokenizer: {pack / 'tokenizer'}")
+
+ step(7, "writing the start script")
+ args = ["--native", str(gguf), "--max-context", str(ctx), "--prefill", "auto", "--mtp", str(fam["mtp"])]
+ if a.vram_reserve_mib is not None: # VRAM left free for other programs: the experts take that much less
+ vram = gpu.get("vram_gb", 0.0)
+ if vram > 0:
+ args += ["--expert-vram", f"{max(vram - 3.0 - a.vram_reserve_mib / 1024, 0):.1f}"]
+ ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)")
+ cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
+ "model_name": f"{fam['name']}-{model.lower()}", "arch": fam["arch"],
+ "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port}
+ if cuda_tk == 12:
+ cfg["cuda"] = 12
+ if hip:
+ cfg["backend"] = "hip"
+ if gpu.get("count", 1) > 1 or a.gpu is not None:
+ cfg["gpu"] = gpu["index"]
+ cfg["gpus_asked"] = True
+ if a.host:
+ cfg["host"] = a.host
+ if a.api_key:
+ cfg["api_key"] = a.api_key
+ if a.browser is not None:
+ cfg["open_browser"] = a.browser
+ cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too
+ cfg_path = ROOT / f"strata-{tag.lower()}.json"
+ write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None)
+ script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False)
+ ok(f"start script: {script.name}")
+ say()
+ say("All set.")
+ say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)")
+ say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages")
+ say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")
+ if a.no_start:
+ return 0
+ return start(cfg_path, port)
+
+
+def preview_family(a) -> int:
+ """--family qwen36: a family setup knows but the engine does not run yet (PREVIEW_FAMILIES). Downloads the chosen
+ size (pinned revision, size and SHA-256 checked) and, with --vision, the image encoder - and says plainly that
+ Strata cannot start it yet. Nothing is configured: no engine, no pack, no start script."""
+ fam = PREVIEW_FAMILIES[a.family]
+ names = list(fam["models"])
+ say()
+ say(f" {fam['title']} - {fam['by']}: {fam['about']}")
+ warn(f"this Strata version does not run {fam['title']} yet (support is in development): setup downloads its "
+ "files, and the engine refuses them with a message until a version that runs it")
+ if a.model and a.model not in names:
+ fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names))
+ ram = ram_gb()
+ for i, m in enumerate(names, 1):
+ d = fam["models"][m]
+ size = fam["sha256"][fam["file"].format(q=m)][0]
+ fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"
+ say(f" {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}")
+ if a.check:
+ return 0
+ model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], "1", a.yes)) - 1]
+ say(f" Its license: {fam['license']}")
+ want = [fam["file"].format(q=model)]
+ if a.vision in ("yes", "gpu", "cpu"):
+ want.append(fam["mmproj"])
+ folder = Path(a.models_dir) / (fam["tag"] + model)
+ files = [folder / w for w in want]
+ left = sum(fam["sha256"][f.name][0] - (f.with_name(f.name + ".part").stat().st_size
+ if f.with_name(f.name + ".part").is_file() else 0)
+ for f in files if not (f.exists() and done(f))) / 1e9
+ if left and free_gb(folder) < left + 1:
+ fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive")
+ step(5, f"downloading {fam['title']} {model}")
+ for f in files:
+ url = (fam["mmproj_hf"] if f.name == fam["mmproj"] else fam["hf"]) + f.name
+ download(url, f, "vision encoder" if f.name == fam["mmproj"] else None)
+ verify_sha256(f, *fam["sha256"][f.name])
+ ok(f"{fam['title']} {model}: {folder}")
+ say()
+ say(f"{fam['title']} is downloaded, but this Strata version cannot run it yet (its engine path is in "
+ "development); nothing was configured. Run setup again without --family qwen36 to install a model it runs.")
+ return 0
+
+
def main() -> int:
+ if sys.platform == "darwin": # a Mac: metal/setup_mac.py (the Metal engine)
+ return mac_setup(sys.argv[1:])
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- 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("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES),
+ help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5 (qwen36 = Qwen3.6-35B-A3B: download only, the "
+ "engine does not run it yet)")
+ ap.add_argument("--model", choices=list(dict.fromkeys([*MODELS, *(m for f in PREVIEW_FAMILIES.values()
+ for m in f["models"])])))
ap.add_argument("--context", type=int)
ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"],
help="the RoPE extension for a context past the model's trained 262144: linear (position "
diff --cc src/core/mtp.cpp
index 9fbaef087,1fc3ff0a9..c550c7322
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@@ -1450,41 -1316,22 +1476,55 @@@ bool MtpDrafter::prefill(const float* R
return true;
}
+// STRATA_DRAFT_TIMING=1: where a draft round's time goes, from cudaEvent pairs around each graph launch (GPU time of the round
+// graph and of each step, and the idle gap the host's decision leaves between two steps) and the host's own wall time.
+namespace {
+struct DraftTiming {
+ bool on = false;
+ cudaEvent_t eb[16] = {}, ea[16] = {};
+ double round_ms = 0, step_ms = 0, gap_ms = 0, wall_ms = 0, tail_ms = 0;
+ double pre_ms = 0, launch_ms = 0, ple_ms = 0, wait0_ms = 0, waitj_ms = 0; // host: staging, graph launch calls, PLE prefetch, spins
+ int64_t rounds = 0, steps = 0;
+ DraftTiming() {
+ const char* e = std::getenv("STRATA_DRAFT_TIMING");
+ on = e != nullptr && e[0] == '1';
+ }
+ void init() {
+ if (!on || eb[0] != nullptr) return;
+ for (int i = 0; i < 16; ++i)
+ if (cudaEventCreate(&eb[i]) != cudaSuccess || cudaEventCreate(&ea[i]) != cudaSuccess) { on = false; (void) cudaGetLastError(); return; }
+ }
+ void report() const {
+ if (rounds == 0) return;
+ const double r = (double) rounds;
+ std::fprintf(stderr, "strata mtp draft timing: %lld rounds, %.2f steps/round: wall %.3f ms = round graph %.3f + steps %.3f GPU "
+ "(%.3f per step) + host gaps between graphs %.3f + tail %.3f (per round)\n",
+ (long long) rounds, (double) steps / r, wall_ms / r, round_ms / r, step_ms / r,
+ steps > 0 ? step_ms / (double) steps : 0.0, gap_ms / r, tail_ms / r);
+ std::fprintf(stderr, "strata mtp draft timing (host, per round): staging %.3f, graph launch calls %.3f, PLE prefetch %.3f, "
+ "wait for draft 0 %.3f, waits for the steps %.3f\n",
+ pre_ms / r, launch_ms / r, ple_ms / r, wait0_ms / r, waitj_ms / r);
+ }
+};
+DraftTiming g_dt;
+} // namespace
+
bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err,
float* probs, float min_p, int* n_drafts) {
+ #if defined(STRATA_GPU_METAL)
+ {
+ if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; }
+ const int max_steps = (int) std::min<int64_t>(std::min(max_t_ - 1, max_drafts_), (int64_t) 1 << 30);
+ const Clock::time_point t0 = Clock::now();
+ int n = 0;
+ if (!strata::metal_engine::mtp_draft(T, tokens, p, a, max_steps, drafts, probs, min_p, &n, err)) return false;
+ for (int j = n; j < max_t_ - 1; ++j) { drafts[j] = 0; if (probs) probs[j] = 0.0f; }
+ if (n_drafts) *n_drafts = n;
+ ms_draft += ms_since(t0);
+ ++rounds;
+ return true;
+ }
+ #endif
const OnDevice on_device(device_);
if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; }
if (chain_live_) { err = "mtp: a pipelined chain is still in flight"; return false; }