> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/llamacpp-server.md).

# Llama.cpp 服务器

在 Clore.ai GPU 上使用 llama.cpp server 高效推理 LLM

在 GPU 上使用 llama.cpp 服务器高效运行 LLM。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 服务器要求

| 参数   | 最低       | 推荐       |
| ---- | -------- | -------- |
| 内存   | 8GB      | 16GB+    |
| 显存   | 6GB      | 8GB+     |
| 网络   | 200Mbps  | 500Mbps+ |
| 启动时间 | 约 2-5 分钟 | -        |

{% hint style="info" %}
由于 GGUF 量化，Llama.cpp 的内存效率很高。7B 模型可在 6-8GB VRAM 上运行。
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、VRAM 和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价）
4. 配置你的订单：
   * 选择 Docker 镜像
   * 设置端口（SSH 用 TCP，Web UI 用 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问你的服务器

* 在以下位置查找连接信息 **我的订单**
* Web 界面：使用 HTTP 端口 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 Llama.cpp？

Llama.cpp 是面向 LLM 最快的 CPU/GPU 推理引擎：

* 支持 GGUF 量化模型
* 内存占用低
* 兼容 OpenAI 的 API
* 支持多用户

## 量化级别

| 格式       | 大小（7B） | 速度 | 质量 |
| -------- | ------ | -- | -- |
| Q2\_K    | 2.8GB  | 最快 | 低  |
| Q4\_K\_M | 4.1GB  | 快  | 好  |
| Q5\_K\_M | 4.8GB  | 中等 | 很高 |
| Q6\_K    | 5.5GB  | 较慢 | 优秀 |
| Q8\_0    | 7.2GB  | 最慢 | 最佳 |

## 快速部署

**Docker 镜像：**

```
ghcr.io/ggerganov/llama.cpp:server-cuda
```

**端口：**

```
22/tcp
8080/http
```

**命令：**

```bash

# 下载模型
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

# 运行服务器
./llama-server \\
    -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \\
    --host 0.0.0.0 \\
    --port 8080 \
    -ngl 35 \\
    -c 4096
```

## 访问你的服务

部署后，找到你的 `http_pub` URL 在 **我的订单**:

1. 前往 **我的订单** 页面
2. 点击你的订单
3. 找到 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 替代 `localhost` 在下面的示例中。

### 验证是否正常工作

```bash
# 检查健康状态
curl https://your-http-pub.clorecloud.net/health

# 获取服务器信息
curl https://your-http-pub.clorecloud.net/props
```

{% hint style="warning" %}
如果你收到 HTTP 502，服务可能仍在启动或正在下载模型。等待 2-5 分钟后重试。
{% endhint %}

## 完整 API 参考

### 标准端点

| 端点                     | 方法   | 描述              |
| ---------------------- | ---- | --------------- |
| `/health`              | GET  | 健康检查            |
| `/v1/models`           | GET  | 列出模型            |
| `/v1/chat/completions` | POST | 聊天（兼容 OpenAI）   |
| `/v1/completions`      | POST | 文本补全（兼容 OpenAI） |
| `/v1/embeddings`       | POST | 生成嵌入            |
| `/completion`          | POST | 原生补全端点          |
| `/tokenize`            | POST | 对文本进行分词         |
| `/detokenize`          | POST | 将 token 反分词     |
| `/props`               | GET  | 服务器属性           |
| `/metrics`             | GET  | Prometheus 指标   |

#### 对文本进行分词

```bash
curl https://your-http-pub.clorecloud.net/tokenize \\
    -H "Content-Type: application/json" \\
    -d '{"content": "Hello world"}'
```

响应：

```json
{"tokens": [15496, 1917]}
```

#### 服务器属性

```bash
curl https://your-http-pub.clorecloud.net/props
```

响应：

```json
{
  "total_slots": 1,
  "chat_template": "...",
  "default_generation_settings": {...}
}
```

## 从源码构建

```bash

# 克隆仓库
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp

# 使用 CUDA 构建
make LLAMA_CUDA=1

# 或使用 CMake
mkdir build && cd build
cmake .. -DLLAMA_CUDA=ON
cmake --build . --config Release
```

