okami.mom/strata

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

Niko1221Tests that pinned old values follow the merged decisions: native-fit (MTP layer 1.08 GB), tune-outcome (calm running step, GUI feedback 2 item 3), setup tests (128K default context on every card; the picture-file host in strata_control/pictures.py is behind acquisition.require)c0380157d

main
30.6 KiB568 linesraw
1"""Tests for the owner's rule in setup.py - it recommends, it never forces: a choice bigger than the recommendation is
2kept and its risk said (#406's 256K on 64 GB, #364/#384's two GPUs in the low-RAM mode, #403's RAM budget), and the
3stops that stay are the ones a user can confirm (confirm_risk: --yes with an explicit flag, or y).  The defaults are
4tools/test_setup_golden.py's.  Mocked - no GPU, no downloads, nothing written outside a temp folder.
5
6    python -m unittest tools.test_setup_risk
7"""
8from __future__ import annotations
9
10import contextlib
11import io
12import itertools
13import json
14import os
15import sys
16import tempfile
17import unittest
18from pathlib import Path
19from unittest import mock
20
21ROOT = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT))
23sys.path.insert(0, str(ROOT / "tools"))
24import setup  # noqa: E402
25from test_setup_golden import PROFILES, card, install  # noqa: E402
26
27
28def arg(cfg, flag):
29    a = cfg["args"]
30    return a[a.index(flag) + 1] if flag in a else None
31
32
33def run(fn, *args, stdin=None):
34    """-> (exit code or None, printed text, questions asked); stdin answers every input() (None: never asked)."""
35    out, asked, code = io.StringIO(), [], None
36
37    def fake_input(prompt=""):
38        asked.append(prompt)
39        if stdin is None:
40            raise AssertionError(f"asked {prompt!r} with --yes")
41        return stdin
42
43    with contextlib.redirect_stdout(out), mock.patch("builtins.input", fake_input):
44        try:
45            fn(*args)
46        except SystemExit as e:
47            code = e.code
48    return code, out.getvalue(), asked
49
50
51class ConfirmRisk(unittest.TestCase):
52    """S6: one helper for the stops a user may take on."""
53
54    def go(self, explicit, yes, stdin=None):
55        return run(setup.confirm_risk, "it may not fit", explicit, yes, "it does not fit", "a smaller size",
56                   stdin=stdin)
57
58    def test_yes_with_an_explicit_choice_is_consent(self):
59        code, out, asked = self.go(True, True)
60        self.assertIsNone(code)
61        self.assertIn("it may not fit", out)
62        self.assertEqual(asked, [])
63
64    def test_yes_alone_keeps_the_stop(self):
65        code, out, asked = self.go(False, True)
66        self.assertEqual(code, 1)
67        self.assertIn("it does not fit", out)
68        self.assertIn("a smaller size", out)
69
70    def test_interactive_default_is_no(self):
71        for explicit in (True, False):
72            code, out, asked = self.go(explicit, False, stdin="")
73            self.assertEqual(code, 1)
74            self.assertIn("[n]", asked[0])
75            self.assertIsNone(self.go(explicit, False, stdin="y")[0])
76
77    def test_paging_with_an_explicit_model(self):
78        code, out, asked = run(setup.confirm_paging, "IQ3_XXS", 54, "auto", True, True)
79        self.assertIsNone(code, out)
80        self.assertIn("installing IQ3_XXS with 54 GB of RAM, as you chose (--model)", out)
81
82
83class Context(unittest.TestCase):
84    """S1 (#406 #364): the RAM rule recommends, an explicit or picked context is kept with a note."""
85    RAM64, GPU32 = PROFILES["64GB-1x32GB"]
86
87    def test_the_ram_rule(self):
88        self.assertEqual(setup.ram_ctx("IQ3_S", 63.7), 131072)
89        self.assertEqual(setup.ram_ctx("IQ3_XXS", 63.7), 131072)
90        self.assertEqual(setup.ram_ctx("IQ3_XXS", 95.8), 524288)      # 43 + 7.2 + 24 GB fits 96
91        self.assertEqual(setup.ram_ctx("IQ3_S", 76.5), 131072)
92        self.assertEqual(setup.ram_ctx("IQ3_S", 78.5), 262144)
93        # #608: where the 200K estimate fits and the 256K one does not, the rule stays at 128K (200K is a menu step)
94        self.assertLessEqual(setup.ctx_ram_need("IQ3_S", 204800), 78.5)
95        self.assertGreater(setup.ctx_ram_need("IQ3_S", 262144), 77.5)
96        self.assertEqual(setup.ram_ctx("IQ3_S", 77.5), 131072)
97        for ram in range(16, 200):
98            for model in ("IQ3_S", "IQ3_XXS", "Q2_0"):
99                self.assertNotEqual(setup.ram_ctx(model, float(ram)), 204800)
100        self.assertEqual(setup.ram_ctx("Q2_0", 31.9), 524288)          # other sizes: no RAM rule
101        self.assertEqual(setup.ram_ctx("IQ3_XXS", 31.9, low_ram=True), 524288)   # the KV cache is in VRAM there
102        self.assertIsNone(setup.ctx_ram_need("IQ3_XXS", 262144, low_ram=True))
103        self.assertAlmostEqual(setup.ctx_ram_need("IQ3_S", 262144), 77.9, places=1)
104
105    def test_an_explicit_256k_is_kept(self):
106        code, out, cfg, _ = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start",
107                                                             "--context", "262144"])
108        self.assertEqual(code, 0, out)
109        self.assertEqual(arg(cfg, "--max-context"), "262144")
110        self.assertNotIn("--rope-scaling", cfg["args"])
111        self.assertIn("256K with IQ3_S needs ~78 GB of RAM by setup's estimate", out)
112        self.assertIn("this PC has 64. Kept as you chose: it may be slower or run out of RAM under load. 128K is the "
113                      "recommended size.", out)
114
115    def test_a_picked_256k_is_kept_and_the_menu_says_the_risk(self):
116        code, out, cfg, asked = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start"],
117                                        answers={"Context?": "6"})
118        self.assertEqual(code, 0, out)
119        self.assertEqual(arg(cfg, "--max-context"), "262144")
120        self.assertIn("256K tokens   (needs ~78 GB RAM, this PC has 64: may run out of memory)", out)
121        self.assertIn("128K tokens   (recommended for your GPU)\n", out)
122        self.assertIn("Kept as you chose", out)
123
124    def test_a_200k_choice_is_kept(self):
125        """#406: 200K was added between the 128K rule and 256K - it is inside the trained 262144, so no rope scaling,
126        and a pick of it is kept with the note 256K gets instead of being capped to 128K."""
127        code, out, cfg, _ = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start"],
128                                    answers={"Context?": "5"})
129        self.assertEqual(code, 0, out)
130        self.assertEqual(arg(cfg, "--max-context"), "204800")
131        self.assertNotIn("--rope-scaling", cfg["args"])
132        self.assertIn("200K tokens   (needs ~77 GB RAM, this PC has 64: may run out of memory)", out)
133        self.assertIn("200K with IQ3_S needs ~77 GB of RAM by setup's estimate", out)
134        self.assertIn("Kept as you chose", out)
135
136    def test_low_ram_mode_keeps_262k_without_a_ram_note(self):
137        ram, found = PROFILES["32GB-2x24GB"]                              # #364
138        code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start",
139                                                 "--context", "262144"])
140        self.assertEqual(code, 0, out)
141        self.assertEqual(arg(cfg, "--max-context"), "262144")
142        self.assertNotIn("Kept as you chose: it may be slower", out)
143
144    def test_the_earlier_install_keeps_its_context(self):
145        """An update (a new copy of Strata) set up like the earlier install keeps its 256K instead of capping it."""
146        with tempfile.TemporaryDirectory() as d:
147            prev = Path(d) / "strata-iq3_s.json"
148            prev.write_text(json.dumps({"args": ["--max-context", "262144", "--kv", "int8"], "port": 8080}))
149            started = mock.Mock(return_value=0)
150            code, out, cfg, _ = install(self.RAM64, self.GPU32, [], extra=[
151                mock.patch.object(setup, "previous_config", lambda *a: prev),
152                mock.patch.object(setup, "start", started)])
153        self.assertEqual(code, 0, out)
154        self.assertEqual(arg(cfg, "--max-context"), "262144")
155        self.assertIn("Kept as you chose", out)
156        self.assertTrue(started.called)
157
158
159class BrokenEarlierConfig(unittest.TestCase):
160    """#459: a new copy of Strata set up like an earlier install skips an earlier config that does not parse (an
161    empty strata-*.json crashed START-HERE with JSONDecodeError) and goes on as a fresh install; configs are written
162    whole (a temporary file moved over the old one)."""
163    RAM64, GPU32 = PROFILES["64GB-1x32GB"]
164
165    def setup_with(self, files):
166        with tempfile.TemporaryDirectory() as d:
167            for i, (name, text) in enumerate(files):                  # in order, oldest first
168                (Path(d) / name).write_text(text, encoding="utf-8")
169                os.utime(Path(d) / name, (1_700_000_000 + i, 1_700_000_000 + i))
170            return install(self.RAM64, self.GPU32, [], extra=[
171                mock.patch.object(setup, "other_installs", lambda settings: [Path(d)]),
172                mock.patch.object(setup, "start", mock.Mock(return_value=0))])
173
174    def test_an_empty_config_is_skipped(self):
175        for text, why in (("", "the file is empty"), ("{\"args\": [", "not valid JSON"), ("[1]", "not a JSON object")):
176            with self.subTest(text=text):
177                code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", text)])
178                self.assertEqual(code, 0, out)
179                self.assertIn("skipped the earlier config ", out)
180                self.assertIn(f"strata-iq3_s.json ({why}): setting this copy up without it", out)
181                self.assertNotIn("Found your earlier install", out)
182                self.assertIsNotNone(cfg)                                # the fresh install's config
183
184    def test_the_newest_readable_config_is_used(self):
185        good = json.dumps({"args": ["--max-context", "262144", "--kv", "int8"], "port": 8080})
186        code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", good), ("strata-q2_0.json", "")])
187        self.assertEqual(code, 0, out)
188        self.assertIn("strata-q2_0.json (the file is empty)", out)
189        self.assertIn("Found your earlier install", out)
190        self.assertIn("(iq3_s)", out)
191        self.assertEqual(arg(cfg, "--max-context"), "262144")
192
193    def test_write_config_leaves_no_partial_file(self):
194        with tempfile.TemporaryDirectory() as d:
195            p = Path(d) / "strata-iq3_s.json"
196            p.write_text("old", encoding="utf-8")
197            setup.write_config(p, {"args": ["--kv", "int8"]})
198            self.assertEqual(p.read_text(encoding="utf-8"), json.dumps({"args": ["--kv", "int8"]}, indent=1))
199            self.assertEqual([f.name for f in Path(d).iterdir()], ["strata-iq3_s.json"])   # no .tmp left
200            with mock.patch.object(Path, "write_text", side_effect=OSError(28, "No space left on device")):
201                with self.assertRaises(OSError):
202                    setup.write_config(p, {"args": []})
203            self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"args": ["--kv", "int8"]})   # kept whole
204
205
206class LowRamGpus(unittest.TestCase):
207    """S2/S3 (#364 #384): one GPU recommended in the low-RAM mode, all of them when asked for."""
208
209    def setUp(self):
210        # the behaviour before RESIDENT_SPLIT_ENGINE (an engine from before 0.1.40); the tests of the newer engine
211        # patch MIN_ENGINE themselves, and the default (MIN_ENGINE = 0.1.40) is covered by test_setup_golden
212        p = mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39))
213        p.start()
214        self.addCleanup(p.stop)
215
216    def test_explicit_gpus_are_kept_with_the_mapped_variant(self):
217        for prof, model in (("32GB-2x24GB", "IQ3_XXS"), ("32GB-2x24GB", "Q2_0"), ("47GB-2x16GB", "IQ3_XXS")):
218            with self.subTest(prof=prof, model=model):
219                ram, found = PROFILES[prof]
220                code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", model, "--no-start",
221                                                         "--gpus", "0,1"])
222                self.assertEqual(code, 0, out)
223                self.assertEqual(cfg["gpu"], [0, 1])
224                self.assertEqual(cfg["layer_split"], "auto")
225                self.assertIn("--mmap-experts", cfg["args"])
226                self.assertNotIn("--resident-experts", cfg["args"])
227                self.assertIn("as you chose (--gpus)", out)
228                self.assertIn("RAM can fill up to 0 free", out)
229                self.assertIn("low-RAM mode on 2 GPUs", out)
230
231    def test_the_share_counts_every_card(self):
232        ram, found = PROFILES["47GB-2x16GB"]                              # #384: 2 x 16 GB, 47 GB, IQ3_XXS at 64K
233        code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start",
234                                                 "--gpus", "0,1"])
235        one = setup.low_ram_gpu_gb("IQ3_XXS", 15.9, 131072, "int8")   # the 128K default
236        self.assertIn(f"the GPUs hold ~{100 * 2 * one / setup.MODELS['IQ3_XXS']['arena_gb']:.0f}% of them", out)
237
238    def test_asked_and_answered_two(self):
239        ram, found = PROFILES["32GB-2x24GB"]
240        code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"],
241                                        answers={"Low-RAM mode: which GPUs?": "2"})     # the roles are the default (Main last); the low-RAM question still defaults to one card
242        self.assertEqual(code, 0, out)
243        self.assertTrue(any("Low-RAM mode: which GPUs? [1]" in q for q in asked), asked)
244        self.assertEqual(cfg["gpu"], [0, 1])
245        self.assertIn("--mmap-experts", cfg["args"])
246        self.assertIn("1) GPU 0 (NVIDIA GeForce RTX 3090, 24 GB) only", out)
247
248    def test_yes_and_enter_keep_one_gpu(self):
249        ram, found = PROFILES["32GB-2x24GB"]
250        for answers in (None, ""):
251            code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"],
252                                        answers=answers)
253            self.assertEqual(code, 0, out)
254            self.assertEqual(cfg["gpu"], 0)
255            self.assertIn("--resident-experts", cfg["args"])
256
257    def test_low_ram_resident_with_gpus(self):
258        ram, found = PROFILES["32GB-2x24GB"]
259        code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", "--gpus", "0,1",
260                                                 "--low-ram", "resident"])
261        self.assertEqual(code, 0, out)
262        self.assertEqual(cfg["gpu"], [0, 1])
263        self.assertIn("--mmap-experts", cfg["args"])
264        self.assertIn("--low-ram resident has no layer split yet", out)
265
266    def test_low_ram_resident_alone_keeps_one_gpu_without_asking(self):
267        ram, found = PROFILES["32GB-2x24GB"]
268        code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start",
269                                                     "--low-ram", "resident"], answers="")
270        self.assertEqual(code, 0, out)
271        self.assertEqual(cfg["gpu"], 0)
272        self.assertFalse(any("Low-RAM mode" in q for q in asked), asked)
273
274    def test_low_ram_on_gpus_with_a_resident_split_engine(self):
275        """#642: an engine that runs the resident variant on a layer split keeps the cards together, resident."""
276        ram, found = PROFILES["32GB-2x24GB"]
277        with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE):
278            code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"],
279                                            answers={"Use these roles?": "y"})     # the recommended roles: Main 0 (last), Helper 1
280            self.assertEqual(code, 0, out)
281            self.assertEqual(cfg["gpu"], [0, 1])
282            self.assertIn("--resident-experts", cfg["args"])
283            self.assertFalse(any("Low-RAM mode" in q for q in asked), asked)
284            self.assertIn("stay in RAM", out)
285            code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start",
286                                                     "--gpus", "0,1", "--low-ram", "resident"])
287            self.assertEqual(code, 0, out)
288            self.assertEqual(cfg["gpu"], [0, 1])
289            self.assertIn("--resident-experts", cfg["args"])
290            self.assertNotIn("no layer split yet", out)
291
292
293class StartOnSeveralGpus(unittest.TestCase):
294    """A resident low-RAM config started on several GPUs reads the experts through the file cache (#364 #384)."""
295
296    def setUp(self):
297        # the behaviour before RESIDENT_SPLIT_ENGINE (an engine from before 0.1.40); the tests of the newer engine
298        # patch MIN_ENGINE themselves, and the default (MIN_ENGINE = 0.1.40) is covered by test_setup_golden
299        p = mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39))
300        p.start()
301        self.addCleanup(p.stop)
302
303    def test_split_mmap(self):
304        cfg = {"args": ["--pack", "p", "--resident-experts", "--kv", "int8"]}
305        out = io.StringIO()
306        with contextlib.redirect_stdout(out):
307            self.assertTrue(setup.split_mmap(cfg))
308            self.assertFalse(setup.split_mmap(cfg))
309            self.assertFalse(setup.split_mmap({"args": ["--mmap-experts"]}))
310        self.assertEqual(cfg["args"], ["--pack", "p", "--mmap-experts", "--kv", "int8"])
311        self.assertIn("no layer split yet", out.getvalue())
312
313    def offer(self, args, stdin):
314        found = PROFILES["32GB-2x24GB"][1]
315        with tempfile.TemporaryDirectory() as d:
316            p = Path(d) / "strata-q2_0.json"
317            cfg = {"args": list(args)}
318            with mock.patch.object(setup, "gpus", lambda: found), \
319                    mock.patch.object(setup, "engine_runs_on", lambda g: True):
320                code, out, asked = run(setup.offer_together, p, cfg, stdin is None, stdin=stdin)
321            return code, out, asked, json.loads(p.read_text())
322
323    def test_offer_together_recommends_one_gpu_for_a_resident_config(self):
324        code, out, asked, cfg = self.offer(["--resident-experts"], None)       # --yes: the recommendation
325        self.assertIsNone(code, out)
326        self.assertNotIn("gpu", cfg)
327        self.assertEqual(cfg["args"], ["--resident-experts"])
328        code, out, asked, cfg = self.offer(["--resident-experts"], "y")
329        self.assertIn("[n]", asked[0])
330        self.assertEqual(cfg["gpu"], [0, 1])
331        self.assertEqual(cfg["args"], ["--mmap-experts"])   # #1447: no helper cache, no --remote-expert-opt
332        code, out, asked, cfg = self.offer(["--mmap-experts"], None)           # other configs: as before
333        self.assertEqual(cfg["gpu"], [0, 1])
334
335    def test_resident_split_engine_keeps_a_resident_config(self):
336        """#642: from RESIDENT_SPLIT_ENGINE a resident config is offered both cards as any other, and stays resident."""
337        with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE):
338            cfg = {"args": ["--pack", "p", "--resident-experts", "--kv", "int8"]}
339            self.assertFalse(setup.split_mmap(cfg))
340            self.assertEqual(cfg["args"], ["--pack", "p", "--resident-experts", "--kv", "int8"])
341            code, out, asked, cfg = self.offer(["--resident-experts"], None)   # --yes: the recommendation
342            self.assertIsNone(code, out)
343            self.assertEqual(cfg["gpu"], [0, 1])
344            self.assertEqual(cfg["args"], ["--resident-experts"])
345            self.assertNotIn("OS file cache", out)
346
347    def test_start_with_gpus(self):
348        found = PROFILES["32GB-2x24GB"][1]
349        with tempfile.TemporaryDirectory() as d:
350            exe = Path(d) / "strata.exe"
351            exe.write_bytes(b"")
352            p = Path(d) / "strata-q2_0.json"
353            p.write_text(json.dumps({"exe": str(exe), "args": ["--resident-experts"], "gpu": 0, "gpus_asked": True}))
354            call = mock.Mock(return_value=0)
355            with mock.patch.object(setup, "gpus", lambda: found), \
356                    mock.patch.object(setup, "ensure_engine_for", lambda cards, path, cfg, yes: cfg), \
357                    mock.patch.object(setup, "is_wsl", lambda: False), \
358                    mock.patch.object(setup.subprocess, "call", call):
359                code, out, _ = run(setup.start, p, None, [0, 1], False, True)
360            cfg = json.loads(p.read_text())
361        self.assertIsNone(code, out)
362        self.assertEqual(cfg["gpu"], [0, 1])
363        self.assertEqual(cfg["args"], ["--mmap-experts"])   # #1447: no helper cache, no --remote-expert-opt
364        self.assertIn("no layer split yet", out)
365        self.assertTrue(call.called)
366
367
368class SmallCard(unittest.TestCase):
369    """S9: a card under 8 GB named with --gpus is a risk to confirm, not a stop."""
370    FOUND = [card(0, "NVIDIA GeForce RTX 3090", 24.0, "86"), card(1, "NVIDIA GeForce RTX 2060", 6.0, "75")]
371
372    def test_named_with_yes(self):
373        code, out, cfg, _ = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start",
374                                                       "--gpus", "0,1"])
375        self.assertEqual(code, 0, out)
376        self.assertEqual(cfg["gpu"], [0, 1])
377        self.assertIn("GPU 1 (NVIDIA GeForce RTX 2060) has 6 GB of VRAM", out)
378        self.assertIn("is used together with the others, as you chose", out)
379
380    def test_named_and_enter_stops(self):
381        code, out, cfg, asked = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start",
382                                                           "--gpus", "0,1"], answers="")
383        self.assertEqual(code, 1)
384        self.assertTrue(any("Use it anyway?" in q for q in asked), asked)
385
386    def test_not_named_is_not_offered(self):
387        code, out, cfg, _ = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start"])
388        self.assertEqual(code, 0, out)
389        self.assertEqual(cfg["gpu"], 0)                                   # one card: as before
390
391
392class SplitShortCard(unittest.TestCase):
393    """#448: a second card too small to lend a split's prompt chunk: the first card alone recommended, the pair kept
394    when named."""
395    FOUND = [card(0, "NVIDIA RTX PRO 4500 Blackwell", 31.8, "120"), card(1, "NVIDIA GeForce RTX 3080", 10.0, "86")]
396
397    def test_rule(self):
398        self.assertEqual([g["index"] for g in setup.split_short(self.FOUND)], [1])
399        self.assertEqual(setup.split_short(PROFILES["32GB-2x24GB"][1]), [])
400        self.assertEqual(setup.split_short(PROFILES["47GB-2x16GB"][1]), [])
401        eights = [card(i, "NVIDIA GeForce RTX 3070", 8.0, "86") for i in range(2)]
402        self.assertEqual(setup.split_short(eights), [])                   # neither card alone reads more
403
404    def test_yes_takes_the_recommended_roles(self):
405        """The 10 GB card is above the 8 GB line, so it starts as a Helper (the owner's rule); the first card is Main and goes last."""
406        code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start"])
407        self.assertEqual(code, 0, out)
408        self.assertEqual(cfg["gpu"], [1, 0])
409        self.assertEqual(cfg["gpu_roles"], {"0": "main", "1": "helper"})
410
411    def test_named_pair_is_kept(self):
412        code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start",
413                                                        "--gpus", "0,1"])
414        self.assertEqual(code, 0, out)
415        self.assertEqual(cfg["gpu"], [0, 1])
416
417    def test_offer_together_defaults_to_one(self):
418        with tempfile.TemporaryDirectory() as d:
419            p = Path(d) / "strata-q2_0.json"
420            with mock.patch.object(setup, "gpus", lambda: self.FOUND), \
421                    mock.patch.object(setup, "engine_runs_on", lambda g: True):
422                code, out, asked = run(setup.offer_together, p, {"args": ["--mmap-experts"]}, True)
423            cfg = json.loads(p.read_text())
424        self.assertIsNone(code, out)
425        self.assertNotIn("gpu", cfg)
426        self.assertIn("#448", out)
427
428
429class RamFloor(unittest.TestCase):
430    """S7: less RAM than the smallest model needs: a stop with --yes alone, a risk with --model."""
431    FOUND = [card(0, "NVIDIA GeForce RTX 3060", 8.0, "86")]
432
433    def test_yes_alone_stops(self):
434        code, out, cfg, _ = install(19.9, self.FOUND, ["--family", "qwen", "--no-start"])
435        self.assertEqual(code, 1)
436        self.assertIn("--model NAME --yes", out)
437
438    def test_an_explicit_model_goes_on(self):
439        code, out, cfg, _ = install(19.9, self.FOUND, ["--family", "coder", "--model", "IQ1_M", "--no-start"])
440        self.assertEqual(code, 0, out)
441        self.assertIn("going on with 20 GB of RAM, as you chose", out)
442
443
444class KvStreaming(unittest.TestCase):
445    """8: --kv-streaming on|off|auto (auto: the RAM test, as before)."""
446    RAM, FOUND = PROFILES["64GB-1x32GB"]
447
448    def go(self, model, *flags):
449        return install(self.RAM, self.FOUND, ["--family", "qwen", "--model", model, "--no-start", *flags])
450
451    def test_off(self):
452        code, out, cfg, _ = self.go("IQ3_XXS", "--kv-streaming", "off")
453        self.assertEqual(code, 0, out)
454        self.assertNotIn("--kv-resident", cfg["args"])
455        self.assertIn("KV streaming off, as you chose", out)
456
457    def test_on_past_the_ram_test(self):
458        # auto leaves it off on 58 GB: IQ3_S needs 50.3 (experts) + 10 (room) + 1.8 (the cache) = 62.1 GB
459        code, out, cfg, _ = install(58.0, self.FOUND, ["--family", "qwen", "--model", "IQ3_S", "--no-start", "--kv-streaming", "on"])
460        self.assertEqual(code, 0, out)
461        self.assertEqual(arg(cfg, "--kv-resident"), "32768")
462        self.assertIn("Kept as you chose (--kv-streaming on)", out)
463        self.assertIn("KV streaming needs ~62 GB of RAM for IQ3_S", out)
464
465    def test_auto_streams_a_64gb_pc_with_few_experts_in_vram(self):
466        """KV-128: the owner's PC reads 63.1 GB; the all-in-RAM rule asked 64.8 and left the cache in VRAM."""
467        card5070 = [card(0, "NVIDIA GeForce RTX 5070", 11.9, "120")]
468        code, out, cfg, _ = install(63.1, card5070, ["--family", "qwen", "--model", "IQ3_S", "--no-start", "--context", "131072"])
469        self.assertEqual(code, 0, out)
470        self.assertEqual(arg(cfg, "--kv-resident"), "32768")
471        self.assertIn("KV streaming on: the context's KV cache lives in RAM", out)
472        self.assertNotIn("Kept as you chose", out)
473
474    def test_auto_stays_off_just_below_the_rule(self):
475        code, out, cfg, _ = install(61.9, self.FOUND, ["--family", "qwen", "--model", "IQ3_S", "--no-start", "--context", "131072"])
476        self.assertEqual(code, 0, out)
477        self.assertNotIn("--kv-resident", cfg["args"])
478        self.assertIn("KV streaming off: it needs ~62 GB of RAM for IQ3_S", out)
479
480    def test_below_64k_is_never_streamed_on_auto(self):
481        code, out, cfg, _ = install(63.1, self.FOUND, ["--family", "qwen", "--model", "IQ3_S", "--no-start", "--context", "32768"])
482        self.assertEqual(code, 0, out)
483        self.assertNotIn("--kv-resident", cfg["args"])
484
485    def test_k8v4_streams(self):
486        code, out, cfg, _ = self.go("Q2_0", "--kv-streaming", "on", "--kv", "k8v4")
487        self.assertEqual(code, 0, out)
488        self.assertEqual(arg(cfg, "--kv-resident"), "32768")
489        self.assertEqual(arg(cfg, "--kv"), "k8v4")
490
491    def test_on_where_it_cannot(self):
492        code, out, cfg, _ = self.go("Q2_0", "--kv-streaming", "on", "--context", "32768")
493        self.assertNotIn("--kv-resident", cfg["args"])
494        self.assertIn("a context under 64K is not streamed", out)
495
496    def test_budget_flag_on_another_size(self):
497        code, out, cfg, _ = self.go("Q2_0", "--resident-budget-gib", "30")
498        self.assertEqual(code, 0, out)
499        self.assertNotIn("--resident-budget-gib", cfg["args"])
500        self.assertIn("--resident-budget-gib is for UD-Q4_K_XL", out)
501
502
503class KvStreamingNeed(unittest.TestCase):
504    """KV-128: the RAM setup asks before it streams the KV cache by itself (`kv_streaming_need_gb`)."""
505
506    def test_the_numbers(self):
507        need = lambda m, kv="int8", ctx=131072: round(setup.kv_streaming_need_gb(m, ctx, kv), 1)
508        self.assertEqual(need("IQ3_S"), 62.1)       # 50.3 + 10 + 1.8; the all-in-RAM rule said 62 + 1.7 + 1 = 64.7
509        self.assertEqual(need("IQ3_XXS"), 54.7)     # 42.9 + 10 + 1.8
510        self.assertEqual(need("Q2_0"), 45.8)        # 34 + 10 + 1.8
511        self.assertEqual(need("IQ3_S", "q4_0"), 61.3)
512
513    def test_never_asks_more_than_before(self):
514        for model, ctx, kv in itertools.product(setup.MODELS, (65536, 131072, 262144), ("int8", "q4_0", "k8v4")):
515            before = setup.MODELS[model]["ram_gb"] + setup.kv_streaming_ram_gb(ctx, kv) + 1
516            self.assertLessEqual(setup.kv_streaming_need_gb(model, ctx, kv), before, (model, ctx, kv))
517
518    @mock.patch.object(setup, "is_wsl", lambda: False)
519    def test_the_rule(self):
520        want = lambda ram, ctx=131072, choice="auto": setup.kv_streaming_wanted("IQ3_S", ctx, "int8", ram, choice)
521        self.assertTrue(want(63.1))
522        self.assertTrue(want(62.1))
523        self.assertFalse(want(62.0))
524        self.assertFalse(want(31.9))                 # a PC in the low-RAM mode keeps the KV in VRAM
525        self.assertFalse(want(63.1, 32768))
526        self.assertFalse(want(63.1, choice="off"))
527        self.assertTrue(want(31.9, choice="on"))
528
529    @mock.patch.object(setup, "is_wsl", lambda: True)
530    def test_wsl_never_streams(self):
531        self.assertFalse(setup.kv_streaming_wanted("IQ3_S", 131072, "int8", 128.0))
532
533
534class RulesAgreeWithTheWrittenConfig(unittest.TestCase):
535    """The launcher's preset diff asks setup's rules (`kv_streaming_wanted`, `low_ram_wanted`) what "auto" decides on
536    this PC, instead of comparing the word "auto" with a config's flags.  That is only honest if those rules are
537    exactly what setup writes into the model's config: the same PC, the same flags, every size and every
538    --kv-streaming / --low-ram choice."""
539    RAM64, CARDS64 = PROFILES["64GB-1x32GB"]
540    RAM32, CARDS32 = PROFILES["32GB-2x24GB"]
541
542    def go(self, ram, cards, model, *flags):
543        return install(ram, cards, ["--family", "qwen", "--model", model, "--no-start", *flags])
544
545    @mock.patch.object(setup, "is_wsl", lambda: False)   # #974: not WSL, as in install()
546    def test_the_streaming_rule_is_the_flag_setup_writes(self):
547        for model, ctx, kv, choice in itertools.product(("Q2_0", "IQ3_XXS", "IQ3_S"), ("32768", "131072"),
548                                                        ("int8", "q4_0", "k8v4"), ("auto", "on", "off")):
549            code, out, cfg, _ = self.go(self.RAM64, self.CARDS64, model, "--context", ctx, "--kv", kv,
550                                        "--kv-streaming", choice)
551            self.assertEqual(code, 0, out)
552            self.assertEqual("--kv-resident" in cfg["args"],
553                             setup.kv_streaming_wanted(model, int(ctx), kv, self.RAM64, choice),
554                             f"{model} at {ctx} with {kv}, --kv-streaming {choice}: setup wrote {cfg['args']}")
555
556    def test_the_low_ram_rule_is_the_flag_setup_writes(self):
557        pcs = [(self.RAM64, self.CARDS64), (self.RAM32, self.CARDS32)]      # auto is on here, off there
558        for (ram, cards), model, choice in itertools.product(pcs, ("Q2_0", "IQ3_XXS", "IQ3_S"),
559                                                              ("auto", "on", "off", "mmap")):
560            code, out, cfg, _ = self.go(ram, cards, model, "--low-ram", choice)
561            self.assertEqual(code, 0, out)
562            low = "--resident-experts" in cfg["args"] or "--mmap-experts" in cfg["args"]
563            self.assertEqual(low, setup.low_ram_wanted(model, ram, choice),
564                             f"{model} on {ram:.0f} GB of RAM, --low-ram {choice}: setup wrote {cfg['args']}")
565
566
567if __name__ == "__main__":
568    unittest.main()