Merge branch 'f-dsv41-tune' into f-024-rel

This commit is contained in:
Niko1221 committed 2026-10-24 01:13:51 +02:00
commit a3f76dfd63
15 files changed
+493 -37

No files matched your search

+33 -2
View File
@@ -71,8 +71,39 @@ 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.
### 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-<version>-<system>-<backend>-<variant>.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
+46 -15
View File
@@ -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)
@@ -7698,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
@@ -7913,14 +7942,14 @@ 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")
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
@@ -7928,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}")
@@ -8358,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: <data folder>/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: "
"<name>-00001-of-0000N.gguf ... -0000N-of-0000N.gguf)")
ap.add_argument("--yes", action="store_true", help="accept the recommended answers")
@@ -9127,8 +9158,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")
+8 -2
View File
@@ -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 = ""
+2
View File
@@ -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:
+20 -2
View File
@@ -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:
@@ -531,6 +535,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 +679,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)
+39
View File
@@ -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
+50 -10
View File
@@ -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:
@@ -1263,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
@@ -1828,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
@@ -1856,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.")
+9 -3
View File
@@ -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))
+1
View File
@@ -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
+81
View File
@@ -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)."""
+69
View File
@@ -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()
+103
View File
@@ -0,0 +1,103 @@
"""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 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
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()
+12
View File
@@ -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))
+5
View File
@@ -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
+15 -3
View File
@@ -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":