> 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/exllamav2-fast.md).

# ExLlamaV2

Запускайте LLM на максимальной скорости с ExLlamaV2.

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

## Что такое ExLlamaV2?

ExLlamaV2 — самый быстрый движок инференса для больших языковых моделей:

* В 2–3 раза быстрее, чем другие движки
* Отличная квантизация (EXL2)
* Низкое использование VRAM
* Поддерживает speculative decoding

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

| Размер модели | Мин. VRAM | Рекомендуется |
| ------------- | --------- | ------------- |
| 7B            | 6 ГБ      | RTX 3060      |
| 13B           | 10 ГБ     | RTX 3090      |
| 34B           | 20 ГБ     | RTX 4090      |
| 70B           | 40 ГБ     | A100          |

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

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

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

**Порты:**

```
22/tcp
8080/http
```

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

```bash
pip install exllamav2 && \
huggingface-cli download turboderp/Llama2-7B-exl2 --local-dir ./model && \
python -m exllamav2.server --model_dir ./model --host 0.0.0.0 --port 8080
```

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

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

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

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

## Установка

```bash

# Установка из PyPI
pip install exllamav2

# Или из исходников (последние возможности)
git clone https://github.com/turboderp/exllamav2
cd exllamav2
pip install .
```

## Скачать модели

### Квантизованные модели EXL2

```bash

# Llama 3.1 8B (4.0 bpw)
huggingface-cli download turboderp/Llama2-7B-exl2 \
    --revision 4.0bpw \
    --local-dir ./llama2-7b-exl2

# Llama 3.1 8B (4.0 bpw)
huggingface-cli download turboderp/Llama2-13B-exl2 \
    --revision 4.0bpw \
    --local-dir ./llama2-13b-exl2

# Mistral 7B (4.0 bpw)
huggingface-cli download turboderp/Mistral-7B-instruct-exl2 \
    --revision 4.0bpw \
    --local-dir ./mistral-7b-exl2

# Mixtral 8x7B
huggingface-cli download turboderp/Mixtral-8x7B-instruct-exl2 \
    --revision 4.0bpw \
    --local-dir ./mixtral-exl2
```

### Биты на вес (bpw)

| BPW | Качество   | VRAM (7B) |
| --- | ---------- | --------- |
| 2.0 | Низкая     | \~3 ГБ    |
| 3.0 | Хорошо     | \~4 ГБ    |
| 4.0 | Отлично    | \~5 ГБ    |
| 5.0 | Отлично    | \~6 ГБ    |
| 6.0 | Почти FP16 | \~7 ГБ    |

## Python API

### Базовая генерация

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config, ExLlamaV2Cache, ExLlamaV2Tokenizer
from exllamav2.generator import ExLlamaV2StreamingGenerator, ExLlamaV2Sampler

# Загрузить модель
config = ExLlamaV2Config()
config.model_dir = "./llama2-7b-exl2"
config.prepare()

model = ExLlamaV2(config)
model.load()

tokenizer = ExLlamaV2Tokenizer(config)
cache = ExLlamaV2Cache(model, lazy=True)

# Создаём генератор
generator = ExLlamaV2StreamingGenerator(model, cache, tokenizer)

# Задаём параметры сэмплирования
settings = ExLlamaV2Sampler.Settings()
settings.temperature = 0.7
settings.top_k = 50
settings.top_p = 0.9

# Генерировать
prompt = "Будущее искусственного интеллекта — это"
output = generator.generate_simple(prompt, settings, num_tokens=200)
print(output)
```

### Стриминговая генерация

```python
from exllamav2.generator import ExLlamaV2StreamingGenerator

generator = ExLlamaV2StreamingGenerator(model, cache, tokenizer)

prompt = "Напиши короткий рассказ о роботе:"
input_ids = tokenizer.encode(prompt)

generator.set_stop_conditions([tokenizer.eos_token_id])
generator.begin_stream(input_ids, settings)

while True:
    chunk, eos, _ = generator.stream()
    if eos:
        break
    print(chunk, end="", flush=True)
```

### Формат чата

```python
def format_chat(messages):
    text = ""
    for msg in messages:
        role = msg["role"]
        content = msg["content"]
        if role == "system":
            text += f"[INST] <<SYS>>\n{content}\n<</SYS>>\n\n"
        elif role == "user":
            text += f"{content} [/INST]"
        elif role == "assistant":
            text += f" {content}</s><s>[INST] "
    return text

messages = [
    {"role": "system", "content": "Вы — полезный помощник."},
    {"role": "user", "content": "Что такое Python?"}
]

prompt = format_chat(messages)
output = generator.generate_simple(prompt, settings, num_tokens=300)
```

## Режим сервера

### Запустить сервер

```bash
python -m exllamav2.server \
    --model_dir ./llama2-7b-exl2 \
    --host 0.0.0.0 \
    --port 8080 \\
    --max_seq_len 4096 \
    --cache_size 4096
```

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

```python
import requests

response = requests.post(
    "http://localhost:8080/v1/completions",
    json={
        "prompt": "Привет, как дела?",
        "max_tokens": 100,
        "temperature": 0.7
    }
)

print(response.json()["choices"][0]["text"] )
```

### Chat Completions

```python
import openai

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

response = client.chat.completions.create(
    model="llama2-7b",
    messages=[{"role": "user", "content": "Привет!"}],
    temperature=0.7
)

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

## TabbyAPI (рекомендуемый сервер)

TabbyAPI предоставляет богатый возможностями сервер ExLlamaV2:

