# Mistral.rs

**用 Rust 编写的超快大型语言模型推理** — 生产就绪服务器，支持 GGUF、GGML、SafeTensors 和兼容 OpenAI 的 API。

> 🦀 **采用 Rust 构建** 以获得最大性能 | 支持 GGUF 和视觉模型 | Apache-2.0 许可证

***

## 什么是 Mistral.rs？

Mistral.rs 是一个完全用 Rust 编写的高性能大型语言模型推理引擎， **Rust**。最初专注于 Mistral 模型，现在支持现代大型语言模型的整个生态。Rust 基础提供：

* **零成本抽象** — 推理期间没有垃圾回收暂停
* **内存安全** — 没有空指针异常或内存泄漏
* **确定性性能** — 一致的延迟，没有 JVM/Python 开销
* **编译时优化** — 在构建时优化的 SIMD、多线程和 GPU 内核

### 主要功能

* **GGUF 支持** — 运行任何量化模型（Q4\_K\_M、Q8\_0 等）
* **ISQ（就地量化）** — 在加载时即时进行量化
* **PagedAttention** — 高效的 KV 缓存与连续批处理
* **视觉语言模型** — 支持 LLaVA、Phi-3 Vision、Idefics
* **推测式解码** — 使用草稿模型更快的推理
* **X-LoRA** — 可扩展的微调适配器支持
* **兼容 OpenAI 的 REST API** — 即插即用替代方案

### 支持的模型系列

| 系列              | 格式               | 引擎        |
| --------------- | ---------------- | --------- |
| Llama 2/3       | GGUF、SafeTensors | Rust CUDA |
| Mistral/Mixtral | GGUF、SafeTensors | Rust CUDA |
| Phi-2/3         | GGUF、SafeTensors | Rust CUDA |
| Gemma           | GGUF、SafeTensors | Rust CUDA |
| Qwen 2          | GGUF、SafeTensors | Rust CUDA |
| Starcoder 2     | GGUF             | Rust CUDA |
| LLaVA 1.5/1.6   | SafeTensors      | 视觉        |
| Phi-3 Vision    | SafeTensors      | 视觉        |

***

## 在 Clore.ai 上快速开始

### 步骤 1：查找 GPU 服务器

