【Python】llama-cpp-python 库:为 llama.cpp 提供 Python 绑定 [复制链接]
发表于 2025-8-24 04:05:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
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 库的详细阐明和常见用法。

1. llama-cpp-python 库的作用



  • 本地 LLM 推理:在本地硬件上运行开源 LLM(如 LLaMA、Mistral、Zephyr),无需依赖云 API
  • 性能:支持量化模子(GGUF 格式),在 CPU 或 GPU 上高效运行,适合资源受限情况。
  • 灵活接口

    • 高条理 API(Llama 类):简化文本生成和对话任务。
    • 低条理 API(C API 绑定):通过 ctypes 提供对 llama.cpp 的直接访问。

  • 与生态集成:支持 LangChain、LlamaIndex 等框架,适合构建复杂应用。
  • 多模态支持:支持多模态模子(如 Llava 1.5),处置惩罚文本和图像输入。
  • API 兼容性:提供类似 OpenAI 的 API 服务器,兼容现有客户端。

2. 安装与情况要求



  • 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)。

  • 安装下令

    • 根本安装(CPU):
      1. pip install llama-cpp-python
      复制代码
    • 使用 OpenBLAS 优化:
      1. CMAKE_ARGS="-DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
      复制代码
    • GPU 支持(CUDA):
      1. CMAKE_ARGS="-DGGML_CUDA=on" FORCE_CMAKE=1 pip install --upgrade --force-reinstall llama-cpp-python --no-cache-dir
      复制代码
    • Metal 支持(MacOS):
      1. CMAKE_ARGS="-DGGML_METAL=on" pip install llama-cpp-python
      复制代码
    • 预编译轮(避免编译):
      1. pip install llama-cpp-python
      2. --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
      复制代码
      替换 /cpu 为 /cu121(CUDA 12.1)或 /metal(Metal)以获取特定支持。

  • Windows 留意事项

    • 需安装 Visual Studio(含 C++ 开辟工具)或 MinGW。
    • 设置情况变量:
      1. set FORCE_CMAKE=1
      2. set CMAKE_ARGS=-DGGML_CUBLAS=ON
      复制代码
    • 可能需手动安装 cmake 和 ninja。

  • 验证安装
    1. import llama_cpp
    2. print(llama_cpp.__version__)  # 示例输出: 0.3.1
    复制代码
  • 模子文件

    • 必要手动下载 GGUF 格式的模子文件(如从 Hugging Face 的 TheBloke 堆栈)。
    • 示例模子:zephyr-7b-beta.Q4_K_M.gguf(Hugging Face: TheBloke/zephyr-7B-beta-GGUF)。


3. 核心功能与用法

llama-cpp-python 提供 Llama 类作为高条理接口,支持文本生成、对话和结构化输出。以下是主要功能和示例。
3.1 根本文本生成

