> 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-mixtral.md).

# Mistral 与 Mixtral

在 Clore.ai GPU 上运行 Mistral 和 Mixtral 模型

{% hint style="info" %}
**有更新的版本可用！** 查看 [**Mistral Small 3.1**](/guides/guides_v2-zh/yu-yan-mo-xing/mistral-small.md) （24B，Apache 2.0，适用于 RTX 4090）和 [**Mistral Large 3**](/guides/guides_v2-zh/yu-yan-mo-xing/mistral-large3.md) （675B MoE，前沿级）.
{% endhint %}

运行 Mistral 和 Mixtral 模型以实现高质量文本生成。

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

## 模型概览

| 模型                  | 参数              | 显存    | 特点       |
| ------------------- | --------------- | ----- | -------- |
| Mistral-7B          | 7B              | 8GB   | 通用       |
| Mistral-7B-Instruct | 7B              | 8GB   | 聊天/指令    |
| Mixtral-8x7B        | 46.7B（12.9B 激活） | 24GB  | MoE，最佳质量 |
| Mixtral-8x22B       | 141B            | 80GB+ | 最大的 MoE  |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**端口：**

```
22/tcp
8000/http
```

**命令：**

```bash
pip install vllm && \\
python -m vllm.entrypoints.openai.api_server \
    --model mistralai/Mistral-7B-Instruct-v0.2 \\
    --port 8000
```

## 访问你的服务

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

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

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

## 安装选项

### 使用 Ollama（最简单）

```bash

# 安装 Ollama
curl -fsSL https://ollama.com/install.sh | sh

# 运行 Mistral
ollama run mistral

# 运行 Mixtral
ollama run mixtral
```

### 使用 vLLM

```bash
pip install vllm

# 启动服务器
python -m vllm.entrypoints.openai.api_server \
    --model mistralai/Mistral-7B-Instruct-v0.2 \\
    --dtype float16
```

### 使用 Transformers

```bash
pip install transformers accelerate
```

## 使用 Transformers 的 Mistral-7B

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "mistralai/Mistral-7B-Instruct-v0.2"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

messages = [
    {"role": "user", "content": "用简单的术语解释量子计算"}
]

inputs = tokenizer.apply_chat_template(
    messages,
    return_tensors="pt"
).to("cuda")

outputs = model.generate(
    inputs,
    max_new_tokens=500,
    do_sample=True,
    temperature=0.7,
    top_p=0.95
)

response = tokenizer.decode(outputs[0], skip_special_tokens=True)
打印(response)
```

## Mixtral-8x7B

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

messages = [
    {"role": "user", "content": "编写一个 Python 函数来计算斐波那契数"}
]

inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda")

outputs = model.generate(
    inputs,
    max_new_tokens=1000,
    do_sample=True,
    temperature=0.7
)

print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```

## 量化模型（更低 VRAM）

### 4位量化

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_quant_type="nf4"
)

model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mixtral-8x7B-Instruct-v0.1",
    quantization_config=quantization_config,
    device_map="auto"
)
```

### 使用 llama.cpp 的 GGUF

```bash

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

# 使用 llama.cpp 运行
./main -m Mistral-7B-Instruct-v0.3-Q4_K_M.gguf \
    -p "解释机器学习" \
    -n 500
```

## vLLM 服务器（生产环境）

```bash
python -m vllm.entrypoints.openai.api_server \
    --model mistralai/Mistral-7B-Instruct-v0.2 \\
    --dtype float16 \\
    --max-model-len 8192 \
    --gpu-memory-utilization 0.9
```

### OpenAI 兼容 API

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[
        {"role": "user", "content": "法国的首都是什么？"}
    ],
    temperature=0.7,
    max_tokens=500
)

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

## 流式输出

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="x")

stream = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    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)
```

## 函数调用

Mistral 支持函数调用：

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="x")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取某个地点的天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]}
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[{"role": "user", "content": "巴黎的天气怎么样？"}],
    tools=tools
)

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