在 [clore.ai](https://clore.ai) 市场：

* **最低要求：** 8GB 显存（用于 7B Q4 模型）
* **推荐：** 较大模型需 RTX 3090/4090（24GB）
* 需要 CUDA 11.8+

### 第 2 步：部署 Mistral.rs Docker

```
Docker 镜像：ghcr.io/ericlbuehler/mistral.rs:cuda
```

**端口映射：**

| 容器端口   | 用途           |
| ------ | ------------ |
| `22`   | SSH 访问       |
| `8080` | REST API 服务器 |

**可用的镜像变体：**

```bash
# CUDA（大多数 Clore.ai 服务器）
ghcr.io/ericlbuehler/mistral.rs:cuda

# 仅 CPU
ghcr.io/ericlbuehler/mistral.rs:cpu

# Metal（Apple Silicon - 非 Clore.ai 使用）
ghcr.io/ericlbuehler/mistral.rs:metal
```

### 第 3 步：连接并验证

```bash
ssh root@<clore-node-ip> -p <ssh-port>

# 检查 mistral.rs 可执行文件
mistralrs-server --help
```

***

## 运行服务器

### 使用 GGUF 模型快速开始

```bash
# 直接从 HuggingFace 提供 GGUF 模型服务
mistralrs-server \
  --port 8080 \
  --log info \
  gguf \
  -m TheBloke/Llama-2-7B-Chat-GGUF \
  -f llama-2-7b-chat.Q4_K_M.gguf
```

### 提供 Mistral 7B（SafeTensors）

```bash
mistralrs-server \
  --port 8080 \
  plain \
  -m mistralai/Mistral-7B-Instruct-v0.3 \
  --isq Q4K
```

### 使用就地量化（ISQ）提供服务

ISQ 在加载时对模型进行量化 — 无需预先量化的模型：

```bash
# 加载 Llama 3 8B 并即时量化为 Q4K
mistralrs-server \
  --port 8080 \
  plain \
  -m meta-llama/Meta-Llama-3-8B-Instruct \
  --isq Q4K

# 可用的 ISQ 选项：
# Q4_0、Q4_1、Q5_0、Q5_1、Q8_0
# Q2K、Q3K、Q4K、Q5K、Q6K、Q8K
# HQQ4、HQQ8（半二次量化）
```

### 视觉语言模型

```bash
mistralrs-server \
  --port 8080 \
  vision-plain \
  -m llava-hf/llava-1.5-7b-hf \
  --isq Q4K
```

### 投机性解码

```bash
# 使用小型草稿模型来加速生成
mistralrs-server \
  --port 8080 \
  speculative \
  -m meta-llama/Meta-Llama-3-8B-Instruct \
  --isq Q4K \
  -d meta-llama/Meta-Llama-3-1B-Instruct \
  --draft-isq Q4K \
  -n 5  # 投机令牌数
```

{% hint style="success" %}
**推测式解码** 可以提供 **2–3 倍的加速** 适用于大多数对话工作负载，其中小型草稿模型可以准确预测下一个令牌。
{% endhint %}

***

## API 使用

### 兼容 OpenAI 的端点

| 端点                       | 方法   | 描述           |
| ------------------------ | ---- | ------------ |
| `/v1/chat/completions`   | POST | 聊天补全         |
| `/v1/completions`        | POST | 文本补全         |
| `/v1/models`             | GET  | 列出模型         |
| `/v1/images/generations` | POST | 图像生成（视觉语言模型） |
| `/v1/re_isq`             | POST | 重新对已加载模型进行量化 |
| `/health`                | GET  | 健康检查         |

### Python 示例

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://<clore-node-ip>:<api-port>/v1",
    api_key="none"  # 默认不需要认证
)

# 聊天补全
response = client.chat.completions.create(
    model="llama-3-8b",  # 模型名称可灵活替换
    messages=[
        {"role": "system", "content": "You are a helpful coding assistant."},
        {"role": "user", "content": "写一个反转链表的 Python 函数"}
    ],
    temperature=0.1,  # 低温度用于代码生成
    max_tokens=1024
)
print(response.choices[0].message.content)
```

### 流式响应

```python
with client.chat.completions.create(
    model="llama-3-8b",
    messages=[{"role": "user", "content": "给我讲一个关于机器人的故事。"}],
    stream=True,
    max_tokens=512
) as stream:
    for chunk in stream:
        delta = chunk.choices[0].delta
        if hasattr(delta, 'content') and delta.content:
            print(delta.content, end="", flush=True)
print()
```

### 视觉/图像输入

```python
BASE_URL = "http://localhost:9090"  # 或您的 CLORE.AI http_pub URL
from pathlib import Path

# 加载图像
image_data = base64.b64encode(Path("photo.jpg").read_bytes()).decode()

response = client.chat.completions.create(
    model="llava-1.5-7b",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{image_data}"
                    }
                },
                {
                    "type": "text",
                    "text": "你在这张图像中看到了什么？"
                }
            ]
        }
    ]
)
print(response.choices[0].message.content)
```

### cURL 示例

```bash
# 基本聊天
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mistral-7b",
    "messages": [{"role": "user", "content": "什么是 Rust？"}],
    "temperature": 0.7,
    "max_tokens": 256
  }'

# 列出模型
curl http://localhost:8080/v1/models

# 健康检查
curl http://localhost:8080/health
```

***

## 配置选项

### 服务器标志

```bash
mistralrs-server \
  --port 8080 \                    # API 端口（默认：1234）
  --host 0.0.0.0 \                 # 绑定地址
  --log info \                     # 日志级别：off/error/warn/info/debug/trace
  --token-source env:HF_TOKEN \    # HuggingFace 令牌来源
  --max-seqs 16 \                  # 最大并发序列数
  --no-paged-attn \                # 禁用 PagedAttention（用于调试）
  --prefix-cache-n 16 \            # 前缀缓存条目数
  plain \                          # 模型类型子命令
  -m meta-llama/Meta-Llama-3-8B-Instruct \
  --isq Q4K
