okami.mom/strata

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

Niko1221Merge f-028-app-p13b8dc8fa3

main
18.7 KiB348 linesraw
1"""Older NVIDIA GPUs (experimental): Pascal / Volta run a second engine built with CUDA 12 (engine-cuda12/), chosen per
2model config by its oldest card; --cuda 12|13 overrides it.  A PC whose cards the ready-made CUDA 13 engine runs on
3gets exactly what it got before.  No GPU, no downloads.
4
5    python -m unittest tools.test_setup_older_gpus
6"""
7from __future__ import annotations
8
9import json
10import os
11import sys
12import tempfile
13import unittest
14from pathlib import Path
15from unittest import mock
16
17ROOT = Path(__file__).resolve().parents[1]
18sys.path.insert(0, str(ROOT))
19sys.path.insert(0, str(Path(__file__).resolve().parent))
20import setup  # noqa: E402
21from test_setup_choices import quiet  # noqa: E402
22from test_setup_golden import PROFILES, install, argv_for  # noqa: E402
23
24
25def card(i, name, vram, arch, driver="580.97"):
26    return {"index": i, "name": name, "vram_gb": vram, "arch": arch, "driver": driver}
27
28
29V100 = card(0, "Tesla V100-PCIE-32GB", 32.0, "70", "575.57")
30P40 = card(0, "Tesla P40", 24.0, "61", "535.104")
31
32
33class Choice(unittest.TestCase):
34    def test_by_the_oldest_card(self):
35        self.assertEqual(setup.cuda_choice(["120"]), (13, None))
36        self.assertEqual(setup.cuda_choice([75, 86, 89]), (13, None))
37        for archs in ([70], [61], [60], [70, 86]):
38            tk, why = setup.cuda_choice(archs)
39            self.assertEqual(tk, 12, archs)
40            self.assertIn(f"sm_{min(archs)} is older than CUDA 13 supports", why)
41
42    def test_a_driver_too_old_for_cuda13_gets_the_cuda12_engine(self):       # #3843
43        self.assertEqual(setup.cuda_choice([86], None, 576)[0], 12)
44        self.assertIn("older than CUDA 13 needs", setup.cuda_choice([86], None, 576)[1])
45        self.assertEqual(setup.cuda_choice([86], None, 580), (13, None))
46        self.assertEqual(setup.cuda_choice([86], None, 0), (13, None))          # driver unknown: as before
47        self.assertEqual(setup.cuda_choice([86], None, 500), (13, None))        # too old for both: setup stops with the driver message
48        self.assertEqual(setup.cuda_choice([86], "13", 576)[0], 13)             # chosen by hand: kept
49
50    def test_the_override_is_honored_with_a_warning(self):
51        tk, why = setup.cuda_choice([70], "13")
52        self.assertEqual(tk, 13)                       # recommend, never force: kept, and said
53        self.assertIn("will not run on that card", why)
54        self.assertEqual(setup.cuda_choice([86], "12")[0], 12)
55        self.assertIn("#220", setup.cuda_choice([86, 120], "12")[1])
56        self.assertEqual(setup.cuda_choice([70], "auto")[0], 12)
57        self.assertEqual(setup.cuda_choice([86], "auto"), (13, None))
58
59    def test_engine_folders_and_configs(self):
60        with mock.patch.object(setup, "ROOT", Path("/s")):
61            self.assertEqual(setup.engine_dir(), Path("/s/engine"))
62            self.assertEqual(setup.engine_dir(12), Path("/s/engine-cuda12"))
63        self.assertEqual(setup.config_toolkit({"exe": "/s/engine/strata.exe"}), 13)
64        self.assertEqual(setup.config_toolkit({"exe": "/s/engine-cuda12/strata.exe"}), 12)
65        self.assertEqual(setup.config_toolkit({"exe": "x", "cuda": 12}), 12)
66        self.assertEqual(setup.engine_defs([86], 12), ["-DSTRATA_EXPERIMENTAL_SM60=ON"])
67        self.assertEqual(setup.engine_defs([86]), [])
68
69
70class OptIn(unittest.TestCase):
71    """Pascal / Volta cards are used only when chosen; a PC with a newer card keeps recommending the newer one."""
72
73    def setUp(self):
74        self.env = mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": ""})
75        self.env.start()
76
77    def tearDown(self):
78        self.env.stop()
79
80    def test_reasons(self):
81        rtx = card(0, "RTX 3090", 24.0, "86")
82        v100 = {**V100, "index": 1}
83        self.assertIsNone(setup.old_gpus_opt_in([rtx]))
84        self.assertIsNone(setup.old_gpus_opt_in([rtx, v100]))                  # the default: unchanged
85        self.assertIn("you chose GPU 1", setup.old_gpus_opt_in([rtx, v100], [1]))
86        self.assertIsNone(setup.old_gpus_opt_in([rtx, v100], [0]))
87        self.assertEqual(setup.old_gpus_opt_in([rtx, v100], cuda="12"), "--cuda 12")
88        self.assertIn("only kind", setup.old_gpus_opt_in([V100]))
89        self.assertIsNone(setup.old_gpus_opt_in([V100], other=True))            # an AMD card it can use instead
90        self.assertIsNone(setup.old_gpus_opt_in([card(0, "GTX 980", 4.0, "52")]))
91        # #3218: a Maxwell card is never routed to the CUDA 12 engine (it holds no sm_52 code), with or without a switch
92        m6000 = card(0, "Quadro M6000", 24.0, "52")
93        self.assertTrue(setup.sm60_card("60") and setup.sm60_card("70") and not setup.sm60_card("75"))
94        self.assertFalse(setup.sm60_card("52"))
95        self.assertIn("not supported", setup.gpu_problem(m6000))
96        self.assertIn("Maxwell only runs from a source build", setup.gpu_problem(m6000))
97        self.assertNotIn("experimental: choose it", setup.gpu_problem(m6000))
98        self.assertIsNone(setup.old_gpus_opt_in([m6000]))
99        for env in ({"STRATA_EXPERIMENTAL_SM60": "1"}, {"STRATA_EXPERIMENTAL_SM52": "1"}):
100            with mock.patch.dict(os.environ, env):
101                self.assertFalse(setup.sm60_card("52"))
102                self.assertIn("not supported", setup.gpu_problem(m6000))
103                self.assertIsNone(setup.old_gpus_opt_in([m6000]))
104        self.assertIsNone(setup.old_gpus_opt_in([m6000], named=[0], cuda="12"))   # naming it does not admit it either
105        with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}):
106            self.assertEqual(setup.old_gpus_opt_in([rtx, v100]), "STRATA_EXPERIMENTAL_SM60=1")
107
108    def test_maxwell_note_is_a_warning_with_the_recipe(self):
109        m6000 = card(0, "Quadro M6000", 24.0, "52")
110        note = setup.maxwell_note([m6000, {**m6000, "index": 1}])
111        self.assertIn("GPU 0 (Quadro M6000), GPU 1 (Quadro M6000)", note)
112        self.assertIn("-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52", note)
113        self.assertIn("docs/OLDER_GPUS.md", note)
114        self.assertNotIn("STRATA_EXPERIMENTAL_SM52", note)                       # no switch the user has to set
115        self.assertEqual(setup.maxwell_note([V100, P40]), "")
116        self.assertEqual(setup.maxwell_note([]), "")
117
118    def test_named(self):
119        self.assertEqual(setup.named_gpus(None, "0,2"), [0, 2])
120        self.assertEqual(setup.named_gpus(1, None), [1])
121        self.assertEqual(setup.named_gpus(None, "all"), [])
122        self.assertEqual(setup.named_gpus(None, "x"), [])
123
124    def test_the_gate_follows_the_opt_in(self):
125        with mock.patch.object(setup, "OLD_GPUS", None):
126            self.assertIsNotNone(setup.gpu_problem(V100))
127        with mock.patch.object(setup, "OLD_GPUS", "you chose GPU 0"):
128            self.assertIsNone(setup.gpu_problem(V100))
129            self.assertIsNotNone(setup.gpu_problem(card(0, "GTX 980", 4.0, "52")))
130
131
132class Libraries(unittest.TestCase):
133    def test_cuda12_wheels_two_folders(self):
134        with tempfile.TemporaryDirectory() as d:
135            sp = Path(d) / "site-packages"
136            names = {"cublas/bin/cublas64_12.dll", "cuda_runtime/bin/cudart64_12.dll", "cu13/bin/x86_64/cublas64_13.dll",
137                     "cublas/lib/libcublas.so.12", "cuda_runtime/lib/libcudart.so.12", "cu13/lib/libcublas.so.13"}
138            for n in names:
139                f = sp / "nvidia" / n
140                f.parent.mkdir(parents=True, exist_ok=True)
141                f.write_bytes(b"")
142            with mock.patch.object(sys, "path", [str(sp)]):
143                for win in (True, False):
144                    with mock.patch.object(setup, "WIN", win):
145                        got12 = sorted(Path(x).relative_to(sp / "nvidia").as_posix() for x in setup.cuda_lib_dirs(12))
146                        got13 = [Path(x).relative_to(sp / "nvidia").as_posix() for x in setup.cuda_lib_dirs()]
147                    if win:
148                        self.assertEqual(got12, ["cublas/bin", "cuda_runtime/bin"])
149                        self.assertEqual(got13, ["cu13/bin/x86_64"])
150                    else:
151                        self.assertEqual(got12, ["cublas/lib", "cuda_runtime/lib"])
152                        self.assertEqual(got13, ["cu13/lib"])
153
154    def test_wheels_pinned_to_12(self):
155        self.assertTrue(all("-cu12==12." in w for w in setup.CUDA12_WHEELS))
156        self.assertEqual(setup.CUDA12_ASSET, "strata-windows-x64-cuda12.zip" if setup.WIN else
157                         "strata-linux-x64-cuda12.zip")
158
159
160class BuildTools(unittest.TestCase):
161    """The compile path: a CUDA 12 engine looks for a 12.x toolkit (STRATA_NVCC picks one), sm_120 needs 12.8+."""
162
163    def tools(self, gpu, nvcc):
164        seen = []
165
166        def find(below=None):
167            seen.append(below)
168            return nvcc(below)
169
170        with mock.patch.object(setup, "find_nvcc", find), mock.patch.object(setup, "find_vcvars", lambda cuda_v=None: "vcvars"), \
171                mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n):
172            got, text = quiet(setup.install_build_tools, gpu, True)
173        return got, seen, text
174
175    def test_cuda12_on_a_newer_card(self):
176        got, seen, _ = self.tools({"arch": "86", "archs": [86], "toolkit": 12},
177                                  lambda below: ("nvcc12", (12, 9)) if below else ("nvcc13", (13, 0)))
178        self.assertEqual((got[0], seen), ("nvcc12", [(13, 0)]))
179
180    def test_sm120_in_a_cuda12_engine_warns_and_needs_12_8(self):
181        got, _, text = self.tools({"arch": "70", "archs": [70, 120]},
182                                  lambda below: ("nvcc12", (12, 9)) if below else ("nvcc13", (13, 0)))
183        self.assertEqual(got[0], "nvcc12")
184        self.assertIn("#220", text)
185        with self.assertRaises(SystemExit):
186            self.tools({"arch": "70", "archs": [70, 120]}, lambda below: ("nvcc12", (12, 6)) if below else (None, None))
187
188
189def fake_prebuilt(calls):
190    """get_prebuilt that installs an engine in the folder of the toolkit it is asked for (and says which)."""
191    def get(url_base, gpu, vision, updating=False, toolkit=13):
192        calls.append(toolkit)
193        eng = setup.engine_dir(toolkit)
194        eng.mkdir(exist_ok=True)
195        (eng / "BUILD.json").write_text(json.dumps({"version": "0.1.39", "source": "release", "archs": [86], "ptx": True,
196                                                    "cuda": "12.9" if toolkit == 12 else "13.0", "vision": "gpu"}))
197        (eng / setup.EXE).write_bytes(b"")
198        (eng / setup.VEXE).write_bytes(b"")                    # pictures are on by default: the engine carries the reader
199        return eng
200    return get
201
202
203class Install(unittest.TestCase):
204    """setup.main() on mocked PCs (tools/test_setup_golden.py's harness)."""
205
206    def run_setup(self, ram, found, argv, env=None):
207        calls, libs = [], []
208        extra = [mock.patch.object(setup, "get_prebuilt", fake_prebuilt(calls)),
209                 mock.patch.object(setup, "pip_cuda_libs", lambda tk=13: libs.append(tk)),
210                 mock.patch.object(setup, "OLD_GPUS", None),
211                 mock.patch.object(setup, "cuda12_min_driver", lambda feed=False: (575, "575.51", "the published figure")),   # never the real feed
212                 mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "", "STRATA_CUDA": "", **(env or {})})]
213        code, out, cfg, asked = install(ram, found, argv, extra=extra)
214        return code, out, cfg, calls, libs
215
216    def test_a_v100_alone_gets_the_cuda12_engine(self):
217        code, out, cfg, calls, libs = self.run_setup(95.0, [V100], argv_for("qwen", "IQ3_XXS"))
218        self.assertEqual(code, 0, out[-3000:])
219        self.assertEqual((calls, libs), ([12], [12]))
220        self.assertEqual(cfg["cuda"], 12)
221        self.assertEqual(cfg["exe"], "<T>/engine-cuda12/<EXE>")
222        self.assertIn("sm_70 is older than CUDA 13 supports", out)
223        self.assertIn("experimental", out)
224
225    def test_a_maxwell_pc_is_warned_with_the_recipe_and_gets_no_engine(self):
226        """#3218: no ready-made engine holds sm_52 code, so none is installed; the way forward is printed, with or
227        without any switch (a user never has to set one)."""
228        m6000 = card(0, "Quadro M6000", 24.0, "52")
229        for env in (None, {"STRATA_EXPERIMENTAL_SM60": "1"}, {"STRATA_EXPERIMENTAL_SM52": "1"}):
230            with self.subTest(env=env):
231                code, out, cfg, calls, libs = self.run_setup(95.0, [m6000], argv_for("qwen", "IQ3_XXS"), env)
232                self.assertNotEqual(code, 0, out[-3000:])
233                self.assertEqual((calls, libs), ([], []))
234                self.assertIsNone(cfg)
235                self.assertIn("Maxwell (compute capability 5.2)", out)
236                self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=52", out)
237                self.assertIn("docs/OLDER_GPUS.md", out)
238
239    def test_a_maxwell_card_beside_a_newer_one_is_not_a_warning(self):
240        rtx = card(0, "NVIDIA GeForce RTX 3090", 24.0, "86")
241        code, out, cfg, calls, _ = self.run_setup(95.0, [rtx, card(1, "GTX 980", 4.0, "52")], argv_for("qwen", "IQ3_XXS"))
242        self.assertEqual((code, calls), (0, [13]), out[-3000:])
243        self.assertNotIn("Maxwell (compute capability", out)
244
245    def test_a_p40_with_an_older_driver(self):
246        code, out, cfg, calls, _ = self.run_setup(95.0, [P40], argv_for("qwen", "IQ3_XXS"))
247        self.assertEqual(code, 0, out[-3000:])                 # driver 535: enough for CUDA 12
248        self.assertIn("575.51", out)                            # #4247: said with the package's own figure, and as a warning, not a stop
249        self.assertNotIn("works with driver 528", out)
250        self.assertEqual(calls, [12])
251
252    def test_a_newer_card_beside_a_v100_is_unchanged(self):
253        """The RTX 3090 is recommended as before; the V100 is listed with how to choose it."""
254        rtx = card(0, "NVIDIA GeForce RTX 3090", 24.0, "86")
255        found = [rtx, {**V100, "index": 1}]
256        code, out, cfg, calls, libs = self.run_setup(95.0, found, argv_for("qwen", "IQ3_XXS"))
257        code0, _, cfg0, _ = install(95.0, [rtx], argv_for("qwen", "IQ3_XXS"))
258        self.assertEqual(code, 0, out[-3000:])
259        self.assertEqual((calls, libs), ([13], [13]))
260        self.assertNotIn("cuda", cfg)
261        self.assertEqual(cfg["exe"], "<T>/engine/<EXE>")
262        self.assertIn("choose it with --gpu 1", out)
263        skip = ("gpu", "gpus_asked", "lib_dirs")       # one card vs two; the fake engine's library folders
264        self.assertEqual({k: v for k, v in cfg.items() if k not in skip}, {k: v for k, v in cfg0.items() if k not in skip})
265
266    def test_naming_the_v100_beside_a_newer_card(self):
267        found = [card(0, "NVIDIA GeForce RTX 3090", 24.0, "86"), {**V100, "index": 1}]
268        code, out, cfg, calls, _ = self.run_setup(95.0, found, argv_for("qwen", "IQ3_XXS") + ["--gpu", "1"])
269        self.assertEqual(code, 0, out[-3000:])
270        self.assertEqual(calls, [12])
271        self.assertEqual((cfg["cuda"], cfg["gpu"]), (12, 1))
272        self.assertIn("you chose GPU 1", out)
273
274    def test_cuda12_asked_for_on_a_newer_card(self):
275        ram, found = PROFILES["128GB-1x24GB"]
276        for argv, env in ((["--cuda", "12"], None), ([], {"STRATA_CUDA": "12"})):
277            with self.subTest(argv=argv, env=env):
278                code, out, cfg, calls, _ = self.run_setup(ram, found, argv_for("qwen", "IQ3_XXS") + argv, env)
279                self.assertEqual(code, 0, out[-3000:])
280                self.assertEqual((calls, cfg["cuda"]), ([12], 12))
281                self.assertIn("--cuda 12 (as you chose", out)
282
283    def test_an_old_driver_gets_cuda12_by_itself(self):                     # #3843: said in one line, not a stop
284        code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")],
285                                                  argv_for("qwen", "IQ3_XXS"))
286        self.assertEqual(code, 0, out[-3000:])
287        self.assertEqual((calls, cfg["cuda"]), ([12], 12))
288        self.assertIn("older than CUDA 13 needs (580): this model runs the CUDA 12 engine", out)
289        code, out, _, _, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "470.10")],
290                                            argv_for("qwen", "IQ3_XXS"))
291        self.assertEqual(code, 1)                                                # too old for both: the stop stays
292        self.assertIn("is too old", out)
293        self.assertNotIn("--cuda 12", out)
294        code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")],
295                                                  argv_for("qwen", "IQ3_XXS") + ["--cuda", "12"])
296        self.assertEqual(code, 0, out[-3000:])
297        self.assertEqual(calls, [12])
298
299    def test_cuda13_forced_on_a_v100_is_said(self):
300        code, out, cfg, calls, _ = self.run_setup(95.0, [V100], argv_for("qwen", "IQ3_XXS") + ["--cuda", "13"])
301        self.assertIn("will not run on that card", out)
302
303
304class Start(unittest.TestCase):
305    """At a start: a Pascal / Volta card added to a CUDA 13 model moves that model to the CUDA 12 engine; updates
306    look at both engine folders."""
307
308    def test_an_old_card_added_moves_the_model(self):
309        with tempfile.TemporaryDirectory() as d:
310            root = Path(d)
311            cfg_path = root / "strata-iq3_xxs.json"
312            cfg = {"exe": str(root / "engine" / setup.EXE), "args": [], "lib_dirs": ["<cu13>"]}
313            calls = []
314            with mock.patch.object(setup, "ROOT", root), \
315                    mock.patch.object(setup, "get_prebuilt", fake_prebuilt(calls)), \
316                    mock.patch.object(setup, "pip_cuda_libs", lambda tk=13: None), \
317                    mock.patch.object(setup, "cuda_lib_dirs", lambda tk=13: [f"<cu{tk}>"]), \
318                    mock.patch.object(setup, "gpu_info", lambda i=None: None):
319                got, text = quiet(setup.ensure_engine_for, [card(0, "RTX 3090", 24.0, "86"), {**V100, "index": 1}],
320                                  cfg_path, dict(cfg), True)
321            self.assertEqual(calls, [12])
322            self.assertEqual(Path(got["exe"]).parent.name, "engine-cuda12")
323            self.assertEqual((got["cuda"], got["lib_dirs"]), (12, ["<cu12>"]))
324            self.assertIn("moves to the experimental CUDA 12 engine", text)
325            self.assertEqual(json.loads(cfg_path.read_text())["cuda"], 12)
326
327    def test_update_looks_at_both_engines(self):
328        with tempfile.TemporaryDirectory() as d:
329            root = Path(d)
330            seen = []
331            real = setup.update_installed_engine
332
333            def spy(url_base, toolkit=None):
334                if toolkit is None:
335                    return real(url_base, toolkit)
336                seen.append(toolkit)
337            with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "update_installed_engine", spy):
338                spy("u")
339                self.assertEqual(seen, [13])
340                (root / "engine-cuda12").mkdir()
341                (root / "engine-cuda12" / "BUILD.json").write_text("{}")
342                seen.clear()
343                spy("u")
344                self.assertEqual(seen, [13, 12])
345
346
347if __name__ == "__main__":
348    unittest.main()