llama-cpp-python
是一个 Python 库,为 llama.cpp
提供 Python 绑定,允许在 Python 中高效运行大型语言模型(LLM)的推理任务。llama.cpp
是一个用 C/C++ 实现的轻量级框架,专注于在 CPU 和 GPU 上运行量化模型(如 LLaMA、Mistral 等),以较低的资源占用实现高性能推理。llama-cpp-python
通过高层次和低层次 API 提供灵活的模型操作,广泛应用于本地化 LLM 部署、文本生成和研究。
以下是对 llama-cpp-python
库的详细说明和常见用法。
Llama
类):简化文本生成和对话任务。ctypes
提供对 llama.cpp
的直接访问。Python 版本:支持 Python 3.6+(推荐 3.8+)。
依赖:
cmake
、gcc
/g++
(Linux/Mac)或 Visual Studio(Windows)。BLAS
(如 OpenBLAS)、CUDA
(NVIDIA GPU)、Metal
(Apple Silicon)、ROCm
(AMD GPU)。安装命令:
pip install llama-cpp-python
CMAKE_ARGS="-DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
CMAKE_ARGS="-DGGML_CUDA=on" FORCE_CMAKE=1 pip install --upgrade --force-reinstall llama-cpp-python --no-cache-dir
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/cpu
替换 /cpu
为 /cu121
(CUDA 12.1)或 /metal
(Metal)以获取特定支持。Windows 注意事项:
set FORCE_CMAKE=1
set CMAKE_ARGS=-DGGML_CUBLAS=ON
cmake
和 ninja
。验证安装:
import llama_cpp
print(llama_cpp.__version__) # 示例输出: 0.3.1
模型文件:
zephyr-7b-beta.Q4_K_M.gguf
(Hugging Face: TheBloke/zephyr-7B-beta-GGUF
)。llama-cpp-python
提供 Llama
类作为高层次接口,支持文本生成、对话和结构化输出。以下是主要功能和示例。
使用 Llama
类加载模型并生成文本。
from llama_cpp import Llama
# 加载模型
llm = Llama(model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf", n_ctx=2048)
# 文本生成
output = llm("Q: What is the capital of France? A: ", max_tokens=32)
print(output["choices"][0]["text"]) # 输出: The capital of France is Paris.
说明:
model_path
:GGUF 模型文件的路径。n_ctx
:上下文长度(最大 token 数)。max_tokens
:生成的最大 token 数。choices
包含生成的文本。使用 create_chat_completion
实现对话。
from llama_cpp import Llama
llm = Llama(model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf", n_ctx=2048)
response = llm.create_chat_completion(
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What's the weather like in Paris?"}
]
)
print(response["choices"][0]["message"]["content"])
说明:
create_chat_completion
模拟 OpenAI 的聊天 API。使用 GBNF 语法文件控制输出格式(如 JSON)。
from llama_cpp import Llama
from pydantic import BaseModel
import json
# 定义 Pydantic 模型并生成 JSON 模式
class Person(BaseModel):
name: str
age: int
schema = json.loads(Person.schema_json())
# 假设已将 schema 转换为 GBNF 文件(json.gbnf)
llm = Llama(
model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf",
grammar_path="path/to/json.gbnf"
)
output = llm("Describe a person in JSON format:", max_tokens=128)
print(output["choices"][0]["text"]) # 输出: {"name": "John Doe", "age": 34}
说明:
llama.cpp
的 json-schema-to-grammar.py
脚本将 JSON 模式转换为 GBNF。grammar_path
指定 GBNF 文件,确保输出符合指定结构。启用 GPU 加速以提高推理速度。
from llama_cpp import Llama
llm = Llama(
model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf",
n_gpu_layers=-1, # -1 表示将所有层卸载到 GPU
n_ctx=2048,
n_batch=512
)
output = llm("Hello, world!", max_tokens=32)
print(output["choices"][0]["text"])
说明:
n_gpu_layers
:指定卸载到 GPU 的层数,-1
表示全部。n_batch
:批处理大小,需根据显存调整。llama-cpp-python
提供类似 OpenAI 的 API 服务器。
pip install 'llama-cpp-python[server]'
python -m llama_cpp.server --model path/to/zephyr-7b-beta.Q4_K_M.gguf --n_gpu_layers 35
访问:
http://localhost:8000/docs
查看 OpenAPI 文档。--host 0.0.0.0
允许远程连接,--port
更改端口。Python 客户端示例:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-no-key-required")
response = client.chat.completions.create(
model="zephyr-7b-beta",
messages=[{"role": "user", "content": "Hi!"}]
)
print(response.choices[0].message.content)
说明:
支持 Llava 1.5 等多模态模型,处理文本和图像。
from llama_cpp import Llama
llm = Llama(
model_path="path/to/llava-13b.Q4_K_M.gguf",
clip_model_path="path/to/clip_model.gguf" # CLIP 模型路径
)
# 假设有图像处理代码,需自定义聊天处理器
说明:
通过 from_pretrained
方法直接从 Hugging Face Hub 下载和加载 GGUF 模型。
from llama_cpp import Llama
# 从 Hugging Face 下载并加载模型
llm = Llama.from_pretrained(
repo_id="Qwen/Qwen2-0.5B-Instruct-GGUF",
filename="*q8_0.gguf",
verbose=False
)
# 聊天完成
response = llm.create_chat_completion(
messages=[
{"role": "user", "content": "Explain quantum computing in simple terms."}
]
)
print(response["choices"][0]["message"]["content"])
说明:
repo_id
:Hugging Face 仓库 ID(如 hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF
)。filename
:GGUF 文件名,支持通配符。huggingface-hub
自动缓存模型到本地(默认路径:~/.cache/huggingface/hub
)。huggingface-hub
:pip install huggingface-hub
由于 llama.cpp
和 Hugging Face 的分词器可能不一致,建议使用 Hugging Face 分词器。
from llama_cpp import Llama, LlamaHFTokenizer
from transformers import AutoTokenizer
# 加载 Hugging Face 分词器
hf_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
llama_tokenizer = LlamaHFTokenizer(hf_tokenizer)
# 加载模型并指定分词器
llm = Llama.from_pretrained(
repo_id="Qwen/Qwen2-0.5B-Instruct-GGUF",
filename="*q8_0.gguf",
tokenizer=llama_tokenizer
)
# 推理
response = llm.create_chat_completion(
messages=[{"role": "user", "content": "What is AI?"}]
)
print(response["choices"][0]["message"]["content"])
说明:
LlamaHFTokenizer
包装 Hugging Face 分词器,确保一致性。llama.cpp
使用 C/C++ 实现,推理速度快,量化支持降低内存占用(例如,7B 模型在 4-bit 量化下需约 4-6GB RAM)。n_gpu_layers
:llm = Llama(model_path="model.gguf", n_gpu_layers=32)
n_ctx
设置,支持长上下文(最大视模型而定)。n_batch
优化 token 处理:llm = Llama(model_path="model.gguf", n_batch=256)
create_chat_completion
构建对话系统。示例(与 LangChain 集成):
from langchain.llms import LlamaCpp
from langchain.prompts import PromptTemplate
llm = LlamaCpp.from_pretrained(
repo_id="Qwen/Qwen2-0.5B-Instruct-GGUF",
filename="*q8_0.gguf",
n_ctx=2048
)
prompt = PromptTemplate(
input_variables=["question"],
template="Question: {question}\nAnswer: "
)
chain = prompt | llm
print(chain.invoke({"question": "What is Python?"}))
说明:
LlamaCpp
是 LangChain 的包装类,支持复杂工作流。convert_hf_to_gguf.py
)。llama.cpp
默认分词器可能与 Hugging Face 不一致,推荐使用 LlamaHFTokenizer
。import os
os.environ["HUGGING_FACE_TOKEN"] = "your_token"
llama-cpp-python
和 huggingface-hub
版本最新(截至 2025,llama-cpp-python
为 0.3.1)。llama.cpp
提交版本(部分功能需特定提交)。llama-cpp-python
可能被弃用,但截至 2025 年,项目仍活跃(GitHub 更新频繁)。以下是一个综合示例,展示从 Hugging Face 下载模型、加载分词器和执行聊天任务:
from llama_cpp import Llama, LlamaHFTokenizer
from transformers import AutoTokenizer
import os
# 设置 Hugging Face 令牌(若需访问受限模型)
os.environ["HUGGING_FACE_TOKEN"] = "your_token"
# 加载分词器
hf_tokenizer = AutoTokenizer.from_pretrained("hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF")
llama_tokenizer = LlamaHFTokenizer(hf_tokenizer)
# 加载模型
llm = Llama.from_pretrained(
repo_id="hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF",
filename="llama-3.2-3b-instruct-q8_0.gguf",
tokenizer=llama_tokenizer,
n_ctx=2048,
n_gpu_layers=32, # GPU 加速
verbose=False
)
# 聊天完成
response = llm.create_chat_completion(
messages=[
{"role": "system", "content": "You are a knowledgeable AI assistant."},
{"role": "user", "content": "Explain the difference between Python and Java."}
],
max_tokens=200
)
print(response["choices"][0]["message"]["content"])
输出示例:
Python and Java are both popular programming languages, but they differ in several key aspects:
1. **Syntax and Readability**:
- **Python**: Known for its simple, readable syntax, emphasizing code clarity. It uses indentation for blocks, reducing boilerplate code.
- **Java**: Has a more verbose syntax, requiring explicit declarations and curly braces `{}` for blocks.
2. **Typing**:
- **Python**: Dynamically typed; variables don't need explicit type declarations (e.g., `x = 5`).
- **Java**: Statically typed; variables must be declared with a type (e.g., `int x = 5`).
3. **Performance**:
- **Python**: Interpreted, generally slower for CPU-intensive tasks but faster for development.
- **Java**: Compiled to bytecode, runs on the JVM, often faster for large-scale applications.
4. **Use Cases**:
- **Python**: Widely used in data science, machine learning, and scripting.
- **Java**: Common in enterprise applications, Android development, and large systems.
5. **Memory Management**:
- Both use garbage collection, but Java’s JVM provides more control over memory optimization.
Choose Python for rapid prototyping and data analysis, Java for robust, scalable systems.
llama.cpp
教程:https://www.datacamp.com/tutorial/llama-cpp-tutorialFiles
选项卡,选择适合硬件的量化级别(如 Q4_K_M
适合低内存,Q8_0
精度更高)。TheBloke
、hugging-quants
。huggingface-cli
加速下载:HUGGINGFACE_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download Qwen/Qwen2-0.5B-Instruct-GGUF --include "*q8_0.gguf"
CMAKE_ARGS="-DGGML_CUDA=ON"
)。CUDA_PATH
)。LlamaHFTokenizer
)。