```

### ISQ 量化参考

| ISQ 选项 | 位数 | 速度    | 显存（7B）  |
| ------ | -- | ----- | ------- |
| `Q2K`  | 2  | ★★☆☆☆ | \~2.5GB |
| `Q3K`  | 3  | ★★★☆☆ | \~3.5GB |
| `Q4_0` | 4  | ★★★★☆ | \~4.5GB |
| `Q4K`  | 4  | ★★★★☆ | \~4.5GB |
| `Q5K`  | 5  | ★★★★★ | \~5.5GB |
| `Q6K`  | 6  | ★★★★★ | \~6.5GB |
| `Q8_0` | 8  | ★★★★★ | ≈8GB    |
| `HQQ4` | 4  | ★★★★☆ | \~4.5GB |
| `HQQ8` | 8  | ★★★★★ | ≈8GB    |

{% hint style="info" %}
**HQQ（半二次量化）** 在相同位级别上，通常比 GGUF 的 Q4 达到更好的质量，尤其是在跟随指令的任务上。
{% endhint %}

***

## 高级功能

### X-LoRA（多个 LoRA 适配器的混合）

动态地为每个令牌运行多个微调适配器并选择：

```bash
mistralrs-server \
  --port 8080 \
  x-lora-plain \
  -m meta-llama/Meta-Llama-3-8B-Instruct \
  --isq Q4K \
  -x ./xlora-config.json
```

### 运行时重新量化

```bash
# 无需重启即可更改量化
curl http://localhost:8080/v1/re_isq \
  -H "Content-Type: application/json" \
  -d '{"isq_type": "Q8_0"}'
```

### 请求日志

```bash
# 启用请求日志到文件
mistralrs-server \
  --port 8080 \
  --log info \
  --request-logging-file ./requests.jsonl \
  plain \
  -m meta-llama/Meta-Llama-3-8B-Instruct \
  --isq Q4K
```

***

## 性能调优

### 优化吞吐量

```bash
# 增加 max-seqs 以处理并发请求
mistralrs-server \
  --port 8080 \
  --max-seqs 32 \
  plain \
  -m meta-llama/Meta-Llama-3-8B-Instruct \
  --isq Q4K
```

### 优化低延迟

```bash
# 降低 max-seqs，禁用前缀缓存共享
mistralrs-server \
  --port 8080 \
  --max-seqs 4 \
  --prefix-cache-n 0 \
  plain \
  -m meta-llama/Meta-Llama-3-8B-Instruct \
  --isq Q4K
```

### 监控性能

```bash
# 在推理期间监视 GPU 使用情况
watch -n 1 nvidia-smi

# 使用 nvtop 进行性能分析
apt-get install nvtop && nvtop
```

***

## Docker Compose

```yaml
version: '3.8'
services:
  mistral-rs:
    image: ghcr.io/ericlbuehler/mistral.rs:cuda
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
      - HF_TOKEN=${HUGGING_FACE_HUB_TOKEN}
    ports:
      - "8080:8080"
    volumes:
      - hf-cache:/root/.cache/huggingface
    command: >
      mistralrs-server
      --port 8080
      --host 0.0.0.0
      --log info
      --max-seqs 16
      --token-source env:HF_TOKEN
      plain
      -m meta-llama/Meta-Llama-3-8B-Instruct
      --isq Q4K
    restart: unless-stopped

volumes:
  hf-cache:
```

***

## 从源码构建

如果 Docker 镜像与您的 CUDA 版本不匹配：

```bash
# 安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env

# 克隆并构建
git clone https://github.com/EricLBuehler/mistral.rs.git
cd mistral.rs

# 使用 CUDA 支持进行构建
cargo build --release --features cuda

