> 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/mistral-mixtral.md).

# Mistral и Mixtral

{% hint style="info" %}
**Доступны более новые версии!** Посмотрите [**Mistral Small 3.1**](/guides/guides_v2-ru/yazykovye-modeli/mistral-small.md) (24B, Apache 2.0, помещается на RTX 4090) и [**Mistral Large 3**](/guides/guides_v2-ru/yazykovye-modeli/mistral-large3.md) (675B MoE, класс передовой модели).
{% endhint %}

Запускайте модели Mistral и Mixtral для высококачественной генерации текста.

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

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

1. Перейдите на [маркетплейс CLORE.AI](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>`

## Обзор моделей

| Модель              | Параметры              | VRAM  | Специализация            |
| ------------------- | ---------------------- | ----- | ------------------------ |
| Mistral-7B          | 7B                     | 8 ГБ  | Универсальное назначение |
| Mistral-7B-Instruct | 7B                     | 8 ГБ  | Чат/инструкции           |
| Mixtral-8x7B        | 46.7B (12.9B активных) | 24 ГБ | MoE, лучшее качество     |
| Mixtral-8x22B       | 141B                   | 80GB+ | Крупнейшая MoE           |

## Быстрое развёртывание

**Docker-образ:**

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

**Порты:**

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

**Команда:**

```bash
pip install vllm && \\
python -m vllm.entrypoints.openai.api_server \\
    --model mistralai/Mistral-7B-Instruct-v0.2 \
    --port 8000
```

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

После развертывания найдите свой `http_pub` URL в **Мои заказы**:

1. Перейдите на **Мои заказы** страницу
2. Нажмите на свой заказ
3. Найдите `http_pub` URL (например, `abc123.clorecloud.net`)

Используйте `https://YOUR_HTTP_PUB_URL` вместо `localhost` в примерах ниже.

## Варианты установки

### С помощью Ollama (самый простой способ)

```bash

# Установите Ollama
curl -fsSL https://ollama.com/install.sh | sh

# Запуск Mistral
ollama run mistral

# Запуск Mixtral
ollama run mixtral
```

### С помощью vLLM

```bash
pip install vllm

# Запустить сервер
python -m vllm.entrypoints.openai.api_server \\
    --model mistralai/Mistral-7B-Instruct-v0.2 \
    --dtype float16
```

### Использование Transformers

```bash
pip install transformers accelerate
```

## Mistral-7B с Transformers

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

model_id = "mistralai/Mistral-7B-Instruct-v0.2"

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

messages = [
    {"role": "user", "content": "Объясните квантовые вычисления простыми словами"}
]

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

outputs = model.generate(
    inputs,
    max_new_tokens=500,
    do_sample=True,
    temperature=0.7,
    top_p=0.95
)

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

## Mixtral-8x7B

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

model_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"

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

messages = [
    {"role": "user", "content": "Напишите функцию на Python для вычисления чисел Фибоначчи"}
]

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

outputs = model.generate(
    inputs,
    max_new_tokens=1000,
    do_sample=True,
    temperature=0.7
)

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

## Квантованные модели (меньше VRAM)

### 4-битная квантизация

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

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_quant_type="nf4"
)

model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mixtral-8x7B-Instruct-v0.1",
    quantization_config=quantization_config,
    device_map="auto"
)
```

### GGUF с llama.cpp

```bash

# Скачать модель GGUF
wget https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3-Q4_K_M.gguf

# Запуск с llama.cpp
./main -m Mistral-7B-Instruct-v0.3-Q4_K_M.gguf \
    -p "Объясните машинное обучение" \
    -n 500
```

## Сервер vLLM (продакшен)

```bash
python -m vllm.entrypoints.openai.api_server \\
    --model mistralai/Mistral-7B-Instruct-v0.2 \
    --dtype float16 \\
    --max-model-len 8192 \
    --gpu-memory-utilization 0.9
