> 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/llamacpp-server.md).

# Сервер Llama.cpp

Эффективно запускайте LLM с сервером llama.cpp на GPU.

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

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

| Параметр      | Минимум     | Рекомендуется |
| ------------- | ----------- | ------------- |
| ОЗУ           | 8 ГБ        | 16 ГБ+        |
| VRAM          | 6 ГБ        | 8 ГБ+         |
| Сеть          | 200 Мбит/с  | 500 Мбит/с+   |
| Время запуска | \~2–5 минут | -             |

{% hint style="info" %}
Llama.cpp экономно использует память благодаря квантизации GGUF. Модели 7B могут работать на 6–8 ГБ VRAM.
{% 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>`

## Что такое Llama.cpp?

Llama.cpp — самый быстрый движок инференса на CPU/GPU для LLM:

* Поддерживает квантизованные модели GGUF
* Низкое потребление памяти
* API, совместимый с OpenAI
* Поддержка многопользовательского режима

## Уровни квантизации

| Формат   | Размер (7B) | Скорость        | Качество    |
| -------- | ----------- | --------------- | ----------- |
| Q2\_K    | 2,8 ГБ      | Самый быстрый   | Низкая      |
| Q4\_K\_M | 4,1 ГБ      | Быстро          | Хорошо      |
| Q5\_K\_M | 4,8 ГБ      | Средне          | Отлично     |
| Q6\_K    | 5,5 ГБ      | Медленнее       | Отлично     |
| Q8\_0    | 7,2 ГБ      | Самый медленный | Лучше всего |

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

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

```
ghcr.io/ggerganov/llama.cpp:server-cuda
```

**Порты:**

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

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

```bash

# Скачать модель
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

# Запустить сервер
./llama-server \\
    -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \\
    --host 0.0.0.0 \
    --port 8080 \\
    -ngl 35 \\
    -c 4096
```

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

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

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

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

### Проверьте, что он работает

```bash
# Проверить состояние
curl https://your-http-pub.clorecloud.net/health

# Получить информацию о сервере
curl https://your-http-pub.clorecloud.net/props
```

{% hint style="warning" %}
Если вы получаете HTTP 502, сервис, возможно, всё ещё запускается или загружает модель. Подождите 2–5 минут и повторите попытку.
{% endhint %}

## Полный справочник API

### Стандартные конечные точки

| Конечная точка         | Метод | Описание                                 |
| ---------------------- | ----- | ---------------------------------------- |
| `/health`              | GET   | Проверка состояния                       |
| `/v1/models`           | GET   | Список моделей                           |
| `/v1/chat/completions` | POST  | Чат (совместимый с OpenAI)               |
| `/v1/completions`      | POST  | Завершение текста (совместимое с OpenAI) |
| `/v1/embeddings`       | POST  | Генерировать эмбеддинги                  |
| `/completion`          | POST  | Нативная конечная точка завершения       |
| `/tokenize`            | POST  | Токенизировать текст                     |
| `/detokenize`          | POST  | Детокенизировать токены                  |
| `/props`               | GET   | Свойства сервера                         |
| `/metrics`             | GET   | Метрики Prometheus                       |

#### Токенизация текста

```bash
curl https://your-http-pub.clorecloud.net/tokenize \\
    -H "Content-Type: application/json" \\
    -d '{"content": "Привет, мир"}'
```

Ответ:

```json
{"tokens": [15496, 1917]}
```

#### Свойства сервера

```bash
curl https://your-http-pub.clorecloud.net/props
```

Ответ:

```json
{
  "total_slots": 1,
  "chat_template": "...",
  "default_generation_settings": {...}
}
```

## Сборка из исходников

```bash

# Клонировать репозиторий
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp

# Сборка с CUDA
make LLAMA_CUDA=1

# Или с CMake
mkdir build && cd build
cmake .. -DLLAMA_CUDA=ON
cmake --build . --config Release
```

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

```bash

# Llama 3.1 8B
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

# Mistral 7B
wget https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3-Q4_K_M.gguf

# Mixtral 8x7B
wget https://huggingface.co/bartowski/Mixtral-8x7B-Instruct-v0.1-GGUF/resolve/main/Mixtral-8x7B-Instruct-v0.1-Q4_K_M.gguf

# Phi-2
wget https://huggingface.co/bartowski/Phi-4-GGUF/resolve/main/Phi-4-Q4_K_M.gguf

# CodeLlama 7B
wget https://huggingface.co/bartowski/CodeLlama-7B-Instruct-GGUF/resolve/main/CodeLlama-7B-Instruct-Q4_K_M.gguf
```

## Параметры сервера

### Базовый сервер

```bash
./llama-server \\
    -m model.gguf \\
    --host 0.0.0.0 \
    --port 8080
```

### Полная выгрузка на GPU

```bash
./llama-server \\
    -m model.gguf \\
    --host 0.0.0.0 \
    --port 8080 \\
    -ngl 99 \\           # Слои GPU (99 = все)
    -c 4096 \\           # Размер контекста
    -t 8 \\              # Потоки CPU
    --parallel 4        # Параллельные запросы
```

### Все параметры

```bash
./llama-server \\
    -m model.gguf \\           # Файл модели
    --host 0.0.0.0 \\          # Адрес привязки
    --port 8080 \\             # Порт
    -ngl 35 \\                 # Слои GPU
    -c 4096 \\                 # Размер контекста
    -t 8 \\                    # Потоки
    -b 512 \\                  # Размер пакета
    --parallel 4 \\            # Параллельные запросы
    --mlock \\                 # Блокировать память
    --no-mmap \\               # Отключить mmap
    --cont-batching \\         # Непрерывная пакетная обработка
    --flash-attn \\            # Flash Attention
    --metrics                 # Включить endpoint метрик
```

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

### Завершения чата (совместимо с OpenAI)

```python
import openai

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

response = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[
        {"role": "system", "content": "Вы — полезный помощник."},
        {"role": "user", "content": "Что такое машинное обучение?"}
    ],
    temperature=0.7,
    max_tokens=500
)

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

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

