okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
26.7 KiB437 linesraw
1"""strata_control/vram_fit.py: the fit math with mock card sizes, and its use in setup (sycl/setup_intel.py) and strata launch."""
2
3from __future__ import annotations
4
5import importlib.util
6import sys
7import unittest
8from pathlib import Path
9
10ROOT = Path(__file__).resolve().parents[2]
11sys.path.insert(0, str(ROOT))
12
13from strata_control import vram_fit as V  # noqa: E402
14
15
16class Measured(unittest.TestCase):
17    """The estimate against the 12 starts on the Arc A750 (8 GB): engine slots / MiB short, from /data/022-arcgyro/out/fa_*.txt."""
18
19    def slack(self, ctx, reserve, prefill):
20        return V.slack_mib("Gyro-M", 8.0, ctx, "int8", reserve, prefill, "intel")
21
22    def test_the_session_matches_the_engines_three_numbers(self):
23        for ctx, mib in ((8192, 234), (16384, 347), (32768, 573)):
24            self.assertAlmostEqual(V.session_mib(ctx), mib, delta=8)
25
26    def test_the_default_does_not_start_and_the_estimate_says_how_short(self):
27        self.assertAlmostEqual(self.slack(32768, 300, "auto"), -747, delta=40)     # engine: about 748 MiB more
28        self.assertAlmostEqual(self.slack(16384, 300, "auto"), -497, delta=40)     # 497
29        self.assertAlmostEqual(self.slack(8192, 100, "auto"), -171, delta=40)      # 171
30
31    def test_the_known_good_start_has_room_for_its_slots(self):
32        self.assertAlmostEqual(self.slack(8192, 100, 1024), 412 * V.SLOT_MIB, delta=60)    # 412 slots
33        self.assertAlmostEqual(self.slack(32768, 100, 1024), 107 * V.SLOT_MIB, delta=60)   # 107 slots
34        self.assertAlmostEqual(self.slack(8192, 100, 512), 683 * V.SLOT_MIB, delta=60)     # 683 slots
35        self.assertAlmostEqual(self.slack(8192, 100, 256), 820 * V.SLOT_MIB, delta=60)     # 820 slots
36
37    def test_gyro_s_default_fits_as_it_did(self):
38        self.assertTrue(V.fits("Gyro-S", 8.0, 32768, "int8", 300, "auto", "intel"))        # 410 slots measured
39
40
41class Plan(unittest.TestCase):
42    """The rule (owner, 2026-11-02): a fit never changes the context or the number of requests; it moves work off the GPU, and says so."""
43
44    def test_gyro_m_on_8gb_reads_prompts_in_smaller_chunks_and_keeps_its_context(self):
45        f = V.plan("Gyro-M", 8.0, 32768, "int8", 300, "auto", "intel", title="Gyro-M")
46        self.assertTrue(f.changed and f.fits)
47        self.assertEqual((f.ctx, f.reserve_mib, f.prefill), (32768, 300, "512"))      # 32K stays; the chunk is the cheap knob, the reserve is not touched
48        self.assertTrue(f.line.startswith("Gyro-M on this 8 GB card: " + V.NOTE_SLOW), f.line)
49        self.assertGreaterEqual(f.slack_mib, V.needed_mib())
50
51    def test_the_context_is_never_changed_for_any_card(self):
52        for model in ("Gyro-M", "Gyro-S", "Qwen3.8-Flash-Next-IQ3_S"):
53            for vendor in ("intel", "cuda", "other"):
54                for gb in (5.0, 6.0, 8.0, 9.0, 10.0, 12.0, 16.0, 24.0, 48.0):
55                    for ctx in (8192, 32768, 131072, 262144):
56                        for slots in (0, 2, 4):
57                            f = V.plan(model, gb, ctx, "int8", 700, "auto", vendor, slots=slots, kv_resident=32768 if ctx >= 65536 else 0)
58                            self.assertEqual(f.ctx, ctx, (model, vendor, gb, ctx, slots))
59                            self.assertEqual(f.slots, slots, (model, vendor, gb, ctx, slots))
60
61    def test_a_chosen_reserve_is_kept(self):
62        f = V.plan("Gyro-M", 8.0, 32768, "int8", 500, "auto", "intel", reserve_fixed=True)
63        self.assertEqual(f.reserve_mib, 500)
64
65    def test_a_chosen_chunk_is_kept(self):
66        f = V.plan("Gyro-M", 8.0, 32768, "int8", 300, "2048", "intel", prefill_fixed=True)
67        self.assertIsNone(f.prefill)
68
69    def test_when_nothing_more_can_move_the_start_goes_as_far_as_it_can_and_says_so(self):
70        f = V.plan("Gyro-M", 6.0, 32768, "int8", 300, "auto", "intel")
71        self.assertEqual(f.ctx, 32768)
72        self.assertEqual((f.prefill, f.reserve_mib), ("256", 100))        # every knob to its end
73        self.assertFalse(f.fits)
74        self.assertIn(V.NOTE_SLOW, f.line)
75
76    def test_a_config_that_fits_comes_back_unchanged(self):
77        for model, gb, ctx in (("Gyro-M", 12.0, 32768), ("Gyro-M", 16.0, 65536), ("Gyro-S", 8.0, 32768), ("Gyro-S", 12.0, 131072),
78                               ("Qwen3.8-Flash-Next-IQ3_XXS", 8.0, 32768), ("Qwen3.8-Flash-Next-IQ3_XXS", 12.0, 131072),
79                               ("Qwen3.8-Flash-Next-IQ3_XXS", 16.0, 262144), ("Qwen3.8-Flash-Next-IQ2_XS", 24.0, 262144)):
80            f = V.plan(model, gb, ctx, "int8", 300, "auto", "nvidia")
81            self.assertEqual((f.ctx, f.reserve_mib, f.prefill, f.changed, f.line), (ctx, 300, None, False, ""), (model, gb, ctx))
82
83    def test_unknown_card_size_and_tiny_cards_are_left_alone(self):
84        for gb in (0, None, 4.0):
85            f = V.plan("Gyro-M", gb, 32768, "int8", 300, "auto", "intel")
86            self.assertFalse(f.changed)
87
88    def test_fit_context_is_the_context_asked_for(self):
89        for ctx in (8192, 32768, 131072):
90            self.assertEqual(V.fit_context("Gyro-M", 8.0, ctx), ctx)
91
92    def test_generic_model_is_found_short_only_when_far_short(self):
93        self.assertFalse(V.plan("Qwen3.8-Flash-Next-IQ3_XXS", 8.0, 32768, "int8", 300, "auto", "intel").changed)
94        self.assertTrue(V.plan("Qwen3.8-Flash-Next-IQ3_XXS", 6.0, 131072, "int8", 300, "auto", "intel").changed)
95
96
97class SetupIntel(unittest.TestCase):
98    @staticmethod
99    def mod():
100        spec = importlib.util.spec_from_file_location("setup_intel_fit", ROOT / "sycl" / "setup_intel.py")
101        m = importlib.util.module_from_spec(spec)
102        spec.loader.exec_module(m)
103        return m
104
105    def cfg(self, m, native="Gyro-M-TQ2_0.gguf", extra=()):
106        base = m.MOUNT
107        return {"exe": "x", "cwd": "y", "args": ["--pack", str(base / "d" / "pack"), "--native", str(base / "d" / native),
108                                                 "--expert-cache", "auto", "--prefill", "auto", "--max-context", "32768",
109                                                 "--kv", "int8", "--vram-reserve-mib", "300", *extra]}
110
111    def val(self, c, flag):
112        return c["args"][c["args"].index(flag) + 1]
113
114    def run_it(self, m, cfg, vram, drv="i915", **kw):
115        notes = []
116        c = m.to_sycl(cfg, m.ROOT / "build-sycl" / "strata", 64.0, {}, vram, drv, "56a1", fit_notes=notes, **kw)
117        return c, notes
118
119    def test_gyro_m_on_the_a750_gets_a_config_that_starts_and_one_line(self):
120        m = self.mod()
121        c, notes = self.run_it(m, self.cfg(m), 8.0, auto_reserve=True)
122        self.assertEqual(self.val(c, "--max-context"), "32768")           # the context is the person's: it stays
123        self.assertEqual(self.val(c, "--vram-reserve-mib"), "300")
124        self.assertEqual(self.val(c, "--prefill"), "512")
125        self.assertEqual(c["args"].count("--vram-reserve-mib"), 1)
126        self.assertEqual(len(notes), 1)
127        self.assertIn("Gyro-M on this 8 GB card: short of GPU memory", notes[0])
128
129    def test_a_reserve_the_user_asked_for_is_kept(self):
130        m = self.mod()
131        c, notes = self.run_it(m, self.cfg(m), 8.0, auto_reserve=False)
132        self.assertEqual(self.val(c, "--vram-reserve-mib"), "300")
133        self.assertEqual(self.val(c, "--max-context"), "32768")
134
135    def test_a_context_the_user_asked_for_is_kept(self):
136        m = self.mod()
137        c, notes = self.run_it(m, self.cfg(m), 8.0, auto_reserve=True, ctx_asked=True)
138        self.assertEqual(self.val(c, "--max-context"), "32768")
139
140    def test_configs_that_fit_are_byte_identical(self):
141        m = self.mod()
142        for vram, drv in ((8.0, "i915"), (12.0, "xe"), (16.0, "i915"), (24.0, "xe"), (32.0, "xe")):
143            for native in ("a.gguf", "Gyro-S-TQ1_0.gguf"):
144                off, _ = self.run_it(m, self.cfg(m, native), vram, drv, fit=False)
145                on, notes = self.run_it(m, self.cfg(m, native), vram, drv, auto_reserve=True)
146                self.assertEqual(off, on, (vram, drv, native))
147                self.assertEqual(notes, [])
148
149
150FN = "qwen3.8-flash-next-iq3_xxs"
151
152
153class SlotSessions(unittest.TestCase):
154    """Request slots ("Concurrent requests" 2 or more, the engine's --batch N): each slot is a session of its own, out of the expert cache's room.
155    The 8 GB Arc A750 figures are the engine's: --batch 2 at 8192 tokens with the MTP layer and a 1024 MiB reserve left 2519 MiB free and the cache needed 99 MiB
156    more (0 slots, a refused start; a SIGSEGV before ab7baa5b1)."""
157
158    def test_the_slot_session_is_the_main_sessions_size(self):
159        self.assertAlmostEqual(V.session_mib(8192), 234, delta=8)       # the engine: "2 slot sessions (0.23 GiB each)"
160
161    def test_kv_streaming_caps_what_a_session_keeps_in_vram(self):
162        full = V.session_mib(131072)
163        streamed = V.session_mib(131072, "int8", 32768)
164        self.assertAlmostEqual(full, 1929, delta=15)
165        self.assertAlmostEqual(streamed, 748, delta=15)                  # measured 0.73 GiB on the CUDA engine (DF2-MEM): the 32K pool (573 MiB with its fixed part) plus what scales with the whole context
166        self.assertEqual(V.session_mib(8192, "int8", 32768), V.session_mib(8192))     # a resident window larger than the context changes nothing
167        self.assertAlmostEqual(V.session_mib(131072, "int8", 4096), V.session_mib(131072, "int8", V.KV_RESIDENT_MIN), delta=0.01)   # the engine raises a smaller window to its minimum (4096)
168
169    def test_without_slots_nothing_changes(self):
170        a = V.slack_mib(FN, 8.0, 8192, "int8", 700, "auto", "intel")
171        self.assertEqual(a, V.slack_mib(FN, 8.0, 8192, "int8", 700, "auto", "intel", 0))
172        self.assertEqual(a, V.slack_mib(FN, 8.0, 8192, "int8", 700, "auto", "intel", 1))
173        self.assertEqual(V.needed_mib(), V.needed_mib(FN, 1))
174
175    def test_the_engines_own_minimum_is_the_threshold(self):
176        self.assertAlmostEqual(V.needed_mib(FN, 2, "intel"), V.SLOT_RUN_MIN * V.SLOT_SLOTTED_MIB + V.MARGIN_MIB, delta=0.01)    # one slot and the margin, not 128 slots
177        self.assertGreater(V.needed_mib(FN, 0), 128 * 1.2)                                                                          # a single request keeps its old rule
178
179    def test_an_8gb_arc_with_two_requests_and_the_refused_reserve_reads_prompts_in_smaller_chunks(self):
180        # 8192 with a 1024 MiB reserve is the start the engine refused (the estimate says 137 MiB short; the engine 99)
181        self.assertLess(V.slack_mib(FN, 8.0, 8192, "int8", 1024, "auto", "intel", 2), 0)
182        f = V.plan(FN, 8.0, 8192, "int8", 1024, "auto", "intel", title=FN, reserve_fixed=True, slots=2)
183        self.assertTrue(f.changed and f.fits)
184        self.assertEqual((f.ctx, f.slots, f.reserve_mib, f.prefill), (8192, 2, 1024, "1024"))      # the context and the 2 requests stay
185        self.assertGreaterEqual(f.slack_mib, V.needed_mib(FN, 2, "intel"))
186        self.assertIn(V.NOTE_SLOW, f.line)
187
188    def test_an_8gb_arc_whose_start_the_engine_runs_is_not_touched(self):
189        # a 700 MiB reserve at 8192 leaves the cache about 84 slots: the engine runs it
190        f = V.plan(FN, 8.0, 8192, "int8", 700, "auto", "intel", title=FN, reserve_fixed=True, prefill_fixed=True, slots=2)
191        self.assertFalse(f.changed)
192        self.assertEqual((f.ctx, f.slots), (8192, 2))
193
194    def test_not_even_every_knob_fits_then_the_start_goes_as_far_as_it_can_with_the_same_requests(self):
195        f = V.plan(FN, 6.0, 8192, "int8", 1500, "auto", "intel", title=FN, reserve_fixed=True, slots=2)
196        self.assertEqual((f.ctx, f.slots), (8192, 2))
197        self.assertEqual(f.prefill, "256")
198        self.assertFalse(f.fits)
199
200    def test_a_12gb_card_keeps_128k_with_streamed_kv(self):
201        # setup writes --kv-resident 32768 at 128K: each of the 3 sessions keeps about 750 MiB (measured), not 1.9 GB
202        for vendor in ("intel", "cuda"):
203            f = V.plan(FN, 12.0, 131072, "int8", 700, "auto", vendor, title=FN, reserve_fixed=True, prefill_fixed=True, slots=2, kv_resident=32768)
204            self.assertFalse(f.changed, vendor)
205            self.assertEqual((f.ctx, f.slots), (131072, 2))
206        self.assertGreater(V.slack_mib(FN, 12.0, 131072, "int8", 700, "auto", "intel", 2, 32768), 2000)
207        # charging each slot the whole 128K would have lowered it (the mistake of 2a1042877)
208        self.assertLess(V.slack_mib(FN, 12.0, 131072, "int8", 700, "auto", "intel", 2, 0), 0)
209
210    def test_a_card_with_no_measured_figure_is_left_to_the_engine(self):
211        f = V.plan(FN, 8.0, 8192, "int8", 1024, "auto", "other", title=FN, reserve_fixed=True, prefill_fixed=True, slots=2)
212        self.assertFalse(f.changed)                # HIP: no measured base yet, so no claim; the engine sizes its cache and says what is short
213        self.assertEqual(f.ctx, 8192)
214
215    def test_a_24gb_cuda_card_is_unchanged(self):
216        f = V.plan(FN, 24.0, 131072, "int8", 700, "auto", "cuda", title=FN, reserve_fixed=True, prefill_fixed=True, slots=4, kv_resident=32768)
217        self.assertFalse(f.changed)
218        self.assertEqual((f.ctx, f.slots, f.line), (131072, 4, ""))
219
220
221class FitStart(unittest.TestCase):
222    """fit_start: the engine arguments of one start (serve/server.py engine_args calls it).  It never changes --max-context and never the requests at once."""
223
224    ARGS = ["--native", "/m/Qwen3.8-Flash-Next-IQ3_XXS-00001-of-00002.gguf", "--expert-cache", "auto", "--prefill", "auto", "--max-context", "8192",
225            "--kv", "int8", "--vram-reserve-mib", "1024", "--mtp", "/m/rt", "--spec", "4"]
226
227    def cfg(self, **kw):
228        c = {"model_name": FN, "parallel": 2}
229        c.update(kw)
230        return c
231
232    def test_an_8gb_arc_reads_prompts_in_smaller_chunks_and_keeps_context_and_requests(self):
233        args, par, note = V.fit_start(self.cfg(), list(self.ARGS), 8192, "sycl")
234        self.assertEqual(args[args.index("--max-context") + 1], "8192")
235        self.assertEqual(args[args.index("--prefill") + 1], "1024")
236        self.assertIsNone(par)                                 # still 2 requests at once
237        self.assertIn(V.NOTE_SLOW, note)
238        self.assertEqual(self.ARGS[self.ARGS.index("--prefill") + 1], "auto")           # the input is not touched
239
240    def test_the_persons_own_reserve_and_chunk_are_kept(self):
241        args, par, note = V.fit_start(self.cfg(user_args=["--vram-reserve-mib", "1024"]), list(self.ARGS), 8192, "sycl")
242        self.assertEqual(args[args.index("--vram-reserve-mib") + 1], "1024")
243        args2 = [("2048" if a == "auto" else a) for a in self.ARGS]
244        self.assertEqual(V.fit_start(self.cfg(), list(args2), 8192, "sycl")[0][args2.index("--prefill") + 1], "2048")
245
246    def test_a_12gb_card_at_128k_with_streamed_kv_is_unchanged(self):
247        a = ["--native", "/m/Qwen3.8-Flash-Next-IQ3_S-00001-of-00002.gguf", "--max-context", "131072", "--kv", "int8", "--kv-resident", "32768",
248             "--vram-reserve-mib", "700"]
249        for backend in ("cuda", "sycl"):
250            self.assertEqual(V.fit_start(self.cfg(model_name="qwen3.8-flash-next-iq3_s"), list(a), 12288, backend), (a, None, ""), backend)
251
252    def test_a_24gb_cuda_card_and_one_request_are_unchanged(self):
253        big = ["--native", "/m/q.gguf", "--max-context", "131072", "--kv", "int8", "--vram-reserve-mib", "700"]
254        self.assertEqual(V.fit_start(self.cfg(parallel=4), list(big), 24576, "cuda"), (big, None, ""))
255        self.assertEqual(V.fit_start(self.cfg(parallel=1), list(self.ARGS), 8192, "sycl"), (self.ARGS, None, ""))
256        self.assertEqual(V.fit_start({"model_name": FN}, list(self.ARGS), 8192, "sycl"), (self.ARGS, None, ""))
257
258    def test_nothing_without_one_cards_memory_or_on_a_split_or_metal(self):
259        self.assertEqual(V.fit_start(self.cfg(), list(self.ARGS), None, "sycl"), (self.ARGS, None, ""))
260        self.assertEqual(V.fit_start(self.cfg(), list(self.ARGS), 8192, "metal"), (self.ARGS, None, ""))
261        self.assertEqual(V.fit_start(self.cfg(layer_split="auto"), list(self.ARGS), 8192, "sycl"), (self.ARGS, None, ""))
262
263    def test_a_start_that_cannot_fit_keeps_its_requests_and_its_context(self):
264        tight = [a if a != "1024" else "1500" for a in self.ARGS]
265        args, par, note = V.fit_start(self.cfg(), tight, 8192, "sycl")
266        self.assertIsNone(par)
267        self.assertEqual(args[args.index("--max-context") + 1], "8192")
268        self.assertIn(V.NOTE_SLOW, note)
269
270    def test_no_context_in_the_args_is_never_added(self):
271        no_ctx = list(self.ARGS)
272        i = no_ctx.index("--max-context")
273        del no_ctx[i:i + 2]
274        args, par, note = V.fit_start(self.cfg(), no_ctx, 8192, "sycl")
275        self.assertNotIn("--max-context", args)
276
277
278class CudaSpill(unittest.TestCase):
279    """The CUDA engine, measured on the RTX PRO 5000 held to 7942 / 8966 / 9990 / 12000 MiB by a memory hog (DF2-MEM, RESULTS-DF2MEM.md): an 8 GB NVIDIA card does not start
280    the default 128K with the KV window setup writes (32768), and starts with the engine's minimum window (20480).  The knob is the window; the context and the requests stay."""
281
282    M = "qwen3.8-flash-next-iq3_s"
283    A = ["--native", "/m/Qwen3.8-Flash-Next-IQ3_S-00001-of-00002.gguf", "--max-context", "131072", "--kv", "int8", "--kv-resident", "32768",
284         "--vram-reserve-mib", "700", "--prefill", "auto"]
285    DF2 = ["--draft", "dflash2", "--draft-model", "/p/q4_0.pack", "--draft-fallback", "none", "--spec", "6", "--draft-conf", "0.8"]
286    MTP = ["--mtp", "/m/rt", "--spec", "4", "--spec-min-p", "0.5"]
287
288    def start(self, vram_mib, n=None, drafter=None, user=None, backend="cuda"):
289        cfg = {"model_name": self.M}
290        if n:
291            cfg["parallel"] = n
292        if user:
293            cfg["user_args"] = user
294        return V.fit_start(cfg, self.A + (drafter if drafter is not None else self.DF2), vram_mib, backend)
295
296    @staticmethod
297    def flag(args, name):
298        return args[args.index(name) + 1] if name in args else None
299
300    def test_the_base_reproduces_the_engines_cache_room(self):
301        g = lambda free: (free + V.GAP_OTHER_MIB) / 1024.0
302        sl = lambda free, n: V.slack_mib(self.M, g(free), 131072, "int8", 700, "auto", "cuda", n, 32768)
303        self.assertAlmostEqual(sl(12000, 2), 3615 - 700 - 218 - 256, delta=60)     # "expert cache auto: 3.53 GiB free ... -> 961 slots"
304        self.assertAlmostEqual(sl(12000, 4), 2120 - 700 - 218 - 256, delta=60)     # "2.07 GiB free ... -> 371 slots"
305        self.assertAlmostEqual(sl(7800, 2), 850 - 835 - 598 - 700 - 218 - 256, delta=60)     # 0.83 GiB after the sessions, then the MTP layer and the head: the OOM
306
307    def test_an_8gb_card_with_dflash2_alone_gets_the_small_kv_window_and_keeps_128k(self):
308        for mib, window in ((8192, "20480"), (8050, None)):
309            args, par, note = self.start(mib)
310            self.assertEqual(self.flag(args, "--max-context"), "131072", mib)
311            if window:
312                self.assertEqual(self.flag(args, "--kv-resident"), window, mib)         # measured: starts and decodes at 69-73 tok/s; 32768 does not start
313            else:
314                self.assertIn(self.flag(args, "--kv-resident"), ("20480", "8192", "4096"), mib)   # a card a little smaller walks further down
315            self.assertEqual(self.flag(args, "--prefill"), "auto")                       # the engine steps its own chunk down
316            self.assertEqual(self.flag(args, "--vram-reserve-mib"), "700")               # a lower reserve starves the DFlash2 prompt staging (measured)
317            self.assertIsNone(par)
318            self.assertIn(V.NOTE_SLOW, note)
319
320    def test_an_8gb_card_with_requests_at_once_keeps_the_requests_and_the_context(self):
321        for n in (2, 4):
322            args, par, note = self.start(8192, n, self.MTP)
323            self.assertEqual(self.flag(args, "--max-context"), "131072", n)
324            self.assertIsNone(par, n)                                                     # the number of requests is the person's
325            self.assertEqual(self.flag(args, "--kv-resident"), "4096", n)               # measured: 2 requests start at 4096 (277 MiB free, 46 tok/s per user) and 8192; 32768 and 20480 do not
326            self.assertIn(V.NOTE_SLOW, note)
327
328    def test_the_window_is_walked_down_only_as_far_as_the_card_needs(self):
329        win = lambda mib, n, drafter: self.flag(self.start(mib, n, drafter)[0], "--kv-resident")
330        self.assertEqual(win(8192, None, self.DF2), "20480")       # DFlash2 alone fits at 20480
331        self.assertEqual(win(8192, None, self.MTP), "8192")        # the MTP layer needs a smaller one
332        self.assertEqual(win(10240, 2, self.MTP), "20480")
333        self.assertEqual(win(10240, 4, self.MTP), "4096")
334        self.assertEqual(win(12288, 8, self.MTP), "8192")
335        self.assertEqual(win(12288, 4, self.MTP), "32768")         # nothing moves where it fits
336
337    def test_the_window_floor_and_steps_match_the_engine(self):
338        self.assertEqual(V.KV_RESIDENT_MIN, 4096)                  # qsa_kv_resident_min()
339        self.assertEqual(V.KV_RESIDENT_STEPS, (20480, 8192, 4096))
340        self.assertTrue(all(w >= V.KV_RESIDENT_MIN for w in V.KV_RESIDENT_STEPS))
341
342    def test_12_16_and_24gb_keep_everything_for_1_2_and_4_requests(self):
343        for mib in (12288, 12282, 16384, 24576):
344            for n, drafter in ((None, self.DF2), (None, self.MTP), (2, self.MTP), (4, self.MTP)):
345                a = self.A + drafter
346                self.assertEqual(V.fit_start({"model_name": self.M, **({"parallel": n} if n else {})}, list(a), mib, "cuda"), (a, None, ""), (mib, n))
347
348    def test_the_8gb_figures_behind_it(self):
349        gb = (7942 + V.GAP_OTHER_MIB) / 1024.0
350        one = V.SLOT_RUN_MIN * V.SLOT_SLOTTED_MIB + V.MARGIN_MIB
351        sl = lambda kvr, drafter: V.slack_mib(self.M, gb, 131072, "int8", 700, "auto", "cuda", 0, kvr, drafter)
352        self.assertLess(sl(32768, "dflash2"), one)             # did not start: "the device arena (75 MiB) does not fit"
353        self.assertGreaterEqual(sl(20480, "dflash2"), one)     # started
354        self.assertLess(sl(32768, "mtp"), one)
355
356    def test_a_window_the_person_set_is_kept(self):
357        args, par, note = self.start(8192, user=["--kv-resident", "32768"])
358        self.assertEqual(self.flag(args, "--kv-resident"), "32768")
359
360    def test_metal_and_unknown_backends_are_not_claimed(self):
361        for backend in ("metal", "vulkan", None, ""):
362            a = self.A + self.DF2
363            self.assertEqual(V.fit_start({"model_name": self.M}, list(a), 8192, backend), (a, None, ""), backend)
364
365    def test_the_hip_base_is_its_own_measurement(self):
366        hip, cuda = V.BASE_SLOTTED_MIB[("hip", "flash-next")], V.BASE_SLOTTED_MIB[("cuda", "flash-next")]
367        self.assertNotEqual(hip, cuda)
368        self.assertAlmostEqual(cuda - hip, 1090, delta=200)           # the R9700 start holds about 1.1 GiB less before the cache than the CUDA one (FREE - 5045 against FREE - 6324, less the context)
369        self.assertTrue(V.HIP_BASE_NOTE.startswith("measured on an R9700"))
370
371    def test_an_8gb_discrete_amd_card_starts_as_set_up_and_a_6gb_one_walks_the_window(self):
372        # measured on the R9700 held to 7942 MiB: DFlash2 alone starts at 128K with setup's window (787 slots, 864 MiB free); at 6400 MiB it needs the loan that keeps 16
373        for mib in (8192, 8176):
374            a = self.A + self.DF2
375            self.assertEqual(V.fit_start({"model_name": self.M}, list(a), mib, "hip"), (a, None, ""), mib)
376        args, par, note = self.start(6144, backend="hip")
377        self.assertEqual(self.flag(args, "--max-context"), "131072")
378        self.assertIn(self.flag(args, "--kv-resident"), ("20480", "8192", "4096"))
379        self.assertIsNone(par)
380        self.assertIn(V.NOTE_SLOW, note)
381        for mib in (12288, 16384, 24576, 32768):
382            a = self.A + self.DF2
383            self.assertEqual(V.fit_start({"model_name": self.M}, list(a), mib, "hip"), (a, None, ""), mib)
384        for n in (2, 4):
385            args, par, note = self.start(8192, n, self.MTP, backend="hip")
386            self.assertEqual(self.flag(args, "--max-context"), "131072", n)
387            self.assertIsNone(par, n)                                        # the number of requests is never touched
388
389    def test_an_integrated_amd_chip_is_left_alone(self):
390        # serve/server.py drafting_vram_mib() returns None for Strix Halo and the other APUs (one pool with the host's RAM): fit_start does nothing without a card's memory
391        a = self.A + self.DF2
392        self.assertEqual(V.fit_start({"model_name": self.M}, list(a), None, "hip"), (a, None, ""))
393
394    def test_the_drafter_is_read_from_the_arguments(self):
395        self.assertEqual(V.drafter_of(self.A + self.DF2), "dflash2")
396        self.assertEqual(V.drafter_of(self.A + ["--mtp", "/m", "--draft", "dflash2", "--draft-model", "/p"]), "dflash2+mtp")
397        self.assertEqual(V.drafter_of(self.A + self.MTP), "mtp")
398        self.assertEqual(V.drafter_of(self.A), "none")
399
400
401
402class Reserve3750(unittest.TestCase):
403    """#3750: 256K context + Q4 KV on a small card.  The app's reserve for a card of 16 GB or less is 1536 MiB (apps/host native-resources.mjs), no longer a fifth of the
404    card (3256 on the reporter's RX 9070 XT).  The fit arithmetic prices the expert cache that is left, and it is positive at 12 GiB with the app's reserve on both
405    discrete backends; the old 3256 left the CUDA engine's measured base at its threshold (a start on the edge, which the reporter's 83 GB model fell over)."""
406
407    M = "Qwen3.8-Flash-Next-IQ3_S"
408
409    def slack(self, gb, reserve, vendor, kv_resident=0, ctx=262144):
410        return V.slack_mib(self.M, gb, ctx, "q4_0", reserve, "auto", vendor, 0, kv_resident, "mtp")
411
412    def test_a_12_gib_card_at_256k_q4_has_a_positive_cache_with_the_apps_reserve(self):
413        for vendor in ("cuda", "hip"):
414            s = self.slack(12.0, 1536, vendor)
415            self.assertGreater(s, V.needed_mib(self.M, 0, vendor, "mtp") + 1000, (vendor, s))
416            self.assertTrue(V.fits(self.M, 12.0, 262144, "q4_0", 1536, "auto", vendor, 0, 0, "mtp"), vendor)
417
418    def test_the_old_fifth_of_the_card_takes_the_room_the_reserve_cap_gives_back(self):
419        for gb, old in ((12.0, 2457), (15.9, 3256)):
420            for vendor in ("cuda", "hip"):
421                self.assertAlmostEqual(self.slack(gb, 1536, vendor) - self.slack(gb, old, vendor), old - 1536, delta=1)
422        # on a 12 GiB CUDA card the old reserve left the cache nothing beyond the working threshold
423        self.assertLess(self.slack(12.0, 3256, "cuda") - V.needed_mib(self.M, 0, "cuda", "mtp"), 100)
424
425    def test_a_fit_never_changes_the_context_and_a_fitting_start_is_returned_byte_identical(self):
426        args = ["--native", "m.gguf", "--max-context", "262144", "--kv", "q4_0", "--vram-reserve-mib", "1536", "--mtp", "mtp.gguf"]
427        for mib in (12288, 16282, 24576):
428            out = V.fit_start({"model_name": self.M}, list(args), mib, "cuda")
429            self.assertEqual(out[0], args, mib)
430            self.assertEqual(out[0][out[0].index("--max-context") + 1], "262144")
431        # a start that would be short keeps its context and its reserve and moves KV to RAM instead
432        out = V.fit_start({"model_name": self.M}, list(args), 6144, "cuda")
433        self.assertEqual(out[0][out[0].index("--max-context") + 1], "262144")
434        self.assertEqual(out[0][out[0].index("--vram-reserve-mib") + 1], "1536")
435
436if __name__ == "__main__":
437    unittest.main()