Skip to content

Studio: propagate the Ollama CUDA runtime to llama-server (replacement for #7563) - #11666

Merged
danielhanchen merged 21 commits into
unslothai:mainfrom
wasimysaid:mimir/rebuild-7563-ollama-cuda-runtime
Sep 25, 2026
Merged

danielhanchen merged 21 commits into
unslothai:mainfrom
wasimysaid:mimir/rebuild-7563-ollama-cuda-runtime

Conversation

@wasimysaid

@wasimysaid wasimysaid commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The Unsloth prebuilt installer can select an Ollama-vendored CUDA runtime from /usr/local/lib/ollama/cuda_v*, but the private directory is not automatically available to the dynamic loader. If the selected CUDA runtime is not otherwise loader-resolvable, llama-server or whisper-server can fail to load its CUDA backend.

This replacement for unslothai/unsloth#7563 propagates the matching Ollama directory to both launchers as a last-resort search path. It does not prepend that path or override a runtime already found through the loader cache or native default directories.

Changes

  • Detect complete, exact-major Ollama CUDA runtime pairs and avoid injecting them when the loader can already resolve the pair.
  • Cover loader-cache ABI compatibility, existing cache targets, and Debian/Ubuntu multiarch defaults when ldconfig is unavailable.
  • Apply the same runtime rescue to llama-server and Whisper, including external Whisper symlinks.
  • Preserve the non-dict install-marker guard and host-independent LD_LIBRARY_PATH assertion.

Verification

  • Linux/CPython 3.13: four affected pytest suites passed (522 passed) at head b1fa74a424ada8918406321bb8e621ff74f0268b.
  • Current-main negative control confirmed that the Ollama runtime is absent from a spawned child's /proc/<pid>/environ on baseline ae3077a09f2dcc7970721f7d06c6022de49ced1f.
  • Six spawned-child checks exercised llama-server and whisper host/rescue behavior plus multiarch-system and empty-directory controls. Child environments were read from /proc/<pid>/environ; LD_DEBUG=libs confirmed the injected directory was searched only in rescue cases.

The Ollama tree and no-ldconfig loader variants were fixtures because this host has no Ollama installation. This validates launch environment and loader search behavior, not CUDA inference.

Credit

Replacement of Imagineer99's original work in #7563; source and analysis credit remains with @Imagineer99 (Lee Jackson).


Verification update — head is now 29595023021c, and the loader behaviour is shown live

The head referenced in the description (b1fa74a424) is superseded. Current head:

29595023021c1f1d6bc6b1e75307301a34bd0cd6 — 21 commits, 19 files, +1746 / -79; fork PR #210.

Main-versus-head dynamic-loader evidence

Full writeup: https://raw.githubusercontent.com/wasimysaid/unsloth/08fe681340a721da23d7bc4e35e7da2887bc2e41/acceptance/210-29595023021c/live-loader.md

Machine-readable result (41 891 bytes, sha256 bebc2a2e057f28b6ecd6b7425b8f233d143f9a11fa59ea5124b97ca150cadaca):
https://raw.githubusercontent.com/wasimysaid/unsloth/08fe681340a721da23d7bc4e35e7da2887bc2e41/acceptance/210-29595023021c/runtime-result.json

Pinned base ae3077a09f2dcc7970721f7d06c6022de49ced1f versus pinned head 29595023021c1f1d6bc6b1e75307301a34bd0cd6; status passed, outcome reproduced. Ten arms were run for each launcher (llama-server, whisper-server) against both revisions. In every arm the product's own child-env builder produced the environment, a real process was spawned with it and its environment was read back from that child's /proc/<pid>/environ, and CUDA resolution was performed by the real glibc loader /lib64/ld-linux-x86-64.so.2 running a compiled ELF whose NEEDED entries are exactly libcudart.so.13 and libcublas.so.13; each arm's resolved object path was read back from the loader child's own /proc/<pid>/maps.

  • Head, unpatched host (ldconfig readable, its cache naming a system CUDA 13): both launchers withheld the vendored directory and the child mapped the system /usr/local/cuda-13.1 payloads (rc 0).
  • Head, ldconfig genuinely unusable (RLIMIT_NPROC = 0 makes every exec fail in the kernel — BlockingIOError: [Errno 11] … '/sbin/ldconfig'): both launchers appended the vendored directory last and the loader mapped both CUDA objects from it (rc 0); the same binary with the appended directory removed failed rc 127, so the resolution is attributable.
  • Exact-SONAME vendored shape loads when forced (rc 0); the payload-only shape (fully-versioned filenames, no SONAME entry) fails rc 127 and the helper refuses that directory.
  • Synthetic arch-dir sub-arms: an unreadable cache with the arch dir populated produced "already provides" and a withhold; the same dir emptied produced "not provided", an append, and a vendored resolution.
  • Base never appends in any arm: every unreadable-cache arm fails rc 127 for both launchers, while its host-default and system-precedence arms resolve the system objects. The base/head difference is therefore exactly the append this change introduces, with the withhold behaviour preserved.

Independent checks

  • All 27 declared artifact digests recomputed and match, and the published runtime-result.json is byte-identical to the local result.
  • The whole ten-arm matrix was re-executed from scratch by a reviewer against the pinned head and the pinned base: all 20 per-arm decisions (vendored presence, last-position, loader rc, loaded objects, origin) and the blocked-exec diagnostics reproduced exactly. The focused suites were re-run at the exact head: 527 passed.

Credit

Replacement of Imagineer99's original work in #7563; source and analysis credit remains with @Imagineer99 (Lee Jackson).

Limitations

  • This host has no /usr/local/lib/ollama tree, so the vendored tree was synthesized inside the arm workspace and reached through the module's documented roots override. The bytes placed in it are the host's real CUDA 13 payloads (sha256-identical to /usr/local/cuda/targets/x86_64-linux/lib), not stubs.
  • The arch-specific default directory used by the two synthetic precedence sub-arms is a workspace directory assigned to the loader's default-dir list; the real /lib/x86_64-linux-gnu and /usr/lib/x86_64-linux-gnu directories were only detected and reported, never modified.
  • The ldconfig-unavailable arms enforce RLIMIT_NPROC = 0 to make exec genuinely fail; that is a real kernel-enforced failure, but it is not a disk image with ldconfig removed.
  • The restricted loader arms deliberately search only the binary directory plus whatever the product appended, modelling a host with no system CUDA toolkit.
  • No GPU kernel was executed: no CUDA workload, no device initialization and no inference, so nothing here attests to GPU runtime behaviour. This validates the loader search path and the child environment, not CUDA inference.
  • The head is behind unslothai/unsloth main (34 commits at audit time, 35 a few minutes later; merge base ae3077a0, the pinned base — main is still moving, so re-check before rebasing). The two failing CI jobs on this head — Repo tests (CPU, studio) and Repo tests (CPU, rest) — are pre-existing unrelated failures, not caused by this change: the failing tests/studio/test_model_picker_catalog_first_paint.py and the pickers.tsx it reads are byte-identical between the pinned base and this head, and the test also fails on the pinned base tree here. Upstream main has since updated both files. Rebasing brings them along.
  • Unrelated existing save/export and HTML-decoder findings raised by automated review were answered on their own comment threads as pre-existing (both files byte-identical between the pinned base and this head) and downvoted; they are not part of this change.

Imagineer99 and others added 8 commits September 23, 2026 07:41
The Linux/WSL prebuilt installer discovers a CUDA runtime under
/usr/local/lib/ollama/cuda_v* and will select a CUDA runtime line from it,
but that directory is private to Ollama and is not on the dynamic linker's
search path. A prebuilt whose only libcudart/libcublas copy lives there
could not load its CUDA backend and silently fell back to CPU.

The launchers now read the build's install marker and put the matching
Ollama CUDA directory last on the child loader path, so it only rescues
hosts with no other copy and never displaces the runtime that qualified
the build. The whisper-server sidecar does the same, including slim
bundles whose CUDA module is hardlinked from a paired llama.cpp install.

Rebuilt from unslothai#7563 by Imagineer99, adapted onto current
main.
…CUDA

The vendored dir joins LD_LIBRARY_PATH, which precedes the loader's cache and
its default dirs however late the entry sits, so appending it last was not
enough: where ldconfig already answers libcudart/libcublas for that major, the
private copy would still take precedence over the runtime that qualified the
build. Yield the dir only while the loader cannot find both, falling back to
the default dirs when no ldconfig can be read.

The rescue direction is unchanged: with neither the cache nor the defaults
providing the pair, the dir is still added.
The no-ldconfig fallback probed only the generic loader defaults, but Debian
and Ubuntu glibc searches the architecture-specific /lib/<triple> and
/usr/lib/<triple> built in -- `ld.so --list-diagnostics` lists them ahead of
/lib and /usr/lib -- and the installer counts them too. A distro CUDA runtime
sitting in one of those was therefore reported missing, the Ollama dir joined
LD_LIBRARY_PATH, and it displaced that runtime despite the loader probe.

Discover the dirs by glob rather than by machine name, so a multilib host, a
second architecture, or a container holding only one of the pair is covered.

The pair of arms pins it: the new discovery rule, and the real list checked
against the interpreter's own MULTIARCH triple, which is what the previous
draft asserted with a condition that could not hold.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #11666, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#92.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1 — reviewed mirror b84f167a9 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/utils/prebuilt/runtime_libs.py (on the mirror)

@@ -36,6 +43,156 @@ def dedupe_existing_dirs(paths: Iterable[str | Path]) -> list[str]:
     return unique
 
 
+# Debian multiarch dirs are built into ld.so's default search path, no ldconfig needed.
+_MULTIARCH_LIB_GLOBS: tuple[str, ...] = ("/lib/*-linux-gnu*", "/usr/lib/*-linux-gnu*")
+
+
+def _multiarch_lib_dirs() -> list[str]:
+    found: list[str] = []
+    for pattern in _MULTIARCH_LIB_GLOBS:
+        try:
+            found.extend(sorted(glob.glob(pattern)))
+        except OSError:
+            continue
+    return found
+
+
+_LOADER_DEFAULT_LIB_DIRS: tuple[str, ...] = (
+    "/lib",
+    "/lib64",
+    "/usr/lib",
+    "/usr/lib64",
+    *_multiarch_lib_dirs(),

P2 Badge Restrict multiarch defaults to the host ABI

On systems with foreign-architecture packages or cross-compilation directories, this expands to every directory matching *-linux-gnu* (for example, both x86_64-linux-gnu and i386-linux-gnu). _loader_already_provides_runtime() then treats CUDA SONAMEs found in any of them as native loader defaults and withholds the Ollama runtime, even though glibc will not search or load the foreign-ABI directory; both llama-server and whisper-server can consequently retain the missing-runtime failure this change is intended to fix. Limit these directories to the host multiarch tuple or verify their ABI before considering them loader-visible.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not reachable in practice: this only matters when a foreign multiarch dir holds libcudart.so. and libcublas.so. for the build's CUDA 12/13 line. NVIDIA removed 32-bit CUDA from 12.0 onward (https://nvidia.custhelp.com/app/answers/detail/a_id/5615), so i386-linux-gnu never carries them, and installing another 64-bit architecture's CUDA libraries through dpkg multiarch on a GPU host is not a supported setup. Leaving the glob as is.

chatgpt-codex-connector[bot] on studio/backend/utils/prebuilt/runtime_libs.py (on the mirror)

@@ -36,6 +43,156 @@ def dedupe_existing_dirs(paths: Iterable[str | Path]) -> list[str]:
     return unique
 
 
+# Debian multiarch dirs are built into ld.so's default search path, no ldconfig needed.
+_MULTIARCH_LIB_GLOBS: tuple[str, ...] = ("/lib/*-linux-gnu*", "/usr/lib/*-linux-gnu*")
+
+
+def _multiarch_lib_dirs() -> list[str]:
+    found: list[str] = []
+    for pattern in _MULTIARCH_LIB_GLOBS:
+        try:
+            found.extend(sorted(glob.glob(pattern)))
+        except OSError:
+            continue
+    return found
+
+
+_LOADER_DEFAULT_LIB_DIRS: tuple[str, ...] = (
+    "/lib",
+    "/lib64",
+    "/usr/lib",
+    "/usr/lib64",
+    *_multiarch_lib_dirs(),
+)
+
+
+def _ld_cache_entries() -> tuple[tuple[str, str, str], ...] | None:
+    """(soname, ABI, path) entries, or None when ldconfig cannot be read."""
+    for candidate in ("ldconfig", "/sbin/ldconfig", "/usr/sbin/ldconfig"):
+        exe = shutil.which(candidate) if "/" not in candidate else candidate
+        if not exe or not os.path.exists(exe):
+            continue
+        try:
+            result = subprocess.run(
+                [exe, "-p"],
+                capture_output = True,
+                text = True,
+                encoding = "utf-8",
+                errors = "replace",
+                timeout = 10,
+            )
+        except (OSError, subprocess.SubprocessError):
+            continue
+        if result.returncode != 0:
+            continue
+        entries: list[tuple[str, str, str]] = []
+        for line in (result.stdout or "").splitlines():
+            match = re.match(r"\s*(\S+)\s+\(([^)]*)\)\s+=>\s+(\S+)", line)
+            if match:
+                soname, abi_text, path = match.groups()
+                abi = abi_text.strip().lower()
+                entries.append((soname, abi, path))
+        return tuple(entries)
+    return None
+
+
+def _loader_resolves_sonames(sonames: tuple[str, ...]) -> bool:
+    """Probe in a child process so CUDA never loads into Studio."""
+    script = "import ctypes, sys; [ctypes.CDLL(name) for name in sys.argv[1:]]"
+    try:
+        result = subprocess.run(
+            [sys.executable, "-I", "-S", "-c", script, *sonames],
+            capture_output = True,
+            timeout = 10,
+        )
+    except (OSError, subprocess.SubprocessError):
+        return False
+    return result.returncode == 0
+
+
+_NATIVE_LOADER_ABIS: dict[str, frozenset[str]] = {
+    "x86_64": frozenset({"libc6,x86-64", "libc6,x86-64-v2", "libc6,x86-64-v3", "libc6,x86-64-v4"}),
+    "amd64": frozenset({"libc6,x86-64", "libc6,x86-64-v2", "libc6,x86-64-v3", "libc6,x86-64-v4"}),
+    "i386": frozenset({"libc6,i686", "libc6,i586", "libc6,i486", "libc6,i386"}),
+    "i686": frozenset({"libc6,i686", "libc6,i586", "libc6,i486", "libc6,i386"}),
+    "aarch64": frozenset({"libc6,aarch64"}),
+    "arm64": frozenset({"libc6,aarch64"}),
+    "armv7l": frozenset({"libc6,armhf"}),
+    "ppc64le": frozenset({"libc6,ppc64le"}),
+    "s390x": frozenset({"libc6,s390x"}),
+    "riscv64": frozenset({"libc6,riscv64"}),
+}
+
+
+def _loader_already_provides_runtime(major: str) -> bool:
+    """LD_LIBRARY_PATH outranks ld.so.cache and default dirs: never shadow a native pair they provide."""
+    sonames = (f"libcudart.so.{major}", f"libcublas.so.{major}")
+    cached = _ld_cache_entries()
+    if cached is None and _loader_resolves_sonames(sonames):
+        return True
+    native_abis = _NATIVE_LOADER_ABIS.get(platform.machine().lower(), frozenset())
+    for soname in sonames:
+        cache_has_compatible = cached is not None and any(
+            cached_soname == soname
+            and abi in native_abis
+            and os.path.isfile(path)
+            and os.access(path, os.R_OK)

P2 Badge Verify cached CUDA libraries are loadable before withholding fallback

When ldconfig reports readable libcudart and libcublas files, this treats the runtime as usable without attempting to load it; the default-directory branch makes the same assumption. On a partial or damaged CUDA installation—such as libcublas.so.13 remaining while its required libcublasLt.so.13 is missing—the files pass these checks but the server still cannot load them, and the working Ollama directory is withheld even though placing it on LD_LIBRARY_PATH would take precedence over the broken cached/default runtime. Probe the candidate pair in the child process before returning true, not only when ldconfig is unavailable.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Out of scope by design: this rescue only fills in for a runtime that is absent. A damaged system CUDA install (libcublas.so.13 without libcublasLt.so.13) is a broken host, and silently routing around it with another application's private copy would contradict the rule the helper exists for: never displace a runtime the loader already resolves. Probing on every launch would also add a CUDA-loading child process to each llama-server start on healthy hosts.

Round 2 — reviewed mirror b84f167a9 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: b84f167a93

View security finding report

Only the user who started this review can view the report in Codex.

No triage reaction was recorded on the mirror

Verdict

The round did not reach a clean review on the mirror before it closed.

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit 828234f into unslothai:main Sep 25, 2026
47 of 49 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…t for unslothai#7563) (unslothai#11666)

* fix(studio): propagate Ollama CUDA runtime to llama-server

The Linux/WSL prebuilt installer discovers a CUDA runtime under
/usr/local/lib/ollama/cuda_v* and will select a CUDA runtime line from it,
but that directory is private to Ollama and is not on the dynamic linker's
search path. A prebuilt whose only libcudart/libcublas copy lives there
could not load its CUDA backend and silently fell back to CPU.

The launchers now read the build's install marker and put the matching
Ollama CUDA directory last on the child loader path, so it only rescues
hosts with no other copy and never displaces the runtime that qualified
the build. The whisper-server sidecar does the same, including slim
bundles whose CUDA module is hardlinked from a paired llama.cpp install.

Rebuilt from unslothai#7563 by Imagineer99, adapted onto current
main.

* fix(studio): never let the Ollama runtime displace a loader-resolved CUDA

The vendored dir joins LD_LIBRARY_PATH, which precedes the loader's cache and
its default dirs however late the entry sits, so appending it last was not
enough: where ldconfig already answers libcudart/libcublas for that major, the
private copy would still take precedence over the runtime that qualified the
build. Yield the dir only while the loader cannot find both, falling back to
the default dirs when no ldconfig can be read.

The rescue direction is unchanged: with neither the cache nor the defaults
providing the pair, the dir is still added.

* fix(studio): count the multiarch dirs when ldconfig cannot be read

The no-ldconfig fallback probed only the generic loader defaults, but Debian
and Ubuntu glibc searches the architecture-specific /lib/<triple> and
/usr/lib/<triple> built in -- `ld.so --list-diagnostics` lists them ahead of
/lib and /usr/lib -- and the installer counts them too. A distro CUDA runtime
sitting in one of those was therefore reported missing, the Ollama dir joined
LD_LIBRARY_PATH, and it displaced that runtime despite the loader probe.

Discover the dirs by glob rather than by machine name, so a multilib host, a
second architecture, or a container holding only one of the pair is covered.

The pair of arms pins it: the new discovery rule, and the real list checked
against the interpreter's own MULTIARCH triple, which is what the previous
draft asserted with a condition that could not hold.

* fix(studio): handle loader cache ABI and symlink markers

* fix(studio): restore cache probe dependency

* fix(studio): ignore stale CUDA cache entries

* fix(studio): handle CUDA loader edge cases

* fix(studio): normalize loader cache ABI labels

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): reject unreadable loader defaults

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): check loader cache without ldconfig

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): require CUDA runtime soname links

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): probe loader after cache query failure

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in vendored CUDA runtime rescue

* Guard os.geteuid in vendored CUDA runtime tests for Windows collection

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: imagineer99 <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants