第2节:Llama.cpp 实现指南 目录 简介 什么是 Llama.cpp? 安装 从源码构建 模型量化 基本用法 高级功能 Python 集成 故障排查 最佳实践 简介 本教程将全面指导您了解 Llama.cpp,从基础安装到高级使用场景。Llama.cpp 是一个强大的 C++ 实现,能够以最小的设置和卓越的性能在各种硬件配置上高效推理大型语言模型(LLMs)。 什么是 Llama.cpp? Llama.cpp 是一个用 C/C++ 编写的 LLM 推理框架,支持在本地运行大型语言模型,设置简单,并在多种硬件上提供最先进的性能。其主要特点包括: 核心功能 纯 C/C++ 实现,无依赖 跨平台兼容性(Windows、macOS、Linux) 硬件优化,适配多种架构 量化支持(1.
本教程将全面指导您了解 Llama.cpp,从基础安装到高级使用场景。Llama.cpp 是一个强大的 C++ 实现,能够以最小的设置和卓越的性能在各种硬件配置上高效推理大型语言模型(LLMs)。
Llama.cpp 是一个用 C/C++ 编写的 LLM 推理框架,支持在本地运行大型语言模型,设置简单,并在多种硬件上提供最先进的性能。其主要特点包括:
下载适合您系统的二进制文件:
llama-<version>-bin-win-<feature>-<arch>.zipllama-<version>-bin-macos-<feature>-<arch>.zipllama-<version>-bin-linux-<feature>-<arch>.zip解压文件并将目录添加到系统 PATH 中
macOS (Homebrew):
brew install llama.cpp
Linux (多种发行版):
# Ubuntu/Debian sudo apt install llama.cpp # Arch Linux sudo pacman -S llama.cpp
pip install llama-cpp-python
# For CUDA (NVIDIA GPUs) CMAKE_ARGS="-DGGML_CUDA=on" pip install llama-cpp-python # For Metal (Apple Silicon) CMAKE_ARGS="-DGGML_METAL=on" pip install llama-cpp-python # For OpenBLAS (CPU optimization) CMAKE_ARGS="-DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
系统要求:
安装前置条件:
macOS:
xcode-select --install
Ubuntu/Debian:
sudo apt update sudo apt install build-essential cmake git
Windows:
git clone https://github.com/ggml-org/llama.cpp cd llama.cpp
cmake -B build
cmake --build build --config Release
为了加快编译速度,可以使用并行任务:
cmake --build build --config Release -j 8
cmake -B build -DGGML_CUDA=ON cmake --build build --config Release
cmake -B build -DGGML_METAL=ON cmake --build build --config Release
cmake -B build -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS cmake --build build --config Release
cmake -B build -DGGML_VULKAN=1 cmake --build build --config Release
cmake -B build -DCMAKE_BUILD_TYPE=Debug cmake --build build
cmake -B build \ -DGGML_CUDA=ON \ -DGGML_BLAS=ON \ -DGGML_BLAS_VENDOR=OpenBLAS \ -DBUILD_SHARED_LIBS=ON
GGUF(通用 GGML 统一格式)是一种优化的文件格式,专为使用 Llama.cpp 和其他框架高效运行大型语言模型而设计。其特点包括:
Llama.cpp 支持多种量化级别:
| 类型 | 位数 | 描述 | 使用场景 |
|---|---|---|---|
| F16 | 16 | 半精度 | 高质量,大内存 |
| Q8_0 | 8 | 8 位量化 | 良好平衡 |
| Q4_0 | 4 | 4 位量化 | 中等质量,较小体积 |
| Q2_K | 2 | 2 位量化 | 最小体积,较低质量 |
# Convert Hugging Face model python convert_hf_to_gguf.py path/to/model --outdir ./models # Quantize the model ./llama-quantize ./models/model.gguf ./models/model-q4_0.gguf q4_0
许多模型已在 Hugging Face 上以 GGUF 格式提供:
# Basic text completion ./llama-cli -m model.gguf -p "Hello, my name is" -n 50 # Interactive chat mode ./llama-cli -m model.gguf -cnv
# Download and run directly ./llama-cli -hf microsoft/DialoGPT-medium
# Start server ./llama-server -m model.gguf --host 0.0.0.0 --port 8080 # With GPU acceleration ./llama-server -m model.gguf --n-gpu-layers 32
| 参数 | 描述 | 示例 |
|---|---|---|
-m |
模型文件路径 | -m model.gguf |
-p |
提示文本 | -p "Hello world" |
-n |
生成的 token 数量 | -n 100 |
-c |
上下文大小 | -c 4096 |
-t |
线程数 | -t 8 |
-ngl |
GPU 层数 | -ngl 32 |
-temp |
温度 | -temp 0.7 |
# Start interactive session ./llama-cli -m model.gguf -cnv # Example conversation: # > Hello, how are you? # Hi there! I'm doing well, thank you for asking... # > What can you help me with? # I can assist with various tasks such as...
./llama-server -m model.gguf \ --host 0.0.0.0 \ --port 8080 \ --ctx-size 4096 \ --n-gpu-layers 32
# Chat completion curl -X POST http://localhost:8080/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "user", "content": "Hello!"} ], "temperature": 0.7, "max_tokens": 100 }' # Text completion curl -X POST http://localhost:8080/completion \ -H "Content-Type: application/json" \ -d '{ "prompt": "The capital of France is", "n_predict": 50 }'
# Set context size ./llama-cli -m model.gguf -c 2048 # Enable memory mapping ./llama-cli -m model.gguf --mlock
# Use all CPU cores ./llama-cli -m model.gguf -t $(nproc) # Specific thread count ./llama-cli -m model.gguf -t 8
# Offload layers to GPU ./llama-cli -m model.gguf -ngl 32 # Use specific GPU CUDA_VISIBLE_DEVICES=0 ./llama-cli -m model.gguf -ngl 32
from llama_cpp import Llama # Initialize model llm = Llama( model_path="./models/model.gguf", n_ctx=2048, n_threads=8, n_gpu_layers=32 ) # Generate text output = llm("Hello, my name is", max_tokens=50) print(output['choices'][0]['text'])
from llama_cpp import Llama llm = Llama(model_path="./models/chat-model.gguf") # Chat completion response = llm.create_chat_completion( messages=[ {"role": "user", "content": "Hello!"} ], temperature=0.7, max_tokens=100 ) print(response['choices'][0]['message']['content'])
# Streaming text generation stream = llm("Tell me a story", max_tokens=200, stream=True) for output in stream: print(output['choices'][0]['text'], end='', flush=True)
from langchain.llms import LlamaCpp from langchain.prompts import PromptTemplate from langchain.chains import LLMChain # Initialize LLM llm = LlamaCpp( model_path="./models/model.gguf", n_ctx=2048, n_threads=8 ) # Create prompt template template = "Question: {question}\nAnswer:" prompt = PromptTemplate(template=template, input_variables=["question"]) # Create chain chain = LLMChain(llm=llm, prompt=prompt) # Use the chain result = chain.run(question="What is artificial intelligence?") print(result)
问题:找不到 CMake
# Solution: Install CMake # Ubuntu/Debian sudo apt install cmake # macOS brew install cmake
问题:找不到编译器
# Solution: Install build tools # Ubuntu/Debian sudo apt install build-essential # macOS xcode-select --install
问题:模型加载失败
问题:性能较差
问题:内存不足
# Solutions: # 1. Use smaller quantization ./llama-cli -m model-q4_0.gguf # 2. Reduce context size ./llama-cli -m model.gguf -c 1024 # 3. Offload to GPU ./llama-cli -m model.gguf -ngl 32
Llama.cpp 提供了一种强大且高效的方式,在各种硬件配置上本地运行大型语言模型。无论您是在开发 AI 应用、进行研究,还是仅仅对 LLMs 进行实验,这个框架都能为广泛的用例提供所需的灵活性和性能。
关键要点:
欲了解更多信息和更新,请访问 Llama.cpp 官方代码库,并参考全面的文档和社区资源。
免责声明:
本文档使用AI翻译服务 Co-op Translator 进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文档作为权威来源。对于关键信息,建议使用专业人工翻译。我们对于因使用本翻译而引起的任何误解或误读不承担责任。