```python
stream = client.chat.completions.create(
    model="llama-3.1-8b",
    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)
```

### Завершение текста

```python
response = client.completions.create(
    model="llama-3.1-8b",
    prompt="Будущее ИИ — это",
    max_tokens=100,
    temperature=0.8
)

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

### Эмбеддинги

```python
response = client.embeddings.create(
    model="llama-3.1-8b",
    input="Привет, мир!"
)

print(f"Embedding: {response.data[0].embedding[:5]}...")
```

## Примеры cURL

### Чат

```bash
curl http://localhost:8080/v1/chat/completions \
    -H "Content-Type: application/json" \\
    -d '{
        "model": "llama-3.1-8b",
        "messages": [
            {"role": "user", "content": "Привет!"}
        ]
    }'
```

### Завершение

```bash
curl http://localhost:8080/completion \\
    -H "Content-Type: application/json" \\
    -d '{
        "prompt": "Создание веб-сайта требует",
        "n_predict": 128,
        "temperature": 0.7
    }'
```

### Проверка состояния

```bash
curl http://localhost:8080/health
```

### Метрики

```bash
curl http://localhost:8080/metrics
```

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

```bash

# Разделить по GPU
./llama-server \\
    -m model.gguf \\
    -ngl 99 \
    --tensor-split 0.5,0.5 \\  # Разделение между 2 GPU
    --main-gpu 0              # Основной GPU
```

## Оптимизация памяти

### Для ограниченного объёма VRAM

```bash

# Частичная выгрузка
./llama-server -m model.gguf -ngl 20 -c 2048

# Используйте меньшую квантизацию

# Загрузите Q2_K или Q3_K вместо Q4_K
```

### Для максимальной скорости

```bash
./llama-server \\
    -m model.gguf \\
    -ngl 99 \
    --flash-attn \\
    --cont-batching \\
    --parallel 8 \\
    -b 1024
```

## Шаблоны для конкретных моделей

### Llama 2 Chat

```bash
./llama-server -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \\
    --chat-template llama2
```

### Mistral Instruct

```bash
./llama-server -m mistral-7b-instruct.gguf \\
    --chat-template mistral
```

### ChatML (многие модели)

```bash
./llama-server -m model.gguf \\
    --chat-template chatml
```

## Python-обёртка сервера

```python
import subprocess
import requests
import time

class LlamaCppServer:
    def __init__(self, model_path, port=8080, gpu_layers=35):
        self.port = port
        self.process = subprocess.Popen([
            "./llama-server",
            "-m", model_path,
            "--host", "0.0.0.0",
            "--port", str(port),
            "-ngl", str(gpu_layers),
            "-c", "4096"
        ])
        self._wait_for_ready()

    def _wait_for_ready(self, timeout=60):
        start = time.time()
        while time.time() - start < timeout:
            try:
                r = requests.get(f"http://localhost:{self.port}/health")
                if r.status_code == 200:
                    return
            except:
                pass
            time.sleep(1)
        raise TimeoutError("Сервер не запустился")

    def chat(self, messages, **kwargs):
        response = requests.post(
            f"http://localhost:{self.port}/v1/chat/completions",
            json={"messages": messages, **kwargs}
        )
        return response.json()

    def stop(self):
        self.process.terminate()

# Использование
server = LlamaCppServer("llama-3.1-8b.gguf")
result = server.chat([{"role": "user", "content": "Привет!"}])
print(result["choices"][0]["message"]["content"])
server.stop()
```

## Бенчмаркинг

```bash

# Встроенный бенчмарк
./llama-bench -m model.gguf -ngl 99

# В вывод включены:

# - Токенов в секунду

# - Использование памяти

# - Время загрузки
```

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

| Модель       | GPU      | Квантование | Токенов/сек |
| ------------ | -------- | ----------- | ----------- |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M    | \~100       |
| Llama 3.1 8B | RTX 4090 | Q4\_K\_M    | \~150       |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M    | \~60        |
| Mistral 7B   | RTX 3090 | Q4\_K\_M    | \~110       |
| Mixtral 8x7B | A100     | Q4\_K\_M    | \~50        |

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

### CUDA не обнаружена

```bash

# Пересоберите с CUDA
make clean
make LLAMA_CUDA=1

# Проверить CUDA
nvidia-smi
```

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

```bash

# Сократите число слоев на GPU
-ngl 20  # Вместо 99

# Уменьшить контекст
-c 2048  # Вместо 4096

# Использовать меньшую квантизацию

# Q4_K_S вместо Q4_K_M
```

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

```bash

# Увеличить размер пакета
-b 1024

# Включить Flash Attention
--flash-attn

# Включить непрерывную пакетную обработку
--cont-batching
```

## Настройка для продакшена

### Сервис systemd

```ini

# /etc/systemd/system/llama.service
[Unit]
Description=Llama.cpp Server
After=network.target

[Service]
Type=simple
ExecStart=/opt/llama.cpp/llama-server -m /models/model.gguf -ngl 99 --host 0.0.0.0 --port 8080
Restart=always

[Install]
WantedBy=multi-user.target
```

### С nginx

```nginx
upstream llama {
    server localhost:8080;
}

server {
    listen 80;

    location / {
        proxy_pass http://llama;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}
```

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

Типичные цены на маркетплейсе 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 — более высокая пропускная способность
* [ExLlamaV2](/guides/guides_v2-ru/yazykovye-modeli/exllamav2-fast.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/llamacpp-server.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.
