okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
6.7 KiB137 linesraw
1"""#5717: a build folder configured with one CUDA toolkit keeps that toolkit's library paths in its CMake cache
2(CUDA_cudart_LIBRARY and the other CUDA_* / CUDAToolkit_* entries): after the toolkit moved, a new
3-DCUDAToolkit_ROOT alone does not search them again and ninja stops on the old libcudart.so.  setup's configure
4must notice a changed toolkit and drop those entries, and must leave an unchanged folder alone.
5
6No real toolkit is needed: the cache and the toolkit folders are fakes, and the configure/build commands are
7recorded instead of run."""
8
9from __future__ import annotations
10
11import sys
12import tempfile
13import unittest
14from pathlib import Path
15from unittest import mock
16
17sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
18
19import setup  # noqa: E402
20
21
22def fake_toolkit(root: Path) -> Path:
23    """A toolkit folder with the files the cache entries point at; returns its nvcc."""
24    for sub in ("bin", "include", "targets/x86_64-linux/lib"):
25        (root / sub).mkdir(parents=True, exist_ok=True)
26    (root / "bin" / "nvcc").write_text("", encoding="utf-8")
27    (root / "targets/x86_64-linux/lib/libcudart.so").write_text("", encoding="utf-8")
28    (root / "targets/x86_64-linux/lib/libcublas.so").write_text("", encoding="utf-8")
29    return root / "bin" / "nvcc"
30
31
32def write_cache(bdir: Path, root: Path, nvcc: str) -> None:
33    """A CMakeCache.txt shaped like the reporter's: the cudart / cuBLAS paths and the toolkit dirs of `root`."""
34    bdir.mkdir(parents=True, exist_ok=True)
35    r = root.as_posix()
36    (bdir / "CMakeCache.txt").write_text("\n".join([
37        "# This is the CMakeCache file.",
38        "CMAKE_GENERATOR:INTERNAL=Ninja",
39        "CMAKE_BUILD_TYPE:STRING=Release",
40        f"CMAKE_CUDA_COMPILER:STRING={nvcc}",
41        f"CUDAToolkit_ROOT:UNINITIALIZED={r}",
42        f"CUDAToolkit_BIN_DIR:PATH={r}/bin",
43        f"CUDAToolkit_NVCC_EXECUTABLE:FILEPATH={r}/bin/nvcc",
44        f"CUDA_cudart_LIBRARY:FILEPATH={r}/targets/x86_64-linux/lib/libcudart.so",
45        f"CUDA_cublas_LIBRARY:FILEPATH={r}/targets/x86_64-linux/lib/libcublas.so",
46        "CUDA_nvml_LIBRARY:FILEPATH=CUDA_nvml_LIBRARY-NOTFOUND",
47        "STRATA_ENABLE_CUDA:BOOL=ON",
48        ""]), encoding="utf-8")
49    det = bdir / "CMakeFiles" / "3.31.6"
50    det.mkdir(parents=True, exist_ok=True)
51    (det / "CMakeCUDACompiler.cmake").write_text(f'set(CMAKE_CUDA_COMPILER_TOOLKIT_ROOT "{r}")\n', encoding="utf-8")
52    (det / "CMakeCXXCompiler.cmake").write_text("", encoding="utf-8")
53    obj = bdir / "CMakeFiles" / "strata.dir"
54    obj.mkdir(parents=True, exist_ok=True)
55    (obj / "main.cpp.o").write_bytes(b"obj")
56
57
58class Issue5717StaleToolkitCache(unittest.TestCase):
59    def setUp(self):
60        self.tmp = tempfile.TemporaryDirectory()
61        self.addCleanup(self.tmp.cleanup)
62        self.base = Path(self.tmp.name)
63        self.bdir = self.base / "build"
64        self.runs = []
65        for p in (mock.patch.object(setup, "ensure_build_tools", return_value=("cmake", "ninja")),
66                  mock.patch.object(setup.acquisition, "require", return_value=None),
67                  mock.patch.object(setup, "WIN", False),
68                  mock.patch.object(setup, "run", side_effect=self._run)):
69            p.start()
70            self.addCleanup(p.stop)
71
72    def _run(self, cmd, *a, **k):
73        self.runs.append([str(c) for c in cmd])
74        return mock.Mock(returncode=0)
75
76    def configure(self, nvcc: Path) -> list:
77        self.runs.clear()
78        setup.cmake_build(self.base, self.bdir, "strata",
79                          ["-DSTRATA_ENABLE_CUDA=ON", f"-DCMAKE_CUDA_COMPILER={nvcc}", *setup.toolkit_root_defs(nvcc)],
80                          None, "build-strata.bat")
81        return self.runs[0]
82
83    def test_a_moved_toolkit_drops_the_cached_cuda_paths(self):
84        """The reporter's case: the old toolkit's folder is gone, the new one is passed as CUDAToolkit_ROOT."""
85        old, new = self.base / "cuda-13.4", self.base / "cuda-13.5"
86        fake_toolkit(old)
87        write_cache(self.bdir, old.resolve(), str(old / "bin" / "nvcc"))
88        new_nvcc = fake_toolkit(new)
89        import shutil
90        shutil.rmtree(old)
91        conf = self.configure(new_nvcc)
92        self.assertIn("-UCUDA_*", conf)
93        self.assertIn("-UCUDAToolkit_*", conf)
94        # the -U comes before the new -DCUDAToolkit_ROOT, or CMake would remove the new value too
95        root_def = next(i for i, a in enumerate(conf) if a.startswith("-DCUDAToolkit_ROOT="))
96        self.assertLess(conf.index("-UCUDAToolkit_*"), root_def)
97        self.assertLess(conf.index("-UCUDA_*"), root_def)
98        # CMake detects the CUDA compiler again (its toolkit root is in that file); the objects stay for the rebuild
99        self.assertEqual(list(self.bdir.glob("CMakeFiles/*/CMakeCUDACompiler.cmake")), [])
100        self.assertTrue((self.bdir / "CMakeFiles" / "3.31.6" / "CMakeCXXCompiler.cmake").exists())
101        self.assertTrue((self.bdir / "CMakeFiles" / "strata.dir" / "main.cpp.o").exists())
102        self.assertTrue((self.bdir / "CMakeCache.txt").exists())
103
104    def test_another_installed_toolkit_also_counts(self):
105        """Both toolkits still installed, setup now builds with the other one: the cached paths are valid files
106        of the wrong toolkit."""
107        old, new = self.base / "cuda-12.9", self.base / "cuda-13.0"
108        fake_toolkit(old)
109        write_cache(self.bdir, old.resolve(), str(old / "bin" / "nvcc"))
110        conf = self.configure(fake_toolkit(new))
111        self.assertIn("-UCUDA_*", conf)
112        self.assertIn("-UCUDAToolkit_*", conf)
113
114    def test_an_unchanged_toolkit_changes_nothing(self):
115        tk = self.base / "cuda-13.5"
116        nvcc = fake_toolkit(tk)
117        write_cache(self.bdir, tk.resolve(), str(nvcc))
118        before = (self.bdir / "CMakeCache.txt").read_bytes()
119        conf = self.configure(nvcc)
120        self.assertFalse([a for a in conf if a.startswith("-U")], conf)
121        self.assertEqual((self.bdir / "CMakeCache.txt").read_bytes(), before)
122        self.assertTrue((self.bdir / "CMakeFiles" / "3.31.6" / "CMakeCUDACompiler.cmake").exists())
123
124    def test_a_new_folder_and_a_cpu_folder_change_nothing(self):
125        nvcc = fake_toolkit(self.base / "cuda-13.5")
126        conf = self.configure(nvcc)                      # never configured: no cache
127        self.assertFalse([a for a in conf if a.startswith("-U")], conf)
128        self.bdir.mkdir(exist_ok=True)
129        (self.bdir / "CMakeCache.txt").write_text("CMAKE_GENERATOR:INTERNAL=Ninja\nSTRATA_ENABLE_CUDA:BOOL=OFF\n",
130                                                  encoding="utf-8")
131        self.runs.clear()
132        setup.cmake_build(self.base, self.bdir, "strata-vision", ["-DSTRATA_VISION_CUDA=OFF"], None, "x.bat")
133        self.assertFalse([a for a in self.runs[0] if a.startswith("-U")], self.runs[0])
134
135
136if __name__ == "__main__":
137    unittest.main()