okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""A short tune for DeepSeek-V4.1-Flash (strata-dsv41): the few settings the engine has, measured on this computer. 2 3python 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): 61. the launch's own settings (the baseline); 72. the same with the DSpark drafter forced on (`--dspark on --dspark-conf 0.65`) against `--dspark auto`, which leaves it unloaded on a 8small card: kept only when it is clearly faster; with it on, a draft block of 3 against the pack's own (5); 93. 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 : 35msg ,flush = True ) 36 37 38def parse_speed (stderr :str )-> float | None : 39m = DECODE .findall (stderr or "" ) 40return 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.""" 45out ,i = [],0 46while i < len (args ): 47if args [i ]== flag : 48i += 2 49continue 50out .append (args [i ]) 51i += 1 52return out 53 54 55def with_flag (args :list [str ],flag :str ,* values :str )-> list [str ]: 56return [* drop (args ,flag ),flag ,* values ] 57 58 59def physical_cores ()-> int | None : 60try : 61import psutil 62return psutil .cpu_count (logical = False ) 63except Exception :# noqa: BLE001 64return 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.""" 69cmd = [exe ,* [a for a in args if a not in ("--serve" ,)],"--ids" ,"@" + str (ids_file ),"--n" ,str (n )] 70try : 71r = subprocess .run (cmd ,capture_output = True ,text = True ,encoding = "utf-8" ,errors = "replace" ,timeout = timeout ,env = env ) 72except (OSError ,subprocess .TimeoutExpired ): 73return None 74if r .returncode != 0 : 75return None 76return parse_speed (r .stderr ) 77 78 79def prompt_ids (pack :Path )-> list [int ]: 80import smoke 81tok = smoke .tokenizer (pack ) 82return tok .encode (smoke .PROMPT ,parse_special = True ) 83 84 85def lib_env (cfg :dict )-> dict : 86env = dict (os .environ ) 87dirs = [str (d )for d in cfg .get ("lib_dirs" )or []if d ] 88key = "PATH" if os .name == "nt" else "LD_LIBRARY_PATH" 89if dirs : 90env [key ]= os .pathsep .join (dirs + [env .get (key ,"" )]) 91return 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.""" 96cfg = json .loads (config .read_text (encoding = "utf-8-sig" )) 97exe ,args = cfg .get ("exe" ), [str (a )for a in cfg .get ("args" )or []] 98res = {"changed" : [],"speeds" : {},"lines" : []} 99if not exe or "--pack" not in args : 100res ["lines" ].append ("This launch has no DeepSeek engine settings to tune, so it starts as it is." ) 101return res 102pack = Path (args [args .index ("--pack" )+ 1 ]) 103env = lib_env (cfg ) 104try : 105ids = prompt_ids (pack ) 106except Exception as e :# noqa: BLE001 107res ["lines" ].append (f"The tuner could not prepare its test question ( { e } ), so the standard settings run." ) 108return res 109with tempfile .TemporaryDirectory ()as d : 110f = Path (d )/ "ids.txt" 111f .write_text ("," .join (str (i )for i in ids ),encoding = "ascii" ) 112base_args = [a for a in args if a != "--serve" ] 113say ("Tuning DeepSeek: measuring the standard settings first ..." ) 114base = measure_fn (exe ,base_args ,f ,n ,timeout ,env ) 115if base is None : 116res ["lines" ].append ("The standard settings did not finish a test run here, so nothing was tuned and they stay as they are." ) 117return res 118res ["speeds" ]["standard" ]= base 119best ,best_args = base ,base_args 120say (f" standard settings: { base :.2f } tokens a second" ) 121trials = [("the drafter on (DSpark)" ,lambda a :with_flag (with_flag (a ,"--dspark" ,"on" ),"--dspark-conf" ,"0.65" ))] 122trials .append (("a shorter draft block (3)" ,lambda a :with_flag (a ,"--dspark-block" ,"3" ))) 123cores ,logical = physical_cores (),os .cpu_count ()or 0 124if cores and logical and logical > cores and "--cpu-threads" not in base_args : 125trials .append ((f" { cores } CPU threads (one for each physical core)" ,lambda a ,c = cores :with_flag (a ,"--cpu-threads" ,str (c )))) 126if mode == "thorough" and cores : 127trials .append (("every logical CPU thread" ,lambda a ,c = logical :with_flag (a ,"--cpu-threads" ,str (c )))) 128queue = list (trials ) 129while queue : 130label ,make = queue .pop (0 ) 131if label == "a shorter draft block (3)" : 132if "on" != (best_args [best_args .index ("--dspark" )+ 1 ]if "--dspark" in best_args else "" ): 133continue # only with the drafter on: with `auto` it may not even be loaded 134cand = make (best_args ) 135say (f" trying { label } ..." ) 136v = measure_fn (exe ,cand ,f ,n ,timeout ,env ) 137if v is None : 138res ["lines" ].append (f"The test with { label } did not finish; that setting stays as it was." ) 139continue 140res ["speeds" ][label ]= v 141say (f" { v :.2f } tokens a second" ) 142if v > best * GAIN : 143best ,best_args = v ,cand 144res ["changed" ].append (label ) 145tried = ", " .join (f" { k } { v :.1f } " for k ,v in res ["speeds" ].items ()) 146if res ["changed" ]: 147new = [a for a in best_args ] 148cfg ["args" ]= new 149cfg .setdefault ("tuned" , {})["dsv41" ]= {"speeds" :res ["speeds" ],"changed" :res ["changed" ]} 150config .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 151res ["lines" ].append (f"Done: { ', ' . join ( res [ 'changed' ]) } - answers about { 100 * ( best / base - 1 ):.0f } % faster " 152f"( { base :.1f } -> { best :.1f } tokens a second). The RAM store sizes itself when the model starts." ) 153else : 154res ["lines" ].append (f"Your computer already runs DeepSeek best with the standard settings ( { base :.1f } tokens a second); nothing changed." ) 155if len (res ["speeds" ])> 1 : 156res ["lines" ].append (f"Tried (tokens a second): { tried } ." ) 157else : 158res ["lines" ].append ("Only the standard settings could be timed here, so there was nothing to compare." ) 159return res 160 161 162def main ()-> int : 163ap = argparse .ArgumentParser () 164ap .add_argument ("--config" ,required = True ) 165ap .add_argument ("--mode" ,default = "quick" ,choices = ["quick" ,"thorough" ]) 166ap .add_argument ("--tokens" ,type = int ,default = 48 ) 167ap .add_argument ("--timeout" ,type = int ,default = 1500 ) 168ap .add_argument ("--output" ,default = "human" ) 169a = ap .parse_args () 170try : 171res = tune (Path (a .config ),a .mode ,a .tokens ,a .timeout ) 172except Exception as e :# noqa: BLE001 - a tune never stops a launch 173res = {"changed" : [],"speeds" : {},"lines" : [f"The tuner stopped ( { type ( e ). __name__ } ), so the standard settings run." ]} 174for line in res ["lines" ]: 175say (line ) 176if a .output == "json" : 177say (json .dumps ({"result" :res })) 178return 0 179 180 181if __name__ == "__main__" : 182sys .exit (main ())