# DeepSeek-R1 推理模型

{% hint style="success" %}
所有示例均在通过以下方式租用的 GPU 服务器上运行： [CLORE.AI 市场](https://clore.ai/marketplace)。RTX 4090 实例起价约 \~$0.50/天。
{% endhint %}

## 概览

DeepSeek-R1 是 DeepSeek 在 2025 年 1 月发布的一个 6710 亿参数的开源权重推理模型，采用 **Apache 2.0** 许可证发布。它是第一个在数学、编码和科学基准上匹配 OpenAI o1 的开源模型——同时通过显式 `<think>` 标签暴露其完整的思维链。

完整模型使用 **专家混合（Mixture-of-Experts，MoE）** 每个标记有 370 亿个激活参数，使得尽管名义参数量庞大，推理仍可行。对于大多数实践者来说， **蒸馏变体** （1.5B → 70B）更实用：它们通过知识蒸馏将 R1 的推理模式继承到 Qwen-2.5 和 Llama-3 基础架构中，并能在普通 GPU 上运行。

## 主要特性

* **显式思维链** — 每个响应都以一个 `<think>` 块开头，模型在产生最终答案之前进行推理、回溯和自我纠正
* **通过强化学习训练** — 推理能力来自 RL 奖励信号，而不是手工编写的思维链数据
* **六种蒸馏变体** — 从完整 671B 蒸馏到 Qwen 和 Llama 架构的 1.5B、7B、8B、14B、32B、70B 参数模型
* **Apache 2.0 许可证** — 完全商业化，无版税，无使用限制
* **广泛的框架支持** — Ollama、vLLM、llama.cpp、SGLang、Transformers、TGI 均开箱即用
* **AIME 2024 Pass\@1：79.8%** — 在竞赛数学上与 OpenAI o1 并列
* **Codeforces 2029 Elo** — 在竞赛编程上超过 o1 的 1891 分

## 1024x1024

| 变体                   | 参数量          | 架构           | FP16 显存  | Q4 显存    | Q4 磁盘    |
| -------------------- | ------------ | ------------ | -------- | -------- | -------- |
| DeepSeek-R1（完整 MoE）  | 671B（37B 激活） | DeepSeek MoE | 约 1.3 TB | 约 350 GB | 约 340 GB |
| R1-Distill-Llama-70B | 70B          | Llama 3      | 140 GB   | 40 GB    | 42 GB    |
| R1-Distill-Qwen-32B  | 32B          | Qwen 2.5     | 64 GB    | 22 GB    | 20 GB    |
| R1-Distill-Qwen-14B  | 14B          | Qwen 2.5     | 28 GB    | 10 GB    | 9 GB     |
| R1-Distill-Llama-8B  | 8B           | Llama 3      | 16 GB    | 6 GB     | 5.5 GB   |
| R1-Distill-Qwen-7B   | 7B           | Qwen 2.5     | 14 GB    | 5 GB     | 4.5 GB   |
| R1-Distill-Qwen-1.5B | 1.5B         | Qwen 2.5     | 3 GB     | 2 GB     | 1.2 GB   |

### 选择变体

| 模型变体           | 推荐变体                   | Clore 上的 GPU                |
| -------------- | ---------------------- | --------------------------- |
| 快速实验、边缘测试      | R1-Distill-Qwen-1.5B   | 任意 GPU                      |
| 预算部署、快速推理      | R1-Distill-Qwen-7B     | RTX 3090（\~$0.30–1/天）       |
| 单 GPU 生产的最佳选择点 | R1-Distill-Qwen-14B Q4 | RTX 4090（\~$0.50–2/天）       |
| 性价比最高（推荐）      | R1-Distill-Qwen-32B Q4 | RTX 4090 24 GB 或 A100 40 GB |
| 最大化蒸馏质量        | R1-Distill-Llama-70B   | 2× A100 80 GB               |
| 研究、完整保真推理      | DeepSeek-R1 671B       | 8× H100 集群                  |

### HuggingFace 仓库

| 变体            | 仓库                                                                                                            |
| ------------- | ------------------------------------------------------------------------------------------------------------- |
| 完整 R1         | [deepseek-ai/DeepSeek-R1](https://huggingface.co/deepseek-ai/DeepSeek-R1)                                     |
| Llama-70B 蒸馏版 | [deepseek-ai/DeepSeek-R1-Distill-Llama-70B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-70B) |
| Qwen-32B 蒸馏版  | [deepseek-ai/DeepSeek-R1-Distill-Qwen-32B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B)   |
| Qwen-14B 蒸馏版  | [deepseek-ai/DeepSeek-R1-Distill-Qwen-14B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-14B)   |
| Llama-8B 蒸馏版  | [deepseek-ai/DeepSeek-R1-Distill-Llama-8B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B)   |
| Qwen-7B 蒸馏版   | [deepseek-ai/DeepSeek-R1-Distill-Qwen-7B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-7B)     |
| Qwen-1.5B 蒸馏版 | [deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B) |

## 要求

| 组件         | 最低（7B Q4） | 推荐（32B Q4） |
| ---------- | --------- | ---------- |
| GPU 显存     | 6 GB      | 24 GB      |
| 系统内存       | 16 GB     | 32 GB      |
| 磁盘         | 10 GB     | 30 GB      |
| CUDA       | 12.1+     | 12.4+      |
| 已预装 Docker | 24.0+     | 25.0+      |

## Ollama 快速入门

Ollama 会自动处理量化、下载和服务——这是运行 DeepSeek-R1 的最快路径。

### 安装并运行

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

# 拉取并运行（选择你的变体）：
ollama run deepseek-r1:1.5b    # 边缘 / 测试
ollama run deepseek-r1:7b      # 预算 — 适用于任何 8 GB+ GPU
ollama run deepseek-r1:14b     # RTX 4090 的最佳点
ollama run deepseek-r1:32b     # A100 / 2× RTX 4090
ollama run deepseek-r1:70b     # 2× A100 80 GB
```

### 示例交互会话

```
>>> 证明 √2 是无理数。

<think>
我将使用反证法。
假设 √2 是有理数，因此 √2 = p/q，其中 p,q 为整数且 gcd(p,q) = 1。
则 2 = p²/q²，得到 p² = 2q²。
这意味着 p² 为偶数，因此 p 必为偶数。记 p = 2k。
代入得： (2k)² = 2q² → 4k² = 2q² → q² = 2k²。
所以 q² 也是偶数，意味着 q 为偶数。
但如果 p 和 q 都为偶数，则 gcd(p,q) ≥ 2，与我们的假设矛盾。
</think>

**证明 √2 是无理数（反证法）：**

假设 √2 = p/q 且为最简分数（gcd(p,q) = 1）。平方得到 p² = 2q²。
由于 p² 为偶数，p 为偶数 — 记 p = 2k。于是 4k² = 2q²，所以 q² = 2k²，
意味着 q 也为偶数。这与 gcd(p,q) = 1 矛盾。∎
```

### 使用与 OpenAI 兼容的 API

```bash
# 启动 Ollama 作为服务器（如果尚未运行）
ollama serve &

# 通过 curl 查询
curl -s http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-r1:32b",
    "messages": [{"role": "user", "content": "将 x^4 - 1 在整数范围内完全因式分解。"}],
    "temperature": 0.6
  }' | python3 -m json.tool
```

### Python 客户端（通过 OpenAI SDK）

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

response = client.chat.completions.create(
    model="deepseek-r1:32b",
    messages=[
        {"role": "user", "content": "编写一个 Python 函数以找出最长回文子串。"}
    ],
    temperature=0.6,
    max_tokens=4096,
)
print(response.choices[0].message.content)
```

## vLLM 生产部署

vLLM 通过连续批处理、分页注意力（PagedAttention）和前缀缓存，为多用户服务提供最高吞吐量。

### 单 GPU — 7B / 14B

```bash
pip install vllm

# 任何 16 GB+ GPU 上的 7B
vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-7B \
    --host 0.0.0.0 --port 8000 \
    --max-model-len 16384

# RTX 4090（24 GB）上的 14B
vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-14B \
    --host 0.0.0.0 --port 8000 \
    --max-model-len 16384 \
    --gpu-memory-utilization 0.92
```

### 多 GPU — 32B（推荐）

```bash
vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \
    --host 0.0.0.0 --port 8000 \
    --tensor-parallel-size 2 \
    --max-model-len 32768 \
    --gpu-memory-utilization 0.90 \
    --enable-prefix-caching
```

> **提示：** 32B Q4 的 GPTQ 或 AWQ 检查点可装入单个 RTX 4090（24 GB）：
>
> ```bash
> vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \
>     --quantization awq --host 0.0.0.0 --port 8000 \
>     --max-model-len 16384
> ```

### 多 GPU — 70B

```bash
vllm serve deepseek-ai/DeepSeek-R1-Distill-Llama-70B \
    --host 0.0.0.0 --port 8000 \
    --tensor-parallel-size 4 \
    --max-model-len 32768 \
    --gpu-memory-utilization 0.90
```

### 查询 vLLM 端点

```bash
curl -s http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
    "messages": [{"role": "user", "content": "解：找出所有满足 p^2 + 2 也是素数的素数 p。"}],
    "temperature": 0.6,
    "max_tokens": 4096
  }'
```

## Transformers / Python（带有 `<think>` 标签解析）

当你需要对生成进行细粒度控制或希望将 R1 集成到 Python 流水线时，请使用 HuggingFace Transformers。

### 基本生成

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

MODEL = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"

tokenizer = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    MODEL,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True,
)

