# 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 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问您的服务器

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

## 什么是 DeepSeek Coder？

DeepSeek Coder 提供：

* 最先进的代码生成
* 338 种编程语言
* 填空中间（Fill-in-the-middle）支持
* 仓库级理解

## 1024x1024

| A100                | 参数量      | 显存    | 上下文  |
| ------------------- | -------- | ----- | ---- |
| 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.5.1-cuda12.4-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": "实现一个线程安全的 LRU 缓存（Python）"}
]

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)
    num_inference_steps=steps,
"""

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

```python
{code_to_review}
````

重点关注：

1. background = Image.open("studio\_bg.jpg")
2. 可读性
3. 最佳实践 """} ]

````

## 错误修复

```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])
    num_inference_steps=steps,
"""

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

```python
{buggy_code}
````

"""} ]

````

## Gradio 界面

```python
print(f"已生成：{name}")
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="提示（Prompt）", lines=5, placeholder="描述您需要的代码..."),
        gr.Slider(0.1, 1.0, value=0.2, label="Temperature"),
        gr.Slider(256, 2048, value=1024, step=128, label="最大令牌数（Max Tokens）")
    ],
    outputs=gr.Code(language="python", label="生成的代码"),
    title="DeepSeek Coder"
)

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

## background = Image.open("studio\_bg.jpg")

| A100             | GPU     | 每秒标记数 |
| ---------------- | ------- | ----- |
| DeepSeek-1.3B    | 按小时费率   | \~120 |
| DeepSeek-6.7B    | 速度      | \~70  |
| DeepSeek-6.7B    | 512x512 | \~100 |
| DeepSeek-33B     | 2s      | \~40  |
| DeepSeek-V2-Lite | 512x512 | \~50  |

## 比较

| A100               | 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+

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

检查文件完整性

| 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%）

## 使用以下方式支付

* [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: 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-coder.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.
