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

# DeepSeek Coder

在 Clore.ai 上使用 DeepSeek Coder 实现一流代码生成

{% hint style="info" %}
**有更新的版本可用！** [**DeepSeek-R1**](/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-r1.md) （推理 + 编码）以及 [**DeepSeek-V3**](/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3.md) （通用）能力要强大得多。另见 [**Qwen2.5-Coder**](/guides/guides_v2-zh/yu-yan-mo-xing/qwen25.md) 以获得强大的编码替代方案。
{% endhint %}

使用 DeepSeek Coder 模型实现业界顶尖的代码生成。

{% 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>`

## 什么是 DeepSeek Coder？

DeepSeek Coder 提供：

* 最先进的代码生成
* 338 种编程语言
* 支持中间填充
* 仓库级理解

## 模型变体

| 模型                  | 参数       | 显存    | 上下文  |
| ------------------- | -------- | ----- | ---- |
| DeepSeek-Coder-1.3B | 1.3B     | 3GB   | 16K  |
| DeepSeek-Coder-6.7B | 6.7B     | 8GB   | 16K  |
| DeepSeek-Coder-33B  | 33B      | 40GB  | 16K  |
| DeepSeek-Coder-V2   | 16B/236B | 20GB+ | 128K |

## 快速部署

**Docker 镜像：**

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

**端口：**

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

**命令：**

```bash
pip install vllm && \\
vllm serve deepseek-ai/deepseek-coder-6.7b-instruct --port 8000
```

## 访问你的服务

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

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

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

## 使用 Ollama

```bash

# 运行 DeepSeek Coder
ollama run deepseek-coder

# 特定尺寸
ollama run deepseek-coder:1.3b
ollama run deepseek-coder:6.7b
ollama run deepseek-coder:33b

# V2（最新）
ollama run deepseek-coder-v2
```

## 安装

```bash
pip install transformers accelerate torch
```

## 代码生成

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

model_id = "deepseek-ai/deepseek-coder-6.7b-instruct"

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

messages = [
    {"role": "user", "content": """
编写一个具有以下功能的 REST API 客户端 Python 类：
- 支持身份验证
- 带指数退避的重试逻辑
- 请求/响应日志记录
"""}
]

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

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

print(tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True))
```

## 中间填充（FIM）

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

model_id = "deepseek-ai/deepseek-coder-6.7b-base"

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

# 中间填充格式
prefix = """def calculate_statistics(data):
    \"\"\"计算列表的平均值、中位数和标准差。\"\"\"
    import statistics

    mean = statistics.mean(data)
"""

suffix = """
    return {
        'mean': mean,
        'median': median,
        'std': std
    }
"""

# FIM 标记
prompt = f"<｜fim▁begin｜>{prefix}<｜fim▁hole｜>{suffix}<｜fim▁end｜>"

inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens=128)

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

## DeepSeek-Coder-V2

最新且最强大：

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

model_id = "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct"

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

messages = [
    {"role": "user", "content": "用 Python 实现一个线程安全的 LRU 缓存"}
]

inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda")
outputs = model.generate(inputs, max_new_tokens=1024, temperature=0.2)
print(tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True))
```

## vLLM 服务器

```bash
vllm serve deepseek-ai/deepseek-coder-6.7b-instruct \\
    --port 8000 \\
    --dtype bfloat16 \\
    --max-model-len 16384 \\
    --trust-remote-code
```

### API 使用

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="deepseek-ai/deepseek-coder-6.7b-instruct",
    messages=[
        {"role": "system", "content": "你是一名专家程序员。"},
        {"role": "user", "content": "编写一个 FastAPI websocket 服务器"}
    ],
    temperature=0.2,
    max_tokens=1500
)

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

## 代码审查

````python
code_to_review = """
def process_data(data):
    result = []
    for i in range(len(data)):
        if data[i] > 0:
            result.append(data[i] * 2)
    return result
"""

messages = [
    {"role": "user", "content": f"""
审查这段代码并提出改进建议：

```python
{code_to_review}
````

重点关注：

1. 性能
2. 可读性
3. 最佳实践 """} ]

````

## Bug 修复

```python
buggy_code = """
def merge_sorted_lists(list1, list2):
    result = []
    i = j = 0
    while i < len(list1) and j < len(list2):
        if list1[i] < list2[j]:
            result.append(list1[i])
            i += 1
        else:
            result.append(list2[j])
    return result
"""

messages = [
    {"role": "user", "content": f"""
找出并修复这段代码中的错误：

```python
{buggy_code}
````

"""} ]

````

## Gradio 界面

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

model_id = "deepseek-ai/deepseek-coder-6.7b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True
)

def generate_code(prompt, temperature, max_tokens):
    messages = [{"role": "user", "content": prompt}]
    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)
    return tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)

demo = gr.Interface(
    fn=generate_code,
    inputs=[
        gr.Textbox(label="提示", lines=5, placeholder="描述您需要的代码..."),
        gr.Slider(0.1, 1.0, value=0.2, label="温度"),
        gr.Slider(256, 2048, value=1024, step=128, label="最大令牌数")
    ],
    outputs=gr.Code(language="python", label="生成的代码"),
    title="DeepSeek Coder"
)

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

## 性能

| 模型               | GPU      | 每秒 Token 数 |
| ---------------- | -------- | ---------- |
| DeepSeek-1.3B    | RTX 3060 | \~120      |
| DeepSeek-6.7B    | RTX 3090 | \~70       |
| DeepSeek-6.7B    | RTX 4090 | \~100      |
| DeepSeek-33B     | A100     | \~40       |
| DeepSeek-V2-Lite | RTX 4090 | \~50       |

## 对比

| 模型                 | HumanEval | 代码质量 |
| ------------------ | --------- | ---- |
| DeepSeek-Coder-33B | 79.3%     | 优秀   |
| CodeLlama-34B      | 53.7%     | 好    |
| GPT-3.5-Turbo      | 72.6%     | 好    |

## 故障排查

### 代码补全无法工作

* 确保使用正确的提示格式，包含 `<|fim_prefix|>`, `<|fim_suffix|>`, `<|fim_middle|>`
* 设置合适的 `max_new_tokens` 用于代码生成

### 模型输出乱码

* 检查模型是否已完整下载
* 确认正在使用 CUDA： `model.device`
* 尝试降低温度（代码建议使用 0.2-0.5）

### 推理缓慢

* 使用 vLLM 可获得 5-10 倍加速
* 启用 `torch.compile()` 适用于 transformers
* 大型变体请使用量化模型

### 导入错误

* 安装依赖： `pip install transformers accelerate`
* 将 PyTorch 更新到 2.0+

## 成本估算

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** 代币支付
* 比较不同提供商的价格

## 下一步

* [DeepSeek-V3](/guides/guides_v2-zh/yu-yan-mo-xing/deepseek-v3.md) - 最新的 DeepSeek 旗舰模型
* [CodeLlama](/guides/guides_v2-zh/yu-yan-mo-xing/codellama.md) - 替代代码模型
* [Qwen2.5-Coder](/guides/guides_v2-zh/yu-yan-mo-xing/qwen25.md) - 阿里巴巴的代码模型
* [vLLM](/guides/guides_v2-zh/yu-yan-mo-xing/vllm.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/deepseek-coder.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.
