llama.cpp
的 Python 绑定 @ggerganov 的llama.cpp
库的简单 Python 绑定。该软件包提供:
ctypes
接口对 C API 进行低级访问。文档位于 https://llama-cpp-python.readthedocs.io/en/latest。
要求:
要安装该软件包,请运行:
pip install llama-cpp-python
这还将从源代码构建llama.cpp
并将其与此 python 包一起安装。
如果失败,请将--verbose
添加到pip install
查看完整的 cmake 构建日志。
预制轮(新)
还可以安装具有基本 CPU 支持的预制轮。
pip install llama-cpp-python
--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
llama.cpp
支持许多硬件加速后端以加速推理以及后端特定选项。有关完整列表,请参阅 llama.cpp 自述文件。
所有llama.cpp
cmake 构建选项都可以通过CMAKE_ARGS
环境变量或在安装过程中通过--config-settings / -C
cli 标志设置。
# Linux and Mac
CMAKE_ARGS= " -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS "
pip install llama-cpp-python
# Windows
$ env: CMAKE_ARGS = " -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS "
pip install llama - cpp - python
它们还可以通过pip install -C / --config-settings
命令进行设置并保存到requirements.txt
文件中:
pip install --upgrade pip # ensure pip is up to date
pip install llama-cpp-python
-C cmake.args= " -DGGML_BLAS=ON;-DGGML_BLAS_VENDOR=OpenBLAS "
# requirements.txt
llama-cpp-python -C cmake.args="-DGGML_BLAS=ON;-DGGML_BLAS_VENDOR=OpenBLAS"
以下是一些常见的后端、它们的构建命令以及所需的任何其他环境变量。
要使用 OpenBLAS 安装,请在安装前设置GGML_BLAS
和GGML_BLAS_VENDOR
环境变量:
CMAKE_ARGS= " -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS " pip install llama-cpp-python
要安装 CUDA 支持,请在安装前设置GGML_CUDA=on
环境变量:
CMAKE_ARGS= " -DGGML_CUDA=on " pip install llama-cpp-python
预制轮(新)
还可以安装支持 CUDA 的预构建轮。只要您的系统满足一些要求:
pip install llama-cpp-python
--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/ < cuda-version >
其中<cuda-version>
是以下之一:
cu121
:CUDA 12.1cu122
:CUDA 12.2cu123
:CUDA 12.3cu124
:CUDA 12.4cu125
:CUDA 12.5例如,要安装 CUDA 12.1 轮:
pip install llama-cpp-python
--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu121
要使用 Metal (MPS) 安装,请在安装前设置GGML_METAL=on
环境变量:
CMAKE_ARGS= " -DGGML_METAL=on " pip install llama-cpp-python
预制轮(新)
还可以安装带有金属支撑的预制轮。只要您的系统满足一些要求:
pip install llama-cpp-python
--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/metal
要安装 AMD 卡的 hipBLAS / ROCm 支持,请在安装前设置GGML_HIPBLAS=on
环境变量:
CMAKE_ARGS= " -DGGML_HIPBLAS=on " pip install llama-cpp-python
要安装 Vulkan 支持,请在安装前设置GGML_VULKAN=on
环境变量:
CMAKE_ARGS= " -DGGML_VULKAN=on " pip install llama-cpp-python
要安装 SYCL 支持,请在安装前设置GGML_SYCL=on
环境变量:
source /opt/intel/oneapi/setvars.sh
CMAKE_ARGS= " -DGGML_SYCL=on -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx " pip install llama-cpp-python
要安装 RPC 支持,请在安装前设置GGML_RPC=on
环境变量:
source /opt/intel/oneapi/setvars.sh
CMAKE_ARGS= " -DGGML_RPC=on " pip install llama-cpp-python
如果您遇到问题,它抱怨找不到'nmake'
'?'
或 CMAKE_C_COMPILER,您可以按照 llama.cpp 存储库中所述提取 w64devkit 并在运行pip
install 之前将其手动添加到 CMAKE_ARGS:
$env:CMAKE_GENERATOR = "MinGW Makefiles"
$env:CMAKE_ARGS = "-DGGML_OPENBLAS=on -DCMAKE_C_COMPILER=C: /w64devkit/bin/gcc.exe -DCMAKE_CXX_COMPILER=C: /w64devkit/bin/g++.exe"
请参阅上述说明并将CMAKE_ARGS
设置为您要使用的 BLAS 后端。
详细的 MacOS Metal GPU 安装文档位于 docs/install/macos.md
注意:如果您使用的是Apple Silicon (M1) Mac,请确保您已安装支持arm64架构的Python版本。例如:
wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh
bash Miniforge3-MacOSX-arm64.sh
否则,安装时将构建 llama.cpp x86 版本,该版本在 Apple Silicon (M1) Mac 上速度会慢 10 倍。
尝试安装
CMAKE_ARGS= " -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_APPLE_SILICON_PROCESSOR=arm64 -DGGML_METAL=on " pip install --upgrade --verbose --force-reinstall --no-cache-dir llama-cpp-python
要升级和重建llama-cpp-python
请将--upgrade --force-reinstall --no-cache-dir
标志添加到pip install
命令中,以确保从源重建软件包。
API参考
高级 API 通过Llama
类提供简单的托管接口。
下面是一个简短的示例,演示了如何使用高级 API 来完成基本文本:
from llama_cpp import Llama
llm = Llama (
model_path = "./models/7B/llama-model.gguf" ,
# n_gpu_layers=-1, # Uncomment to use GPU acceleration
# seed=1337, # Uncomment to set a specific seed
# n_ctx=2048, # Uncomment to increase the context window
)
output = llm (
"Q: Name the planets in the solar system? A: " , # Prompt
max_tokens = 32 , # Generate up to 32 tokens, set to None to generate up to the end of the context window
stop = [ "Q:" , " n " ], # Stop generating just before the model would generate a new question
echo = True # Echo the prompt back in the output
) # Generate a completion, can also call create_completion
print ( output )
默认情况下llama-cpp-python
以 OpenAI 兼容格式生成补全:
{
"id" : "cmpl-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ,
"object" : "text_completion" ,
"created" : 1679561337 ,
"model" : "./models/7B/llama-model.gguf" ,
"choices" : [
{
"text" : "Q: Name the planets in the solar system? A: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune and Pluto." ,
"index" : 0 ,
"logprobs" : None ,
"finish_reason" : "stop"
}
],
"usage" : {
"prompt_tokens" : 14 ,
"completion_tokens" : 28 ,
"total_tokens" : 42
}
}
文本完成可通过Llama
类的__call__
和create_completion
方法获得。
您可以使用from_pretrained
方法直接从 Hugging Face 下载gguf
格式的Llama
模型。您需要安装huggingface-hub
软件包才能使用此功能( pip install huggingface-hub
)。
llm = Llama . from_pretrained (
repo_id = "Qwen/Qwen2-0.5B-Instruct-GGUF" ,
filename = "*q8_0.gguf" ,
verbose = False
)
默认情况下from_pretrained
会将模型下载到 Huggingface 缓存目录,然后您可以使用huggingface-cli
工具管理已安装的模型文件。
高级 API 还提供了一个简单的聊天完成界面。
聊天完成要求模型知道如何将消息格式化为单个提示。 Llama
类使用预先注册的聊天格式(即chatml
、 llama-2
、 gemma
等)或通过提供自定义聊天处理程序对象来完成此操作。
该模型将使用以下优先顺序将消息格式化为单个提示:
chat_handler
(如果提供)chat_format
(如果提供)gguf
模型元数据中的tokenizer.chat_template
(应该适用于大多数新模型,旧模型可能没有这个)llama-2
聊天格式设置verbose=True
以查看所选的聊天格式。
from llama_cpp import Llama
llm = Llama (
model_path = "path/to/llama-2/llama-model.gguf" ,
chat_format = "llama-2"
)
llm . create_chat_completion (
messages = [
{ "role" : "system" , "content" : "You are an assistant who perfectly describes images." },
{
"role" : "user" ,
"content" : "Describe this image in detail please."
}
]
)
聊天完成可通过Llama
类的create_chat_completion
方法实现。
为了兼容 OpenAI API v1,您可以使用create_chat_completion_openai_v1
方法,该方法将返回 pydantic 模型而不是字典。
要将聊天响应限制为仅有效 JSON 或特定 JSON 模式,请使用create_chat_completion
中的response_format
参数。
以下示例将仅响应有效的 JSON 字符串。
from llama_cpp import Llama
llm = Llama ( model_path = "path/to/model.gguf" , chat_format = "chatml" )
llm . create_chat_completion (
messages = [
{
"role" : "system" ,
"content" : "You are a helpful assistant that outputs in JSON." ,
},
{ "role" : "user" , "content" : "Who won the world series in 2020" },
],
response_format = {
"type" : "json_object" ,
},
temperature = 0.7 ,
)
要将响应进一步限制为特定 JSON 架构,请将该架构添加到response_format
参数的schema
属性中。
from llama_cpp import Llama
llm = Llama ( model_path = "path/to/model.gguf" , chat_format = "chatml" )
llm . create_chat_completion (
messages = [
{
"role" : "system" ,
"content" : "You are a helpful assistant that outputs in JSON." ,
},
{ "role" : "user" , "content" : "Who won the world series in 2020" },
],
response_format = {
"type" : "json_object" ,
"schema" : {
"type" : "object" ,
"properties" : { "team_name" : { "type" : "string" }},
"required" : [ "team_name" ],
},
},
temperature = 0.7 ,
)
高层API支持OpenAI兼容的函数和工具调用。这可以通过functionary
预训练模型聊天格式或通过通用chatml-function-calling
聊天格式来实现。
from llama_cpp import Llama
llm = Llama ( model_path = "path/to/chatml/llama-model.gguf" , chat_format = "chatml-function-calling" )
llm . create_chat_completion (
messages = [
{
"role" : "system" ,
"content" : "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. The assistant calls functions with appropriate input when necessary"
},
{
"role" : "user" ,
"content" : "Extract Jason is 25 years old"
}
],
tools = [{
"type" : "function" ,
"function" : {
"name" : "UserDetail" ,
"parameters" : {
"type" : "object" ,
"title" : "UserDetail" ,
"properties" : {
"name" : {
"title" : "Name" ,
"type" : "string"
},
"age" : {
"title" : "Age" ,
"type" : "integer"
}
},
"required" : [ "name" , "age" ]
}
}
}],
tool_choice = {
"type" : "function" ,
"function" : {
"name" : "UserDetail"
}
}
)
可以在此处找到这组模型的各种 gguf 转换文件。 Functionary 能够智能地调用函数,并分析任何提供的函数输出以生成一致的响应。所有 v2 型号的 functionary 都支持并行函数调用。初始化 Llama 类时,您可以为chat_format
提供functionary-v1
或functionary-v2
。
由于 llama.cpp 和 HuggingFace 的 tokenizer 之间存在差异,需要为工作人员提供 HF Tokenizer。 LlamaHFTokenizer
类可以被初始化并传递到 Llama 类中。这将覆盖 Llama 类中使用的默认 llama.cpp 标记生成器。分词器文件已包含在托管 gguf 文件的相应 HF 存储库中。
from llama_cpp import Llama
from llama_cpp . llama_tokenizer import LlamaHFTokenizer
llm = Llama . from_pretrained (
repo_id = "meetkai/functionary-small-v2.2-GGUF" ,
filename = "functionary-small-v2.2.q4_0.gguf" ,
chat_format = "functionary-v2" ,
tokenizer = LlamaHFTokenizer . from_pretrained ( "meetkai/functionary-small-v2.2-GGUF" )
)
注意:无需提供 Functionary 中使用的默认系统消息,因为它们会自动添加到 Functionary 聊天处理程序中。因此,消息应仅包含为模型提供附加上下文的聊天消息和/或系统消息(例如:日期时间等)。
llama-cpp-python
支持 llava1.5 等语言模型,允许语言模型从文本和图像中读取信息。
以下是支持的多模式模型及其各自的聊天处理程序 (Python API) 和聊天格式 (服务器 API)。
模型 | LlamaChatHandler | chat_format |
---|---|---|
llava-v1.5-7b | Llava15ChatHandler | llava-1-5 |
llava-v1.5-13b | Llava15ChatHandler | llava-1-5 |
llava-v1.6-34b | Llava16ChatHandler | llava-1-6 |
月梦2 | MoondreamChatHandler | moondream2 |
纳诺拉瓦 | NanollavaChatHandler | nanollava |
骆驼-3-视觉-阿尔法 | Llama3VisionAlphaChatHandler | llama-3-vision-alpha |
minicpm-v-2.6 | MiniCPMv26ChatHandler | minicpm-v-2.6 |
然后,您需要使用自定义聊天处理程序来加载剪辑模型并处理聊天消息和图像。
from llama_cpp import Llama
from llama_cpp . llama_chat_format import Llava15ChatHandler
chat_handler = Llava15ChatHandler ( clip_model_path = "path/to/llava/mmproj.bin" )
llm = Llama (
model_path = "./path/to/llava/llama-model.gguf" ,
chat_handler = chat_handler ,
n_ctx = 2048 , # n_ctx should be increased to accommodate the image embedding
)
llm . create_chat_completion (
messages = [
{ "role" : "system" , "content" : "You are an assistant who perfectly describes images." },
{
"role" : "user" ,
"content" : [
{ "type" : "text" , "text" : "What's in this image?" },
{ "type" : "image_url" , "image_url" : { "url" : "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } }
]
}
]
)
您还可以使用from_pretrained
方法从 Hugging Face Hub 中提取模型。
from llama_cpp import Llama
from llama_cpp . llama_chat_format import MoondreamChatHandler
chat_handler = MoondreamChatHandler . from_pretrained (
repo_id = "vikhyatk/moondream2" ,
filename = "*mmproj*" ,
)
llm = Llama . from_pretrained (
repo_id = "vikhyatk/moondream2" ,
filename = "*text-model*" ,
chat_handler = chat_handler ,
n_ctx = 2048 , # n_ctx should be increased to accommodate the image embedding
)
response = llm . create_chat_completion (
messages = [
{
"role" : "user" ,
"content" : [
{ "type" : "text" , "text" : "What's in this image?" },
{ "type" : "image_url" , "image_url" : { "url" : "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } }
]
}
]
)
print ( response [ "choices" ][ 0 ][ "text" ])
注:多模态模型还支持工具调用和JSON模式。
图像可以作为 base64 编码的数据 URI 传递。以下示例演示了如何执行此操作。
import base64
def image_to_base64_data_uri ( file_path ):
with open ( file_path , "rb" ) as img_file :
base64_data = base64 . b64encode ( img_file . read ()). decode ( 'utf-8' )
return f"data:image/png;base64, { base64_data } "
# Replace 'file_path.png' with the actual path to your PNG file
file_path = 'file_path.png'
data_uri = image_to_base64_data_uri ( file_path )
messages = [
{ "role" : "system" , "content" : "You are an assistant who perfectly describes images." },
{
"role" : "user" ,
"content" : [
{ "type" : "image_url" , "image_url" : { "url" : data_uri }},
{ "type" : "text" , "text" : "Describe this image in detail please." }
]
}
]
llama-cpp-python
支持推测性解码,允许模型根据草稿模型生成补全。
使用推测解码的最快方法是通过LlamaPromptLookupDecoding
类。
只需在初始化期间将其作为草稿模型传递给Llama
类即可。
from llama_cpp import Llama
from llama_cpp . llama_speculative import LlamaPromptLookupDecoding
llama = Llama (
model_path = "path/to/model.gguf" ,
draft_model = LlamaPromptLookupDecoding ( num_pred_tokens = 10 ) # num_pred_tokens is the number of tokens to predict 10 is the default and generally good for gpu, 2 performs better for cpu-only machines.
)
要生成文本嵌入,请使用create_embedding
或embed
。请注意,您必须在创建模型时将embedding=True
传递给构造函数,以便它们正常工作。
import llama_cpp
llm = llama_cpp . Llama ( model_path = "path/to/model.gguf" , embedding = True )
embeddings = llm . create_embedding ( "Hello, world!" )
# or create multiple embeddings at once
embeddings = llm . create_embedding ([ "Hello, world!" , "Goodbye, world!" ])
Transformer 风格模型中的嵌入有两个主要概念:标记级别和序列级别。序列级嵌入是通过将令牌级嵌入“池化”在一起而生成的,通常是通过对它们进行平均或使用第一个令牌。
明确面向嵌入的模型通常会默认返回序列级嵌入,每个输入字符串一个。非嵌入模型(例如为文本生成设计的模型)通常仅返回标记级别的嵌入,每个序列中的每个标记都有一个嵌入。因此,对于令牌级别嵌入,返回类型的维度将更高。
在某些情况下,可以在模型创建时使用pooling_type
标志来控制池行为。您可以使用LLAMA_POOLING_TYPE_NONE
确保任何模型的令牌级别嵌入。相反,目前不可能获得面向生成的模型来产生序列级嵌入,但您始终可以手动进行池化。
Llama 模型的上下文窗口决定了一次可以处理的最大令牌数量。默认情况下,该值设置为 512 个令牌,但可以根据您的要求进行调整。
例如,如果您想使用更大的上下文,您可以在初始化 Llama 对象时通过设置 n_ctx 参数来扩展上下文窗口:
llm = Llama ( model_path = "./models/7B/llama-model.gguf" , n_ctx = 2048 )
llama-cpp-python
提供了一个 Web 服务器,旨在充当 OpenAI API 的直接替代品。这允许您将 llama.cpp 兼容模型与任何 OpenAI 兼容客户端(语言库、服务等)一起使用。
要安装服务器包并开始:
pip install ' llama-cpp-python[server] '
python3 -m llama_cpp.server --model models/7B/llama-model.gguf
与上面的硬件加速部分类似,您还可以安装 GPU (cuBLAS) 支持,如下所示:
CMAKE_ARGS= " -DGGML_CUDA=on " FORCE_CMAKE=1 pip install ' llama-cpp-python[server] '
python3 -m llama_cpp.server --model models/7B/llama-model.gguf --n_gpu_layers 35
导航到 http://localhost:8000/docs 以查看 OpenAPI 文档。
要绑定到0.0.0.0
以启用远程连接,请使用python3 -m llama_cpp.server --host 0.0.0.0
。同样,要更改端口(默认为 8000),请使用--port
。
您可能还想设置提示格式。对于 chatml,请使用
python3 -m llama_cpp.server --model models/7B/llama-model.gguf --chat_format chatml
这将根据模型期望的方式格式化提示。您可以在型号卡中找到提示格式。有关可能的选项,请参阅 llama_cpp/llama_chat_format.py 并查找以“@register_chat_format”开头的行。
如果您安装了huggingface-hub
,您还可以使用--hf_model_repo_id
标志从 Hugging Face Hub 加载模型。
python3 -m llama_cpp.server --hf_model_repo_id Qwen/Qwen2-0.5B-Instruct-GGUF --model ' *q8_0.gguf '
GHCR 上提供了 Docker 映像。运行服务器:
docker run --rm -it -p 8000:8000 -v /path/to/models:/models -e MODEL=/models/llama-model.gguf ghcr.io/abetlen/llama-cpp-python:latest
termux 上的 Docker(需要 root)是目前在手机上运行它的唯一已知方法,请参阅 termux 支持问题
API参考
低级 API 是直接ctypes
绑定到llama.cpp
提供的 C API。整个低级 API 可以在 llama_cpp/llama_cpp.py 中找到,并直接镜像 llama.h 中的 C API。
下面是一个简短的示例,演示了如何使用低级 API 来标记提示:
import llama_cpp
import ctypes
llama_cpp . llama_backend_init ( False ) # Must be called once at the start of each program
params = llama_cpp . llama_context_default_params ()
# use bytes for char * params
model = llama_cpp . llama_load_model_from_file ( b"./models/7b/llama-model.gguf" , params )
ctx = llama_cpp . llama_new_context_with_model ( model , params )
max_tokens = params . n_ctx
# use ctypes arrays for array params
tokens = ( llama_cpp . llama_token * int ( max_tokens ))()
n_tokens = llama_cpp . llama_tokenize ( ctx , b"Q: Name the planets in the solar system? A: " , tokens , max_tokens , llama_cpp . c_bool ( True ))
llama_cpp . llama_free ( ctx )
查看示例文件夹以获取使用低级 API 的更多示例。
文档可通过 https://llama-cpp-python.readthedocs.io/ 获取。如果您发现文档有任何问题,请提出问题或提交 PR。
该软件包正在积极开发中,我欢迎任何贡献。
首先,克隆存储库并以可编辑/开发模式安装包:
git clone --recurse-submodules https://github.com/abetlen/llama-cpp-python.git
cd llama-cpp-python
# Upgrade pip (required for editable mode)
pip install --upgrade pip
# Install with pip
pip install -e .
# if you want to use the fastapi / openapi server
pip install -e .[server]
# to install all optional dependencies
pip install -e .[all]
# to clear the local build cache
make clean
您还可以通过在vendor/llama.cpp
子模块中检查所需的提交,然后运行make clean
和pip install -e .
来测试llama.cpp
的特定提交。再次。 llama.h
API 中的任何更改都需要更改llama_cpp/llama_cpp.py
文件以匹配新 API(其他地方可能需要其他更改)。