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

# Mistral Small 3.1

Mistral Small 3.1, выпущенная в марте 2025 года компанией Mistral AI, — это **плотная модель с 24 миллиардами параметров** которая значительно превосходит свои размеры. Благодаря окну контекста 128K, нативным возможностям работы с изображениями, лучшему в классе вызову функций и **лицензии Apache 2.0**её, пожалуй, можно назвать лучшей моделью, которую можно запустить на одной RTX 4090. Она превосходит GPT-4o Mini и Claude 3.5 Haiku по большинству бенчмарков, при этом комфортно помещается на потребительском железе в квантизированном виде.

## Ключевые особенности

* **24B плотных параметров** — без сложности MoE, простое развёртывание
* **Контекстное окно 128K** — результат RULER 128K: 81,2%, превосходит GPT-4o Mini (65,8%)
* **Нативное зрение** — анализируйте изображения, графики, документы и скриншоты
* **лицензии Apache 2.0** — полностью открыта для коммерческого и личного использования
* **Элитный вызов функций** — нативное использование инструментов с JSON-выводом, идеально для агентных рабочих процессов
* **Многоязычность** — более 25 языков, включая CJK, арабский, хинди и европейские языки

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

| Компонент | Квантизированная (Q4) | Полная точность (BF16)  |
| --------- | --------------------- | ----------------------- |
| GPU       | 1× RTX 4090 24GB      | 2× RTX 4090 или 1× H100 |
| VRAM      | \~16 ГБ               | \~55 ГБ                 |
| ОЗУ       | 32GB                  | 64GB                    |
| Диск      | 20 ГБ                 | 50 ГБ                   |
| CUDA      | 12.8+                 | 12.8+                   |

**Рекомендация Clore.ai**: RTX 4090 ($0.14–0.42/ч) для квантизированного инференса — лучшее соотношение цены и производительности

## Быстрый старт с Ollama

Самый быстрый способ запустить Mistral Small 3.1:

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

# Запустить Mistral Small 3.1 (автоматически загружает ~14 ГБ Q4-квантизацию)
ollama run mistral-small3.1

# Или укажите конкретную квантизацию
ollama run mistral-small3.1:24b-instruct-2503-q4_K_M
```

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

```bash
# Запустить сервер Ollama
ollama serve &

# Скачать модель
ollama pull mistral-small3.1

# Выполнить запрос через API
curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \\
  -d '{
    "model": "mistral-small3.1",
    "messages": [
      {"role": "system", "content": "Вы полезный помощник по программированию."},
      {"role": "user", "content": "Напиши декоратор Python для ограничения скорости запросов"}
    ],
    "temperature": 0.15
  }'
```

### Ollama с поддержкой Vision

```bash
# Отправить изображение на анализ
curl http://localhost:11434/api/chat -d '{
  "model": "mistral-small3.1",
  "messages": [{
    "role": "user",
    "content": "Что показывает это изображение?",
    "images": ["/path/to/image.jpg"]
  }]
}'
```

## Настройка vLLM (продакшн)

Для production-нагрузок с высокой пропускной способностью и одновременными запросами:

```bash
# Установить vLLM (требуется v0.8.1+)
pip install -U vllm

# Проверить, что установлен mistral_common (должно произойти автоматически)
python -c "import mistral_common; print(mistral_common.__version__)"
```

### Запуск на одной GPU (только текст)

```bash
vllm serve mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \
  --max-model-len 32768 \
  --gpu-memory-utilization 0.90
```

### Запуск с Vision (рекомендуется 2 GPU)

```bash
vllm serve mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \
  --limit-mm-per-prompt 'image=10' \\
  --tensor-parallel-size 2 \
  --max-model-len 65536
```

### Обратиться к серверу

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-3.1-24B-Instruct-2503",
    messages=[
        {"role": "system", "content": "Вы полезный помощник. Сегодня 2026-02-20."},
        {"role": "user", "content": "Напиши полный REST API на FastAPI с CRUD-операциями для блога"}
    ],
    temperature=0.15,
    max_tokens=4096
)
print(response.choices[0].message.content)
```

## HuggingFace Transformers

Для прямой интеграции и экспериментов на Python:

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

model_name = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    load_in_4bit=True  # 4-битная квантизация — помещается на GPU с 24 ГБ
)

messages = [
    {"role": "system", "content": "Вы полезный помощник по программированию."},
    {"role": "user", "content": "Реализуй бинарное дерево поиска на Python с методами insert, delete и search"}
]

input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)

