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

# Gemma 2

{% hint style="info" %}
**Доступна более новая версия!** Google выпустила [**Gemma 3**](/guides/guides_v2-ru/yazykovye-modeli/gemma3.md) в марте 2025 года — модель 27B превосходит Llama 3.1 405B и добавляет нативную мультимодальную поддержку. Рассмотрите возможность обновления.
{% endhint %}

Запускайте модели Google Gemma 2 для эффективного инференса.

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

## Что такое Gemma 2?

Gemma 2 от Google предлагает:

* Модели от 2B до 27B параметров
* Отличная производительность при данном размере
* Хорошее следование инструкциям
* Эффективная архитектура

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

| Модель      | Параметры | VRAM | Контекст |
| ----------- | --------- | ---- | -------- |
| Gemma-2-2B  | 2B        | 3GB  | 8K       |
| Gemma-2-9B  | 9B        | 12GB | 8K       |
| Gemma-2-27B | 27B       | 32GB | 8K       |

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

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

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

**Порты:**

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

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

```bash
pip install vllm && \\
vllm serve google/gemma-2-9b-it --port 8000
```

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

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

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

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

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

```bash

# Запуск Gemma 2
ollama run gemma2

# Конкретные размеры
ollama run gemma2:2b
ollama run gemma2:9b
ollama run gemma2:27b
```

## Установка

```bash
pip install transformers accelerate torch
```

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

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

model_id = "google/gemma-2-9b-it"

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

messages = [
    {"role": "user", "content": "Объясните, как нейронные сети учатся."}
]

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

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

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

## Gemma 2 2B (Лёгкая)

Для развёртывания на edge/mobile-устройствах:

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

model_id = "google/gemma-2-2b-it"

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

# Быстрый инференс для простых задач
messages = [{"role": "user", "content": "Подведите итог в одном предложении: ИИ преобразует отрасли."}]
```

## Gemma 2 27B (Лучшее качество)

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

model_id = "google/gemma-2-27b-it"

# Используйте 4-битную квантизацию, чтобы поместиться в 24 ГБ VRAM
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16
)

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    quantization_config=quantization_config,
    device_map="auto"
)
```

## Сервер vLLM

```bash
vllm serve google/gemma-2-9b-it \\
    --port 8000 \\
    --dtype bfloat16 \\
    --max-model-len 8192
```

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

```python
from openai import OpenAI

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

response = client.chat.completions.create(
    model="google/gemma-2-9b-it",
    messages=[
        {"role": "user", "content": "Напишите хайку о программировании"}
    ],
    temperature=0.8
)

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="google/gemma-2-9b-it",
    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)
```

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

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

model_id = "google/gemma-2-9b-it"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)

def chat(message, history, temperature):
    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", add_generation_prompt=True).to("cuda")
    outputs = model.generate(inputs, max_new_tokens=512, temperature=temperature, do_sample=True)

    return tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)

demo = gr.ChatInterface(
    fn=chat,
    additional_inputs=[gr.Slider(0.1, 1.5, value=0.7, label="Температура")],
    title="Gemma 2 Чат"
)

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

## Пакетная обработка

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

model_id = "google/gemma-2-9b-it"
tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side="left")
tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)

prompts = [
    "Объясните гравитацию в одном предложении.",
    "Что такое фотосинтез?",
    "Определите машинное обучение.",
    "Какова скорость света?"
]

messages_batch = [[{"role": "user", "content": p}] for p in prompts]

inputs = tokenizer.apply_chat_template(
    messages_batch,
    return_tensors="pt",
    padding=True,
    add_generation_prompt=True
).to("cuda")

outputs = model.generate(inputs, max_new_tokens=128, pad_token_id=tokenizer.pad_token_id)

for i, output in enumerate(outputs):
    response = tokenizer.decode(output, skip_special_tokens=True)
    print(f"Q: {prompts[i]}")
    print(f"A: {response.split('<start_of_turn>model')[-1].strip()}\n")
```

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

| Модель              | GPU      | Токенов/сек |
| ------------------- | -------- | ----------- |
| Gemma-2-2B          | RTX 3060 | \~100       |
| Gemma-2-9B          | RTX 3090 | \~60        |
| Gemma-2-9B          | RTX 4090 | \~85        |
| Gemma-2-27B         | A100     | \~45        |
| Gemma-2-27B (4-бит) | RTX 4090 | \~30        |

## Сравнение

| Модель       | MMLU  | Качество | Скорость |
| ------------ | ----- | -------- | -------- |
| Gemma-2-9B   | 71.3% | Отлично  | Быстро   |
| Llama-3.1-8B | 69.4% | Хорошо   | Быстро   |
| Mistral-7B   | 62.5% | Хорошо   | Быстро   |

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

{% hint style="danger" %}
**CUDA out of memory**
{% endhint %}

для 27B - используйте 4-битную квантизацию с BitsAndBytesConfig - уменьшите \`max\_new\_tokens\` - очистите кэш GPU: \`torch.cuda.empty\_cache()\`

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

* Используйте vLLM для промышленного развёртывания
* Включите Flash Attention
* Попробуйте модель 9B для более быстрого инференса

### Проблемы с качеством вывода

* Используйте версию, дообученную на инструкциях (`-it` суффикс)
* Настройте температуру (рекомендуется 0.7-0.9)
* Добавьте системную подсказку для контекста

### Предупреждения токенизатора

* Обновите transformers до последней версии
* Используйте `padding_side="left"` для пакетного инференса

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

Типичные цены на маркетплейсе 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** токенами
* Сравните цены у разных провайдеров

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

* Llama 3.2 — модель Meta
* Qwen2.5 - модель Alibaba
* Инференс vLLM — промышленное обслуживание


---

# 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/gemma2.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.
