> 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-ru/yazykovye-modeli/deepseek-coder.md).

# DeepSeek Coder

{% hint style="info" %}
**Доступны более новые версии!** [**DeepSeek-R1**](/guides/guides_v2-ru/yazykovye-modeli/deepseek-r1.md) (рассуждение + кодирование) и [**DeepSeek-V3**](/guides/guides_v2-ru/yazykovye-modeli/deepseek-v3.md) (общего назначения) значительно более способны. Также см. [**Qwen2.5-Coder**](/guides/guides_v2-ru/yazykovye-modeli/qwen25.md) как сильная альтернатива для кодирования.
{% endhint %}

Лучшее в своем классе генерация кода с моделями DeepSeek Coder.

{% hint style="success" %}
Все примеры можно запускать на GPU-серверах, арендуемых через [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Аренда на CLORE.AI

1. Посетите [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Отфильтруйте по типу GPU, объему VRAM и цене
3. Выберите **On-Demand** (фиксированная ставка) или **Spot** (цена по ставке)
4. Настройте ваш заказ:
   * Выберите Docker-образ
   * Установите порты (TCP для SSH, HTTP для веб-интерфейсов)
   * Добавьте переменные окружения при необходимости
   * Введите команду запуска
5. Выберите способ оплаты: **CLORE**, **BTC**, или **USDT/USDC**
6. Создайте заказ и дождитесь развертывания

### Доступ к вашему серверу

* Найдите данные для подключения в **Моих заказах**
* Веб-интерфейсы: используйте URL HTTP-порта
* SSH: `ssh -p <port> root@<proxy-address>`

## Что такое DeepSeek Coder?

DeepSeek Coder предлагает:

* Передовую генерацию кода
* 338 языков программирования
* Поддержка Fill-in-the-middle
* Понимание на уровне репозитория

## Варианты моделей

| Модель              | Параметры | VRAM  | Контекст |
| ------------------- | --------- | ----- | -------- |
| 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": """
Напишите класс на Python для REST API клиента с:
- Поддержкой аутентификации
- Логикой повторных попыток с экспоненциальной задержкой
- Логированием запросов/ответов
"""}
]

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))
```

## Fill-in-the-Middle (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
)

# Формат Fill-in-the-middle
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": "Implement a thread-safe LRU cache in 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": "You are an expert programmer."},
        {"role": "user", "content": "Write a FastAPI websocket server"}
    ],
    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. Лучшие практики """} ]

````

## Исправление ошибок

```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="Prompt", lines=5, placeholder="Describe the code you need..."),
        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="Generated Code"),
    title="DeepSeek Coder"
)

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

## Производительность

| Модель           | GPU      | Токенов/с |
| ---------------- | -------- | --------- |
| 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 Marketplace*](https://clore.ai/marketplace) *для текущих тарифов.*

**Экономьте деньги:**

* Используйте **Spot** рынок для гибких рабочих нагрузок (часто на 30–50% дешевле)
* Платите с помощью **CLORE** токенов
* Сравнивайте цены у разных провайдеров

## Дальнейшие шаги

* [DeepSeek-V3](/guides/guides_v2-ru/yazykovye-modeli/deepseek-v3.md) - Последняя флагманская модель DeepSeek
* [CodeLlama](/guides/guides_v2-ru/yazykovye-modeli/codellama.md) - Альтернативная модель для кода
* [Qwen2.5-Coder](/guides/guides_v2-ru/yazykovye-modeli/qwen25.md) - Кодовая модель Alibaba
* [vLLM](/guides/guides_v2-ru/yazykovye-modeli/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-ru/yazykovye-modeli/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.