## 下载模型

```bash

# Llama 3.1 8B
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

# Mistral 7B
wget https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3-Q4_K_M.gguf

# Mixtral 8x7B
wget https://huggingface.co/bartowski/Mixtral-8x7B-Instruct-v0.1-GGUF/resolve/main/Mixtral-8x7B-Instruct-v0.1-Q4_K_M.gguf

# Phi-2
wget https://huggingface.co/bartowski/Phi-4-GGUF/resolve/main/Phi-4-Q4_K_M.gguf

# CodeLlama 7B
wget https://huggingface.co/bartowski/CodeLlama-7B-Instruct-GGUF/resolve/main/CodeLlama-7B-Instruct-Q4_K_M.gguf
```

## 服务器选项

### 基础服务器

```bash
./llama-server \\
    -m model.gguf \\
    --host 0.0.0.0 \\
    --port 8080
```

### 完整 GPU 卸载

```bash
./llama-server \\
    -m model.gguf \\
    --host 0.0.0.0 \\
    --port 8080 \
    -ngl 99 \\           # GPU 层数（99 = 全部）
    -c 4096 \\           # 上下文大小
    -t 8 \              # CPU 线程数
    --parallel 4        # 并发请求
```

### 所有选项

```bash
./llama-server \\
    -m model.gguf \\           # 模型文件
    --host 0.0.0.0 \\          # 绑定地址
    --port 8080 \\             # 端口
    -ngl 35 \\                 # GPU 层数
    -c 4096 \\                 # 上下文大小
    -t 8 \\                    # 线程数
    -b 512 \\                  # 批大小
    --parallel 4 \\            # 并行请求
    --mlock \\                 # 锁定内存
    --no-mmap \\               # 禁用 mmap
    --cont-batching \\         # 连续批处理
    --flash-attn \\            # Flash Attention
    --metrics                 # 启用指标端点
```

## API 使用

### 聊天补全（兼容 OpenAI）

```python
import openai

client = openai.OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="not-needed"
)

response = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "什么是机器学习？"}
    ],
    temperature=0.7,
    max_tokens=500
)

print(response.choices[0].message.content)
```

### 流式输出

```python
stream = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[{"role": "user", "content": "写一个故事"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

### 文本补全

```python
response = client.completions.create(
    model="llama-3.1-8b",
    prompt="AI 的未来是",
    max_tokens=100,
    temperature=0.8
)

print(response.choices[0].text)
```

### 嵌入

```python
response = client.embeddings.create(
    model="llama-3.1-8b",
    input="Hello, world!"
)

print(f"Embedding: {response.data[0].embedding[:5]}...")
```

## cURL 示例

### 聊天

```bash
curl http://localhost:8080/v1/chat/completions \\
    -H "Content-Type: application/json" \\
    -d '{
        "model": "llama-3.1-8b",
        "messages": [
            {"role": "user", "content": "你好！"}
        ]
    }'
```

### 补全

```bash
curl http://localhost:8080/completion \\
    -H "Content-Type: application/json" \\
    -d '{
        "prompt": "构建网站需要",
        "n_predict": 128,
        "temperature": 0.7
    }'
```

### 健康检查

```bash
curl http://localhost:8080/health
```

### 指标

```bash
curl http://localhost:8080/metrics
```

## 多 GPU

```bash

# 在多个 GPU 之间切分
./llama-server \\
    -m model.gguf \\
    -ngl 99 \\
    --tensor-split 0.5,0.5 \\  # 在 2 个 GPU 之间切分
    --main-gpu 0              # 主 GPU
```

## 内存优化

### 适用于有限显存

```bash

# 部分卸载
./llama-server -m model.gguf -ngl 20 -c 2048

# 使用更小的量化

# 下载 Q2_K 或 Q3_K，而不是 Q4_K
```

### 为了获得最高速度

```bash
./llama-server \\
    -m model.gguf \\
    -ngl 99 \\
    --flash-attn \\
    --cont-batching \\
    --parallel 8 \\
    -b 1024
```

## 模型特定模板

### Llama 2 聊天

```bash
./llama-server -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \\
    --chat-template llama2