```bash

# Клонировать TabbyAPI
git clone https://github.com/theroyallab/tabbyAPI
cd tabbyAPI

# Установка
pip install -r requirements.txt

# Настройка

# Отредактируйте config.yml, указав путь к вашей модели

# Запуск
python main.py
```

### Возможности TabbyAPI

* API, совместимый с OpenAI
* Поддержка нескольких моделей
* Горячая замена LoRA
* Потоковая передача
* Вызов функций
* API администратора

## Спекулятивное декодирование

Используйте меньшую модель, чтобы ускорить генерацию:

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config, ExLlamaV2Cache

# Загрузить основную модель (13B)
main_config = ExLlamaV2Config()
main_config.model_dir = "./llama2-13b-exl2"
main_config.prepare()
main_model = ExLlamaV2(main_config)
main_model.load()

# Загрузить черновую модель (7B)
draft_config = ExLlamaV2Config()
draft_config.model_dir = "./llama2-7b-exl2"
draft_config.prepare()
draft_model = ExLlamaV2(draft_config)
draft_model.load()

# Создать speculative-генератор
from exllamav2.generator import ExLlamaV2DraftGenerator

generator = ExLlamaV2DraftGenerator(
    main_model, draft_model,
    cache_main, cache_draft,
    tokenizer
)

# Генерировать (быстрее с speculation)
output = generator.generate_simple(prompt, settings, num_tokens=500)
```

## Квантифицируйте собственные модели

### Преобразовать в EXL2

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config
from exllamav2.conversion import convert_model

# Источник: модель HuggingFace

# Цель: квантизованная EXL2

convert_model(
    input_dir="./llama-3.1-8b-hf",
    output_dir="./llama-3.1-8b-exl2-4bpw",
    cal_dataset="wikitext",  # Калибровочный набор данных
    bits=4.0,  # Биты на вес
    head_bits=6,  # Более высокая точность для внимания
)
```

### Командная строка

```bash
python convert.py \
    -i ./llama-3.1-8b-hf \
    -o ./llama-3.1-8b-exl2 \
    -cf ./llama-3.1-8b-exl2 \
    -b 4.0 \
    -hb 6
```

## Управление памятью

### Выделение кэша

```python

# Фиксированный размер кэша
cache = ExLlamaV2Cache(model, max_seq_len=4096)

# Динамический кэш
cache = ExLlamaV2Cache(model, lazy=True)
cache.current_seq_len = 0  # Растёт по мере необходимости
```

### Несколько GPU

```python
config = ExLlamaV2Config()
config.model_dir = "./large-model"

# Разделить по GPU
config.set_auto_split([0.5, 0.5])  # По 50% на каждый GPU

model = ExLlamaV2(config)
model.load()
```

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

| Модель       | Движок    | GPU      | Токенов/сек |
| ------------ | --------- | -------- | ----------- |
| Llama 3.1 8B | ExLlamaV2 | RTX 3090 | \~150       |
| Llama 3.1 8B | llama.cpp | RTX 3090 | \~100       |
| Llama 3.1 8B | vLLM      | RTX 3090 | \~120       |
| Llama 3.1 8B | ExLlamaV2 | RTX 3090 | \~90        |
| Mixtral 8x7B | ExLlamaV2 | A100     | \~70        |

## Расширенные настройки

### Параметры сэмплирования

```python
settings = ExLlamaV2Sampler.Settings()
settings.temperature = 0.7
settings.top_k = 50
settings.top_p = 0.9
settings.token_repetition_penalty = 1.1
settings.token_frequency_penalty = 0.0
settings.token_presence_penalty = 0.0
settings.mirostat = False
settings.mirostat_tau = 5.0
settings.mirostat_eta = 0.1
```

### Пакетная генерация

```python
prompts = [
    "Смысл жизни — это",
    "Искусственный интеллект будет",
    "Изменение климата — это"
]

outputs = []
for prompt in prompts:
    output = generator.generate_simple(prompt, settings, num_tokens=100)
    outputs.append(output)
```

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

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

```python

# Использовать меньший кэш
cache = ExLlamaV2Cache(model, max_seq_len=2048)

# Или модель с меньшим bpw (3.0 вместо 4.0)
```

### Медленная загрузка

```python

# Включить быструю загрузку
config.fasttensors = True
```

### Модель не найдена

```bash

# Проверьте, что файлы модели существуют
ls ./model/

# Должны быть: config.json, *.safetensors, tokenizer.json
```

## Интеграция с LangChain

```python
from langchain.llms.base import LLM
from typing import Optional, List

class ExLlamaV2LLM(LLM):
    model: ExLlamaV2
    tokenizer: ExLlamaV2Tokenizer
    generator: ExLlamaV2StreamingGenerator
    settings: ExLlamaV2Sampler.Settings

    @property
    def _llm_type(self) -> str:
        return "exllamav2"

    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        return self.generator.generate_simple(prompt, self.settings, num_tokens=500)

# Использование
llm = ExLlamaV2LLM(model=model, tokenizer=tokenizer, generator=generator, settings=settings)
result = llm("Что такое квантовые вычисления?")
```

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

Типичные цены на маркетплейсе 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 — обслуживание с высокой пропускной способностью
* [Сервер llama.cpp](/guides/guides_v2-ru/yazykovye-modeli/llamacpp-server.md) - Кроссплатформенность
* [Text Generation WebUI](/guides/guides_v2-ru/yazykovye-modeli/text-generation-webui.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/exllamav2-fast.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.
