llama-cpp-python
llama-cpp-python copied to clipboard
RPC is broken due to change of interface in llama.cpp main repository (rpc : early register backend devices #11262)
RPC does not work in llama-cpp-python since this commit in llama.cpp
Revision: 667d72846c06b2cf4f7c8a4265e210991a49706b
Author: Radoslav Gerganov <[email protected]>
Date: 17/01/2025 09:57:09
Message:
rpc : early register backend devices (#11262)
Early register RPC devices and do not propagate RPC specifics in the
llama model structures.
This commit change the way rpc_servers are passed to llama.cpp, (in llama.cpp\common\arg.cpp) it is not a parameter anymore (params.rpc_servers = value;) but need to call add_rpc_devices(value);
To reproduce:
from llama_cpp import Llama
llm = Llama(
model_path=MODEL,
rpc_servers=RPC_NODES,
n_ctx = 4096,
flash_attn = False,
n_gpu_layers = 99,
verbose=True
)
--> should init with RPC offloading
here is a quick fix i created with chatgpt to get rpc working:
diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py
index 7e9a6af..5274e98 100644
--- a/llama_cpp/llama.py
+++ b/llama_cpp/llama.py
@@ -51,6 +51,45 @@ import llama_cpp._internals as internals
from ._logger import set_verbose
from ._utils import suppress_stdout_stderr
+_rpc_devices_registered = False
+from llama_cpp.llama_cpp import _lib # now _lib holds the shared library handle
+
+def add_rpc_devices(servers: str) -> None:
+ """
+ Register RPC devices with the llama backend using the provided comma‐separated string.
+ """
+ global _rpc_devices_registered
+ if _rpc_devices_registered:
+ return # Already registered, so do nothing
+ lib = _lib # use the imported shared library handle
+ # Bind ggml_backend_reg_by_name
+ lib.ggml_backend_reg_by_name.argtypes = [ctypes.c_char_p]
+ lib.ggml_backend_reg_by_name.restype = ctypes.c_void_p
+ rpc_reg = lib.ggml_backend_reg_by_name(b"RPC")
+ if not rpc_reg:
+ raise ValueError("failed to find RPC backend")
+ # Bind ggml_backend_reg_get_proc_address
+ lib.ggml_backend_reg_get_proc_address.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
+ lib.ggml_backend_reg_get_proc_address.restype = ctypes.c_void_p
+ rpc_add_fn_ptr = lib.ggml_backend_reg_get_proc_address(rpc_reg, b"ggml_backend_rpc_add_device")
+ if not rpc_add_fn_ptr:
+ raise ValueError("failed to find RPC device add function")
+ # Create a callable from the function pointer: returns a void pointer given a char*
+ PROTOTYPE = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p)
+ rpc_add_fn = PROTOTYPE(rpc_add_fn_ptr)
+ # Bind ggml_backend_device_register
+ lib.ggml_backend_device_register.argtypes = [ctypes.c_void_p]
+ lib.ggml_backend_device_register.restype = None
+ # For each server in the comma-separated list, register the device.
+ for server in servers.split(','):
+ server = server.strip().encode("utf-8")
+ dev = rpc_add_fn(server)
+ if dev:
+ lib.ggml_backend_device_register(dev)
+ else:
+ raise ValueError(f"failed to register RPC device for server: {server.decode('utf-8')}")
+ _rpc_devices_registered = True
+
class Llama:
"""High-level Python wrapper for a llama.cpp model."""
@@ -227,7 +266,7 @@ class Llama:
self.model_params.split_mode = split_mode
self.model_params.main_gpu = main_gpu
if rpc_servers is not None:
- self.model_params.rpc_servers = rpc_servers.encode("utf-8")
+ add_rpc_devices(rpc_servers)
self._rpc_servers = rpc_servers
else:
self._rpc_servers = None
What are we waiting for to fix it? Is there any road-blocker?
Does anyone can merge it? I think this is an important feature that doesn't work.
An updated version (rpc needs to be added back for the patch to apply)
diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py
index 71d94eb..8042108 100644
--- a/llama_cpp/llama.py
+++ b/llama_cpp/llama.py
@@ -51,6 +51,44 @@ import llama_cpp._internals as internals
from ._logger import set_verbose
from ._utils import suppress_stdout_stderr
+_rpc_devices_registered = False
+
+def add_rpc_devices(servers: str) -> None:
+ """
+ Register RPC devices with the llama backend using the provided comma‐separated string.
+ """
+ global _rpc_devices_registered
+ if _rpc_devices_registered:
+ return # Already registered, so do nothing
+ lib = llama_cpp._lib # use the imported shared library handle
+ # Bind ggml_backend_reg_by_name
+ lib.ggml_backend_reg_by_name.argtypes = [ctypes.c_char_p]
+ lib.ggml_backend_reg_by_name.restype = ctypes.c_void_p
+ rpc_reg = lib.ggml_backend_reg_by_name(b"RPC")
+ if not rpc_reg:
+ raise ValueError("failed to find RPC backend")
+ # Bind ggml_backend_reg_get_proc_address
+ lib.ggml_backend_reg_get_proc_address.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
+ lib.ggml_backend_reg_get_proc_address.restype = ctypes.c_void_p
+ rpc_add_fn_ptr = lib.ggml_backend_reg_get_proc_address(rpc_reg, b"ggml_backend_rpc_add_device")
+ if not rpc_add_fn_ptr:
+ raise ValueError("failed to find RPC device add function")
+ # Create a callable from the function pointer: returns a void pointer given a char*
+ PROTOTYPE = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p)
+ rpc_add_fn = PROTOTYPE(rpc_add_fn_ptr)
+ # Bind ggml_backend_device_register
+ lib.ggml_backend_device_register.argtypes = [ctypes.c_void_p]
+ lib.ggml_backend_device_register.restype = None
+ # For each server in the comma-separated list, register the device.
+ for server in servers.split(','):
+ server = server.strip().encode("utf-8")
+ dev = rpc_add_fn(server)
+ if dev:
+ lib.ggml_backend_device_register(dev)
+ else:
+ raise ValueError(f"failed to register RPC device for server: {server.decode('utf-8')}")
+ _rpc_devices_registered = True
+
class Llama:
"""High-level Python wrapper for a llama.cpp model."""
@@ -66,6 +104,7 @@ class Llama:
split_mode: int = llama_cpp.LLAMA_SPLIT_MODE_LAYER,
main_gpu: int = 0,
tensor_split: Optional[List[float]] = None,
+ rpc_servers: Optional[str] = None,
vocab_only: bool = False,
use_mmap: bool = True,
use_mlock: bool = False,
@@ -151,6 +190,7 @@ class Llama:
split_mode: How to split the model across GPUs. See llama_cpp.LLAMA_SPLIT_* for options.
main_gpu: main_gpu interpretation depends on split_mode: LLAMA_SPLIT_MODE_NONE: the GPU that is used for the entire model. LLAMA_SPLIT_MODE_ROW: the GPU that is used for small tensors and intermediate results. LLAMA_SPLIT_MODE_LAYER: ignored
tensor_split: How split tensors should be distributed across GPUs. If None, the model is not split.
+ rpc_servers: Comma separated list of RPC servers to use for offloading
vocab_only: Only load the vocabulary no weights.
use_mmap: Use mmap if possible.
use_mlock: Force the system to keep the model in RAM.
@@ -228,6 +268,11 @@ class Llama:
) # 0x7FFFFFFF is INT32 max, will be auto set to all layers
self.model_params.split_mode = split_mode
self.model_params.main_gpu = main_gpu
+ if rpc_servers is not None:
+ add_rpc_devices(rpc_servers)
+ self._rpc_servers = rpc_servers
+ else:
+ self._rpc_servers = None
self.tensor_split = tensor_split
self._c_tensor_split = None
if self.tensor_split is not None:
Found a way to patch around this issue by dynamically including it in python using ctypes if anyone is interested
try:
# 1. Boot the core engine
if hasattr(llama_cpp, "llama_backend_init"):
llama_cpp.llama_backend_init()
import os
import ctypes
base_dir = os.path.dirname(llama_cpp.__file__)
# 2. Grab the base ggml.dll (handles the hardware registry)
ggml_dll_path = os.path.join(base_dir, "lib", "ggml.dll")
if not os.path.exists(ggml_dll_path):
ggml_dll_path = os.path.join(base_dir, "ggml.dll")
ggml_lib = ctypes.CDLL(ggml_dll_path)
# 3. Grab the network ggml-rpc.dll (handles the IP handshakes)
rpc_dll_path = os.path.join(base_dir, "lib", "ggml-rpc.dll")
if not os.path.exists(rpc_dll_path):
rpc_dll_path = os.path.join(base_dir, "ggml-rpc.dll")
# 4. Extract the direct device-add function
if os.path.exists(rpc_dll_path):
print(f"[LLM-Chat] Loading RPC extension directly from: {rpc_dll_path}")
rpc_lib = ctypes.CDLL(rpc_dll_path)
rpc_add_fn = rpc_lib.ggml_backend_rpc_add_device
else:
print(f"[LLM-Chat] Warning: ggml-rpc.dll not found, checking fallback locations...")
# Fallback just in case it statically linked
rpc_add_fn = ggml_lib.ggml_backend_rpc_add_device
# 5. Map the C-functions directly to Python
rpc_add_fn.argtypes = [ctypes.c_char_p]
rpc_add_fn.restype = ctypes.c_void_p
ggml_lib.ggml_backend_device_register.argtypes = [ctypes.c_void_p]
ggml_lib.ggml_backend_device_register.restype = None
# 6. Initialize and register your remote rpc PC
for server in rpc_servers.split(','):
server_bytes = server.strip().encode("utf-8")
# Ping the remote rpc and create the memory buffer
dev = rpc_add_fn(server_bytes)
if dev:
# Successfully pinged! Now add it to the main host's registry
ggml_lib.ggml_backend_device_register(dev)
print(f"[LLM-Chat] Successfully registered RPC device: {server.strip()}")
else:
print(f"[LLM-Chat] Warning: Failed to init RPC device: {server.strip()}")
except Exception as e:
print(f" Ctypes workaround failed: {e}")
import traceback
traceback.print_exc()