Skip to content

Commit d322c49

Browse files
authored
fix(installer): validate CUDA forward compatibility (#1814)
1 parent f15a301 commit d322c49

3 files changed

Lines changed: 180 additions & 2 deletions

File tree

‎docs/public/install.sh‎

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@ Options:
4848
Environment overrides:
4949
SONAR_BASE_URL Site that hosts Sonar platform wheels.
5050
SONAR_UV_VERSION uv installer version.
51+
SONAR_ENABLE_CUDA_COMPATIBILITY
52+
Opt in to installed CUDA compatibility libraries.
53+
SONAR_CUDA_COMPATIBILITY_PATH
54+
Override the compatibility library directory.
5155
EOF
5256
}
5357

@@ -215,6 +219,37 @@ version_at_least() {
215219
[ "$first" = "$required" ]
216220
}
217221

222+
check_cuda_driver() {
223+
command -v python3 >/dev/null 2>&1 ||
224+
die "python3 is required to validate CUDA compatibility. Install it or update the NVIDIA driver."
225+
python3 - <<'PY'
226+
import ctypes
227+
import sys
228+
229+
try:
230+
cuda = ctypes.CDLL("libcuda.so.1")
231+
version = ctypes.c_int()
232+
status = cuda.cuDriverGetVersion(ctypes.byref(version))
233+
if status:
234+
raise RuntimeError(f"cuDriverGetVersion failed with CUDA error {status}")
235+
if version.value < 13020:
236+
raise RuntimeError(f"loaded libcuda reports driver API {version.value}, requires CUDA 13.2 (13020)")
237+
status = cuda.cuInit(0)
238+
if status:
239+
raise RuntimeError(f"cuInit failed with CUDA error {status}")
240+
count = ctypes.c_int()
241+
status = cuda.cuDeviceGetCount(ctypes.byref(count))
242+
if status:
243+
raise RuntimeError(f"cuDeviceGetCount failed with CUDA error {status}")
244+
if count.value < 1:
245+
raise RuntimeError("loaded CUDA driver exposes no devices")
246+
except (OSError, AttributeError, RuntimeError) as error:
247+
print(f"CUDA driver probe: {error}", file=sys.stderr)
248+
sys.exit(1)
249+
print(f"Loaded CUDA driver API {version.value}, accessible devices: {count.value}.")
250+
PY
251+
}
252+
218253
check_cuda() {
219254
command -v nvidia-smi >/dev/null 2>&1 ||
220255
die "nvidia-smi is required to validate the NVIDIA driver."
@@ -225,8 +260,32 @@ check_cuda() {
225260
head -n 1)
226261
[ -n "$supported_cuda" ] ||
227262
die "Could not determine the CUDA version supported by the NVIDIA driver."
228-
version_at_least "$supported_cuda" 13.2 ||
229-
die "The NVIDIA driver supports CUDA $supported_cuda. Sonar requires CUDA 13.2 or newer."
263+
compat_path=
264+
compat_enabled=$(printf '%s' "${SONAR_ENABLE_CUDA_COMPATIBILITY:-0}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
265+
case "$compat_enabled" in
266+
1 | true)
267+
compat_path=${SONAR_CUDA_COMPATIBILITY_PATH:-}
268+
if [ -z "$compat_path" ]; then
269+
if [ -n "${CONDA_PREFIX:-}" ] && [ -d "$CONDA_PREFIX/cuda-compat" ]; then
270+
compat_path=$CONDA_PREFIX/cuda-compat
271+
else
272+
compat_path=/usr/local/cuda-13.2/compat
273+
fi
274+
fi
275+
[ -f "$compat_path/libcuda.so.1" ] ||
276+
die "CUDA compatibility library not found at $compat_path/libcuda.so.1."
277+
export LD_LIBRARY_PATH="$compat_path${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
278+
;;
279+
esac
280+
if ! version_at_least "$supported_cuda" 13.2 || [ "${compat_path:-}" ]; then
281+
check_cuda_driver ||
282+
die "Sonar requires a working CUDA 13.2 driver. Update the driver or explicitly configure supported CUDA compatibility libraries."
283+
say "nvidia-smi reports CUDA $supported_cuda; the loaded CUDA driver passed compatibility checks."
284+
if [ -n "${LD_LIBRARY_PATH:-}" ]; then
285+
say "Keep this environment when launching Sonar, including in services:"
286+
say " export LD_LIBRARY_PATH=$(shell_quote "$LD_LIBRARY_PATH")"
287+
fi
288+
fi
230289

231290
compute_caps=$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null || true)
232291
[ -n "$compute_caps" ] ||

