> 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/mistral-rs.md).

# Mistral.rs

**用 Rust 编写的极速 LLM 推理** — 具备 GGUF、GGML、SafeTensors 支持以及与 OpenAI 兼容的 API 的生产就绪服务器。

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

***

## 什么是 Mistral.rs？

Mistral.rs 是一个完全使用 **Rust**编写的高性能 LLM 推理引擎。最初专注于 Mistral 模型，如今已支持现代 LLM 的完整生态。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 VRAM（适用于 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  # 推测 token 数
```

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

***

## API 使用

### 兼容 OpenAI 的端点

| 端点                       | 方法   | 描述         |
| ------------------------ | ---- | ---------- |
| `/v1/chat/completions`   | POST | 聊天补全       |
| `/v1/completions`        | POST | 文本补全       |
| `/v1/models`             | GET  | 列出模型       |
| `/v1/images/generations` | POST | 图像生成（VLM）  |
| `/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": "你是一个乐于助人的代码助手。"},
        {"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
import base64
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 选项 | 位数 | 质量    | VRAM（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 适配器混合）

运行多个微调适配器，并按 token 动态选择：

```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 内存进行量化（会出现临时峰值）。如果你的 VRAM 紧张，可以使用来自 TheBloke 或类似来源的预量化 GGUF 文件——它们在加载期间使用的峰值内存更低。
{% endhint %}

***

## Clore.ai GPU 推荐

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

| GPU       | 显存    | Clore.ai 价格                       | 推荐用途                  | 吞吐量（Mistral 7B Q4） |
| --------- | ----- | --------------------------------- | --------------------- | ------------------ |
| RTX 3090  | 24 GB | $0.07–0.21/小时                     | 最佳预算选择——7B Q4/Q8、视觉模型 | \~120 tok/s        |
| RTX 4090  | 24 GB | $0.14–0.42/小时                     | 高吞吐量 7B–34B、推测解码      | 约200 tok/s         |
| A100 40GB | 40 GB | [裸机](https://clore.ai/bare-metal) | 生产环境 34B–70B Q4 服务    | \~160 tok/s        |
| A100 80GB | 80 GB | [裸机](https://clore.ai/bare-metal) | 全精度 70B、多模型           | \~185 tok/s        |

**为什么 RTX 3090 在这里表现出色：** Mistral.rs 的 Rust CUDA 内核避免了 Python GIL 开销和垃圾回收暂停，这些问题会拖慢 Python 服务器。在相同硬件上运行 Mistral 7B Q4\_K\_M 的 RTX 3090 可实现约 120 tok/s——与 vLLM 在同样硬件上的表现相当，而成本只是其一小部分（$0.07–0.21/小时 vs 云服务提供商收取的 $0.07–0.21/小时）。

**推测解码：** 将大型模型（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)


---

# 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/mistral-rs.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.
