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

# DeepSeek-R1 推理模型

在 Clore.ai GPU 上运行 DeepSeek-R1 开源推理模型

{% hint style="success" %}
所有示例都运行在通过 [CLORE.AI 市场](https://clore.ai/marketplace)租用的 GPU 服务器上。RTX 4090 实例起价为 $0.14–0.42/小时。
{% endhint %}

## 概览

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

完整模型采用 **专家混合（MoE）** 架构，每个 token 有 370 亿个活跃参数，尽管总参数量惊人，但仍可进行推理。对于大多数从业者来说， **蒸馏版变体** （15 亿 → 700 亿）更实用：它们通过知识蒸馏将 R1 的推理模式继承到 Qwen-2.5 和 Llama-3 基础架构中，并可在普通 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 显存    | 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.07–0.21/hr)                                                                                                   |
| 单卡生产环境最佳点   | R1-Distill-Qwen-14B Q4 | [RTX 4090](https://clore.ai/rent-4090.html?utm_source=docs\&utm_medium=guide\&utm_campaign=deepseek-r1) ($0.14–0.42/hr)    |
| 性价比最高（推荐）   | 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) |

## 需求

{% hint style="warning" %}
**Clore.ai 市场上未列出多 GPU 的 80GB 级机型。** 目前列出的最大配置是 4× RTX PRO 6000 Blackwell（每张 96GB，共 380GB）以及 8–11× RTX 5090（每张 32GB）。A100 / H200 / B200 容量可按 [裸机](https://clore.ai/bare-metal) 需求提供。部署前请查看 [GPU 价格与可用性](/guides/guides_v2-zh/ru-men-zhi-nan/pricing.md) 。
{% endhint %}

| 组件     | 最低配置（7B Q4） | 推荐（32B Q4） |
| ------ | ----------- | ---------- |
| GPU 显存 | 6 GB        | 24 GB      |
| 系统内存   | 16 GB       | 32 GB      |
| 磁盘     | 10 GB       | 30 GB      |
| CUDA   | 12.8+       | 12.8+      |
| 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         |

### 性能调优

* **温度 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>` 输出

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

```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) — *通过强化学习激励大语言模型的推理能力*
* [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
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/deepseek-r1.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.