```

### Mistral 指令

```bash
./llama-server -m mistral-7b-instruct.gguf \\
    --chat-template mistral
```

### ChatML（许多模型）

```bash
./llama-server -m model.gguf \\
    --chat-template chatml
```

## Python 服务器封装

```python
import subprocess
import requests
import time

class LlamaCppServer:
    def __init__(self, model_path, port=8080, gpu_layers=35):
        self.port = port
        self.process = subprocess.Popen([
            "./llama-server",
            "-m", model_path,
            "--host", "0.0.0.0",
            "--port", str(port),
            "-ngl", str(gpu_layers),
            "-c", "4096"
        ])
        self._wait_for_ready()

    def _wait_for_ready(self, timeout=60):
        start = time.time()
        while time.time() - start < timeout:
            try:
                r = requests.get(f"http://localhost:{self.port}/health")
                if r.status_code == 200:
                    return
            except:
                pass
            time.sleep(1)
        raise TimeoutError("Server didn't start")

    def chat(self, messages, **kwargs):
        response = requests.post(
            f"http://localhost:{self.port}/v1/chat/completions",
            json={"messages": messages, **kwargs}
        )
        return response.json()

    def stop(self):
        self.process.terminate()

# 用法
server = LlamaCppServer("llama-3.1-8b.gguf")
result = server.chat([{"role": "user", "content": "你好！"}])
print(result["choices"][0]["message"]["content"] )
server.stop()
```

## 基准测试

```bash

# 内置基准测试
./llama-bench -m model.gguf -ngl 99

# 输出包括：

# - 每秒 token 数

# - 内存使用量

# - 加载时间
```

## 性能对比

| 模型           | GPU      | 量化       | 每秒 Token 数 |
| ------------ | -------- | -------- | ---------- |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M | \~100      |
| Llama 3.1 8B | RTX 4090 | Q4\_K\_M | \~150      |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M | \~60       |
| Mistral 7B   | RTX 3090 | Q4\_K\_M | \~110      |
| Mixtral 8x7B | A100     | Q4\_K\_M | \~50       |

## 故障排查

### 未检测到 CUDA

```bash

# 重新使用 CUDA 构建
make clean
make LLAMA_CUDA=1

# 检查 CUDA
nvidia-smi
```

### 内存不足

```bash

# 减少 GPU 层数
-ngl 20  # 而不是 99

# 减少上下文
-c 2048  # 而不是 4096

# 使用更小的量化

# 使用 Q4_K_S 而不是 Q4_K_M
```

### 生成缓慢

```bash

# 增大批大小
-b 1024

# 启用 flash attention
--flash-attn

# 启用连续批处理
--cont-batching
```

## 生产环境配置

### Systemd 服务

```ini

# /etc/systemd/system/llama.service
[Unit]
Description=Llama.cpp Server
After=network.target

[Service]
Type=simple
ExecStart=/opt/llama.cpp/llama-server -m /models/model.gguf -ngl 99 --host 0.0.0.0 --port 8080
Restart=always

[Install]
WantedBy=multi-user.target
```

### 配合 nginx

```nginx
upstream llama {
    server localhost:8080;
}

server {
    listen 80;

    location / {
        proxy_pass http://llama;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}
```

## 成本估算

CLORE.AI 市场常见费率（截至 2024 年）：

| GPU       | 小时费率    | 日费率     | 4 小时会话  |
| --------- | ------- | ------- | ------- |
| RTX 3060  | \~$0.03 | \~$0.70 | \~$0.12 |
| RTX 3090  | \~$0.06 | \~$1.50 | \~$0.25 |
| RTX 4090  | \~$0.10 | \~$2.30 | \~$0.40 |
| A100 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

*价格因提供商和需求而异。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 下一步

* vLLM 推理 - 更高吞吐量
* [ExLlamaV2](/guides/guides_v2-zh/yu-yan-mo-xing/exllamav2-fast.md) - 更快的推理
* [Text Generation WebUI](/guides/guides_v2-zh/yu-yan-mo-xing/text-generation-webui.md) - Web 界面


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/llamacpp-server.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
