From 2dbb263b02d0840319d607d9d4d4258e4a674ed9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:18:48 +0200 Subject: [PATCH 01/34] launch/setup for DeepSeek: setup installs the screens packages (textual) and launch goes on in plain lines without them; the Tuning screen shows the DeepSeek tuner's real length and what it tries; the Advanced list knows strata-dsv41's own flags; the model menu counts the disk (download + preparation) in 'fits'; docs: tuning and the separate engine package; tests --- docs/DEEPSEEK41.md | 19 ++++++- setup.py | 28 +++++++--- strata_cli/launch/app.py | 10 +++- strata_cli/launch/catalog.py | 2 + strata_cli/launch/cmd.py | 18 ++++++- strata_cli/launch/params.py | 39 ++++++++++++++ strata_cli/launch/screens.py | 12 +++-- tests/terminal/test_dsv41_tui_items.py | 73 ++++++++++++++++++++++++++ tools/strata_mcp.py | 18 +++++-- 9 files changed, 199 insertions(+), 20 deletions(-) create mode 100644 tests/terminal/test_dsv41_tui_items.py diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 32bd2a22..12021fd4 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -71,8 +71,23 @@ The server speaks to the engine as it does for the other models, so `/v1/chat/co A value marked `string="true"` stays a string. - Defaults when a request names none: temperature 1.0, top_p 1.0. -Pictures and the DSpark drafter are in the engine (strata-dsv41 reads them from the unsloth mmproj and dspark files beside the model; the server side is not wired yet). Not in this version: several requests at once (`--parallel` is ignored with a note), tuning -(`--tune` is skipped with a note). +Not in this version: several requests at once (`--parallel` is ignored with a warning) and pictures (`--vision` is ignored with a warning). + +## Tuning + +`strata launch --tune quick` (or `thorough`, or the Tuning screen) works for DeepSeek with its own short tuner, `tools/dsv41/tune.py`. It starts +the engine a few times on a fixed short question and measures the answer speed: the standard settings first, then the DSpark drafter forced on, +then a shorter draft block (3), then one CPU thread for each physical core (thorough also tries every logical thread). A setting is kept only for a +gain of more than 5%, and the result is written into the launch's settings. Expect about 5 to 10 minutes (each run loads the model, which takes +1 to 3 minutes); close other heavy programs first. If a run fails or the computer is too busy to tell, the standard settings stay and one plain line +says so. The RAM store (`--ssd-cache`) sizes itself when the model starts, so the tuner does not touch it, and the context stays what you chose. + +## The engine package + +DeepSeek's engine, `strata-dsv41`, is a separate download from the Strata engine: when you choose DeepSeek, setup (or `strata launch`) fetches the +package for your computer from the signed update feed (resumable, signature and every file checked) and installs it in `engine-dsv41/` beside +`engine/`. The Qwen engine's files are never changed. If the feed has no package for your graphics card, setup says so in plain words and stops before +anything big is downloaded. ## Compressed experts (trellis), for testing diff --git a/setup.py b/setup.py index aaa732c0..eb9cb825 100644 --- a/setup.py +++ b/setup.py @@ -3231,6 +3231,18 @@ def requirement_lines(path: Path | None = None) -> list[str]: return lines +MONITOR_REQUIREMENTS = ROOT / "requirements-monitor.txt" + + +def runtime_packages() -> list[str]: + """The packages setup installs for a run: the pinned runtime ones, plus the Terminal's screens (textual, which brings rich: `strata launch` + and `strata monitor` need them; the packaged Terminal bundles them, a source install gets them here).""" + base = requirement_lines() if REQUIREMENTS.exists() else list(PY_PACKAGES) + if MONITOR_REQUIREMENTS.exists(): + base += [r for r in requirement_lines(MONITOR_REQUIREMENTS) if r not in base] + return base + + def _installed(name: str) -> bool: try: import importlib.metadata as md @@ -6645,8 +6657,8 @@ def update_install(have: list, a) -> int: say(" No model is installed in this Strata folder yet: run START-HERE.bat (Linux: ./setup.sh) to set it up -") say(" it finds an earlier install's model files next to it and reuses them.") return 0 - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil") + pip_install(runtime_packages(), + "numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil, textual (the screens)") if not a.build: update_installed_engine(a.prebuilt) mtp_done: set = set() @@ -7576,8 +7588,8 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte warn(f"little free disk space in {folder}: {free_gb(folder):.1f} GB free for about {left:.1f} GB. Setup goes on and should fit") step(3, "Python packages") - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") + pip_install(runtime_packages(), + "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil, textual (the screens)") step(4, "the Strata engine") llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) @@ -7913,8 +7925,8 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} does not use them") step(3, "Python packages") - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") + pip_install(runtime_packages(), + "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil, textual (the screens)") step(4, "the Strata engine") llama, eng, meta, lib_dirs, gpu, _vision = engine_step(a, gpu, hip, amd, cuda_tk, "none") @@ -9127,8 +9139,8 @@ def main() -> int: # ---- 3. python packages step(3, "Python packages") - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil") + pip_install(runtime_packages(), + "numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil, textual (the screens)") # ---- 4. the engine step(4, "the Strata engine") diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index 4f1a565f..058239ed 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -148,8 +148,14 @@ class Ctx: tuned_args, tuned_env = list(merged.get("args") or []), dict(merged.get("env") or {}) except Exception: # noqa: BLE001 pass - exe = self.engine_exe() - text = P.engine_help_text(exe) if exe else None + if (cfg or {}).get("arch") == "deepseek41" or self.settings.family == "deepseek41": # DeepSeek runs strata-dsv41: its settings, not the Qwen engine's + own = (cfg or {}).get("exe") + exe = own if own and Path(str(own)).is_file() else None + text = P.dsv41_help_text(exe) + exe = exe or "static" + else: + exe = self.engine_exe() + text = P.engine_help_text(exe) if exe else None if exe and text: self.engine_flags = sorted({p.name for p in P.parse_help(text)}) self.engine_note = "" diff --git a/strata_cli/launch/catalog.py b/strata_cli/launch/catalog.py index bde400e4..9f8e9359 100644 --- a/strata_cli/launch/catalog.py +++ b/strata_cli/launch/catalog.py @@ -72,6 +72,8 @@ def verdict(on_this_pc: str | None) -> tuple[str, str]: return TIGHT, "not checked (this computer's memory could not be read)" if low.startswith("does not fit"): return NO, "too big (can still try)" + if "free disk space" in low: # DeepSeek: fits in memory, not on the disk (still allowed) + return TIGHT, "tight: needs more disk space" if "low-ram mode" in low: return FITS, "fits, a bit slower" if "part of its experts" in low or "read from the ssd" in low: diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 267d92ba..09ffde9b 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -531,6 +531,13 @@ def open_page(url: str) -> bool: return False +def _screens_missing() -> str | None: + """The Python package the screens need that this install lacks ("rich" / "textual"), None when both are there. A source install made before + setup installed them has neither: `strata launch` then goes on in plain lines instead of stopping with a traceback.""" + import importlib.util + return next((m for m in ("rich", "textual") if importlib.util.find_spec(m) is None), None) + + def _tui(run, *args, **kw) -> int: """Open the screens. An error of the screens themselves ends with a plain sentence and a non-zero exit code, never a traceback and exit 0 (tester report T02).""" @@ -668,14 +675,21 @@ def run_launch(a: argparse.Namespace) -> int: have_choices = bool(a.preset or a.model or a.model_path or a.context or a.vision or a.parallel or a.access or a.tune or a.drafting) interactive = sys.stdin.isatty() and sys.stdout.isatty() and not a.no_tui and not machine and not a.plan plain_questions = False + no_screens_package = None + if interactive and _screens_missing(): + no_screens_package = _screens_missing() + interactive = False + _say(f"The screens need a Python package this install does not have yet ({no_screens_package}), so Strata goes on in plain lines. " + "Run setup again (START-HERE / ./setup.sh) to get the screens.") if not have_choices and not interactive and not a.plan: if machine or a.no_tui or catalog is None or not _can_ask(): # --no-tui never asks (round 8, M) return fail("`strata launch` with no choices opens screens, and this is not a terminal (or --no-tui was given). Name what to start: --preset NAME, or --model NAME " "(strata launch --help has examples; --plan shows what would happen without changing anything).", 2) # Git Bash, mintty and some editor panels cannot show the screens although a person is typing: go on in plain lines, and ask first plain_questions = True - _say("This window cannot show Strata's screens (Git Bash and similar windows do not pass the keyboard through). " - "For the screens, open Windows Terminal, PowerShell or cmd, or run `winpty strata launch`. Going on with plain questions.") + if no_screens_package is None: + _say("This window cannot show Strata's screens (Git Bash and similar windows do not pass the keyboard through). " + "For the screens, open Windows Terminal, PowerShell or cmd, or run `winpty strata launch`. Going on with plain questions.") if interactive and not have_choices: if catalog is None: return fail("This Terminal does not carry the model list, so the screens cannot open. Install it again with the one-line installer.", 5) diff --git a/strata_cli/launch/params.py b/strata_cli/launch/params.py index f6af060b..9a3a98d8 100644 --- a/strata_cli/launch/params.py +++ b/strata_cli/launch/params.py @@ -212,6 +212,45 @@ def flag_list(engine: str | Path | None) -> list[str] | None: return None +#: strata-dsv41's settings in plain words (its own --help is one bracketed usage line, which the Qwen engine's list parser cannot read). +DSV41_FLAGS = { + "--pack": ("DIR", "The folder with the model's prepared data."), + "--max-context": ("N", "How much text the model remembers at once."), + "--eos": ("ID", "The token that ends an answer (1 for DeepSeek)."), + "--dspark": ("on|off|none|auto", "The DSpark drafter that guesses ahead to speed up answers (auto loads it only where it helps)."), + "--dspark-conf": ("F", "How sure a DSpark guess must be to be used (0 to 1)."), + "--dspark-block": ("N", "The most words DSpark guesses in one round."), + "--expert-profile": ("FILE|none", "A table of which experts are used most, to decide what is kept in memory first."), + "--ssd-cache": ("GB", "How much RAM keeps the most used experts so they are not read from the SSD again (sizes itself when absent)."), + "--ssd-policy": ("lru|lfu|lfulru", "Which experts the RAM store drops first."), + "--prefill-chunk": ("N", "How many prompt words are read at once (the fast prompt path)."), + "--threads": ("on|off", "Read long prompts layer by layer on all CPU threads."), + "--cpu-threads": ("N", "How many CPU threads compute the experts the graphics card does not hold."), + "--tp": ("N", "Share each layer between this many graphics cards."), + "--gpus": ("LIST", "Which graphics cards to use together."), + "--reserve-mib": ("N", "Graphics memory (in MiB) kept free for other programs."), + "--vram-experts": ("F", "How many experts to keep in graphics memory."), + "--mmap-experts": ("on|off|auto", "Read the experts in place from the model's files."), + "--no-expert-cache": ("", "Do not keep the most used experts in graphics memory."), + "--vision": ("on|off", "Let the model read pictures."), + "--verbose": ("", "Print more about what the engine does."), +} + + +def dsv41_help_text(engine: str | Path | None) -> str: + """A list of strata-dsv41's settings the Advanced screen can read: ours in plain words, plus any flag its own --help names that we do not + describe. Works before the engine is installed too (the plain words are static).""" + lines = [f" {flag} {meta} {desc}" if meta else f" {flag} {desc}" for flag, (meta, desc) in DSV41_FLAGS.items()] + if engine: + import subprocess + try: + proc = subprocess.run([str(engine), "--help"], capture_output=True, text=True, timeout=20) + seen = set(re.findall(r"--[a-z][a-z0-9-]*", (proc.stdout or "") + " " + (proc.stderr or ""))) + lines += [f" {f} An engine setting (the engine's help has no sentence for it)." for f in sorted(seen) if f not in DSV41_FLAGS] + except Exception: # noqa: BLE001 - the static list stands + pass + return "\n".join(lines) + "\n" + def engine_help_text(engine: str | Path | None) -> str | None: if not engine: return None diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index 2c95a6ec..167f4748 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -1041,9 +1041,15 @@ class TuningScreen(Base): def on_mount(self) -> None: s = self.ctx.settings first = self.ctx.fresh_setup and not s.is_tuned - items = [Item(["Quick", "about 20 minutes", "checks the most likely gains" + ("; suggested the first time" if first else "")], key="quick"), - Item(["Thorough", "up to 2 hours", "tries more settings, measures each one several times"], key="thorough"), - Item(["Skip", "", "use the default settings (already good on most computers)"], key="skip")] + if s.family == "deepseek41": # DeepSeek's own short tune (tools/dsv41/tune.py): its real length and what it tries + items = [Item(["Quick", "about 5-10 minutes", "tries the DSpark drafter on or off, a shorter draft block and the CPU threads; keeps only clear gains" + + ("; suggested the first time" if first else "")], key="quick"), + Item(["Thorough", "about 10-15 minutes", "also tries every CPU thread"], key="thorough"), + Item(["Skip", "", "use the default settings (already good on most computers)"], key="skip")] + else: + items = [Item(["Quick", "about 20 minutes", "checks the most likely gains" + ("; suggested the first time" if first else "")], key="quick"), + Item(["Thorough", "up to 2 hours", "tries more settings, measures each one several times"], key="thorough"), + Item(["Skip", "", "use the default settings (already good on most computers)"], key="skip")] if not self.ctx.tune_chosen and s.tune == "skip" and not s.is_tuned and self.ctx.fresh_setup: s.tune = "quick" self.query_one(Menu).set_items(items, {"quick": 0, "thorough": 1, "skip": 2}.get(s.tune, 0)) diff --git a/tests/terminal/test_dsv41_tui_items.py b/tests/terminal/test_dsv41_tui_items.py new file mode 100644 index 00000000..69f42dbb --- /dev/null +++ b/tests/terminal/test_dsv41_tui_items.py @@ -0,0 +1,73 @@ +"""H100 fresh-install items for DeepSeek in the Terminal: the screens' packages, the Advanced list's own flags, the disk in "fits".""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) + +from strata_cli.launch import cmd, params as P # noqa: E402 +from strata_cli.launch.catalog import TIGHT, verdict # noqa: E402 + +CARD = {"index": 0, "name": "RTX 5070", "vram_gb": 12.0, "vendor": "nvidia", "usable": True} + + +class Screens(unittest.TestCase): + def test_missing_package_is_named_not_a_traceback(self): + import importlib.util as u + real = u.find_spec + with mock.patch.object(u, "find_spec", lambda n, *a, **k: None if n == "rich" else real(n, *a, **k)): + self.assertEqual(cmd._screens_missing(), "rich") + with mock.patch.object(u, "find_spec", lambda n, *a, **k: None if n == "textual" else real(n, *a, **k)): + self.assertEqual(cmd._screens_missing(), "textual") + + def test_setup_installs_the_screens_packages(self): + import setup + names = [r.split("==")[0].split(";")[0].strip() for r in setup.runtime_packages()] + self.assertIn("textual", names) + self.assertIn("numpy", names) + + +class Advanced(unittest.TestCase): + ARGS = ["--pack", "P", "--max-context", "8192", "--eos", "1", "--dspark", "auto", "--dspark-conf", "0.65"] + + def test_deepseeks_own_flags_are_known_before_the_engine_is_installed(self): + rows = P.build_rows(P.dsv41_help_text(None), self.ARGS, None, {}, {}, {}) + mine = {r.name: r for r in rows if r.name in self.ARGS} + self.assertEqual(set(mine), {"--pack", "--max-context", "--eos", "--dspark", "--dspark-conf"}) + for r in mine.values(): + self.assertNotIn("not in this engine's list", r.description) + self.assertTrue(r.known) + + def test_a_real_typing_mistake_is_still_flagged(self): + rows = P.build_rows(P.dsv41_help_text(None), self.ARGS + ["--dsparkk", "1"], None, {}, {}, {}) + self.assertIn("not in this engine's list", next(r for r in rows if r.name == "--dsparkk").description) + + +class Disk(unittest.TestCase): + def setUp(self): + import strata_mcp as M + self.s = M.Strata(ROOT) + + def hw(self, disk): + return {"ram_gb": 64.0, "gpus": [CARD], "engine_vendor": "nvidia", "disk_free_gb": disk} + + def test_fits_in_memory_but_not_on_the_disk_is_tight_with_the_numbers(self): + w = self.s.dsv41_words(self.hw(37.0), "IST-DAS-2.25bpw") + self.assertTrue(w.startswith("tight"), w) + self.assertIn("free disk space", w) + self.assertIn("37 GB", w) + self.assertEqual(verdict(w), (TIGHT, "tight: needs more disk space")) + + def test_enough_disk_or_already_installed_is_unchanged(self): + self.assertNotIn("free disk space", self.s.dsv41_words(self.hw(900.0), "IST-DAS-2.25bpw")) + self.assertNotIn("free disk space", self.s.dsv41_words(self.hw(37.0), "IST-DAS-2.25bpw", installed=True)) + self.assertNotIn("free disk space", self.s.dsv41_words({**self.hw(None)}, "IST-DAS-2.25bpw")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index b0314f0f..05d4931f 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -1221,7 +1221,7 @@ class Strata: verdict = "fits" if have_gb >= d["ram_gb"] else "tight" if have_gb >= d["ram_gb"] - 8 else "does not fit" try: if own and own.get("multi_file"): # DeepSeek-V4.1-Flash: strata_control/dsv41_fit.py (cards + RAM, the n-gram table on the SSD) - verdict = self.dsv41_words(hw, m) + verdict = self.dsv41_words(hw, m, installed=tag in have) elif own: # its own engine path: no budget or low-RAM mode of Flash-Next's to judge by pass elif d.get("budget") and S and hasattr(S, "unsloth_budget") and not S.unsloth_budget(m, ram): @@ -1269,8 +1269,20 @@ class Strata: cards = [c for c in cards if int(c.get("index", -1)) in {int(i) for i in only}] return dsv41_fit.plan(cards, (hw or {}).get("ram_gb"), disk_free, vendor=(hw or {}).get("engine_vendor"), model=model) - def dsv41_words(self, hw, model=None) -> str: - """The catalog's `on_this_pc` text for DeepSeek-V4.1-Flash (strata_cli/launch/catalog.verdict reads its first words).""" + def dsv41_words(self, hw, model=None, installed: bool = False) -> str: + """The catalog's `on_this_pc` text for DeepSeek-V4.1-Flash, with the disk it needs (download and preparation) beside the memory: a set that + fits in memory but not on the disk is "tight", never refused (strata_cli/launch/catalog.verdict reads its first words).""" + words = self._dsv41_memory_words(hw, model) + free = (hw or {}).get("disk_free_gb") + if installed or free is None or words.startswith("does not fit"): + return words + pl = self.dsv41_plan(hw, free, model=model) + if pl.get("disk_ok") is False: + return (f"tight: it needs about {pl['disk_need_gb']:.0f} GB of free disk space (the download and its preparation) and this computer has " + f"{free:.0f} GB free; free some space or choose another drive when you install it ({words})") + return words + + def _dsv41_memory_words(self, hw, model=None) -> str: pl = self.dsv41_plan(hw, model=model) v = pl["verdict"] if v == "no_card": From 75c57be831fb68fff656e8f4c50c93619f7eec7b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:34:09 +0200 Subject: [PATCH 02/34] release notes 0.2.4: Thanks names IST-DAS and Unsloth only --- docs/release-notes-0.2.4.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index 3d000bf9..2b1849eb 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -65,7 +65,6 @@ Everything from 0.2.3 is attached again, so the release page still holds every f - **IST-DAS** for the 2.00 and 2.25-bit sets of DeepSeek V4.1-Flash. - **Unsloth** for the DSpark drafter GGUF. -- **Project Maya (mw00, MIT)**, whose DeepSeek engine this port started from. --- From 4278304914679feccb4166650a750400cf313142 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 23 Oct 2026 21:43:13 +0200 Subject: [PATCH 03/34] dsv41: finer DS4_PROF for the chunked prompt (stages, expert kernels by type) --- src/dsv41/ds4_model.cu | 99 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index a9e37044..41304d8a 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -16,6 +16,7 @@ #include "ds4_engram_io.hpp" #include "ds4_gguf.cuh" +#include "ds4_iq.cuh" #include "ds4_gguf_cpu.hpp" #include "ds4_kernels.cuh" #include "ds4_os.hpp" @@ -1121,7 +1122,30 @@ struct Model::Impl { // ... and a run of chunks' (prof_chunk): a layer's start, after its attention, after the routing and the shared // expert, after its experts (the streamed ones' waits for their reads in it); printed after the run bool prof_chunk = false; - double cprof_ms[4] = {}; + // DS4_PROF stages of the chunked prompt (finer ones than the decode's 0..5): 0 between layers, 1 attention rest (wq_b, wo, + // hc_post), 2 router-side tail (shared expert), 3 experts (+ waits), 4 Engram, 5 attn mHC (mix, split, norm), 6 attention + // projections (wq_a, wkv, compressor), 7 compressor + indexer, 8 q_b + rope, 9 sparse attention, 10 ffn mHC + router + sort + double cprof_ms[16] = {}; + // DS4_PROF: the experts' kernels alone, by type (events around the gate/up and down calls of run_set) + struct EkMark { + cudaEvent_t e0, e1, e2; + int tg, td, nrows, nexp, maxrows, dev, ff; + }; + std::vector ek_marks; + std::map> ek_pool; // by device + cudaEvent_t ek_ev() { + int cur = 0; + cudaGetDevice(&cur); + std::vector& pl = ek_pool[cur]; + if (!pl.empty()) { + cudaEvent_t e = pl.back(); + pl.pop_back(); + return e; + } + cudaEvent_t e = nullptr; + cudaEventCreate(&e); + return e; + } void prof_mark(const Dev& d, int stage) { if (!prof_window && !prof_chunk) return; std::lock_guard lk(prof_mu); @@ -3421,8 +3445,30 @@ struct Model::Impl { gg::set_gate_up(sa, c.x, D, c.row_tok + a, c.h16, FF, d.st); gg::set_down(sa, c.h16, FF, c.y, D, d.st); } else { + EkMark ek{}; + const bool ekp = prof_chunk; + if (ekp) { + std::lock_guard lk(prof_mu); + ek.e0 = ek_ev(); + ek.e1 = ek_ev(); + ek.e2 = ek_ev(); + ek.tg = gg::expert_type(sa.lay, 0); + ek.td = gg::expert_type(sa.lay, 2); + ek.nrows = nrows; + ek.nexp = j - i0; + ek.maxrows = max_rows; + ek.ff = FF; + cudaGetDevice(&ek.dev); + cudaEventRecord(ek.e0, d.st); + } x3::set_gate_up(sa, c.x, D, c.row_tok + a, c.h16, FF, d.st); + if (ekp) cudaEventRecord(ek.e1, d.st); x3::set_down(sa, c.h16, FF, c.y, D, d.st); + if (ekp) { + cudaEventRecord(ek.e2, d.st); + std::lock_guard lk(prof_mu); + ek_marks.push_back(ek); + } } if (dump_y != nullptr && (dump_y_layer < 0 || l.il == dump_y_layer)) { std::vector bb(b + i0, b + j + 1); @@ -6247,16 +6293,19 @@ struct Model::Impl { engram_gate(c.h + (size_t) s0 * H * D, c.eg_kv, l.eg_w, H, D, ns, g.eps, s); } } + prof_mark(d, 4); // attention if (!hc_mix_chunk(d, c, c.h, l.hca_fn, T, c.mix, err)) return false; hc_split(c.mix, l.hca_scale, l.hca_base, H, g.sinkhorn, g.hc_eps, T, c.a_pre, c.a_post, c.a_comb, s); hc_pre_norm(c.h, c.pre, l.attn_norm, D, H, T, g.eps, c.x, s); x3::rows_f16(c.x, D, nullptr, T, D, c.x16, s); + prof_mark(d, 5); if (!gemm(d, c, l.wq_a, c.x16, D, T, c.qr, g.q_lora, 0.0f, err) || !gemm(d, c, l.wkv, c.x16, D, T, c.kvr, HD, 0.0f, err)) return false; if (l.kv_src && !gemm(d, c, l.c_wkv, c.x16, D, T, c.ckr, HD, 0.0f, err)) return false; if (l.kv_src && l.ratio > 1 && !gemm(d, c, l.c_wgate, c.x16, D, T, c.cgr, HD, 0.0f, err)) return false; + prof_mark(d, 6); Finish fq; fq.w = l.q_norm; fq.eps = g.eps; @@ -6409,6 +6458,7 @@ struct Model::Impl { } ckv = sr.ckv[(size_t) l.dev]; } + prof_mark(d, 7); // the attention in slabs: q, the sparse attention, wo_a, wo_b (this member's share) into acc if (NHL == 0) CK(cudaMemsetAsync(c.acc, 0, (size_t) T * D * sizeof(*c.acc), s)); // (no heads) for (int a0 = 0; a0 < T && NHL > 0; a0 += c.A) { @@ -6420,6 +6470,7 @@ struct Model::Impl { fr.vpp = NHL; fr.freqs = freqs; finish(c.q, na * NHL, HD, HD, fr, s); + prof_mark(d, 8); AttnRows ar; ar.gen = 1; ar.p0 = p0; @@ -6429,6 +6480,7 @@ struct Model::Impl { ar.kcap = g.ix_topk; sparse_attn(c.q, c.ext, ckv, c.topk + (size_t) a0 * topk_stride(), (int) topk_stride(), ar, l.sink, NHL, HD, na, 1.0f / std::sqrt((float) HD), c.o, s, kKvFp4, 0, &d.attn_scr); // (a short last slab) + prof_mark(d, 9); Finish fo; fo.rd = g.rd; fo.pos = (int) (p0 + a0); @@ -6466,6 +6518,7 @@ struct Model::Impl { CK(cudaMemcpyAsync(l.vs_dev, l.vs_pin, (size_t) l.n_exp * 4, cudaMemcpyHostToDevice, s)); // (this member's) moe_sort(c.ridx, T, l.k_exp, l.vs_dev, n_vs, c.bounds, c.row_tok, c.pos, s); CK(cudaMemcpyAsync(c.bounds_pin, c.bounds, (size_t) (n_vs + 1) * 4, cudaMemcpyDeviceToHost, s)); + prof_mark(d, 10); // the shared expert into acc while the host waits for the bounds if (!gemm(d, c, l.s1, c.x16, D, T, c.sg, FF, 0.0f, err) || !gemm(d, c, l.s3, c.x16, D, T, c.su, FF, 0.0f, err)) return false; @@ -7373,6 +7426,50 @@ struct Model::Impl { "ds4 prompt GPU time, %d tokens: attention %.0f ms, routing + shared expert %.0f ms, experts %.0f ms " "(with the waits for streamed ones), between layers %.0f ms\n", n, cprof_ms[1], cprof_ms[2], cprof_ms[3], cprof_ms[0]); + { // the finer table (ms, % of the sum) + static const char* nm_[16] = {"between layers", "attn rest (q_b, wo_a/b, hc_post)", "shared expert", "experts (incl waits)", + "engram", "attn mHC (mix/split/norm)", "attn projections", "compressor + indexer", + "q_b + rope", "sparse attention", "ffn mHC + router + sort", "", "", "", "", ""}; + double sum = 0; + for (double v : cprof_ms) sum += v; + for (int i = 0; i < 11; ++i) + std::fprintf(stderr, "ds4 prof %-34s %9.1f ms %5.1f%%\n", nm_[i], cprof_ms[i], sum > 0 ? 100.0 * cprof_ms[i] / sum : 0.0); + struct Agg { + double ms = 0, flops = 0; + long calls = 0, rows = 0, experts = 0; + }; + std::map, Agg> agg; // (type, role 0 gate+up, 1 down) + { + std::lock_guard lk(prof_mu); + for (const EkMark& m : ek_marks) { + float a = 0, b = 0; + cudaSetDevice(m.dev); + cudaEventElapsedTime(&a, m.e0, m.e1); + cudaEventElapsedTime(&b, m.e1, m.e2); + Agg& x = agg[{m.tg, 0}]; + x.ms += a; + x.flops += 2.0 * 2.0 * m.nrows * (double) g.dim * (double) m.ff; + x.calls++, x.rows += m.nrows, x.experts += m.nexp; + Agg& y = agg[{m.td, 1}]; + y.ms += b; + y.flops += 2.0 * m.nrows * (double) g.dim * (double) m.ff; + y.calls++, y.rows += m.nrows, y.experts += m.nexp; + ek_pool[m.dev].push_back(m.e0); + ek_pool[m.dev].push_back(m.e1); + ek_pool[m.dev].push_back(m.e2); + } + ek_marks.clear(); + } + double tot = 0; + for (auto& kv : agg) tot += kv.second.ms; + for (auto& kv : agg) + std::fprintf(stderr, + "ds4 prof expert kernels type %-8s %-7s %9.1f ms calls %5ld rows/expert %6.1f ~%5.1f TFLOPS (2048-wide ffn)\n", + gg::iq::name(kv.first.first), kv.first.second ? "down" : "gate+up", kv.second.ms, kv.second.calls, + kv.second.experts > 0 ? (double) kv.second.rows / (double) kv.second.experts : 0.0, + kv.second.ms > 0 ? kv.second.flops / kv.second.ms / 1e9 : 0.0); + std::fprintf(stderr, "ds4 prof expert kernels total %.1f ms\n", tot); + } for (double& v : cprof_ms) v = 0; prof_chunk = false; } From 8fda835383628f2308d91acfde6e72cc0d37d48e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 23 Oct 2026 21:48:14 +0200 Subject: [PATCH 04/34] dsv41: DS4_PROF expert-kernel timers on both set paths --- src/dsv41/ds4_model.cu | 43 +++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 41304d8a..1d724de8 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -3441,34 +3441,35 @@ struct Model::Impl { sa.n_embd = D; sa.n_ff = FF; sa.limit = g.lim; + EkMark ek{}; + const bool ekp = prof_chunk; + if (ekp) { + std::lock_guard lk(prof_mu); + ek.e0 = ek_ev(); + ek.e1 = ek_ev(); + ek.e2 = ek_ev(); + ek.tg = gg::expert_type(sa.lay, 0); + ek.td = gg::expert_type(sa.lay, 2); + ek.nrows = nrows; + ek.nexp = j - i0; + ek.maxrows = max_rows; + ek.ff = FF; + cudaGetDevice(&ek.dev); + cudaEventRecord(ek.e0, d.st); + } if (sa.lay.fmt == gg::kFmtMXFP4) { gg::set_gate_up(sa, c.x, D, c.row_tok + a, c.h16, FF, d.st); + if (ekp) cudaEventRecord(ek.e1, d.st); gg::set_down(sa, c.h16, FF, c.y, D, d.st); } else { - EkMark ek{}; - const bool ekp = prof_chunk; - if (ekp) { - std::lock_guard lk(prof_mu); - ek.e0 = ek_ev(); - ek.e1 = ek_ev(); - ek.e2 = ek_ev(); - ek.tg = gg::expert_type(sa.lay, 0); - ek.td = gg::expert_type(sa.lay, 2); - ek.nrows = nrows; - ek.nexp = j - i0; - ek.maxrows = max_rows; - ek.ff = FF; - cudaGetDevice(&ek.dev); - cudaEventRecord(ek.e0, d.st); - } x3::set_gate_up(sa, c.x, D, c.row_tok + a, c.h16, FF, d.st); if (ekp) cudaEventRecord(ek.e1, d.st); x3::set_down(sa, c.h16, FF, c.y, D, d.st); - if (ekp) { - cudaEventRecord(ek.e2, d.st); - std::lock_guard lk(prof_mu); - ek_marks.push_back(ek); - } + } + if (ekp) { + cudaEventRecord(ek.e2, d.st); + std::lock_guard lk(prof_mu); + ek_marks.push_back(ek); } if (dump_y != nullptr && (dump_y_layer < 0 || l.il == dump_y_layer)) { std::vector bb(b + i0, b + j + 1); From 94413c70570d34cdce9f62e4b229e355a5a6cc40 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:34:50 +0200 Subject: [PATCH 05/34] dsv41: gfx12 WMMA prompt tiles for the i-quant expert sets (STRATA_DS4_HIPK=1, default off) --- src/dsv41/ds4_iq.cu | 6 + src/dsv41/ds4_iq_hip.inc | 274 +++++++++++++++++++++++++++++++++++++ src/dsv41/ds4_iq_hip_r.inc | 177 ++++++++++++++++++++++++ src/dsv41/ds4_iq_hip_s.inc | 162 ++++++++++++++++++++++ src/dsv41/ds4_model.cu | 4 +- 5 files changed, 622 insertions(+), 1 deletion(-) create mode 100644 src/dsv41/ds4_iq_hip.inc create mode 100644 src/dsv41/ds4_iq_hip_r.inc create mode 100644 src/dsv41/ds4_iq_hip_s.inc diff --git a/src/dsv41/ds4_iq.cu b/src/dsv41/ds4_iq.cu index 40a6ff9b..b116133d 100644 --- a/src/dsv41/ds4_iq.cu +++ b/src/dsv41/ds4_iq.cu @@ -18,6 +18,8 @@ #include #include #include +#include +#include #include #include #include @@ -1172,8 +1174,12 @@ void dn_ne(const Args& a, int groups, int ne, cudaStream_t s) { else if (ne <= 8) launch_dn(a, groups, s); else launch_dn(a, groups, s); } +#include "ds4_iq_hip.inc" template void launch_set(const SetArgs& a, dim3 grid, cudaStream_t s) { +#if defined(STRATA_USE_HIP) + if (hipk::launch(a, s)) return; // (gfx12, STRATA_DS4_HIPK=1: the matrix-core tiles) +#endif #if !defined(STRATA_USE_HIP) if (tc_ok()) { set_tc_kernel<<>>(a); diff --git a/src/dsv41/ds4_iq_hip.inc b/src/dsv41/ds4_iq_hip.inc new file mode 100644 index 00000000..6fd2fcb4 --- /dev/null +++ b/src/dsv41/ds4_iq_hip.inc @@ -0,0 +1,274 @@ +// Strata. The prompt sets of ds4_iq.cu on the gfx12 (RDNA4, R9700 = gfx1201) matrix cores: v_wmma_f32_16x16x16_f16, F16 operands, +// F32 accumulation. Included by ds4_iq.cu inside its anonymous namespace (it uses its Ty, decode<>, load_tab<>, swiglu, SetArgs). +// +// The idea is the CUDA prompt tiles' (set_h16ws_kernel on f-dsv41-cuk-int2): a block-tile of the expert's rows x weight rows, K in +// steps of 64; each i-quant block is decoded ONCE into shared memory as F16 (code * the sub-block's scale: the product is exact up +// to the F16 rounding of the scale and the product) and then shared by every row of the tile; x as F16 rows next to it, both +// double-buffered, one barrier a step. The F32 FMA tile of today (set_kernel) decodes the weights once per 64 rows and does +// scalar FMAs. Default OFF: STRATA_DS4_HIPK=1 switches it on (gfx12 only, the types below, experts of more than 16 rows). +#pragma once +#if defined(STRATA_USE_HIP) + +namespace hipk { +constexpr int kStH = 72; // halves a shared row: 64 + 8 (the pad spreads the banks; rows stay 16-byte aligned) +using hv2 = _Float16 __attribute__((ext_vector_type(2))); +using hv8 = _Float16 __attribute__((ext_vector_type(8))); +using fv8 = float __attribute__((ext_vector_type(8))); + +template +constexpr bool kTypes = T == kIQ2_XXS || T == kIQ2_XS || T == kIQ2_S || T == kIQ3_XXS || T == kIQ3_S || T == kIQ4_XS || + T == kIQ1_S || T == kIQ1_M || T == kIQ4_NL; + +__device__ __forceinline__ fv8 wmma16(hv8 a, hv8 b, fv8 c) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + return c; +#endif +} +__device__ __forceinline__ uint32_t as_u32(hv2 v) { return __builtin_bit_cast(uint32_t, v); } +__device__ __forceinline__ hv2 as_hv2(uint32_t v) { return __builtin_bit_cast(hv2, v); } +// 4 int8 codes (a word) -> 4 halves times the scale: 1024 + (code + 128) is exact in a half's mantissa, less 1152 +__device__ __forceinline__ uint2 codes4(int w, hv2 sc) { + const uint32_t u = (uint32_t) w ^ 0x80808080u; + const uint32_t lo = __byte_perm(u, 0x64646464u, 0x5140), hi = __byte_perm(u, 0x64646464u, 0x5342); + const hv2 m = {(_Float16) 1152.0f, (_Float16) 1152.0f}; + const hv2 a = (as_hv2(lo) - m) * sc, b = (as_hv2(hi) - m) * sc; + return make_uint2(as_u32(a), as_u32(b)); +} + +// BM rows x BN weight rows (a matrix: gate and up: two) per block, 8 waves WM x WN, each wave (BM/WM) x (BN/WN) +template +__global__ void __launch_bounds__(256) set_kernel(const SetArgs a, int dbg) { + static_assert(WM * WN == 8, "8 waves"); + constexpr int NM = GU ? 2 : 1, MT = BM / WM / 16, NT = BN / WN / 16; + static_assert(MT >= 1 && NT >= 1 && MT * WM * 16 == BM && NT * WN * 16 == BN, "wave tiling"); + __shared__ uint32_t tab[Ty::TAB > 0 ? Ty::TAB : 1]; + __shared__ int srow[BM]; + __shared__ __align__(16) _Float16 xs[2][BM][kStH]; + __shared__ __align__(16) _Float16 ws[2][NM][BN][kStH]; + const int e = blockIdx.z; + const int lo = a.bounds[e] - a.row0, hi_r = a.bounds[e + 1] - a.row0; + const int r0 = lo + blockIdx.x * BM; + if (r0 >= hi_r || hi_r - lo <= a.skip_le) return; // (uniform) + load_tab(tab); + const int nr = min(BM, hi_r - r0); + const int c0 = blockIdx.y * BN; + const uint8_t* blob = a.wbase + (size_t) e * a.stride; + const int K = GU ? a.n_embd : a.n_ff; + const size_t rb = row_bytes_t(K); + const int tid = (int) threadIdx.x, warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4; + if (tid < BM) srow[tid] = GU ? a.idx[r0 + min(tid, nr - 1)] : r0 + min(tid, nr - 1); + __syncthreads(); + const int nst = K / 64; + + // a step's operands are fetched and decoded into registers (the global loads and the codebook's lookups) while the matrix + // cores work on the step before, and written to shared memory after them + constexpr int NI = (NM * BN * 2 + 255) / 256; // weight items a thread + constexpr int NX = GU ? (BM * 16 + 255) / 256 : (BM * 8 + 255) / 256; // row chunks a thread + struct Regs { + int q[NI][8]; + _Float16 sc0[NI], sc1[NI]; + float4 xv[GU ? NX : 1]; + uint4 xu[GU ? 1 : NX]; + }; + auto fetch = [&](int s, Regs& R) { +#pragma unroll + for (int ii = 0; ii < NI; ++ii) { + const int it = tid + ii * 256; + if (it < NM * BN * 2) { + const int kbl = it & 1, col = (it >> 1) % BN, mat = it / (2 * BN); + Sub sb; + if (dbg & 2) { for (int w = 0; w < 8; ++w) sb.q[w] = tid + w; sb.d = 1.0f; sb.s0 = sb.s1 = 1; } else + decode(blob + a.tr[GU ? mat : 2] + (size_t) (c0 + col) * rb, s * 2 + kbl, tab, sb); +#pragma unroll + for (int w = 0; w < 8; ++w) R.q[ii][w] = sb.q[w]; + R.sc0[ii] = (_Float16) (sb.d * (float) sb.s0); + R.sc1[ii] = (_Float16) (sb.d * (float) sb.s1); + } + } +#pragma unroll + for (int xi = 0; xi < NX; ++xi) { + const int c = tid + xi * 256; + if constexpr (GU) { + if (c < BM * 16) { + const int row = c >> 4, ch = c & 15; + R.xv[xi] = *(const float4*) (a.xf + (size_t) srow[row] * a.ldx + (size_t) s * 64 + ch * 4); + } + } else { + if (c < BM * 8) { + const int row = c >> 3, ch = c & 7; + R.xu[xi] = *(const uint4*) (a.xh + (size_t) srow[row] * a.ldx + (size_t) s * 64 + ch * 8); + } + } + } + }; + auto store = [&](const Regs& R, int b) { +#pragma unroll + for (int ii = 0; ii < NI; ++ii) { + const int it = tid + ii * 256; + if (it < NM * BN * 2) { + const int kbl = it & 1, col = (it >> 1) % BN, mat = it / (2 * BN); + const hv2 h0 = {R.sc0[ii], R.sc0[ii]}, h1 = {R.sc1[ii], R.sc1[ii]}; + uint2* dst = (uint2*) &ws[b][mat][col][kbl * 32]; // (values 4 w .. 4 w + 3 of the half at dst[w], 16 + 4 w .. at dst[4 + w]) +#pragma unroll + for (int w = 0; w < 4; ++w) { + dst[w] = codes4(R.q[ii][w], h0); + dst[4 + w] = codes4(R.q[ii][4 + w], h1); + } + } + } +#pragma unroll + for (int xi = 0; xi < NX; ++xi) { + const int c = tid + xi * 256; + if constexpr (GU) { + if (c < BM * 16) { + const int row = c >> 4, ch = c & 15; + const float4 v = R.xv[xi]; + const hv2 p = {(_Float16) v.x, (_Float16) v.y}, q = {(_Float16) v.z, (_Float16) v.w}; + *(uint2*) &xs[b][row][ch * 4] = make_uint2(as_u32(p), as_u32(q)); + } + } else { + if (c < BM * 8) { + const int row = c >> 3, ch = c & 7; + *(uint4*) &xs[b][row][ch * 8] = R.xu[xi]; + } + } + } + }; + + const int wm = warp / WN, wn = warp % WN; + fv8 acc[NM][MT][NT]; +#pragma unroll + for (int m = 0; m < NM; ++m) +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < NT; ++j) acc[m][i][j] = fv8{0, 0, 0, 0, 0, 0, 0, 0}; + + // read-ahead: the first and last byte of the weights' block and a word of the rows' line of a step PF steps on, summed into a + // value that is never used (the loads only warm the caches; their latency is not waited for until the end) + int touched = 0; + auto touch = [&](int s) { + if (dbg & 4) return; +#pragma unroll + for (int ii = 0; ii < NI; ++ii) { + const int it = tid + ii * 256; + if (it < NM * BN * 2) { + const int col = (it >> 1) % BN, mat = it / (2 * BN); + const uint8_t* p = blob + a.tr[GU ? mat : 2] + (size_t) (c0 + col) * rb + (size_t) ((s * 2) >> 3) * Ty::B; + touched += p[0] + p[Ty::B - 1]; + } + } + if constexpr (GU) { + for (int c = tid; c < BM * 2; c += 256) touched += (int) a.xf[(size_t) srow[c >> 1] * a.ldx + (size_t) s * 64 + (c & 1) * 32]; + } else { + for (int c = tid; c < BM * 2; c += 256) touched += (int) a.xh[(size_t) srow[c >> 1] * a.ldx + (size_t) s * 64 + (c & 1) * 32]; + } + }; + constexpr int PF = 4; + for (int s = 1; s <= PF && s < nst; ++s) touch(s + 1 < nst ? s + 1 : s); + { + Regs R0; + fetch(0, R0); + store(R0, 0); + } + __syncthreads(); + for (int s = 0; s < nst; ++s) { + const int b = s & 1; + Regs R; + if (s + 1 < nst) fetch(s + 1, R); + if (s + 1 + PF < nst) touch(s + 1 + PF); +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + hv8 af[MT]; +#pragma unroll + for (int i = 0; i < MT; ++i) af[i] = *(const hv8*) &xs[b][wm * (16 * MT) + i * 16 + l16][kk * 16 + hi * 8]; +#pragma unroll + for (int m = 0; m < NM; ++m) +#pragma unroll + for (int j = 0; j < NT; ++j) { + const hv8 bf = *(const hv8*) &ws[b][m][wn * (16 * NT) + j * 16 + l16][kk * 16 + hi * 8]; +#pragma unroll + for (int i = 0; i < MT; ++i) + if (!(dbg & 1) && wm * (16 * MT) + i * 16 < nr) acc[m][i][j] = wmma16(af[i], bf, acc[m][i][j]); // (a tile past the rows: skipped, uniform) + } + } + if (s + 1 < nst) store(R, b ^ 1); + __syncthreads(); + } + if (touched == 0x7fffffff && tid == 12345) a.y[0] = 0.0f; + // D[row = 8 hi + i][col = l16] of every tile +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int q = 0; q < 8; ++q) { + const int row = wm * (16 * MT) + i * 16 + 8 * hi + q; + if (row >= nr) continue; + const size_t lr = (size_t) (r0 + row); +#pragma unroll + for (int j = 0; j < NT; ++j) { + const int col = c0 + wn * (16 * NT) + j * 16 + l16; + if (GU) a.h[lr * a.ldo + col] = __half_as_ushort(__float2half_rn(swiglu(acc[0][i][j][q], acc[1][i][j][q], a.limit))); + else a.y[lr * a.ldo + col] = acc[0][i][j][q]; + } + } +} + +#include "ds4_iq_hip_r.inc" + +inline bool ok_device() { // gfx12 and STRATA_DS4_HIPK=1 + static std::atomic state[16]; + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 16) return false; + int v = state[dev].load(std::memory_order_relaxed); + if (v == 0) { + cudaDeviceProp prop{}; + const bool gfx12 = cudaGetDeviceProperties(&prop, dev) == cudaSuccess && std::strncmp(prop.gcnArchName, "gfx12", 5) == 0; + const char* e = std::getenv("STRATA_DS4_HIPK"); + v = gfx12 && e != nullptr && e[0] != '0' ? 1 : 2; + state[dev].store(v, std::memory_order_relaxed); + } + return v == 1; +} + +template +inline bool run(const SetArgs& a, cudaStream_t s) { + const int N = GU ? a.n_ff : a.n_embd; + const dim3 grid((unsigned) ((a.max_rows + BM - 1) / BM), (unsigned) (N / BN), (unsigned) a.n_exp); + static const int dbg = std::getenv("HIPK_DBG") ? std::atoi(std::getenv("HIPK_DBG")) : 0; + set_kernel<<>>(a, dbg); + return cudaPeekAtLastError() == cudaSuccess; +} +// false: not taken (the caller's tiles do it) +template +inline bool launch(const SetArgs& a, cudaStream_t s) { + if constexpr (!kTypes) { + return false; + } else { + if (!ok_device() || a.max_rows <= 16) return false; + const int K = GU ? a.n_embd : a.n_ff, N = GU ? a.n_ff : a.n_embd; + if (K % 256 != 0 || N % 64 != 0 || a.ldx % 8 != 0 || a.ldo % 2 != 0) return false; + if (((uintptr_t) (GU ? (const void*) a.xf : (const void*) a.xh) & 15) != 0) return false; + static const int var = std::getenv("STRATA_DS4_HIPK") ? std::atoi(std::getenv("STRATA_DS4_HIPK")) : 0; + if (var != 2) { // 2: the shared-memory weights kernel + static const int cfg = std::getenv("HIPK_CFG") ? std::atoi(std::getenv("HIPK_CFG")) : 0; + if (cfg == 1 && a.max_rows <= 32) return runr(a, s); + if (cfg == 2 && a.max_rows <= 32) return runr(a, s); + if (cfg == 3 && a.max_rows <= 32) return runr(a, s); + if (cfg == 4 && a.max_rows <= 32) return runr(a, s); + if (cfg == 5 && a.max_rows <= 32) return runr(a, s); + if (a.max_rows <= 32) return runr(a, s); + if (a.max_rows <= 64) return runr(a, s); + return runr(a, s); + } + if (a.max_rows <= 32) return run(a, s); + if (a.max_rows <= 64) return run(a, s); + if constexpr (GU) return run(a, s); + else return run(a, s); + } +} +} // namespace hipk + +#endif diff --git a/src/dsv41/ds4_iq_hip_r.inc b/src/dsv41/ds4_iq_hip_r.inc new file mode 100644 index 00000000..73660660 --- /dev/null +++ b/src/dsv41/ds4_iq_hip_r.inc @@ -0,0 +1,177 @@ +// Strata. Part of ds4_iq_hip.inc (included from it): the weights straight into the matrix cores' registers. +// One lane of the B operand of a 16x16x16 step holds 8 consecutive k of one weight row: exactly one 8-value group of a 32-value +// sub-block of an i-quant block (the grid entry, its signs). grp_dec decodes that group alone: 8 int8 codes (two words) and the +// scale (weight = scale * code), so a wave needs no shared memory for the weights and no barrier: every wave decodes its own +// columns once and uses them for every row of the tile. kb: the 32-value sub-block of the row, p: its group (0..3). +// The decode is in two halves so that the loads of a k-step can be issued one k-step ahead of its use: grp_load fetches the +// group raw bytes into registers (Raw), grp_dec turns them into codes and scale (the codebook lookups, the signs). +__device__ __forceinline__ float hf(uint32_t h) { return __half2float(__ushort_as_half((uint16_t) h)); } +#include "ds4_iq_hip_s.inc" + +constexpr int kKC = 64; // K a step: two sub-blocks +// BM rows (MT tiles of 16) x BN = NW 16 NTW weight rows per block; NW waves, each NTW column tiles of 16 and every row tile +template +__global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg) { + constexpr int NM = GU ? 2 : 1, MT = BM / 16, BN = NW * 16 * NTW, NTH = NW * 32; + static_assert(BM % 16 == 0, "row tiles"); + __shared__ uint32_t tab[Ty::TAB > 0 ? Ty::TAB : 1]; + __shared__ int srow[BM]; + __shared__ __align__(16) _Float16 xs[2][BM][kStH]; + const int e = blockIdx.z; + const int lo = a.bounds[e] - a.row0, hi_r = a.bounds[e + 1] - a.row0; + const int r0 = lo + blockIdx.x * BM; + if (r0 >= hi_r || hi_r - lo <= a.skip_le) return; // (uniform) + load_tab(tab); + const int nr = min(BM, hi_r - r0); + const int c0 = blockIdx.y * BN; + const uint8_t* blob = a.wbase + (size_t) e * a.stride; + const int K = GU ? a.n_embd : a.n_ff; + const size_t rb = row_bytes_t(K); + const int tid = (int) threadIdx.x, warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4; + for (int i = tid; i < BM; i += NTH) srow[i] = GU ? a.idx[r0 + min(i, nr - 1)] : r0 + min(i, nr - 1); + __syncthreads(); + const int nst = K / kKC; + // the weight rows of this lane column tiles + const uint8_t* wrow[NM][NTW]; +#pragma unroll + for (int m = 0; m < NM; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) + wrow[m][j] = blob + a.tr[GU ? m : 2] + (size_t) ((c0 + warp * (16 * NTW) + j * 16 + l16)) * rb; + + constexpr int NX = GU ? (BM * 16 + NTH - 1) / NTH : (BM * 8 + NTH - 1) / NTH; + struct XR { + float4 f[GU ? NX : 1]; + uint4 u[GU ? 1 : NX]; + }; + auto fetchx = [&](int s, XR& R) { +#pragma unroll + for (int xi = 0; xi < NX; ++xi) { + const int c = tid + xi * NTH; + if constexpr (GU) { + if (c < BM * 16) { + const int row = c >> 4, ch = c & 15; + R.f[xi] = *(const float4*) (a.xf + (size_t) srow[row] * a.ldx + (size_t) s * kKC + ch * 4); + } + } else { + if (c < BM * 8) { + const int row = c >> 3, ch = c & 7; + R.u[xi] = *(const uint4*) (a.xh + (size_t) srow[row] * a.ldx + (size_t) s * kKC + ch * 8); + } + } + } + }; + auto storex = [&](const XR& R, int b) { +#pragma unroll + for (int xi = 0; xi < NX; ++xi) { + const int c = tid + xi * NTH; + if constexpr (GU) { + if (c < BM * 16) { + const int row = c >> 4, ch = c & 15; + const float4 v = R.f[xi]; + const hv2 p = {(_Float16) v.x, (_Float16) v.y}, q = {(_Float16) v.z, (_Float16) v.w}; + *(uint2*) &xs[b][row][ch * 4] = make_uint2(as_u32(p), as_u32(q)); + } + } else { + if (c < BM * 8) { + const int row = c >> 3, ch = c & 7; + *(uint4*) &xs[b][row][ch * 8] = R.u[xi]; + } + } + } + }; + + fv8 acc[NM][MT][NTW]; +#pragma unroll + for (int m = 0; m < NM; ++m) +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[m][i][j] = fv8{0, 0, 0, 0, 0, 0, 0, 0}; + + { + XR R0; + fetchx(0, R0); + storex(R0, 0); + } + // the weights of a step (64 values) are loaded one step ahead: two sets of registers, the step loop unrolled by two + SRaw sr0[NM][NTW], sr1[NM][NTW]; + auto load_stage = [&](SRaw (&dst)[NM][NTW], int s) { +#pragma unroll + for (int m = 0; m < NM; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) stage_load(wrow[m][j], s, hi, dst[m][j]); + }; + auto do_stage = [&](int s, SRaw (&cur)[NM][NTW], SRaw (&nxt)[NM][NTW]) { + const int b = s & 1; + XR R; + if (s + 1 < nst) { + fetchx(s + 1, R); + load_stage(nxt, s + 1); + } + hv8 bf[NM][NTW]; + auto step = [&](auto tt) { + constexpr int t = decltype(tt)::value; + constexpr int sub = t >> 1, ks = t & 1; +#pragma unroll + for (int m = 0; m < NM; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) { + int c0_, c1_; + float sc; + step_dec(cur[m][j], s, hi, tab, c0_, c1_, sc); + const hv2 h = {(_Float16) sc, (_Float16) sc}; + const uint2 u0 = codes4(c0_, h), u1 = codes4(c1_, h); + bf[m][j] = __builtin_bit_cast(hv8, make_uint4(u0.x, u0.y, u1.x, u1.y)); + } + const int kcol = sub * 32 + ks * 16 + hi * 8; +#pragma unroll + for (int i = 0; i < MT; ++i) { + if (i * 16 < nr) { // (a tile past the rows: skipped, uniform) + const hv8 af = *(const hv8*) &xs[b][i * 16 + l16][kcol]; +#pragma unroll + for (int m = 0; m < NM; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[m][i][j] = wmma16(af, bf[m][j], acc[m][i][j]); + } + } + }; + step(std::integral_constant{}); + step(std::integral_constant{}); + step(std::integral_constant{}); + step(std::integral_constant{}); + if (s + 1 < nst) storex(R, b ^ 1); + __syncthreads(); + }; + load_stage(sr0, 0); + __syncthreads(); + for (int s = 0; s < nst; s += 2) { // (nst is a multiple of 4) + do_stage(s, sr0, sr1); + do_stage(s + 1, sr1, sr0); + } +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int q = 0; q < 8; ++q) { + const int row = i * 16 + 8 * hi + q; + if (row >= nr) continue; + const size_t lr = (size_t) (r0 + row); +#pragma unroll + for (int j = 0; j < NTW; ++j) { + const int col = c0 + warp * (16 * NTW) + j * 16 + l16; + if (GU) a.h[lr * a.ldo + col] = __half_as_ushort(__float2half_rn(swiglu(acc[0][i][j][q], acc[1][i][j][q], a.limit))); + else a.y[lr * a.ldo + col] = acc[0][i][j][q]; + } + } +} + +template +inline bool runr(const SetArgs& a, cudaStream_t s) { + const int N = GU ? a.n_ff : a.n_embd; + constexpr int BN = NW * 16 * NTW; + if (N % BN != 0) return false; + const dim3 grid((unsigned) ((a.max_rows + BM - 1) / BM), (unsigned) (N / BN), (unsigned) a.n_exp); + static const int dbg = std::getenv("HIPK_DBG") ? std::atoi(std::getenv("HIPK_DBG")) : 0; + set_kernel_r<<>>(a, dbg); + return cudaPeekAtLastError() == cudaSuccess; +} diff --git a/src/dsv41/ds4_iq_hip_s.inc b/src/dsv41/ds4_iq_hip_s.inc new file mode 100644 index 00000000..1dee41ad --- /dev/null +++ b/src/dsv41/ds4_iq_hip_s.inc @@ -0,0 +1,162 @@ +// Strata. Part of ds4_iq_hip_r.inc: the weights of a whole 64-value step (two 32-value sub-blocks) of one weight row in a few wide +// loads, and the decode of its four 8-value groups (k-steps) from registers. The loads are unaligned (the blocks of the i-quants are +// 2-byte aligned; the AMD hardware takes unaligned vector loads). A lane holds the group p = 2 ks + hi of every sub-block, so +// the two lanes of a column (hi 0 / 1) share most of their bytes. s: the step (64 values), b: the block (256 values: 4 steps), +// jb = 2 (s & 3): the first sub-block of the step in its block. +struct SRaw { + uint32_t w[10]; +}; +__device__ __forceinline__ uint4 ldu128(const void* p) { + uint4 v; + __builtin_memcpy(&v, p, 16); + return v; +} +__device__ __forceinline__ uint2 ldu64(const void* p) { + uint2 v; + __builtin_memcpy(&v, p, 8); + return v; +} +__device__ __forceinline__ uint32_t ldu32(const void* p) { + uint32_t v; + __builtin_memcpy(&v, p, 4); + return v; +} +__device__ __forceinline__ uint32_t ldu16(const void* p) { + uint16_t v; + __builtin_memcpy(&v, p, 2); + return v; +} +template +__device__ __forceinline__ void stage_load(const uint8_t* __restrict__ row, int s, int hi, SRaw& r) { + if constexpr (T == kIQ4_NL) { // 32-value blocks of 18 bytes: the step is blocks 2 s and 2 s + 1 + const uint8_t* b0 = row + (size_t) (2 * s) * 18; + const uint2 qa = ldu64(b0 + 2 + 8 * hi), qb = ldu64(b0 + 18 + 2 + 8 * hi); + r.w[0] = qa.x, r.w[1] = qa.y, r.w[2] = qb.x, r.w[3] = qb.y; + r.w[4] = ldu16(b0); + r.w[5] = ldu16(b0 + 18); + } else { + const uint8_t* b = row + (size_t) (s >> 2) * Ty::B; + const int jb = 2 * (s & 3); + if constexpr (T == kIQ2_XXS) { + const uint4 q = ldu128(b + 2 + 8 * jb); + r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w; + r.w[4] = ldu16(b); + } else if constexpr (T == kIQ2_XS) { + const uint4 q = ldu128(b + 2 + 8 * jb); + r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w; + r.w[4] = ldu16(b + 66 + jb); + r.w[5] = ldu16(b); + } else if constexpr (T == kIQ2_S) { + const uint2 q = ldu64(b + 2 + 4 * jb), sg = ldu64(b + 34 + 4 * jb); + r.w[0] = q.x, r.w[1] = q.y, r.w[2] = sg.x, r.w[3] = sg.y; + r.w[4] = ldu16(b + 66 + jb); + r.w[5] = ldu16(b + 74 + jb); + r.w[6] = ldu16(b); + } else if constexpr (T == kIQ3_XXS) { + const uint4 q = ldu128(b + 2 + 8 * jb); + const uint2 ax = ldu64(b + 66 + 4 * jb); + r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w; + r.w[4] = ax.x, r.w[5] = ax.y; + r.w[6] = ldu16(b); + } else if constexpr (T == kIQ3_S) { + const uint4 q = ldu128(b + 2 + 8 * jb); + const uint2 sg = ldu64(b + 74 + 4 * jb); + r.w[0] = q.x, r.w[1] = q.y, r.w[2] = q.z, r.w[3] = q.w; + r.w[4] = ldu16(b + 66 + jb); + r.w[5] = sg.x, r.w[6] = sg.y; + r.w[7] = b[106 + (jb >> 1)]; + r.w[8] = ldu16(b); + } else if constexpr (T == kIQ4_XS) { + const uint2 qa = ldu64(b + 8 + 16 * jb + 8 * hi), qb = ldu64(b + 8 + 16 * (jb + 1) + 8 * hi); + r.w[0] = qa.x, r.w[1] = qa.y, r.w[2] = qb.x, r.w[3] = qb.y; + r.w[4] = ldu16(b + 2); + r.w[5] = b[4 + (jb >> 1)]; + r.w[6] = ldu16(b); + } else if constexpr (T == kIQ1_S) { + const uint2 q = ldu64(b + 2 + 4 * jb); + r.w[0] = q.x, r.w[1] = q.y; + r.w[2] = ldu32(b + 34 + 2 * jb); + r.w[3] = ldu16(b); + } else { // IQ1_M + const uint2 q = ldu64(b + 4 * jb); + const uint2 d4 = ldu64(b + 48); + r.w[0] = q.x, r.w[1] = q.y; + r.w[2] = ldu32(b + 32 + 2 * jb); + r.w[3] = ldu16(b + 48 + (jb >> 1) * 2); + r.w[4] = d4.x, r.w[5] = d4.y; + } + } +} +// the k-step t (0..3, compile time) of a loaded step: sub-block sub = t >> 1, group p = 2 (t & 1) + hi +template +__device__ __forceinline__ void step_dec(const SRaw& r, int s, int hi, const uint32_t* tab, int& c0, int& c1, float& sc) { + constexpr int sub = TT >> 1, ks = TT & 1; + const int p = 2 * ks + hi; + if constexpr (T == kIQ2_XXS) { + const uint2 g = ((const uint2*) tab)[(r.w[2 * sub] >> (8 * p)) & 255u]; + const uint32_t a1 = r.w[2 * sub + 1]; + const uint32_t sg = ksigns8(a1 >> (7 * p)); + c0 = sgn4(g.x, sg); + c1 = sgn4(g.y, sg >> 4); + sc = hf(r.w[4]) * (float) (2 * (int) (a1 >> 28) + 1) * 0.125f; + } else if constexpr (T == kIQ2_XS) { + const uint32_t v = (r.w[2 * sub + (ks)] >> (16 * hi)) & 0xffffu; + const uint2 g = ((const uint2*) tab)[v & 511u]; + const uint32_t sg = ksigns8(v >> 9); + const uint32_t scb = (r.w[4] >> (8 * sub)) & 255u; + c0 = sgn4(g.x, sg); + c1 = sgn4(g.y, sg >> 4); + sc = hf(r.w[5]) * (float) (2 * (int) (ks == 0 ? scb & 15 : scb >> 4) + 1) * 0.125f; + } else if constexpr (T == kIQ2_S) { + const uint32_t qh = (r.w[4] >> (8 * sub)) & 255u; + const uint32_t idx = ((r.w[sub] >> (8 * p)) & 255u) | ((qh << (8 - 2 * p)) & 0x300u); + const uint32_t sg = (r.w[2 + sub] >> (8 * p)) & 255u; + const uint32_t scb = (r.w[5] >> (8 * sub)) & 255u; + const uint2 g = ((const uint2*) tab)[idx]; + c0 = sgn4(g.x, sg); + c1 = sgn4(g.y, sg >> 4); + sc = hf(r.w[6]) * (float) (2 * (int) (ks == 0 ? scb & 15 : scb >> 4) + 1) * 0.125f; + } else if constexpr (T == kIQ3_XXS) { + const uint32_t word = r.w[2 * sub + ks]; + const uint32_t aux = r.w[4 + sub]; + const uint32_t sg = ksigns8(aux >> (7 * p)); + c0 = sgn4(tab[(word >> (16 * hi)) & 255u], sg); + c1 = sgn4(tab[(word >> (16 * hi + 8)) & 255u], sg >> 4); + sc = hf(r.w[6]) * (float) (2 * (int) (aux >> 28) + 1) * 0.25f; + } else if constexpr (T == kIQ3_S) { + const uint32_t word = r.w[2 * sub + ks]; + const uint32_t h = (r.w[4] >> (8 * sub)) & 255u; + const uint32_t sg = (r.w[5 + sub] >> (8 * p)) & 255u; + c0 = sgn4(tab[((word >> (16 * hi)) & 255u) | ((h << (8 - 2 * p)) & 256u)], sg); + c1 = sgn4(tab[((word >> (16 * hi + 8)) & 255u) | ((h << (7 - 2 * p)) & 256u)], sg >> 4); + sc = hf(r.w[8]) * (float) (1 + 2 * (int) ((r.w[7] >> (4 * sub)) & 15)); + } else if constexpr (T == kIQ4_XS) { + const int jb = 2 * (s & 3); + const int ls = ((r.w[5] >> (4 * sub)) & 15) | (((r.w[4] >> (2 * (jb + sub))) & 3) << 4); + const int2 v0 = tab16(r.w[2 * sub], tab), v1 = tab16(r.w[2 * sub + 1], tab); + c0 = ks == 0 ? v0.x : v0.y; + c1 = ks == 0 ? v1.x : v1.y; + sc = hf(r.w[6]) * (float) (ls - 32); + } else if constexpr (T == kIQ1_S) { + const uint32_t qh = (r.w[2] >> (16 * sub)) & 0xffffu; + const uint32_t g = tab[((r.w[sub] >> (8 * p)) & 255u) | (((qh >> (3 * p)) & 7u) << 8)]; + const bool neg = (qh & 0x8000u) != 0; + c0 = (int) iq1_codes(g & 0x0F0F0F0Fu, neg); + c1 = (int) iq1_codes((g >> 4) & 0x0F0F0F0Fu, neg); + sc = hf(r.w[3]) * (float) (2 * (int) ((qh >> 12) & 7u) + 1) * 0.125f; + } else if constexpr (T == kIQ1_M) { + const uint32_t qh = (r.w[2] >> (8 * (2 * sub + ks))) & 255u; // (p < 2: the first byte of the sub-block, else the second) + const uint32_t g = tab[((r.w[sub] >> (8 * p)) & 255u) | ((qh << (hi ? 4 : 8)) & 0x700u)]; + const bool neg = (hi ? qh & 0x80u : qh & 0x08u) != 0; + c0 = (int) iq1_codes(g & 0x0F0F0F0Fu, neg); + c1 = (int) iq1_codes((g >> 4) & 0x0F0F0F0Fu, neg); + const int sh = (int) ((r.w[3] >> (6 * sub + (ks == 0 ? 0 : 3))) & 7u); + const uint32_t d16 = (r.w[4] >> 12 & 0xfu) | ((r.w[4] >> 24) & 0xf0u) | ((r.w[5] >> 4) & 0xf00u) | ((r.w[5] >> 16) & 0xf000u); + sc = hf(d16) * (float) (2 * sh + 1) * 0.125f; + } else { // IQ4_NL + const int2 v0 = tab16(r.w[2 * sub], tab), v1 = tab16(r.w[2 * sub + 1], tab); + c0 = ks == 0 ? v0.x : v0.y; + c1 = ks == 0 ? v1.x : v1.y; + sc = hf(r.w[4 + sub]); + } +} diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 1d724de8..2126ab33 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -7465,8 +7465,10 @@ struct Model::Impl { for (auto& kv : agg) tot += kv.second.ms; for (auto& kv : agg) std::fprintf(stderr, - "ds4 prof expert kernels type %-8s %-7s %9.1f ms calls %5ld rows/expert %6.1f ~%5.1f TFLOPS (2048-wide ffn)\n", + "ds4 prof expert kernels type %-8s %-7s %9.1f ms calls %5ld experts %6ld (%.1f us each, %.1f a call) rows/expert %6.1f ~%5.1f TFLOPS\n", gg::iq::name(kv.first.first), kv.first.second ? "down" : "gate+up", kv.second.ms, kv.second.calls, + kv.second.experts, kv.second.experts > 0 ? 1e3 * kv.second.ms / (double) kv.second.experts : 0.0, + kv.second.calls > 0 ? (double) kv.second.experts / (double) kv.second.calls : 0.0, kv.second.experts > 0 ? (double) kv.second.rows / (double) kv.second.experts : 0.0, kv.second.ms > 0 ? kv.second.flops / kv.second.ms / 1e9 : 0.0); std::fprintf(stderr, "ds4 prof expert kernels total %.1f ms\n", tot); From a23b5f209ccb9c4b42c3a27a509f5b57d2bfeab3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:35:47 +0200 Subject: [PATCH 06/34] dsv41: gfx12 WMMA expert tiles on by default (STRATA_DS4_HIPK=0 turns them off) --- src/dsv41/ds4_iq_hip.inc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/dsv41/ds4_iq_hip.inc b/src/dsv41/ds4_iq_hip.inc index 6fd2fcb4..29abeda8 100644 --- a/src/dsv41/ds4_iq_hip.inc +++ b/src/dsv41/ds4_iq_hip.inc @@ -5,7 +5,7 @@ // steps of 64; each i-quant block is decoded ONCE into shared memory as F16 (code * the sub-block's scale: the product is exact up // to the F16 rounding of the scale and the product) and then shared by every row of the tile; x as F16 rows next to it, both // double-buffered, one barrier a step. The F32 FMA tile of today (set_kernel) decodes the weights once per 64 rows and does -// scalar FMAs. Default OFF: STRATA_DS4_HIPK=1 switches it on (gfx12 only, the types below, experts of more than 16 rows). +// scalar FMAs. Default ON for gfx12, STRATA_DS4_HIPK=0 switches it off (gfx12 only, the types below, experts of more than 16 rows). #pragma once #if defined(STRATA_USE_HIP) @@ -217,7 +217,7 @@ __global__ void __launch_bounds__(256) set_kernel(const SetArgs a, int dbg) { #include "ds4_iq_hip_r.inc" -inline bool ok_device() { // gfx12 and STRATA_DS4_HIPK=1 +inline bool ok_device() { // gfx12 unless STRATA_DS4_HIPK=0 static std::atomic state[16]; int dev = 0; cudaGetDevice(&dev); @@ -227,7 +227,7 @@ inline bool ok_device() { // gfx12 and STRATA_DS4_HIPK=1 cudaDeviceProp prop{}; const bool gfx12 = cudaGetDeviceProperties(&prop, dev) == cudaSuccess && std::strncmp(prop.gcnArchName, "gfx12", 5) == 0; const char* e = std::getenv("STRATA_DS4_HIPK"); - v = gfx12 && e != nullptr && e[0] != '0' ? 1 : 2; + v = gfx12 && !(e != nullptr && e[0] == '0') ? 1 : 2; // (on by default on gfx12; STRATA_DS4_HIPK=0 off) state[dev].store(v, std::memory_order_relaxed); } return v == 1; From 062fd4a95e5fda85e7379c90a16eb88dd901acfe Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:38:34 +0200 Subject: [PATCH 07/34] release notes 0.2.4: the DeepSeek engine is a separate download (automatic and by hand), Qwen engines unchanged --- docs/release-notes-0.2.4.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index 2b1849eb..fadabfac 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -53,13 +53,26 @@ These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so e ## Updating -- **From 0.2.3 or 0.2.3.1:** run `strata update` in the Terminal. It fetches Control 0.1.49 and, on Windows NVIDIA, Linux NVIDIA and Linux AMD (Radeon AI PRO R9700 and RX 9070) PCs, the engine package that carries DeepSeek. Other engine packages stay at 0.1.48. The app is not touched. +- **From 0.2.3 or 0.2.3.1:** run `strata update` in the Terminal. It fetches Control 0.1.49. Your Qwen engine does not change: every engine package is still the 0.1.48 file, byte for byte. - **Mac:** the Mac Terminal and engine stay on 0.1.48. DeepSeek is not on the Mac yet. - **New installs:** the install command (`install.ps1` on Windows, `install.sh` on Linux) installs this version. +## The DeepSeek engine is a separate download + +DeepSeek runs on its own engine package, `strata-dsv41`, which sits beside your Qwen engine and never replaces it. There are two ways to get it. + +- **Automatic:** choose DeepSeek in `strata launch` or `strata setup`. Strata downloads the package that fits your PC, checks its signature and installs it. +- **By hand:** download the package for your system from this page, check it against `SHA256SUMS.txt`, and install it with the command in the Terminal guide. TODO(setup worker): exact command. + +| System | File | +|---|---| +| Windows, NVIDIA RTX 30 / 40 / 50 | `strata-dsv41-0.1.49-windows-x86_64-cuda-cuda13.tar.gz` | +| Linux, NVIDIA RTX 30 / 40 / 50 | `strata-dsv41-0.1.49-linux-x86_64-cuda-cuda13.tar.gz` | +| Linux, Radeon AI PRO R9700 / RX 9070 | `strata-dsv41-0.1.49-linux-x86_64-hip-rx9070.tar.gz` | + ## Downloads -Everything from 0.2.3 is attached again, so the release page still holds every file. New in this release: `strata-control-0.1.49-windows-x86_64.zip`, `strata-control-0.1.49-linux-x86_64.tar.gz` and the three engine packages `strata-engine-0.1.49-windows-x86_64-cuda-cuda13`, `strata-engine-0.1.49-linux-x86_64-cuda-cuda13` and `strata-engine-0.1.49-linux-x86_64-hip-rx9070`. The installers, AppImages, dmg and the other engine packages are the 0.2.3 files. +Everything from 0.2.3 is attached again, so the release page still holds every file. New in this release: `strata-control-0.1.49-windows-x86_64.zip`, `strata-control-0.1.49-linux-x86_64.tar.gz` and the three DeepSeek packages above. The installers, AppImages, dmg and the Qwen engine packages are the 0.2.3 files. ## Thanks From 71c674dcdb5d38e38d961b414aea9faf3daf8338 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:41:28 +0200 Subject: [PATCH 08/34] DeepSeek engine by hand: --dsv41-package FILE (setup and strata launch) or a file put in engine-dsv41/; the package is checked (DeepSeek engine for this system, signed manifest, every file's hash) before it is installed; plain steps in the missing-engine message and docs; tests --- docs/DEEPSEEK41.md | 16 ++++++ setup.py | 33 +++++++++--- strata_cli/launch/cmd.py | 4 ++ strata_cli/launch/runner.py | 2 + strata_cli/launch/settings.py | 1 + strata_control/dsv41_engine.py | 81 +++++++++++++++++++++++++++++ tests/terminal/test_dsv41_engine.py | 69 ++++++++++++++++++++++++ 7 files changed, 199 insertions(+), 7 deletions(-) diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 12021fd4..20ca1138 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -89,6 +89,22 @@ package for your computer from the signed update feed (resumable, signature and `engine/`. The Qwen engine's files are never changed. If the feed has no package for your graphics card, setup says so in plain words and stops before anything big is downloaded. +### Getting the engine by hand + +If the automatic download does not work for you (no access to the update feed, or an offline computer), download the engine package yourself from +the release page: the file is named `strata-dsv41----.tar.gz` (Windows and Linux; pick the one for your system and +graphics card). Check it against `SHA256SUMS.txt` on the release page if you like. Then give it to Strata in either of two ways: + +``` +strata launch --model ist-das-2.00bpw --dsv41-package PATH-TO-THE-FILE +python setup.py --family deepseek41 --dsv41-package PATH-TO-THE-FILE +``` + +or put the file in the `engine-dsv41/` folder (setup tells you its exact place when it cannot find the engine) and run the same command again. +Strata checks the package before it uses it: it must be the DeepSeek engine (not the Strata engine) for your system, its manifest must be signed by a key +Strata trusts, and every file must match the hash in the manifest. A damaged or foreign file is refused with a plain line and nothing is installed. +The unpacked folder works as well as the archive. The Strata (Qwen) engine is not touched either way. + ## Compressed experts (trellis), for testing `strata-dsv41` reads the routed experts in the trellis types as well as the source MXFP4: TQK6 and TQK7 (agentionai's files), and the diff --git a/setup.py b/setup.py index eb9cb825..c5f2eb5c 100644 --- a/setup.py +++ b/setup.py @@ -7710,12 +7710,29 @@ def dsv41_engine_dir(eng: Path) -> Path: return (home() if CONTROL else Path(eng).parent) / DSV41_ENGINE_DIR -def get_dsv41_engine(eng: Path, hip: bool) -> Path | None: - """Download, check and unpack the DeepSeek engine package next to the engine `eng`; its strata-dsv41, or None when it cannot be had.""" - acquisition.require("the DeepSeek engine") +def dsv41_manual_steps(eng: Path) -> str: + return (f"If you downloaded the DeepSeek engine package from the release page (the file strata-dsv41-...-{'windows' if WIN else 'linux'}-....{'zip' if WIN else 'tar.gz'}), " + f"run the same command again with --dsv41-package PATH-OF-THE-FILE (strata launch accepts it too), or put the file in {dsv41_engine_dir(eng)} " + "and run it again. Strata checks it before it is used.") + + +def get_dsv41_engine(eng: Path, hip: bool, package: str | None = None) -> Path | None: + """The DeepSeek engine package next to the engine `eng`: one the person gave (--dsv41-package) or put in engine-dsv41/ by hand, else downloaded from + the signed feed. Checked first either way; its strata-dsv41, or None when it cannot be had.""" from strata_control import dsv41_engine - from strata_cli import update_cmd root = dsv41_engine_dir(eng) + if package: + exe = dsv41_engine.install_package(root, package, emit=lambda m: say(" " + m)) + if exe is None: + fail("the DeepSeek engine package you gave could not be used", "see the line above; nothing else was changed") + return exe + for f in dsv41_engine.pending(root): + say(f" Found {f.name} in {root}: checking it ...") + exe = dsv41_engine.install_package(root, f, emit=lambda m: say(" " + m)) + if exe is not None: + return exe + acquisition.require("the DeepSeek engine") + from strata_cli import update_cmd source = update_cmd._feed_source(argparse.Namespace(feed=None), root.parent) say(" Downloading the DeepSeek engine (its own package, separate from the Strata engine) ...") hw = None @@ -7932,7 +7949,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, llama, eng, meta, lib_dirs, gpu, _vision = engine_step(a, gpu, hip, amd, cuda_tk, "none") exe = dsv41_exe(eng) if exe is None and not getattr(a, "build", False): - get_dsv41_engine(eng, hip) + get_dsv41_engine(eng, hip, getattr(a, "dsv41_package", None)) exe = dsv41_exe(eng) if exe is not None and exe.parent != Path(eng): lib_dirs = [*lib_dirs, str(exe.parent)] # its own package carries the libraries it needs @@ -7940,8 +7957,8 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, if os.environ.get("STRATA_VERBOSE") == "1" or "--verbose" in sys.argv: say(" Details for developers: build it with cmake -DSTRATA_BUILD_DSV41=ON and point STRATA_DSV41_EXE at it.") fail("DeepSeek's engine is not available for this computer yet", - "Supported graphics cards: NVIDIA RTX 30 and RTX 50 series, and the Radeon AI PRO R9700. Update Strata later (a newer version may add " - "your card), or pick another model. Nothing has been downloaded.") + "Supported graphics cards: NVIDIA RTX 30 and RTX 50 series, and the Radeon AI PRO R9700. " + dsv41_manual_steps(eng) + + " Or update Strata later (a newer version may add your card), or pick another model. Nothing has been downloaded.") ok(f"engine: {exe}") step(5, f"downloading {fam['title']} {model}") @@ -8370,6 +8387,8 @@ def main() -> int: ap.add_argument("--set-default-data-dir", action="store_true", help="with --data-dir: remember the new folder as the data folder without moving anything") ap.add_argument("--models-dir", help="where the GGUF files go (default: /models)") + ap.add_argument("--dsv41-package", metavar="FILE", help="DeepSeek: the engine package you downloaded from the release page (a .tar.gz or .zip, " + "or its unpacked folder); it is checked and installed instead of being fetched") ap.add_argument("--gguf-dir", help="use GGUF files you already have (a folder with every shard: " "-00001-of-0000N.gguf ... -0000N-of-0000N.gguf)") ap.add_argument("--yes", action="store_true", help="accept the recommended answers") diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 09ffde9b..6a5042e6 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -84,6 +84,8 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] g.add_argument("--preset", metavar="NAME", help="start a saved preset (other flags change it for this start)") g.add_argument("--model", metavar="NAME", help="the model size, e.g. iq3_xxs, q2_0, ud-q4_k_xl (any case)") g.add_argument("--family", metavar="NAME", help="the model family when a size is offered by several (qwen, swift, coder, ...)") + g.add_argument("--dsv41-package", metavar="FILE", help="DeepSeek: the engine package you downloaded from the release page (.tar.gz or .zip); " + "it is checked and installed instead of being fetched") g.add_argument("--model-path", metavar="PATH", help="use model files you already have: a folder of shards or one .gguf file") g.add_argument("--data-dir", metavar="DIR", help="where downloaded model files are stored (default: Strata's data folder)") g.add_argument("--move-data", action="store_true", @@ -199,6 +201,8 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet s = store.load(a.preset) if a.preset else S.LaunchSettings() if a.preset: s.name = s.name or a.preset + if getattr(a, "dsv41_package", None): + s.dsv41_package = str(Path(a.dsv41_package).expanduser()) if a.model_path: s.model_path = str(Path(a.model_path).expanduser()) if not a.model: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 22156b15..710dfbd0 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -739,6 +739,8 @@ class Runner: if s.model_path: p = Path(s.model_path) args += ["--gguf-dir", str(p if p.is_dir() else p.parent)] + if s.dsv41_package and s.family == "deepseek41": + args += ["--dsv41-package", s.dsv41_package] if s.gpu_roles: args += ["--gpu-roles", ",".join(f"{k}={v}" for k, v in sorted(s.gpu_roles.items(), key=lambda kv: int(kv[0])))] elif s.gpus: diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index a819a307..dd175f28 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -82,6 +82,7 @@ class LaunchSettings: family: str | None = None # catalog family id (qwen, swift, coder, unsloth, gyro, nvfp4...) model: str | None = None # catalog size (IQ3_XXS ...) model_path: str | None = None # "Use model files I already have": a .gguf file or a folder + dsv41_package: str | None = None # DeepSeek: the engine package the person downloaded by hand (checked, then installed) data_dir: str | None = None # where model files are stored (None: the Strata default) gpus: list[int] | None = None # None = the engine's choice (all usable cards) gpu_roles: dict[str, str] | None = None # {"1": "main", "0": "helper", "2": "off"}: a role for every card; None = the recommendation diff --git a/strata_control/dsv41_engine.py b/strata_control/dsv41_engine.py index ecd24713..5085c8aa 100644 --- a/strata_control/dsv41_engine.py +++ b/strata_control/dsv41_engine.py @@ -29,6 +29,87 @@ def find(dest: Path) -> Path | None: return folders[-1] / exe_name() if folders else None +ARCHIVE_SUFFIXES = (".tar.gz", ".tar.xz", ".zip") +MAX_UNPACKED = 8 << 30 # a DeepSeek engine package is under a GB; this only stops an archive that unpacks into something huge + + +def pending(dest: Path) -> list[Path]: + """Packages the person put in `dest` (engine-dsv41/) by hand: strata-dsv41-*.tar.gz / .zip, newest first.""" + try: + files = [f for f in Path(dest).iterdir() if f.is_file() and f.name.startswith("strata-dsv41") and f.name.endswith(ARCHIVE_SUFFIXES)] + except OSError: + return [] + return sorted(files, key=lambda f: f.stat().st_mtime, reverse=True) + + +def install_package(dest: Path, package: str | os.PathLike, *, emit: Callable[[str], None] = print) -> Path | None: + """Install a DeepSeek engine package the person downloaded from the release page (a .tar.gz / .zip, or the unpacked folder) into `dest`. + Checked before anything is installed: it is a DeepSeek engine package for this system, its manifest is signed by a key Strata trusts, and every + file matches the hash in the manifest. Returns the new strata-dsv41, or None with a plain line through `emit`.""" + from strata_control import components, engine_component as ec, signing, updater + from strata_control.targets import host_platform + + src, dest = Path(package).expanduser(), Path(dest) + if not src.exists(): + emit(f"{src} is not there. Download the DeepSeek engine package for your system from the release page and give its path again.") + return None + work = dest.parent / (DIR + ".manual") + shutil.rmtree(work, ignore_errors=True) + work.mkdir(parents=True) + try: + if src.is_dir(): + root = work / "pkg" + shutil.copytree(src, root) + else: + fmt = "zip" if src.name.endswith(".zip") else "tar.xz" if src.name.endswith(".tar.xz") else "tar.gz" + if not src.name.endswith(ARCHIVE_SUFFIXES): + emit(f"{src.name} is not a package file (.tar.gz or .zip). Download the DeepSeek engine package for your system from the release page.") + return None + root = work / "pkg" + updater.extract(src, root, fmt, MAX_UNPACKED) + if not (root / ec.MANIFEST).is_file(): + inner = next((d for d in root.iterdir() if d.is_dir() and (d / ec.MANIFEST).is_file()), None) if root.is_dir() else None + if inner is None: + emit(f"{src.name} is not an engine package (it has no {ec.MANIFEST}).") + return None + root = inner + component = ec.read_manifest(root) + if component.entrypoint != exe_name(): + emit(f"{src.name} is not the DeepSeek engine (its program is {component.entrypoint}, not {exe_name()}). " + "The Strata engine package is a different download.") + return None + if component.platform != host_platform(): + emit(f"{src.name} is for {component.platform}, and this computer is {host_platform()}. Download the one for your system.") + return None + outer = ec._verifier + signing.install_component_verifier(signing.load_trusted_keys()) + try: + ec.verify_signature(component, {**os.environ, ec.ENV_REQUIRE_SIGNED: "1"}) + ec.verify(component, full=True) + except ec.ComponentProblem as exc: + emit(f"{src.name} did not pass its check ({exc}). It may be damaged or not from the Strata release: download it again from the release page.") + return None + finally: + ec.register_signature_verifier(outer) + name = f"{component.version}-{component.platform}-{component.backend}" + (f"-{component.variant}" if component.variant else "") + dest.mkdir(parents=True, exist_ok=True) + target = dest / name + shutil.rmtree(target, ignore_errors=True) + shutil.move(str(root), str(target)) + if os.name != "nt": + (target / exe_name()).chmod(0o755) + for old in dest.iterdir(): + if old.is_dir() and old.name != target.name: + shutil.rmtree(old, ignore_errors=True) + emit(f"DeepSeek engine {component.version} ({component.backend}) checked (signed, every file matches) and installed: {target}") + return target / exe_name() + except (updater.UpdateError, ec.ComponentProblem, OSError) as exc: + emit(f"{src.name} could not be installed: {exc}") + return None + finally: + shutil.rmtree(work, ignore_errors=True) + + def install(dest: Path, source: str, *, hardware: dict | None = None, emit: Callable[[str], None] = print, cancel=None) -> Path | None: """Fetch the DeepSeek engine package for this PC from the signed feed at `source` (a URL or a folder) into `dest`. Returns the new strata-dsv41, or None with a plain line through `emit` when there is none (not in the feed, nothing for this PC).""" diff --git a/tests/terminal/test_dsv41_engine.py b/tests/terminal/test_dsv41_engine.py index 63480326..26c04756 100644 --- a/tests/terminal/test_dsv41_engine.py +++ b/tests/terminal/test_dsv41_engine.py @@ -130,5 +130,74 @@ class Dsv41Engine(unittest.TestCase): self.assertFalse((self.root / "data" / "engine-dsv41").exists() and any((self.root / "data" / "engine-dsv41").iterdir())) +class ManualPackage(Dsv41Engine): + """A package the person downloaded by hand: a .tar.gz / .zip or the unpacked folder, checked before it is installed.""" + + def archive(self, version="0.1.49"): + folder = build(self.root / f"man-{version}", version, self.key) + out = self.root / "dl" + out.mkdir(exist_ok=True) + entry = feed_tool.pack_engine(folder, out, prefix="strata-dsv41") + return folder, out / Path(entry["url"]).name + + def test_a_downloaded_archive_is_checked_and_installed_beside_the_engine(self): + _folder, archive = self.archive() + lines = [] + exe = dsv41_engine.install_package(self.root / "data" / "engine-dsv41", archive, emit=lines.append) + self.assertIsNotNone(exe, lines) + self.assertTrue(exe.is_file()) + self.assertIn("signed, every file matches", " ".join(lines)) + self.assertEqual(self.tree(self.eng), self.before) + + def test_an_unpacked_folder_works_too(self): + folder, _ = self.archive() + exe = dsv41_engine.install_package(self.root / "data" / "engine-dsv41", folder) + self.assertIsNotNone(exe) + + def test_a_damaged_file_is_refused_and_nothing_is_installed(self): + folder, _ = self.archive() + (folder / EXE).write_bytes(b"tampered") + lines = [] + self.assertIsNone(dsv41_engine.install_package(self.root / "data" / "engine-dsv41", folder, emit=lines.append)) + self.assertIn("did not pass its check", " ".join(lines)) + dest = self.root / "data" / "engine-dsv41" + self.assertFalse(dest.exists() and any(p.is_dir() for p in dest.iterdir())) + + def test_a_package_signed_by_an_unknown_key_is_refused(self): + other = fx.make_key() + folder = build(self.root / "foreign", "0.1.49", other) + lines = [] + self.assertIsNone(dsv41_engine.install_package(self.root / "data" / "engine-dsv41", folder, emit=lines.append)) + self.assertIn("did not pass its check", " ".join(lines)) + + def test_the_strata_engine_package_is_not_taken_for_deepseeks(self): + src = self.root / "qsrc" + src.mkdir() + (src / "strata").write_bytes(b"qwen engine") + folder = package_engine.build(src, "cuda", "0.1.49", components.host_platform(), self.root / "qout", entry="strata", archs=("sm_86",), + min_driver={"nvidia": "580.65"}, build_id="q", variant="cuda13") + feed_tool.sign_package(folder, self.key) + lines = [] + self.assertIsNone(dsv41_engine.install_package(self.root / "data" / "engine-dsv41", folder, emit=lines.append)) + self.assertIn("not the DeepSeek engine", " ".join(lines)) + + def test_a_missing_or_wrong_file_is_said_plainly(self): + lines = [] + self.assertIsNone(dsv41_engine.install_package(self.root / "x", self.root / "nope.tar.gz", emit=lines.append)) + self.assertIn("is not there", " ".join(lines)) + junk = self.root / "notes.txt" + junk.write_text("x") + self.assertIsNone(dsv41_engine.install_package(self.root / "x", junk, emit=lines.append)) + self.assertIn("not a package file", " ".join(lines)) + + def test_files_put_in_the_folder_are_found(self): + _f, archive = self.archive() + dest = self.root / "data" / "engine-dsv41" + dest.mkdir(parents=True) + shutil.copy(archive, dest / archive.name) + (dest / "readme.txt").write_text("x") + self.assertEqual([p.name for p in dsv41_engine.pending(dest)], [archive.name]) + + if __name__ == "__main__": unittest.main() From d914211e64467608da6cafcdcf82509d90e8c87e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:41:47 +0200 Subject: [PATCH 09/34] release notes 0.2.4: the manual DeepSeek engine command --- docs/release-notes-0.2.4.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index fadabfac..8ee4ab63 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -62,7 +62,7 @@ These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so e DeepSeek runs on its own engine package, `strata-dsv41`, which sits beside your Qwen engine and never replaces it. There are two ways to get it. - **Automatic:** choose DeepSeek in `strata launch` or `strata setup`. Strata downloads the package that fits your PC, checks its signature and installs it. -- **By hand:** download the package for your system from this page, check it against `SHA256SUMS.txt`, and install it with the command in the Terminal guide. TODO(setup worker): exact command. +- **By hand:** download the package for your system from this page, check it against `SHA256SUMS.txt`, and run `strata launch --model ist-das-2.00bpw --dsv41-package PATH-TO-FILE` (or `python setup.py --family deepseek41 --dsv41-package PATH-TO-FILE`). Strata checks that it is the DeepSeek engine, that it fits your system and that its signature and file hashes are good, and refuses anything else. You can also put the file in the `engine-dsv41` folder next to `engine`. | System | File | |---|---| From 5be4964c2b112896928a91013daf6dbc6c904923 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:56:08 +0200 Subject: [PATCH 10/34] launch for DeepSeek: the tune text says what it really does and its result lists what was timed (or that nothing could be compared); the plan names an installed DeepSeek engine ('installed, 0.1.49') instead of saying setup will download it; preset test; tests --- strata_cli/launch/runner.py | 58 +++++++++++++++++++++----- tests/terminal/test_dsv41_tui_items.py | 30 +++++++++++++ tests/terminal/test_dsv41_tune.py | 12 ++++++ tools/dsv41/tune.py | 5 +++ 4 files changed, 95 insertions(+), 10 deletions(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 710dfbd0..b408ff73 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1265,7 +1265,8 @@ class Runner: mode = "thorough" if s.tune == "thorough" else "quick" argv = [sys.executable, str(Path(__file__).resolve().parents[2] / "tools" / "dsv41" / "tune.py"), "--config", str(cfg), "--mode", mode, "--output", "json"] - self.emit("tune", "Tuning DeepSeek for the best speed: a few short test runs (1-3 minutes each). Close other heavy programs.", 0) + self.emit("tune", "Tuning DeepSeek: it times a short question with your standard settings, then with the DSpark drafter on (and, if that helps, a shorter " + "draft block) and the CPU threads set to your physical cores; each run loads the model once. It keeps only a clear gain. Close other heavy programs.", 0) try: p = self._spawn(argv) except Exception as e: # noqa: BLE001 - a tune never stops a launch @@ -1830,21 +1831,54 @@ class Runner: except Exception: # noqa: BLE001 return "" - def dsv41_engine(self) -> bool | None: - """Whether the installed engine carries strata-dsv41 (True / False); None when no engine is installed yet or it cannot be told.""" + def dsv41_engine_found(self) -> tuple[Path | None, bool | None]: + """(strata-dsv41 already installed, or None; whether the engine can be told at all). Looks where setup puts DeepSeek's own engine package + (engine-dsv41/ beside the engine, in Strata's own folder, and in the data folder), and at STRATA_DSV41_EXE (a build of your own).""" + from strata_control import dsv41_engine own = (os.environ.get("STRATA_DSV41_EXE") or "").strip() if own: - return Path(own).is_file() + return (Path(own) if Path(own).is_file() else None), True + folders: list[Path] = [] try: from strata_control import engine_component as ec rep = ec.status() exe = (rep.get("engine") or {}).get("exe") if rep.get("usable") else None - if not exe: - return None - folder = Path(str(exe)).parent - return any((d / n).is_file() for d in (folder, folder.parent / "engine-dsv41") for n in ("strata-dsv41", "strata-dsv41.exe")) + if exe: + folder = Path(str(exe)).parent + folders += [folder.parent / dsv41_engine.DIR] + try: + folders.append(self.catalog.strata.setup_module().dsv41_engine_dir(folder)) + except Exception: # noqa: BLE001 + pass + known = True + else: + known = None except Exception: # noqa: BLE001 - return None + known = None + try: # where the setup this Terminal runs puts it (its own engine folder, or Strata's folder) + mod = self.catalog.strata.setup_module() + folders += [Path(self.catalog.root) / dsv41_engine.DIR, # setup runs here in the app's installer mode: its home() is this folder + mod.dsv41_engine_dir(Path(mod.ROOT) / "engine"), Path(mod.home()) / dsv41_engine.DIR] + except Exception: # noqa: BLE001 + pass + try: + folders.append((Path(self.s.data_dir) if self.s.data_dir else self.catalog.data_dir()) / dsv41_engine.DIR) + except Exception: # noqa: BLE001 + pass + for f in folders: + found = dsv41_engine.find(f) + if found is not None: + return found, True + for f in folders[:1]: # the engine's own folder: an all-in-one package carries it + for n in ("strata-dsv41", "strata-dsv41.exe"): + if (f.parent / n).is_file(): + return f.parent / n, True + return None, known + + def dsv41_engine(self) -> bool | None: + """Whether the installed engine carries strata-dsv41 (True / False); None when no engine is installed yet or it cannot be told.""" + found, known = self.dsv41_engine_found() + return True if found is not None else (False if known else None) def placement(self) -> dict: """Where DeepSeek-V4.1-Flash would go on this computer's cards (strata_control/dsv41_fit.py): the cards this launch names, else every @@ -1858,7 +1892,11 @@ class Runner: free = None p = self.catalog.strata.dsv41_plan(hw, free, s.gpus, model=s.model) warnings = list(p["warnings"]) - engine = self.dsv41_engine() + found, known = self.dsv41_engine_found() + engine = True if found is not None else (False if known else None) + if found is not None: + ver = next((part for part in (found.parent.name.split("-")[0], ) if part[:1].isdigit()), "") + p["lines"].append("DeepSeek engine: installed" + (f", {ver}" if ver else "") + ".") if engine is False: warnings.append("DeepSeek runs on its own engine package (about 70 MB, separate from the Strata engine): setup downloads it first. " "If it cannot be fetched, setup stops with a message before the model is downloaded.") diff --git a/tests/terminal/test_dsv41_tui_items.py b/tests/terminal/test_dsv41_tui_items.py index 69f42dbb..6c99c0db 100644 --- a/tests/terminal/test_dsv41_tui_items.py +++ b/tests/terminal/test_dsv41_tui_items.py @@ -48,6 +48,36 @@ class Advanced(unittest.TestCase): self.assertIn("not in this engine's list", next(r for r in rows if r.name == "--dsparkk").description) +class Presets(unittest.TestCase): + def test_a_saved_preset_is_read_from_where_it_is_written_whatever_the_data_dir(self): + import tempfile + from strata_cli.launch import settings as S, store + with tempfile.TemporaryDirectory() as d, mock.patch.dict("os.environ", {"STRATA_LAUNCH_PRESET_DIR": d}): + s = S.LaunchSettings(family="deepseek41", model="IST-DAS-2.00bpw", data_dir=str(Path(d) / "elsewhere"), name="DS 8K") + store.save(s, "DS 8K") + self.assertEqual([p.name for p in store.list_presets()], ["DS 8K"]) + self.assertEqual(store.preset_dir(), Path(d)) # (the folder does not depend on the launch's --data-dir) + + +class PlanEngine(unittest.TestCase): + def test_an_installed_deepseek_engine_is_named_in_the_plan_not_downloaded(self): + import tempfile + from strata_cli.launch import runner as R + with tempfile.TemporaryDirectory() as d: + pkg = Path(d) / "engine-dsv41" / "0.1.49-windows-x86_64-cuda-cuda13" + pkg.mkdir(parents=True) + exe = pkg / ("strata-dsv41.exe" if sys.platform == "win32" else "strata-dsv41") + exe.write_bytes(b"x") + fake = mock.MagicMock() + fake.s.data_dir = d + fake.catalog.data_dir.return_value = Path(d) + fake.catalog.strata.setup_module.side_effect = RuntimeError("no setup") + with mock.patch.dict("os.environ", {"STRATA_DSV41_EXE": ""}), mock.patch("strata_control.engine_component.status", return_value={"usable": False}): + found, known = R.Runner.dsv41_engine_found(fake) + self.assertEqual(found, exe) + self.assertTrue(known) + + class Disk(unittest.TestCase): def setUp(self): import strata_mcp as M diff --git a/tests/terminal/test_dsv41_tune.py b/tests/terminal/test_dsv41_tune.py index aa81fb39..30b28a0d 100644 --- a/tests/terminal/test_dsv41_tune.py +++ b/tests/terminal/test_dsv41_tune.py @@ -51,6 +51,18 @@ class Tune(unittest.TestCase): self.assertEqual(len(calls), 4) # baseline, drafter on, block 3, threads self.assertIn("tuned", json.loads(self.cfg.read_text())) + def test_the_result_says_what_was_tried(self): + res, _ = self.run_tune(lambda a: 4.5) + text = " ".join(res["lines"]) + self.assertIn("Tried (tokens a second): standard 4.5", text) + self.assertIn("the drafter on (DSpark) 4.5", text) + + def test_a_single_timing_says_there_was_nothing_to_compare(self): + def only_baseline(a): + return 4.5 if "--dspark" in a and a[a.index("--dspark") + 1] == "auto" and "--cpu-threads" not in a else None + res, _ = self.run_tune(only_baseline) + self.assertIn("nothing to compare", " ".join(res["lines"])) + def test_noise_changes_nothing(self): before = self.cfg.read_text() res, _ = self.run_tune(lambda a: 4.5 + 0.1 * (len(a) % 2)) diff --git a/tools/dsv41/tune.py b/tools/dsv41/tune.py index 1b286ba8..fd3aa8b6 100644 --- a/tools/dsv41/tune.py +++ b/tools/dsv41/tune.py @@ -142,6 +142,7 @@ def tune(config: Path, mode: str = "quick", n: int = 48, timeout: int = 1500, me if v > best * GAIN: best, best_args = v, cand res["changed"].append(label) + tried = ", ".join(f"{k} {v:.1f}" for k, v in res["speeds"].items()) if res["changed"]: new = [a for a in best_args] cfg["args"] = new @@ -151,6 +152,10 @@ def tune(config: Path, mode: str = "quick", n: int = 48, timeout: int = 1500, me f"({base:.1f} -> {best:.1f} tokens a second). The RAM store sizes itself when the model starts.") else: res["lines"].append(f"Your computer already runs DeepSeek best with the standard settings ({base:.1f} tokens a second); nothing changed.") + if len(res["speeds"]) > 1: + res["lines"].append(f"Tried (tokens a second): {tried}.") + else: + res["lines"].append("Only the standard settings could be timed here, so there was nothing to compare.") return res From cdc3a265773f5b5de301afc5ac6fe7099044515e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:59:52 +0200 Subject: [PATCH 11/34] dsv41: keep a conversation another request displaces and take it back at its checkpoints (STRATA_DS4_SLOT_KEEP), shared-start checkpoint (pin=N) A prompt that does not continue the conversation in the model first sets that one aside (position, window rings, compressor partial groups, each KV source's compressed KV and index keys, its checkpoints), then takes back the kept conversation it does continue, in RAM or from the slot folder, also across restarts. The latest checkpoint the prompt still agrees with is used (end of the last prompt, before it, the anchor of the first prompt of a run, and the shared start the server marks with pin=N). The .meta format and the prefix matching are in ds4_slotmeta.hpp with a GPU-free test (ds4_slot_test). STRATA_DS4_REUSE=0 reads every request from token 0 (reference for tests). Off unless STRATA_DS4_SLOT_KEEP=1. --- CMakeLists.txt | 4 + src/dsv41/ds4_main.cpp | 405 ++++++++++++++++++++++++++++++++++++- src/dsv41/ds4_model.cu | 404 +++++++++++++++++++++++++++++++++++- src/dsv41/ds4_model.hpp | 21 +- src/dsv41/ds4_slotmeta.hpp | 98 +++++++++ tests/dsv41/slot_test.cpp | 153 ++++++++++++++ 6 files changed, 1070 insertions(+), 15 deletions(-) create mode 100644 src/dsv41/ds4_slotmeta.hpp create mode 100644 tests/dsv41/slot_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c46b305c..bbe296b2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -884,6 +884,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) if(STRATA_ENABLE_HIP) target_compile_options(ds4_iq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") endif() + # the kept conversations' .meta file and prefix matching (ds4_slotmeta.hpp): no GPU, no model + add_executable(ds4_slot_test tests/dsv41/slot_test.cpp) + target_include_directories(ds4_slot_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_slot_test PRIVATE cxx_std_17) endif() if(STRATA_ENABLE_HIP) foreach(_t strata_dsv41_kernels strata-dsv41) diff --git a/src/dsv41/ds4_main.cpp b/src/dsv41/ds4_main.cpp index e614e6cb..0ea0c151 100644 --- a/src/dsv41/ds4_main.cpp +++ b/src/dsv41/ds4_main.cpp @@ -11,16 +11,27 @@ // 0 0 0 0`; `STOP` ends a request early, `QUIT` the engine. A prompt that // continues the state (the conversation so far) reuses it; one that only shares the last prompt's start goes back to // that prompt's end; anything else starts over. `GENI [keys] ` carries the prompt's pictures -// (the file: see read_pics); the state is shared only where the same picture sits at the same place. +// (the file: see read_pics); the state is shared only where the same picture sits at the same place. With +// STRATA_DS4_SLOT_KEEP=1 the conversations are kept when another one takes the model (a slot each: the state, the +// compressed KV included), and across runs in STRATA_DS4_SLOT_DIR - so a request that does not continue the state but +// does continue a kept conversation reads only its new tokens. +// `pin=N` on a GEN marks the first N prompt tokens as a start other requests share (a system prompt and its tools): the +// read stops there for a checkpoint, so a request behind the same start - another agent - goes back to it instead of +// reading it again (also without slots). STRATA_DS4_REUSE=0 turns every reuse off (each request reads its whole prompt). #include "ds4_model.hpp" #include "ds4_packinfo.hpp" +#include "ds4_slotmeta.hpp" #include #include #include #include #include +#include #include +#include +#include +#include #include #include #include @@ -182,6 +193,9 @@ struct Req { unsigned long long seed = 0; int spec = -1; // spec=0|1: this request drafts or not (-1: as the engine was started) float conf = -1.0f; // dspark_conf=F: the drafts' confidence floor for this request (-1: the engine's) + long long pin = 0; // pin=N: the first N prompt tokens are a start other requests share (a system prompt and its + // tools): the state at N is kept as a checkpoint, so another agent behind the same start + // goes back to it instead of reading it again std::string file; // GENI: the pictures std::vector ids; }; @@ -277,11 +291,12 @@ bool parse_gen(const std::string& line, Req& r, bool geni) { else if (k == "seed") r.seed = std::strtoull(v.c_str(), nullptr, 10); else if (k == "spec") r.spec = std::atoi(v.c_str()) != 0; else if (k == "dspark_conf") r.conf = std::strtof(v.c_str(), nullptr); + else if (k == "pin") r.pin = std::atoll(v.c_str()); } return !r.ids.empty() && (!geni || !r.file.empty()); } -int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float conf_min) { +int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float conf_min, const std::string& pack) { std::vector eos = parse_ids(eos_list); for (const std::string& l : m.info_lines()) std::printf("%s\n", l.c_str()); std::printf("READY %lld stop\n", (long long) m.max_context()); @@ -294,6 +309,321 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c std::vector held; // the pictures the state holds (start, hash, span) SpanCache spans; const int img_tok = m.image_token(); + // CONVERSATION SLOTS: a request that does not continue the conversation in the model first sets that one aside + // (Model::slot_save: its window rings, the compressors' partial groups and every source's compressed KV and index + // keys), then takes back the kept conversation this prompt does continue (slot_load) - chats, and an agent's side + // requests, that interleave no longer re-read each other's prompts (70k and 185k tokens alternating: 75-200 s a + // switch at ~930 tok/s). STRATA_DS4_SLOT_KEEP=1 turns them on and keeps them across runs, in STRATA_DS4_SLOT_DIR + // (default /slots): a slot is a .bin (the state) and a .meta (this model's identity, the conversation's + // tokens and its size), both written under a temporary name first; a slot whose .meta is missing, foreign or does + // not match its file, or unused for STRATA_DS4_SLOT_DAYS (7) days, is removed at start. STRATA_DS4_SLOT_CAP (4) is + // the conversations kept in RAM; past it the least recently used is written to the folder and read back from there + // (RAM first, the folder past the cap), and the engine's end writes the ones in RAM to the folder, so the next run + // reads on from them. STRATA_DS4_SLOT_GB (16) caps the folder's .bin files: at start, and after every write, the + // folder's least recently used conversation is removed while they are over it (never the one just written, so a + // conversation bigger than the cap stays). STRATA_DS4_SLOT_MIN (1024) is the shortest conversation set aside (a + // shorter one is read again in about the time its slot would take). Text only: a conversation that holds pictures + // is not set aside, and a prompt with pictures takes none back. + const auto env_num = [](const char* k, double d) { const char* v = std::getenv(k); return v ? std::atof(v) : d; }; + const bool slot_keep = + std::getenv("STRATA_DS4_SLOT_KEEP") != nullptr && std::atoi(std::getenv("STRATA_DS4_SLOT_KEEP")) != 0; + const bool reuse = std::getenv("STRATA_DS4_REUSE") == nullptr || std::atoi(std::getenv("STRATA_DS4_REUSE")) != 0; + int slot_max = slot_keep ? std::max(0, (int) env_num("STRATA_DS4_SLOT_CAP", 4)) : 0; + const size_t slot_min = (size_t) std::max(1.0, env_num("STRATA_DS4_SLOT_MIN", 1024)); + const double slot_days = env_num("STRATA_DS4_SLOT_DAYS", 7); + const uint64_t slot_budget = (uint64_t) (env_num("STRATA_DS4_SLOT_GB", 16) * 1073741824.0); + namespace fs = std::filesystem; + std::filesystem::path slot_dir; + struct Slot { + std::vector tokens; + std::string path; // empty: the state is in data (RAM) + uint64_t bytes = 0, used = 0; + std::shared_ptr> data; // the RAM slot's bytes (null: a file slot) + std::vector cks; // the positions short of its end it can be taken back at + }; + std::vector slots; + uint64_t slot_clock = 0, slot_seq = 0; + const std::string slot_identity = m.slot_identity(); + const auto note = [&](const std::string& msg) { + std::fprintf(stderr, "ds4 slots: %s\n", msg.c_str()); + std::printf("NOTE sessions: %s\n", msg.c_str()); + std::fflush(stdout); + }; + const auto gb = [](uint64_t b) { + char s[32]; + std::snprintf(s, sizeof s, "%.2f GB", (double) b / 1e9); + return std::string(s); + }; + const auto meta_of = [](const std::string& bin) { return bin.substr(0, bin.size() - 4) + ".meta"; }; + const auto meta_write = [&](const std::string& path, const std::vector& toks, uint64_t bytes, + const std::vector& cks) -> bool { + return strata::ds4::slotmeta::write(path, slot_identity, toks, bytes, cks); + }; + // a .meta of this model -> its tokens and the slot's size (false: foreign, damaged or not this model's) + const auto meta_read = [&](const std::string& path, std::vector& toks, uint64_t& bytes, + std::vector& cks) -> bool { + return strata::ds4::slotmeta::read(path, slot_identity, m.max_context(), toks, bytes, cks); + }; + const auto slot_age_days = [](const std::string& p) { + std::error_code ec; + const auto t = fs::last_write_time(p, ec); + if (ec) return 1e9; + return std::chrono::duration(fs::file_time_type::clock::now() - t).count() / 86400.0; + }; + const auto slot_drop = [&](size_t i) { + if (slots[i].data) // a RAM slot: its buffer simply dies + slots[i].data.reset(); + else { + std::error_code ec; + std::filesystem::remove(slots[i].path, ec); + std::filesystem::remove(meta_of(slots[i].path), ec); + } + slots.erase(slots.begin() + (long) i); + }; + const auto slot_count = [&](int& ram, int& disk) { + ram = disk = 0; + for (const Slot& s : slots) (s.data ? ram : disk) += 1; + }; + // the folder's conversations (their .bin; a .meta beside each is a few KB: identity and tokens) + const auto slot_folder_bytes = [&]() { + uint64_t total = 0; + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(slot_dir, ec)) { + const std::string fn = de.path().filename().string(); + if (fn.rfind("slot-", 0) == 0 && fn.size() > 9 && fn.compare(fn.size() - 4, 4, ".bin") == 0) { + const uint64_t bytes = (uint64_t) std::filesystem::file_size(de.path(), ec); + if (!ec) total += bytes; + } + } + return total; + }; + // the folder over STRATA_DS4_SLOT_GB: its least recently used conversation goes first, and never `keep` (the one just + // written), so a conversation bigger than the cap stays + const auto slot_trim = [&](const std::string& keep) { + const uint64_t before = slot_folder_bytes(); + size_t dropped = 0; + while (slot_folder_bytes() > slot_budget) { + size_t lru = SIZE_MAX; + for (size_t i = 0; i < slots.size(); ++i) + if (!slots[i].data && slots[i].path != keep && (lru == SIZE_MAX || slots[i].used < slots[lru].used)) + lru = i; + if (lru == SIZE_MAX) break; + slot_drop(lru); + ++dropped; + } + if (dropped > 0) { + char msg[256]; + std::snprintf(msg, sizeof msg, "the folder held %s (over STRATA_DS4_SLOT_GB, %s): %zu least recently used " + "conversation(s) removed, %s left", gb(before).c_str(), gb(slot_budget).c_str(), dropped, + gb(slot_folder_bytes()).c_str()); + note(msg); + } + }; + // a RAM slot into the folder (its bytes, then its .meta); false: not written (its bytes go, then) + const auto slot_write_file = [&](Slot& s) -> bool { + std::error_code ec; + const auto space = std::filesystem::space(slot_dir, ec); + if (!ec && space.available < ((uint64_t) 8 << 30)) { // (8 GB free, the GLM engine's guard) + std::fprintf(stderr, "ds4 slots: under 8 GB free in %s - the conversation is not written\n", + slot_dir.string().c_str()); + return false; + } + const auto stamp = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + const std::string path = + (slot_dir / ("slot-" + std::to_string(stamp) + "-" + std::to_string(++slot_seq) + ".bin")).string(); + { + std::ofstream f(path + ".tmp", std::ios::binary | std::ios::trunc); + f.write((const char*) s.data->data(), (std::streamsize) s.data->size()); + f.flush(); + if (!f) { + std::filesystem::remove(path + ".tmp", ec); + std::fprintf(stderr, "ds4 slots: writing %s.tmp failed (disk full?)\n", path.c_str()); + return false; + } + } + fs::rename(path + ".tmp", path, ec); + if (ec || !meta_write(meta_of(path), s.tokens, s.data->size(), s.cks)) { + std::filesystem::remove(path + ".tmp", ec); + std::filesystem::remove(path, ec); + std::fprintf(stderr, "ds4 slots: writing %s failed\n", path.c_str()); + return false; + } + s.path = path; + s.bytes = s.data->size(); + s.data.reset(); + slot_trim(path); // (the folder over its cap: the least recently used conversation goes, not this one) + return true; + }; + // the conversation in the model into a slot (the state is lost otherwise: another one takes the model) + const auto slot_put = [&](const char* why) { + if (slot_max <= 0) return; + const std::vector& t = m.tokens(); + if (t.size() < slot_min) return; // (a fresh engine's 0-token state is no conversation: nothing to set aside) + const auto t0 = std::chrono::steady_clock::now(); + auto buf = std::make_shared>(); + std::string e; + const uint64_t bytes = m.slot_save(*buf, e); // (a state unchanged since it was taken refuses here: nothing + if (bytes == 0) { // changes, its slot stays) + if (e != "it is already set aside") + std::fprintf(stderr, "ds4 slots: setting the conversation aside failed (%s) - it is read from token 0 " + "when it comes back\n", e.c_str()); + return; + } + for (size_t i = slots.size(); i-- > 0;) // an earlier state of this conversation is superseded + if (slots[i].tokens.size() <= t.size() && std::equal(slots[i].tokens.begin(), slots[i].tokens.end(), t.begin())) + slot_drop(i); + slots.push_back({t, "", bytes, ++slot_clock, nullptr, m.check_positions()}); + slots.back().data = buf; + while (true) { // past the cap: the least recently used conversation in RAM to the folder, or gone + int ram = 0, disk = 0; + slot_count(ram, disk); + if (ram <= slot_max) break; + size_t lru = SIZE_MAX; + for (size_t i = 0; i < slots.size(); ++i) + if (slots[i].data && (lru == SIZE_MAX || slots[i].used < slots[lru].used)) lru = i; + if (lru == SIZE_MAX) break; + if (!slot_write_file(slots[lru])) slot_drop(lru); + } + int ram = 0, disk = 0; + slot_count(ram, disk); + char msg[256]; + std::snprintf(msg, sizeof msg, "saved a %zu-token conversation%s (%s in RAM in %.1f s); %d in RAM, %d in %s", + t.size(), why, gb(bytes).c_str(), + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), ram, disk, + slot_dir.string().c_str()); + note(msg); + }; + // the kept conversation this prompt shares the most of - past `floor` tokens, what the model itself can go back + // to - back in the model: the tokens it covers (0: none). A conversation the prompt continues whole comes back + // whole (`whole`); one it leaves part way - a retried prompt, a history the client renders again without the + // earlier reasoning - comes back at its latest checkpoint the prompt still agrees with (the end of a prompt, the + // position before it, the anchor where its run of continued prompts began). + const auto slot_take = [&](const std::vector& prompt, size_t floor, bool& whole) -> size_t { + whole = false; + if (slot_max <= 0 || prompt.size() < 2) return 0; + std::vector cands; + for (const Slot& sl : slots) cands.push_back({&sl.tokens, &sl.cks}); + size_t len = 0; + const size_t best = strata::ds4::slotmeta::pick(cands, prompt, floor, &len); + if (best == SIZE_MAX) return 0; + const size_t whole_len = slots[best].tokens.size(); + const auto t0 = std::chrono::steady_clock::now(); + const bool ram = slots[best].data != nullptr; + std::string e; + bool back = false; + if (ram) back = m.slot_load(slots[best].data->data(), slots[best].data->size(), (int64_t) whole_len, e); + else { + std::ifstream f(slots[best].path, std::ios::binary); + std::vector file; + if (f) { + f.seekg(0, std::ios::end); + const std::streamoff n = f.tellg(); + f.seekg(0, std::ios::beg); + if (n > 0) { + file.resize((size_t) n); + if (f.read((char*) file.data(), n)) + back = m.slot_load(file.data(), file.size(), (int64_t) whole_len, e); + else e = "reading " + slots[best].path + " failed"; + } else e = slots[best].path + " is empty"; + } else e = "cannot read " + slots[best].path; + } + if (!back) { + note("taking a conversation back failed (" + (e.empty() ? std::string("it did not load") : e) + + ") - reading its prompt again"); + slot_drop(best); + return 0; + } + if (len < whole_len && !(m.restore((int64_t) len) && (size_t) m.pos() == len)) { + note("going back to token " + std::to_string(len) + " of a kept conversation failed - reading its prompt again"); + m.reset(); + return 0; + } + whole = len == whole_len; + slots[best].used = ++slot_clock; + if (!ram) { // its age counts from its last use (a file slot's only) + std::error_code ec; + fs::last_write_time(meta_of(slots[best].path), fs::file_time_type::clock::now(), ec); + } + char msg[256]; + std::string part; + if (!whole) part = " at token " + std::to_string(len) + " of " + std::to_string(whole_len); + std::snprintf(msg, sizeof msg, "took back a %zu-token conversation%s from %s (%.1f s); %zu new tokens to read", + len, part.c_str(), ram ? "RAM" : "the folder", + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), + prompt.size() - len); + note(msg); + return len; + }; + if (slot_max > 0) { + slot_dir = std::getenv("STRATA_DS4_SLOT_DIR") ? std::filesystem::path(std::getenv("STRATA_DS4_SLOT_DIR")) + : std::filesystem::path(pack) / "slots"; + std::error_code ec; + std::filesystem::create_directories(slot_dir, ec); + if (!std::filesystem::is_directory(slot_dir, ec)) { + std::fprintf(stderr, "ds4 slots: %s is not writable - conversations are not set aside\n", + slot_dir.string().c_str()); + slot_max = 0; + } else { + struct Found { + std::string bin; + std::vector toks; + uint64_t bytes; + std::vector cks; + fs::file_time_type t; + }; + std::vector found; + size_t refused = 0; + for (const auto& de : std::filesystem::directory_iterator(slot_dir, ec)) { // a previous run's slots + const std::string fn = de.path().filename().string(), p = de.path().string(); + if (fn.rfind("slot-", 0) != 0) continue; + const bool is_bin = fn.size() > 9 && fn.compare(fn.size() - 4, 4, ".bin") == 0; + const bool is_meta = fn.size() > 10 && fn.compare(fn.size() - 5, 5, ".meta") == 0; + if (!is_bin && !is_meta) { // a .tmp an interrupted write left + std::filesystem::remove(de.path(), ec); + continue; + } + if (!is_meta) continue; // a .bin is judged by its .meta + const std::string bin = p.substr(0, p.size() - 5) + ".bin"; + Found fd{bin, {}, 0, {}, fs::last_write_time(de.path(), ec)}; + const uint64_t have = fs::exists(bin, ec) ? (uint64_t) fs::file_size(bin, ec) : 0; + if (meta_read(p, fd.toks, fd.bytes, fd.cks) && have == fd.bytes && fd.bytes > 0 && slot_age_days(p) <= slot_days) + found.push_back(std::move(fd)); + else { + ++refused; + std::filesystem::remove(p, ec); + std::filesystem::remove(bin, ec); + } + } + for (const auto& de : std::filesystem::directory_iterator(slot_dir, ec)) { // a .bin without its .meta + const std::string p = de.path().string(), fn = de.path().filename().string(); + if (fn.rfind("slot-", 0) == 0 && fn.size() > 9 && fn.compare(fn.size() - 4, 4, ".bin") == 0 && + !fs::exists(meta_of(p), ec)) + std::filesystem::remove(de.path(), ec); + } + std::sort(found.begin(), found.end(), [](const Found& a, const Found& b) { return a.t < b.t; }); + uint64_t total = 0; + for (auto& fd : found) { + total += fd.bytes; + slots.push_back({std::move(fd.toks), fd.bin, fd.bytes, ++slot_clock, nullptr, std::move(fd.cks)}); + } + std::string msg = "folder " + slot_dir.string() + ": " + std::to_string(slots.size()) + + " conversation(s) kept from earlier runs (" + gb(total) + ")"; + if (refused) msg += ", " + std::to_string(refused) + " not this model's or incomplete - removed"; + note(msg); + slot_trim(""); // (the folder over STRATA_DS4_SLOT_GB: the least recently used conversation goes first) + } + } + if (slot_max > 0) { +#if !defined(_WIN32) + // (the server ends the engine with QUIT and waits for it; a SIGTERM to the whole process group - systemd + // stopping a service, a supervisor killing the server's group - must not end it mid-write, and a server that + // is already gone must not end it with SIGPIPE when it writes its last lines) + std::signal(SIGTERM, SIG_IGN); + std::signal(SIGINT, SIG_IGN); + std::signal(SIGPIPE, SIG_IGN); +#endif + } while (in.next(line)) { if (line == "QUIT") break; const bool geni = line.rfind("GENI ", 0) == 0; @@ -325,6 +655,10 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c continue; } } + if (!reuse) { // (STRATA_DS4_REUSE=0, for A/Bs and tests: every request is a fresh read of its whole prompt) + m.reset(); + held.clear(); + } const auto& st = m.tokens(); const size_t n_state = st.size(); size_t c = 0; @@ -340,12 +674,32 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c for (const Pic& q : held) if ((size_t) q.start < c && !same(pics, q)) c = (size_t) q.start; size_t from = 0; - if (c == n_state && n_state < r.ids.size()) from = n_state; - else if (m.restorable((int64_t) std::min(c, r.ids.size() - 1)) >= 0 && - m.restore((int64_t) std::min(c, r.ids.size() - 1))) - from = (size_t) m.pos(); - else m.reset(); - if (from == 0) held.clear(); + bool took = false, continued = false; // (continued: the conversation goes on - its anchor stays) + // the conversation continues, reused in place - a conversation has to be in the model first: a fresh engine + // (the start of a run, so every restart) holds 0 tokens, and every prompt "continues" that to token 0; taken + // as a continuation, the take below would never run for the folder's conversations, the case they are for + if (n_state > 0 && c == n_state && n_state < r.ids.size()) { + from = n_state; + continued = true; + } + else { + // CONVERSATION SLOTS: this prompt does not continue the conversation in the model - that one is set aside + // first (another one takes the model, and its state is lost otherwise), then the kept conversation this + // prompt does continue is taken back - if it goes further back than the checkpoints the state itself holds + if (held.empty()) slot_put(""); + const int64_t limit = (int64_t) std::min(c, r.ids.size() - 1); + const int64_t rs = m.restorable(limit); + bool whole = false; + const size_t back = pics.empty() ? slot_take(r.ids, rs > 0 ? (size_t) rs : 0, whole) : 0; + if (back > 0) { + from = back; + took = true; + continued = whole; + } else if (rs >= 0 && m.restore(limit)) + from = (size_t) m.pos(); + else m.reset(); + } + if (took || from == 0) held.clear(); // (a slot is text only: the state that comes back holds no pictures) if ((int64_t) r.ids.size() + std::max(0LL, r.max_new) > m.max_context()) { std::printf("ERR the prompt (%zu tokens) and max_new %lld are more than the context %lld\n", r.ids.size(), r.max_new, (long long) m.max_context()); @@ -399,8 +753,12 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c }); // (DS4_LAST_WINDOW=1: the last token in a window of its own after the checkpoint, as before - for A/B runs) static const bool last_window = std::getenv("DS4_LAST_WINDOW") != nullptr; + // (pin=N: the read stops at N for a checkpoint of the shared start; only when this read crosses N, and N leaves + // the prompt's last token to the usual end) + const size_t pin_at = (r.pin >= 256 && (size_t) r.pin + 1 < total) ? (size_t) r.pin : 0; while (ok && done < total) { - const size_t n = std::min((size_t) m.feed_unit(), total - done); + size_t n = std::min((size_t) m.feed_unit(), total - done); + if (pin_at > done && pin_at < done + n) n = pin_at - done; // (the prompt's end: the last token in the same run, the checkpoint before it kept on the way) const bool fin = done + n == total; if (fin && last_window) { @@ -411,6 +769,7 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c ok = fin ? m.feed_mark(r.ids.data() + done, (int) n, 1, 1, err) : m.feed(r.ids.data() + done, (int) n, 0, err); done += n; + if (ok && pin_at != 0 && done == pin_at) m.checkpoint(3); if (ok && (done >= next_pp || done == total)) { const double ms = now_ms() - t0; std::printf("PP %zu %zu %.1f %.1f %zu\n", done, r.ids.size(), ms, @@ -431,6 +790,7 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c } held = std::move(pics); m.checkpoint(0); + if (!continued) m.pin(); // (a new run of prompts: where it may be rendered again from) const double t1 = now_ms(); long long produced = 0; const char* finish = "length"; @@ -527,6 +887,31 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c per_position(s_dec, s).c_str()); m.save_profile(); } + // the engine ends (QUIT or the end of its input): the conversation in the model is set aside, and every one in + // RAM is written to the folder, so the next run reads on from them + if (slot_max > 0) { + if (held.empty()) slot_put(" as the engine ended"); + size_t written = 0; + while (true) { // (a write can take the folder's least recently used conversation away: the list is asked again) + size_t i = SIZE_MAX; + for (size_t k = 0; k < slots.size(); ++k) + if (slots[k].data) { + i = k; + break; + } + if (i == SIZE_MAX) break; + if (slot_write_file(slots[i])) ++written; + else slot_drop(i); // (its state could not be written: there is nothing more to do at the engine's end) + } + if (written > 0) { + int ram = 0, disk = 0; + slot_count(ram, disk); + char msg[256]; + std::snprintf(msg, sizeof msg, "wrote %zu conversation(s) to %s; %d there in all", written, + slot_dir.string().c_str(), disk); + note(msg); + } + } m.save_profile(); return 0; } @@ -847,7 +1232,7 @@ int main(int argc, char** argv) { return 1; } if (!o.vision_only) std::fprintf(stderr, "%s", m.describe().c_str()); - if (serve_mode) return serve(m, eos, spec, o.dspark_conf); + if (serve_mode) return serve(m, eos, spec, o.dspark_conf, o.pack); const int window_given = window; if (window == 0) window = 16; // (the scoring / profiling runs; the plain run below takes the model's feed unit) if (!prof_ids.empty()) return profile_run(m, prof_ids, window); diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index a9e37044..7d17fc56 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -920,7 +921,14 @@ struct Model::Impl { std::vector> win; std::vector> comp; }; - Check ck[2]; // the end of the last prompt, and the position before it + static constexpr int kChecks = 4; + Check ck[kChecks]; // the end of the last prompt, the position before it, the anchor (the position + // before the end of the first prompt of the run of prompts that each continued + // the last in place: a chat template that drops earlier turns' reasoning at a new + // user message re-renders the history from about there) and the prefix (where the + // server said the prompt's shared start - system prompt and tools - ends: another + // agent behind the same start goes back to it) + bool slot_held = false; // slot_save took this state and nothing has changed it since std::vector prof; // [nl][n_exp] routed-expert hits Stats st; int cur_topk_n[kWin] = {}, cur_cand_n[kWin] = {}; // what the latest indexer / candidate source left, per query @@ -4528,7 +4536,8 @@ struct Model::Impl { pos = 0; toks.clear(); ctoks.clear(); - ck[0].pos = ck[1].pos = -1; + slot_held = false; + for (Check& c0 : ck) c0.pos = -1; for (Layer& l0 : L) for (int m = 0; m < l0.nm; ++m) { Layer& l = member(l0, m); @@ -4547,7 +4556,7 @@ struct Model::Impl { // the state at pos into checkpoint `slot` (the window rings and the compressors' partial groups: the rest of the // state is indexed by position, and what lies past a restored position is written again) void checkpoint(int slot) { - Check& c = ck[slot & 1]; + Check& c = ck[slot & (kChecks - 1)]; c.pos = pos; c.win.resize(L.size()); c.comp.resize(L.size() * 2); @@ -4574,7 +4583,7 @@ struct Model::Impl { // the checkpoint at or before position limit (the state's tokens agree with a new prompt up to there), or -1 int best_check(int64_t limit) const { int b = -1; - for (int i = 0; i < 2; ++i) + for (int i = 0; i < kChecks; ++i) if (ck[i].pos >= 0 && ck[i].pos <= limit && ck[i].pos <= pos && (b < 0 || ck[i].pos > ck[b].pos)) b = i; return b; } @@ -4583,6 +4592,33 @@ struct Model::Impl { return b < 0 ? -1 : ck[b].pos; } + // checkpoint 1 (the position before the last prompt's end) becomes the anchor too + void pin() { + if (ck[1].pos > 0) ck[2] = ck[1]; + } + // the checkpoints the state can go back to (what a slot of it keeps), latest first + std::vector check_positions() const { + std::vector v; + for (const Check& c : ck) + if (c.pos > 0 && c.pos <= pos && c.win.size() == L.size() && + std::find(v.begin(), v.end(), c.pos) == v.end()) + v.push_back(c.pos); + std::sort(v.rbegin(), v.rend()); + return v; + } + // the checkpoints a slot keeps (each with its role: 0, 1 or the anchor) + std::vector slot_checks() const { + std::vector v; + for (int i = 0; i < kChecks; ++i) + if (ck[i].pos > 0 && ck[i].pos <= pos && ck[i].win.size() == L.size()) v.push_back(i); + return v; + } + size_t check_bytes() const { + size_t n = 16; + for (const Layer& l : L) n += (size_t) g.win * win_rb() + (l.c_kv ? 2 * (size_t) l.ratio * g.hd * 4 : 0); + return n; + } + bool restore(int64_t limit) { const int b = best_check(limit); if (b < 0) return false; @@ -4606,11 +4642,362 @@ struct Model::Impl { pos = c.pos; toks.resize((size_t) pos); ctoks.resize((size_t) pos); + slot_held = false; for (Check& o2 : ck) // a later checkpoint saw tokens the state no longer has if (o2.pos > pos) o2.pos = -1; return true; } + // ---- the kept conversations (a slot): the state out of the model and back, through a file or a host buffer. + // A prompt that continues the state is reused in place (checkpoint / restore, the compressed KV left where it is); + // a conversation that leaves the model for another one is a slot - the whole state: the position, its tokens, + // every window ring (the DSpark blocks' included), the compressors' partial groups and each KV source's compressed + // KV and index keys up to it (rows 0 .. pos / ratio, the groups its position completed; one the prompt has not + // completed yet lives in the compressor's partial group). A tensor parallel group's members hold the same state, + // so one member's ring is saved and written back into all of them. Text only: a conversation that holds pictures + // is not a slot (the Engram history's rows are the tokens' again, no -1 among them). + static constexpr uint64_t kSlotMagic = 0x31544f4c53345344ull; // "DS4SLOT1" (little endian) + + int64_t src_rows(const Src& s) const { return pos / std::max(1, s.ratio); } + + // the slot's bytes: the header, the tokens, every layer's ring and partial group, every source's rows, the end + size_t slot_bytes() const { + size_t n = 8 + 8 + slot_identity().size() + 8 + (size_t) pos * 4; + for (const Layer& l : L) n += 8 + (size_t) g.win * win_rb() + 8 + (l.c_kv ? 2 * (size_t) l.ratio * g.hd * 4 : 0); + for (const Src& s : srcs) n += 8 + (size_t) src_rows(s) * (ckv_rb() + ik_rb()); + n += 8 + slot_checks().size() * check_bytes(); // (the checkpoints: what the slot can be taken back at) + return n + 8; + } + + uint64_t slot_save(std::vector& out, std::string& err) { + if (slot_held) { + err = "it is already set aside"; + return 0; + } + if (pos <= 0) { + err = "there is no conversation"; + return 0; + } + if ((int64_t) toks.size() != pos) { + err = "the state's tokens do not match its position"; + return 0; + } + if (!imgs.empty()) { + err = "it holds pictures"; + return 0; + } + const std::string id = slot_identity(); + out.assign(slot_bytes(), 0); + uint8_t* p = out.data(); + size_t off = 0; + const auto put = [&](const void* s, size_t b) { + std::memcpy(p + off, s, b); + off += b; + }; + const uint64_t il = id.size(), n = (uint64_t) pos; + put(&kSlotMagic, 8); + put(&il, 8); + put(id.data(), (size_t) il); + put(&n, 8); + put(toks.data(), (size_t) n * 4); + for (Dev& d : devs) { // (the devices' work ends before their state is read) + cudaSetDevice(d.id); + cudaStreamSynchronize(d.st); + } + for (size_t i = 0; i < L.size(); ++i) { + const Layer& l = L[i]; + const Dev& d = devs[(size_t) l.dev]; + cudaSetDevice(d.id); + const uint64_t wb = (uint64_t) g.win * win_rb(); + put(&wb, 8); + if (cudaMemcpy(p + off, l.win, (size_t) wb, cudaMemcpyDeviceToHost) != cudaSuccess) { + err = l.name + "window ring: " + cudaGetErrorString(cudaGetLastError()); + return 0; + } + off += (size_t) wb; + const uint64_t cn = l.c_kv ? (uint64_t) l.ratio * (uint64_t) g.hd : 0; + put(&cn, 8); + if (cn > 0) { + const size_t cb = (size_t) cn * 4; + if (cudaMemcpy(p + off, l.c_kv, cb, cudaMemcpyDeviceToHost) != cudaSuccess || + cudaMemcpy(p + off + cb, l.c_score, cb, cudaMemcpyDeviceToHost) != cudaSuccess) { + err = l.name + "compressor's group: " + cudaGetErrorString(cudaGetLastError()); + return 0; + } + off += 2 * cb; + } + } + for (const Src& s : srcs) { + const uint64_t rows = (uint64_t) src_rows(s); + put(&rows, 8); + if (rows == 0) continue; + const int di = L[(size_t) s.layer].dev; + const uint8_t* ckv = s.ckv[(size_t) di]; + const uint8_t* ik = s.ik[(size_t) di]; // (a pack whose sources are not index sources: none, zeros) + if (ckv == nullptr) { + err = "source layer " + std::to_string(s.layer) + "'s rows are not on its device"; + return 0; + } + const size_t cb = (size_t) rows * ckv_rb(), ib = (size_t) rows * ik_rb(); + cudaSetDevice(devs[(size_t) di].id); + if (cudaMemcpy(p + off, ckv, cb, cudaMemcpyDeviceToHost) != cudaSuccess || + (ik != nullptr && cudaMemcpy(p + off + cb, ik, ib, cudaMemcpyDeviceToHost) != cudaSuccess)) { + err = "source layer " + std::to_string(s.layer) + "'s compressed KV: " + cudaGetErrorString(cudaGetLastError()); + return 0; + } + off += cb + ib; + } + { + const std::vector cs = slot_checks(); + const uint64_t nc = cs.size(); + put(&nc, 8); + for (int k : cs) { + const Check& c = ck[k]; + const uint64_t role = (uint64_t) k, cp = (uint64_t) c.pos; + put(&role, 8); + put(&cp, 8); + for (size_t i = 0; i < L.size(); ++i) { + put(c.win[i].data(), (size_t) g.win * win_rb()); + if (L[i].c_kv) { + put(c.comp[2 * i].data(), (size_t) L[i].ratio * g.hd * 4); + put(c.comp[2 * i + 1].data(), (size_t) L[i].ratio * g.hd * 4); + } + } + } + } + if (off + 8 != out.size()) { + err = "the state's size does not add up"; + return 0; + } + put(&kSlotMagic, 8); + slot_held = true; + return (uint64_t) off; + } + + bool slot_load(const uint8_t* data, size_t bytes, int64_t n_pos, std::string& err) { + size_t off = 0; + bool wrote = false, ok = false; + // a load that stops after some of another conversation's state went into the layers leaves a state no + // checkpoint can repair: it is reset (the prompt is read from token 0), never served from the mix + struct FailClosed { + Impl& p; + const bool& wrote; + const bool& ok; + ~FailClosed() { + if (!ok && wrote) p.reset(); + } + } guard{*this, wrote, ok}; + const auto room = [&](size_t b) { return b <= bytes && off <= bytes - b; }; + uint64_t magic = 0, il = 0, n = 0; + if (!room(16)) { + err = "the slot is cut short"; + return false; + } + std::memcpy(&magic, data + off, 8); + std::memcpy(&il, data + off + 8, 8); + off += 16; + if (magic != kSlotMagic || il == 0 || il > (1u << 20)) { + err = "not a saved conversation"; + return false; + } + if (!room((size_t) il + 8)) { + err = "the slot is cut short"; + return false; + } + { + std::string id((size_t) il, '\0'); + std::memcpy(id.data(), data + off, (size_t) il); + off += (size_t) il; + std::memcpy(&n, data + off, 8); + off += 8; + if (id != slot_identity()) { + err = "another model's, or another engine version's, conversation"; + return false; + } + } + if (n != (uint64_t) n_pos || n_pos <= 0 || n_pos > o.max_context || !room((size_t) n * 4)) { + err = "the conversation's position is not this prompt's"; + return false; + } + std::vector toks_in((size_t) n); + std::memcpy(toks_in.data(), data + off, (size_t) n * 4); + off += (size_t) n * 4; + for (Dev& d : devs) { // (their work ends before the state is written over) + cudaSetDevice(d.id); + cudaStreamSynchronize(d.st); + } + for (size_t i = 0; i < L.size(); ++i) { + Layer& l = L[i]; + const Dev& d = devs[(size_t) l.dev]; + cudaSetDevice(d.id); + uint64_t wb = 0, cn = 0; + if (!room(8)) { + err = "the slot is cut short"; + return false; + } + std::memcpy(&wb, data + off, 8); + off += 8; + if (wb != (uint64_t) g.win * win_rb() || !room((size_t) wb + 8)) { + err = l.name + "window ring of another size"; + return false; + } + wrote = true; + for (int m = 0; m < l.nm; ++m) { + Layer& lm = member(l, m); + if (cudaMemcpy(lm.win, data + off, (size_t) wb, cudaMemcpyHostToDevice) != cudaSuccess) { + err = l.name + "window ring: " + cudaGetErrorString(cudaGetLastError()); + return false; + } + } + off += (size_t) wb; + std::memcpy(&cn, data + off, 8); + off += 8; + if (cn != (l.c_kv ? (uint64_t) l.ratio * (uint64_t) g.hd : 0)) { + err = l.name + "compressor's group of another size"; + return false; + } + if (cn > 0) { + const size_t cb = (size_t) cn * 4; + if (!room(2 * cb)) { + err = "the slot is cut short"; + return false; + } + for (int m = 0; m < l.nm; ++m) { + Layer& lm = member(l, m); + if (cudaMemcpy(lm.c_kv, data + off, cb, cudaMemcpyHostToDevice) != cudaSuccess || + cudaMemcpy(lm.c_score, data + off + cb, cb, cudaMemcpyHostToDevice) != cudaSuccess) { + err = l.name + "compressor's group: " + cudaGetErrorString(cudaGetLastError()); + return false; + } + } + off += 2 * cb; + } + } + for (const Src& s : srcs) { + uint64_t rows = 0; + if (!room(8)) { + err = "the slot is cut short"; + return false; + } + std::memcpy(&rows, data + off, 8); + off += 8; + if (rows != (uint64_t) (n_pos / std::max(1, s.ratio))) { + err = "source layer " + std::to_string(s.layer) + "'s rows are not this conversation's"; + return false; + } + if (rows == 0) continue; + const size_t cb = (size_t) rows * ckv_rb(), ib = (size_t) rows * ik_rb(); + if (!room(cb + ib)) { + err = "the slot is cut short"; + return false; + } + for (size_t di = 0; di < devs.size(); ++di) { + if (s.ckv[di] == nullptr && s.ik[di] == nullptr) continue; + cudaSetDevice(devs[di].id); + if (s.ckv[di] != nullptr && cudaMemcpy(s.ckv[di], data + off, cb, cudaMemcpyHostToDevice) != cudaSuccess) { + err = "source layer " + std::to_string(s.layer) + "'s compressed KV: " + cudaGetErrorString(cudaGetLastError()); + return false; + } + if (s.ik[di] != nullptr && + cudaMemcpy(s.ik[di], data + off + cb, ib, cudaMemcpyHostToDevice) != cudaSuccess) { + err = "source layer " + std::to_string(s.layer) + "'s index keys: " + cudaGetErrorString(cudaGetLastError()); + return false; + } + } + off += cb + ib; + } + Check got[kChecks]; // the slot's checkpoints: the positions it can be taken back at + { + uint64_t nc = 0; + if (!room(8)) { + err = "the slot is cut short"; + return false; + } + std::memcpy(&nc, data + off, 8); + off += 8; + if (nc > (uint64_t) kChecks) { + err = "the slot's checkpoints are damaged"; + return false; + } + for (uint64_t k = 0; k < nc; ++k) { + uint64_t role = 0, cp = 0; + if (!room(16)) { + err = "the slot is cut short"; + return false; + } + std::memcpy(&role, data + off, 8); + std::memcpy(&cp, data + off + 8, 8); + off += 16; + if (role >= (uint64_t) kChecks || got[role].pos >= 0 || cp == 0 || cp > (uint64_t) n_pos) { + err = "the slot's checkpoints are damaged"; + return false; + } + Check& c = got[role]; + c.pos = (int64_t) cp; + c.win.resize(L.size()); + c.comp.resize(L.size() * 2); + for (size_t i = 0; i < L.size(); ++i) { + const size_t wb = (size_t) g.win * win_rb(), cb = L[i].c_kv ? (size_t) L[i].ratio * g.hd * 4 : 0; + if (!room(wb + 2 * cb)) { + err = "the slot is cut short"; + return false; + } + c.win[i].assign(data + off, data + off + wb); + off += wb; + if (cb > 0) { + c.comp[2 * i].resize(cb / 4); + c.comp[2 * i + 1].resize(cb / 4); + std::memcpy(c.comp[2 * i].data(), data + off, cb); + std::memcpy(c.comp[2 * i + 1].data(), data + off + cb, cb); + off += 2 * cb; + } + } + } + } + uint64_t end = 0; + if (!room(8)) { + err = "the slot is cut short"; + return false; + } + std::memcpy(&end, data + off, 8); + off += 8; + if (end != kSlotMagic) { + err = "the slot does not end where it should"; + return false; + } + pos = n_pos; + toks.swap(toks_in); + ctoks.resize((size_t) pos); + for (size_t i = 0; i < (size_t) pos; ++i) + ctoks[i] = toks[i] < pk.eg_vocab ? pk.eg_map[(size_t) toks[i]] : 0; + for (int k = 0; k < kChecks; ++k) ck[k] = std::move(got[k]); // (the slot's own; the old ones held the state + // this one replaced) + slot_held = false; + ok = true; + return true; + } + + std::string slot_identity() const { + const auto size_of = [](const std::string& p) { + std::error_code ec; + const auto s = std::filesystem::file_size(p, ec); + return ec ? 0ull : (unsigned long long) s; + }; + std::ostringstream id; + id << "strata-ds4-session-3 engine=" << STRATA_VERSION << " mtp=" << g.n_mtp << " dim=" << g.dim << " hd=" << g.hd + << " win=" << g.win << " ratios="; + for (int r : g.ratios) id << r << ","; + id << " kv="; + for (int v : g.kv_src) id << v << ","; + id << " ix="; + for (int v : g.ix_src) id << v << ","; + id << " ds4.txt:" << size_of(pk.dir + "/ds4.txt") << " engram.bin:" << size_of(pk.dir + "/engram.bin") + << " tensors.txt:" << size_of(pk.dir + "/tensors.txt"); + for (size_t i = 0; i < pk.files.size(); ++i) + id << " " << pk.files[i] << ":" << os::file_size(pk.fds[i]); + return id.str(); + } + size_t bounce_bytes() const { return (size_t) kWin * ((size_t) g.hc * g.dim * 4 + 8 * 4 + topk_stride() * 4 + cand_stride() * 4); } @@ -6211,6 +6598,7 @@ struct Model::Impl { pos = p0 + keep; toks.resize((size_t) pos); ctoks.resize((size_t) pos); + slot_held = false; } // ---- a window: T tokens at positions pos .. pos + T - 1 through every layer; the logits of its last `logits` rows @@ -7583,6 +7971,7 @@ struct Model::Impl { return false; } const int64_t p0 = pos; + slot_held = false; // (the state grows now: what slot_save took is no longer the conversation) for (int t = 0; t < T; ++t) { toks.push_back(tk[t]); ctoks.push_back(ctok(pos + t, tk[t])); @@ -8404,7 +8793,14 @@ const std::vector& Model::tokens() const { return p_->toks; } void Model::reset() { p_->reset(); } void Model::checkpoint(int slot) { p_->checkpoint(slot); } bool Model::restore(int64_t limit) { return p_->restore(limit); } +void Model::pin() { p_->pin(); } +std::vector Model::check_positions() const { return p_->check_positions(); } int64_t Model::restorable(int64_t limit) const { return p_->restorable(limit); } +uint64_t Model::slot_save(std::vector& out, std::string& err) { return p_->slot_save(out, err); } +bool Model::slot_load(const uint8_t* data, size_t bytes, int64_t n_pos, std::string& err) { + return p_->slot_load(data, bytes, n_pos, err); +} +std::string Model::slot_identity() const { return p_->slot_identity(); } void Model::save_profile() const { p_->save_profile(); } const Stats& Model::stats() const { Stats& st = p_->st; diff --git a/src/dsv41/ds4_model.hpp b/src/dsv41/ds4_model.hpp index 929636d5..b4c35f0b 100644 --- a/src/dsv41/ds4_model.hpp +++ b/src/dsv41/ds4_model.hpp @@ -8,7 +8,9 @@ // its own 128-token window, the compressed groups completed by its position. The state a token leaves is the // 128-token window ring of every layer, the compressors' partial groups, the compressed KV and index keys of the KV // source layers (append-only), and the Engram n-gram history; checkpoint() / restore() keep the first two (the rest is -// truncated by position) so a conversation can go back to the end of its last prompt. +// truncated by position) so a conversation can go back to the end of its last prompt. A conversation that leaves the +// model altogether (another chat answered in between) is a slot: slot_save / slot_load take the same state - the +// compressed KV and index keys included, which a checkpoint leaves in place - through a file or a host buffer. #pragma once #include @@ -146,6 +148,23 @@ public: void checkpoint(int slot = 0); bool restore(int64_t limit); int64_t restorable(int64_t limit) const; + /// Checkpoint 1 also becomes the anchor (kept until a restore goes before it): the position before the end of the + /// first prompt of a run that continued in place, where a re-rendered history (earlier reasoning dropped) splits. + void pin(); + /// The positions restore() can go back to, latest first (a slot keeps them: it can be taken back at any of them). + std::vector check_positions() const; + + /// The conversation in the model into `out` (slot_save): its position, its tokens, every window ring (the DSpark + /// blocks' included), the compressors' partial groups and each KV source's compressed KV and index keys up to it, + /// the pieces the state a prompt continues is made of. 0 and err: nothing was set aside (it holds pictures, there + /// is no conversation, or the conversation is already set aside - unchanged since). + uint64_t slot_save(std::vector& out, std::string& err); + /// `data` (a slot's bytes) back into the model: the state at the slot's position n_pos, as slot_save took it - + /// what a prompt that continues the slot's tokens reads on from (the caller checked the tokens are a prefix). + bool slot_load(const uint8_t* data, size_t bytes, int64_t n_pos, std::string& err); + /// What a saved conversation must match: this engine's version, this model's geometry and files and the drafter's + /// blocks - a slot naming anything else is not this model's state (a file's .meta says so; slot_load refuses). + std::string slot_identity() const; /// The vision tower: the token every position of an image's span carries (-1: no tower). int image_token() const; diff --git a/src/dsv41/ds4_slotmeta.hpp b/src/dsv41/ds4_slotmeta.hpp new file mode 100644 index 00000000..dab9fea3 --- /dev/null +++ b/src/dsv41/ds4_slotmeta.hpp @@ -0,0 +1,98 @@ +// The kept-conversation (slot) bookkeeping that needs no GPU: a slot's .meta file (identity, size, tokens, checkpoint +// positions) and the choice of which kept conversation a prompt continues, and from where. The engine's serve loop +// (ds4_main.cpp) uses these; tests/dsv41/slot_test.cpp checks them alone. +// +// Slot .meta layout (little endian), "DS4META2": +// u64 magic, u64 identity length, identity bytes, u64 .bin bytes, u64 token count, i32 tokens[], +// u64 checkpoint count (0..4), i64 checkpoints[], u64 magic +// The magic at both ends and the .bin size make a half-written or foreign file refused, never read. +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::ds4::slotmeta { + +constexpr uint64_t kMagic = 0x324154454d345344ull; // "DS4META2" + +// Written under a temporary name and renamed over `path` (an interrupted write leaves no half file). +inline bool write(const std::string& path, const std::string& identity, const std::vector& toks, + uint64_t bytes, const std::vector& cks) { + const std::string tmp = path + ".tmp"; + { + std::ofstream f(tmp, std::ios::binary | std::ios::trunc); + const uint64_t il = identity.size(), nt = toks.size(), nc = cks.size(); + f.write((const char*) &kMagic, 8); + f.write((const char*) &il, 8); + f.write(identity.data(), (std::streamsize) il); + f.write((const char*) &bytes, 8); + f.write((const char*) &nt, 8); + f.write((const char*) toks.data(), (std::streamsize) (nt * sizeof(int32_t))); + f.write((const char*) &nc, 8); + f.write((const char*) cks.data(), (std::streamsize) (nc * sizeof(int64_t))); + f.write((const char*) &kMagic, 8); + f.flush(); + if (!f) return false; + } + std::error_code ec; + std::filesystem::rename(tmp, path, ec); + return !ec; +} + +// false: foreign (another identity), damaged, cut short, or not plausible (no tokens, more than max_ctx, a checkpoint +// outside the tokens). +inline bool read(const std::string& path, const std::string& identity, int64_t max_ctx, std::vector& toks, + uint64_t& bytes, std::vector& cks) { + std::ifstream f(path, std::ios::binary); + uint64_t m0 = 0, il = 0, nt = 0, nc = 0, m1 = 0; + if (!f.read((char*) &m0, 8) || m0 != kMagic || !f.read((char*) &il, 8) || il != identity.size()) return false; + std::string id(il, '\0'); + if (!f.read(id.data(), (std::streamsize) il) || id != identity) return false; + if (!f.read((char*) &bytes, 8) || !f.read((char*) &nt, 8) || nt == 0 || nt > (uint64_t) max_ctx) return false; + toks.resize(nt); + if (!f.read((char*) toks.data(), (std::streamsize) (nt * sizeof(int32_t))) || !f.read((char*) &nc, 8) || nc > 4) + return false; + cks.resize(nc); + if (!f.read((char*) cks.data(), (std::streamsize) (nc * sizeof(int64_t))) || !f.read((char*) &m1, 8) || m1 != kMagic) + return false; + for (int64_t c : cks) + if (c <= 0 || (uint64_t) c > nt) return false; + return true; +} + +// The kept conversation `prompt` continues the furthest, and where: *len is the number of the slot's tokens that are +// the prompt's (0: none). A conversation the prompt continues whole comes back whole (len == its size); one the prompt +// leaves part way - a retried prompt, a history re-rendered without the earlier reasoning - comes back at its latest +// checkpoint the prompt still agrees with. Only a match longer than `floor` (what the model itself can go back to) +// counts. The last prompt token is never covered (a prompt always reads its last token). Ties keep the earlier slot. +struct Cand { + const std::vector* tokens; + const std::vector* cks; +}; +inline size_t pick(const std::vector& slots, const std::vector& prompt, size_t floor, size_t* len) { + *len = 0; + if (prompt.size() < 2) return SIZE_MAX; + size_t best = SIZE_MAX; + for (size_t i = 0; i < slots.size(); ++i) { + const std::vector& t = *slots[i].tokens; + const size_t lim = std::min(t.size(), prompt.size() - 1); + size_t c = 0; + while (c < lim && t[c] == prompt[c]) ++c; + size_t u = c == t.size() ? c : 0; + if (u == 0) + for (int64_t k : *slots[i].cks) + if ((size_t) k <= c && (size_t) k > u) u = (size_t) k; + if (u > *len && u > floor) { + best = i; + *len = u; + } + } + return best; +} + +} // namespace strata::ds4::slotmeta diff --git a/tests/dsv41/slot_test.cpp b/tests/dsv41/slot_test.cpp new file mode 100644 index 00000000..0235b05c --- /dev/null +++ b/tests/dsv41/slot_test.cpp @@ -0,0 +1,153 @@ +// The kept conversations' bookkeeping without a GPU (src/dsv41/ds4_slotmeta.hpp): the .meta file's round trip and +// every way it is refused, and which kept conversation a prompt continues, and from where. +// ds4_slot_test exit 0: all passed +#include "ds4_slotmeta.hpp" + +#include +#include +#include +#include +#include + +namespace sm = strata::ds4::slotmeta; +namespace fs = std::filesystem; + +static int fails = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::printf("FAIL line %d: %s\n", __LINE__, #c); \ + ++fails; \ + } \ + } while (0) + +static std::vector seq(int a, int n) { + std::vector v((size_t) n); + for (int i = 0; i < n; ++i) v[(size_t) i] = a + i; + return v; +} +static std::vector as_int(const std::vector& v) { return std::vector(v.begin(), v.end()); } + +static void patch(const std::string& p, size_t off, uint8_t b) { + std::FILE* f = std::fopen(p.c_str(), "r+b"); + std::fseek(f, (long) off, SEEK_SET); + std::fwrite(&b, 1, 1, f); + std::fclose(f); +} + +static void meta_tests(const fs::path& dir) { + const std::string id = "strata-ds4-session-2 engine=test", path = (dir / "slot-1.meta").string(); + const std::vector toks = seq(100, 50); + const std::vector cks = {40, 33, 7}; + CHECK(sm::write(path, id, toks, 123456789ull, cks)); + CHECK(!fs::exists(path + ".tmp")); // (renamed over, no half file left) + std::vector t; + std::vector c; + uint64_t bytes = 0; + CHECK(sm::read(path, id, 1000, t, bytes, c)); + CHECK(t == toks && c == cks && bytes == 123456789ull); + // no checkpoints is valid (a slot of a state that had none) + CHECK(sm::write(path, id, toks, 5, {})); + CHECK(sm::read(path, id, 1000, t, bytes, c) && c.empty() && bytes == 5); + // another model's / engine's identity: refused, never read + CHECK(!sm::read(path, id + "x", 1000, t, bytes, c)); + CHECK(!sm::read(path, "other", 1000, t, bytes, c)); + // more tokens than the context: refused + CHECK(!sm::read(path, id, 49, t, bytes, c)); + CHECK(sm::read(path, id, 50, t, bytes, c)); + // a missing file + CHECK(!sm::read((dir / "none.meta").string(), id, 1000, t, bytes, c)); + // every cut length, a damaged magic at either end + CHECK(sm::write(path, id, toks, 9, cks)); + const size_t full = (size_t) fs::file_size(path); + for (size_t keep = 0; keep < full; ++keep) { + fs::copy_file(path, dir / "cut.meta", fs::copy_options::overwrite_existing); + fs::resize_file(dir / "cut.meta", keep); + if (sm::read((dir / "cut.meta").string(), id, 1000, t, bytes, c)) { + std::printf("FAIL: a .meta cut to %zu of %zu bytes was read\n", keep, full); + ++fails; + break; + } + } + fs::copy_file(path, dir / "bad0.meta", fs::copy_options::overwrite_existing); + patch((dir / "bad0.meta").string(), 0, 0x55); + CHECK(!sm::read((dir / "bad0.meta").string(), id, 1000, t, bytes, c)); + fs::copy_file(path, dir / "bad1.meta", fs::copy_options::overwrite_existing); + patch((dir / "bad1.meta").string(), full - 1, 0x55); + CHECK(!sm::read((dir / "bad1.meta").string(), id, 1000, t, bytes, c)); + // a checkpoint outside the conversation, a zero one, more than four + CHECK(sm::write(path, id, toks, 9, {51})); + CHECK(!sm::read(path, id, 1000, t, bytes, c)); + CHECK(sm::write(path, id, toks, 9, {0})); + CHECK(!sm::read(path, id, 1000, t, bytes, c)); + CHECK(sm::write(path, id, toks, 9, {4, 3, 2, 1})); + CHECK(sm::read(path, id, 1000, t, bytes, c) && c.size() == 4); + CHECK(sm::write(path, id, toks, 9, {1, 2, 3, 4, 5})); + CHECK(!sm::read(path, id, 1000, t, bytes, c)); + // no tokens at all + CHECK(sm::write(path, id, {}, 9, {})); + CHECK(!sm::read(path, id, 1000, t, bytes, c)); + // an unwritable place: false, not a crash + CHECK(!sm::write((dir / "nodir" / "x.meta").string(), id, toks, 1, {})); +} + +static size_t pick(const std::vector>& toks, const std::vector>& cks, + const std::vector& prompt, size_t floor, size_t* len) { + std::vector c; + for (size_t i = 0; i < toks.size(); ++i) c.push_back({&toks[i], &cks[i]}); + return sm::pick(c, prompt, floor, len); +} + +static void pick_tests() { + size_t len = 99; + const std::vector a = seq(1000, 3000), b = seq(5000, 2000); + // the next turn of A: A whole, then new tokens + std::vector a_turn = a; + for (int32_t x : seq(9000, 40)) a_turn.push_back(x); + CHECK(pick({a, b}, {{}, {}}, as_int(a_turn), 0, &len) == 0 && len == a.size()); + CHECK(pick({b, a}, {{}, {}}, as_int(a_turn), 0, &len) == 1 && len == a.size()); + // nothing shared: none, len 0 + CHECK(pick({a, b}, {{}, {}}, as_int(seq(7777, 100)), 0, &len) == SIZE_MAX && len == 0); + // a prompt equal to the slot's tokens: the last token is still read, so the slot is not taken whole + CHECK(pick({a}, {{}}, as_int(a), 0, &len) == SIZE_MAX && len == 0); + CHECK(pick({a}, {{2900}}, as_int(a), 0, &len) == 0 && len == 2900); + // a shorter prompt than the slot (a prefix of it): taken at a checkpoint within it, never past it + std::vector head(a.begin(), a.begin() + 2000); + CHECK(pick({a}, {{2900, 1500}}, as_int(head), 0, &len) == 0 && len == 1500); + // a retried prompt: A's prompt end (2950) is a checkpoint; the new prompt agrees up to 2960 then differs + std::vector retry(a.begin(), a.begin() + 2960); + for (int32_t x : seq(8000, 30)) retry.push_back(x); + CHECK(pick({a}, {{2950, 2000, 1000}}, as_int(retry), 0, &len) == 0 && len == 2950); + // diverging before the latest checkpoint: the latest one it still agrees with (the anchor) + std::vector early(a.begin(), a.begin() + 1200); + for (int32_t x : seq(8000, 30)) early.push_back(x); + CHECK(pick({a}, {{2950, 2000, 1000}}, as_int(early), 0, &len) == 0 && len == 1000); + // diverging before every checkpoint: none + std::vector first(a.begin(), a.begin() + 500); + for (int32_t x : seq(8000, 30)) first.push_back(x); + CHECK(pick({a}, {{2950, 2000, 1000}}, as_int(first), 0, &len) == SIZE_MAX && len == 0); + // the floor: what the model itself can go back to wins unless the slot goes further + CHECK(pick({a}, {{}}, as_int(a_turn), 3000, &len) == SIZE_MAX && len == 0); + CHECK(pick({a}, {{}}, as_int(a_turn), 2999, &len) == 0 && len == 3000); + // two slots, the longer match wins; a tie keeps the earlier one + std::vector a_short(a.begin(), a.begin() + 1000); + CHECK(pick({a_short, a}, {{}, {}}, as_int(a_turn), 0, &len) == 1 && len == 3000); + CHECK(pick({a, a}, {{}, {}}, as_int(a_turn), 0, &len) == 0 && len == 3000); + // too short a prompt + CHECK(pick({a}, {{}}, {1000}, 0, &len) == SIZE_MAX && len == 0); + CHECK(pick({a}, {{}}, {}, 0, &len) == SIZE_MAX && len == 0); + // an empty slot list + CHECK(pick({}, {}, as_int(a_turn), 0, &len) == SIZE_MAX && len == 0); +} + +int main() { + const fs::path dir = fs::temp_directory_path() / "ds4-slot-test"; + std::error_code ec; + fs::remove_all(dir, ec); + fs::create_directories(dir); + meta_tests(dir); + pick_tests(); + fs::remove_all(dir, ec); + std::printf(fails ? "FAILED: %d\n" : "slot_test: all passed\n", fails); + return fails ? 1 : 0; +} From b8f9c63ae7439b1e24b6bd111ee39a98441bfcc6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:59:52 +0200 Subject: [PATCH 12/34] serve: DeepSeek-V4.1 marks the system prompt and tools as the shared start (pin=N) so a sub-agent goes back to it Only the deepseek41 family; STRATA_DS4_AUTO_PIN=0 switches it off, a client's own strata_prefix wins, Qwen is untouched. --- serve/server.py | 20 +++++++++++++++++++ serve/test_dsv41.py | 48 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/serve/server.py b/serve/server.py index 19e03a2b..8141108d 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4894,10 +4894,30 @@ class Service: # (an encoder restart, the cache's eviction) with other bits still matches its checkpoints self.embeddings.keys = [Path(p).stem[:16] for p, _ in encoded] write_temporary(combined, [p for p, _ in encoded]) + if self.family == "deepseek41" and req is not None and req.get("strata_prefix") is None and not images: + lead = self.deepseek_shared_start(messages) + if lead: + req["strata_prefix"] = {"messages": lead} if req is not None and req.get("strata_prefix") is not None: req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images)) return ids, kwargs.get("enable_thinking", True) is not False, max_new + @staticmethod + def deepseek_shared_start(messages) -> int: + """DeepSeek-V4.1 only: how many leading messages are the system prompt (its tools are rendered with them). An + agent and its sub-agents that work behind the same system prompt and tools share exactly this start, so the + engine keeps a checkpoint of its state there (pin=N): the next agent behind the same start goes back to it + instead of reading it again. 0: none (STRATA_DS4_AUTO_PIN=0, no system message, or nothing after it).""" + if os.environ.get("STRATA_DS4_AUTO_PIN", "1") == "0": + return 0 + n = 0 + for m in messages: + if isinstance(m, dict) and m.get("role") in ("system", "developer"): + n += 1 + else: + break + return n if 0 < n < len(messages) else 0 + PREFIX_END = "\u0001strata-prefix-end\u0001" # marks where a message's shared part ends in the rendered prompt def resolve_prefix(self, spec, messages, tools, kwargs, ids, has_images=False) -> dict: diff --git a/serve/test_dsv41.py b/serve/test_dsv41.py index bc798034..a4c13bcd 100644 --- a/serve/test_dsv41.py +++ b/serve/test_dsv41.py @@ -527,6 +527,54 @@ class Api(unittest.TestCase): self.assertEqual(last["decode_tok_s"], 100.0) + # -- the shared start of an agent's and its sub-agents' prompts (the engine keeps its state there) ------------ + def test_the_system_prompt_and_tools_are_the_shared_start(self): + self.start("ok") + sysmsg = {"role": "system", "content": "You are an agent. " * 20} + body = {"messages": [sysmsg, {"role": "user", "content": "task one"}], "tools": [WEATHER], "max_tokens": 40} + self.assertEqual(self.post("/v1/chat/completions", body)[0], 200) + n = self.engine.last_sampling["strata_prefix"]["tokens"] + ids = self.engine.last_prompt + self.assertTrue(0 < n < len(ids) - 1) + self.assertIn("get_weather", self.tok.decode(ids[:n])) # the tools are in the shared start + self.assertNotIn("task one", self.tok.decode(ids[:n])) # the first user message is not + # another agent behind the same system prompt and tools, another task: the same boundary, the same start + body["messages"] = [sysmsg, {"role": "user", "content": "a different task for the sub-agent"}] + self.assertEqual(self.post("/v1/chat/completions", body)[0], 200) + self.assertEqual(self.engine.last_sampling["strata_prefix"]["tokens"], n) + self.assertEqual(self.engine.last_prompt[:n], ids[:n]) + + def test_no_shared_start_without_a_system_prompt_or_when_switched_off(self): + self.start("ok") + self.chat() + self.assertNotIn("strata_prefix", self.engine.last_sampling) + body = {"messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], "max_tokens": 40} + old = os.environ.get("STRATA_DS4_AUTO_PIN") + os.environ["STRATA_DS4_AUTO_PIN"] = "0" + try: + self.post("/v1/chat/completions", body) + self.assertNotIn("strata_prefix", self.engine.last_sampling) + finally: + if old is None: + os.environ.pop("STRATA_DS4_AUTO_PIN", None) + else: + os.environ["STRATA_DS4_AUTO_PIN"] = old + + def test_a_clients_own_prefix_wins(self): + self.start("ok") + body = {"messages": [{"role": "system", "content": "s " * 30}, {"role": "user", "content": "u"}], + "max_tokens": 40, "strata_prefix": {"tokens": 7}} + self.post("/v1/chat/completions", body) + self.assertEqual(self.engine.last_sampling["strata_prefix"], {"tokens": 7}) + + def test_the_qwen_path_asks_for_no_prefix(self): + # the same request on a server that is not DeepSeek's: nothing is added (Qwen keeps its own cache logic) + svc = Service(MockEngine(self.tok, "ok"), self.tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja")) + req = {} + svc.prepare([{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], None, {}, 16, req=req) + self.assertEqual(req, {}) + + class PickTemplateTests(unittest.TestCase): """A pack made from another GGUF can ship the V4-Flash template (`tool_calls`, no space): the V4.1 model then writes malformed calls (P2003 install test). The server swaps in the V4.1 template for such a pack.""" From 1d31e2a1e474bcb9bc167be5cdf1cfbbfe7604a9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 00:59:52 +0200 Subject: [PATCH 13/34] tools/dsv41/slot_keep_test.py: two agents taking turns, fresh reads vs shared start vs slots vs restart vs folder cap --- tools/dsv41/slot_keep_test.py | 475 ++++++++++++++++++++++++++++++++++ 1 file changed, 475 insertions(+) create mode 100644 tools/dsv41/slot_keep_test.py diff --git a/tools/dsv41/slot_keep_test.py b/tools/dsv41/slot_keep_test.py new file mode 100644 index 00000000..8e3ec365 --- /dev/null +++ b/tools/dsv41/slot_keep_test.py @@ -0,0 +1,475 @@ +#!/usr/bin/env python3 +"""tools/dsv41/slot_keep_test.py - the kept conversations of strata-dsv41 (STRATA_DS4_SLOT_KEEP=1): a prompt that does +not continue the conversation in the model takes the kept one it does continue back, so an agent and its sub-agents +that take turns on one model read only their new tokens. + + python tools/dsv41/slot_keep_test.py --exe build/strata-dsv41 --pack /data/pack2.00 --ids-dir /tmp/slot-ids + [--engine-args "--vram-experts 0 --max-context 20000"] [--turns 3] [--steps ref,old,pin,on,restart,cap] + +The prompts are real text (this repo's docs), tokenized through the pack's tokenizer (tools/strata_tokenizer.py, needs +`regex`) the first time and kept as .ids files in --ids-dir, so a box without `regex` can run the test from a folder +made elsewhere (--make-only writes just the folder). Random ids draw near-tie logits, where two greedy runs differ and +nothing can be compared; real text does not. + +Runs of the engine's `--serve` protocol, greedy, spec=0 (the state's position is then exactly the answer's). Two agents, +A (parent) and B (a sub-agent), each with its own conversation behind the SAME system prompt and tools, take turns +A1 B1 A2 B2 ... (the server marks the shared start with pin=N on every request): + ref STRATA_DS4_REUSE=0: every request is a fresh read of its whole prompt. Its answers are the reference every + other run must print, token for token. + old the engine as it was (no pin, no slots): each turn reads its whole prompt again, the other agent having + taken the model. Timings only. + pin the shared start marked, no slots: B goes back to the start A's state holds instead of reading it again. + on the shared start marked and the slots on: a turn that continues a kept conversation reads only its new tokens. + restart a new process on the folder `on` left (QUIT wrote the conversations there): each agent's next turn reads only + its new tokens. + cap a folder capped below three conversations' size: it stays under the cap and the newest is kept. + +Exit 0: every check passed. 1: a check failed (the reason is printed). 2: the engine did not start or answer, or the +prompts could not be made. +""" +from __future__ import annotations + +import argparse +import json +import os +import queue +import shlex +import shutil +import struct +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +META_MAGIC = 0x324154454D345344 # "DS4META2" (little endian): a slot's .meta, as src/dsv41/ds4_slotmeta.hpp writes it + + +# ------------------------------------------------------------------------------------------------- prompts +def corpus_text() -> str: + """Real text for the prompts: the repo's README and docs, in a fixed order.""" + parts = [] + for p in [ROOT / "README.md", *sorted((ROOT / "docs").glob("*.md"))]: + try: + parts.append(p.read_text(encoding="utf-8")) + except OSError: + continue + return "\n\n".join(parts) + + +def text_tokens(tok, text: str, salt: str, n: int) -> list[int]: + """`n` tokens of `text`, opened by `salt` (so two prompts differ from their first words), repeated if too short.""" + out: list[int] = [] + i = 0 + text = text[:max(4000, n * 7)] # (a few chars a token; the loop below repeats it if that was too short) + while len(out) < n: + out += tok.encode(f"{salt} {i}.\n{text}\n", parse_special=False) + i += 1 + return out[:n] + + +def make_tokenizer(pack: str): + sys.path.insert(0, str(ROOT / "tools")) + import strata_tokenizer as ST # noqa: E402 + t = Path(pack) / "tokenizer" + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + tokens = [None] * len(vocab) + for s, i in vocab.items(): + tokens[i] = s + return ST.Tokenizer(tokens, (t / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((t / "token_type.json").read_text(encoding="utf-8"))) + + +def prompts(ids_dir: Path, pack: str, n_sys: int, n_task: int, n_turn: int, turns: int) -> dict[str, list[int]]: + """sys (the shared system prompt + tools), taskA, taskB, and turnA1.. turnB (each new user/tool text).""" + want = {"sys": n_sys, "taskA": n_task, "taskB": n_task, **{f"turn{x}{i}": n_turn for x in "AB" for i in range(1, turns + 1)}} + ids_dir.mkdir(parents=True, exist_ok=True) + have: dict[str, list[int]] = {} + tok = None + text = None + for name, n in want.items(): + f = ids_dir / f"{name}.ids" + ids: list[int] | None = None + if f.exists(): + ids = [int(x) for x in f.read_text().split()] + if len(ids) != n: + ids = None + if ids is None: + if tok is None: + tok = make_tokenizer(pack) + text = corpus_text() + salt = {"sys": "System prompt and tools.", "taskA": "Task for agent A."}.get(name, f"Message {name}.") + if name == "taskB": + salt = "Task for agent B." + # (the system prompt is cut from the corpus' start, the others from later in it, so they differ) + body = text if name == "sys" else text[len(text) // 3:] + ids = text_tokens(tok, body, salt, n) + f.write_text(" ".join(str(x) for x in ids)) + have[name] = ids + return have + + +# ------------------------------------------------------------------------------------------------- the .meta file +def meta_tokens(path: str) -> tuple[list[int], list[int]] | None: + """A slot's .meta, as the engine writes it: the magic, its identity (length, bytes), the state's size, its tokens, + its checkpoints (count, positions), the magic again. None: not one of the engine's .meta files, or damaged.""" + try: + with open(path, "rb") as f: + data = f.read() + m0, il = struct.unpack_from(" None: + for raw in iter(self.proc.stdout.readline, b""): + self.lines.put(raw.decode("utf-8", "replace").strip()) + self.lines.put(None) + + def _line(self, end: float) -> str: + while True: + left = end - time.monotonic() + if left <= 0: + raise RuntimeError("the engine did not answer in time") + try: + line = self.lines.get(timeout=min(left, 5.0)) + except queue.Empty: + if self.proc.poll() is not None and self.lines.empty(): + raise RuntimeError(f"the engine ended (exit {self.proc.returncode})") + continue + if line is None: + raise RuntimeError("the engine's output ended") + if line.startswith("NOTE "): + self.notes.append(line[5:].strip()) + return line + + def start(self, timeout: float) -> None: + env = dict(os.environ) + env.update(self.env) + fd, self.err_path = tempfile.mkstemp(prefix="ds4-slots-err-") + err = os.fdopen(fd, "wb") + self.proc = subprocess.Popen([self.exe, *self.args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err, + env=env, bufsize=0) + err.close() + threading.Thread(target=self._pump, daemon=True).start() + end = time.monotonic() + timeout + while True: + line = self._line(end) + if line.startswith("READY "): + self.ready = line + return + if line.startswith("ERR "): + raise RuntimeError("the engine refused to start: " + line) + + def request(self, prompt: list[int], max_new: int, pin: int = 0, timeout: float = 3600.0) -> dict: + keys = f" pin={pin}" if pin else "" + self.proc.stdin.write(f"GEN {max_new} spec=0{keys} {','.join(str(t) for t in prompt)}\n".encode()) + self.proc.stdin.flush() + out = {"tokens": [], "reused": None, "prompt_len": len(prompt), "finish": None, "s": 0.0, "ttft_ms": 0.0} + t0 = time.monotonic() + end = t0 + timeout + while True: + line = self._line(end) + if line.startswith("T "): + out["tokens"].append(int(line[2:])) + elif line.startswith("ERR "): + out["error"] = line[4:] + return out + elif line.startswith("DONE "): + f = line.split() + out["generated"], out["prompt"], out["finish"] = int(f[1]), int(f[2]), f[5] + out["ttft_ms"] = float(f[3]) # (request start to the first token's logits: the restore + the read) + out["decode_ms"] = float(f[4]) + out["reused"] = int(f[8]) + out["s"] = time.monotonic() - t0 + return out + + def quit(self, timeout: float = 300.0) -> None: + try: + self.proc.stdin.write(b"QUIT\n") + self.proc.stdin.flush() + except OSError: + pass + end = time.monotonic() + timeout + while time.monotonic() < end: + try: + line = self.lines.get(timeout=1.0) + except queue.Empty: + if self.proc.poll() is not None: + break + continue + if line is None: + break + if line.startswith("NOTE "): + self.notes.append(line[5:].strip()) + try: + self.proc.wait(timeout=max(1.0, end - time.monotonic())) + except subprocess.TimeoutExpired: + self.proc.kill() + raise RuntimeError("the engine did not end after QUIT") + + def stderr_lines(self) -> list[str]: + if not self.err_path: + return [] + try: + with open(self.err_path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + os.unlink(self.err_path) + except OSError: + return [] + return lines + + +def run(exe: str, pack: str, engine_args: list[str], slots: str, keep: bool, steps: list[tuple[str, object]], + max_new: int, pin: int = 0, reuse: bool = True, slot_gb: float | None = None, load_timeout: float = 3600.0): + """One engine process; each step is (name, a function of the answers so far that gives its prompt). `pin`: the + shared start's length sent with every request (what the server sends); `reuse` False: every request is a fresh + read of its whole prompt (STRATA_DS4_REUSE=0).""" + env = {"STRATA_DS4_SLOT_KEEP": "1" if keep else "0", "STRATA_DS4_SLOT_DIR": slots, "STRATA_DS4_SLOT_MIN": "256", + "STRATA_DS4_REUSE": "1" if reuse else "0"} + if slot_gb is not None: + env["STRATA_DS4_SLOT_GB"] = str(slot_gb) + args = ["--pack", pack, "--dspark", "off", "--threads", "on", "--vision", "off", "--expert-profile", "none", + *engine_args, "--serve"] + eng = Engine(exe, args, env) + t0 = time.monotonic() + answers: dict[str, dict] = {} + try: + eng.start(load_timeout) + load_s = time.monotonic() - t0 + for name, make in steps: + prompt = make(answers) + answers[name] = eng.request(prompt, max_new, pin=pin) + if "error" in answers[name]: + raise RuntimeError(f"{name}: {answers[name]['error']}") + finally: + if eng.proc is not None: + try: + eng.quit() + except RuntimeError as e: + print(" ", e, flush=True) + err = eng.stderr_lines() + for line in err: + if line.startswith("ds4 slots:") and "failed" in line: + raise RuntimeError("the engine: " + line) + return answers, eng.notes, load_s + + +def main() -> int: + ap = argparse.ArgumentParser(description="the kept conversations: two agents taking turns on one model") + ap.add_argument("--pack", required=True) + ap.add_argument("--exe", default=str(ROOT / "build" / "strata-dsv41")) + ap.add_argument("--ids-dir", default="", help="the prompts' .ids files (made from the docs when missing)") + ap.add_argument("--make-only", action="store_true", help="write the .ids files and stop") + ap.add_argument("--engine-args", default="", help="more engine flags, e.g. '--vram-experts 0 --max-context 20000'") + ap.add_argument("--len-sys", type=int, default=6000, help="the shared system prompt + tools (tokens)") + ap.add_argument("--len-task", type=int, default=300, help="each agent's own first message (tokens)") + ap.add_argument("--len-turn", type=int, default=150, help="each later message (tokens)") + ap.add_argument("--turns", type=int, default=3, help="turns per agent") + ap.add_argument("--max-new", type=int, default=24) + ap.add_argument("--steps", default="ref,old,pin,on,restart,cap", + help="ref: fresh reads (the reference), old: the engine as it was, pin: the shared start only, " + "on: slots + shared start, restart: a new process on the folder, cap: the folder's cap") + ap.add_argument("--keep-dir", default="", help="keep the slot folders here (default: a temp dir, removed)") + a_ = ap.parse_args() + steps = set(a_.steps.split(",")) + ids_dir = Path(a_.ids_dir or tempfile.mkdtemp(prefix="slot-ids-")) + try: + P = prompts(ids_dir, a_.pack, a_.len_sys, a_.len_task, a_.len_turn, a_.turns + 1) + except (OSError, ImportError, ValueError) as e: + print(f"the prompts cannot be made: {e}", flush=True) + return 2 + if a_.make_only: + print(f"prompts written to {ids_dir}", flush=True) + return 0 + if not os.path.exists(a_.exe): + print(f"{a_.exe}: no engine - build it first", flush=True) + return 2 + engine_args = shlex.split(a_.engine_args) + N, max_new = a_.turns, a_.max_new + PIN = len(P["sys"]) + ok = True + + def check(what: str, cond: bool) -> None: + nonlocal ok + print((" ok " if cond else " FAIL ") + what, flush=True) + ok = ok and cond + + # the turns A1 B1 A2 B2 ...; an agent's prompt is its previous prompt + the answer it got + the new message + # (the answers of `ref` when given, so every arm sends the same prompts byte for byte) + def build_steps(ref: dict | None, upto: int = N, start: int = 1, agents: str = "AB"): + out = [] + for i in range(start, upto + 1): + for x in agents: + def make(ans, x=x, i=i): + src = ref if ref is not None else ans + prompt = P["sys"] + P["task" + x] + for j in range(1, i): + prompt = prompt + src[f"{x}{j}"]["tokens"] + P[f"turn{x}{j}"] + return prompt + out.append((f"{x}{i}", make)) + return out + + def table(ans: dict, upto: int = N) -> tuple[float, float]: + for i in range(1, upto + 1): + for x in "AB": + r = ans[f"{x}{i}"] + print(f" {x}{i}: prompt {r['prompt_len']:>6} first token {r['ttft_ms'] / 1000:6.2f} s " + f"reused {r['reused']:>6}", flush=True) + wall = sum(ans[f"{x}{i}"]["s"] for i in range(1, upto + 1) for x in "AB") + tt = sum(ans[f"{x}{i}"]["ttft_ms"] for i in range(1, upto + 1) for x in "AB") / 1000 + print(f" {2 * upto} turns: wall {wall:.1f} s, time to first token (sum) {tt:.1f} s", flush=True) + return wall, tt + + def same_tokens(name: str, ans: dict, ref: dict, upto: int = N) -> bool: + bad = [f"{x}{i}" for i in range(1, upto + 1) for x in "AB" if ans[f"{x}{i}"]["tokens"] != ref[f"{x}{i}"]["tokens"]] + for k in bad: + print(f" {k}: {ans[k]['tokens'][:8]} vs the reference's {ref[k]['tokens'][:8]}", flush=True) + return not bad + + tmp = tempfile.mkdtemp(prefix="ds4-slots-") if not a_.keep_dir else a_.keep_dir + os.makedirs(tmp, exist_ok=True) + dir_on = os.path.join(tmp, "on") + ref = None + sums: dict[str, tuple[float, float]] = {} + try: + print(f"prompts: system+tools {len(P['sys'])} tok, task {len(P['taskA'])}, turn {len(P['turnA1'])}; " + f"{N} turns per agent, {max_new} new tokens each, pin={PIN}", flush=True) + need_ref = bool(steps & {"ref", "pin", "on", "restart", "cap"}) + if need_ref: + print("ref: A1 B1 A2 B2 ... every request a fresh read of its whole prompt (STRATA_DS4_REUSE=0), shared " + "start marked", flush=True) + ref, _, load0 = run(a_.exe, a_.pack, engine_args, os.path.join(tmp, "ref"), False, + build_steps(None, N + 1), max_new, pin=PIN, reuse=False) + print(f" load {load0:.0f} s", flush=True) + sums["ref"] = table(ref) + check("ref: nothing is reused", all(ref[f"{x}{i}"]["reused"] == 0 for i in range(1, N + 1) for x in "AB")) + + if "old" in steps: + print("old: the engine as it was (no shared start, no slots): the other agent takes the model every turn", + flush=True) + old, _, _ = run(a_.exe, a_.pack, engine_args, os.path.join(tmp, "old"), False, + build_steps(ref, N) if ref else build_steps(None, N), max_new) + sums["old"] = table(old) + if ref is not None: + print(f" tokens {'the same as' if same_tokens('old', old, ref) else 'DIFFER from'} the reference's " + "(informational: no shared-start split here)", flush=True) + + if "pin" in steps: + print("pin: the shared start marked, no slots: a sub-agent goes back to the start the other left", flush=True) + pn, _, _ = run(a_.exe, a_.pack, engine_args, os.path.join(tmp, "pin"), False, build_steps(ref, N), max_new, + pin=PIN) + sums["pin"] = table(pn) + check(f"pin: the sub-agent's first turn reads only its own task (reused {pn['B1']['reused']} of {PIN})", + pn["B1"]["reused"] == PIN) + check(f"pin: every turn prints the reference's tokens ({2 * N} x {max_new})", same_tokens("pin", pn, ref)) + + if "on" in steps: + print("on: slots on (RAM) and the shared start marked", flush=True) + on, notes, _ = run(a_.exe, a_.pack, engine_args, dir_on, True, build_steps(ref, N), max_new, pin=PIN) + sums["on"] = table(on) + check(f"on: the sub-agent's first turn reads only its own task (reused {on['B1']['reused']} of {PIN})", + on["B1"]["reused"] == PIN) + check(f"on: every turn prints the reference's tokens ({2 * N} x {max_new})", same_tokens("on", on, ref)) + # a turn after the first continues a kept conversation: the whole earlier prompt + answer minus its last + # token is reused (the state ends one token short of the answer's last one) + full = True + for i in range(2, N + 1): + for x in "AB": + want = on[f"{x}{i}"]["prompt_len"] - len(P[f"turn{x}{i - 1}"]) - 1 + got = on[f"{x}{i}"]["reused"] + if got != want: + full = False + print(f" {x}{i}: reused {got}, expected {want}", flush=True) + check("on: every later turn reuses its whole earlier conversation", full) + if "old" in sums: + check(f"on: faster to the first token than the old engine ({sums['on'][1]:.1f} s vs {sums['old'][1]:.1f} s)", + sums["on"][1] < sums["old"][1]) + print(f" wall x{sums['old'][0] / max(sums['on'][0], 1e-9):.2f}, first token x" + f"{sums['old'][1] / max(sums['on'][1], 1e-9):.2f} against the old engine", flush=True) + + if "restart" in steps: + bins = [f for f in os.listdir(dir_on) if f.startswith("slot-") and f.endswith(".bin")] if os.path.isdir(dir_on) else [] + check(f"restart: the folder holds both agents' conversations ({len(bins)} .bin)", len(bins) == 2) + print("restart: each agent's next turn, a new process on the folder", flush=True) + rs, notes2, _ = run(a_.exe, a_.pack, engine_args, dir_on, True, + [(f"{x}{N + 1}", build_steps(ref, N + 1, N + 1, x)[0][1]) for x in "AB"], max_new, + pin=PIN) + for x in "AB": + r = rs[f"{x}{N + 1}"] + print(f" {x}{N + 1}: prompt {r['prompt_len']:>6} first token {r['ttft_ms'] / 1000:6.2f} s reused {r['reused']:>6}", + flush=True) + want = r["prompt_len"] - len(P[f"turn{x}{N}"]) - 1 + check(f"restart: {x}{N + 1} reuses its whole conversation ({r['reused']} of {want})", r["reused"] == want) + check(f"restart: {x}{N + 1} prints the reference's tokens", r["tokens"] == ref[f"{x}{N + 1}"]["tokens"]) + + if "cap" in steps: + # three conversations (A, B and an unrelated C) cannot fit under A+B's bytes: the least recently used goes + ca = os.path.join(tmp, "cap") + seen = {} + if os.path.isdir(dir_on): + for fn in os.listdir(dir_on): + if fn.endswith(".bin"): + seen[fn] = os.path.getsize(os.path.join(dir_on, fn)) + if len(seen) == 2: + cap_gb = sum(seen.values()) / 2**30 * 1.02 + c_prompt = P["taskB"] + P["taskA"] + P["sys"][:2000] + print(f"cap: A, B, C into a folder capped at {cap_gb:.3f} GB (the bytes of A and B)", flush=True) + run(a_.exe, a_.pack, engine_args, ca, True, + [("A1", build_steps(ref, 1)[0][1]), ("B1", build_steps(ref, 1)[1][1]), + ("C1", lambda _: c_prompt)], max_new, pin=PIN, slot_gb=cap_gb) + total = sum(os.path.getsize(os.path.join(ca, f)) for f in os.listdir(ca) if f.endswith(".bin")) + held = [] + a_start, b_start = P["sys"] + P["taskA"], P["sys"] + P["taskB"] + for fn in sorted(os.listdir(ca)): + if fn.endswith(".meta"): + mt = meta_tokens(os.path.join(ca, fn)) + if mt: + t = mt[0] + held.append("C" if t[:len(c_prompt)] == c_prompt else "A" if t[:len(a_start)] == a_start + else "B" if t[:len(b_start)] == b_start else "?") + print(f" the folder holds {sorted(held)} ({total / 2**20:.1f} MiB of {cap_gb * 1024:.1f} MiB)", flush=True) + check("cap: the folder stays under its cap", total <= cap_gb * 2**30) + check("cap: the newest conversation (C) is kept", "C" in held) + check("cap: the least recently used (A) is gone", "A" not in held) + else: + print(" (no two conversations in the loop's folder: the cap check needs the on step)", flush=True) + except (RuntimeError, OSError) as e: + print(f"FAIL: {e}", flush=True) + ok = False + finally: + if not a_.keep_dir: + shutil.rmtree(tmp, ignore_errors=True) + if sums: + print("summary (wall s, sum of first-token s): " + " ".join(f"{k} {v[0]:.1f}/{v[1]:.1f}" for k, v in sums.items()), + flush=True) + print("PASS: the kept conversations read on from their state" if ok else "FAIL", flush=True) + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) From 736a4136e1db54c32b3e2516c28c765b93180105 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:09:06 +0200 Subject: [PATCH 14/34] serve: DeepSeek-V4.1 engine gets the slot switch and a slot folder in Strata's data folder (other families untouched) --- serve/server.py | 17 +++++++++++++++++ serve/test_dsv41.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/serve/server.py b/serve/server.py index 8141108d..55a37196 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3477,6 +3477,21 @@ def hip_auto_devices(cfg: dict, env: dict) -> list[int] | None: return visible +DS41_SLOT_KEEP_DEFAULT = "0" # the engine keeps a displaced conversation in RAM and in the slot folder (see below) + + +def deepseek_slot_env(env: dict, cfg: dict) -> None: + """DeepSeek-V4.1 only. The engine sets a conversation aside when another request takes the model and takes it back + at its checkpoints (agents and sub-agents that take turns do not read their prompts again). STRATA_DS4_SLOT_KEEP + switches it (the default above; a config's env or the shell wins); the folder is `ds4-slots` next to the run log, in + Strata's data folder (STRATA_DS4_SLOT_DIR names another), and the engine caps it (STRATA_DS4_SLOT_GB, 16) and + removes what is older than a week or not this model's.""" + env.setdefault("STRATA_DS4_SLOT_KEEP", DS41_SLOT_KEEP_DEFAULT) + log = cfg.get("log") + if "STRATA_DS4_SLOT_DIR" not in env and log: + env["STRATA_DS4_SLOT_DIR"] = str(Path(log).parent / "ds4-slots") + + def child_env(cfg: dict, *, offline: bool = False) -> dict: """The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that compiled it) first on the library search path.""" @@ -3491,6 +3506,8 @@ def child_env(cfg: dict, *, offline: bool = False) -> dict: env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in ordered_gpus(cfg)) for k, v in (cfg.get("env") or {}).items(): # engine settings the config carries (AMD: the GEMM tuning table) env[str(k)] = str(v) + if (cfg.get("arch") or "") == "deepseek41": # (only this engine reads these; Qwen's environment is untouched) + deepseek_slot_env(env, cfg) # Strict offline reaches children through the environment, because a tool subprocess or a model # loader is code this server does not own. Applied last so a profile's own `env` cannot remove # the policy by naming the same variable. diff --git a/serve/test_dsv41.py b/serve/test_dsv41.py index a4c13bcd..b928e816 100644 --- a/serve/test_dsv41.py +++ b/serve/test_dsv41.py @@ -20,7 +20,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "tools")) import strata_tokenizer as ST # noqa: E402 -from serve import frontend # noqa: E402 +from serve import frontend, server # noqa: E402 from serve.dsml import DsmlOutputParser, DsmlTranslator, to_dsml_force # noqa: E402 from serve.frontend import ChatTemplate, OutputParser, openai_to_messages # noqa: E402 from serve.server import (FAMILY_MODEL_NAMES, MockEngine, Service, default_model_name, model_card_sampling, # noqa: E402 @@ -575,6 +575,36 @@ class Api(unittest.TestCase): self.assertEqual(req, {}) +class SlotEnv(unittest.TestCase): + """The engine's kept conversations: the folder and the switch reach the DeepSeek engine only.""" + + KEYS = ("STRATA_DS4_SLOT_KEEP", "STRATA_DS4_SLOT_DIR") + + def env(self, cfg): + saved = {k: os.environ.pop(k, None) for k in self.KEYS} + try: + return server.child_env(cfg) + finally: + for k, v in saved.items(): + if v is not None: + os.environ[k] = v + + def test_deepseek_gets_a_folder_in_the_data_folder_and_the_default_switch(self): + env = self.env({"arch": "deepseek41", "log": str(Path("data") / "strata-deepseek.log"), "args": []}) + self.assertEqual(Path(env["STRATA_DS4_SLOT_DIR"]), Path("data") / "ds4-slots") + self.assertEqual(env["STRATA_DS4_SLOT_KEEP"], server.DS41_SLOT_KEEP_DEFAULT) + + def test_the_configs_own_settings_win(self): + env = self.env({"arch": "deepseek41", "log": "x/y.log", + "env": {"STRATA_DS4_SLOT_KEEP": "1", "STRATA_DS4_SLOT_DIR": "elsewhere"}}) + self.assertEqual((env["STRATA_DS4_SLOT_KEEP"], env["STRATA_DS4_SLOT_DIR"]), ("1", "elsewhere")) + + def test_other_families_get_nothing(self): + for arch in ("qwen4exp", None, "gyro"): + env = self.env({"arch": arch, "log": "x/y.log"} if arch else {"log": "x/y.log"}) + self.assertFalse([k for k in env if k.startswith("STRATA_DS4_")], arch) + + class PickTemplateTests(unittest.TestCase): """A pack made from another GGUF can ship the V4-Flash template (`tool_calls`, no space): the V4.1 model then writes malformed calls (P2003 install test). The server swaps in the V4.1 template for such a pack.""" From be26cb79957eb4e4377531a602d7edf70f02a71c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:10:21 +0200 Subject: [PATCH 15/34] DeepSeek-V4.1: slots on by default (2 GB cap, one week), docs --- docs/DEEPSEEK41.md | 5 +++++ serve/server.py | 8 +++++--- serve/test_dsv41.py | 3 ++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 32bd2a22..7aefeec4 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -70,6 +70,11 @@ The server speaks to the engine as it does for the other models, so `/v1/chat/co server turns them into OpenAI `tool_calls` and Anthropic `tool_use`, including `tool_choice`, streamed arguments and calls written inside the thinking. A value marked `string="true"` stays a string. - Defaults when a request names none: temperature 1.0, top_p 1.0. +- Agents and sub-agents that take turns do not read their prompts again. When another request takes the model, the engine sets the + conversation aside (about 17 MB per 6.5K tokens) and takes it back when the next prompt continues it; the system prompt and tools shared by + an agent and its sub-agents are kept as a checkpoint too. Slots survive a restart, live in `ds4-slots` next to the run log, are capped at + 2 GB and are removed after a week. `STRATA_DS4_SLOT_KEEP=0` turns it off, `STRATA_DS4_SLOT_GB` changes the cap, `STRATA_DS4_AUTO_PIN=0` + turns off the shared-start checkpoint. The answers are the same as a fresh read of the prompt. Pictures and the DSpark drafter are in the engine (strata-dsv41 reads them from the unsloth mmproj and dspark files beside the model; the server side is not wired yet). Not in this version: several requests at once (`--parallel` is ignored with a note), tuning (`--tune` is skipped with a note). diff --git a/serve/server.py b/serve/server.py index 55a37196..fdfd5949 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3477,16 +3477,18 @@ def hip_auto_devices(cfg: dict, env: dict) -> list[int] | None: return visible -DS41_SLOT_KEEP_DEFAULT = "0" # the engine keeps a displaced conversation in RAM and in the slot folder (see below) +DS41_SLOT_KEEP_DEFAULT = "1" # the engine keeps a displaced conversation in RAM and in the slot folder (see below) +DS41_SLOT_GB_DEFAULT = "2" # the folder's cap in GB (a 6.5K-token conversation is about 17 MB) def deepseek_slot_env(env: dict, cfg: dict) -> None: """DeepSeek-V4.1 only. The engine sets a conversation aside when another request takes the model and takes it back at its checkpoints (agents and sub-agents that take turns do not read their prompts again). STRATA_DS4_SLOT_KEEP switches it (the default above; a config's env or the shell wins); the folder is `ds4-slots` next to the run log, in - Strata's data folder (STRATA_DS4_SLOT_DIR names another), and the engine caps it (STRATA_DS4_SLOT_GB, 16) and - removes what is older than a week or not this model's.""" + Strata's data folder (STRATA_DS4_SLOT_DIR names another), and the engine caps it (STRATA_DS4_SLOT_GB, 2 here, 16 in the engine) and + removes what is older than a week or not this model's. On by default; STRATA_DS4_SLOT_KEEP=0 turns it off.""" env.setdefault("STRATA_DS4_SLOT_KEEP", DS41_SLOT_KEEP_DEFAULT) + env.setdefault("STRATA_DS4_SLOT_GB", DS41_SLOT_GB_DEFAULT) log = cfg.get("log") if "STRATA_DS4_SLOT_DIR" not in env and log: env["STRATA_DS4_SLOT_DIR"] = str(Path(log).parent / "ds4-slots") diff --git a/serve/test_dsv41.py b/serve/test_dsv41.py index b928e816..15315ee5 100644 --- a/serve/test_dsv41.py +++ b/serve/test_dsv41.py @@ -592,7 +592,8 @@ class SlotEnv(unittest.TestCase): def test_deepseek_gets_a_folder_in_the_data_folder_and_the_default_switch(self): env = self.env({"arch": "deepseek41", "log": str(Path("data") / "strata-deepseek.log"), "args": []}) self.assertEqual(Path(env["STRATA_DS4_SLOT_DIR"]), Path("data") / "ds4-slots") - self.assertEqual(env["STRATA_DS4_SLOT_KEEP"], server.DS41_SLOT_KEEP_DEFAULT) + self.assertEqual(env["STRATA_DS4_SLOT_KEEP"], "1") + self.assertEqual(env["STRATA_DS4_SLOT_GB"], "2") def test_the_configs_own_settings_win(self): env = self.env({"arch": "deepseek41", "log": "x/y.log", From 8a7102ec4da82da31eb831f7b5db1711fa41eb39 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:11:15 +0200 Subject: [PATCH 16/34] dsv41: a long prompt skips layers 20-39 on all but its last 2,668 rows (STRATA_DS4_PROMPT_SKIP, on by default) Layers 20-39 of DeepSeek-V4.1-Flash read a prompt's earlier tokens only through layer 20's compressed KV and index keys, and each looks back one 128-token window more than the layer before. So for the answer and for the rings the decode reads they need their own work only on the last (40 - 20) x 127 + 128 = 2,668 rows. A prompt of ~3,700 or more new tokens on one GPU now runs its earlier chunks through layers 0-19 plus layer 20's kv_only part (the hyper-connection pre-norm, the compressor latent, the index keys, the compressed KV) and nothing of the later layers' attention or experts; the chunk the cut falls in runs layers 20-39 from the cut row on; later chunks run every layer. The expert flow plans nothing for the skipped (chunk, layer)s. STRATA_DS4_PROMPT_SKIP: 1 (default) the skip, 2 only the last 128 rows (DeepSeek's own serving; answers shift a little), 0 off. Same approach as Maya #318. H100 emulation (64 GB cgroup, 12 GiB VRAM, store 41 GB, 3.6 GB/s SSD cap): 16K prompt 69.3 s -> 51.5 s (236 -> 318 tok/s, two alternating pairs), 4K 32.5 s -> 30.7 s; 800 teacher-forced positions after a 4,200-token skipped prompt: KL 0.00029 against the full work, top-1 against the text 88.11% against 87.98%, ppl 1.5110 against 1.5111. --score gets DS4_SCORE_PREFIX=N (the segments joined, the first N tokens read as one prompt with the last row's logits, the rest scored) so the skip can be scored; tools/dsv41/test_prompt_skip.py runs it against a pack when one is named. The Maya notice file now says later Maya changes are covered by the same notice. --- src/dsv41/ds4_main.cpp | 20 +++- src/dsv41/ds4_model.cu | 183 +++++++++++++++++++++++------ third_party/project-maya/NOTICE.md | 4 + tools/dsv41/test_prompt_skip.py | 56 +++++++++ 4 files changed, 225 insertions(+), 38 deletions(-) create mode 100644 tools/dsv41/test_prompt_skip.py diff --git a/src/dsv41/ds4_main.cpp b/src/dsv41/ds4_main.cpp index e614e6cb..fb4c1824 100644 --- a/src/dsv41/ds4_main.cpp +++ b/src/dsv41/ds4_main.cpp @@ -583,6 +583,16 @@ int score(strata::ds4::Model& m, const std::string& ids_path, const std::string& std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str()); return 1; } + // DS4_SCORE_PREFIX=N (a test of the long-prompt layer skip): the segments are joined into one stream, its first N + // tokens are read as one prompt (logits of the last row only: the path a long prompt takes, where the skip applies) + // and only the positions after them are scored, in windows + const long long prefix_n = std::getenv("DS4_SCORE_PREFIX") ? std::atoll(std::getenv("DS4_SCORE_PREFIX")) : 0; + if (prefix_n > 0 && segs.size() > 1) { + ScoreSeg all; + all.name = "concat"; + for (const ScoreSeg& sg : segs) all.ids.insert(all.ids.end(), sg.ids.begin(), sg.ids.end()); + segs.assign(1, all); + } std::FILE* out = std::fopen(out_path.c_str(), "wb"); std::FILE* sj = std::fopen((out_path + ".seg.json").c_str(), "wb"); if (out == nullptr || sj == nullptr) { @@ -601,7 +611,15 @@ int score(strata::ds4::Model& m, const std::string& ids_path, const std::string& const long long first = line; double sum_nll = 0.0; long long top1 = 0, cnt = 0; - for (size_t a = 0; a + 1 < ids.size();) { + size_t a0 = 0; + if (prefix_n > 0 && (size_t) prefix_n + 1 < ids.size()) { + a0 = (size_t) prefix_n; + if (!m.feed(ids.data(), (int) a0, 1, err)) { + std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str()); + return 1; + } + } + for (size_t a = a0; a + 1 < ids.size();) { const int T = (int) std::min((size_t) window, ids.size() - 1 - a); // (positions a .. a+T-1 are scored) if (!m.feed(ids.data() + a, T, T, err) || !m.logits(lg) || lg.size() < (size_t) T * (size_t) V) { std::fprintf(stderr, "strata-dsv41: %s\n", err.empty() ? "no logits" : err.c_str()); diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index a9e37044..bc29b69d 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -583,6 +583,7 @@ struct Chunk { int spec_k = -1, spec_il = -1, n_spec = 0; // the likely items queued last: (chunk, layer), how many, from where size_t spec_begin = 0; std::vector fl_layers, fl_T; // the device's trunk layers in order; the run's chunk sizes + int fl_yoco = -1, fl_cut_k = 0, fl_cut_r = 0; // Run::yoco / cut_k / cut_r: what a layer's chunk streams for int bc_n = 0, bc_w = 0; // a batch's compacted bounds: bc_n regions of bc_w, by batch count int *bc_pin = nullptr, *bc_dev = nullptr; uint64_t n_batch = 0; @@ -813,6 +814,7 @@ struct Model::Impl { std::vector> chunks; // per device size_t eg_cap = kWin; // tokens h_eg holds int tap_cap = kWin; // rows h_taps holds (a chunk seeds the drafter with its last 128) + static constexpr int kYocoMin = 1024; // a long prompt's skip (forward_chunks): the fewest rows worth skipping bool logits_all = false; // the last feed was a chunk with logits for every row (chunk_logits) std::vector chunk_logits; std::function progress; // a run of chunks: the tokens done so far (the main thread, while it waits) @@ -3203,8 +3205,22 @@ struct Model::Impl { if (v >= l.n_slots + c.n_spec && b[(size_t) v + 1] > b[(size_t) v]) flow_push(c, l, mi, k, e, v); } } - // the next (chunk, layer) of the device after (k, il) in the run's order (false: none) + // the next (chunk, layer) of the device after (k, il) in the run's order that streams experts (false: none) - a + // long prompt's skip leaves out its early chunks' layers from Run::yoco on (kv_only there: no experts) bool flow_next(const Chunk& c, int k, int il, int& k2, int& il2) const { + while (flow_next1(c, k, il, k2, il2)) { + if (c.fl_yoco < 0 || k2 >= c.fl_cut_k || il2 < c.fl_yoco) return true; + k = k2; + il = il2; + } + return false; + } + // the rows chunk k runs layer il on (a long prompt's skip: the cut chunk's from cut_r on, from the yoco layer on) + static int fl_rows(const Chunk& c, int k, int il) { + const int T = c.fl_T[(size_t) k]; + return c.fl_yoco >= 0 && k == c.fl_cut_k && il >= c.fl_yoco ? T - c.fl_cut_r : T; + } + bool flow_next1(const Chunk& c, int k, int il, int& k2, int& il2) const { const auto it = std::find(c.fl_layers.begin(), c.fl_layers.end(), il); const size_t i = (size_t) (it - c.fl_layers.begin()); if (c.lm) { // (layer-major: the layer's next chunk, then the next layer's first) @@ -3345,7 +3361,7 @@ struct Model::Impl { flow_rest(c, k, L0.il, b); const size_t lb = c.spec_begin, le = c.base + c.items.size(), n_lay = le - lb; int k2 = 0, il2 = 0; - if (flow_next(c, k, L0.il, k2, il2)) flow_spec(c, k2, il2, c.fl_T[(size_t) k2]); + if (flow_next(c, k, L0.il, k2, il2)) flow_spec(c, k2, il2, fl_rows(c, k2, il2)); const size_t R = (size_t) c.ring_n, bmax = std::max(1, R / 2); int v_done = 0; while (c.n_comp < le) { @@ -6219,8 +6235,10 @@ struct Model::Impl { // layer L0 for a chunk of T tokens at p0 as group member mi: layer()'s arithmetic over the chunk's rows (the // projections as GEMMs, the attention and the indexer in slabs, the routed experts as sorted rows: the VRAM ones in - // place, the CPU lane's streamed in batches) - bool layer_chunk(Layer& L0, int mi, int64_t p0, int T, const WinPlan& wp, Streamer& S, std::string& err) { + // place, the CPU lane's streamed in batches). kv_only (a long prompt's first pass, Run::stop): only what the layers + // after it read of these rows - its compressed KV and index keys - and nothing of its own attention or experts + bool layer_chunk(Layer& L0, int mi, int64_t p0, int T, const WinPlan& wp, Streamer& S, std::string& err, + bool kv_only = false) { Layer& l = member(L0, mi); Dev& d = devs[(size_t) l.dev]; Chunk& c = *chunks[(size_t) l.dev]; @@ -6252,35 +6270,37 @@ struct Model::Impl { hc_split(c.mix, l.hca_scale, l.hca_base, H, g.sinkhorn, g.hc_eps, T, c.a_pre, c.a_post, c.a_comb, s); hc_pre_norm(c.h, c.pre, l.attn_norm, D, H, T, g.eps, c.x, s); x3::rows_f16(c.x, D, nullptr, T, D, c.x16, s); - if (!gemm(d, c, l.wq_a, c.x16, D, T, c.qr, g.q_lora, 0.0f, err) || - !gemm(d, c, l.wkv, c.x16, D, T, c.kvr, HD, 0.0f, err)) + if (!kv_only && (!gemm(d, c, l.wq_a, c.x16, D, T, c.qr, g.q_lora, 0.0f, err) || + !gemm(d, c, l.wkv, c.x16, D, T, c.kvr, HD, 0.0f, err))) return false; if (l.kv_src && !gemm(d, c, l.c_wkv, c.x16, D, T, c.ckr, HD, 0.0f, err)) return false; if (l.kv_src && l.ratio > 1 && !gemm(d, c, l.c_wgate, c.x16, D, T, c.cgr, HD, 0.0f, err)) return false; - Finish fq; - fq.w = l.q_norm; - fq.eps = g.eps; - finish(c.qr, T, g.q_lora, g.q_lora, fq, s); - x3::rows_f16(c.qr, g.q_lora, nullptr, T, g.q_lora, c.qr16, s); - // the window rows: the ring's (positions p0 - win ..) then the chunk's - ring_to_ext(l.win, c.ext, p0, g.win, HD, s); - Finish fk; - fk.w = l.kv_norm; - fk.eps = g.eps; - fk.rd = g.rd; - fk.pos = (int) p0; - fk.freqs = freqs; - fk.quant = 1; - fk.dst = c.ext + (size_t) g.win * HD; - fk.dst_stride = HD; - finish(c.kvr, T, HD, HD, fk, s); - // feed_mark's checkpoint: the ring as it was before row snap_t - the old ring, then the chunk's rows before it - const bool snap = wp.snap_t >= 0 && mi == 0 && L0.snap_win != nullptr; - if (snap) { - CK(cudaMemcpyAsync(L0.snap_win, l.win, (size_t) g.win * win_rb(), cudaMemcpyDeviceToDevice, s)); - if (wp.snap_t > 0) ext_to_ring(c.ext, L0.snap_win, p0, g.win, wp.snap_t, HD, s, nullptr); + const bool snap = !kv_only && wp.snap_t >= 0 && mi == 0 && L0.snap_win != nullptr; + if (!kv_only) { + Finish fq; + fq.w = l.q_norm; + fq.eps = g.eps; + finish(c.qr, T, g.q_lora, g.q_lora, fq, s); + x3::rows_f16(c.qr, g.q_lora, nullptr, T, g.q_lora, c.qr16, s); + // the window rows: the ring's (positions p0 - win ..) then the chunk's + ring_to_ext(l.win, c.ext, p0, g.win, HD, s); + Finish fk; + fk.w = l.kv_norm; + fk.eps = g.eps; + fk.rd = g.rd; + fk.pos = (int) p0; + fk.freqs = freqs; + fk.quant = 1; + fk.dst = c.ext + (size_t) g.win * HD; + fk.dst_stride = HD; + finish(c.kvr, T, HD, HD, fk, s); + // feed_mark's checkpoint: the ring as it was before row snap_t - the old ring, then the chunk's rows before it + if (snap) { + CK(cudaMemcpyAsync(L0.snap_win, l.win, (size_t) g.win * win_rb(), cudaMemcpyDeviceToDevice, s)); + if (wp.snap_t > 0) ext_to_ring(c.ext, L0.snap_win, p0, g.win, wp.snap_t, HD, s, nullptr); + } + ext_to_ring(c.ext, l.win, p0, g.win, T, HD, s, nullptr); } - ext_to_ring(c.ext, l.win, p0, g.win, T, HD, s, nullptr); const uint8_t* ckv = nullptr; const long long ss = (long long) o.max_context + 64; if (l.ratio > 0) { @@ -6328,7 +6348,7 @@ struct Model::Impl { fi.pdst_stride = (long long) ik_rb(); finish(c.ikr, ng, g.ix_hd, g.ix_hd, fi, s); } - if (clen_max > 0) { + if (clen_max > 0 && !kv_only) { if (!gemm_f16w(c, l.i_wproj, g.ix_heads, D, c.x16, D, T, 1.0f / std::sqrt((float) g.ix_hd) / std::sqrt((float) g.ix_heads), c.iw, 64, err)) return false; @@ -6409,6 +6429,7 @@ struct Model::Impl { } ckv = sr.ckv[(size_t) l.dev]; } + if (kv_only) return true; // the attention in slabs: q, the sparse attention, wo_a, wo_b (this member's share) into acc if (NHL == 0) CK(cudaMemsetAsync(c.acc, 0, (size_t) T * D * sizeof(*c.acc), s)); // (no heads) for (int a0 = 0; a0 < T && NHL > 0; a0 += c.A) { @@ -6629,7 +6650,39 @@ struct Model::Impl { std::vector T; std::vector seq; int64_t snap_pos = -1; // feed_mark: the position whose state before it the layers keep (-1: none) + // a long prompt's skip (forward_chunks): the cut at row cut_r of chunk cut_k - the chunks before it go through + // the layers before `yoco`, that layer as layer_chunk's kv_only and none after it; chunk cut_k's rows before + // cut_r the same, its rows from cut_r on and the chunks after it through every layer (yoco -1: no skip) + int yoco = -1, cut_k = 0, cut_r = 0; + bool runs(int k, int il) const { return yoco < 0 || k >= cut_k || il <= yoco; } + bool kv_only(int k, int il) const { return yoco >= 0 && k < cut_k && il == yoco; } + int r0(int k, int il) const { return yoco >= 0 && k == cut_k && il >= yoco ? cut_r : 0; } // the first row }; + // layer L0 over chunk k per a long prompt's skip (Run): its kv_only, or its rows from Run::r0 on - the chunk's + // buffers seen from that row (the yoco layer: its kv_only over the rows before it first) + bool run_layer(Layer& L0, int mi, int64_t p0, int T, const WinPlan& wp, Streamer& S, std::string& err, + const Run& run, int k, int il) { + if (run.kv_only(k, il)) return layer_chunk(L0, mi, p0, T, wp, S, err, true); + const int r0 = run.r0(k, il); + if (r0 <= 0) return layer_chunk(L0, mi, p0, T, wp, S, err); + if (il == run.yoco) { + WinPlan w0 = wp; + w0.snap_t = -1; + if (!layer_chunk(L0, mi, p0, r0, w0, S, err, true)) return false; + } + Chunk& c = *chunks[(size_t) member(L0, mi).dev]; + float* const h0 = c.h; + float* const pre0 = c.pre; + c.h += (size_t) r0 * g.hc * g.dim; + c.pre += (size_t) r0 * 8; + WinPlan w1 = wp; + w1.snap_t = wp.snap_t >= r0 ? wp.snap_t - r0 : -1; + const bool ok = layer_chunk(L0, mi, p0 + r0, T - r0, w1, S, err); + c.h = h0; + c.pre = pre0; + return ok; + } + // layer-major (c.lm: a run of several chunks, device di every trunk layer, the flow set up by run_dev_chunks): // layer after layer, each through all the chunks in order - a chunk's state to host memory after each of its // layers and back before the next - so a layer's experts are read from the files once for the whole run (the @@ -6647,7 +6700,8 @@ struct Model::Impl { std::vector> egu; // (Engram layer, chunk) for (int il : c.fl_layers) if (L[(size_t) il].eg >= 0) - for (int k = 0; k < nk; ++k) egu.push_back({L[(size_t) il].eg, k}); + for (int k = 0; k < nk; ++k) + if (run.runs(k, il)) egu.push_back({L[(size_t) il].eg, k}); const size_t eg_per = (size_t) (pk.eg_ngram - 1) * pk.eg_heads * (pk.eg_hd + pk.eg_hd / 32); auto read_eg = [this, &c, &run, &egu, eg_per](size_t u) { if (u >= 2) cudaEventSynchronize(c.eg_ev[u % 2]); @@ -6662,6 +6716,7 @@ struct Model::Impl { Layer& L0 = L[(size_t) il]; const bool last_l = li + 1 == c.fl_layers.size(); for (int k = 0; k < nk; ++k) { + if (!run.runs(k, il)) continue; // (a skipped early chunk: nothing after the yoco layer) const int64_t p0 = run.p0[(size_t) k]; const int T = run.T[(size_t) k], slot = k % 2; const bool last_k = k + 1 == nk; @@ -6703,8 +6758,10 @@ struct Model::Impl { (size_t) nr, cudaMemcpyDeviceToHost, s)); } } - if (!layer_chunk(L0, 0, p0, T, wp, S, err)) return false; + const bool kvo = run.kv_only(k, il); + if (!run_layer(L0, 0, p0, T, wp, S, err, run, k, il)) return false; if (dump_l != nullptr) dump_layer(d, c.h, il, p0, T); + if (kvo) continue; // (no layer after it reads this chunk's state) if (!last_l) { // the chunk's state kept for the next layer const Xfer x = chunk_xfer(c.lm_state + (size_t) k * hb, c, T, true); for (int i = 0; i < x.n; ++i) @@ -6756,6 +6813,9 @@ struct Model::Impl { for (int m = 0; m < L[(size_t) il].nm; ++m) if (member(L[(size_t) il], m).dev == di) c.fl_layers.push_back(il); c.fl_T = run.T; + c.fl_yoco = run.yoco; + c.fl_cut_k = run.cut_k; + c.fl_cut_r = run.cut_r; c.spec_k = c.spec_il = -1; c.wait_ms = 0; c.it_file = c.it_ram = c.it_spec = c.it_spec_unused = c.it_lc = 0; @@ -6772,6 +6832,7 @@ struct Model::Impl { } for (int k = 0; k < nk && !c.flow; ++k) for (int il = 0; il < g.nl; ++il) { + if (!run.runs(k, il) || run.kv_only(k, il)) continue; // (a long prompt's skip: no experts there) const Layer& L0 = L[(size_t) il]; bool here = false; for (int m = 0; m < L0.nm; ++m) here = here || member(L0, m).dev == di; @@ -6827,7 +6888,7 @@ struct Model::Impl { wp.snap_t = run.snap_pos >= p0 && run.snap_pos < p0 + T ? (int) (run.snap_pos - p0) : -1; bool started = false; std::vector got(srcs.size(), 0); - for (int il = 0; il < g.nl; ++il) { + for (int il = 0; il < g.nl && run.runs(k, il); ++il) { Layer& L0 = L[(size_t) il]; int mi = -1; for (int m = 0; m < L0.nm; ++m) @@ -6882,7 +6943,7 @@ struct Model::Impl { (size_t) nr, cudaMemcpyDeviceToHost, s)); } } - if (!layer_chunk(L0, mi, p0, T, wp, S, err)) return false; + if (!run_layer(L0, mi, p0, T, wp, S, err, run, k, il)) return false; if (dump_l != nullptr && mi == 0) dump_layer(d, c.h, il, p0, T); const bool last = il + 1 == g.nl || L[(size_t) il + 1].grp != L0.grp; if (last && mi == 0 && il + 1 < g.nl) { // the hand-off, once the next group took the chunk before last @@ -7267,6 +7328,33 @@ struct Model::Impl { } } + // the first layer of a long prompt's second half (forward_chunks' two passes), or -1: the first with compress ratio 1 + // (V4.1: 20), every one after it ratio 1 too and owning no compressed KV or index keys of its own (they read its), + // every trunk layer on one GPU. The settings' MAYA_DS4_PROMPT_SKIP (STRATA_DS4_PROMPT_SKIP; DS4_YOCO for tests): + // 1 (the default) the skip, 2 DeepSeek's own serving's (the last 128 rows only: faster, the answers shift a + // little), 0 off + static int yoco_mode() { + static const int m = [] { + const char* v = std::getenv("DS4_YOCO"); + if (v == nullptr) v = std::getenv("STRATA_DS4_PROMPT_SKIP"); + return v != nullptr ? std::atoi(v) : 1; + }(); + return m; + } + int yoco_layer() const { + if (yoco_mode() == 0 || chunk <= 0 || g.nl < 2 || (int) g.ratios.size() < g.nl) return -1; + int yl = -1; + for (int il = 0; il < g.nl && yl < 0; ++il) + if (g.ratios[(size_t) il] == 1) yl = il; + if (yl <= 0 || !L[(size_t) yl].kv_src) return -1; + for (int il = 0; il < g.nl; ++il) { + const Layer& l = L[(size_t) il]; + if (l.nm != 1 || l.dev != L[0].dev) return -1; + if (il > yl && (g.ratios[(size_t) il] != 1 || l.kv_src)) return -1; + } + return yl; + } + // n tokens at positions pos .. in chunks of equal size (at most `chunk`), pipelined over the groups; the logits of // the last min(logits_rows, 16) rows (logits_rows > 16: a run of one chunk, every row's into chunk_logits) bool forward_chunks(const int* tk, int n, int logits_rows, std::string& err, int snap_slot = -1) { @@ -7280,13 +7368,34 @@ struct Model::Impl { err = "token " + std::to_string(tk[t]) + " out of range"; return false; } + // a long prompt's skip: the layers from yoco_layer() on (V4.1: 20-39) read the earlier positions only through + // that layer's compressed KV and index keys, and each looks back one window (win - 1 positions) more than the + // layer before - so they need their own work only on the last keep = (nl - yoco) (win - 1) + win rows for the + // run's last rows and the rings the decode reads to be what the full work gives (up to the experts' summing + // order). The chunks stay as they are: the ones before the cut go through the layers before yoco and its + // kv_only, the cut's chunk through those over all its rows and through the rest from the cut on (Run::r0, a + // view of its buffers), the chunks after it through every layer - each layer's experts read as without the + // skip. One GPU (DS4_YOCO=1; 0: off); not with every row's logits (tests) + const int yl = logits_rows > kWin ? -1 : yoco_layer(); + // (DS4_YOCO_KEEP=: fewer - DeepSeek's own serving replays the last 128 tokens through those layers + // (DeepInfer's "SWA bounded replay"), which shifts the answers a little; at least one window) + static const int keep_env = std::getenv("DS4_YOCO_KEEP") ? std::atoi(std::getenv("DS4_YOCO_KEEP")) : 0; + const int keep = yl <= 0 ? 0 + : keep_env > 0 ? std::max(keep_env, g.win) + : yoco_mode() == 2 ? g.win : (g.nl - yl) * (g.win - 1) + g.win; + const int a = yl > 0 && n - keep >= kYocoMin ? n - keep : 0; const int nc = (n + chunk - 1) / chunk, per = (n + nc - 1) / nc; Run run; - for (int a = 0; a < n; a += per) { - run.p0.push_back(pos + a); - run.T.push_back(std::min(per, n - a)); + for (int x = 0; x < n; x += per) { + run.p0.push_back(pos + x); + run.T.push_back(std::min(per, n - x)); run.seq.push_back(++win_seq); } + if (a > 0) { + run.yoco = yl; + run.cut_k = a / per; + run.cut_r = a - run.cut_k * per; + } logits_all = logits_rows > kWin; if (logits_all) chunk_logits.resize((size_t) n * g.vocab); for (int t = 0; t < n; ++t) { diff --git a/third_party/project-maya/NOTICE.md b/third_party/project-maya/NOTICE.md index 0b3bf289..40c6ddb8 100644 --- a/third_party/project-maya/NOTICE.md +++ b/third_party/project-maya/NOTICE.md @@ -9,3 +9,7 @@ MIT License, the full text is in `LICENSE` beside this file. The notice stays wi Changes made while porting into Strata are listed in the git history of the `src/dsv41` directory (the first commit of each file is the unmodified upstream copy). + +Later changes taken from Project Maya releases v1.1.18 to v1.1.26 (the same approach re-written onto Strata's engine, +for example the long-prompt layer skip, the thinking budget, conversation slots) are covered by the same copyright +and permission notice, in `LICENSE` beside this file. diff --git a/tools/dsv41/test_prompt_skip.py b/tools/dsv41/test_prompt_skip.py new file mode 100644 index 00000000..719c9c07 --- /dev/null +++ b/tools/dsv41/test_prompt_skip.py @@ -0,0 +1,56 @@ +"""The long-prompt layer skip (STRATA_DS4_PROMPT_SKIP=1) against the full work: same answers within noise. + +Needs a GPU, a DeepSeek-V4.1 pack and the golden ids file, so it runs only when they are named: + + STRATA_DSV41_BIN=.../strata-dsv41 STRATA_DSV41_PACK=/data/pack2.00 STRATA_DSV41_IDS=.../logpos.ids.json \ + python -m unittest tools.dsv41.test_prompt_skip + +The golden segments are joined, the first DS4_SCORE_PREFIX tokens (4200) are read as one prompt (the path a long prompt +takes: logits of the last row only, where the skip applies), and the positions after them are scored teacher-forced. +The skip changes only what the layers 20-39 compute for the prompt's early rows, so the scored rows' KL against the +full work must stay at the noise of the experts' summing order. +""" +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +import quant_quality # noqa: E402 + +BIN = os.environ.get("STRATA_DSV41_BIN") +PACK = os.environ.get("STRATA_DSV41_PACK") +IDS = os.environ.get("STRATA_DSV41_IDS") + + +def keep_rows(nl=40, yoco=20, win=128): + """The rows a long prompt keeps on layers yoco.. (the engine's forward_chunks): each layer looks back one window + more than the layer before, so the last (nl - yoco) * (win - 1) + win rows.""" + return (nl - yoco) * (win - 1) + win + + +class PromptSkip(unittest.TestCase): + def test_keep_rows_is_the_chain_of_windows(self): + self.assertEqual(keep_rows(), 2668) + + @unittest.skipUnless(BIN and PACK and IDS, "needs STRATA_DSV41_BIN / _PACK / _IDS") + def test_scored_rows_after_a_skipped_prompt_match_the_full_work(self): + with tempfile.TemporaryDirectory() as tmp: + outs = {} + for mode in ("0", "1"): + out = pathlib.Path(tmp) / f"skip{mode}.tsv" + env = dict(os.environ, STRATA_DS4_PROMPT_SKIP=mode, DS4_SCORE_PREFIX="4200", DS4_CHUNK="1024") + subprocess.run([BIN, "--pack", PACK, "--tp", "1", "--threads", "off", "--max-context", "6144", "--vision", + "off", "--dspark", "off", "--expert-profile", "none", "--window", "128", "--score", IDS, + "--score-out", str(out)], check=True, env=env) + outs[mode] = quant_quality.read_run(str(out)) + res = quant_quality.compare(outs["0"], outs["1"])["all"] + self.assertGreater(res["positions"], 500) + self.assertLess(res["kl"], 0.002) + self.assertGreaterEqual(res["top1"], 0.99) + + +if __name__ == "__main__": + unittest.main() From b4418e30dfa6cfb8a0f14093310d03ac8f32d183 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:11:25 +0200 Subject: [PATCH 17/34] serve: DeepSeek-V4.1 with a short max_tokens (48-1023) caps the thinking at half of it, so a text block always arrives /v1/messages and /v1/chat/completions with max_tokens 200-600 and the thinking on spent all of max_tokens on the thinking: the 0.1.45 answer room starts at max_tokens 1024 and a client that gave no budget of its own got no text block. For the deepseek41 family only, with no budget from the client or the config, the thinking is now capped at max_tokens / 2 for max_tokens from 48 up to 1023 (the existing wrap-up, and the answer follow in the other half). A client's own reasoning_budget_tokens / budget_tokens wins, "answer_room": false turns it off, thinking off is unchanged, other families (Qwen) are untouched. Maya #363 closes the thinking in the engine instead; the server's #123 budget already does that for every engine, so only the short-cap gap needed closing. Tests (serve/test_dsv41.py SmallCap, fake engine that thinks without end): max_tokens 200, 400 and 600 on both APIs return a non-empty text block with the thinking wrapped up at half; thinking off answers directly; a client budget wins; a tool call under a short cap still parses; another family keeps the old behaviour. serve suite: 1025 tests OK (15 skipped). --- serve/server.py | 11 ++++- serve/test_dsv41.py | 110 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 117 insertions(+), 4 deletions(-) diff --git a/serve/server.py b/serve/server.py index 19e03a2b..920cd35b 100644 --- a/serve/server.py +++ b/serve/server.py @@ -201,7 +201,8 @@ VISION_START = "<|vision_start|>" # sets it; 0 turns it off. REPEAT_STOP_TOKENS = 256 ANSWER_ROOM_MIN_CAP = 1024 # 0.1.45: from this max_tokens on, thinking without a budget is closed early enough to leave room to answer -ANSWER_RESERVE_MIN = 512 # #984: the tokens kept for the answer when a thinking budget is cut down to fit max_tokens +DS41_SMALL_CAP_MIN = 48 # DeepSeek-V4.1 only: from this max_tokens up to ANSWER_ROOM_MIN_CAP, thinking is capped at half of it +ANSWER_RESERVE_MIN = 512 # #984: the tokens kept for the answer when a thinking budget is cut down to fit max_tokens # #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) # #1053 (opt-in "reasoning_close_retry": true): a reply that ends on its stop token still inside , with no answer # and no call, is continued once with the thinking closed (the same way the budget's wrap-up closes it) @@ -5052,6 +5053,14 @@ class Service: budget = max_new - min(max(ANSWER_RESERVE_MIN, max_new // 4), max_new // 2) if max_new <= 32768: print(f"[strata] thinking limited to {budget} of max_tokens {max_new} so the answer has room " "(\"answer_room\": false in the config turns this off)", flush=True) + if (thinking and not budget and self.answer_room and self.family == "deepseek41" + and max_new and DS41_SMALL_CAP_MIN <= max_new < ANSWER_ROOM_MIN_CAP): + # DeepSeek-V4.1 only: a short max_tokens (/v1/messages and /v1/chat/completions with 200-600) was spent + # entirely on the thinking, so no text block ever arrived. With no budget of the client's own, the thinking + # is capped at half of max_tokens; then the wrap-up, and the answer follow in the other half. + budget = max_new // 2 + print(f"[strata] thinking limited to {budget} of max_tokens {max_new} so the answer has room " + "(\"answer_room\": false in the config turns this off)", flush=True) if budget and max_new and max_new > 0: # #984: a budget at or near max_tokens never fires before the reply is cut off while still thinking, so # it has no answer. Close the thinking early enough to leave room for one. diff --git a/serve/test_dsv41.py b/serve/test_dsv41.py index bc798034..f9f13a85 100644 --- a/serve/test_dsv41.py +++ b/serve/test_dsv41.py @@ -23,7 +23,7 @@ import strata_tokenizer as ST # noqa: E402 from serve import frontend # noqa: E402 from serve.dsml import DsmlOutputParser, DsmlTranslator, to_dsml_force # noqa: E402 from serve.frontend import ChatTemplate, OutputParser, openai_to_messages # noqa: E402 -from serve.server import (FAMILY_MODEL_NAMES, MockEngine, Service, default_model_name, model_card_sampling, # noqa: E402 +from serve.server import (FAMILY_MODEL_NAMES, MockEngine, REASONING_WRAP_UP, Service, default_model_name, model_card_sampling, # noqa: E402 serve) FIX = ROOT / "serve" / "fixtures" / "deepseek41" @@ -296,8 +296,8 @@ class ReadyTimeout(unittest.TestCase): server.apply_ready_timeout({"engine_ready_s": bad}) -class Api(unittest.TestCase): - """Both APIs against a fake engine that replays scripted DeepSeek text.""" +class ApiBase(unittest.TestCase): + """Both APIs against a fake engine that replays scripted DeepSeek text (the helpers; Api has the tests).""" @classmethod def setUpClass(cls): @@ -334,6 +334,8 @@ class Api(unittest.TestCase): body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 400, **extra} return self.post("/v1/chat/completions", body) + +class Api(ApiBase): # -- thinking -------------------------------------------------------------------------------- def test_thinking_by_default(self): self.start("The user greets me.\n\nHello!") @@ -527,6 +529,108 @@ class Api(unittest.TestCase): self.assertEqual(last["decode_tok_s"], 100.0) +class ThinkForever(DsEngine): + """Thinks without end (random letters) until the thinking is closed in the prompt, then answers.""" + + ANSWER = "Four." + + def __init__(self, tok): + super().__init__(tok, "") + self.prompts = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.prompts.append(list(ids)) + self.last_prompt = list(ids) + got = 0 + try: + if self.tok.decode(list(ids[-14:])).endswith("\n\n"): + out = self.tok.encode(self.ANSWER) + [EOS] + else: + import random + rng = random.Random(len(ids)) # (no repeated token: the server's loop guard would end it) + out = self.tok.encode("".join(chr(97 + rng.randrange(26)) for _ in range(max_new))) + for t in out[:max_new]: + if cancel.is_set(): + return + got += 1 + yield t + finally: + self.last = {"generated": got, "prompt_tokens": len(ids), "prompt_ms": 50.0, "decode_ms": got * 10.0, + "finish": "stop"} + + +class SmallCap(ApiBase): + """A short max_tokens (200-600) with the thinking on: it was all spent on the thinking and no text block came. + With no budget of the client's own the thinking is capped at half of max_tokens (this family only).""" + + def start_forever(self): + self.start("") + engine = ThinkForever(self.tok) + self.svc.engine = engine + self.engine = engine + return engine + + def text_of(self, r): + return "".join(c.get("text", "") for c in r["content"] if c["type"] == "text") + + def test_every_short_cap_gets_an_answer_on_both_apis(self): + for cap in (200, 400, 600): + for api in ("anthropic", "openai"): + with self.subTest(cap=cap, api=api): + self.start_forever() + if api == "anthropic": + status, r = self.post("/v1/messages", {"model": "x", "max_tokens": cap, "thinking": {"type": "enabled"}, + "messages": [{"role": "user", "content": "2+2?"}]}) + self.assertEqual(status, 200, r) + self.assertEqual(self.text_of(r), ThinkForever.ANSWER) + self.assertLessEqual(r["usage"]["output_tokens"], cap) + else: + status, r = self.chat(max_tokens=cap) + self.assertEqual(status, 200, r) + self.assertEqual(r["choices"][0]["message"]["content"], ThinkForever.ANSWER) + self.assertLessEqual(r["usage"]["completion_tokens"], cap) + first = self.engine.prompts[0] + self.assertEqual(len(self.engine.prompts), 2) # the thinking was wrapped up, then answered + self.assertEqual(len(self.engine.prompts[1]) - len(first), cap // 2 - 0 + len(self.tok.encode( + REASONING_WRAP_UP, parse_special=True))) + + def test_thinking_off_is_untouched(self): + for cap in (200, 400, 600): + with self.subTest(cap=cap): + self.start("Plain answer.") + status, r = self.chat(max_tokens=cap, reasoning_effort="none") + self.assertEqual(status, 200, r) + self.assertEqual(r["choices"][0]["message"]["content"], "Plain answer.") + status, r = self.post("/v1/messages", {"model": "x", "max_tokens": cap, "thinking": {"type": "disabled"}, + "messages": [{"role": "user", "content": "hi"}]}) + self.assertEqual(self.text_of(r), "Plain answer.") + + def test_a_client_budget_wins(self): + self.start_forever() + status, r = self.chat(max_tokens=600, reasoning_budget_tokens=20) + self.assertEqual(status, 200, r) + self.assertEqual(len(self.engine.prompts[1]) - len(self.engine.prompts[0]), 20 + len(self.tok.encode( + REASONING_WRAP_UP, parse_special=True))) + + def test_a_tool_call_under_a_short_cap_still_parses(self): + for cap in (200, 400, 600): + with self.subTest(cap=cap): + self.start("Need it." + call(("f", [("a", "1", True)]))) + status, r = self.chat(max_tokens=cap, tools=[{"type": "function", "function": { + "name": "f", "description": "f", "parameters": {"type": "object", "properties": {"a": {"type": "string"}}}}}]) + self.assertEqual(status, 200, r) + calls = r["choices"][0]["message"]["tool_calls"] + self.assertEqual(calls[0]["function"]["name"], "f") + self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"a": "1"}) + self.assertEqual(len(self.engine.last_prompt) > 0, True) + + def test_other_families_keep_the_old_behaviour(self): + self.start_forever() + self.svc.set_family(None) + status, r = self.chat(max_tokens=300) + self.assertEqual(len(self.engine.prompts), 1) # no wrap-up: Qwen's serving is as it was + + class PickTemplateTests(unittest.TestCase): """A pack made from another GGUF can ship the V4-Flash template (`tool_calls`, no space): the V4.1 model then writes malformed calls (P2003 install test). The server swaps in the V4.1 template for such a pack.""" From 60d847ba3389e1e282c625bffd6c168dcc299128 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:16:19 +0200 Subject: [PATCH 18/34] launch: a GPU runtime start failure (hsa_exception) says the card was not ready, with a next step; the runtime text stays in the log --- strata_cli/launch/runner.py | 10 +++++++++- tests/terminal/test_round8_fixes.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index b408ff73..abe7e575 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1967,6 +1967,11 @@ def _read_json(path: Path) -> dict | None: #: lines of an engine log that say why it stopped (the last one wins), and a plain next step for the causes we know. Recommend, never force. CAUSE_LINE = re.compile(r"error|exception|failed|cannot|can't|could not|no device|not found|out of memory|unsupported|abort|invalid|missing|" r"no kernel|illegal|denied|refus", re.I) +# The GPU runtime (ROCm) failed while the card was being set up, often right after another engine exited: the runtime's own text +# ("terminate called after throwing an instance of 'rocr::AMD::hsa_exception'") stays in the log, not in the sentence shown. +HSA_START = re.compile(r"hsa_exception|HSA_STATUS_ERROR|hsaKmt", re.I) +HSA_START_NEXT = ("The graphics card was not ready yet; wait a few seconds and run it again. If it keeps happening, restart the PC " + "and report the log.") KNOWN_CAUSES = ( (re.compile(r"no device of requested type|device not found|no (gpu|sycl|level.zero) device|permission denied.*(dri|render)", re.I), "The engine could not open the graphics card. On Linux the account must be allowed to use it: add it to the render group " @@ -2045,10 +2050,13 @@ def explain_engine_exit(result: dict, config: Path | None, marks: dict | None = stage = "The engine stopped while it was loading the model" + (f" (exit code {code})" if code not in (None, 0) else "") else: stage = f"The server did not become ready ({state}: {why or 'see the engine log'})" + hsa = HSA_START.search(" ".join(lines + [str(why or "")])) # the runtime's own text is kept out of the sentence (it is in the log) + if hsa: + cause = "" text = stage + (f": {cause}" if cause else ".") if not text.endswith((".", "!")): text += "." - step = next((words for pattern, words in KNOWN_CAUSES if pattern.search(" ".join([cause, str(why or "")]))), "Run it again; if it repeats, report the log.") + step = HSA_START_NEXT if hsa else next((words for pattern, words in KNOWN_CAUSES if pattern.search(" ".join([cause, str(why or "")]))), "Run it again; if it repeats, report the log.") return text, step + (f" The engine's log: {log}" if log else " The engine's log has the reason (strata logs, or the log named in the run config).") diff --git a/tests/terminal/test_round8_fixes.py b/tests/terminal/test_round8_fixes.py index 1a891483..47ef0276 100644 --- a/tests/terminal/test_round8_fixes.py +++ b/tests/terminal/test_round8_fixes.py @@ -44,6 +44,22 @@ class EngineExitIsExplained(unittest.TestCase): self.assertIn("render group", nxt) self.assertIn(str(log), nxt) + def test_a_gpu_runtime_start_failure_gets_a_plain_sentence_and_keeps_the_runtime_text_out_of_it(self): + cfg, log = self.config_with_log(["strata generate: loading", "terminate called after throwing an instance of 'rocr::AMD::hsa_exception'", + " what(): "]) + text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "engine_exit_code": 134}, cfg) + self.assertIn("stopped while it was loading the model (exit code 134)", text) + self.assertNotIn("hsa_exception", text + nxt) + self.assertNotIn("terminate called", text + nxt) + self.assertIn("graphics card was not ready yet", nxt) + self.assertIn("wait a few seconds", nxt) + self.assertIn("restart the PC", nxt) + self.assertIn(str(log), nxt) + text, nxt = R.explain_engine_exit({"error": "server_exited", "engine_exit_code": 134, + "log_tail": "terminate called after throwing an instance of 'rocr::AMD::hsa_exception' | what():"}, None) + self.assertNotIn("hsa_exception", text) + self.assertIn("graphics card was not ready yet", nxt) + def test_out_of_memory_and_old_engine_get_their_own_next_step(self): cfg, _ = self.config_with_log(["strata generate: CUDA error: out of memory"]) self.assertIn("--context 16k", R.explain_engine_exit({"error": "server_exited"}, cfg)[1]) From fa77717a57bd7f4f4dd5df4a920467e60444c3ac Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:16:46 +0200 Subject: [PATCH 19/34] README: DeepSeek V4.1-Flash (ISTA-DASLab IQ2_XXS / IQ2_XS) in the model list, Terminal only --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 435bcf02..697dcbce 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,17 @@ More choices: Every size, download and what fits where: [docs/MODELS.md](docs/MODELS.md). +### DeepSeek V4.1-Flash (in the Terminal, from 0.2.4) + +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) is a different, much bigger model. ISTA-DASLab made the two sets below. Strata runs them on a PC with one 12 GB graphics card and 46 to 64 GB of RAM, and reads the rest from your SSD. It runs through its own engine package, `strata-dsv41`, which `strata launch` downloads when you pick DeepSeek. The desktop app does not offer it yet. + +| Set | Download | Quality against the original model | Writes at | +| --- | ---: | --- | --- | +| **IQ2_XXS** (2.00 bits) | 257 GB | KL 0.169, perplexity 3.64 (+16%) | 6 to 9 tokens/s on an RTX 3060, about 5 on an RTX 5070 | +| **IQ2_XS** (2.25 bits) | 274 GB | KL 0.110, perplexity 3.40 (+8%); code +3.5%, agent work +2.5% | a little slower than IQ2_XXS | + +Start it with `strata launch --model ist-das-2.00bpw` (or `ist-das-2.25bpw`). Details, speeds per card and the manual install: [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md). + ## How fast is it? Based on a 12 GB graphics card (RTX 5070, Ryzen 5 7600, 64 GB RAM). See results from other cards: From 524ff90e1ad5e03c26fe3350e531c295d801e4cb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:17:00 +0200 Subject: [PATCH 20/34] docs: the final DeepSeek quants (ISTA-DASLab repository) in the release notes and DEEPSEEK41.md --- docs/DEEPSEEK41.md | 2 +- docs/release-notes-0.2.4.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 20ca1138..058abcd2 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -26,7 +26,7 @@ with an out-of-memory message. Both are said before anything is downloaded. ## The official 2-bit versions (the ones for a normal PC) -Setup offers two official sets (helcig/tmp-oct26-2, pinned): **IST-DAS 2.00 bpw** (138 GB) and **IST-DAS 2.25 bpw** (155 GB). Both use the +Setup offers two official sets (ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF, pinned): **IST-DAS 2.00 bpw** (138 GB) and **IST-DAS 2.25 bpw** (155 GB). Both use the same 111 GB n-gram table (downloaded once into `models/deepseek-v4.1-flash-shared`) and the 8 GB DSpark drafter: 257 GB of disk for 2.00, 274 GB for 2.25, 412 GB for both. Quality against the original model: perplexity +16% on 2.00, +8% on 2.25 (code and agent work about +3.5% / +2.5% on 2.25). diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index 8ee4ab63..499a4683 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -6,12 +6,12 @@ Strata now runs DeepSeek V4.1-Flash on a PC with one 12 GB graphics card and 46 ## What you get -- **DeepSeek V4.1-Flash** in the model list of Setup, in two sizes from IST-DAS: +- **DeepSeek V4.1-Flash** in the model list of Setup, in two sizes from [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF): | set | download | quality against the original model | |---|---|---| - | 2.00 bits | 257 GB | perplexity +16%; code and agent text +8.5% and +5.9% | - | 2.25 bits | 274 GB | perplexity +7.7% to +8.3%; code and agent text +3.5% and +2.5% | + | IQ2_XXS (2.00 bits) | 257 GB | perplexity +16%; code and agent text +8.5% and +5.9% | + | IQ2_XS (2.25 bits) | 274 GB | perplexity +7.7% to +8.3%; code and agent text +3.5% and +2.5% | "Perplexity" is how surprised the model is by a fixed set of 4,995 test texts; lower is closer to the original. Pick 2.25 for coding and agent work when you have the disk. Setup shows both sizes and warns if your PC is short of disk or RAM. It does not stop you. - Setup downloads the files, builds the model folder and starts the engine. You set no flags. @@ -76,7 +76,7 @@ Everything from 0.2.3 is attached again, so the release page still holds every f ## Thanks -- **IST-DAS** for the 2.00 and 2.25-bit sets of DeepSeek V4.1-Flash. +- **ISTA-DASLab** for the IQ2_XXS and IQ2_XS sets of DeepSeek V4.1-Flash ([ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF)). - **Unsloth** for the DSpark drafter GGUF. --- From 41e804d93cc58f09cf789e96a62205c9f73ef7e8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:18:16 +0200 Subject: [PATCH 21/34] launch: the hsa_exception sentence ignores hsaKmt lines, and a real cause in the same log (out of memory, no permission on the card) still wins; tests for both --- strata_cli/launch/runner.py | 10 ++++++++-- tests/terminal/test_round8_fixes.py | 12 ++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index abe7e575..c309ea0f 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1969,7 +1969,7 @@ CAUSE_LINE = re.compile(r"error|exception|failed|cannot|can't|could not|no devic r"no kernel|illegal|denied|refus", re.I) # The GPU runtime (ROCm) failed while the card was being set up, often right after another engine exited: the runtime's own text # ("terminate called after throwing an instance of 'rocr::AMD::hsa_exception'") stays in the log, not in the sentence shown. -HSA_START = re.compile(r"hsa_exception|HSA_STATUS_ERROR|hsaKmt", re.I) +HSA_START = re.compile(r"hsa_exception|HSA_STATUS_ERROR", re.I) HSA_START_NEXT = ("The graphics card was not ready yet; wait a few seconds and run it again. If it keeps happening, restart the PC " "and report the log.") KNOWN_CAUSES = ( @@ -2052,7 +2052,13 @@ def explain_engine_exit(result: dict, config: Path | None, marks: dict | None = stage = f"The server did not become ready ({state}: {why or 'see the engine log'})" hsa = HSA_START.search(" ".join(lines + [str(why or "")])) # the runtime's own text is kept out of the sentence (it is in the log) if hsa: - cause = "" + # a real cause in the same log (out of memory, no permission on the card ...) wins: its line is the cause shown + real = next((x for x in reversed(lines) if any(p.search(x) for p, _ in KNOWN_CAUSES)), None) + if real: + hsa = None + cause = re.sub(r"^(\[strata\]\s*)?(\d{4}-\d\d-\d\d[ T][\d:.]+\s*)?", "", real.strip())[:240] + else: + cause = "" text = stage + (f": {cause}" if cause else ".") if not text.endswith((".", "!")): text += "." diff --git a/tests/terminal/test_round8_fixes.py b/tests/terminal/test_round8_fixes.py index 47ef0276..d3e9db47 100644 --- a/tests/terminal/test_round8_fixes.py +++ b/tests/terminal/test_round8_fixes.py @@ -60,6 +60,18 @@ class EngineExitIsExplained(unittest.TestCase): self.assertNotIn("hsa_exception", text) self.assertIn("graphics card was not ready yet", nxt) + def test_a_real_cause_in_the_same_log_wins_over_the_gpu_runtime_start_failure(self): + cfg, log = self.config_with_log(["strata generate: CUDA error: out of memory", + "terminate called after throwing an instance of 'rocr::AMD::hsa_exception'", " what(): "]) + text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "engine_exit_code": 134}, cfg) + self.assertIn("out of memory", text) + self.assertIn("--context 16k", nxt) + self.assertNotIn("graphics card was not ready", nxt) + cfg, _ = self.config_with_log(["Permission denied: /dev/dri/renderD128", "terminate called after throwing an instance of 'rocr::AMD::hsa_exception'"]) + self.assertIn("render group", R.explain_engine_exit({"error": "server_exited", "engine_exit_code": 134}, cfg)[1]) + cfg, _ = self.config_with_log(["hsaKmtOpenKFD ok", "strata generate: CUDA error: out of memory"]) + self.assertNotIn("graphics card was not ready", R.explain_engine_exit({"error": "server_exited"}, cfg)[1]) + def test_out_of_memory_and_old_engine_get_their_own_next_step(self): cfg, _ = self.config_with_log(["strata generate: CUDA error: out of memory"]) self.assertIn("--context 16k", R.explain_engine_exit({"error": "server_exited"}, cfg)[1]) From f51b80c222768fe55ecd30e46623af729aa73b9e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:19:04 +0200 Subject: [PATCH 22/34] README: R9700 numbers in the DeepSeek block (11 tokens/s on one card, 4x about 31, 55 to 69 with DSpark); the same block in the six translated READMEs; release notes: one-card R9700 row --- README.de.md | 13 +++++++++++++ README.es.md | 13 +++++++++++++ README.fr.md | 13 +++++++++++++ README.ja.md | 13 +++++++++++++ README.md | 6 ++++-- README.pt-BR.md | 13 +++++++++++++ README.zh-CN.md | 13 +++++++++++++ docs/release-notes-0.2.4.md | 3 ++- 8 files changed, 84 insertions(+), 3 deletions(-) diff --git a/README.de.md b/README.de.md index d0ef2b7f..3ff89dc5 100644 --- a/README.de.md +++ b/README.de.md @@ -190,6 +190,19 @@ Weitere Auswahl: Alle Größen, Downloads und was wo läuft: [docs/MODELS.md](docs/MODELS.md). +### DeepSeek V4.1-Flash (im Terminal, ab 0.2.4) + +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) ist ein anderes, deutlich größeres Modell. ISTA-DASLab hat die beiden Sets unten gebaut. Strata startet sie auf einem PC mit einer 12-GB-Grafikkarte und 46 bis 64 GB RAM und liest den Rest von der SSD. Es läuft auf NVIDIA-RTX-Karten der Serien 30 bis 50 und auf der Radeon AI PRO R9700. Es nutzt ein eigenes Engine-Paket, `strata-dsv41`, das `strata launch` lädt, wenn du DeepSeek wählst. Die Desktop-App bietet es noch nicht an. + +| Set | Download | Qualität im Vergleich zum Originalmodell | Antwortet mit | +| --- | ---: | --- | --- | +| **IQ2_XXS** (2.00 Bit) | 257 GB | KL 0,169, Perplexität 3,64 (+16 %) | 6 bis 9 Tokens/s auf einer RTX 3060, etwa 5 auf einer RTX 5070 | +| **IQ2_XS** (2.25 Bit) | 274 GB | KL 0,110, Perplexität 3,40 (+8 %); Code +3,5 %, Agent-Aufgaben +2,5 % | etwa 11 Tokens/s auf einer Radeon AI PRO R9700 | + +4x Radeon AI PRO R9700: etwa 31 Tokens/s, 55 bis 69 mit DSpark. + +Starte es mit `strata launch --model ist-das-2.00bpw` (oder `ist-das-2.25bpw`). Details, Geschwindigkeiten je Karte und die manuelle Installation: [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md). + ## Wie schnell ist es? Gemessen mit einer Grafikkarte mit 12 GB (RTX 5070, Ryzen 5 7600, 64 GB RAM). Ergebnisse anderer Karten findest du hier: diff --git a/README.es.md b/README.es.md index 37c134ae..a0f81838 100644 --- a/README.es.md +++ b/README.es.md @@ -190,6 +190,19 @@ Más opciones: Todos los tamaños, descargas y lo que cabe en cada equipo: [docs/MODELS.md](docs/MODELS.md). +### DeepSeek V4.1-Flash (en el Terminal, desde 0.2.4) + +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) es otro modelo, mucho más grande. ISTA-DASLab hizo los dos conjuntos de abajo. Strata los ejecuta en un PC con una tarjeta gráfica de 12 GB y de 46 a 64 GB de RAM, y lee el resto de tu SSD. Funciona en tarjetas NVIDIA RTX de las series 30 a 50 y en la Radeon AI PRO R9700. Usa su propio paquete de motor, `strata-dsv41`, que `strata launch` descarga cuando eliges DeepSeek. La app de escritorio todavía no lo ofrece. + +| Conjunto | Descarga | Calidad frente al modelo original | Responde a | +| --- | ---: | --- | --- | +| **IQ2_XXS** (2.00 bits) | 257 GB | KL 0,169, perplejidad 3,64 (+16 %) | de 6 a 9 tokens/s en una RTX 3060, unos 5 en una RTX 5070 | +| **IQ2_XS** (2.25 bits) | 274 GB | KL 0,110, perplejidad 3,40 (+8 %); código +3,5 %, tareas de agente +2,5 % | unos 11 tokens/s en una Radeon AI PRO R9700 | + +4x Radeon AI PRO R9700: unos 31 tokens/s, de 55 a 69 con DSpark. + +Inícialo con `strata launch --model ist-das-2.00bpw` (o `ist-das-2.25bpw`). Detalles, velocidades por tarjeta e instalación manual: [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md). + ## ¿Qué velocidad tiene? Medido con una tarjeta gráfica de 12 GB (RTX 5070, Ryzen 5 7600, 64 GB de RAM). Resultados con otras tarjetas: diff --git a/README.fr.md b/README.fr.md index 7c74b635..8fbfb4f0 100644 --- a/README.fr.md +++ b/README.fr.md @@ -191,6 +191,19 @@ Autres choix : Toutes les tailles, les téléchargements et ce qui tient où : [docs/MODELS.md](docs/MODELS.md). +### DeepSeek V4.1-Flash (dans le Terminal, depuis 0.2.4) + +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) est un autre modèle, beaucoup plus gros. ISTA-DASLab a produit les deux versions ci-dessous. Strata les fait tourner sur un PC avec une carte graphique de 12 Go et de 46 à 64 Go de RAM, et lit le reste sur votre SSD. Il fonctionne sur les cartes NVIDIA RTX des séries 30 à 50 et sur la Radeon AI PRO R9700. Il utilise son propre paquet de moteur, `strata-dsv41`, que `strata launch` télécharge quand vous choisissez DeepSeek. L’application de bureau ne le propose pas encore. + +| Version | Téléchargement | Qualité par rapport au modèle d’origine | Écrit à | +| --- | ---: | --- | --- | +| **IQ2_XXS** (2.00 bits) | 257 GB | KL 0,169, perplexité 3,64 (+16 %) | 6 à 9 tokens/s sur une RTX 3060, environ 5 sur une RTX 5070 | +| **IQ2_XS** (2.25 bits) | 274 GB | KL 0,110, perplexité 3,40 (+8 %) ; code +3,5 %, tâches d’agent +2,5 % | environ 11 tokens/s sur une Radeon AI PRO R9700 | + +4x Radeon AI PRO R9700 : environ 31 tokens/s, 55 à 69 avec DSpark. + +Lancez-le avec `strata launch --model ist-das-2.00bpw` (ou `ist-das-2.25bpw`). Détails, vitesses par carte et installation manuelle : [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md). + ## Quelle est sa vitesse ? Mesuré avec une carte graphique de 12 Go (RTX 5070, Ryzen 5 7600, 64 Go de RAM). Voir les résultats d'autres cartes : diff --git a/README.ja.md b/README.ja.md index b0c9c589..9a6a2c20 100644 --- a/README.ja.md +++ b/README.ja.md @@ -183,6 +183,19 @@ Gyro は NVIDIA と AMD のカード(AMD は実験的)、および Linux 上 すべてのサイズ、ダウンロード、どの構成で何が動くかは [docs/MODELS.md](docs/MODELS.md) にあります。 +### DeepSeek V4.1-Flash(ターミナル版、0.2.4 から) + +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) は、これとは別のずっと大きなモデルです。下の 2 つのセットは ISTA-DASLab が作りました。Strata は、12 GB のグラフィックスカード 1 枚と 46 から 64 GB の RAM を持つ PC でこれを動かし、残りは SSD から読みます。NVIDIA RTX 30 から 50 シリーズのカードと Radeon AI PRO R9700 で動きます。専用のエンジンパッケージ `strata-dsv41` を使い、DeepSeek を選ぶと `strata launch` がダウンロードします。デスクトップアプリはまだ対応していません。 + +| セット | ダウンロード | 元のモデルとの品質差 | 出力速度 | +| --- | ---: | --- | --- | +| **IQ2_XXS** (2.00 ビット) | 257 GB | KL 0.169、パープレキシティ 3.64(+16%) | RTX 3060 で毎秒 6 から 9 トークン、RTX 5070 で約 5 | +| **IQ2_XS** (2.25 ビット) | 274 GB | KL 0.110、パープレキシティ 3.40(+8%)、コード +3.5%、エージェント作業 +2.5% | Radeon AI PRO R9700 1 枚で毎秒約 11 トークン | + +Radeon AI PRO R9700 4 枚:毎秒約 31 トークン、DSpark ありで 55 から 69。 + +`strata launch --model ist-das-2.00bpw`(または `ist-das-2.25bpw`)で起動します。詳細、カードごとの速度、手動インストールは [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md) にあります。 + ## どのくらい速い? 12 GBのグラフィックスカード(RTX 5070、Ryzen 5 7600、RAM 64 GB)での数値です。ほかのカードの結果は diff --git a/README.md b/README.md index 697dcbce..94236f35 100644 --- a/README.md +++ b/README.md @@ -190,12 +190,14 @@ Every size, download and what fits where: [docs/MODELS.md](docs/MODELS.md). ### DeepSeek V4.1-Flash (in the Terminal, from 0.2.4) -[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) is a different, much bigger model. ISTA-DASLab made the two sets below. Strata runs them on a PC with one 12 GB graphics card and 46 to 64 GB of RAM, and reads the rest from your SSD. It runs through its own engine package, `strata-dsv41`, which `strata launch` downloads when you pick DeepSeek. The desktop app does not offer it yet. +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) is a different, much bigger model. ISTA-DASLab made the two sets below. Strata runs them on a PC with one 12 GB graphics card and 46 to 64 GB of RAM, and reads the rest from your SSD. It runs on NVIDIA RTX 30 to 50 cards and on the Radeon AI PRO R9700. It uses its own engine package, `strata-dsv41`, which `strata launch` downloads when you pick DeepSeek. The desktop app does not offer it yet. | Set | Download | Quality against the original model | Writes at | | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 bits) | 257 GB | KL 0.169, perplexity 3.64 (+16%) | 6 to 9 tokens/s on an RTX 3060, about 5 on an RTX 5070 | -| **IQ2_XS** (2.25 bits) | 274 GB | KL 0.110, perplexity 3.40 (+8%); code +3.5%, agent work +2.5% | a little slower than IQ2_XXS | +| **IQ2_XS** (2.25 bits) | 274 GB | KL 0.110, perplexity 3.40 (+8%); code +3.5%, agent work +2.5% | about 11 tokens/s on one Radeon AI PRO R9700 | + +4x Radeon AI PRO R9700: about 31 tokens/s, 55 to 69 with DSpark. Start it with `strata launch --model ist-das-2.00bpw` (or `ist-das-2.25bpw`). Details, speeds per card and the manual install: [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md). diff --git a/README.pt-BR.md b/README.pt-BR.md index a5d5098e..afcf5a00 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -183,6 +183,19 @@ Mais opções: Todos os tamanhos, downloads e o que cabe em cada configuração: [docs/MODELS.md](docs/MODELS.md). +### DeepSeek V4.1-Flash (no Terminal, a partir da 0.2.4) + +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) é outro modelo, bem maior. A ISTA-DASLab fez os dois conjuntos abaixo. O Strata os executa em um PC com uma placa de vídeo de 12 GB e de 46 a 64 GB de RAM, e lê o resto do seu SSD. Ele roda em placas NVIDIA RTX das séries 30 a 50 e na Radeon AI PRO R9700. Usa um pacote de motor próprio, `strata-dsv41`, que o `strata launch` baixa quando você escolhe o DeepSeek. O app de desktop ainda não o oferece. + +| Conjunto | Download | Qualidade em relação ao modelo original | Responde a | +| --- | ---: | --- | --- | +| **IQ2_XXS** (2.00 bits) | 257 GB | KL 0,169, perplexidade 3,64 (+16%) | 6 a 9 tokens/s em uma RTX 3060, cerca de 5 em uma RTX 5070 | +| **IQ2_XS** (2.25 bits) | 274 GB | KL 0,110, perplexidade 3,40 (+8%); código +3,5%, tarefas de agente +2,5% | cerca de 11 tokens/s em uma Radeon AI PRO R9700 | + +4x Radeon AI PRO R9700: cerca de 31 tokens/s, 55 a 69 com DSpark. + +Inicie com `strata launch --model ist-das-2.00bpw` (ou `ist-das-2.25bpw`). Detalhes, velocidades por placa e a instalação manual: [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md). + ## Qual é a velocidade? Com base numa placa de vídeo de 12 GB (RTX 5070, Ryzen 5 7600, 64 GB de RAM). Veja resultados de outras placas: diff --git a/README.zh-CN.md b/README.zh-CN.md index e18d8ee5..98c5b869 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -182,6 +182,19 @@ Gyro 可在 NVIDIA 和 AMD 显卡(AMD 为实验性支持)以及 Linux 上的 所有尺寸、下载大小,以及各种配置能跑什么:[docs/MODELS.md](docs/MODELS.md)。 +### DeepSeek V4.1-Flash(终端版,0.2.4 起) + +[DeepSeek V4.1-Flash](https://huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF) 是另一个大得多的模型。下面两个版本由 ISTA-DASLab 制作。Strata 在一台有一块 12 GB 显卡和 46 到 64 GB 内存的电脑上运行它们,其余部分从固态硬盘读取。它可在 NVIDIA RTX 30 到 50 系列显卡和 Radeon AI PRO R9700 上运行。它使用自己的引擎包 `strata-dsv41`,你选择 DeepSeek 时由 `strata launch` 下载。桌面应用暂时不提供它。 + +| 版本 | 下载大小 | 与原模型相比的质量 | 生成速度 | +| --- | ---: | --- | --- | +| **IQ2_XXS** (2.00 位) | 257 GB | KL 0.169,困惑度 3.64(+16%) | RTX 3060 上每秒 6 到 9 个 token,RTX 5070 上约 5 个 | +| **IQ2_XS** (2.25 位) | 274 GB | KL 0.110,困惑度 3.40(+8%);代码 +3.5%,智能体任务 +2.5% | 一块 Radeon AI PRO R9700 上每秒约 11 个 token | + +4 块 Radeon AI PRO R9700:每秒约 31 个 token,使用 DSpark 时为 55 到 69。 + +用 `strata launch --model ist-das-2.00bpw`(或 `ist-das-2.25bpw`)启动。详情、各显卡的速度和手动安装见 [docs/DEEPSEEK41.md](docs/DEEPSEEK41.md)。 + ## 速度如何? 以下数据基于 12 GB 显卡(RTX 5070、Ryzen 5 7600、64 GB 内存)。其他显卡的结果见: diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index 499a4683..8e634ae1 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -24,7 +24,8 @@ Output is the speed of the answer. Prompt is how fast Strata reads what you send |---|---|---| | RTX 5070 12 GB, 64 GB RAM | about 5 tokens/s (code) | 231 tokens/s at 8K | | RTX 3060 12 GB, 46 GB RAM | about 6 to 9 tokens/s (6.1-6.7 without DSpark, 8.2-8.7 with) | about 103 tokens/s at 8K | -| 4x Radeon AI PRO R9700 (AMD) | about 31 tokens/s | about 360 tokens/s at 8K, 557 at 32K | +| 1x Radeon AI PRO R9700 (AMD), IQ2_XS | about 11 tokens/s | not measured | +| 4x Radeon AI PRO R9700 (AMD) | about 31 tokens/s (55 to 69 with DSpark) | about 360 tokens/s at 8K, 557 at 32K | These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so expect it to be a little slower. Your drive matters: the 12 GB cards spend most of each token waiting on the SSD and on the CPU, and a slow NVMe drive lowers every number above. From dfe29bce61df9779e0eec45712894e02d4e172fe Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:20:04 +0200 Subject: [PATCH 23/34] serve: DeepSeek-V4.1 thinks at most 32768 tokens when neither the request nor the config names a budget Same default as Maya #363. For the deepseek41 family only: Service.reasoning_budget() answers 32768 when the request has no reasoning_budget_tokens / thinking_budget_tokens and the config has no reasoning_budget_tokens at all (a config value, 0 included, wins; a request's 0 turns it off). The existing wrap-up (#123) closes the thinking at the budget, and the answer-room clamp still cuts it to leave the answer its share of max_tokens. Thinking off and other families unchanged. Tests in serve/test_dsv41.py: the default, a request's 0 and own value, the config's value and 0, another family, and a 5000-token cap that is wrapped up and answered. serve suite: 1027 tests OK (15 skipped). --- serve/server.py | 5 +++++ serve/test_dsv41.py | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/serve/server.py b/serve/server.py index 920cd35b..5fa70820 100644 --- a/serve/server.py +++ b/serve/server.py @@ -201,6 +201,7 @@ VISION_START = "<|vision_start|>" # sets it; 0 turns it off. REPEAT_STOP_TOKENS = 256 ANSWER_ROOM_MIN_CAP = 1024 # 0.1.45: from this max_tokens on, thinking without a budget is closed early enough to leave room to answer +DS41_DEFAULT_BUDGET = 32768 # DeepSeek-V4.1 only: the thinking budget when neither the request nor the config names one DS41_SMALL_CAP_MIN = 48 # DeepSeek-V4.1 only: from this max_tokens up to ANSWER_ROOM_MIN_CAP, thinking is capped at half of it ANSWER_RESERVE_MIN = 512 # #984: the tokens kept for the answer when a thinking budget is cut down to fit max_tokens # #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) @@ -3894,6 +3895,7 @@ class Service: self.vision_held = False # an elastic encoder holds VRAM the expert cache gave it self.last_image_at = 0.0 # when an image turn last ended (the elastic encoder's idle) self.reasoning_loop_recovery = False + self.reasoning_budget_configured = False # the config named reasoning_budget_tokens (0 included): no family default self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False @@ -4141,6 +4143,8 @@ class Service: value = req.get("thinking_budget_tokens") if value is None: value = self.reasoning_budget_tokens + if not value and self.family == "deepseek41" and not self.reasoning_budget_configured: + value = DS41_DEFAULT_BUDGET # DeepSeek-V4.1 only, as Maya ships it: no budget anywhere = this one if isinstance(value, float) and value.is_integer(): value = int(value) if isinstance(value, bool) or not isinstance(value, int): @@ -8522,6 +8526,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in svc.repeat_stop_tokens = rs svc.effort_end = bool(effort_end) # #458: "effort_position": "end" with an engine that has it if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request + svc.reasoning_budget_configured = True try: svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] budget = svc.reasoning_budget({}) diff --git a/serve/test_dsv41.py b/serve/test_dsv41.py index f9f13a85..04b4d2bb 100644 --- a/serve/test_dsv41.py +++ b/serve/test_dsv41.py @@ -624,6 +624,29 @@ class SmallCap(ApiBase): self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"a": "1"}) self.assertEqual(len(self.engine.last_prompt) > 0, True) + def test_the_family_default_thinking_budget(self): + """DeepSeek-V4.1 only, as Maya ships it: 32768 thinking tokens when neither the request nor the config names a budget.""" + self.start("ok") + self.assertEqual(self.svc.reasoning_budget({}), 32768) + self.assertIsNone(self.svc.reasoning_budget({"reasoning_budget_tokens": 0})) # a request turns it off + self.assertEqual(self.svc.reasoning_budget({"reasoning_budget_tokens": 50}), 50) # and its own wins + self.assertEqual(self.svc.reasoning_budget({"thinking_budget_tokens": 70}), 70) + self.svc.reasoning_budget_tokens, self.svc.reasoning_budget_configured = 90, True + self.assertEqual(self.svc.reasoning_budget({}), 90) # the config's wins + self.svc.reasoning_budget_tokens = 0 # the config says none + self.assertIsNone(self.svc.reasoning_budget({})) + self.svc.reasoning_budget_configured = False + self.svc.set_family(None) + self.assertIsNone(self.svc.reasoning_budget({})) # other families: none + + def test_the_default_budget_closes_a_long_thinking(self): + self.start_forever() + status, r = self.chat(max_tokens=5000) + self.assertEqual(status, 200, r) + self.assertEqual(r["choices"][0]["message"]["content"], ThinkForever.ANSWER) + status, r = self.chat(max_tokens=300, reasoning_effort="none") # thinking off: no budget, no wrap-up + self.assertEqual(len(self.engine.prompts), 3) + def test_other_families_keep_the_old_behaviour(self): self.start_forever() self.svc.set_family(None) From 0e121c7a1363747bf34c7039e0f654614715fb9e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:21:32 +0200 Subject: [PATCH 24/34] DeepSeek table: the IQ4_NL Engram table row (README and 6 translations, DEEPSEEK41.md, release notes); notes: long-prompt skip and the 32,768 thinking budget --- README.de.md | 1 + README.es.md | 1 + README.fr.md | 1 + README.ja.md | 1 + README.md | 1 + README.pt-BR.md | 1 + README.zh-CN.md | 1 + docs/DEEPSEEK41.md | 9 +++++++++ docs/release-notes-0.2.4.md | 3 +++ 9 files changed, 19 insertions(+) diff --git a/README.de.md b/README.de.md index 3ff89dc5..65a8279d 100644 --- a/README.de.md +++ b/README.de.md @@ -198,6 +198,7 @@ Alle Größen, Downloads und was wo läuft: [docs/MODELS.md](docs/MODELS.md). | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 Bit) | 257 GB | KL 0,169, Perplexität 3,64 (+16 %) | 6 bis 9 Tokens/s auf einer RTX 3060, etwa 5 auf einer RTX 5070 | | **IQ2_XS** (2.25 Bit) | 274 GB | KL 0,110, Perplexität 3,40 (+8 %); Code +3,5 %, Agent-Aufgaben +2,5 % | etwa 11 Tokens/s auf einer Radeon AI PRO R9700 | +| **IQ4_NL** (Engram-Tabelle, kein drittes Modell) | 111 GB, schon in beiden Downloads oben enthalten | Die 4-Bit-Engram-Nachschlagetabelle, die das Modell aus RAM oder SSD liest. Beide Sets nutzen diese eine Datei (`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf`). | n/a | 4x Radeon AI PRO R9700: etwa 31 Tokens/s, 55 bis 69 mit DSpark. diff --git a/README.es.md b/README.es.md index a0f81838..e18da76e 100644 --- a/README.es.md +++ b/README.es.md @@ -198,6 +198,7 @@ Todos los tamaños, descargas y lo que cabe en cada equipo: [docs/MODELS.md](doc | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 bits) | 257 GB | KL 0,169, perplejidad 3,64 (+16 %) | de 6 a 9 tokens/s en una RTX 3060, unos 5 en una RTX 5070 | | **IQ2_XS** (2.25 bits) | 274 GB | KL 0,110, perplejidad 3,40 (+8 %); código +3,5 %, tareas de agente +2,5 % | unos 11 tokens/s en una Radeon AI PRO R9700 | +| **IQ4_NL** (tabla Engram, no es un tercer modelo) | 111 GB, ya incluidos en las dos descargas de arriba | La tabla de consulta Engram de 4 bits que el modelo lee de la RAM o del SSD. Los dos conjuntos usan este único archivo (`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf`). | n/a | 4x Radeon AI PRO R9700: unos 31 tokens/s, de 55 a 69 con DSpark. diff --git a/README.fr.md b/README.fr.md index 8fbfb4f0..948b2422 100644 --- a/README.fr.md +++ b/README.fr.md @@ -199,6 +199,7 @@ Toutes les tailles, les téléchargements et ce qui tient où : [docs/MODELS.md] | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 bits) | 257 GB | KL 0,169, perplexité 3,64 (+16 %) | 6 à 9 tokens/s sur une RTX 3060, environ 5 sur une RTX 5070 | | **IQ2_XS** (2.25 bits) | 274 GB | KL 0,110, perplexité 3,40 (+8 %) ; code +3,5 %, tâches d’agent +2,5 % | environ 11 tokens/s sur une Radeon AI PRO R9700 | +| **IQ4_NL** (table Engram, pas un troisième modèle) | 111 Go, déjà compris dans les deux téléchargements ci-dessus | La table de consultation Engram en 4 bits que le modèle lit dans la RAM ou sur le SSD. Les deux versions utilisent ce seul fichier (`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf`). | n/a | 4x Radeon AI PRO R9700 : environ 31 tokens/s, 55 à 69 avec DSpark. diff --git a/README.ja.md b/README.ja.md index 9a6a2c20..26351c87 100644 --- a/README.ja.md +++ b/README.ja.md @@ -191,6 +191,7 @@ Gyro は NVIDIA と AMD のカード(AMD は実験的)、および Linux 上 | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 ビット) | 257 GB | KL 0.169、パープレキシティ 3.64(+16%) | RTX 3060 で毎秒 6 から 9 トークン、RTX 5070 で約 5 | | **IQ2_XS** (2.25 ビット) | 274 GB | KL 0.110、パープレキシティ 3.40(+8%)、コード +3.5%、エージェント作業 +2.5% | Radeon AI PRO R9700 1 枚で毎秒約 11 トークン | +| **IQ4_NL**(Engram テーブル、3 つ目のモデルではありません) | 111 GB、上の 2 つのダウンロードに含まれています | モデルが RAM または SSD から読む 4 ビットの Engram 参照テーブルです。2 つのセットはこの 1 つのファイル(`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf`)を共有します。 | 該当なし | Radeon AI PRO R9700 4 枚:毎秒約 31 トークン、DSpark ありで 55 から 69。 diff --git a/README.md b/README.md index 94236f35..49845e0b 100644 --- a/README.md +++ b/README.md @@ -196,6 +196,7 @@ Every size, download and what fits where: [docs/MODELS.md](docs/MODELS.md). | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 bits) | 257 GB | KL 0.169, perplexity 3.64 (+16%) | 6 to 9 tokens/s on an RTX 3060, about 5 on an RTX 5070 | | **IQ2_XS** (2.25 bits) | 274 GB | KL 0.110, perplexity 3.40 (+8%); code +3.5%, agent work +2.5% | about 11 tokens/s on one Radeon AI PRO R9700 | +| **IQ4_NL** (Engram table, not a third model) | 111 GB, already in both downloads above | The 4-bit Engram lookup table the model reads from RAM or SSD. Both sets use this one file (`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf`). | n/a | 4x Radeon AI PRO R9700: about 31 tokens/s, 55 to 69 with DSpark. diff --git a/README.pt-BR.md b/README.pt-BR.md index afcf5a00..414b08e5 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -191,6 +191,7 @@ Todos os tamanhos, downloads e o que cabe em cada configuração: [docs/MODELS.m | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 bits) | 257 GB | KL 0,169, perplexidade 3,64 (+16%) | 6 a 9 tokens/s em uma RTX 3060, cerca de 5 em uma RTX 5070 | | **IQ2_XS** (2.25 bits) | 274 GB | KL 0,110, perplexidade 3,40 (+8%); código +3,5%, tarefas de agente +2,5% | cerca de 11 tokens/s em uma Radeon AI PRO R9700 | +| **IQ4_NL** (tabela Engram, não é um terceiro modelo) | 111 GB, já incluídos nos dois downloads acima | A tabela de consulta Engram de 4 bits que o modelo lê da RAM ou do SSD. Os dois conjuntos usam este único arquivo (`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf`). | n/a | 4x Radeon AI PRO R9700: cerca de 31 tokens/s, 55 a 69 com DSpark. diff --git a/README.zh-CN.md b/README.zh-CN.md index 98c5b869..02bd4a16 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -190,6 +190,7 @@ Gyro 可在 NVIDIA 和 AMD 显卡(AMD 为实验性支持)以及 Linux 上的 | --- | ---: | --- | --- | | **IQ2_XXS** (2.00 位) | 257 GB | KL 0.169,困惑度 3.64(+16%) | RTX 3060 上每秒 6 到 9 个 token,RTX 5070 上约 5 个 | | **IQ2_XS** (2.25 位) | 274 GB | KL 0.110,困惑度 3.40(+8%);代码 +3.5%,智能体任务 +2.5% | 一块 Radeon AI PRO R9700 上每秒约 11 个 token | +| **IQ4_NL**(Engram 表,不是第三个模型) | 111 GB,已包含在上面两个下载中 | 模型从内存或固态硬盘读取的 4 位 Engram 查找表。两个版本共用这一个文件(`DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf`)。 | 不适用 | 4 块 Radeon AI PRO R9700:每秒约 31 个 token,使用 DSpark 时为 55 到 69。 diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 058abcd2..0bd609be 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -31,6 +31,15 @@ same 111 GB n-gram table (downloaded once into `models/deepseek-v4.1-flash-share 2.00, 274 GB for 2.25, 412 GB for both. Quality against the original model: perplexity +16% on 2.00, +8% on 2.25 (code and agent work about +3.5% / +2.5% on 2.25). +| File | Size | What it is | +| --- | ---: | --- | +| IQ2_XXS shards (2.00 bpw), 4 files | 138 GB | the model, first set | +| IQ2_XS shards (2.25 bpw), 4 files | 155 GB | the model, second set | +| IQ4_NL: `DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf` | 111 GB | the 4-bit Engram lookup table the model reads from RAM or SSD. Not a third model: both sets use this one file, and it is already in their download sizes | +| DSpark drafter (Q8_0) | 8 GB | the small draft model (Unsloth) | + +138 + 111 + 8 = 257 GB for 2.00; 155 + 111 + 8 = 274 GB for 2.25. + Measured: an RTX 5070 (12 GB) with 64 GB of RAM and a 3.6 GB/s NVMe drive answers at about 4.7 tokens/s and reads prompts at 121 tokens/s (4K) to 231 tokens/s (8K, layer-major path); an RTX 3060 (12 GB) with 46 GB of RAM about 7.2 tokens/s; four R9700 about 31 tokens/s. Under about 40 GB of RAM it is untested and slow; setup says so and still installs. diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index 8e634ae1..d61ed03b 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -12,6 +12,7 @@ Strata now runs DeepSeek V4.1-Flash on a PC with one 12 GB graphics card and 46 |---|---|---| | IQ2_XXS (2.00 bits) | 257 GB | perplexity +16%; code and agent text +8.5% and +5.9% | | IQ2_XS (2.25 bits) | 274 GB | perplexity +7.7% to +8.3%; code and agent text +3.5% and +2.5% | + | IQ4_NL (Engram table, not a third model) | 111 GB, already in both downloads above | The 4-bit Engram lookup table the model reads from RAM or SSD; both sets use this one file | "Perplexity" is how surprised the model is by a fixed set of 4,995 test texts; lower is closer to the original. Pick 2.25 for coding and agent work when you have the disk. Setup shows both sizes and warns if your PC is short of disk or RAM. It does not stop you. - Setup downloads the files, builds the model folder and starts the engine. You set no flags. @@ -34,6 +35,8 @@ These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so e - **A RAM expert store that sizes itself.** The model is a mixture of experts: each token uses a few of thousands of small blocks. Strata keeps the busiest ones in RAM, takes whatever RAM is free, and reads the rest from the SSD with direct reads. On the RTX 5070 PC with 64 GB this gave 4.3 to 4.9 tokens/s where memory-mapping the files gave 1.8 to 2.2. - **Hot-expert profiles ship with the engine,** so the first prompts do not start cold. - **Faster prompts.** The engine now reads long prompts layer by layer in big chunks instead of 16 tokens at a time. A 200-token prompt went from 3.6 to 6.4 tokens/s on the RTX 5070 PC, and 8K prompts reach 231 tokens/s. +- **Faster long prompts.** A prompt over about 3,700 tokens skips work that the last 20 layers cannot use (a 16K prompt is about 34% faster). The answers match the full computation in 99.75% of positions. +- **Thinking budget.** When neither your request nor your config sets one, DeepSeek thinks for at most 32,768 tokens. A request can set its own budget; 0 turns the limit off. - **DSpark** (a small draft model from Unsloth) is on where it measured faster and off on CPU-bound PCs. On the RTX 3060 PC (20 threads) it raised decode from 6.1-6.7 to 8.2-8.7 tokens/s. On the 4x R9700 box it raised 31 tokens/s to 55 to 69. On the RTX 5070 PC with a 6-core Ryzen 5 7600 it gave no gain at any setting (code 4.64 tokens/s with it off against 4.33 at best with it on; agent 3.41 against 2.86 to 3.21), because checking the drafts costs the CPU about what the saved tokens are worth. There `--dspark auto` does not load the drafter. - **Faster CPU rows.** The engine has new exact rows for the experts the CPU computes: AVX-512 on Zen 4 and Zen 5, AVX2 on other CPUs, chosen automatically. On the Ryzen 5 7600 PC with an RTX 5070 (2.00 set, DSpark on, three alternating pairs, identical text in all six runs), decode went from 4.08 to 5.11 tokens/s (+25%) and prompt reading rose 26%. This was measured on one CPU, a Zen 4. Zen 5 gained more in the kernel tests. - **Cards and engines:** tested on an RTX 3060 (Linux, full model), an RTX 5070 (Windows) and the Radeon AI PRO R9700 (gfx1201, Linux). The RTX 30 kernels (sm_86) were also checked on an RTX A4000. Windows on RTX 30 is built but was not run here. RX 9070 (gfx1200) is built but untested. The engine packages carry `strata-dsv41` next to `strata`. From 2e477ecd40f0fe62e2cff334f0b233142029363c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:21:59 +0200 Subject: [PATCH 25/34] release notes: the 99.75% is agreement between skip on and off over 799 positions --- docs/release-notes-0.2.4.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index d61ed03b..8b09b94c 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -35,7 +35,7 @@ These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so e - **A RAM expert store that sizes itself.** The model is a mixture of experts: each token uses a few of thousands of small blocks. Strata keeps the busiest ones in RAM, takes whatever RAM is free, and reads the rest from the SSD with direct reads. On the RTX 5070 PC with 64 GB this gave 4.3 to 4.9 tokens/s where memory-mapping the files gave 1.8 to 2.2. - **Hot-expert profiles ship with the engine,** so the first prompts do not start cold. - **Faster prompts.** The engine now reads long prompts layer by layer in big chunks instead of 16 tokens at a time. A 200-token prompt went from 3.6 to 6.4 tokens/s on the RTX 5070 PC, and 8K prompts reach 231 tokens/s. -- **Faster long prompts.** A prompt over about 3,700 tokens skips work that the last 20 layers cannot use (a 16K prompt is about 34% faster). The answers match the full computation in 99.75% of positions. +- **Faster long prompts.** A prompt over about 3,700 tokens skips work that the last 20 layers cannot use (a 16K prompt is about 34% faster). In the 799 positions we compared, the model's top choice for the next word was the same with and without the skip in 99.75% of them. - **Thinking budget.** When neither your request nor your config sets one, DeepSeek thinks for at most 32,768 tokens. A request can set its own budget; 0 turns the limit off. - **DSpark** (a small draft model from Unsloth) is on where it measured faster and off on CPU-bound PCs. On the RTX 3060 PC (20 threads) it raised decode from 6.1-6.7 to 8.2-8.7 tokens/s. On the 4x R9700 box it raised 31 tokens/s to 55 to 69. On the RTX 5070 PC with a 6-core Ryzen 5 7600 it gave no gain at any setting (code 4.64 tokens/s with it off against 4.33 at best with it on; agent 3.41 against 2.86 to 3.21), because checking the drafts costs the CPU about what the saved tokens are worth. There `--dspark auto` does not load the drafter. - **Faster CPU rows.** The engine has new exact rows for the experts the CPU computes: AVX-512 on Zen 4 and Zen 5, AVX2 on other CPUs, chosen automatically. On the Ryzen 5 7600 PC with an RTX 5070 (2.00 set, DSpark on, three alternating pairs, identical text in all six runs), decode went from 4.08 to 5.11 tokens/s (+25%) and prompt reading rose 26%. This was measured on one CPU, a Zen 4. Zen 5 gained more in the kernel tests. From 598372c3fd203c5692ca89806cb5b276960f7a94 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:24:14 +0200 Subject: [PATCH 26/34] setup: repin the DeepSeek 2.00/2.25 sets to ISTA-DASLab's final files (flat repository 0d8f49fb, IQ2_XXS = 2.00 bpw, IQ2_XS = 2.25 bpw, DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf); the first release's local files (model-2.00bpw-..., engram-IQ4_NL.gguf, in 2.00bpw/ folders) stay accepted by their old size and SHA-256 and are never downloaded again; tests --- setup.py | 101 +++++++++++++++++++++++++----------- strata_control/dsv41_fit.py | 8 +-- tools/test_setup_dsv41.py | 77 ++++++++++++++++++++++----- 3 files changed, 139 insertions(+), 47 deletions(-) diff --git a/setup.py b/setup.py index c5f2eb5c..46de4599 100644 --- a/setup.py +++ b/setup.py @@ -99,7 +99,7 @@ HF_REVISIONS = { "unsloth/Qwen3.6-35B-A3B-MTP-GGUF": "5bc3e238d916f48a861bac2f8a1990a0e9b7e98d", # 2026-10-12 "agentionai/Qwen3.8-Flash-Next-Gyro-GGUF": "1ada08422e404aca51ab9df665f089f34c419c6b", # 2026-10-13 "unsloth/DeepSeek-V4.1-Flash-1017-GGUF": "f924b94f19c1fea02c06a65c8475b0a45e2b88b1", # 2026-10-20 (the port's reference) - "helcig/tmp-oct26-2": "851709dcf0d97f091a4bdce758b2e4b0b468dd26", # 2026-10-23 (the official IST-DAS DeepSeek sets) + "ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF": "0d8f49fb15df73789a9c237a1b8b7b088423dbc0", # 2026-10-24 (ISTA-DASLab's final 2.00 / 2.25 bpw sets and Engram) } @@ -678,15 +678,31 @@ DSV41_FILES = { "dspark-DeepSeek-V4.1-Flash-1017-Q8_0.gguf": (7976914240, "6ba6ac1b331c540691a209e7fc97dec2a24e295acb1e755c84c7d24a4373927a"), "mmproj-BF16.gguf": (972208288, "9a1ef7c40d0d702c7ed8c5f863f60abae64091387ba3fce0ad19ce9beeda3bf9"), } -# The two OFFICIAL IST-DAS sets (helcig/tmp-oct26-2 at the revision above; Hub LFS sha256 = what the files hash to): 4 shards each, plus ONE -# Engram table (110.6 GB, the same file for both sets: downloaded once into the shared folder) and the DSpark drafter and the 5.8 MB -# metadata shard of Unsloth's set that pack_gguf --engram-meta reads (both pinned in DSV41_FILES above). This is the set a normal PC runs -# (64 GB RAM + a 12 GB card; docs/DEEPSEEK41.md); the UD-Q8_K_XL entry stays for the big machines. -DSV41_ISTA_REPO = "helcig/tmp-oct26-2" -DSV41_ISTA_ENGRAM = "engram-IQ4_NL.gguf" -DSV41_ISTA_SHARD = "model-{bpw}-{i:05d}-of-00004.gguf" +# The two OFFICIAL IST-DAS sets (ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF at the revision above, a flat repository; Hub LFS sha256 = what the +# files hash to): IQ2_XXS is the 2.00 bpw set and IQ2_XS the 2.25 bpw set, 4 shards each, plus ONE Engram table (110.6 GB, the same file for both sets: +# downloaded once into the shared folder) and the DSpark drafter and the 5.8 MB metadata shard of Unsloth's set that pack_gguf --engram-meta reads +# (both pinned in DSV41_FILES above). This is the set a normal PC runs (64 GB RAM + a 12 GB card; docs/DEEPSEEK41.md); the UD-Q8_K_XL entry stays +# for the big machines. +DSV41_ISTA_REPO = "ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF" +DSV41_ISTA_ENGRAM = "DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf" +DSV41_ISTA_SHARD = "DeepSeek-V4.1-Flash-1017-GSQ-RCO-{quant}-{i:05d}-of-00004.gguf" DSV41_DSPARK = "dspark-DeepSeek-V4.1-Flash-1017-Q8_0.gguf" DSV41_ISTA_FILES = { + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XS-00001-of-00004.gguf": (39535776992, "4c65307992ab586c527ca1f6f64062aa96a33b23c02b7fed103f45f75e854798"), + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XS-00002-of-00004.gguf": (39494617536, "933461a974fcccee741bf2f9798201e72ab4aa3f8a952be56f849896ca6ea30e"), + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XS-00003-of-00004.gguf": (39423838496, "bbf91fa346a85ebaf32dd4fd5c456b534d780d381e54f46ac90783a481373240"), + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XS-00004-of-00004.gguf": (36771591232, "e5b2f8781fab688cd4bc3bc7a69651b5dbb90ed94965657c6bead8bb4774f3cf"), + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-00001-of-00004.gguf": (39075714624, "d46efb67ccffd8fb5d7f18b423896381b9e06d8491e161c370ddf3b05b07e050"), + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-00002-of-00004.gguf": (39388449504, "cec1b2c3da429dc768b8bb9bc4dc4403d81f74d34db660a6a34ee3e555bf2c70"), + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-00003-of-00004.gguf": (39246891616, "9d9c2140fcb134a0b9a74dedd0e5167e68077af6d08ce7f856bce112f0a35dd3"), + "DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-00004-of-00004.gguf": (20527837312, "9b790a2297ed3cdede379fc984f4a52bb95f3b23724c797af11d1fa6a69db059"), + "DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf": (110595290816, "eb19f30d368d393784e1fc54fdfaffc427ebb2110bf3762fdf5a8fbb9a2d740a"), +} +# The files the first release of these sets was downloaded as (helcig/tmp-oct26-2, 2026-10-23: model-2.00bpw-0000N-of-00004.gguf, model-2.25bpw-..., +# engram-IQ4_NL.gguf, usually in a 2.00bpw/ or 2.25bpw/ folder): testers and our boxes have them. They are the same weights: shards 2-4 are the +# same bytes as today's, and shard 1 and the Engram differ only in their GGUF header (metadata). setup accepts them from "files already here" +# (size and SHA-256 checked against these pins) and never downloads them. Not in REPO_PINS: nothing is fetched under these names. +DSV41_LEGACY_FILES = { "model-2.00bpw-00001-of-00004.gguf": (39075713728, "78ab9efc46a26647c3e94b322c99cd7e2af261dd28b38f2712e128562db1ef47"), "model-2.00bpw-00002-of-00004.gguf": (39388449504, "cec1b2c3da429dc768b8bb9bc4dc4403d81f74d34db660a6a34ee3e555bf2c70"), "model-2.00bpw-00003-of-00004.gguf": (39246891616, "9d9c2140fcb134a0b9a74dedd0e5167e68077af6d08ce7f856bce112f0a35dd3"), @@ -697,13 +713,19 @@ DSV41_ISTA_FILES = { "model-2.25bpw-00004-of-00004.gguf": (36771591232, "e5b2f8781fab688cd4bc3bc7a69651b5dbb90ed94965657c6bead8bb4774f3cf"), "engram-IQ4_NL.gguf": (110595290720, "1f17d8ae37e9df3bb45f7ef1b4fcd1706d7b759af0413c117bf8e92aed459281"), } +# today's name -> the name it had in the first release +DSV41_LEGACY_NAMES = { + **{DSV41_ISTA_SHARD.format(quant="IQ2_XXS", i=i): "model-2.00bpw-%05d-of-00004.gguf" % i for i in range(1, 5)}, + **{DSV41_ISTA_SHARD.format(quant="IQ2_XS", i=i): "model-2.25bpw-%05d-of-00004.gguf" % i for i in range(1, 5)}, + DSV41_ISTA_ENGRAM: "engram-IQ4_NL.gguf", +} # the files every official set shares (name -> where it comes from); they live in models/deepseek-v4.1-flash-shared, once DSV41_SHARED = { - DSV41_ISTA_ENGRAM: hf(DSV41_ISTA_REPO) + "2.00bpw/", + DSV41_ISTA_ENGRAM: hf(DSV41_ISTA_REPO), DSV41_SHARD.format(i=1): hf(DSV41_REPO) + "UD-Q8_K_XL/", # only its metadata is read (pack_gguf --engram-meta) DSV41_DSPARK: hf(DSV41_REPO), } -DSV41_ALL_FILES = {**DSV41_FILES, **DSV41_ISTA_FILES} +DSV41_ALL_FILES = {**DSV41_FILES, **DSV41_ISTA_FILES, **DSV41_LEGACY_FILES} DSV41_PROFILES = ROOT / "data" / "dsv41" # the shipped hot-expert profiles (profile-2.00.bin, profile-2.25.bin, + .sha256) DSV41_CONTEXT = 8192 # the context the engine was checked at (4096 and 8192; 64K is not tried yet) MULTI_FILE_FAMILIES = { @@ -725,15 +747,15 @@ MULTI_FILE_FAMILIES["deepseek41"]["models"] = { "about": "the smaller official version: 138 GB of model + 111 GB n-gram table + 8 GB drafter (257 GB of disk). Runs on a PC with " "a 12 GB card and 40-64 GB of RAM at about 5-7 tokens a second; quality about 16% above the original model's " "perplexity", - "ram_gb": 40, "recipe": "ista", "subdir": "2.00bpw", "profile": "profile-2.00.bin", "hf": hf(DSV41_ISTA_REPO) + "2.00bpw/", - "shards": [DSV41_ISTA_SHARD.format(bpw="2.00bpw", i=i) for i in range(1, 5)], + "ram_gb": 40, "recipe": "ista", "subdir": None, "legacy_subdir": "2.00bpw", "profile": "profile-2.00.bin", "hf": hf(DSV41_ISTA_REPO), + "shards": [DSV41_ISTA_SHARD.format(quant="IQ2_XXS", i=i) for i in range(1, 5)], "shared": [DSV41_ISTA_ENGRAM, DSV41_SHARD.format(i=1), DSV41_DSPARK]}, "IST-DAS-2.25bpw": { "label": "IST-DAS 2.25 bpw", "about": "the better official version: 155 GB of model + 111 GB n-gram table + 8 GB drafter (274 GB of disk, 17 GB more than " "2.00). About the same speed; quality about 8% above the original model's perplexity (code and agent work 2.5-3.5%)", - "ram_gb": 44, "recipe": "ista", "subdir": "2.25bpw", "profile": "profile-2.25.bin", "hf": hf(DSV41_ISTA_REPO) + "2.25bpw/", - "shards": [DSV41_ISTA_SHARD.format(bpw="2.25bpw", i=i) for i in range(1, 5)], + "ram_gb": 44, "recipe": "ista", "subdir": None, "legacy_subdir": "2.25bpw", "profile": "profile-2.25.bin", "hf": hf(DSV41_ISTA_REPO), + "shards": [DSV41_ISTA_SHARD.format(quant="IQ2_XS", i=i) for i in range(1, 5)], "shared": [DSV41_ISTA_ENGRAM, DSV41_SHARD.format(i=1), DSV41_DSPARK]}, "UD-Q8_K_XL": { "label": "Unsloth UD-Q8_K_XL", @@ -754,7 +776,7 @@ REPO_PINS = { "unsloth/Qwen3.6-35B-A3B-MTP-GGUF": QWEN36_FILES, "agentionai/Qwen3.8-Flash-Next-Gyro-GGUF": GYRO_FILES, "unsloth/DeepSeek-V4.1-Flash-1017-GGUF": DSV41_FILES, - "helcig/tmp-oct26-2": DSV41_ISTA_FILES, + "ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF": DSV41_ISTA_FILES, } # EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README ESP_VECTOR = ROOT / "data" / "experimental-speed-projection" / "Qwen3.8-Flash-Next-experimental-speed-projection.gguf" @@ -7768,11 +7790,27 @@ def dsv41_folder(a, fam: dict, tag: str, model: str = "UD-Q8_K_XL") -> Path: if a.gguf_dir: folder = Path(a.gguf_dir) d = fam["models"][model] - sub = d.get("subdir") or model - return folder / sub if (folder / sub).is_dir() and not (folder / d["shards"][0]).exists() else folder + names = [n for s in d["shards"] for n in (s, DSV41_LEGACY_NAMES.get(s)) if n] + if any((folder / n).exists() for n in names): + return folder + for sub in (d.get("subdir"), d.get("legacy_subdir"), model): # the set's own folder inside (the first release used 2.00bpw/, 2.25bpw/) + if sub and (folder / sub).is_dir(): + return folder / sub + return folder return Path(a.models_dir) / tag +def dsv41_pick(folder: Path, name: str) -> Path: + """`name` in `folder`, or the file it was called in the first release (DSV41_LEGACY_NAMES; the same weights) when only that one is there; + else `name` (where it will be downloaded to).""" + if (folder / name).exists(): + return folder / name + old = DSV41_LEGACY_NAMES.get(name) + if old and (folder / old).exists(): + return folder / old + return folder / name + + def dsv41_shared_dir(a, fam: dict) -> Path: """Where the files the official sets share (the Engram, the DSpark drafter, the metadata shard) are downloaded to: one folder, so installing the second set does not download the 111 GB Engram again.""" @@ -7783,7 +7821,7 @@ def dsv41_find_shared(a, name: str, folder: Path, shared: Path) -> Path: """The file `name` (an Engram, the drafter, ...) the person already has: in the shared folder, beside the shards, or (--gguf-dir) in the folder above them or one folder level down from either; else where it will be downloaded to (the shared folder). The size must be the pinned one, so a half-copied file is not taken for the file.""" - size = DSV41_ALL_FILES[name][0] + names = [n for n in (name, DSV41_LEGACY_NAMES.get(name)) if n] # today's name, and the first release's (the same weights) roots = [shared, folder] if a.gguf_dir: base = Path(a.gguf_dir) @@ -7798,12 +7836,13 @@ def dsv41_find_shared(a, name: str, folder: Path, shared: Path) -> Path: except OSError: continue for k in kids: - f = k / name - try: - if f.is_file() and f.stat().st_size == size: - return f - except OSError: - pass + for n in names: + f = k / n + try: + if f.is_file() and f.stat().st_size == DSV41_ALL_FILES[n][0]: + return f + except OSError: + pass return shared / name @@ -7883,14 +7922,14 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, model = names[int(ask("Which version?", [str(i) for i in range(1, len(names) + 1)], "1", a.yes)) - 1] ok(f"size: {model}") md = fam["models"][model] - say(" Its GGUF files: " + ("IST-DAS (huggingface.co/helcig/tmp-oct26-2), with the DSpark drafter and a small metadata file from Unsloth" + say(" Its GGUF files: " + ("IST-DAS / ISTA-DASLab (huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF), with the DSpark drafter and a small metadata file from Unsloth" if md.get("recipe") == "ista" else "Unsloth (huggingface.co/unsloth/DeepSeek-V4.1-Flash-1017-GGUF)")) ista = md.get("recipe") == "ista" tag = fam["tag"] + model cards = dsv41_cards(gpu, all_cards, bool(a.gpu is not None or a.gpus)) ctx = a.context or DSV41_CONTEXT folder = dsv41_folder(a, fam, tag, model) - shards = [folder / n for n in md["shards"]] + shards = [dsv41_pick(folder, n) for n in md["shards"]] shared_dir = dsv41_shared_dir(a, fam) shared = [dsv41_find_shared(a, n, folder, shared_dir) for n in md.get("shared", [])] own_files = {f: bool(a.gguf_dir) or f.parent != shared_dir for f in shared} # a file found outside setup's own folder is the person's @@ -7899,7 +7938,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, p = f.with_name(f.name + ".part") return p.stat().st_size if p.is_file() else 0 - left = sum(0 if f.exists() and (done(f) or a.gguf_dir or own_files.get(f)) else fam["sha256"][f.name][0] - partial(f) + left = sum(0 if f.exists() and (done(f) or a.gguf_dir or own_files.get(f) or f.name in DSV41_LEGACY_FILES) else fam["sha256"][f.name][0] - partial(f) for f in [*shards, *shared]) / 1e9 probe = folder if folder.exists() else (folder.parent if folder.parent.exists() else Path(a.models_dir)) free = free_gb(probe) @@ -7968,9 +8007,11 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, else: if a.gguf_dir and not f.exists(): fail(f"{f} is missing", f"put {f.name} in {folder}, or drop --gguf-dir to download it") - if not a.gguf_dir: + if not a.gguf_dir and f.name not in DSV41_LEGACY_FILES: # (a first-release file is checked, never fetched under its old name) download((md.get("hf") or fam["hf"]) + f.name, f) - verify_sha256(f, *fam["sha256"][f.name], own=bool(a.gguf_dir)) + if f.name in DSV41_LEGACY_FILES: + ok(f"{f.name}: a file of the first release of this set (the same weights); it is used as it is") + verify_sha256(f, *fam["sha256"][f.name], own=bool(a.gguf_dir) or f.name in DSV41_LEGACY_FILES) for f in shared: # the Engram, the drafter, the metadata shard: once for every official set if f.exists() and (done(f) or own_files[f]): ok(f"{f.name} already here ({f.parent})") @@ -7991,7 +8032,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, have_pack = False if not have_pack: if ista: - run(dsv41_pack_cmd(folder, md["shards"], shared[0], shared[1], shared[2], pack)) + run(dsv41_pack_cmd(folder, [f.name for f in shards], shared[0], shared[1], shared[2], pack)) else: run([sys.executable, str(ROOT / "tools" / "dsv41" / "pack_gguf.py"), "--model", str(folder), "--out", str(pack)]) if ista: diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index 96b84112..b5dc6857 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -48,20 +48,20 @@ MEASURED = ("4 x Radeon AI PRO R9700 (32 GB) with 251 GB of RAM: prompts of 3,00 "at 25-31 tokens a second (--tp 2); one answer at a time") -# The two official IST-DAS sets (helcig/tmp-oct26-2, setup.py DSV41_ISTA_FILES): 4 shards each (the experts as IQ1_M / IQ2 / IQ3 types, the +# The two official IST-DAS sets (ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF, setup.py DSV41_ISTA_FILES): 4 shards each (the experts as IQ1_M / IQ2 / IQ3 types, the # dense weights Q8_0 / Q5_K), plus ONE Engram (110.6 GB, IQ4_NL, shared by both sets, stays on the SSD) and the DSpark drafter (8.0 GB). # Measured 2026-10-23 (f-dsv41-rel): quality against the original model (ppl +16% for 2.00, +7.7-8.3% for 2.25; code / agent +3.5% / +2.5% # on 2.25); speed on the owner PC (RTX 5070 12 GB, 64 GB RAM, 3.6 GB/s NVMe): answers ~4.7 tokens a second, prompts 121 tokens a second at 4K and # 231 tokens a second at 8K; RTX 3060 12 GB with 46 GB of RAM (the engine held to 36 GB): answers ~7.2 tokens a second on 2.00; 4 x Radeon AI PRO # R9700: answers ~31 tokens a second, prompts 330-373 tokens a second at 8K. -ISTA_ENGRAM_BYTES = 110_595_290_720 +ISTA_ENGRAM_BYTES = 110_595_290_816 ISTA_DSPARK_BYTES = 7_976_914_240 ISTA_META_BYTES = 5_780_589 # the first shard of Unsloth's UD-Q8_K_XL: only the metadata --engram-meta reads ISTA_SETS = { - "IST-DAS-2.00bpw": {"title": "IST-DAS 2.00 bpw", "set_bytes": 138_238_892_160, "experts_gb": 132.07, "profile": "profile-2.00.bin", + "IST-DAS-2.00bpw": {"title": "IST-DAS 2.00 bpw", "set_bytes": 138_238_893_056, "experts_gb": 132.07, "profile": "profile-2.00.bin", "ppl": "16%", "ram_ok_gb": 40.0, "ram_great_gb": 160.0, "disk_total": 257.0, "quality": "about 16% above the original model's perplexity (the 2-bit price)"}, - "IST-DAS-2.25bpw": {"title": "IST-DAS 2.25 bpw", "set_bytes": 155_225_823_328, "experts_gb": 149.06, "profile": "profile-2.25.bin", + "IST-DAS-2.25bpw": {"title": "IST-DAS 2.25 bpw", "set_bytes": 155_225_824_256, "experts_gb": 149.06, "profile": "profile-2.25.bin", "ppl": "8%", "ram_ok_gb": 44.0, "ram_great_gb": 176.0, "disk_total": 274.0, "quality": "about 8% above the original model's perplexity (code and agent work about 2.5-3.5% above), " "the better of the two, 17 GB more disk"}, diff --git a/tools/test_setup_dsv41.py b/tools/test_setup_dsv41.py index add4bf8c..6d951379 100644 --- a/tools/test_setup_dsv41.py +++ b/tools/test_setup_dsv41.py @@ -322,32 +322,35 @@ RTX5070 = {"index": 0, "name": "NVIDIA GeForce RTX 5070", "vram_gb": 12.0, "vend class OfficialSets(unittest.TestCase): - """The two official IST-DAS sets (helcig/tmp-oct26-2): the catalog, the pins, the pack recipe, the fit words.""" + """The two official IST-DAS sets (ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF): the catalog, the pins, the pack recipe, the fit words.""" def test_the_pinned_files(self): fam = setup.MULTI_FILE_FAMILIES["deepseek41"] self.assertEqual(list(fam["models"]), ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "UD-Q8_K_XL"]) # the official sets first - self.assertEqual(setup.HF_REVISIONS["helcig/tmp-oct26-2"], "851709dcf0d97f091a4bdce758b2e4b0b468dd26") - self.assertIs(setup.REPO_PINS["helcig/tmp-oct26-2"], setup.DSV41_ISTA_FILES) + repo = "ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF" + self.assertEqual(setup.HF_REVISIONS[repo], "0d8f49fb15df73789a9c237a1b8b7b088423dbc0") + self.assertIs(setup.REPO_PINS[repo], setup.DSV41_ISTA_FILES) + self.assertNotIn("helcig/tmp-oct26-2", setup.HF_REVISIONS) # the first release's repository is only remembered as local names + self.assertEqual(setup.DSV41_ISTA_REPO, repo) self.assertEqual(len(setup.DSV41_ISTA_FILES), 9) # 2 x 4 shards + the Engram for n, (size, sha) in setup.DSV41_ISTA_FILES.items(): self.assertRegex(sha, r"^[0-9a-f]{64}$", n) - eng = setup.DSV41_ISTA_FILES["engram-IQ4_NL.gguf"] - self.assertEqual(eng, (110_595_290_720, "1f17d8ae37e9df3bb45f7ef1b4fcd1706d7b759af0413c117bf8e92aed459281")) + eng = setup.DSV41_ISTA_FILES["DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf"] + self.assertEqual(eng, (110_595_290_816, "eb19f30d368d393784e1fc54fdfaffc427ebb2110bf3762fdf5a8fbb9a2d740a")) self.assertEqual(setup.DSV41_ALL_FILES["dspark-DeepSeek-V4.1-Flash-1017-Q8_0.gguf"], (7_976_914_240, "6ba6ac1b331c540691a209e7fc97dec2a24e295acb1e755c84c7d24a4373927a")) sums = {m: sum(setup.DSV41_ALL_FILES[n][0] for n in fam["models"][m]["shards"]) for m in list(fam["models"])[:2]} - self.assertEqual(sums, {"IST-DAS-2.00bpw": 138_238_892_160, "IST-DAS-2.25bpw": 155_225_823_328}) + self.assertEqual(sums, {"IST-DAS-2.00bpw": 138238893056, "IST-DAS-2.25bpw": 155225824256}) self.assertEqual(sums["IST-DAS-2.00bpw"], dsv41_fit.ISTA_SETS["IST-DAS-2.00bpw"]["set_bytes"]) self.assertEqual(sums["IST-DAS-2.25bpw"], dsv41_fit.ISTA_SETS["IST-DAS-2.25bpw"]["set_bytes"]) - self.assertEqual(setup.DSV41_ISTA_FILES["engram-IQ4_NL.gguf"][0], dsv41_fit.ISTA_ENGRAM_BYTES) + self.assertEqual(setup.DSV41_ISTA_FILES["DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf"][0], dsv41_fit.ISTA_ENGRAM_BYTES) for m in ("IST-DAS-2.00bpw", "IST-DAS-2.25bpw"): # both sets name the same shared files: the Engram is downloaded once self.assertEqual(fam["models"][m]["shared"], [setup.DSV41_ISTA_ENGRAM, setup.DSV41_SHARD.format(i=1), setup.DSV41_DSPARK]) for n in fam["models"][m]["shared"]: self.assertIn(n, setup.DSV41_SHARED) self.assertIn(n, setup.DSV41_ALL_FILES) - self.assertRegex(setup.DSV41_SHARED[setup.DSV41_ISTA_ENGRAM], r"helcig/tmp-oct26-2/resolve/851709dc[0-9a-f]{32}/2\.00bpw/$") - self.assertRegex(fam["models"]["IST-DAS-2.25bpw"]["hf"], r"helcig/tmp-oct26-2/resolve/851709dc[0-9a-f]{32}/2\.25bpw/$") + self.assertRegex(setup.DSV41_SHARED[setup.DSV41_ISTA_ENGRAM], r"ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF/resolve/0d8f49fb[0-9a-f]{32}/$") + self.assertRegex(fam["models"]["IST-DAS-2.25bpw"]["hf"], r"ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF/resolve/0d8f49fb[0-9a-f]{32}/$") def test_shipped_profiles_match_their_hashes(self): import hashlib @@ -359,7 +362,7 @@ class OfficialSets(unittest.TestCase): def test_the_pack_recipe_is_the_plain_one(self): folder, pack = Path("/m/set"), Path("/d/pack") - names = [f"model-2.00bpw-{i:05d}-of-00004.gguf" for i in range(1, 5)] + names = [f"DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-{i:05d}-of-00004.gguf" for i in range(1, 5)] cmd = setup.dsv41_pack_cmd(folder, names, Path("/s/engram-IQ4_NL.gguf"), Path("/s/meta.gguf"), Path("/s/dspark.gguf"), pack) self.assertTrue(cmd[1].endswith("pack_gguf.py")) self.assertEqual(cmd[2:], ["--model", str(folder), "--shards", *names, "--engram", str(Path("/s/engram-IQ4_NL.gguf")), @@ -418,6 +421,53 @@ class SharedFiles(unittest.TestCase): self.assertEqual(got, f) +class LegacyFiles(unittest.TestCase): + """Files of the first release (model-2.00bpw-0000N-of-00004.gguf, engram-IQ4_NL.gguf, often in a 2.00bpw/ folder) are the same weights: accepted.""" + + def test_the_old_pins_are_the_old_files_and_the_unchanged_shards_match_today_s(self): + for i in (2, 3, 4): # same bytes: same size and SHA-256 under both names + new = setup.DSV41_ISTA_SHARD.format(quant="IQ2_XXS", i=i) + self.assertEqual(setup.DSV41_ALL_FILES[new], setup.DSV41_LEGACY_FILES["model-2.00bpw-%05d-of-00004.gguf" % i]) + new = setup.DSV41_ISTA_SHARD.format(quant="IQ2_XS", i=i) + self.assertEqual(setup.DSV41_ALL_FILES[new], setup.DSV41_LEGACY_FILES["model-2.25bpw-%05d-of-00004.gguf" % i]) + self.assertNotEqual(setup.DSV41_ALL_FILES[setup.DSV41_ISTA_SHARD.format(quant="IQ2_XXS", i=1)], + setup.DSV41_LEGACY_FILES["model-2.00bpw-00001-of-00004.gguf"]) # shard 1 and the Engram differ in their header only + self.assertNotIn("model-2.00bpw-00001-of-00004.gguf", setup.DSV41_ISTA_FILES) # (never downloaded under the old names) + self.assertNotIn("model-2.00bpw-00001-of-00004.gguf", setup.REPO_PINS["ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF"]) + + def test_pick_prefers_today_s_name_then_the_old_one(self): + with tempfile.TemporaryDirectory() as d: + folder = Path(d) + new = setup.DSV41_ISTA_SHARD.format(quant="IQ2_XXS", i=2) + self.assertEqual(setup.dsv41_pick(folder, new), folder / new) # nothing there: where it will be downloaded + (folder / "model-2.00bpw-00002-of-00004.gguf").write_bytes(b"x") + self.assertEqual(setup.dsv41_pick(folder, new).name, "model-2.00bpw-00002-of-00004.gguf") + (folder / new).write_bytes(b"y") + self.assertEqual(setup.dsv41_pick(folder, new).name, new) + + def test_the_folder_of_the_first_release_is_found_from_the_parent(self): + with tempfile.TemporaryDirectory() as d: + sub = Path(d) / "2.00bpw" + sub.mkdir() + (sub / "model-2.00bpw-00001-of-00004.gguf").write_bytes(b"x") + fam = setup.MULTI_FILE_FAMILIES["deepseek41"] + a = argparse.Namespace(gguf_dir=d, models_dir=d) + self.assertEqual(setup.dsv41_folder(a, fam, "t", "IST-DAS-2.00bpw"), sub) + a2 = argparse.Namespace(gguf_dir=str(sub), models_dir=d) + self.assertEqual(setup.dsv41_folder(a2, fam, "t", "IST-DAS-2.00bpw"), sub) + + def test_the_old_engram_name_is_found(self): + with tempfile.TemporaryDirectory() as d: + sub = Path(d) / "2.00bpw" + sub.mkdir() + old = sub / "engram-IQ4_NL.gguf" + old.write_bytes(b"e") + a = argparse.Namespace(gguf_dir=d) + with mock.patch.dict(setup.DSV41_ALL_FILES, {"engram-IQ4_NL.gguf": (1, "0" * 64)}): + got = setup.dsv41_find_shared(a, setup.DSV41_ISTA_ENGRAM, sub, Path(d) / "shared") + self.assertEqual(got, old) + + class InstallOfficial(Install): """install_dsv41 for an official set, the engine and the tools mocked.""" @@ -438,10 +488,11 @@ class InstallOfficial(Install): get = [c for c in self.calls if c[0] == "get"] folder = self.root / "models" / "deepseek-v4.1-flash-IST-DAS-2.00bpw" shared = self.root / "models" / "deepseek-v4.1-flash-shared" - self.assertEqual([c[2] for c in get][:4], [folder / f"model-2.00bpw-{i:05d}-of-00004.gguf" for i in range(1, 5)]) + self.assertEqual([c[2] for c in get][:4], [folder / f"DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-{i:05d}-of-00004.gguf" for i in range(1, 5)]) self.assertEqual([c[2] for c in get][4:], [shared / setup.DSV41_ISTA_ENGRAM, shared / setup.DSV41_SHARD.format(i=1), shared / setup.DSV41_DSPARK]) - self.assertTrue(get[0][1].endswith("/2.00bpw/model-2.00bpw-00001-of-00004.gguf")) + self.assertTrue(get[0][1].endswith("/DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XXS-00001-of-00004.gguf")) + self.assertNotIn("/2.00bpw/", get[0][1]) # the repository is flat self.assertEqual(sum(1 for c in self.calls if c[0] == "sha"), 7) pack = [c for c in self.calls if c[0] == "run"][-1][1] self.assertIn("--engram-meta", pack) @@ -459,7 +510,7 @@ class InstallOfficial(Install): rc, out = self.install_ista(model="IST-DAS-2.25bpw") self.assertEqual(rc, 0, out) got = [c[2].name for c in self.calls if c[0] == "get"] - self.assertEqual(got, [f"model-2.25bpw-{i:05d}-of-00004.gguf" for i in range(1, 5)]) # only the four shards + self.assertEqual(got, [f"DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XS-{i:05d}-of-00004.gguf" for i in range(1, 5)]) # only the four shards def test_pack_info_profile_smoke_and_the_launch_flags(self): rc, out = self.install_ista() From 4ebba26767514c6af1856dd6a6ab1f209d14d93d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:25:23 +0200 Subject: [PATCH 27/34] pack_gguf: an Engram file ('engram' or 'deepseek41-engram') is never taken for a model shard or for the model's metadata; real header fixture and tests; setup test: the first release's files are packed as they are with no shard download --- tests/fixtures/dsv41/engram-final-header.gguf | Bin 0 -> 416 bytes tests/terminal/test_pack_gguf_engram.py | 60 ++++++++++++++++++ tools/dsv41/pack_gguf.py | 23 ++++++- tools/test_setup_dsv41.py | 24 +++++++ 4 files changed, 104 insertions(+), 3 deletions(-) create mode 100644 tests/fixtures/dsv41/engram-final-header.gguf create mode 100644 tests/terminal/test_pack_gguf_engram.py diff --git a/tests/fixtures/dsv41/engram-final-header.gguf b/tests/fixtures/dsv41/engram-final-header.gguf new file mode 100644 index 0000000000000000000000000000000000000000..1a0d28f4c4fa6d355615d2aa8ee263331b4f32da GIT binary patch literal 416 zcmah_%Sy#C5Usj#;YJj>?y?lY(B9i(i(B;~h#=znGHH%Y=_4gg(WO7&NBCtf`~-i% zrVkWccpx(q&Ya1~tk;j%JD%rl_s7B24u@m%GSo0sax$sPEmGSV?DpLL#7m%Qfg%jf zP-lj!#UFx?1aEa`(m{MO^#p?8Bk^G_W!CgCMYe0 zt})veWx<2V`39Ac{26(s?69Y;@xjH*=aH-CUAg+$g&u=G{Aa-F`_F*ax37=AQTsc7 E1CLl;EdT%j literal 0 HcmV?d00001 diff --git a/tests/terminal/test_pack_gguf_engram.py b/tests/terminal/test_pack_gguf_engram.py new file mode 100644 index 00000000..17848fa2 --- /dev/null +++ b/tests/terminal/test_pack_gguf_engram.py @@ -0,0 +1,60 @@ +"""pack_gguf must never take an Engram file's metadata for the model's: ISTA-DASLab's final Engram says general.architecture 'deepseek41-engram' +(the first release's said 'engram'). The fixture is the real header of DeepSeek-V4.1-Flash-Engram-IQ4_NL.gguf (its 416 bytes: metadata and the tensor +directory, no data).""" +from __future__ import annotations + +import struct +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tools" / "dsv41")) +import pack_gguf as PG # noqa: E402 + +FIXTURE = ROOT / "tests" / "fixtures" / "dsv41" / "engram-final-header.gguf" + + +def tiny_gguf(path: Path, arch: str, extra: dict | None = None) -> Path: + """A GGUF with only metadata (string and uint32 values), no tensors.""" + kv = {"general.architecture": arch, **(extra or {})} + out = bytearray(b"GGUF" + struct.pack("= need else "%s: %d of %d bytes" % (g.path.name, have, need) +def is_engram_file(g) -> bool: + """The Engram table's GGUF: general.architecture 'engram' (the first release) or 'deepseek41-engram' (ISTA-DASLab's final files).""" + arch = str(g.kv.get("general.architecture") or "") + return arch == "engram" or arch.endswith("-engram") + + +def model_kv(gs): + """The metadata of the model: of the first group whose architecture IS deepseek41 - never an Engram file's, whatever order they come in.""" + return next((g.kv for g in gs if g.kv.get("general.architecture") == "deepseek41"), None) + + def engram_set(model: pathlib.Path, explicit: str | None): """The Engram tables' GGUF set for a quant that leaves them out: (its folder, its files read), or (None, []). explicit (--engram): that folder, whole; else the first whole one of ENGRAM_SETS beside the quant or in its @@ -427,9 +438,15 @@ def main() -> int: raise SystemExit("%s: no .gguf files" % model if not shards else "%s: not there" % next(p for p in shards if not p.is_file())) gs = [Gguf(p) for p in shards] - kv = next((g.kv for g in gs if "general.architecture" in g.kv), None) - if kv is None or kv["general.architecture"] not in ("deepseek41",): - raise SystemExit("%s: not a DeepSeek-V4.1 GGUF (architecture %r)" % (model, kv and kv.get("general.architecture"))) + if not a.shards: # a folder's *.gguf: the Engram table (architecture 'engram', today 'deepseek41-engram') is not a model shard + keep = [i for i, g in enumerate(gs) if not is_engram_file(g)] + shards, gs = [shards[i] for i in keep], [gs[i] for i in keep] + if not gs: + raise SystemExit("%s: no model shards (only an Engram table)" % model) + kv = model_kv(gs) + if kv is None: + arch = next((g.kv.get("general.architecture") for g in gs), None) + raise SystemExit("%s: not a DeepSeek-V4.1 GGUF (architecture %r)" % (model, arch)) split = int(kv.get("split.count", 1)) if split != len(shards): counts = sorted({m.group(1) for m in (re.search(r"-of-(\d{5})\.gguf$", p.name) for p in shards) if m}) diff --git a/tools/test_setup_dsv41.py b/tools/test_setup_dsv41.py index 6d951379..c7b7446b 100644 --- a/tools/test_setup_dsv41.py +++ b/tools/test_setup_dsv41.py @@ -512,6 +512,30 @@ class InstallOfficial(Install): got = [c[2].name for c in self.calls if c[0] == "get"] self.assertEqual(got, [f"DeepSeek-V4.1-Flash-1017-GSQ-RCO-IQ2_XS-{i:05d}-of-00004.gguf" for i in range(1, 5)]) # only the four shards + def test_the_first_releases_files_are_used_as_they_are_nothing_is_downloaded_but_the_small_files(self): + own = self.root / "own" + sub = own / "2.00bpw" + sub.mkdir(parents=True) + for i in range(1, 5): + (sub / f"model-2.00bpw-{i:05d}-of-00004.gguf").write_bytes(b"GGUF") + (sub / "engram-IQ4_NL.gguf").write_bytes(b"E") + (own / "dspark").mkdir() + (own / "dspark" / setup.DSV41_DSPARK).write_bytes(b"D") + tiny = {n: (4, "0" * 64) for n in setup.DSV41_LEGACY_FILES if n.startswith("model-2.00bpw")} + tiny["engram-IQ4_NL.gguf"] = (1, "0" * 64) + tiny[setup.DSV41_DSPARK] = (1, "0" * 64) + with mock.patch.dict(setup.DSV41_ALL_FILES, tiny): + rc, out = self.install_ista(gguf_dir=str(own)) + self.assertEqual(rc, 0, out) + got = [c[2].name for c in self.calls if c[0] == "get"] + self.assertEqual(got, [setup.DSV41_SHARD.format(i=1)]) # only the 5.8 MB metadata shard + pack = [c for c in self.calls if c[0] == "run"][-1][1] + shards = pack[pack.index("--shards") + 1:pack.index("--engram")] + self.assertEqual(shards, [f"model-2.00bpw-{i:05d}-of-00004.gguf" for i in range(1, 5)]) # packed from the files as they are + self.assertTrue(pack[pack.index("--engram") + 1].endswith("engram-IQ4_NL.gguf")) + self.assertIn("model", pack[pack.index("--model") + 1] + "model") + self.assertEqual(Path(pack[pack.index("--model") + 1]), sub) + def test_pack_info_profile_smoke_and_the_launch_flags(self): rc, out = self.install_ista() self.assertEqual(rc, 0, out) From afd24ea6ae039255c0983d2a6c6ba415e39bddba Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:27:07 +0200 Subject: [PATCH 28/34] launch: the last lines suggest 'strata launch --stop' (and --save-preset NAME to keep the settings) when no preset was saved; --preset "" only when one exists; tests --- strata_cli/launch/cmd.py | 15 +++++++++++++-- tests/terminal/test_dsv41_tui_items.py | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 6a5042e6..697e99d7 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -542,6 +542,15 @@ def _screens_missing() -> str | None: return next((m for m in ("rich", "textual") if importlib.util.find_spec(m) is None), None) +def final_hint_lines(s, preset_saved: bool) -> list[str]: + """The last lines of a flag launch: how to connect an app and how to stop. `--preset ""` is suggested only when a preset by that name exists + (--preset NAME, or --save-preset NAME); otherwise the plain command, and how to keep the settings.""" + if preset_saved: + return [f" Connect an app: strata connect opencode Stop: strata launch --stop --preset \"{s.name}\""] + return [" Connect an app: strata connect opencode Stop: strata launch --stop", + " To keep these settings for next time, add --save-preset NAME."] + + def _tui(run, *args, **kw) -> int: """Open the screens. An error of the screens themselves ends with a plain sentence and a non-zero exit code, never a traceback and exit 0 (tester report T02).""" @@ -804,7 +813,8 @@ def run_launch(a: argparse.Namespace) -> int: _say(f" {'Anthropic apps':<14} {result.urls[0]} (Claude Code: ANTHROPIC_BASE_URL, no /v1 at the end)") if result.key: from strata_cli.launch import access - _say(f" {'API key':<14} {access.mask_key(result.key)} (show it: strata launch --show-key --preset \"{s.name}\")") + _say(f" {'API key':<14} {access.mask_key(result.key)} (show it: strata launch --show-key" + + (f" --preset \"{s.name}\")" if (a.preset or a.save_preset) else ")")) for n in result.notices: _say(f"[!] {n}") local = next((u for u in result.urls if "127.0.0.1" in u), result.urls[0] if result.urls else "") @@ -816,7 +826,8 @@ def run_launch(a: argparse.Namespace) -> int: _say(f" Watch it: STRATA_API_KEY=$(strata launch --show-key) strata monitor --url {local} --credential-env STRATA_API_KEY") else: _say(f" Watch it: strata monitor --url {local}") - _say(f" Connect an app: strata connect opencode Stop: strata launch --stop --preset \"{s.name}\"") + for line in final_hint_lines(s, bool(a.preset or a.save_preset)): + _say(line) return 0 except store.PresetError as e: return fail(str(e), 2) diff --git a/tests/terminal/test_dsv41_tui_items.py b/tests/terminal/test_dsv41_tui_items.py index 6c99c0db..ab5e584a 100644 --- a/tests/terminal/test_dsv41_tui_items.py +++ b/tests/terminal/test_dsv41_tui_items.py @@ -101,3 +101,19 @@ class Disk(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class FinalHint(unittest.TestCase): + def test_no_preset_means_the_plain_stop_command_and_a_way_to_keep_the_settings(self): + from strata_cli.launch import settings as S + s = S.LaunchSettings(name="IST-DAS-2.00bpw 8K") + lines = cmd.final_hint_lines(s, False) + text = "\n".join(lines) + self.assertIn("strata launch --stop", text) + self.assertNotIn("--preset", text.replace("--save-preset", "")) + self.assertIn("--save-preset NAME", text) + + def test_a_saved_preset_keeps_its_name_in_the_hint(self): + from strata_cli.launch import settings as S + s = S.LaunchSettings(name="Office") + self.assertIn('--stop --preset "Office"', "\n".join(cmd.final_hint_lines(s, True))) From e2361d80d2e646972d8c96cd33557e801fe7b27b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:39:15 +0200 Subject: [PATCH 29/34] DeepSeek-V4.1: slot keep and auto-pin default off (switches STRATA_DS4_SLOT_KEEP=1, STRATA_DS4_AUTO_PIN=1) --- docs/DEEPSEEK41.md | 10 +++++----- serve/server.py | 8 ++++---- serve/test_dsv41.py | 26 ++++++++++++++++---------- 3 files changed, 25 insertions(+), 19 deletions(-) diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 7aefeec4..1be93387 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -70,11 +70,11 @@ The server speaks to the engine as it does for the other models, so `/v1/chat/co server turns them into OpenAI `tool_calls` and Anthropic `tool_use`, including `tool_choice`, streamed arguments and calls written inside the thinking. A value marked `string="true"` stays a string. - Defaults when a request names none: temperature 1.0, top_p 1.0. -- Agents and sub-agents that take turns do not read their prompts again. When another request takes the model, the engine sets the - conversation aside (about 17 MB per 6.5K tokens) and takes it back when the next prompt continues it; the system prompt and tools shared by - an agent and its sub-agents are kept as a checkpoint too. Slots survive a restart, live in `ds4-slots` next to the run log, are capped at - 2 GB and are removed after a week. `STRATA_DS4_SLOT_KEEP=0` turns it off, `STRATA_DS4_SLOT_GB` changes the cap, `STRATA_DS4_AUTO_PIN=0` - turns off the shared-start checkpoint. The answers are the same as a fresh read of the prompt. +- Agents and sub-agents that take turns can skip reading their prompts again (off in this version, a switch for testing). With + `STRATA_DS4_SLOT_KEEP=1` the engine sets a conversation aside when another request takes the model (about 17 MB per 6.5K tokens) and takes it + back when the next prompt continues it, also after a restart. Slots live in `ds4-slots` next to the run log, are capped at 2 GB + (`STRATA_DS4_SLOT_GB`) and are removed after a week. `STRATA_DS4_AUTO_PIN=1` also keeps the system prompt and tools shared by an agent + and its sub-agents as a checkpoint. Pictures and the DSpark drafter are in the engine (strata-dsv41 reads them from the unsloth mmproj and dspark files beside the model; the server side is not wired yet). Not in this version: several requests at once (`--parallel` is ignored with a note), tuning (`--tune` is skipped with a note). diff --git a/serve/server.py b/serve/server.py index fdfd5949..ee6e37e7 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3477,7 +3477,7 @@ def hip_auto_devices(cfg: dict, env: dict) -> list[int] | None: return visible -DS41_SLOT_KEEP_DEFAULT = "1" # the engine keeps a displaced conversation in RAM and in the slot folder (see below) +DS41_SLOT_KEEP_DEFAULT = "0" # the engine keeps a displaced conversation in RAM and in the slot folder (see below) DS41_SLOT_GB_DEFAULT = "2" # the folder's cap in GB (a 6.5K-token conversation is about 17 MB) @@ -3486,7 +3486,7 @@ def deepseek_slot_env(env: dict, cfg: dict) -> None: at its checkpoints (agents and sub-agents that take turns do not read their prompts again). STRATA_DS4_SLOT_KEEP switches it (the default above; a config's env or the shell wins); the folder is `ds4-slots` next to the run log, in Strata's data folder (STRATA_DS4_SLOT_DIR names another), and the engine caps it (STRATA_DS4_SLOT_GB, 2 here, 16 in the engine) and - removes what is older than a week or not this model's. On by default; STRATA_DS4_SLOT_KEEP=0 turns it off.""" + removes what is older than a week or not this model's. Off by default (0.2.4); STRATA_DS4_SLOT_KEEP=1 turns it on.""" env.setdefault("STRATA_DS4_SLOT_KEEP", DS41_SLOT_KEEP_DEFAULT) env.setdefault("STRATA_DS4_SLOT_GB", DS41_SLOT_GB_DEFAULT) log = cfg.get("log") @@ -4926,8 +4926,8 @@ class Service: """DeepSeek-V4.1 only: how many leading messages are the system prompt (its tools are rendered with them). An agent and its sub-agents that work behind the same system prompt and tools share exactly this start, so the engine keeps a checkpoint of its state there (pin=N): the next agent behind the same start goes back to it - instead of reading it again. 0: none (STRATA_DS4_AUTO_PIN=0, no system message, or nothing after it).""" - if os.environ.get("STRATA_DS4_AUTO_PIN", "1") == "0": + instead of reading it again. 0: none (off unless STRATA_DS4_AUTO_PIN=1, no system message, or nothing after it).""" + if os.environ.get("STRATA_DS4_AUTO_PIN", "0") != "1": return 0 n = 0 for m in messages: diff --git a/serve/test_dsv41.py b/serve/test_dsv41.py index 15315ee5..f623f5ba 100644 --- a/serve/test_dsv41.py +++ b/serve/test_dsv41.py @@ -530,6 +530,7 @@ class Api(unittest.TestCase): # -- the shared start of an agent's and its sub-agents' prompts (the engine keeps its state there) ------------ def test_the_system_prompt_and_tools_are_the_shared_start(self): self.start("ok") + self.auto_pin("1") sysmsg = {"role": "system", "content": "You are an agent. " * 20} body = {"messages": [sysmsg, {"role": "user", "content": "task one"}], "tools": [WEATHER], "max_tokens": 40} self.assertEqual(self.post("/v1/chat/completions", body)[0], 200) @@ -544,24 +545,29 @@ class Api(unittest.TestCase): self.assertEqual(self.engine.last_sampling["strata_prefix"]["tokens"], n) self.assertEqual(self.engine.last_prompt[:n], ids[:n]) + def auto_pin(self, value): + old = os.environ.get("STRATA_DS4_AUTO_PIN") + if value is None: + os.environ.pop("STRATA_DS4_AUTO_PIN", None) + else: + os.environ["STRATA_DS4_AUTO_PIN"] = value + self.addCleanup(lambda: os.environ.pop("STRATA_DS4_AUTO_PIN", None) if old is None + else os.environ.__setitem__("STRATA_DS4_AUTO_PIN", old)) + def test_no_shared_start_without_a_system_prompt_or_when_switched_off(self): self.start("ok") + self.auto_pin("1") self.chat() - self.assertNotIn("strata_prefix", self.engine.last_sampling) + self.assertNotIn("strata_prefix", self.engine.last_sampling) # no system message body = {"messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], "max_tokens": 40} - old = os.environ.get("STRATA_DS4_AUTO_PIN") - os.environ["STRATA_DS4_AUTO_PIN"] = "0" - try: + for off in (None, "0"): # off by default, and when switched off + self.auto_pin(off) self.post("/v1/chat/completions", body) self.assertNotIn("strata_prefix", self.engine.last_sampling) - finally: - if old is None: - os.environ.pop("STRATA_DS4_AUTO_PIN", None) - else: - os.environ["STRATA_DS4_AUTO_PIN"] = old def test_a_clients_own_prefix_wins(self): self.start("ok") + self.auto_pin("1") body = {"messages": [{"role": "system", "content": "s " * 30}, {"role": "user", "content": "u"}], "max_tokens": 40, "strata_prefix": {"tokens": 7}} self.post("/v1/chat/completions", body) @@ -592,7 +598,7 @@ class SlotEnv(unittest.TestCase): def test_deepseek_gets_a_folder_in_the_data_folder_and_the_default_switch(self): env = self.env({"arch": "deepseek41", "log": str(Path("data") / "strata-deepseek.log"), "args": []}) self.assertEqual(Path(env["STRATA_DS4_SLOT_DIR"]), Path("data") / "ds4-slots") - self.assertEqual(env["STRATA_DS4_SLOT_KEEP"], "1") + self.assertEqual(env["STRATA_DS4_SLOT_KEEP"], "0") self.assertEqual(env["STRATA_DS4_SLOT_GB"], "2") def test_the_configs_own_settings_win(self): From fa3252ad5de1526fbcdd6757c538767f0fc74895 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:43:35 +0200 Subject: [PATCH 30/34] dsv41 serve: with slots off the loop is as before (no anchor copy, same continuation test on an empty engine) --- src/dsv41/ds4_main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/dsv41/ds4_main.cpp b/src/dsv41/ds4_main.cpp index 92c15d0f..a55b717e 100644 --- a/src/dsv41/ds4_main.cpp +++ b/src/dsv41/ds4_main.cpp @@ -678,7 +678,7 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c // the conversation continues, reused in place - a conversation has to be in the model first: a fresh engine // (the start of a run, so every restart) holds 0 tokens, and every prompt "continues" that to token 0; taken // as a continuation, the take below would never run for the folder's conversations, the case they are for - if (n_state > 0 && c == n_state && n_state < r.ids.size()) { + if ((n_state > 0 || slot_max <= 0) && c == n_state && n_state < r.ids.size()) { // (slots off: as before) from = n_state; continued = true; } @@ -790,7 +790,7 @@ int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float c } held = std::move(pics); m.checkpoint(0); - if (!continued) m.pin(); // (a new run of prompts: where it may be rendered again from) + if (!continued && slot_max > 0) m.pin(); // (a new run of prompts: where it may be rendered again from) const double t1 = now_ms(); long long produced = 0; const char* finish = "length"; From 624a226d13e78e708a0946b899767b326546fa87 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:30:38 +0200 Subject: [PATCH 31/34] dsv41 store zero-copy: clear the device's zc_tab entry when VRAM takes an expert over (a stale pointer into a reused slot made zc_stage copy another expert's blob into the plan: garbage, NaN routing, illegal access) --- src/dsv41/ds4_model.cu | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index bc29b69d..29c2f48d 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -5503,6 +5503,11 @@ struct Model::Impl { l.slot[(size_t) sw.in] = l.spare_vram; if (!l.zc.empty() && l.zc[(size_t) sw.in]) { // (VRAM's now: not the store's to compute any more) l.zc[(size_t) sw.in] = 0; + if (l.zc_tab != nullptr) { // (the device's table too: its entry pointed into the slot the store now reuses - when `in` left VRAM later, + // zc_stage copied whatever lay there, another expert's blob, into the plan) + cudaSetDevice(devs[0].id); + cudaMemsetAsync(l.zc_tab + sw.in, 0, 8, devs[0].st); + } store->unmark(l.il, sw.in); } if (l.nm == 1) set_vm(l, sw.in, l.spare_vram); From d50da4e3a146b509f40bfcc39efde606e7981ec7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:48:18 +0200 Subject: [PATCH 32/34] release notes: the run-to-run difference is near-tied words, not only expert placement --- docs/release-notes-0.2.4.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index 8b09b94c..eabe3b5b 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -53,7 +53,7 @@ These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so e - DSpark is off on PCs where the CPU is the limit. - Not in this release: Mac and Strix Halo. DeepSeek V4.1-Flash does not run there yet. - Output on 12 GB cards is 4 to 8 tokens/s. That is usable for chat and slow for long agent runs. -- The answers can differ from run to run with the same prompt when experts move between the card and the CPU. The cause is which experts sit on the card at that moment. +- The same prompt can give a slightly different answer from one run to the next. At some words the model's top choices are nearly tied, and small differences in how the numbers are added up decide between them. ## Updating From 4f8770d13ea210279d73cc57ada14d6497da099d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:52:08 +0200 Subject: [PATCH 33/34] release notes: R9700 prompt numbers with the new kernels (4 cards 8K about 320, 32K about 750) --- docs/release-notes-0.2.4.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index eabe3b5b..67dec502 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -26,7 +26,7 @@ Output is the speed of the answer. Prompt is how fast Strata reads what you send | RTX 5070 12 GB, 64 GB RAM | about 5 tokens/s (code) | 231 tokens/s at 8K | | RTX 3060 12 GB, 46 GB RAM | about 6 to 9 tokens/s (6.1-6.7 without DSpark, 8.2-8.7 with) | about 103 tokens/s at 8K | | 1x Radeon AI PRO R9700 (AMD), IQ2_XS | about 11 tokens/s | not measured | -| 4x Radeon AI PRO R9700 (AMD) | about 31 tokens/s (55 to 69 with DSpark) | about 360 tokens/s at 8K, 557 at 32K | +| 4x Radeon AI PRO R9700 (AMD) | about 31 tokens/s (55 to 69 with DSpark) | about 320 tokens/s at 8K, about 750 at 32K | These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so expect it to be a little slower. Your drive matters: the 12 GB cards spend most of each token waiting on the SSD and on the CPU, and a slow NVMe drive lowers every number above. @@ -35,6 +35,7 @@ These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so e - **A RAM expert store that sizes itself.** The model is a mixture of experts: each token uses a few of thousands of small blocks. Strata keeps the busiest ones in RAM, takes whatever RAM is free, and reads the rest from the SSD with direct reads. On the RTX 5070 PC with 64 GB this gave 4.3 to 4.9 tokens/s where memory-mapping the files gave 1.8 to 2.2. - **Hot-expert profiles ship with the engine,** so the first prompts do not start cold. - **Faster prompts.** The engine now reads long prompts layer by layer in big chunks instead of 16 tokens at a time. A 200-token prompt went from 3.6 to 6.4 tokens/s on the RTX 5070 PC, and 8K prompts reach 231 tokens/s. +- **Faster prompts on Radeon AI PRO R9700.** New matrix-core kernels (RDNA4) read prompts about 64% faster at 8K and 69% faster at 32K on 4 cards (196 to 320 and 445 to 755 tokens/s), and about 22% faster at 8K on one card. Answer speed does not change. They are on by default on these cards. - **Faster long prompts.** A prompt over about 3,700 tokens skips work that the last 20 layers cannot use (a 16K prompt is about 34% faster). In the 799 positions we compared, the model's top choice for the next word was the same with and without the skip in 99.75% of them. - **Thinking budget.** When neither your request nor your config sets one, DeepSeek thinks for at most 32,768 tokens. A request can set its own budget; 0 turns the limit off. - **DSpark** (a small draft model from Unsloth) is on where it measured faster and off on CPU-bound PCs. On the RTX 3060 PC (20 threads) it raised decode from 6.1-6.7 to 8.2-8.7 tokens/s. On the 4x R9700 box it raised 31 tokens/s to 55 to 69. On the RTX 5070 PC with a 6-core Ryzen 5 7600 it gave no gain at any setting (code 4.64 tokens/s with it off against 4.33 at best with it on; agent 3.41 against 2.86 to 3.21), because checking the drafts costs the CPU about what the saved tokens are worth. There `--dspark auto` does not load the drafter. From eec705cc98949fb1eb1cea13433ba5f6617889ae Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 01:58:45 +0200 Subject: [PATCH 34/34] release notes: the prompt-skip agreement at the final tip, 99.5% of 799 positions --- docs/release-notes-0.2.4.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.4.md b/docs/release-notes-0.2.4.md index 67dec502..9c483298 100644 --- a/docs/release-notes-0.2.4.md +++ b/docs/release-notes-0.2.4.md @@ -36,7 +36,7 @@ These are the 2.00-bit set. The 2.25-bit set reads 13% more data per token, so e - **Hot-expert profiles ship with the engine,** so the first prompts do not start cold. - **Faster prompts.** The engine now reads long prompts layer by layer in big chunks instead of 16 tokens at a time. A 200-token prompt went from 3.6 to 6.4 tokens/s on the RTX 5070 PC, and 8K prompts reach 231 tokens/s. - **Faster prompts on Radeon AI PRO R9700.** New matrix-core kernels (RDNA4) read prompts about 64% faster at 8K and 69% faster at 32K on 4 cards (196 to 320 and 445 to 755 tokens/s), and about 22% faster at 8K on one card. Answer speed does not change. They are on by default on these cards. -- **Faster long prompts.** A prompt over about 3,700 tokens skips work that the last 20 layers cannot use (a 16K prompt is about 34% faster). In the 799 positions we compared, the model's top choice for the next word was the same with and without the skip in 99.75% of them. +- **Faster long prompts.** A prompt over about 3,700 tokens skips work that the last 20 layers cannot use (a 16K prompt is about 34% faster). In 99.5% of the 799 positions we compared, the model's top choice for the next word was the same with and without the skip. - **Thinking budget.** When neither your request nor your config sets one, DeepSeek thinks for at most 32,768 tokens. A request can set its own budget; 0 turns the limit off. - **DSpark** (a small draft model from Unsloth) is on where it measured faster and off on CPU-bound PCs. On the RTX 3060 PC (20 threads) it raised decode from 6.1-6.7 to 8.2-8.7 tokens/s. On the 4x R9700 box it raised 31 tokens/s to 55 to 69. On the RTX 5070 PC with a 6-core Ryzen 5 7600 it gave no gain at any setting (code 4.64 tokens/s with it off against 4.33 at best with it on; agent 3.41 against 2.86 to 3.21), because checking the drafts costs the CPU about what the saved tokens are worth. There `--dspark auto` does not load the drafter. - **Faster CPU rows.** The engine has new exact rows for the experts the CPU computes: AVX-512 on Zen 4 and Zen 5, AVX2 on other CPUs, chosen automatically. On the Ryzen 5 7600 PC with an RTX 5070 (2.00 set, DSpark on, three alternating pairs, identical text in all six runs), decode went from 4.08 to 5.11 tokens/s (+25%) and prompt reading rose 26%. This was measured on one CPU, a Zen 4. Zen 5 gained more in the kernel tests.