Skip to content

Commit 5ccc899

Browse files
committed
feat: add llama.cpp extension bindings
1 parent 4aa82f0 commit 5ccc899

1 file changed

Lines changed: 93 additions & 0 deletions

File tree

‎llama_cpp/llama_cpp_ext.py‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
from __future__ import annotations
2+
3+
import ctypes
4+
import functools
5+
6+
from typing import Any, Iterable, Union
7+
8+
from . import llama_cpp
9+
10+
_lib = llama_cpp._lib
11+
12+
13+
def _ctypes_function_from_names(
14+
names: Iterable[str],
15+
argtypes: list[Any],
16+
restype: Any,
17+
):
18+
"""Decorator for extension functions whose exported symbol name can vary by ABI."""
19+
20+
def decorator(f):
21+
missing: list[str] = []
22+
for name in names:
23+
try:
24+
func = getattr(_lib, name)
25+
except AttributeError:
26+
missing.append(name)
27+
continue
28+
func.argtypes = argtypes
29+
func.restype = restype
30+
functools.wraps(f)(func)
31+
return func
32+
raise AttributeError(
33+
f"None of the shared library symbols were found: {', '.join(missing)}"
34+
)
35+
36+
return decorator
37+
38+
39+
# LLAMA_API void llama_set_embeddings_pre_norm(struct llama_context * ctx, bool value, bool masked);
40+
@_ctypes_function_from_names(
41+
(
42+
"llama_set_embeddings_pre_norm",
43+
"_Z29llama_set_embeddings_pre_normP13llama_contextbb",
44+
"?llama_set_embeddings_pre_norm@@YAXPEAUllama_context@@_N1@Z",
45+
),
46+
[llama_cpp.llama_context_p_ctypes, ctypes.c_bool, ctypes.c_bool],
47+
None,
48+
)
49+
def llama_set_embeddings_pre_norm(
50+
ctx: llama_cpp.llama_context_p,
51+
value: bool,
52+
masked: bool,
53+
/,
54+
):
55+
"""Set whether the context outputs pre-norm embeddings or not."""
56+
...
57+
58+
59+
# LLAMA_API float * llama_get_embeddings_pre_norm(struct llama_context * ctx);
60+
@_ctypes_function_from_names(
61+
(
62+
"llama_get_embeddings_pre_norm",
63+
"_Z29llama_get_embeddings_pre_normP13llama_context",
64+
"?llama_get_embeddings_pre_norm@@YAPEAMPEAUllama_context@@@Z",
65+
),
66+
[llama_cpp.llama_context_p_ctypes],
67+
ctypes.POINTER(ctypes.c_float),
68+
)
69+
def llama_get_embeddings_pre_norm(
70+
ctx: llama_cpp.llama_context_p,
71+
/,
72+
):
73+
"""Get the pre-norm embeddings from the last evaluation."""
74+
...
75+
76+
77+
# LLAMA_API float * llama_get_embeddings_pre_norm_ith(struct llama_context * ctx, int32_t i);
78+
@_ctypes_function_from_names(
79+
(
80+
"llama_get_embeddings_pre_norm_ith",
81+
"_Z33llama_get_embeddings_pre_norm_ithP13llama_contexti",
82+
"?llama_get_embeddings_pre_norm_ith@@YAPEAMPEAUllama_context@@H@Z",
83+
),
84+
[llama_cpp.llama_context_p_ctypes, ctypes.c_int32],
85+
ctypes.POINTER(ctypes.c_float),
86+
)
87+
def llama_get_embeddings_pre_norm_ith(
88+
ctx: llama_cpp.llama_context_p,
89+
i: Union[ctypes.c_int32, int],
90+
/,
91+
):
92+
"""Get the pre-norm embeddings for the ith output row from the last evaluation."""
93+
...

0 commit comments

Comments
 (0)