## Gradio 界面

```python
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "mistralai/Mistral-7B-Instruct-v0.2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

def chat(message, history, temperature, max_tokens):
    messages = []
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        messages.append({"role": "assistant", "content": h[1]})
    messages.append({"role": "user", "content": message})

    inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda")

    outputs = model.generate(
        inputs,
        max_new_tokens=max_tokens,
        temperature=temperature,
        do_sample=True
    )

    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    # 提取助手回复
    return response.split("[/INST]")[-1].strip()

demo = gr.ChatInterface(
    fn=chat,
    additional_inputs=[
        gr.Slider(0.1, 2.0, value=0.7, label="温度"),
        gr.Slider(100, 2000, value=500, step=100, label="最大 Token 数")
    ],
    title="Mistral-7B 聊天"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## 性能对比

### 吞吐量（tokens/秒）

| 模型                | RTX 3060 | RTX 3090 | RTX 4090 | A100 40GB |
| ----------------- | -------- | -------- | -------- | --------- |
| Mistral-7B FP16   | 45       | 80       | 120      | 150       |
| Mistral-7B Q4     | 70       | 110      | 160      | 200       |
| Mixtral-8x7B FP16 | -        | -        | 30       | 60        |
| Mixtral-8x7B Q4   | -        | 25       | 50       | 80        |
| Mixtral-8x22B Q4  | -        | -        | -        | 25        |

### 首个 token 时间（TTFT）

| 模型            | RTX 3090 | RTX 4090 | A100  |
| ------------- | -------- | -------- | ----- |
| Mistral-7B    | 80ms     | 50ms     | 35ms  |
| Mixtral-8x7B  | -        | 150ms    | 90ms  |
| Mixtral-8x22B | -        | -        | 200ms |

### 上下文长度与 VRAM 对比（Mistral-7B）

| 上下文 | FP16 | Q8   | Q4   |
| --- | ---- | ---- | ---- |
| 4K  | 15GB | 9GB  | 5GB  |
| 8K  | 18GB | 11GB | 7GB  |
| 16K | 24GB | 15GB | 9GB  |
| 32K | 36GB | 22GB | 14GB |

## 显存要求

| 模型            | FP16  | 8 位  | 4 位  |
| ------------- | ----- | ---- | ---- |
| Mistral-7B    | 14GB  | 8GB  | 5GB  |
| Mixtral-8x7B  | 90GB  | 45GB | 24GB |
| Mixtral-8x22B | 180GB | 90GB | 48GB |

## 应用场景

### 代码生成

```python
prompt = """
编写一个具有以下功能的 REST API 客户端 Python 类：
- 身份验证处理
- 重试逻辑
- 错误处理
"""
```

### 数据分析

```python
prompt = """
分析这些数据并提供见解：
第一季度销售额：$100K
第二季度销售额：$150K
第三季度销售额：$120K
第四季度销售额：$200K
"""
```

### 创意写作

```python
prompt = """
编写一个关于某个 AI 获得自我意识的短篇故事，
以艾萨克·阿西莫夫的风格。
"""
```

## 故障排查

### 内存不足

* 使用 4 位量化
* 使用 Mistral-7B 而不是 Mixtral
* 降低 max\_model\_len

### 生成缓慢

* 在生产中使用 vLLM
* 启用 flash attention
* 使用张量并行实现多 GPU

### 输出质量差

* 调整 temperature（0.1-0.9）
* 使用指令版
* 更好的系统提示

## 成本估算

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](/guides/guides_v2-zh/yu-yan-mo-xing/vllm.md) - 生产环境服务
* [Ollama](/guides/guides_v2-zh/yu-yan-mo-xing/ollama.md) - 易于部署
* [DeepSeek-V3](/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3.md) - 最佳推理模型
* [Qwen2.5](/guides/guides_v2-zh/yu-yan-mo-xing/qwen25.md) - 多语言替代方案


---

# 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-mixtral.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.
