diff --git a/README.md b/README.md index 03db4da8..df2ba573 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,23 @@ of [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next). With 64 GB of RAM all three fit (close the browser for IQ3_XXS, and keep its context at 128K or less). With 48 GB only Q2_0 / IQ2_XS may fit. 32 GB is not enough. +### Or: Swift 1.5 (a fine-tune that thinks shorter) + +The setup's first question also offers **[Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF)**, +UkisAI's fine-tune of Qwen3.8-Flash-Next, trained to reach the answer with much less thinking (its authors: 63% fewer +thinking tokens, 1.8x sooner answers, under 1% accuracy loss). Same architecture, the same three sizes, its own +vision encoder; Strata runs it at the same speed (4K, IQ2_XS: 465 prompt / 78.7 output tokens/s, vs 467 / 78.3 for +the original). Its authors recommend **IQ2_XS** (their Q2_0 is marked experimental). Its license is the Swift Open +License 1.0 - read it on the model page. + +Our small check (8 reasoning questions, default thinking, IQ2_XS): both models got **8/8**; Swift used **1,234** +output tokens in 28 s, the original **2,682** in 46 s - most of the difference from one question the original +thought about for 1,524 tokens. Not a benchmark, but consistent with the claim. + +``` +START-HERE.bat --setup --family swift --model IQ2_XS +``` + ## Before you start You need **only an NVIDIA driver** (version 580 or newer; update it with the NVIDIA App or from @@ -99,11 +116,12 @@ Windows, `build-essential` + CUDA on Ubuntu) and compiles the engine for your GP ### Double-click `START-HERE.bat` -**The first time** it asks three questions and does the rest: +**The first time** it asks four questions and does the rest: -1. **Which model?** Q2_0, IQ2_XS or IQ3_XXS (it recommends one for your RAM). -2. **How much context?** 8K to 256K tokens (it recommends one for your VRAM). -3. **Images?** yes / no (see [Images](#images-vision)). +1. **Which model?** Qwen3.8-Flash-Next (the original) or Swift 1.5 (the fine-tune that thinks shorter). +2. **Which size?** Q2_0, IQ2_XS or IQ3_XXS (it recommends one for your RAM). +3. **How much context?** 8K to 256K tokens (it recommends one for your VRAM). +4. **Images?** yes / no (see [Images](#images-vision)). Then it downloads and prepares everything (the model is 66-76 GB, so the first start takes a while; an interrupted download continues where it stopped) and **starts the model**: your browser opens `http://127.0.0.1:8080`, a small @@ -135,7 +153,7 @@ With more than one model installed, it asks which one to start. `run-.bat ./setup.sh ``` -The same three questions, the same automatic install (it uses `sudo apt` for Python and, only if it has to compile, +The same questions, the same automatic install (it uses `sudo apt` for Python and, only if it has to compile, for the build tools), and the same start: `http://127.0.0.1:8080`. Later runs of `./setup.sh` (or `./run-.sh`) start the model directly. Options as on Windows (`./setup.sh --setup`, `--model Q2_0 --yes`, `--gguf-dir /data/Q2_0`). Terminal chat: `.venv/bin/python chat.py`. @@ -304,7 +322,8 @@ The full story, with measurements, bottlenecks and what comes next: **[docs/pape - Model: [Qwen/Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; quantizations: [ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF). - Their licenses apply to the weights. + Swift 1.5: [ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) + by UkisAI. Their licenses apply to the weights. - [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT): the i-quant formats, the GPU dot products and dequantizers transcribed in `src/kernels/cuda/iq_kernels.cu`, the CPU backend linked for the i-quant experts, the `mtmd` library behind the image encoder (`tools/vision/`), and `gguf-py` used by the tools. See diff --git a/include/strata/kernels/cpu/expert_layout.hpp b/include/strata/kernels/cpu/expert_layout.hpp index d4b20cb0..126549ae 100644 --- a/include/strata/kernels/cpu/expert_layout.hpp +++ b/include/strata/kernels/cpu/expert_layout.hpp @@ -23,6 +23,9 @@ struct ExpertLayout { /// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in the model's shard 1, so /// the arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown). std::vector gguf_off; + /// Per layer, the GGUF file (a name beside the --native shard) that holds its experts when the model's + /// shards split the layers (Swift's GGUFs: layers 13-47 in shard 2). Empty = the --native shard itself. + std::vector gguf_file; uint64_t max_blob = BLOB; uint64_t total = 0; ///< experts.bin size diff --git a/serve/server.py b/serve/server.py index 91889ee5..1afb7e19 100644 --- a/serve/server.py +++ b/serve/server.py @@ -580,7 +580,9 @@ def main() -> int: engine = StrataEngine(cfg["exe"], cfg["args"], cwd=cfg.get("cwd"), log=cfg.get("log"), env=env) else: engine, vision = MockEngine(tok, a.script), None - svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + # the model's own chat template (exported with its tokenizer), else the original model's + tpl = tpath / "chat_template.jinja" + svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"), model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision) svc.api_key = a.api_key or cfg.get("api_key", "") httpd = serve(svc, host=a.host, port=a.port) diff --git a/setup.py b/setup.py index b91a2c37..2d9efcdd 100644 --- a/setup.py +++ b/setup.py @@ -3,15 +3,15 @@ START-HERE.bat (Windows) / ./setup.sh (Linux) - they install Python if needed and run this file -The first time it asks three questions - which model, how much context, and whether the model should also read -images - then installs everything and starts the model on http://127.0.0.1:8080 (OpenAI- and Anthropic-compatible +The first time it asks four questions - which model (the original Qwen3.8-Flash-Next or the Swift 1.5 fine-tune), +which size, how much context, and whether the model should also read images - then installs everything and starts the model on http://127.0.0.1:8080 (OpenAI- and Anthropic-compatible API; a small page there shows that it runs). Every later start skips straight to running the model: nothing that is already downloaded, installed or prepared is done again. What the first run does (each step is skipped when it is already done): 1. checks your PC: NVIDIA GPU and driver, RAM, CPU, free disk space - 2. asks the three questions + 2. asks the questions 3. installs the Python packages it needs into .venv (numpy, jinja2, ..., and NVIDIA's CUDA libraries) 4. gets the Strata engine: a ready-made build for RTX 30/40/50 cards (no compiler needed); if none fits your PC, it installs the build tools (asks first) and compiles the engine for your GPU @@ -19,7 +19,7 @@ What the first run does (each step is skipped when it is already done): 6. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) 7. writes run-.bat / run-.sh and starts the model -Options: --model Q2_0|IQ2_XS|IQ3_XXS, --context 32768, --vision yes|no|gpu|cpu, --port 8080, --yes (recommended +Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS, --context 32768, --vision yes|no|gpu|cpu, --port 8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, --models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made engine), --check (only check this PC). @@ -54,6 +54,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" # the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] MIN_DRIVER = 580 # CUDA 13.0 +MIN_ENGINE = (0, 1, 1) # the ready-made engine that reads split models (Swift 1.5) PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja"] MODELS = { @@ -64,6 +65,22 @@ MODELS = { "ram_gb": 60, "arena_gb": 42.9}, } CONTEXTS = [8192, 32768, 65536, 131072, 262144] +# The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. +FAMILIES = { + "qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab", + "about": "the original model", + "hf": "https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/{q}/", + "file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "", + "mmproj_hf": "https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/", + "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next"}, + "swift": {"title": "Swift 1.5", "by": "UkisAI's fine-tune of Qwen3.8-Flash-Next", + "about": "thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its authors' numbers)", + "hf": "https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/", + "file": "Swift-Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "swift-", + "mmproj_hf": "https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/", + "mmproj": "mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf", "name": "swift-1.5", + "license": "Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"}, +} MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" # the image encoder on the GPU: ~0.9 GB of weights + ~0.3 GB of work buffers at 1024 image tokens, kept free of # expert slots (the engine's default reserve is 700 MiB) @@ -384,8 +401,13 @@ def get_prebuilt(url_base, gpu, vision) -> Path | None: eng = ROOT / "engine" info = eng / "BUILD.json" if info.exists() and (eng / EXE).exists(): - ok("ready-made engine already installed") - return eng + meta = json.loads(info.read_text()) + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("source") == "local" or ver >= MIN_ENGINE: + ok("ready-made engine already installed") + return eng + say(f" Updating the ready-made engine ({meta.get('version')} -> {'.'.join(map(str, MIN_ENGINE))} or newer) ...") + info.unlink() if not url_base: return None z = ROOT / "engine" / PREBUILT_ASSET @@ -404,6 +426,11 @@ def get_prebuilt(url_base, gpu, vision) -> Path | None: with zipfile.ZipFile(z) as f: f.extractall(tmp) meta = json.loads((tmp / "BUILD.json").read_text()) + if tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) < MIN_ENGINE: + warn(f"the ready-made engine at {base} is version {meta.get('version')}; this setup needs " + f"{'.'.join(map(str, MIN_ENGINE))}: compiling instead") + shutil.rmtree(tmp, ignore_errors=True) + return None archs = [int(a) for a in meta.get("archs", [])] arch = int(gpu["arch"]) if arch not in archs and not (meta.get("ptx") and arch > max(archs)): @@ -577,6 +604,7 @@ def write_run_script(model, cfg_path, port): # ------------------------------------------------------------------------------------------------ main def main() -> int: 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("--context", type=int) ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], @@ -598,12 +626,12 @@ def main() -> int: # ---- 0. already installed: just start it have = installed_configs() - if have and not (a.setup or a.model or a.check or a.no_start): + if have and not (a.setup or a.model or a.family or a.check or a.no_start): if len(have) == 1: return start(have[0], None) say() for i, c in enumerate(have, 1): - say(f" {i}) {c.stem[len('strata-'):].upper()}") + say(f" {i}) {json.loads(c.read_text(encoding='utf-8')).get('model_name', c.stem)}") say(f" {len(have) + 1}) install another model / change settings") pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes)) if pick <= len(have): @@ -640,17 +668,31 @@ def main() -> int: # ---- 2. the questions step(2, "your choices") + fams = list(FAMILIES) + if a.family: + family = a.family + else: + for i, f in enumerate(fams, 1): + d = FAMILIES[f] + say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}") + family = fams[int(ask("Which model?", [str(i) for i in range(1, len(fams) + 1)], "1", a.yes)) - 1] + fam = FAMILIES[family] + ok(f"model: {fam['title']}") + if fam.get("license"): + say(f" Its license: {fam['license']}") + say() names = list(MODELS) 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}" say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}") rec = "3" if ram >= 60 else "1" - model = a.model or names[int(ask("Which model?", ["1", "2", "3"], rec, a.yes)) - 1] + model = a.model or names[int(ask("Which size?", ["1", "2", "3"], rec, a.yes)) - 1] if ram < MODELS[model]["ram_gb"] - 4: fail(f"{model} needs about {MODELS[model]['ram_gb']} GB of RAM; this PC has {ram:.0f} GB", "choose Q2_0 or IQ2_XS, or add RAM") - ok(f"model: {model}") + ok(f"size: {model}") + tag = fam["tag"] + model # names of the pack, config and start script rec_ctx = 32768 if gpu["vram_gb"] < 14 else 65536 if gpu["vram_gb"] < 20 else 131072 if a.context: ctx = a.context @@ -673,11 +715,11 @@ def main() -> int: say(" download and keeps ~1.4 GB of VRAM free for the image encoder, so text is a few % slower.") vision = "gpu" if ask("Do you want images?", ["y", "n"], "n", a.yes) == "y" else "none" ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) - models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / model - shards = [models_dir / f"Qwen3.8-Flash-Next-GSQ-RCO-{model}-0000{i}-of-00002.gguf" for i in (1, 2)] + models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag + shards = [models_dir / fam["file"].format(q=model, i=i) for i in (1, 2)] have_model = all(s.exists() and (done(s) or a.gguf_dir) for s in shards) need = (0 if a.gguf_dir or have_model else MODELS[model]["download_gb"]) + 8 + \ - (40 if model == "Q2_0" and avx512 else 0) + (1 if vision != "none" else 0) + (40 if model == "Q2_0" and avx512 and family == "qwen" else 0) + (1 if vision != "none" else 0) if free_gb(models_dir) < need: fail(f"not enough free disk space in {models_dir}: need ~{need:.0f} GB", "use --models-dir on a bigger drive") @@ -702,15 +744,15 @@ def main() -> int: ok(f"engine: {eng / EXE}") # ---- 5. the model files - step(5, f"downloading {model}") + step(5, f"downloading {fam['title']} {model}") if not a.gguf_dir: for s in shards: if s.exists() and done(s): ok(f"{s.name} already downloaded") continue - # shard 2 is the same file for all three models: reuse one that is already here + # the original's shard 2 is the same file for all three sizes: reuse one that is already here other = [p for p in Path(a.models_dir).glob("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf") if done(p)] - if s.name.endswith("00002-of-00002.gguf") and other and not s.exists(): + if family == "qwen" and s.name.endswith("00002-of-00002.gguf") and other and not s.exists(): try: os.link(other[0], s) mark(s) @@ -718,24 +760,24 @@ def main() -> int: continue except OSError: pass - download(HF + f"{model}/{s.name}", s) + download(fam["hf"].format(q=model) + s.name, s) for s in shards: if not s.exists(): fail(f"missing {s}") ok("model files present") - mmproj = Path(a.models_dir) / MMPROJ + mmproj = Path(a.models_dir) / fam["mmproj"] if vision != "none": - if not mmproj.exists() and a.gguf_dir and (Path(a.gguf_dir) / MMPROJ).exists(): - mmproj = Path(a.gguf_dir) / MMPROJ + if not mmproj.exists() and a.gguf_dir and (Path(a.gguf_dir) / fam["mmproj"]).exists(): + mmproj = Path(a.gguf_dir) / fam["mmproj"] else: - download(HF + MMPROJ, mmproj, "vision encoder") + download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") ok(f"vision encoder: {mmproj}") # ---- 6. the pack and the MTP draft layer step(6, "preparing the model for Strata") - pack = ROOT / "packs" / model.lower() + pack = ROOT / "packs" / tag.lower() env = dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py")) - if model == "Q2_0" and avx512: + if model == "Q2_0" and avx512 and family == "qwen": # the Q2_0 experts repacked for the AVX-512 kernel (the measured speed): a one-time ~40 GB conversion if not (pack / "index.txt").exists() or not (pack / "experts.bin").exists(): # index.txt is written last say(" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...") @@ -765,7 +807,12 @@ def main() -> int: # ---- 7. the start script step(7, "writing the start script") - args = ["--pack", str(pack), "--native", str(shards[0]), "--ple-gguf", str(shards[1]), + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile # the PLE table's shard: shard 2 (original) or 1 (Swift) + 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" / "expert-profile.bin"), "--expert-cache", "auto", "--prefill", "2048", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt), "--max-context", str(ctx)] @@ -774,16 +821,16 @@ def main() -> int: if vision != "none": args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])] cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), - "model_name": f"qwen3.8-flash-next-{model.lower()}", "log": str(ROOT / f"strata-{model.lower()}.log"), + "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": a.port} if vision != "none": cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} if vision == "cpu": cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) - cfg_path = ROOT / f"strata-{model.lower()}.json" + cfg_path = ROOT / f"strata-{tag.lower()}.json" cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - script = write_run_script(model, cfg_path, a.port) + script = write_run_script(tag, cfg_path, a.port) ok(f"start script: {script.name}") say() diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index db4465d6..3eb65e9d 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -545,13 +545,28 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: const auto t0 = std::chrono::steady_clock::now(); std::atomic next{0}; std::atomic bad{false}; + // a layer's experts may sit in another shard of the model (native_experts.txt v3): a name beside `gguf` + const size_t cut = gguf.find_last_of("/\\"); + const std::string dir = cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1); + auto file_of = [&](int64_t l) -> std::string { + if (lay.gguf_file.empty() || lay.gguf_file[(size_t) l].empty()) return gguf; + return dir + lay.gguf_file[(size_t) l]; + }; auto worker = [&]() { - std::ifstream f(gguf, std::ios::binary); - if (!f) { bad = true; return; } + std::ifstream f; + std::string open_name; std::vector buf; for (;;) { const int64_t l = next.fetch_add(1); if (l >= lay.n_layers || bad) break; + const std::string name = file_of(l); + if (name != open_name) { + f.close(); + f.clear(); + f.open(name, std::ios::binary); + if (!f) { bad = true; return; } + open_name = name; + } const auto& fm = lay.fmt[(size_t) l]; const uint64_t blob = lay.bytes[(size_t) l]; const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; diff --git a/src/kernels/cpu/expert_layout.cpp b/src/kernels/cpu/expert_layout.cpp index c02cd657..ec06ac78 100644 --- a/src/kernels/cpu/expert_layout.cpp +++ b/src/kernels/cpu/expert_layout.cpp @@ -113,6 +113,11 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n L.gguf_off[(size_t) (3 * l)] = go; L.gguf_off[(size_t) (3 * l + 1)] = uo; L.gguf_off[(size_t) (3 * l + 2)] = dox; + std::string file; // v3: the shard that holds this layer (a file name beside --native) + if (ss >> file) { + if (L.gguf_file.empty()) L.gguf_file.assign((size_t) n_layers, std::string()); + L.gguf_file[(size_t) l] = file; + } } L.fmt[(size_t) l] = f; L.offset[(size_t) l] = off; diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 705ced66..b1bd98b2 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -164,15 +164,19 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // row. `GgufFile` parses the header, so `tensor_data` is already correct; this asserts the tensor // exactly fills the file from there, which is what makes the whole arrangement checkable rather than // assumed. A wrong data offset would leave a different remainder. + // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must + // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. const uint64_t need = impl_->n_rows * (uint64_t) PLE_ROW_BYTES; const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); - if (need != have) { + const bool alone = impl_->file->tensors().size() == 1; + if (alone ? need != have : t->offset + need > have) { char buf[256]; std::snprintf(buf, sizeof buf, - "PLE table size mismatch: %llu rows x %d B = %llu, but the file holds %llu from " + "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " "data_start %llu", (unsigned long long) impl_->n_rows, PLE_ROW_BYTES, (unsigned long long) need, - (unsigned long long) have, (unsigned long long) impl_->file->data_start()); + (unsigned long long) t->offset, (unsigned long long) have, + (unsigned long long) impl_->file->data_start()); err = buf; close(); return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e116abe5..863dde91 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -333,6 +333,23 @@ void usage() { " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n"); } +/// All shards of a split GGUF, from shard 1's path ("...-00001-of-00002.gguf"); just the path when it is not split. +std::vector model_shards(const std::string& first) { + const std::string tag = "-00001-of-"; + const size_t at = first.rfind(tag); + if (at == std::string::npos || first.size() < at + tag.size() + 10) return {first}; + const int total = std::atoi(first.substr(at + tag.size(), 5).c_str()); + std::vector out; + for (int i = 1; i <= total && i <= 99; ++i) { + char num[8]; + std::snprintf(num, sizeof num, "%05d", i); + std::string p = first; + p.replace(at + 1, 5, num); + if (std::ifstream(p, std::ios::binary)) out.push_back(p); + } + return out.empty() ? std::vector{first} : out; +} + bool parse_i64_list(const char* s, std::vector& out, std::string& err) { out.clear(); std::string text(s); @@ -592,7 +609,13 @@ int main(int argc, char** argv) { o.native_ple_key = o.native_moe_combine = o.native_gdn = o.native_router = true; o.native_qsa = o.native_qsa_indexer = o.native_rope = o.native_ple_postops = true; if (o.native_head_gguf.empty()) o.native_head_gguf = o.native_preset; - if (o.native_dense_gguf.empty()) o.native_dense_gguf = {o.native_preset, o.ple_gguf}; + if (o.native_dense_gguf.empty()) { + // every shard of the model (-0000N-of-0000M.gguf beside --native), then the PLE shard: a split + // may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) + o.native_dense_gguf = model_shards(o.native_preset); + if (std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) + o.native_dense_gguf.push_back(o.ple_gguf); + } // Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract // cost 27.0 vs 17.2 ms/token of pool time and G-C does not need it; `--cpu-oracle-q8-0` still selects it. } diff --git a/tools/iq_pack.py b/tools/iq_pack.py index 2c5d54f1..637d8039 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -15,7 +15,12 @@ its GGUF form: With --base: the base (Q2_0) pack's dense.bin, hard-linked - the float tensors are byte-identical in all three model files (checked) - plus extra.bin for tensors that are float here but quantized in the base pack (blk.1.ple_key). - tokenizer/ exported from the GGUF (tools/strata_tokenizer.py). + tokenizer/ exported from the GGUF (tools/strata_tokenizer.py), with the model's chat template. + +Split files: every shard of the model is read (-0000N-of-0000M.gguf beside --gguf), so the layers may be +split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in shard 1). A layer whose experts +are not in shard 1 names its shard in native_experts.txt (v3). Router tensors stored as F32 whose values are +exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router takes; anything else is refused. """ from __future__ import annotations @@ -34,6 +39,33 @@ sys.path.insert(0, str(HERE)) import gguf_reader as G # noqa: E402 FLOAT = {"BF16", "F32", "F16"} +ROUTERS = ("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight") +NOT_IN_PACK = {"per_layer_token_embd.weight"} # the 28.8 GB PLE table: read from its GGUF by the engine + + +class Model: + """All shards of one model: name -> (GGUFFile, TensorInfo, memmap, shard path).""" + + def __init__(self, first: pathlib.Path): + import re + m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", first.name) + paths = [first] + if m: + total = int(m.group(2)) + paths = [first.with_name(first.name[:m.start()] + "-%05d-of-%05d.gguf" % (i, total)) + for i in range(1, total + 1)] + paths = [p for p in paths if p.exists()] + self.paths = paths + self.where = {} + for p in paths: + g = G.GGUFFile(p) + mm = np.memmap(p, dtype=np.uint8, mode="r") + for t in g.tensors: + self.where[t.name] = (g, t, mm, p) + + def bytes(self, name) -> np.ndarray: + g, t, mm, _ = self.where[name] + return tensor_bytes(mm, g, t) ROLES = ("gate", "up", "down") N_EXPERT = 512 ALIGN = 64 @@ -59,13 +91,14 @@ def is_expert(name: str) -> bool: return name.startswith("blk.") and name.endswith(("_exps.weight",)) -def index_standalone(src, out, g, T, mm) -> int: - """Every non-expert tensor of shard 1: floats into dense.bin as stored, quantized ones native-only.""" +def index_standalone(src, out, model: Model) -> int: + """Every non-expert tensor of the model: floats into dense.bin as stored (exact-BF16 F32 routers as BF16), + quantized ones native-only.""" rows, at = [], 0 served = 0 with open(out / "dense.bin", "wb") as fo: - for t in g.tensors: - if is_expert(t.name): + for name, (g, t, mm, _) in model.where.items(): + if is_expert(t.name) or t.name in NOT_IN_PACK: continue if len(t.shape) > 2: print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape))) @@ -75,6 +108,13 @@ def index_standalone(src, out, g, T, mm) -> int: if t.type_name in FLOAT: raw = tensor_bytes(mm, g, t).tobytes() kind = {"BF16": "4", "F16": "5", "F32": "2"}[t.type_name] + if t.type_name == "F32" and t.name.endswith(ROUTERS): + u = np.frombuffer(raw, dtype=np.uint32) + if np.count_nonzero(u & 0xFFFF): + print("router %s is F32 with values that are not BF16; the engine's router is BF16" % t.name) + return 1 + raw = (u >> 16).astype(np.uint16).tobytes() # the exact BF16 values + kind = "4" rows.append([t.name, "0", kind, str(at), str(len(raw)), "0", str(len(raw)), str(ne0), str(ne1), "0", "0", "1"] + ["0"] * 7) fo.write(raw) @@ -167,15 +207,21 @@ def main() -> int: out.mkdir(parents=True, exist_ok=True) g = G.GGUFFile(src) - T = {t.name: t for t in g.tensors} mm = np.memmap(src, dtype=np.uint8, mode="r") + model = Model(src) + T = {n: w[1] for n, w in model.where.items()} + if len(model.paths) > 1: + print("model shards: " + ", ".join(p.name for p in model.paths)) if a.base: - rc = index_from_base(a, src, base, out, g, T, mm) + if any(w[3] != src for w in model.where.values() if not w[1].name in NOT_IN_PACK): + print("--base needs a model whose tensors are all in shard 1") + return 1 + rc = index_from_base(a, src, base, out, g, {t.name: t for t in g.tensors}, mm) else: - rc = index_standalone(src, out, g, T, mm) + rc = index_standalone(src, out, model) if rc: return rc - if not (out / "tokenizer" / "vocab.json").exists(): + if not (out / "tokenizer" / "vocab.json").exists() or not (out / "tokenizer" / "chat_template.jinja").exists(): subprocess.run([sys.executable, str(HERE / "strata_tokenizer.py"), "--gguf", str(src), "--out", str(out)], check=True) # writes /tokenizer/ @@ -192,10 +238,17 @@ def main() -> int: layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts)) offset += blob * N_EXPERT with open(out / "native_experts.txt", "w", encoding="utf-8", newline="\n") as fo: - fo.write("# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off " - "(n_expert %d, total %d; the last three are absolute offsets in %s)\n" % (N_EXPERT, offset, src.name)) + fo.write("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] " + "(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n" + % (N_EXPERT, offset, src.name)) for l, gt, dt, off, blob, ts in layout: - fo.write("%d %d %d %d %d %d %d %d\n" % (l, gt, dt, off, blob, *[g.data_start + t.offset for t in ts])) + ws = [model.where[t.name] for t in ts] + if len({w[3] for w in ws}) != 1: + print("layer %d: its gate/up/down tensors are in different shards" % l) + return 1 + gg, shard = ws[0][0], ws[0][3] + line = "%d %d %d %d %d %d %d %d" % (l, gt, dt, off, blob, *[gg.data_start + t.offset for t in ts]) + fo.write(line + ("" if shard == src else " " + shard.name) + "\n") if a.skip_experts or not a.experts_bin: if (out / "experts.bin").exists() and not a.experts_bin: print("note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out) @@ -206,7 +259,7 @@ def main() -> int: return 0 with open(path, "wb") as fo: for l, gt, dt, off, blob, ts in layout: - parts = [tensor_bytes(mm, g, t).reshape(N_EXPERT, -1) for t in ts] + parts = [model.bytes(t.name).reshape(N_EXPERT, -1) for t in ts] chunk = np.concatenate(parts, axis=1) # (512, blob): gate | up | down per expert assert chunk.shape == (N_EXPERT, blob) fo.write(chunk.tobytes()) diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py index d81da51c..59dfb876 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -230,6 +230,12 @@ def extract(gguf_path, out_dir) -> dict: sorted(tk.ranks.items(), key=lambda kv: kv[1])), encoding="utf-8") (out / "token_type.json").write_text(json.dumps(tk.token_types), encoding="utf-8") (out / "tokenizer.json").write_text(json.dumps(cfg, ensure_ascii=False, indent=1), encoding="utf-8") + # the model's own chat template: fine-tunes change it (Swift 1.5 differs from Qwen3.8-Flash-Next's) + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + from gguf_reader import GGUFFile + tpl = GGUFFile(pathlib.Path(gguf_path)).metadata.get("tokenizer.chat_template") + if tpl: + (out / "chat_template.jinja").write_text(tpl, encoding="utf-8", newline="\n") return cfg