okami.mom/strata

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

Niko1221Merge f-spark-s2 6d65761c4 into f-own-inte32329cd3

main
2.4 KiB54 linesraw
1"""The picture reader's context retry (tools/vision/own/vit_gpu.cu, set_device_retrying) exists only in a Linux CUDA build.
2
3A new CUDA context on a shared-memory GPU (DGX Spark) can fail with "out of memory" for a moment while the kernel has no free 2 MiB blocks; the reader
4tries again up to 12 times, one second apart.  The same cudaDevAttrIntegrated is true on AMD APUs (HIP build, same source file) and on Macs (a different
5reader), and Windows has no such case, so the retry loop sits inside one guard, and the pure rule (vit_gpu.h) says no for everything but integrated + out of memory.
6"""
7import re
8import unittest
9from pathlib import Path
10
11OWN = Path(__file__).resolve().parent / "vision" / "own"
12CU = OWN / "vit_gpu.cu"
13GUARD = "#if defined(__linux__) && !defined(STRATA_VIT_HIP)   // SPARK-CTX-RETRY"
14
15
16def guarded_span(lines):
17    start = next(i for i, l in enumerate(lines) if l.strip() == GUARD)
18    depth = 0
19    for i in range(start, len(lines)):
20        s = lines[i].lstrip()
21        if re.match(r"#\s*if", s):
22            depth += 1
23        elif re.match(r"#\s*endif", s):
24            depth -= 1
25            if depth == 0:
26                return start, i
27    raise AssertionError("the guard has no matching #endif")
28
29
30class CtxRetryGuard(unittest.TestCase):
31    def setUp(self):
32        self.lines = CU.read_text(encoding="utf-8").splitlines()
33
34    def test_guard_present_once(self):
35        self.assertEqual(sum(1 for l in self.lines if l.strip() == GUARD), 1)
36
37    def test_attribute_and_retry_inside_the_guard(self):
38        first, last = guarded_span(self.lines)
39        for needle in ("cudaDevAttrIntegrated", "cudaErrorMemoryAllocation", "vit_gpu_retry_context(", "sleep_for("):
40            at = [i for i, l in enumerate(self.lines) if needle in l]
41            self.assertTrue(at, needle)
42            for i in at:
43                self.assertTrue(first < i < last, f"{needle!r} at line {i + 1} is outside the Linux-CUDA guard ({first + 1}-{last + 1})")
44
45    def test_the_context_is_made_through_the_retrying_call(self):
46        text = "\n".join(self.lines)
47        self.assertIn("set_device_retrying(device)", text)
48        # the only cudaSetDevice left in load() is the one inside set_device_retrying, and the later ones in encode / alloc ignore their result or need no retry
49        load = text[text.index("bool VitGpu::load("):text.index("bool VitGpu::encode(")]
50        self.assertNotIn("cudaSetDevice(", load)
51
52
53if __name__ == "__main__":
54    unittest.main()