output = model.generate(
    input_ids,
    max_new_tokens=2048,
    temperature=0.15,
    do_sample=True
)
print(tokenizer.decode(output[0][input_ids.shape[-1]:], skip_special_tokens=True))
```

## Пример вызова функций

Mistral Small 3.1 — одна из лучших небольших моделей для работы с инструментами:

```python
import json
from openai import OpenAI

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

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "Получить текущую цену акции по заданному тикеру",
            "parameters": {
                "type": "object",
                "required": ["ticker"],
                "properties": {
                    "ticker": {"type": "string", "description": "Тикер акции (например, AAPL)"}
                }
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate_portfolio_value",
            "description": "Рассчитать общую стоимость портфеля по заданным активам",
            "parameters": {
                "type": "object",
                "required": ["holdings"],
                "properties": {
                    "holdings": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "ticker": {"type": "string"},
                                "shares": {"type": "number"}
                            }
                        }
                    }
                }
            }
        }
    }
]

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-3.1-24B-Instruct-2503",
    messages=[{"role": "user", "content": "Какова текущая цена AAPL и MSFT?"}],
    tools=tools,
    tool_choice="auto",
    temperature=0.15
)

for tool_call in response.choices[0].message.tool_calls:
    print(f"Вызов: {tool_call.function.name}({tool_call.function.arguments})")
```

## Быстрый старт с Docker

```bash
# Развёртывание на одной GPU
docker run --gpus all -p 8000:8000 \
  -v ~/.cache/huggingface:/root/.cache/huggingface \
  vllm/vllm-openai:latest \\
  --model mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \
  --max-model-len 32768

# С поддержкой vision (2 GPU)
docker run --gpus all -p 8000:8000 \
  -v ~/.cache/huggingface:/root/.cache/huggingface \
  vllm/vllm-openai:latest \\
  --model mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \
  --limit-mm-per-prompt 'image=10' \\
  --tensor-parallel-size 2
```

## Советы для пользователей Clore.ai

* **RTX 4090 — идеальный вариант**: При $0.14–0.42/ч одна RTX 4090 запускает Mistral Small 3.1 в квантизированном виде с запасом. Лучшее соотношение цены и производительности на Clore.ai для универсальной LLM.
* **Используйте низкую температуру**: Mistral AI рекомендует `temperature=0.15` для большинства задач. Более высокие температуры вызывают нестабильный вывод у этой модели.
* **RTX 3090 тоже подходит**: При $0.07–0.21/ч RTX 3090 (24 ГБ) отлично запускает Q4-квантизированную модель с Ollama. Немного медленнее, чем 4090, но вдвое дешевле.
* **Ollama для быстрого запуска, vLLM для production**: Ollama даёт рабочую модель за 60 секунд. Для одновременных API-запросов и более высокой пропускной способности переключитесь на vLLM.
* **Вызов функций делает её особенной**: Многие модели 24B могут вести диалог — немногие надёжно вызывают инструменты. Вызов функций у Mistral Small 3.1 сопоставим с GPT-4o Mini. Создавайте агентов, бэкенды API и пайплайны автоматизации с уверенностью.

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

| Проблема                                   | Решение                                                                                                                   |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `OutOfMemoryError` на RTX 4090             | Используйте квантизированную модель через Ollama или `load_in_4bit=True` в Transformers. Полный BF16 требует около 55 ГБ. |
| Модель Ollama не найдена                   | Используйте `ollama run mistral-small3.1` (официальное название библиотеки).                                              |
| Ошибки токенизатора vLLM                   | Всегда передавайте `--tokenizer-mode mistral --config-format mistral --load-format mistral`.                              |
| Низкое качество вывода                     | Установите `temperature=0.15`. Добавьте системный prompt. Mistral Small чувствительна к температуре.                      |
| Vision не работает на 1 GPU                | Для функций vision требуется больше VRAM. Используйте `--tensor-parallel-size 2` или уменьшите `--max-model-len`.         |
| Вызовы функций возвращают пустой результат | Добавьте `--tool-call-parser mistral --enable-auto-tool-choice` в vLLM serve.                                             |

## Дополнительное чтение

* [Mistral Small 3.1 на HuggingFace](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)
* [Публикация в блоге Mistral AI](https://mistral.ai/news/mistral-small-3-1/)
* [Страница модели Ollama](https://ollama.com/library/mistral-small3.1)
* [Документация vLLM](https://docs.vllm.ai/)
* [Библиотека Mistral Common](https://github.com/mistralai/mistral-common)
* [Платформа Mistral AI](https://console.mistral.ai/)


---

# 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-small.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.