prompt = "前 100 个正整数的和是多少？"
messages = [{"role": "user", "content": prompt}]
input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)

with torch.no_grad():
    output = model.generate(
        **inputs,
        max_new_tokens=2048,
        temperature=0.6,
        do_sample=True,
    )

full_response = tokenizer.decode(output[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
print(full_response)
```

### 解析 `<think>` 标签

```python
def parse_r1_response(text: str) -> dict:
    """将 DeepSeek-R1 的响应拆分为思考部分和答案部分。"""
    think_match = re.search(r"<think>(.*?)</think>", text, re.DOTALL)
    thinking = think_match.group(1).strip() if think_match else ""
    answer = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
    return {
        "thinking": thinking,
        "answer": answer,
        "thinking_tokens": len(thinking.split()),
    }

result = parse_r1_response(full_response)
print(f"模型推理了 {result['thinking_tokens']} 个词")
print(f"答案：{result['answer']}")
```

### 使用流式（streaming）和 `<think>` 状态跟踪

```python
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
    messages=[{"role": "user", "content": "从 ax² + bx + c = 0 推导出二次公式。"}],
    stream=True,
    max_tokens=4096,
    temperature=0.6,
)

in_think = False
for chunk in stream:
    token = chunk.choices[0].delta.content or ""
    if "<think>" in token:
        in_think = True
        print("[推理] ", end="", flush=True)
        if not filename.endswith(('.jpg', '.png')):
    if "</think>" in token:
        in_think = False
        print("\n[答案] ", end="", flush=True)
        if not filename.endswith(('.jpg', '.png')):
    if not in_think:
        print(token, end="", flush=True)
print()
```

## 在 Clore.ai 上的 Docker 部署

### Ollama Docker（最简单）

**Docker 镜像：** `ollama/ollama` **端口：** `22/tcp，11434/http`

```bash
# 在 Clore 实例上
docker run -d --gpus all \
    -v ollama_data:/root/.ollama \
    -p 11434:11434 \
    --name deepseek-r1 \
    ollama/ollama

# 拉取并服务模型
docker exec deepseek-r1 ollama pull deepseek-r1:32b
```

### vLLM Docker（生产）

**Docker 镜像：** `vllm/vllm-openai:latest` **端口：** `22/tcp，8000/http`

```yaml
# docker-compose.yml
version: "3.8"
services:
  deepseek-r1:
    image: vllm/vllm-openai:latest
    ports:
      - "8000:8000"
    volumes:
      - hf_cache:/root/.cache/huggingface
    environment:
      - HUGGING_FACE_HUB_TOKEN=${HF_TOKEN:-}
    command: >
      --model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B
      --host 0.0.0.0 --port 8000
      --tensor-parallel-size 2
      --max-model-len 32768
      --gpu-memory-utilization 0.90
      --enable-prefix-caching
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 300s
volumes:
  hf_cache:
```

在 Clore.ai 上部署：

1. 打开 [clore.ai/marketplace](https://clore.ai/marketplace)
2. 按以下条件筛选 **2× GPU，总显存 48 GB+** （例如 2× RTX 4090 或 A100 80 GB）
3. 将 Docker 镜像设置为 `vllm/vllm-openai:latest`
4. 映射端口 **8000** 为 HTTP
5. 将上面 compose 文件中的命令粘贴到启动命令中
6. 在健康检查通过后通过 HTTP 端点连接

## Clore.ai 部署提示

### 选择合适的 GPU

| 预算型  | GPU             | 每日费用         | 最佳变体                              |
| ---- | --------------- | ------------ | --------------------------------- |
| 最小   | RTX 3090（24 GB） | $0.30 – 1.00 | R1-Distill-Qwen-7B 或 14B Q4       |
| 标准   | RTX 4090（24 GB） | $0.50 – 2.00 | R1-Distill-Qwen-14B FP16 或 32B Q4 |
| 生产环境 | A100 80 GB      | $3 – 8       | R1-Distill-Qwen-32B FP16          |
| 高质量  | 2× A100 80 GB   | $6 – 16      | R1-Distill-Llama-70B FP16         |

### 性能调优

* **Temperature 0.6** 是针对推理任务推荐的默认值 — DeepSeek 自己的论文使用该值
* **设置 `max_tokens` 慷慨设置** — 推理模型会生成较长的 `<think>` 块；非平凡问题建议 4096+
* **启用前缀缓存** (`--enable-prefix-caching` 在使用共享系统提示时（在 vLLM 中）
* **限制并发量** (`--max-num-seqs 16`）用于推理工作负载 — 每个请求比标准聊天使用更多计算资源
* **使用 Q4 量化** 以在单个 24 GB GPU 上以最小质量损失容纳 32B（蒸馏已压缩 R1 的知识）

### 上下文长度注意事项

推理模型比标准聊天模型消耗更多上下文，因为思维 `<think>` 块：

| 任务复杂度      | 典型思考长度          | 所需总上下文      |
| ---------- | --------------- | ----------- |
| 简单算术       | 约 100 个标记       | 约 300 个标记   |
| 代码生成       | 约 500–1000 个标记  | 约 2000 个标记  |
| 竞赛数学（AIME） | 约 2000–4000 个标记 | 约 5000 个标记  |
| 多步研究分析     | 约 4000–8000 个标记 | 约 10000 个标记 |

## # 使用固定种子以获得一致结果

### 内存不足（OOM）

```bash
# 减少上下文长度
--max-model-len 8192    # 代替 32768

# 限制并发序列数
--max-num-seqs 8

# 使用量化
--quantization awq      # 或 gptq
```

### 模型未生成任何 `<think>` 块

某些系统提示会抑制思维。避免类似“简洁”或“不要解释你的推理”的指令。使用最小的系统提示或根本不使用：

```python
# 良好 — 保留推理
messages = [{"role": "user", "content": "..."}]

# 不良 — 可能抑制思维
messages = [
    {"role": "system", "content": "请尽量简短。不要解释。"},
    {"role": "user", "content": "..."}
]
```

### 重复或循环的 `<think>` 输出

降低 temperature 以减少推理链中的随机性：

```python
temperature = 0.0   # 确定性 — 适用于数学/代码
temperature = 0.3   # 轻微变化 — 适合分析
```

### 第一个标记慢（高 TTFT）

这是预期的 — 模型在可见答案之前会生成 `<think>` 标记。对于对延迟敏感且不需要推理的应用，请改用 [DeepSeek-V3](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3) 。

### 在 Clore 实例上下载停滞

在某些提供商上 HuggingFace 下载可能很慢。将模型预缓存到持久卷：

```bash
# 下载一次到卷中
huggingface-cli download deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \
    --local-dir /data/models/deepseek-r1-32b

# 将 vLLM 指向本地路径
vllm serve /data/models/deepseek-r1-32b --host 0.0.0.0 --port 8000
```

## 延伸阅读

* [DeepSeek-R1 论文](https://arxiv.org/abs/2501.12948) — *通过强化学习激励大型语言模型的推理能力*
* [DeepSeek-R1 GitHub](https://github.com/deepseek-ai/DeepSeek-R1) — 带有模型卡的官方仓库
* [DeepSeek-V3 指南](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3) — 来自同一实验室的非推理通用模型
* [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) — 任何模型的简单本地部署
* [Open WebUI 指南](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/open-webui) — 带有原生 `<think>` 标签渲染的聊天界面
* [Qwen 2.5 指南](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/qwen25) — 大多数 R1 蒸馏所使用的基础架构


---

# 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/deepseek-r1.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.
