okami.mom/strata

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

Niko1221Merge f-0213-tuicfg (final c6dda74bf) into f-0213-int049ae1c67

main
11.2 KiB217 linesraw
1"""Round 0213 TUICFG, step 6: tuning stays available (#5056 STRATA_API_KEY, #5122 RAM guard, #5078 engine abort shown as a 503).
2Doubles only: a stub session, a tiny HTTP worker, a recorded spawn."""
3from __future__ import annotations
4
5import json
6import os
7import tempfile
8import threading
9import unittest
10from http.server import BaseHTTPRequestHandler, HTTPServer
11from pathlib import Path
12from unittest import mock
13
14from strata_control import autotune, tune_session
15from strata_control.tune_session import StartFailed, WorkerEngine, WorkerSession, native_failure
16from tests.tuning.stub_session import FakeClock, StubSession, flag
17from tests.tuning.test_autotune import BASE, make_ctx, speed_with
18
19
20class WorkerKey(unittest.TestCase):
21    """#5056: the worker must answer to the key the tuner made, whatever STRATA_API_KEY says."""
22
23    def spawned(self, env):
24        seen = {}
25
26        def popen(argv, name, **kw):
27            seen["env"], seen["argv"] = dict(kw["env"]), argv
28            raise OSError("not started in this test")
29        with tempfile.TemporaryDirectory() as tmp, mock.patch.dict(os.environ, env, clear=False), \
30                mock.patch("serve.lifeline.popen", popen), mock.patch.object(tune_session.tune_machine, "gpu_used_mib", return_value=None):
31            if "STRATA_API_KEY" not in env:
32                os.environ.pop("STRATA_API_KEY", None)
33            s = WorkerSession(base_config={"args": [], "api_key": "from-the-preset"}, serve_dir=tmp, workdir=tmp)
34            with self.assertRaises(StartFailed):
35                with s.engine([], {}):
36                    pass
37            cfg = json.loads((Path(tmp) / "run-1.json").read_text())
38        return seen, cfg
39
40    def test_the_variable_is_not_passed_to_the_worker_and_the_config_key_is_the_tuners_own(self):
41        for env in ({"STRATA_API_KEY": "client-shared-key"}, {"STRATA_API_KEY": ""}, {}):
42            with self.subTest(env=env):
43                seen, cfg = self.spawned(env)
44                self.assertNotIn("STRATA_API_KEY", seen["env"])
45                self.assertEqual(len(cfg["api_key"]), 32)
46                self.assertNotEqual(cfg["api_key"], "from-the-preset")
47                self.assertNotIn(cfg["api_key"], " ".join(seen["argv"]), "the key is not on the command line")
48
49
50class FailingWorker(BaseHTTPRequestHandler):
51    def log_message(self, *a):  # noqa: ANN002
52        pass
53
54    def do_GET(self):  # noqa: N802
55        body = json.dumps({"data": [{"id": "m"}]}).encode()
56        self.send_response(200)
57        self.send_header("content-length", str(len(body)))
58        self.end_headers()
59        self.wfile.write(body)
60
61    def do_POST(self):  # noqa: N802
62        self.rfile.read(int(self.headers["content-length"]))
63        body = json.dumps({"error": {"message": "the engine stopped unexpectedly (exit code -6); the next request restarts it"}}).encode()
64        self.send_response(503)
65        self.send_header("content-length", str(len(body)))
66        self.end_headers()
67        self.wfile.write(body)
68
69
70class FakeProc:
71    pid = 0
72
73    def poll(self):
74        return None
75
76
77class EngineAbort(unittest.TestCase):
78    """#5078: a generic 503 from the worker must carry the engine's own last error line, and a memory failure is an OOM."""
79
80    def engine(self, log_text):
81        srv = HTTPServer(("127.0.0.1", 0), FailingWorker)
82        threading.Thread(target=srv.serve_forever, daemon=True).start()
83        self.addCleanup(srv.shutdown)
84        tmp = tempfile.TemporaryDirectory()
85        self.addCleanup(tmp.cleanup)
86        log = Path(tmp.name) / "engine.log"
87        log.write_text(log_text)
88        session = WorkerSession(base_config={"args": []}, serve_dir=".", workdir=tmp.name)
89        return WorkerEngine(session, FakeProc(), srv.server_address[1], "k", [log], 1.0, None, lambda x: None)
90
91    def test_a_cuda_oom_in_prefill_is_reported_as_an_oom_with_the_native_line(self):
92        eng = self.engine("strata serve: 687 MiB of VRAM free with everything loaded\n"
93                          "ggml-cuda (strata mmq): out of memory: cudaMalloc(&p, size)\n  in alloc at ggml_cuda_host.cu:127\n")
94        with self.assertRaises(StartFailed) as cm:
95            eng.chat("hello", 8)
96        self.assertEqual(cm.exception.status, "OOM")
97        self.assertIn("the worker refused the request (503)", cm.exception.reason)
98        self.assertIn("out of memory: cudaMalloc", cm.exception.reason)
99
100    def test_another_abort_keeps_its_line_and_is_not_an_oom(self):
101        eng = self.engine("loading\nterminate called after throwing an instance of 'std::runtime_error'\n")
102        with self.assertRaises(StartFailed) as cm:
103            eng.chat("hello", 8)
104        self.assertEqual(cm.exception.status, "NO_TOKENS")
105        self.assertIn("terminate called", cm.exception.reason)
106
107    def test_a_quiet_log_keeps_the_old_message(self):
108        eng = self.engine("loading\nready\n")
109        with self.assertRaises(StartFailed) as cm:
110            eng.chat("hello", 8)
111        self.assertEqual((cm.exception.status, "engine:" in cm.exception.reason), ("NO_TOKENS", False))
112
113    def test_the_memory_guards_information_line_is_not_an_error(self):
114        self.assertEqual(native_failure("memory guard: limit 20 GiB, available 30 GiB\nready\n"), "")
115
116    def test_a_crashing_candidate_is_failed_alone_and_the_baseline_is_kept(self):
117        def fail(args, env):
118            if flag(args, "--kv-resident") == "65536":
119                return StartFailed("NO_TOKENS", "the worker refused the request (503) | engine: terminate called")
120            return None
121        clock = FakeClock()
122        session = StubSession(model=speed_with({("--kv-resident", "65536"): 1.10}), clock=clock, fail=fail)
123        t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(), clock=clock, sleep=clock.sleep, system=session.system,
124                           total_ram_mib=64000, total_vram_mib=12000, quiet=lambda: None)
125        r = t.run()
126        failed = [a for a in r.arms if a["status"] == "failed"]
127        self.assertTrue(failed and "terminate called" in failed[0]["reason"])
128        self.assertNotEqual(r.outcome, "base_failed")
129        self.assertNotIn("--kv-resident", r.settings["args"], "the crashed candidate is never applied")
130        self.assertIn(r.outcome, ("default_confirmed", "inconclusive"), "the tune ends with a result, not as a failure")
131
132    def test_a_base_that_aborts_names_the_native_failure(self):
133        def fail(args, env):
134            return StartFailed("OOM", "the worker refused the request (503): b'..' | engine: ggml-cuda: out of memory: cudaMalloc")
135        clock = FakeClock()
136        session = StubSession(model=speed_with({}), clock=clock, fail=fail)
137        t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(), clock=clock, sleep=clock.sleep, system=session.system,
138                           total_ram_mib=64000, total_vram_mib=12000, quiet=lambda: None)
139        r = t.run()
140        self.assertEqual(r.outcome, "base_failed")
141        self.assertIn("cudaMalloc", r.message)
142
143
144class RamGuard(unittest.TestCase):
145    """#5122: the restart candidate needs what the base run had, not the base's peak RSS plus the floor."""
146
147    def tuner(self, free_before, free_after, rss=23429.0, wait_ram_s=30, big_card=False, gain=1.10):
148        clock = FakeClock()
149        session = StubSession(model=speed_with({("--kv-resident", "65536"): gain}), clock=clock, avail=free_before, rss=lambda a, e: rss)
150        real = session.system
151
152        def system():
153            out = real()
154            out["memory"]["available_mib"] = free_before if not session.runs else free_after
155            return out
156        ctx = make_ctx()
157        if big_card:                     # a 24 GB card also plans the 32K prompt chunk, which asks for 4 GiB more RAM than the base
158            ctx.vram_mib = 24000
159        t = autotune.Tuner(session, BASE, {}, ctx, autotune.Options(wait_ram_s=wait_ram_s, per_request=False), clock=clock, sleep=clock.sleep,
160                           system=system, total_ram_mib=32000, quiet=lambda: None)
161        return t, session
162
163    def test_a_candidate_that_adds_nothing_is_tried_when_the_base_started_with_the_same_free_memory(self):
164        t, session = self.tuner(free_before=23654, free_after=24680)      # 23.1 GiB at the base start, 24.1 GiB free later (the report)
165        r = t.run()
166        self.assertTrue(any(flag(a, "--kv-resident") == "65536" for a, _ in session.runs), "the 64K resident-KV candidate (no extra RAM) was started")
167        self.assertFalse([a for a in r.arms if a["status"] == "skipped"], r.arms)
168
169    def test_less_free_memory_than_the_base_had_is_still_skipped(self):
170        t, session = self.tuner(free_before=23654, free_after=18000)
171        r = t.run()
172        self.assertFalse(any(flag(a, "--kv-resident") == "65536" for a, _ in session.runs))
173        self.assertTrue(any(a["status"] == "skipped" and "memory" in a["reason"] for a in r.arms))
174
175    def test_a_candidate_that_needs_more_than_the_base_asks_for_the_difference(self):
176        t, _ = self.tuner(free_before=23654, free_after=24680)
177        t.base_runs.append(tune_session.RunResult(status="PASS", rss_peak_mib=23429.0))
178        t._base_start_avail = 23654.0
179        t.system = lambda: {"memory": {"available_mib": 24680, "total_mib": 32000}}
180        self.assertIsNone(t._ram_guard(0, "x", wait_s=0))
181        self.assertIn("not enough free memory", t._ram_guard(4096, "x", wait_s=0) or "")     # 23.1 + 4 GiB needed, 24.1 free
182
183    def test_skipped_for_memory_is_said_instead_of_already_the_fastest(self):
184        """Owner 11-04: 'N settings could not be tried: not enough free memory', only when some were skipped for memory, in place of 'already the fastest'."""
185        t, session = self.tuner(free_before=23654, free_after=24680, big_card=True, gain=1.0)
186        r = t.run()
187        self.assertEqual([(a["id"], a["status"]) for a in r.arms if a["status"] == "skipped"], [("prefill_32k", "skipped")], r.arms)
188        self.assertEqual(r.outcome, "default_confirmed")
189        self.assertEqual(r.not_tried, 1)
190        self.assertEqual(r.message, "1 setting could not be tried: not enough free memory")
191        self.assertNotIn("fastest", r.message)
192        self.assertEqual(r.values["not_tried"], 1)
193        from strata_cli.launch.runner import tune_words
194        word, sentence = tune_words(r.to_dict())
195        self.assertEqual(sentence, "1 setting could not be tried: not enough free memory")
196        self.assertNotEqual(word, "already fastest")
197
198    def test_the_plural(self):
199        from strata_cli.launch.runner import tune_words
200        self.assertEqual(tune_words({"outcome": "default_confirmed", "not_tried": 2})[1], "2 settings could not be tried: not enough free memory")
201
202    def test_nothing_skipped_keeps_the_old_sentences(self):
203        t, session = self.tuner(free_before=23654, free_after=24680, gain=1.0)
204        r = t.run()
205        self.assertEqual(r.not_tried, 0)
206        self.assertEqual(r.message, "Your current settings are already the fastest we found. Nothing was changed.")
207        from strata_cli.launch.runner import tune_words
208        self.assertEqual(tune_words(r.to_dict())[0], "already fastest")
209
210    def test_the_old_rule_still_holds_when_the_base_had_plenty(self):
211        t, session = self.tuner(free_before=40000, free_after=9000)
212        t.run()
213        self.assertEqual(len(session.runs), 1, "only the base was started")
214
215
216if __name__ == "__main__":
217    unittest.main()