‎docs/src/content/docs/getting-started/installation.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,26 @@ and a driver supporting CUDA 13.2 or newer. Supported compute capabilities are
4949
8.0, 8.6, 8.9, 9.0, 10.0, 10.3, and 12.x. ARM64 wheels also support 11.0
5050
(Jetson Thor). Jetson Orin (8.7) and CUDA 12 drivers are not supported.
5151

52+
On supported NVIDIA hardware, an installed CUDA forward-compatibility package
53+
can provide the required driver API without upgrading the host driver. The
54+
installer accepts this when a Python 3 probe loads `libcuda.so.1`, reports API
55+
13.2 or newer, initializes CUDA, and finds an accessible device. GPU architecture
56+
checks still apply.
57+
58+
If the compatibility libraries are already on `LD_LIBRARY_PATH`, no additional
59+
option is needed. Otherwise, opt in and select their directory:
60+
61+
```bash
62+
export SONAR_ENABLE_CUDA_COMPATIBILITY=1
63+
export SONAR_CUDA_COMPATIBILITY_PATH=/usr/local/cuda-13.2/compat
64+
curl -LsSf https://sonar.dphn.ai/install.sh | sh
65+
```
66+
67+
Keep the `LD_LIBRARY_PATH` export printed by the installer in the environment
68+
that launches Sonar, including service definitions. The installer does not
69+
install compatibility libraries or change the host driver or global linker
70+
configuration.
71+
5272
Install [uv](https://docs.astral.sh/uv/getting-started/installation/). Then
5373
create an environment and install Sonar.
5474

‎tests/scripts/test_install.py‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,41 @@
1717
import pytest
1818

1919

20+
@pytest.fixture(scope="module")
21+
def cuda_driver(tmp_path_factory: pytest.TempPathFactory) -> Path:
22+
"""Exercise the real dynamic loader without depending on the test host GPU."""
23+
compiler = shutil.which("cc")
24+
if platform.system() != "Linux" or compiler is None:
25+
pytest.skip("CUDA driver probe tests require Linux and a C compiler")
26+
assert compiler is not None
27+
directory = tmp_path_factory.mktemp("cuda compat")
28+
subprocess.run(
29+
[compiler, "-shared", "-fPIC", "-x", "c", "-", "-o", str(directory / "libcuda.so.1")],
30+
input="""
31+
#include <stdlib.h>
32+
static int value(const char *name, int fallback) {
33+
const char *text = getenv(name);
34+
return text ? atoi(text) : fallback;
35+
}
36+
int cuDriverGetVersion(int *version) {
37+
*version = value("TEST_DRIVER_API", 13020);
38+
return value("TEST_DRIVER_STATUS", 0);
39+
}
40+
int cuInit(unsigned int flags) {
41+
return value("TEST_INIT_STATUS", 0);
42+
}
43+
int cuDeviceGetCount(int *count) {
44+
*count = value("TEST_DEVICE_COUNT", 1);
45+
return value("TEST_COUNT_STATUS", 0);
46+
}
47+
""",
48+
text=True,
49+
check=True,
50+
capture_output=True,
51+
)
52+
return directory
53+
54+
2055
@pytest.fixture
2156
def installer_environment(tmp_path: Path) -> dict[str, str]:
2257
commands = {
@@ -47,6 +82,8 @@ def installer_environment(tmp_path: Path) -> dict[str, str]:
4782
"TEST_MACHINE": "aarch64",
4883
"TEST_COMPUTE_CAPS": "11.0",
4984
"TEST_CUDA_VERSION": "13.2",
85+
"SONAR_ENABLE_CUDA_COMPATIBILITY": "0",
86+
"SONAR_CUDA_COMPATIBILITY_PATH": "",
5087
}
5188

5289

@@ -127,6 +164,7 @@ def test_installer_validates_cuda_platform(
127164
tmp_path: Path,
128165
installer_environment: dict[str, str],
129166
machine: str,
167+
cuda_driver: Path,
130168
os_name: str,
131169
cuda_version: str,
132170
compute_caps: str,
@@ -138,6 +176,7 @@ def test_installer_validates_cuda_platform(
138176
TEST_CUDA_VERSION=cuda_version,
139177
TEST_COMPUTE_CAPS=compute_caps,
140178
)
179+
installer_environment.update(LD_LIBRARY_PATH=str(cuda_driver), TEST_DRIVER_API="13000")
141180
result = _installer_dry_run(tmp_path, installer_environment, "cuda")
142181

143182
if error is None:
@@ -150,6 +189,66 @@ def test_installer_validates_cuda_platform(
150189
assert not (tmp_path / "venv").exists()
151190

152191

192+
@pytest.mark.parametrize("explicit_path", [False, True])
193+
@pytest.mark.parametrize(
194+
"overrides,error",
195+
[
196+
({}, None),
197+
({"TEST_DRIVER_API": "13000"}, "requires CUDA 13.2"),
198+
({"TEST_DRIVER_STATUS": "999"}, "cuDriverGetVersion failed"),
199+
({"TEST_INIT_STATUS": "803"}, "cuInit failed"),
200+
({"TEST_DEVICE_COUNT": "0"}, "exposes no devices"),
201+
({"TEST_COUNT_STATUS": "100"}, "cuDeviceGetCount failed"),
202+
({"TEST_COMPUTE_CAPS": "8.7"}, "compute capability: 8.7"),
203+
],
204+
)
205+
def test_installer_probes_compatibility_driver(
206+
tmp_path: Path, installer_environment: dict[str, str], cuda_driver: Path, explicit_path: bool, overrides, error
207+
) -> None:
208+
installer_environment.update(
209+
TEST_CUDA_VERSION="13.0",
210+
LD_LIBRARY_PATH=str(tmp_path / "unused"),
211+
SONAR_ENABLE_CUDA_COMPATIBILITY="true" if explicit_path else "0",
212+
SONAR_CUDA_COMPATIBILITY_PATH=str(cuda_driver),
213+
)
214+
if not explicit_path:
215+
installer_environment["LD_LIBRARY_PATH"] = str(cuda_driver)
216+
installer_environment.update(overrides)
217+
result = _installer_dry_run(tmp_path, installer_environment, "cuda")
218+
if error is None:
219+
assert result.returncode == 0, result.stdout + result.stderr
220+
assert "https://download.pytorch.org/whl/cu132" in result.stdout
221+
export = next(line.strip() for line in result.stdout.splitlines() if "export LD_LIBRARY_PATH=" in line)
222+
subprocess.run(
223+
[
224+
"sh",
225+
"-c",
226+
f"{export}; exec python3 -c 'import ctypes; assert ctypes.CDLL(\"libcuda.so.1\").cuInit(0) == 0'",
227+
],
228+
env={**installer_environment, "LD_LIBRARY_PATH": ""},
229+
capture_output=True,
230+
text=True,
231+
check=True,
232+
)
233+
else:
234+
assert result.returncode != 0, result.stdout + result.stderr
235+
assert error in result.stderr
236+
assert "https://sonar.invalid/whl/" not in result.stdout
237+
assert not (tmp_path / "venv").exists()
238+
239+
240+
def test_installer_rejects_missing_explicit_compatibility_library(tmp_path: Path, installer_environment) -> None:
241+
installer_environment.update(
242+
TEST_CUDA_VERSION="13.0",
243+
SONAR_ENABLE_CUDA_COMPATIBILITY="1",
244+
SONAR_CUDA_COMPATIBILITY_PATH=str(tmp_path / "missing"),
245+
)
246+
result = _installer_dry_run(tmp_path, installer_environment, "cuda")
247+
assert result.returncode != 0
248+
assert "CUDA compatibility library not found" in result.stderr
249+
assert not (tmp_path / "venv").exists()
250+
251+
153252
def _wheel(name: str, version: str, *, dependency: bool = False) -> tuple[str, bytes]:
154253
module = name.replace("-", "_")
155254
dist_info = f"{module}-{version}.dist-info"

0 commit comments

Comments
 (0)