okami.mom/strata

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

Niko1221merge f-split-s5 dab63e9c3 (tuning presets on Models, effective values, outcome codes, apply_saved_tuning) into f-split-int0c165b48b

main
6.9 KiB130 linesraw
1"""A saved tuning is applied at every start: after an app restart (a new process), after an unload and a load, and it can be seen
2(`presets effective`, `presets status`) and switched off and on again."""
3
4from __future__ import annotations
5
6import json
7import os
8import subprocess
9import sys
10import tempfile
11import unittest
12from pathlib import Path
13
14ROOT = Path(__file__).resolve().parents[2]
15
16
17def cli(env, *args):
18    out = subprocess.run([sys.executable, str(ROOT / "strata.py"), *args, "--output", "json"], capture_output=True, text=True,
19                         env=env, cwd=str(ROOT), timeout=120)
20    return json.loads(out.stdout[out.stdout.index("{"):]), out
21
22
23def fresh_process(env, code):
24    """A new Python process: what an app restart or a new server start is."""
25    r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, cwd=str(ROOT), timeout=120)
26    assert r.returncode == 0, r.stderr
27    return json.loads(r.stdout.strip().splitlines()[-1])
28
29
30class PersistenceTest(unittest.TestCase):
31    def setUp(self):
32        self.tmp = tempfile.TemporaryDirectory()
33        self.addCleanup(self.tmp.cleanup)
34        t = Path(self.tmp.name)
35        (t / "model.gguf").write_bytes(b"gguf" * 1000)
36        (t / "engine.exe").write_bytes(b"x")
37        (t / "tok").mkdir()
38        self.cfg_path = t / "strata-model.json"
39        self.cfg = {"exe": str(t / "engine.exe"), "tokenizer": str(t / "tok"), "model_name": "iq3_s-test", "ui_resource_profile": "work",
40                    "args": ["--native", str(t / "model.gguf"), "--expert-cache", "auto", "--spec", "4", "--max-context", "65536",
41                             "--kv", "int8", "--kv-resident", "32768"]}
42        self.cfg_path.write_text(json.dumps(self.cfg))
43        self.env = dict(os.environ, STRATA_PRESET_DIR=str(t / "presets"), PYTHONPATH=str(ROOT), STRATA_NO_PRESET="")
44        self.env.pop("STRATA_NO_PRESET")
45        # the tune's result, saved as a preset by the library, the way `strata tune auto` does
46        sys.path.insert(0, str(ROOT))
47        os.environ["STRATA_PRESET_DIR"] = str(t / "presets")
48        self.addCleanup(lambda: os.environ.pop("STRATA_PRESET_DIR", None))
49        from strata_control import presets
50        self.presets = presets
51        ident = presets.current_identity(self.cfg, exe=self.cfg["exe"])
52        result = {"outcome": "improved", "seconds": 900, "settings": {"args": {"--kv-resident": 65536}, "env": {}, "per_request": {}},
53                  "answers": {"class": "exact", "fields": []}, "base": {"decode_tok_s": 60.0}, "chosen": {"decode_tok_s": 64.0},
54                  "gain_pct": 6.6, "pairs": 2, "faster_pairs": 2, "noise": {}}
55        self.preset = presets.create(result, choices=presets.choices_from_config(self.cfg), identity=ident, name="IQ3_S 64K – Work")
56
57    CODE = ("import json,sys;sys.path.insert(0,'.');from serve import server;"
58            "c=json.load(open(%r));out=server.apply_saved_tuning(c,say=lambda l:None);"
59            "print(json.dumps(out['args']))")
60
61    def args_at_start(self):
62        return fresh_process(self.env, self.CODE % str(self.cfg_path))
63
64    def test_applied_after_restart_and_after_unload_and_load(self):
65        for _ in range(3):                  # three starts = a restart, an unload, a load: every one is a new server process
66            args = self.args_at_start()
67            self.assertEqual(args[args.index("--kv-resident") + 1], "65536")
68            self.assertEqual(args[args.index("--spec") + 1], "4")            # the user's own flags are untouched
69        self.assertEqual(json.loads(self.cfg_path.read_text())["args"], self.cfg["args"])    # the saved run config itself never changes
70
71    def test_a_tune_worker_measures_the_configuration_as_given(self):
72        env = dict(self.env, STRATA_NO_PRESET="1")
73        args = fresh_process(env, self.CODE % str(self.cfg_path))
74        self.assertEqual(args[args.index("--kv-resident") + 1], "32768")
75
76    def test_expert_mode_can_read_what_will_run(self):
77        out, _ = cli(self.env, "presets", "effective", str(self.cfg_path))
78        self.assertTrue(out["applied"])
79        self.assertEqual(out["preset"]["name"], "IQ3_S 64K – Work")
80        self.assertEqual(out["changed"], [{"flag": "--kv-resident", "was": "32768", "now": "65536"}])
81        self.assertEqual(out["args"][out["args"].index("--kv-resident") + 1], "65536")
82
83    def test_which_tuning_is_in_use_and_switching_it_off_and_on(self):
84        st, _ = cli(self.env, "presets", "status", str(self.cfg_path))
85        self.assertEqual(st["active"]["name"], "IQ3_S 64K – Work")
86        self.assertFalse(st["switched_off"])
87        off, _ = cli(self.env, "presets", "off", str(self.cfg_path))
88        self.assertIsNone(off["active"])
89        args = self.args_at_start()
90        self.assertEqual(args[args.index("--kv-resident") + 1], "32768")        # back to the standard settings
91        eff, _ = cli(self.env, "presets", "effective", str(self.cfg_path))
92        self.assertFalse(eff["applied"])
93        st, _ = cli(self.env, "presets", "status", str(self.cfg_path))
94        self.assertIsNone(st["active"])
95        self.assertTrue(st["switched_off"])
96        self.assertEqual(st["last_active"]["name"], "IQ3_S 64K – Work")          # kept, and listed, so it can be switched on again
97        on, _ = cli(self.env, "presets", "apply", st["last_active"]["id"])
98        self.assertTrue(on["ok"])
99        args = self.args_at_start()
100        self.assertEqual(args[args.index("--kv-resident") + 1], "65536")
101
102    def test_a_changed_gpu_is_not_applied_and_says_why(self):
103        p = self.presets.load(self.preset["id"])
104        p["identity"]["hardware"]["hard"]["gpus"] = [{"name": "Another GPU", "vram_mib": 1}]
105        self.presets._write_json(self.presets._path(p["id"]), p)
106        out, _ = cli(self.env, "presets", "effective", str(self.cfg_path))
107        self.assertFalse(out["applied"])
108        self.assertIn("graphics card", out["why_not"])
109
110
111class OutcomeCodesTest(unittest.TestCase):
112    def test_codes_and_values(self):
113        from strata_control import autotune
114        mk = autotune.TuneResult
115        r = mk(outcome="improved", gain_pct=7.2, seconds=1200, waited_s=120, pairs=5, faster_pairs=4)
116        r.base, r.chosen = {"decode_tok_s": 50.0}, {"decode_tok_s": 53.6}
117        autotune.Tuner.finalize(r)
118        self.assertEqual(r.code, "faster")
119        self.assertEqual(r.values["gain_pct"], 7.2)
120        self.assertEqual(r.values["minutes"], 18.0)
121        for outcome, reason, code in (("default_confirmed", "", "already_fastest"), ("inconclusive", "noisy", "busy_pc"),
122                                      ("inconclusive", "drift", "busy_pc"), ("inconclusive", "not_tried", "busy_pc"),
123                                      ("base_failed", "start_failed", "failed"), ("cancelled", "", "stopped")):
124            x = mk(outcome=outcome, reason_code=reason)
125            autotune.Tuner.finalize(x)
126            self.assertEqual((x.code, x.reason_code), (code, reason), outcome)
127
128
129if __name__ == "__main__":
130    unittest.main()