# DeepSeek-R1 推理模型

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

## 概览

DeepSeek-R1 是一个 671B 参数的开权重推理模型，于 2025 年 1 月由 DeepSeek 发布，采用以下许可： **Apache 2.0** 。它是首个在数学、编程和科学基准上与 OpenAI o1 持平的开源模型——同时通过显式的 `<think>` 标签暴露其完整的思维链。

完整模型使用 **混合专家（MoE）** 架构，每个 token 仅激活 37B 参数，这使得尽管参数总数惊人，推理仍然可行。对大多数实践者来说， **蒸馏版本** （1.5B → 70B）更实用：它们通过将知识蒸馏到 Qwen-2.5 和 Llama-3 基础架构中，继承了 R1 的推理模式，并可在普通 GPU 上运行。

## 主要特性

* **显式思维链** — 每个回复都以一个 `<think>` 块开头，模型会在其中进行推理、回溯并自我纠正，然后再给出最终答案
* **通过强化学习训练** — 推理能力源自 RL 奖励信号，而不是人工编写的思维链数据
* **六个蒸馏版本** — 从完整 671B 模型蒸馏而来的 1.5B、7B、8B、14B、32B、70B 参数模型，基于 Qwen 和 Llama 架构
* **Apache 2.0 许可** — 可完全商用，无版税，无使用限制
* **广泛框架支持** — Ollama、vLLM、llama.cpp、SGLang、Transformers、TGI 开箱即用
* **AIME 2024 Pass\@1：79.8%** — 在竞赛数学上与 OpenAI o1 持平
* **Codeforces 2029 Elo** — 超过 o1 的 1891，适用于算法竞赛编程

## 模型变体

| 变体                   | 参数量          | 架构           | FP16 显存  | Q4 VRAM  | 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](https://clore.ai/rent-4090.html?utm_source=docs\&utm_medium=guide\&utm_campaign=deepseek-r1) （约每天 0.50–2 美元）    |
| 性价比最高（推荐）      | R1-Distill-Qwen-32B Q4 | [RTX 4090 24 GB](https://clore.ai/rent-4090.html?utm_source=docs\&utm_medium=guide\&utm_campaign=deepseek-r1) 或 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

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

# 14B 适用于 RTX 4090（24 GB）
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']}")
```

### 流式输出与 `<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)
        continue
    if "</think>" in token:
        in_think = False
        print("\n[答案] ", end="", flush=True)
        continue
    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 tokens       | 约 300 tokens   |
| 代码生成       | 约 500–1000 tokens  | 约 2000 tokens  |
| 竞赛数学（AIME） | 约 2000–4000 tokens | 约 5000 tokens  |
| 多步骤研究分析    | 约 4000–8000 tokens | 约 10000 tokens |

## 故障排查

### 内存不足（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   # 略有变化——适合分析
```

### 首个 token 很慢（TTFT 高）

这是正常的——模型会先生成 `<think>` tokens，然后才显示答案。对于不需要推理、且对延迟敏感的应用，请使用 [DeepSeek-V3](/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3.md) 替代。

### 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) — *通过强化学习激励 LLM 的推理能力*
* [DeepSeek-R1 GitHub](https://github.com/deepseek-ai/DeepSeek-R1) — 含模型卡的官方仓库
* [DeepSeek-V3 指南](/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3.md) — 同一实验室的非推理通用模型
* [vLLM 指南](/guides/guides_v2-zh/yu-yan-mo-xing/vllm.md) — 完整的生产服务部署方案
* [Ollama 指南](/guides/guides_v2-zh/yu-yan-mo-xing/ollama.md) — 适用于任何模型的简单本地部署
* [Open WebUI 指南](/guides/guides_v2-zh/yu-yan-mo-xing/open-webui.md) — 支持原生 `<think>` 标签渲染的聊天界面
* [Qwen 2.5 指南](/guides/guides_v2-zh/yu-yan-mo-xing/qwen25.md) — 大多数 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.
