# Mistral 与 Mixtral

{% hint style="info" %}
**有更新版本可用！** 查看 [**Mistral Small 3.1**](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/mistral-small) （24B，Apache 2.0，可在 RTX 4090 上运行）和 [**Mistral Large 3**](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/mistral-large3) （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 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问您的服务器

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

## 模型概览

| A100                | 参数量             | 显存    | 专长       |
| ------------------- | --------------- | ----- | -------- |
| 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.5.1-cuda12.4-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)
print(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))
```

## 量化模型（更低显存）

### 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": ["celsius", "fahrenheit"]}
                },
                "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
print(f"已生成：{name}")
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="Max Tokens")
    ],
    title="Mistral-7B 聊天"
)

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

## 性能比较

### 吞吐量（tokens/秒）

| A100              | 按小时费率 | 速度  | 512x512 | 按日费率 |
| ----------------- | ----- | --- | ------- | ---- |
| 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   |

### 首个标记时间（TTFT）

| A100          | 速度    | 512x512 | 2s    |
| ------------- | ----- | ------- | ----- |
| Mistral-7B    | 80 毫秒 | 50 毫秒   | 35 毫秒 |
| Mixtral-8x7B  | -     | 150ms   | 90 毫秒 |
| Mixtral-8x22B | -     | -       | 200ms |

### 上下文长度 vs 显存（Mistral-7B）

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

## 显存要求

| A100          | 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 使用张量并行

### 输出质量差

* 调整温度（0.1-0.9）
* 使用 instruct 变体
* 更好的系统提示

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

* [vLLM](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/vllm) - 生产服务
* [Ollama](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/ollama) - 简易部署
* [DeepSeek-V3](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3) - 最佳推理模型
* [Qwen2.5](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/qwen25) - 多语言替代方案


---

# Agent Instructions: 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:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/mistral-mixtral.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
