okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
8.1 KiB182 linesraw
1"""A short tune for DeepSeek-V4.1-Flash (strata-dsv41): the few settings the engine has, measured on this computer.
2
3    python tools/dsv41/tune.py --config <launch config .json> [--mode quick|thorough] [--runs N]
4
5What it does (a few short decode runs through the engine's own command line; each loads the model, so about 1-3 minutes each):
6  1. the launch's own settings (the baseline);
7  2. the same with the DSpark drafter forced on (`--dspark on --dspark-conf 0.65`) against `--dspark auto`, which leaves it unloaded on a
8     small card: kept only when it is clearly faster; with it on, a draft block of 3 against the pack's own (5);
9  3. the CPU threads: the number of physical cores against every logical thread (SMT), when they differ: kept only when clearly faster.
10The RAM store (`--ssd-cache`) sizes itself from the free memory at start, so it is left as the engine's own; the line says so.
11A setting is changed only for a gain of more than 5% (run-to-run noise on this engine is about 5%).  Whatever is kept is written into
12the config's args; a run that fails or a computer that is too busy leaves the config as it was, with one plain line.  Always exits 0.
13The context stays what the person chose.
14"""
15from __future__ import annotations
16
17import argparse
18import json
19import os
20import re
21import subprocess
22import sys
23import tempfile
24from pathlib import Path
25
26ROOT = Path(__file__).resolve().parents[2]
27sys.path.insert(0, str(ROOT / "tools"))
28sys.path.insert(0, str(Path(__file__).resolve().parent))
29
30GAIN = 1.05
31DECODE = re.compile(r"decode:\s*\d+ tokens in [\d.]+ ms \(([\d.]+) tok/s\)")
32
33
34def say(msg: str) -> None:
35    print(msg, flush=True)
36
37
38def parse_speed(stderr: str) -> float | None:
39    m = DECODE.findall(stderr or "")
40    return float(m[-1]) if m else None
41
42
43def drop(args: list[str], flag: str) -> list[str]:
44    """`args` without `flag` and its value."""
45    out, i = [], 0
46    while i < len(args):
47        if args[i] == flag:
48            i += 2
49            continue
50        out.append(args[i])
51        i += 1
52    return out
53
54
55def with_flag(args: list[str], flag: str, *values: str) -> list[str]:
56    return [*drop(args, flag), flag, *values]
57
58
59def physical_cores() -> int | None:
60    try:
61        import psutil
62        return psutil.cpu_count(logical=False)
63    except Exception:                                    # noqa: BLE001
64        return None
65
66
67def measure(exe: str, args: list[str], ids_file: Path, n: int, timeout: int, env: dict) -> float | None:
68    """Decode tokens a second of one CLI run, or None when it did not run to the end."""
69    cmd = [exe, *[a for a in args if a not in ("--serve",)], "--ids", "@" + str(ids_file), "--n", str(n)]
70    try:
71        r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
72    except (OSError, subprocess.TimeoutExpired):
73        return None
74    if r.returncode != 0:
75        return None
76    return parse_speed(r.stderr)
77
78
79def prompt_ids(pack: Path) -> list[int]:
80    import smoke
81    tok = smoke.tokenizer(pack)
82    return tok.encode(smoke.PROMPT, parse_special=True)
83
84
85def lib_env(cfg: dict) -> dict:
86    env = dict(os.environ)
87    dirs = [str(d) for d in cfg.get("lib_dirs") or [] if d]
88    key = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
89    if dirs:
90        env[key] = os.pathsep.join(dirs + [env.get(key, "")])
91    return env
92
93
94def tune(config: Path, mode: str = "quick", n: int = 48, timeout: int = 1500, measure_fn=measure) -> dict:
95    """Returns {"changed": [...], "speeds": {...}, "lines": [plain sentences]}; writes the config when something was kept."""
96    cfg = json.loads(config.read_text(encoding="utf-8-sig"))
97    exe, args = cfg.get("exe"), [str(a) for a in cfg.get("args") or []]
98    res = {"changed": [], "speeds": {}, "lines": []}
99    if not exe or "--pack" not in args:
100        res["lines"].append("This launch has no DeepSeek engine settings to tune, so it starts as it is.")
101        return res
102    pack = Path(args[args.index("--pack") + 1])
103    env = lib_env(cfg)
104    try:
105        ids = prompt_ids(pack)
106    except Exception as e:                                # noqa: BLE001
107        res["lines"].append(f"The tuner could not prepare its test question ({e}), so the standard settings run.")
108        return res
109    with tempfile.TemporaryDirectory() as d:
110        f = Path(d) / "ids.txt"
111        f.write_text(",".join(str(i) for i in ids), encoding="ascii")
112        base_args = [a for a in args if a != "--serve"]
113        say("Tuning DeepSeek: measuring the standard settings first ...")
114        base = measure_fn(exe, base_args, f, n, timeout, env)
115        if base is None:
116            res["lines"].append("The standard settings did not finish a test run here, so nothing was tuned and they stay as they are.")
117            return res
118        res["speeds"]["standard"] = base
119        best, best_args = base, base_args
120        say(f"  standard settings: {base:.2f} tokens a second")
121        trials = [("the drafter on (DSpark)", lambda a: with_flag(with_flag(a, "--dspark", "on"), "--dspark-conf", "0.65"))]
122        trials.append(("a shorter draft block (3)", lambda a: with_flag(a, "--dspark-block", "3")))
123        cores, logical = physical_cores(), os.cpu_count() or 0
124        if cores and logical and logical > cores and "--cpu-threads" not in base_args:
125            trials.append((f"{cores} CPU threads (one for each physical core)", lambda a, c=cores: with_flag(a, "--cpu-threads", str(c))))
126        if mode == "thorough" and cores:
127            trials.append(("every logical CPU thread", lambda a, c=logical: with_flag(a, "--cpu-threads", str(c))))
128        queue = list(trials)
129        while queue:
130            label, make = queue.pop(0)
131            if label == "a shorter draft block (3)":
132                if "on" != (best_args[best_args.index("--dspark") + 1] if "--dspark" in best_args else ""):
133                    continue                                       # only with the drafter on: with `auto` it may not even be loaded
134            cand = make(best_args)
135            say(f"  trying {label} ...")
136            v = measure_fn(exe, cand, f, n, timeout, env)
137            if v is None:
138                res["lines"].append(f"The test with {label} did not finish; that setting stays as it was.")
139                continue
140            res["speeds"][label] = v
141            say(f"    {v:.2f} tokens a second")
142            if v > best * GAIN:
143                best, best_args = v, cand
144                res["changed"].append(label)
145    tried = ", ".join(f"{k} {v:.1f}" for k, v in res["speeds"].items())
146    if res["changed"]:
147        new = [a for a in best_args]
148        cfg["args"] = new
149        cfg.setdefault("tuned", {})["dsv41"] = {"speeds": res["speeds"], "changed": res["changed"]}
150        config.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
151        res["lines"].append(f"Done: {', '.join(res['changed'])} - answers about {100 * (best / base - 1):.0f}% faster "
152                            f"({base:.1f} -> {best:.1f} tokens a second). The RAM store sizes itself when the model starts.")
153    else:
154        res["lines"].append(f"Your computer already runs DeepSeek best with the standard settings ({base:.1f} tokens a second); nothing changed.")
155    if len(res["speeds"]) > 1:
156        res["lines"].append(f"Tried (tokens a second): {tried}.")
157    else:
158        res["lines"].append("Only the standard settings could be timed here, so there was nothing to compare.")
159    return res
160
161
162def main() -> int:
163    ap = argparse.ArgumentParser()
164    ap.add_argument("--config", required=True)
165    ap.add_argument("--mode", default="quick", choices=["quick", "thorough"])
166    ap.add_argument("--tokens", type=int, default=48)
167    ap.add_argument("--timeout", type=int, default=1500)
168    ap.add_argument("--output", default="human")
169    a = ap.parse_args()
170    try:
171        res = tune(Path(a.config), a.mode, a.tokens, a.timeout)
172    except Exception as e:                                # noqa: BLE001 - a tune never stops a launch
173        res = {"changed": [], "speeds": {}, "lines": [f"The tuner stopped ({type(e).__name__}), so the standard settings run."]}
174    for line in res["lines"]:
175        say(line)
176    if a.output == "json":
177        say(json.dumps({"result": res}))
178    return 0
179
180
181if __name__ == "__main__":
182    sys.exit(main())