diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 14099136..212a9e2d 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -88,6 +88,12 @@ The server speaks to the engine as it does for the other models, so `/v1/chat/co Not in this version: several requests at once (`--parallel` is ignored with a warning) and pictures (`--vision` is ignored with a warning). +## Speed: Faster or Full quality + +DeepSeek picks 6 experts for every word it writes. **Faster** uses 5 of them (engine flag `--experts 5`): a small quality change, usually not noticeable, and answers come sooner. It is the default on a PC whose graphics cards total 16 GiB or less: the engine decides that itself (`--experts auto`), and Strata passes `--experts` only when you choose. **Full quality** uses all 6 (`--experts 6`). + +The choice needs the DeepSeek engine 0.1.50 or newer (0.1.49.2 does not take `--experts`); with an older engine the step and the plan line are left out and nothing is passed. In `strata launch` the guided screens have a Speed step for DeepSeek; with flags use `--speed faster|full`, or `--full-quality` in scripts. `strata launch --plan` shows which one this PC gets. + ## 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 diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index 058239ed..f27dab0e 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -24,11 +24,11 @@ from strata_cli.launch import store from strata_cli.launch.catalog import Catalog from strata_cli.launch.runner import Cancelled, Event, LaunchError, Result, Runner, read_config from strata_cli.launch.screens import (AccessScreen, AdvancedScreen, CardsScreen, ConfirmScreen, ContextScreen, FolderScreen, - ModelScreen, ParallelScreen, PicturesScreen, RunScreen, SaveScreen, StartScreen, + ModelScreen, ParallelScreen, PicturesScreen, RunScreen, SaveScreen, SpeedScreen, StartScreen, TuningScreen, flow_for) from strata_cli.launch.widgets import CSS, Glyphs -SCREENS = {"model": ModelScreen, "cards": CardsScreen, "folder": FolderScreen, "context": ContextScreen, "pictures": PicturesScreen, +SCREENS = {"model": ModelScreen, "cards": CardsScreen, "folder": FolderScreen, "context": ContextScreen, "pictures": PicturesScreen, "speed": SpeedScreen, "parallel": ParallelScreen, "tuning": TuningScreen, "advanced": AdvancedScreen, "access": AccessScreen, "save": SaveScreen} diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 8df981b9..99b49a2d 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -105,6 +105,10 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] help="which drafter guesses words ahead to make answers faster: auto (recommended: Strata picks from what it measured on cards like yours; " "that is the MTP today), mtp, dflash2 (Qwen3.8-Flash-Next only; downloads a 1.2 GB drafter once) or off. If DFlash2 cannot run " "(not enough graphics memory, or a model it is not for) the MTP is used and the start says why") + g.add_argument("--speed", type=_choice("a speed", S.SPEED_MODES), metavar="faster|full", + help="DeepSeek: faster uses 5 of 6 experts per word (a small quality change, usually not noticeable; the default on a PC with 16 GB " + "of graphics memory or less), full uses all 6") + g.add_argument("--full-quality", action="store_true", help="DeepSeek: all 6 experts per word (the same as --speed full), for scripts") g.add_argument("--gpu", metavar="LIST", help="graphics card numbers to use, e.g. 0 or 0,1 (default: the engine's choice)") g.add_argument("--gpu-roles", metavar="LIST", help="a role for each graphics card: main, helper or off, e.g. 1=main,0=helper (cards you do not name are off). " "Main does the last steps of every answer; a helper holds part of the model") @@ -233,6 +237,12 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet s.mtp = a.mtp if a.drafting: s.drafting = a.drafting + if getattr(a, "full_quality", False): + if getattr(a, "speed", None) == "faster": + notices.append(S.Notice("warn", "--full-quality and --speed faster were both given; full quality is used.", "")) + s.speed = "full" + elif getattr(a, "speed", None): + s.speed = a.speed if a.gpu and getattr(a, "gpu_roles", None): raise ValueError("Use --gpu (which cards) or --gpu-roles (a role for each card), not both.") if a.gpu: @@ -337,6 +347,9 @@ def apply_defaults(s: S.LaunchSettings, catalog) -> tuple[S.LaunchSettings, list if s.vision not in (None, "off"): notices.append(S.Notice("warn", "DeepSeek-V4.1-Flash cannot read pictures in this Strata version, so pictures are off.", "")) s.vision = "off" # (tuning is DeepSeek's own short tune: tools/dsv41/tune.py, run by the launch) + elif s.speed: + notices.append(S.Notice("warn", "--speed and --full-quality are for DeepSeek; this model uses all its experts, so they are not used.", "")) + s.speed = None notices += S.check_context(s, max_fit_tokens=None) if s.access != "local" and not s.api_key and not s.no_key: from strata_cli.launch import access @@ -694,7 +707,7 @@ def run_launch(a: argparse.Namespace) -> int: s, notices = settings_from_args(a, catalog) if not machine: _interrupted_move_notice() - 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) + 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 or getattr(a, "speed", None) or getattr(a, "full_quality", False)) 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 @@ -756,6 +769,8 @@ def run_launch(a: argparse.Namespace) -> int: _say(f" download {(plan.get('download') or {}).get('text', '')}") if plan.get("drafting"): _say(f" drafting {plan['drafting'].replace('Drafting: ', '', 1)}") + if plan.get("speed"): + _say(f" speed {plan['speed'].replace('Speed: ', '', 1)}") _placement_lines(plan.get("placement")) _say(f" tuning {s.tune} access {S.ACCESS_WORDS[s.access]}, port {s.port}" + (" API key on" if s.api_key else "")) @@ -824,6 +839,14 @@ def run_launch(a: argparse.Namespace) -> int: from strata_cli.launch import access _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 ")")) + speed_line = "" + if hasattr(runner, "speed_line"): + from strata_cli.launch.runner import experts_from_log + speed_line = runner.speed_line(experts_from_log(_engine_log_of(result.config) or None)) + if not isinstance(speed_line, str): + speed_line = "" + if speed_line: + _say(f" {'Speed':<14} {speed_line.replace('Speed: ', '', 1)}") engine_log = _engine_log_of(result.config) if engine_log: _say(f" {'Engine log':<14} {engine_log} (follow it: strata logs --follow)") diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 73f4d180..76a4a6bd 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -398,7 +398,79 @@ def cards_for_launch(s: S.LaunchSettings, catalog, ram_gb: float | None = None, return None -def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str], log: str | None = None, gpus: "list[int] | dict | None" = None) -> dict: +EXPERTS_MIN_ENGINE = (0, 1, 50) # the first DeepSeek engine that accepts --experts (0.1.49.2, the one shipped before, does not) + + +def dsv41_engine_version(exe) -> tuple: + """The version of a DeepSeek engine: from its package folder's name ("0.1.50-windows-x86_64-cuda-cuda13"), else what `--version` prints; + () when neither says.""" + if not exe: + return () + from strata_control import dsv41_engine + folder = Path(str(exe)).parent.name + version = dsv41_engine.version_key(folder) if folder[:1].isdigit() else () + if version: + return version + try: + done = subprocess.run([str(exe), "--version"], capture_output=True, text=True, timeout=10, stdin=subprocess.DEVNULL) + found = re.search(r"(\d+\.\d+\.\d+(?:\.\d+)?)", (done.stdout or "") + (done.stderr or "")) + return tuple(int(x) for x in found.group(1).split(".")) if found else () + except (OSError, subprocess.SubprocessError, ValueError): + return () + + +def engine_takes_experts(exe) -> bool: + """Does this DeepSeek engine accept --experts (0.1.50 or newer)? An engine whose version cannot be told counts as not: nothing is passed, + nothing is shown, no error.""" + return dsv41_engine_version(exe) >= EXPERTS_MIN_ENGINE + + +def used_vram_gb(computer, s: "S.LaunchSettings") -> float: + """Graphics memory (GiB) of the cards this launch uses, summed as the engine sums it: the cards named (--gpu, the Cards step; a role other than + off), else every card that can be used.""" + cards = list(computer.usable_gpus) + chosen = None + if s.gpu_roles: + chosen = {int(k) for k, v in s.gpu_roles.items() if str(v) != "off"} + elif s.gpus: + chosen = {int(g) for g in s.gpus} + if chosen is not None: + cards = [c for c in cards if int(c.get("index", 0)) in chosen] + return sum(float(c.get("vram_gb") or 0) for c in cards) + + +EXPERTS_LINE = re.compile(r"experts per word: (\d+)") + + +def experts_from_log(path) -> int | None: + """The engine's own answer, read back from its startup line "experts per word: N" (the last one in the log), None when it is not there.""" + try: + data = Path(path).read_bytes()[-262144:].decode("utf-8", "replace") + except (OSError, TypeError, ValueError): + return None + found = EXPERTS_LINE.findall(data) + return int(found[-1]) if found else None + + +def apply_experts(cfg: dict, experts: int | None) -> None: + """DeepSeek's speed choice as the engine flag: --experts 5 (Faster) or --experts 6 (Full quality), replacing one already in the saved args.""" + if experts is None or not isinstance(cfg.get("args"), list): + return + args, out, i = [str(x) for x in cfg["args"]], [], 0 + while i < len(args): + if args[i] == "--experts": + i += 2 + continue + if args[i].startswith("--experts="): + i += 1 + continue + out.append(args[i]) + i += 1 + cfg["args"] = out + ["--experts", str(int(experts))] + + +def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str], log: str | None = None, gpus: "list[int] | dict | None" = None, + experts: int | None = None) -> dict: """The private run config of this launch: the installed one plus the choices that are not setup's (host, port, key, cards, advanced).""" from strata_control import tune_knobs cfg = json.loads(json.dumps(base)) @@ -434,6 +506,7 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str] cfg["env"] = tune_knobs.apply_to_env(dict(cfg.get("env") or {}), e_changes) from strata_control import draft_layer draft_layer.apply(cfg) # "mtp": false (from the installed config too) never sits beside --mtp in the saved args (B10) + apply_experts(cfg, experts) return cfg @@ -1286,6 +1359,7 @@ class Runner: cfg = derive_config(base, self.s, bool_flags=tune_knobs.BOOL_FLAGS, log=str(launch_dir() / f"{self.name}.engine.log"), gpus=cards_for_launch(self.s, self.catalog, base=base)) self.use_own_dsv41_engine(cfg) + apply_experts(cfg, self.experts_flag(cfg.get("exe"))) # after the engine is settled: only a 0.1.50+ engine is given --experts wait = self.start_wait() if wait > 600 and not cfg.get("engine_ready_s"): # the server's own wait for the engine (900 s) must not end before the start's cfg["engine_ready_s"] = wait + 60 @@ -1894,11 +1968,53 @@ class Runner: model = {"title": title, "family": s.family, "model": s.model, "model_gb": row.download_gb if row is not None else None, "own_files": bool(s.model_path), "folder": s.model_path} out = {"profile": self.profile, "settings": s.to_dict(with_key=False), "warnings": warns, - "flags": S.flags_text(s), "steps": list(STAGES), "model": model, "download": download, "drafting": self.drafting_plan_line()} + "flags": S.flags_text(s), "steps": list(STAGES), "model": model, "download": download, "drafting": self.drafting_plan_line(), + "speed": self.speed_line()} if self.multi_file(): out["placement"] = self.placement() return out + def resolved_speed(self) -> tuple[str, bool] | None: + """DeepSeek's speed: ("faster" | "full", whether it is the default for this PC); None for any other model. The default is the engine's own + rule (`--experts auto`: 5 when the cards used total 16 GiB or less); only an explicit choice is written as --experts.""" + if not self.multi_file() or not self.speed_engine_ok(): + return None + try: + default = S.faster_default(used_vram_gb(self.catalog.computer(), self.s)) + except Exception: # noqa: BLE001 - when the cards cannot be read, the engine's own default stands + default = False + if self.s.speed in S.SPEED_MODES: + return self.s.speed, (self.s.speed == "faster") == default + return ("faster" if default else "full"), True + + def speed_engine_ok(self, exe=None) -> bool: + """The DeepSeek engine this launch will run takes --experts (0.1.50 or newer; the self-upgrade normally brings it first, but nothing relies + on that). `exe`: the engine a config names; else the one launch finds. No engine yet, or an older one: False, and the Speed choice stays out.""" + if exe is None: + try: + exe = self.dsv41_engine_found()[0] + except Exception: # noqa: BLE001 + exe = None + return engine_takes_experts(exe) + + def experts_flag(self, exe=None) -> int | None: + """The engine's --experts for this launch: 5 or 6 only when the person chose and the engine takes it; None (nothing is passed, the engine's + `--experts auto` decides) when they did not, for an engine that is too old, and for a model that has no such choice.""" + if not self.multi_file() or self.s.speed not in S.SPEED_MODES or not self.speed_engine_ok(exe): + return None + return 5 if self.s.speed == "faster" else 6 + + def speed_line(self, engine_experts: int | None = None) -> str: + """The speed line of --plan and of the summary, in plain words, with the quality note when it is Faster. `engine_experts`: what the + running engine said at its start ("experts per word: N"); it wins over the rule above, so the words are always the engine's.""" + speed = self.resolved_speed() + if speed is None: + return "" + if engine_experts is not None and not self.s.speed: + speed = ("faster" if engine_experts < 6 else "full", True) + text = "Speed: " + S.speed_words(speed[0], speed[1]) + return text + (". " + S.FASTER_NOTE if speed[0] == "faster" else "") + def drafting_plan_line(self) -> str: """The drafting line of --plan: what drafts, or why not what was asked for. Nothing is changed or downloaded.""" from strata_control import drafting diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index a17bbd54..9550c960 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -30,11 +30,33 @@ STEPS = (("model", "Model"), ("cards", "Cards"), ("folder", "Folder"), ("context ("parallel", "Parallel"), ("tuning", "Tuning"), ("advanced", "Advanced"), ("access", "Access"), ("save", "Save")) +STEP_LABELS = {**dict(STEPS), "speed": "Speed"} + + +def speed_choice_available(ctx) -> bool: + """The Speed step is an active choice only when the DeepSeek engine launch will run takes --experts (0.1.50 or newer); otherwise it is not + there, with no error. Asked once per run of the screens (the engine files are looked up once).""" + cached = getattr(ctx, "_speed_ok", None) + if cached is None: + try: + from strata_cli.launch.runner import Runner + cached = bool(Runner(ctx.settings, catalog=ctx.catalog, emit=lambda e: None).speed_engine_ok()) + except Exception: # noqa: BLE001 + cached = False + try: + ctx._speed_ok = cached + except AttributeError: + pass + return cached + + def flow_for(ctx) -> list[str]: - """The steps of this computer: the Cards step exists only when two or more graphics cards can be used.""" + """The steps of this computer: the Cards step exists only when two or more graphics cards can be used; the Speed step only for DeepSeek.""" ids = [sid for sid, _ in STEPS] if len(ctx.computer.usable_gpus) < 2: ids.remove("cards") + if getattr(ctx.settings, "family", None) == "deepseek41" and speed_choice_available(ctx): + ids.insert(ids.index("context") + 1, "speed") return ids @@ -111,7 +133,7 @@ class Base(Screen): out.append("STRATA ", style=f"bold {ACCENT}") out.append(f"{self.title_line}", style=f"bold {ACCENT}") if self.step_id in flow: - labels = dict(STEPS) + labels = STEP_LABELS n = flow.index(self.step_id) if self.width() >= 118: out.append(" ") @@ -1023,6 +1045,44 @@ class PicturesScreen(Base): self.ctx.settings.vision = key +# ------------------------------------------------------------------------------------------------ DeepSeek: speed + +class SpeedScreen(Base): + step_id = "speed" + help_text = ("DeepSeek picks 6 experts for every word it writes. Faster uses 5 of them: answers come sooner, with a small quality change that is " + "usually not noticeable. Full quality uses all 6. Faster is the default on a PC whose graphics cards total 16 GB or less (the engine decides the same way).") + + def body(self) -> ComposeResult: + yield Static(Text("Speed or full quality?", style=f"bold {ACCENT}"), markup=False) + yield Menu(id="menu") + + def default_faster(self) -> bool: + from strata_cli.launch.runner import used_vram_gb + return S.faster_default(used_vram_gb(self.ctx.computer, self.ctx.settings)) + + def on_mount(self) -> None: + s = self.ctx.settings + faster_default = self.default_faster() + here = Cell("default on this PC", "") + items = [Item(["Faster", here if faster_default else Cell("", "")], key="faster"), + Item(["Full quality", here if not faster_default else Cell("", "")], key="full")] + sel = 0 if (s.speed or ("faster" if faster_default else "full")) == "faster" else 1 + self.query_one(Menu).columns = [("", 24), ("", 0)] + self.query_one(Menu).set_items(items, sel) + self.paint() + + def explain(self) -> Text: + key = self.menu().current.key if self.menu() and self.menu().current else "faster" + if key == "faster": + return Text(S.FASTER_NOTE + " It is the default on a PC with 16 GB of graphics memory or less.", style=MUTE) + return Text("Full quality uses all 6 experts per word. Answers are a little slower; pick it when the last bit of quality matters more.", style=MUTE) + + def commit(self) -> None: + key = self.menu().current.key + default = "faster" if self.default_faster() else "full" + self.ctx.settings.speed = None if key == default else key # the default stays "the default for this PC" in a saved preset + + # ------------------------------------------------------------------------------------------------ 6 parallel class ParallelScreen(Base): @@ -1489,9 +1549,12 @@ class SaveScreen(Base): def summary_lines(self) -> list[tuple[str, str]]: s = self.ctx.settings r = next((x for x in self.ctx.rows if (x.family, x.model) == (s.family, s.model)), None) + from strata_cli.launch.runner import used_vram_gb lines = [("Model", (r.title if r else (s.model or "?")) + (" (your files)" if s.model_path else "")), ("Context", S.context_label(s.context) + f", memory {s.kv or 'int8'}"), ("Pictures", "on" if s.vision != "off" else "off"), + *([("Speed", S.speed_words(s.speed or ("faster" if S.faster_default(used_vram_gb(self.ctx.computer, s)) else "full"), + s.speed is None))] if s.family == "deepseek41" and speed_choice_available(self.ctx) else []), ("Parallel", f"{s.parallel} at a time" if s.parallel else f"fit to your card ({S.fit_parallel(self.ctx.computer.main_vram_gb)})"), ("Tuning", ({"quick": "quick (about 5-10 min)", "thorough": "thorough (about 10-15 min)", "skip": "skipped"} if s.family == "deepseek41" else {"quick": "quick (about 20 min)", "thorough": "thorough (up to 2 h)", "skip": "skipped"})[s.tune]), diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index dd175f28..0345ce1b 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -28,6 +28,24 @@ VISION_MODES = ("off", "on", "gpu", "cpu") MTP_MODES = ("on", "off") #: strata_control/drafting.py MODES (tests/terminal/test_drafting.py keeps the two the same) DRAFTING_MODES = ("auto", "mtp", "dflash2", "off") +SPEED_MODES = ("faster", "full") # DeepSeek: 5 experts per word (Faster) or all 6 (Full quality) +FASTER_VRAM_GIB = 16.0 # the engine's rule (src/dsv41/ds4_experts_rule.hpp): `--experts auto` is 5 when the cards used total 16 GiB or less +FASTER_NOTE = "Faster uses 5 of 6 experts per word: a small quality change, usually not noticeable." + + +def faster_default(total_vram_gb: float | None) -> bool: + """Mirrors the engine's `--experts auto`: Faster (5 experts) when the cards the launch uses total 16 GiB (17,179,869,184 bytes) or less. + The engine decides at its start; this only says the same thing in the screens and in --plan, so the two never disagree.""" + # The catalog's vram_gb is already GiB: nvidia-smi's memory.total in MiB / 1024 (setup.py gpus(), tools/strata_mcp.py), an AMD card's bytes / 2**30, + # Windows registry bytes / 2**30. Compared in whole MiB so a 16 GB card (RTX 4080 / 4060 Ti 16 GB: 16376 MiB = 15.99 GiB) counts as 16 GiB or less. + return bool(total_vram_gb) and round(float(total_vram_gb) * 1024) <= round(FASTER_VRAM_GIB * 1024) + + +def speed_words(speed: str, default: bool) -> str: + """The plain words for the chosen speed, for --plan and the summary.""" + if speed == "faster": + return "Faster" + (" (default on this PC)" if default else "") + return "Full quality" + (" (default on this PC)" if default else "") + ": all 6 experts per word" KV_MODES = ("int8", "q4_0", "k8v4", "fp16") DEFAULT_PORT = 8080 @@ -90,6 +108,7 @@ class LaunchSettings: kv: str | None = None # None = int8 above 8K, as setup vision: str | None = None # None = the default (on when the model can read pictures and the engine has the reader), off | on | gpu | cpu parallel: int | None = None # None = fit to the card + speed: str | None = None # DeepSeek only: None = the default for this PC (faster up to 16 GB of graphics memory); faster | full drafting: str | None = None # None = Auto (recommended): the table in strata_control/drafting.py; mtp | dflash2 | off choose one. Saved in the launch config mtp: str | None = None # None = as installed (draft layer on); "off" starts without it (less graphics memory and RAM, slower); "on" overrides an installed "off" tune: str = "skip" # quick | thorough | skip @@ -293,6 +312,10 @@ def flags_text(s: LaunchSettings, *, preset: str | None = None) -> str: parts.append(f"--mtp {s.mtp}") if s.drafting: parts.append(f"--drafting {s.drafting}") + if s.speed == "full": + parts.append("--full-quality") + elif s.speed == "faster": + parts.append("--speed faster") parts.append(f"--tune {s.tune}") if s.tune_allow_small: parts.append("--tune-allow-small") diff --git a/tests/terminal/test_launch_speed.py b/tests/terminal/test_launch_speed.py new file mode 100644 index 00000000..068ccb3e --- /dev/null +++ b/tests/terminal/test_launch_speed.py @@ -0,0 +1,272 @@ +"""DeepSeek's speed choice (0.2.4.3): Faster (--experts 5, the default on a PC with 16 GB of graphics memory or less) or Full quality (--experts 6).""" + +from __future__ import annotations + +import asyncio +import json +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.launch import settings as S +from strata_cli.launch.app import LaunchApp +from strata_cli.launch.runner import (Runner, apply_experts, derive_config, dsv41_engine_version, engine_takes_experts, experts_from_log, + used_vram_gb) +from strata_cli.launch.screens import SpeedScreen, flow_for +from tests.terminal import test_launch as TL +from tests.terminal.launch_support import Home, text_of +from tests.terminal.test_launch_tui import SIZE, make_ctx, press + +run_cli = TL.run_cli + + +class Words(unittest.TestCase): + def test_the_default_is_faster_up_to_16_gb_of_graphics_memory(self): + for gb in (8, 12, 15.9, 16.0): # the engine's rule: 16 GiB or less (17,179,869,184 bytes) + self.assertTrue(S.faster_default(gb), gb) + for gb in (16.01, 16.4, 20, 24, 48, 0, None): + self.assertFalse(S.faster_default(gb), gb) + + def test_plain_words_and_the_quality_note(self): + self.assertEqual(S.speed_words("faster", True), "Faster (default on this PC)") + self.assertEqual(S.speed_words("faster", False), "Faster") + self.assertEqual(S.speed_words("full", False), "Full quality: all 6 experts per word") + self.assertEqual(S.FASTER_NOTE, "Faster uses 5 of 6 experts per word: a small quality change, usually not noticeable.") + + def test_the_flags_text_says_the_same(self): + self.assertNotIn("--speed", S.flags_text(S.LaunchSettings(family="deepseek41", model="IST-DAS-2.00bpw"))) + self.assertIn("--full-quality", S.flags_text(S.LaunchSettings(family="deepseek41", model="IST-DAS-2.00bpw", speed="full"))) + self.assertIn("--speed faster", S.flags_text(S.LaunchSettings(family="deepseek41", model="IST-DAS-2.00bpw", speed="faster"))) + + +class Units(unittest.TestCase): + """The catalog's vram_gb is GiB, the engine's unit: checked through the code that reads the cards (#3843-style: exact MiB values).""" + + def nvidia(self, *mib): + text = "\n".join(f"{i}, NVIDIA GeForce RTX {i}, {m}, 8.9, 580.97" for i, m in enumerate(mib)) + import setup + from tools import strata_mcp + with mock.patch.object(setup, "out", return_value=text), mock.patch.object(strata_mcp, "run_quiet", return_value=text): + return setup.gpus(), strata_mcp.own_nvidia_gpus() + + def total(self, cards): + return sum(round(c["vram_gb"], 1) for c in cards) # the catalog rounds each card to 0.1 GiB + + def test_nvidia_mib_is_divided_by_1024(self): + for cards in self.nvidia(16376): + self.assertAlmostEqual(cards[0]["vram_gb"], 16376 / 1024) + + def test_16_gb_cards_count_as_16_gib_or_less(self): + for mib in (16376, 16384, 16380): # RTX 4080 / 4060 Ti 16 GB, an exact 16 GiB card, in between + for cards in self.nvidia(mib): + self.assertTrue(S.faster_default(self.total(cards)), mib) + for mib in (12288, 12282, 8188): # RTX 3060, 12 GiB, 8 GB + for cards in self.nvidia(mib): + self.assertTrue(S.faster_default(self.total(cards)), mib) + + def test_bigger_cards_and_sums_over_16_gib_do_not(self): + for mib in (24564, 24576, 20475, 32607): + for cards in self.nvidia(mib): + self.assertFalse(S.faster_default(self.total(cards)), mib) + for cards in self.nvidia(8188, 8188): # two 8 GB cards: 15.99 GiB together + self.assertTrue(S.faster_default(self.total(cards))) + for cards in self.nvidia(12288, 8188): # 12 + 8: over + self.assertFalse(S.faster_default(self.total(cards))) + + def test_an_amd_16_gb_card_counts(self): + for size in (17179869184, 17163091968): # 16 GiB exactly, and a 16 GB card's 16,368 MiB + self.assertTrue(S.faster_default(round(size / 2 ** 30, 1)), size) + self.assertFalse(S.faster_default(round(34342961152 / 2 ** 30, 1))) # a 32 GB card + + +class EngineFlag(unittest.TestCase): + def test_experts_replaces_the_saved_value_and_goes_last(self): + cfg = {"args": ["--pack", "p", "--experts", "6", "--dspark", "auto"]} + apply_experts(cfg, 5) + self.assertEqual(cfg["args"], ["--pack", "p", "--dspark", "auto", "--experts", "5"]) + cfg = {"args": ["--experts=5", "--pack", "p"]} + apply_experts(cfg, 6) + self.assertEqual(cfg["args"], ["--pack", "p", "--experts", "6"]) + cfg = {"args": ["--pack", "p"]} + apply_experts(cfg, None) + self.assertEqual(cfg["args"], ["--pack", "p"]) + + def test_derive_config_passes_it(self): + base = {"exe": "x", "args": ["--pack", "p"]} + cfg = derive_config(base, S.LaunchSettings(), bool_flags=frozenset(), experts=5) + self.assertEqual(cfg["args"][-2:], ["--experts", "5"]) + self.assertEqual(derive_config(base, S.LaunchSettings(), bool_flags=frozenset())["args"], ["--pack", "p"]) + + +class Resolve(unittest.TestCase): + def runner(self, *cards, **kw): + cat = mock.Mock() + cat.strata.multi_family.return_value = True + gpus = [{"index": i, "vram_gb": gb} for i, gb in enumerate(cards)] + cat.computer.return_value = mock.Mock(usable_gpus=gpus) + r = Runner(S.LaunchSettings(family="deepseek41", model="IST-DAS-2.00bpw", **kw), catalog=cat, emit=lambda e: None) + r.dsv41_engine_found = lambda: (Path(self.engine), True) + return r + + engine = "/x/engine-dsv41/0.1.50-linux-x86_64-cuda-cuda13/strata-dsv41" + + def test_a_12_gb_pc_gets_faster_and_a_big_one_full_quality_in_the_words(self): + self.assertEqual(self.runner(12).resolved_speed(), ("faster", True)) + self.assertEqual(self.runner(96).resolved_speed(), ("full", True)) + self.assertEqual(self.runner(8, 8).resolved_speed(), ("faster", True)) # summed over the cards, as the engine sums them + self.assertEqual(self.runner(12, 12).resolved_speed(), ("full", True)) + + def test_nothing_is_passed_to_the_engine_unless_the_person_chose(self): + for cards in ((12,), (96,), (8, 8)): + self.assertIsNone(self.runner(*cards).experts_flag(), cards) # the engine's --experts auto decides: one rule + self.assertEqual(self.runner(12, speed="full").experts_flag(), 6) + self.assertEqual(self.runner(96, speed="faster").experts_flag(), 5) + + def test_a_choice_wins_over_the_default_in_the_words(self): + self.assertEqual(self.runner(12, speed="full").resolved_speed(), ("full", False)) + + def test_only_the_cards_the_launch_uses_are_summed(self): + comp = mock.Mock(usable_gpus=[{"index": 0, "vram_gb": 12}, {"index": 1, "vram_gb": 24}]) + self.assertEqual(used_vram_gb(comp, S.LaunchSettings()), 36) + self.assertEqual(used_vram_gb(comp, S.LaunchSettings(gpus=[0])), 12) + self.assertEqual(used_vram_gb(comp, S.LaunchSettings(gpu_roles={"0": "main", "1": "off"})), 12) + + def test_the_engines_own_line_wins_in_the_summary(self): + r = self.runner(12) + self.assertIn("Faster (default on this PC)", r.speed_line(5)) + self.assertIn("Full quality (default on this PC)", r.speed_line(6)) # the engine said 6 although the rule here said Faster + self.assertIn("Full quality: all 6 experts per word", self.runner(12, speed="full").speed_line(5)) # a choice stays what was chosen + + def test_the_number_is_read_back_from_the_engine_log(self): + import tempfile + from pathlib import Path + with tempfile.TemporaryDirectory() as d: + log = Path(d) / "e.log" + log.write_text("ds4: loading\nds4: experts per word: 6\nlater\nds4: experts per word: 5\n", encoding="utf-8") + self.assertEqual(experts_from_log(log), 5) + log.write_text("nothing here\n", encoding="utf-8") + self.assertIsNone(experts_from_log(log)) + self.assertIsNone(experts_from_log(Path(d) / "missing.log")) + + def test_the_line_has_the_note_only_for_faster(self): + self.assertIn(S.FASTER_NOTE, self.runner(12).speed_line()) + self.assertIn("Faster (default on this PC)", self.runner(12).speed_line()) + self.assertEqual(self.runner(12, speed="full").speed_line(), "Speed: Full quality: all 6 experts per word") + + def test_an_engine_older_than_0_1_50_gets_no_experts_flag_and_no_speed(self): + old = "/x/engine-dsv41/0.1.49.2-linux-x86_64-cuda-cuda13/strata-dsv41" + r = self.runner(12, speed="full") + r.dsv41_engine_found = lambda: (Path(old), True) + self.assertFalse(r.speed_engine_ok()) + self.assertIsNone(r.experts_flag()) # an explicit choice too: this engine would not understand the flag + self.assertIsNone(r.resolved_speed()) + self.assertEqual(r.speed_line(), "") # no line in --plan, no error + r.dsv41_engine_found = lambda: (None, None) # no engine yet: nothing either + self.assertIsNone(r.experts_flag()) + self.assertEqual(self.runner(12, speed="full").experts_flag(), 6) + self.assertEqual(r.experts_flag(self.engine), 6) # the config's engine decides in build_config (after the self-upgrade) + + def test_the_version_comes_from_the_package_folder(self): + for name, want in (("0.1.49.2", False), ("0.1.49.9", False), ("0.1.50", True), ("0.1.50.1", True), ("0.2.0", True), ("0.1.49", False)): + exe = f"/x/engine-dsv41/{name}-windows-x86_64-cuda-cuda13/strata-dsv41.exe" + self.assertEqual(engine_takes_experts(exe), want, name) + self.assertEqual(dsv41_engine_version("/x/engine-dsv41/0.1.50-a/strata-dsv41"), (0, 1, 50)) + self.assertFalse(engine_takes_experts(None)) + self.assertFalse(engine_takes_experts("/nowhere/strata-dsv41")) # a name that says nothing and a program that is not there + + def test_a_build_of_your_own_is_asked_for_its_version(self): + done = mock.Mock(stdout="strata-dsv41 0.1.50.1 (abc)\n", stderr="") + with mock.patch("strata_cli.launch.runner.subprocess.run", return_value=done): + self.assertTrue(engine_takes_experts("/home/me/build/strata-dsv41")) + done = mock.Mock(stdout="strata-dsv41 0.1.49.2\n", stderr="") + with mock.patch("strata_cli.launch.runner.subprocess.run", return_value=done): + self.assertFalse(engine_takes_experts("/home/me/build/strata-dsv41")) + + def test_another_model_has_no_speed(self): + cat = mock.Mock() + cat.strata.multi_family.return_value = False + r = Runner(S.LaunchSettings(family="qwen", model="IQ3_S"), catalog=cat, emit=lambda e: None) + self.assertIsNone(r.resolved_speed()) + self.assertIsNone(r.experts_flag()) + self.assertEqual(r.speed_line(), "") + + +class Flags(unittest.TestCase): + def plan(self, *args): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "ist-das-2.00bpw", "--family", "deepseek41", *args]) + self.assertEqual(code, 0, err + out) + return json.loads(out)["plan"] + + def test_plan_names_the_speed_in_plain_words(self): + with mock.patch.object(Runner, "resolved_speed", return_value=("faster", True)): + p = self.plan() + self.assertIn("Faster (default on this PC)", p["speed"]) + self.assertIn(S.FASTER_NOTE, p["speed"]) + + def test_full_quality_flag_and_speed_flag(self): + self.assertEqual(self.plan("--full-quality")["settings"]["speed"], "full") + self.assertEqual(self.plan("--speed", "full")["settings"]["speed"], "full") + self.assertEqual(self.plan("--speed", "faster")["settings"]["speed"], "faster") + self.assertIn("--full-quality", self.plan("--full-quality")["flags"]) + + def test_both_flags_say_so_and_full_quality_wins(self): + p = self.plan("--full-quality", "--speed", "faster") + self.assertEqual(p["settings"]["speed"], "full") + self.assertTrue(any("full quality is used" in w for w in p["warnings"])) + + def test_another_model_warns_and_drops_it(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--full-quality"]) + p = json.loads(out)["plan"] + self.assertIsNone(p["settings"]["speed"]) + self.assertTrue(any("for DeepSeek" in w for w in p["warnings"])) + + def test_human_plan_prints_a_speed_line(self): + with mock.patch.object(Runner, "resolved_speed", return_value=("faster", True)): + code, out, err = run_cli(["launch", "--plan", "--model", "ist-das-2.00bpw", "--family", "deepseek41"]) + self.assertIn(" speed Faster (default on this PC)", out) + + +class Screen(unittest.TestCase): + def setUp(self): + self.home = Home().__enter__() + self.addCleanup(self.home.__exit__, None, None, None) + + def test_the_step_exists_only_for_deepseek(self): + ctx = make_ctx() + self.assertNotIn("speed", flow_for(ctx)) + ctx.settings.family = "deepseek41" + with mock.patch.object(Runner, "speed_engine_ok", return_value=False): # engine 0.1.49.2 or none: the step is not there + self.assertNotIn("speed", flow_for(ctx)) + ctx._speed_ok = None + with mock.patch.object(Runner, "speed_engine_ok", return_value=True): + flow = flow_for(ctx) + self.assertEqual(flow[flow.index("context") + 1], "speed") + + def test_the_screen_offers_two_choices_and_remembers_only_a_change(self): + ctx = make_ctx() + ctx.settings.family, ctx.settings.model = "deepseek41", "IST-DAS-2.00bpw" + faster_here = S.faster_default(used_vram_gb(ctx.computer, ctx.settings)) + ctx._speed_ok = True + app = LaunchApp(ctx) + + async def go(): + async with app.run_test(size=SIZE) as pilot: + await pilot.pause(0.2) + app.goto("speed") + await pilot.pause(0.3) + t = text_of(app) + self.assertIn("Faster", t) + self.assertIn("Full quality", t) + self.assertIn(S.FASTER_NOTE, t) + screen = app.screen + self.assertIsInstance(screen, SpeedScreen) + screen.commit() + self.assertEqual(ctx.settings.speed, None if faster_here else "faster") + await press(pilot, "down") + screen.commit() + self.assertIn(ctx.settings.speed, (None, "full")) + asyncio.run(go()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_ownfiles.py b/tools/test_setup_ownfiles.py index a86f22fe..d9faf411 100644 --- a/tools/test_setup_ownfiles.py +++ b/tools/test_setup_ownfiles.py @@ -60,8 +60,12 @@ class OwnFileChecks(unittest.TestCase): self.assertFalse(self.file.exists()) def test_a_complete_own_gguf_of_another_size_or_hash_is_used_with_a_warning(self): # #3777 - sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # `discover -s tools` puts only tools/ on the path - from tests.terminal.test_own_files import gguf_bytes + import importlib.util # by path: another `tests` package may already be loaded + spec = importlib.util.spec_from_file_location("own_files_helper", Path(__file__).resolve().parents[1] / "tests" / "terminal" / "test_own_files.py") + helper = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + spec.loader.exec_module(helper) + gguf_bytes = helper.gguf_bytes gguf = Path(self.tmp.name) / "fine-tune.gguf" gguf.write_bytes(gguf_bytes(["Q8_0"])) for size, sha in ((gguf.stat().st_size + 96, "0" * 64), (gguf.stat().st_size, "0" * 64)):