使用 Llama 类加载模子并生成文本。
  1. from llama_cpp import Llama
  2. # 加载模型
  3. llm = Llama(model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf", n_ctx=2048)
  4. # 文本生成
  5. output = llm("Q: What is the capital of France? A: ", max_tokens=32)
  6. print(output["choices"][0]["text"])  # 输出: The capital of France is Paris.
复制代码
阐明


  • model_path:GGUF 模子文件的路径。
  • n_ctx:上下文长度(最大 token 数)。
  • max_tokens:生成的最大 token 数。
  • 输出是一个字典,choices 包含生成的文本。
3.2 对话模式

使用 create_chat_completion 实现对话。
  1. from llama_cpp import Llama
  2. llm = Llama(model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf", n_ctx=2048)
  3. response = llm.create_chat_completion(
  4.     messages=[
  5.         {"role": "system", "content": "You are a helpful assistant."},
  6.         {"role": "user", "content": "What's the weather like in Paris?"}
  7.     ]
  8. )
  9. print(response["choices"][0]["message"]["content"])
复制代码
阐明


  • create_chat_completion 模拟 OpenAI 的谈天 API。
  • 支持体系提示和多轮对话。
3.3 结构化输出(Grammar)

使用 GBNF 语法文件控制输出格式(如 JSON)。
  1. from llama_cpp import Llama
  2. from pydantic import BaseModel
  3. import json
  4. # 定义 Pydantic 模型并生成 JSON 模式
  5. class Person(BaseModel):
  6.     name: str
  7.     age: int
  8. schema = json.loads(Person.schema_json())
  9. # 假设已将 schema 转换为 GBNF 文件(json.gbnf)
  10. llm = Llama(
  11.     model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf",
  12.     grammar_path="path/to/json.gbnf"
  13. )
  14. output = llm("Describe a person in JSON format:", max_tokens=128)
  15. print(output["choices"][0]["text"])  # 输出: {"name": "John Doe", "age": 34}
复制代码
阐明


  • 使用 llama.cpp 的 json-schema-to-grammar.py 脚本将 JSON 模式转换为 GBNF。
  • grammar_path 指定 GBNF 文件,确保输出符合指定结构。
  • 留意:可能因 token 限制导致 JSON 不完整。
3.4 GPU 加速

启用 GPU 加速以进步推理速率。
  1. from llama_cpp import Llama
  2. llm = Llama(
  3.     model_path="path/to/zephyr-7b-beta.Q4_K_M.gguf",
  4.     n_gpu_layers=-1,  # -1 表示将所有层卸载到 GPU
  5.     n_ctx=2048,
  6.     n_batch=512
  7. )
  8. output = llm("Hello, world!", max_tokens=32)
  9. print(output["choices"][0]["text"])
复制代码
阐明


  • n_gpu_layers:指定卸载到 GPU 的层数,-1 表示全部。
  • n_batch:批处置惩罚大小,需根据显存调整。
3.5 运行 OpenAI 兼容服务器

llama-cpp-python 提供类似 OpenAI 的 API 服务器
  1. pip install 'llama-cpp-python[server]'
  2. 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 客户端示例
  1. from openai import OpenAI
  2. client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-no-key-required")
  3. response = client.chat.completions.create(
  4.     model="zephyr-7b-beta",
  5.     messages=[{"role": "user", "content": "Hi!"}]
  6. )
  7. print(response.choices[0].message.content)
复制代码
阐明


  • 服务器兼容 OpenAI 客户端库,适合快速集成。
3.6 多模态支持(Llava)

支持 Llava 1.5 等多模态模子,处置惩罚文本和图像。
  1. from llama_cpp import Llama
  2. llm = Llama(
  3.     model_path="path/to/llava-13b.Q4_K_M.gguf",
  4.     clip_model_path="path/to/clip_model.gguf"  # CLIP 模型路径
  5. )
  6. # 假设有图像处理代码,需自定义聊天处理器
复制代码
阐明


  • 需下载多模态 GGUF 模子和对应的 CLIP 模子。
  • 使用自界说谈天处置惩罚器处置惩罚图像输入。
3.7 Hugging Face 集成

通过 from_pretrained 方法直接从 Hugging Face Hub 下载和加载 GGUF 模子。
  1. from llama_cpp import Llama
  2. # 从 Hugging Face 下载并加载模型
  3. llm = Llama.from_pretrained(
  4.     repo_id="Qwen/Qwen2-0.5B-Instruct-GGUF",
  5.     filename="*q8_0.gguf",
  6.     verbose=False
  7. )
  8. # 聊天完成
  9. response = llm.create_chat_completion(
  10.     messages=[
  11.         {"role": "user", "content": "Explain quantum computing in simple terms."}
  12.     ]
  13. )
  14. 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:
    1. pip install huggingface-hub
    复制代码
3.8 使用 Hugging Face 分词器

由于 llama.cpp 和 Hugging Face 的分词器可能不一致,建议使用 Hugging Face 分词器。
  1. from llama_cpp import Llama, LlamaHFTokenizer
  2. from transformers import AutoTokenizer
  3. # 加载 Hugging Face 分词器
  4. hf_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
  5. llama_tokenizer = LlamaHFTokenizer(hf_tokenizer)
  6. # 加载模型并指定分词器
  7. llm = Llama.from_pretrained(
  8.     repo_id="Qwen/Qwen2-0.5B-Instruct-GGUF",
  9.     filename="*q8_0.gguf",
  10.     tokenizer=llama_tokenizer
  11. )
  12. # 推理
  13. response = llm.create_chat_completion(
  14.     messages=[{"role": "user", "content": "What is AI?"}]
  15. )
  16. print(response["choices"][0]["message"]["content"])
复制代码
阐明


  • LlamaHFTokenizer 包装 Hugging Face 分词器,确保一致性。
  • 分词器文件通常包含在 GGUF 模子的 Hugging Face 堆栈中。

4. 性能与优化



  • 高效性:llama.cpp 使用 C/C++ 实现,推理速率快,量化支持降低内存占用(比方,7B 模子在 4-bit 量化下需约 4-6GB RAM)。
  • GPU 加速

    • 支持 CUDA(NVIDIA)、ROCm(AMD)、SYCL(Intel)。
    • 示例:加载模子时设置 n_gpu_layers:
      1. llm = Llama(model_path="model.gguf", n_gpu_layers=32)
      复制代码

  • 上下文长度:通过 n_ctx 设置,支持长上下文(最大视模子而定)。
  • 批量处置惩罚:设置 n_batch 优化 token 处置惩罚:
    1. llm = Llama(model_path="model.gguf", n_batch=256)
    复制代码

5. 现实应用场景



  • 谈天呆板人:使用 create_chat_completion 构建对话体系。
  • 代码生成:加载 CodeLlama 模子,生成代码片断。
  • 文本总结:结合 LangChain 和 Hugging Face 模子举行文档总结。
  • 本地推理:在无 GPU 的设备上运行轻量模子。
  • API 服务:部署 OpenAI 兼容服务器,集成到 Web 应用。
示例(与 LangChain 集成)
  1. from langchain.llms import LlamaCpp
  2. from langchain.prompts import PromptTemplate
  3. llm = LlamaCpp.from_pretrained(
  4.     repo_id="Qwen/Qwen2-0.5B-Instruct-GGUF",
  5.     filename="*q8_0.gguf",
  6.     n_ctx=2048
  7. )
  8. prompt = PromptTemplate(
  9.     input_variables=["question"],
  10.     template="Question: {question}\nAnswer: "
  11. )
  12. chain = prompt | llm
  13. print(chain.invoke({"question": "What is Python?"}))
复制代码
阐明


  • LlamaCpp 是 LangChain 的包装类,支持复杂工作流。

6. 留意事项



  • 模子格式

    • 仅支持 GGUF 格式,Hugging Face 的 PyTorch 模子需转换(使用 convert_hf_to_gguf.py)。
    • 转换脚本:https://github.com/ggerganov/llama.cpp

  • 分词器题目

    • llama.cpp 默认分词器可能与 Hugging Face 不一致,保举使用 LlamaHFTokenizer。

  • 内存需求

    • 量化模子仍需足够内存(比方,7B Q4 模子约需 4GB RAM)。
    • 检查硬件支持(CPU/GPU)和上下文长度。

  • Hugging Face 权限

    • 某些模子(如 LLaMA)是受限模子,需申请访问权限(https://huggingface.co/meta-llama)。
    • 设置 Hugging Face 令牌:
      1. import os
      2. 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 更新频繁)。


7. 综合示例

以下是一个综合示例,展示从 Hugging Face 下载模子、加载分词器和执行谈天任务:
  1. from llama_cpp import Llama, LlamaHFTokenizer
  2. from transformers import AutoTokenizer
  3. import os
  4. # 设置 Hugging Face 令牌(若需访问受限模型)
  5. os.environ["HUGGING_FACE_TOKEN"] = "your_token"
  6. # 加载分词器
  7. hf_tokenizer = AutoTokenizer.from_pretrained("hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF")
  8. llama_tokenizer = LlamaHFTokenizer(hf_tokenizer)
  9. # 加载模型
  10. llm = Llama.from_pretrained(
  11.     repo_id="hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF",
  12.     filename="llama-3.2-3b-instruct-q8_0.gguf",
  13.     tokenizer=llama_tokenizer,
  14.     n_ctx=2048,
  15.     n_gpu_layers=32,  # GPU 加速
  16.     verbose=False
  17. )
  18. # 聊天完成
  19. response = llm.create_chat_completion(
  20.     messages=[
  21.         {"role": "system", "content": "You are a knowledgeable AI assistant."},
  22.         {"role": "user", "content": "Explain the difference between Python and Java."}
  23.     ],
  24.     max_tokens=200
  25. )
  26. print(response["choices"][0]["message"]["content"])
复制代码
输出示例
  1. Python and Java are both popular programming languages, but they differ in several key aspects:
  2. 1. **Syntax and Readability**:
  3.    - **Python**: Known for its simple, readable syntax, emphasizing code clarity. It uses indentation for blocks, reducing boilerplate code.
  4.    - **Java**: Has a more verbose syntax, requiring explicit declarations and curly braces `{}` for blocks.
  5. 2. **Typing**:
  6.    - **Python**: Dynamically typed; variables don't need explicit type declarations (e.g., `x = 5`).
  7.    - **Java**: Statically typed; variables must be declared with a type (e.g., `int x = 5`).
  8. 3. **Performance**:
  9.    - **Python**: Interpreted, generally slower for CPU-intensive tasks but faster for development.
  10.    - **Java**: Compiled to bytecode, runs on the JVM, often faster for large-scale applications.
  11. 4. **Use Cases**:
  12.    - **Python**: Widely used in data science, machine learning, and scripting.
  13.    - **Java**: Common in enterprise applications, Android development, and large systems.
  14. 5. **Memory Management**:
  15.    - Both use garbage collection, but Java’s JVM provides more control over memory optimization.
  16. Choose Python for rapid prototyping and data analysis, Java for robust, scalable systems.
复制代码

8. 资源与文档



  • 官方文档:https://llama-cpp-python.readthedocs.io/
  • GitHub 堆栈:https://github.com/abetlen/llama-cpp-python
  • PyPI 页面:https://pypi.org/project/llama-cpp-python/
  • Hugging Face GGUF 指南:https://huggingface.co/docs/hub/gguf
  • llama.cpp 文档:https://github.com/ggerganov/llama.cpp
  • 教程

    • DataCamp 的 llama.cpp 教程:https://www.datacamp.com/tutorial/llama-cpp-tutorial
    • PyImageSearch 的指南:https://pyimagesearch.com/2024/08/26/llama-cpp-the-ultimate-guide-to-efficient-llm-inference-and-applications/


9. 常见题目与解答



  • 如何选择 GGUF 模子?

    • 查看 Hugging Face 堆栈的 Files 选项卡,选择适合硬件的量化级别(如 Q4_K_M 适合低内存,Q8_0 精度更高)。
    • 保举堆栈:TheBloke、hugging-quants。

  • 模子下载慢怎么办?

    • 使用 huggingface-cli 加速下载:
      1. HUGGINGFACE_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download Qwen/Qwen2-0.5B-Instruct-GGUF --include "*q8_0.gguf"
      复制代码

  • GPU 不工作?

    • 确保安装 GPU 版本(CMAKE_ARGS="-DGGML_CUDA=ON")。
    • 检查 CUDA 情况变量(CUDA_PATH)。

  • 如何调试分词题目?

    • 始终使用 Hugging Face 分词器(LlamaHFTokenizer)。
    • 检查模子卡中的分词器设置。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表