Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- feat: expose explicit backend loaders in the internal GGML module by @original4422 in #2451

- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
54 changes: 54 additions & 0 deletions docs/install/dynamic_backends.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Explicit dynamic backend loading (internal API)

Custom builds using `GGML_BACKEND_DL=ON` place GGML backend modules alongside the package libraries.
The native default discovery paths may not include that directory when Python runs elsewhere.
Existing native `GGML_BACKEND_PATH` can name an out-of-tree backend module; the internal `llama_cpp._ggml` module also exposes explicit registration functions.
These are low-level, private interfaces and may change with the bundled GGML version.
They are not exported as a stable top-level `llama_cpp` API.
Importing `_ggml` does not register backends or change the existing automatic selection behavior.

Load a known module before constructing models:

```python
import os
from contextlib import closing
from pathlib import Path

from llama_cpp import Llama, _ggml

# Example for a custom Unix GGML_BACKEND_DL CPU build.
# Choose the actual module filename produced by your build on other platforms.
plugin = Path(_ggml.libggml_base_path) / "libggml-cpu.so"
backend = _ggml.ggml_backend_load(os.fsencode(plugin))
if backend is None:
raise RuntimeError(f"Could not load backend: {plugin}")

try:
with closing(Llama(model_path="model.gguf", n_gpu_layers=0)) as model:
result = model.create_completion("Hello", max_tokens=8)
finally:
_ggml.ggml_backend_unload(backend)
```

The returned handle is opaque and native-owned; keep it until every model, context and other resource using that backend has closed.
Unload it exactly once, and never use the handle afterward.
Do not unload a backend that another thread or model is using.
The functions do not manage model lifetime or synchronize other users.

To request native discovery in a particular directory, use:

```python
_ggml.ggml_backend_load_all_from_path(os.fsencode(_ggml.libggml_base_path))
```

`ggml_backend_load_all()` and `ggml_backend_load_all_from_path(None)` request the existing native default search paths.
Both bulk functions return `None`; they do not return unload handles.
Paths use `bytes` (for example, `os.fsencode`), and the individual loader returns `None` on failure.
These operations require backend modules compatible with the loaded GGML library; they do not make a statically linked build dynamic.

The generic loading contract has been exercised with real dynamic modules and a tiny model on macOS arm64.
The macOS build may also contain Metal and BLAS modules; `n_gpu_layers=0` is used for the CPU model controls.
This does not establish Linux x86 CPU-variant selection, cross-platform backend compatibility or a performance improvement.

For opt-in dynamic integration tests, set `LLAMA_CPP_TEST_BACKEND` to the absolute CPU module path and `LLAMA_CPP_TEST_MODEL` to an existing small GGUF, then run `python -m pytest tests/test_ggml_backend.py`.
The tests isolate registry changes in subprocesses and do not download models.
43 changes: 43 additions & 0 deletions llama_cpp/_ggml.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,53 @@
This module provides a minimal interface for working with ggml tensors from llama-cpp-python
"""

import ctypes
import os
import pathlib
from typing import NewType, Optional

import llama_cpp._ctypes_extensions as ctypes_ext

libggml_base_path = pathlib.Path(os.path.abspath(os.path.dirname(__file__))) / "lib"
libggml = ctypes_ext.load_shared_library("ggml", libggml_base_path)


ctypes_function = ctypes_ext.ctypes_function_for_shared_library(libggml)

# Opaque native registry handle, owned by GGML rather than Python.
ggml_backend_reg_t = NewType("ggml_backend_reg_t", int)
ggml_backend_reg_t_ctypes = ctypes.c_void_p


@ctypes_function("ggml_backend_load", [ctypes.c_char_p], ggml_backend_reg_t_ctypes)
def ggml_backend_load(path: bytes, /) -> Optional[ggml_backend_reg_t]:
"""Load and register a backend module; return None if loading fails.

Pass a filesystem-encoded path (for example, os.fsencode(path)).
Keep the returned handle alive until all models and backend resources close.
"""
...


@ctypes_function("ggml_backend_unload", [ggml_backend_reg_t_ctypes], None)
def ggml_backend_unload(reg: ggml_backend_reg_t, /) -> None:
"""Unload a handle returned by ggml_backend_load after its resources close.

Do not reuse the handle after unloading, or unload a backend still in use.
"""
...


@ctypes_function("ggml_backend_load_all", [], None)
def ggml_backend_load_all() -> None:
"""Register backends using GGML's native default search paths."""
...