# 可执行文件位置
./target/release/mistralrs-server --help
```

{% hint style="warning" %}
**构建时间：** Rust 编译速度较慢。完整构建预计需 10–20 分钟。使用 `sccache` 以加速增量构建： `cargo install sccache && RUSTC_WRAPPER=sccache cargo build --release --features cuda`
{% endhint %}

***

## 故障排除

### 未找到 CUDA 库

```bash
# 检查 CUDA 库
ldconfig -p | grep libcuda
ls /usr/local/cuda/lib64/

# 设置库路径
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
```

### 模型下载失败

```bash
# 设置 HuggingFace 令牌
export HF_TOKEN=your_token_here

# 或使用 --token-source 标志
mistralrs-server \
  --token-source env:HF_TOKEN \
  ...

# 或先手动下载
huggingface-cli download meta-llama/Meta-Llama-3-8B-Instruct --local-dir ./llama3-8b
mistralrs-server ... plain -m ./llama3-8b --isq Q4K
```

### 端口 8080 被占用

```bash
# 查找并终止进程
fuser -k 8080/tcp

# 使用不同端口
mistralrs-server --port 9090 ...
```

### 量化期间内存不足

```bash
# ISQ 在 GPU 上进行量化 — 先减少其他 GPU 使用
# 或切换到 GGUF（预量化，加载时峰值内存更低）
mistralrs-server \
  gguf \
  -m TheBloke/Llama-2-7B-Chat-GGUF \
  -f llama-2-7b-chat.Q4_K_M.gguf
```

{% hint style="danger" %}
**ISQ 与 GGUF：** ISQ 在加载时使用 GPU 内存进行量化（会出现临时峰值）。如果显存紧张，请使用来自 TheBloke 或类似来源的预量化 GGUF 文件 — 它们在加载期间使用更低的峰值内存。
{% endhint %}

***

## Clore.ai 的 GPU 建议

Mistral.rs 是一个原生 Rust 引擎 — 它的低开销意味着相比基于 Python 的服务器，你能以更低的 GPU 成本获得更高的吞吐量。

| GPU               | 显存（VRAM） | Clore.ai 价格 | 推荐使用                   | 吞吐量（Mistral 7B Q4） |
| ----------------- | -------- | ----------- | ---------------------- | ------------------ |
| RTX 3090          | 24 GB    | \~$0.12/小时  | 最佳预算选项 — 7B Q4/Q8、视觉模型 | \~120 令牌/秒         |
| RTX 4090          | 24 GB    | \~$0.70/小时  | 高吞吐量 7B–34B，投机性解码      | \~200 令牌/秒         |
| A100 40GB         | 40 GB    | \~$1.20/小时  | 生产级 34B–70B Q4 服务      | \~160 令牌/秒         |
| 💡 本指南中的所有示例均可部署在 | 80 GB    | \~$2.00/小时  | 全精度 70B，多模型            | \~185 令牌/秒         |

**为什么 RTX 3090 在此表现出色：** Mistral.rs 的 Rust CUDA 内核避免了 Python GIL 开销和会影响 Python 服务器的垃圾回收暂停。在相同硬件上运行 Mistral 7B Q4\_K\_M 的 RTX 3090 提供了 ~~120 令牌/秒 — 在相同硬件上与 vLLM 可比，但成本只是其一小部分（~~$0.12/小时 vs 云提供商收费 $1–2/小时）。

**投机性解码：** 将大型模型（34B）与小型草稿模型（3B）配对，可在不损失质量的情况下实现 2–3× 加速。RTX 4090 非常适合这种模式。

***

## 资源

* 🐙 **GitHub：** [github.com/EricLBuehler/mistral.rs](https://github.com/EricLBuehler/mistral.rs)
* 📦 **容器镜像库：** [ghcr.io/ericlbuehler/mistral.rs](https://ghcr.io/ericlbuehler/mistral.rs)
* 📚 **文档：** [ericlbuehler.github.io/mistral.rs](https://ericlbuehler.github.io/mistral.rs/mistralrs/)
* 💬 **Discord：** [discord.gg/SZrecqK8qw](https://discord.gg/SZrecqK8qw)
* 🤗 **GGUF 模型：** [huggingface.co/TheBloke](https://huggingface.co/TheBloke)