```

### API, совместимый с OpenAI

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="not-needed"
)

response = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[
        {"role": "user", "content": "Какова столица Франции?"}
    ],
    temperature=0.7,
    max_tokens=500
)

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

## Потоковая передача

```python
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[{"role": "user", "content": "Напишите историю о роботе"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

## Вызов функций

Mistral поддерживает вызов функций:

```python
from openai import OpenAI

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

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Получить погоду для местоположения",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[{"role": "user", "content": "Какая погода в Париже?"}],
    tools=tools
)

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

## Интерфейс Gradio

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

model_id = "mistralai/Mistral-7B-Instruct-v0.2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

def chat(message, history, temperature, max_tokens):
    messages = []
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        messages.append({"role": "assistant", "content": h[1]})
    messages.append({"role": "user", "content": message})

    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
    )

    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    # Извлечь ответ ассистента
    return response.split("[/INST]")[-1].strip()

demo = gr.ChatInterface(
    fn=chat,
    additional_inputs=[
        gr.Slider(0.1, 2.0, value=0.7, label="Температура"),
        gr.Slider(100, 2000, value=500, step=100, label="Макс. токены")
    ],
    title="Чат Mistral-7B"
)

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

## Сравнение производительности

### Пропускная способность (токенов/с)

| Модель            | RTX 3060 | RTX 3090 | RTX 4090 | A100 40 ГБ |
| ----------------- | -------- | -------- | -------- | ---------- |
| Mistral-7B FP16   | 45       | 80       | 120      | 150        |
| Mistral-7B Q4     | 70       | 110      | 160      | 200        |
| Mixtral-8x7B FP16 | -        | -        | 30       | 60         |
| Mixtral-8x7B Q4   | -        | 25       | 50       | 80         |
| Mixtral-8x22B Q4  | -        | -        | -        | 25         |

### Время до первого токена (TTFT)

| Модель        | RTX 3090 | RTX 4090 | A100   |
| ------------- | -------- | -------- | ------ |
| Mistral-7B    | 80 мс    | 50 мс    | 35 мс  |
| Mixtral-8x7B  | -        | 150 мс   | 90 мс  |
| Mixtral-8x22B | -        | -        | 200 мс |

### Длина контекста vs VRAM (Mistral-7B)

| Контекст | FP16  | Q8    | Q4    |
| -------- | ----- | ----- | ----- |
| 4K       | 15 ГБ | 9 ГБ  | 5 ГБ  |
| 8K       | 18 ГБ | 11 ГБ | 7 ГБ  |
| 16K      | 24 ГБ | 15 ГБ | 9 ГБ  |
| 32K      | 36 ГБ | 22 ГБ | 14 ГБ |

## Требования к VRAM

| Модель        | FP16   | 8-bit | 4-bit |
| ------------- | ------ | ----- | ----- |
| Mistral-7B    | 14 ГБ  | 8 ГБ  | 5 ГБ  |
| Mixtral-8x7B  | 90 ГБ  | 45 ГБ | 24 ГБ |
| Mixtral-8x22B | 180 ГБ | 90 ГБ | 48 ГБ |

## Сценарии использования

### Генерация кода

```python
prompt = """
Напишите класс Python для клиента REST API со следующими возможностями:
- Обработка аутентификации
- Логика повторных попыток
- Обработка ошибок
"""
```

### Анализ данных

```python
prompt = """
Проанализируйте эти данные и предоставьте выводы:
Продажи за 1-й квартал: $100K
Продажи за 2-й квартал: $150K
Продажи за 3-й квартал: $120K
Продажи за 4-й квартал: $200K
"""
```

### Творческое письмо

```python
prompt = """
Напишите короткий рассказ об ИИ, который обретает самосознание,
в стиле Айзека Азимова.
"""
```

## Устранение неполадок

### Недостаточно памяти

* Используйте 4-битную квантизацию
* Используйте Mistral-7B вместо Mixtral
* Уменьшите max\_model\_len

### Медленная генерация

* Используйте vLLM для продакшена
* Включите flash attention
* Используйте тензорный параллелизм для нескольких GPU

### Низкое качество вывода

* Настройте temperature (0.1-0.9)
* Используйте instruct-версию
* Лучшие системные промпты

## Оценка стоимости

Типичные цены на маркетплейсе 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 40 ГБ | \~$0.17          | \~$4.00        | \~$0.70          |
| A100 80 ГБ | \~$0.25          | \~$6.00        | \~$1.00          |

*Цены зависят от провайдера и спроса. Проверьте* [*маркетплейс CLORE.AI*](https://clore.ai/marketplace) *актуальные тарифы.*

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

* Используйте **Spot** рынок для прерываемых задач — примерно треть серверов оценивает spot-цены ниже on-demand (медиана \~13% скидки), остальные совпадают с ними
* Платите **CLORE** токенами
* Сравните цены у разных провайдеров

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

* [vLLM](/guides/guides_v2-ru/yazykovye-modeli/vllm.md) - Развертывание в продакшене
* [компонент](/guides/guides_v2-ru/yazykovye-modeli/ollama.md) - Простое развертывание
* [DeepSeek-V3](/guides/guides_v2-ru/yazykovye-modeli/deepseek-v3.md) - Лучшая модель для рассуждений
* [Qwen2.5](/guides/guides_v2-ru/yazykovye-modeli/qwen25.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/mistral-mixtral.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.