@ctypes_function("ggml_backend_load_all_from_path", [ctypes.c_char_p], None)
def ggml_backend_load_all_from_path(dir_path: Optional[bytes], /) -> None:
"""Register backends from a filesystem-encoded directory.

None requests GGML's native default search paths instead.
"""
...
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ nav:
- "Getting Started": "index.md"
- "Installation Guides":
- "macOS (Metal)": "install/macos.md"
- "Dynamic Backends (Internal)": "install/dynamic_backends.md"
- "API Reference": "api-reference.md"
- "OpenAI Compatible Web Server": "server.md"
- "Changelog": "changelog.md"
Expand Down
124 changes: 124 additions & 0 deletions tests/test_ggml_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Native loader contracts; dynamic-model cases are opt-in for custom builds."""

import contextlib
import ctypes
import json
import os
from pathlib import Path
import socket
import subprocess
import sys

import pytest

from llama_cpp import Llama, _ggml


def _registry():
count = _ggml.libggml.ggml_backend_reg_count
count.argtypes = []
count.restype = ctypes.c_size_t
get = _ggml.libggml.ggml_backend_reg_get
get.argtypes = [ctypes.c_size_t]
get.restype = ctypes.c_void_p
name = _ggml.libggml.ggml_backend_reg_name
name.argtypes = [ctypes.c_void_p]
name.restype = ctypes.c_char_p
return [name(get(i)).decode() for i in range(count())]


def _completion(model_path):
with contextlib.closing(
Llama(
model_path=model_path,
n_ctx=64,
n_batch=64,
n_threads=2,
n_threads_batch=2,
n_gpu_layers=0,
verbose=False,
)
) as model:
completion = model.create_completion(
"Once upon a time", max_tokens=2, temperature=0
)
assert completion["usage"]["completion_tokens"] == 2
assert completion["choices"][0]["text"]
return completion["choices"][0]["text"]


def _probe(mode, plugin, model_path):
def no_network(*args, **kwargs):
raise AssertionError("native loader test must not use the network")

socket.create_connection = no_network
socket.socket.connect = no_network
if mode == "missing":
missing = Path.cwd() / "missing-backend.so"
assert _ggml.ggml_backend_load(os.fsencode(missing)) is None
with pytest.raises(ctypes.ArgumentError):
_ggml.ggml_backend_load(str(missing))
assert _ggml.ggml_backend_load_all_from_path(os.fsencode(Path.cwd())) is None
assert _ggml.ggml_backend_load_all_from_path(None) is None
assert _ggml.ggml_backend_load_all() is None
return {"mode": mode, "null_handle": True, "void_returns": True}

assert Path(plugin).is_file()
assert Path(model_path).is_file()
assert _registry() == [], "use a fresh GGML_BACKEND_DL build for these cases"
if mode == "load":
with pytest.raises(ValueError, match="Failed to load model"):
_completion(model_path)
reg = _ggml.ggml_backend_load(os.fsencode(plugin))
assert reg is not None
try:
assert _registry() == ["CPU"]
text = _completion(model_path)
finally:
# _completion closes the model/context before the plugin is unloaded.
assert _ggml.ggml_backend_unload(reg) is None
assert _registry() == []
with pytest.raises(ValueError, match="Failed to load model"):
_completion(model_path)
return {"mode": mode, "fail_pass_fail": True, "text": text}
if mode == "from_path":
assert (
_ggml.ggml_backend_load_all_from_path(os.fsencode(Path(plugin).parent))
is None
)
elif mode == "all":
os.chdir(Path(plugin).parent)
assert _ggml.ggml_backend_load_all() is None
else:
raise AssertionError(mode)
assert "CPU" in _registry()
return {"mode": mode, "registry": _registry(), "text": _completion(model_path)}


@pytest.mark.parametrize("mode", ["missing", "load", "from_path", "all"])
def test_native_backend_loaders(tmp_path, mode):
plugin = os.environ.get("LLAMA_CPP_TEST_BACKEND", "")
model_path = os.environ.get("LLAMA_CPP_TEST_MODEL", "")
if mode != "missing" and not (plugin and model_path):
pytest.skip(
"set LLAMA_CPP_TEST_BACKEND and LLAMA_CPP_TEST_MODEL for dynamic tests"
)
env = os.environ.copy()
# Test explicit registration, not the native environment-variable workaround.
env.pop("GGML_BACKEND_PATH", None)
result = subprocess.run(
[sys.executable, str(Path(__file__).resolve()), mode, plugin, model_path],
cwd=tmp_path,
env=env,
capture_output=True,
text=True,
timeout=60,
)
assert result.returncode == 0, result.stdout + result.stderr
report = json.loads(result.stdout)
assert report["mode"] == mode
print(result.stdout.strip())


if __name__ == "__main__":
print(json.dumps(_probe(*sys.argv[1:])))