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

# Gemma 3

Gemma 3, выпущенная в марте 2025 года Google DeepMind, построена на той же технологии, что и Gemini 2.0. Её выдающееся достижение: **модель 27B обходит Llama 3.1 405B** в бенчмарках LMArena — модель в 15 раз большего размера. Она изначально мультимодальна (текст + изображения + видео), поддерживает контекст 128K и запускается на одном RTX 4090 с квантованием.

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

* **Намного мощнее своего веса**: 27B опережает модели класса 405B в основных бенчмарках
* **Нативно мультимодальна**: Встроенное понимание текста, изображений и видео
* **Окно контекста 128K**: Обрабатывает длинные документы, кодовые базы, беседы
* **Четыре размера**: 1B, 4B, 12B, 27B — на любой бюджет GPU
* **Версии QAT**: Варианты с Quantization-Aware Training позволяют запускать 27B на потребительских GPU
* **Широкая поддержка фреймворков**: Ollama, vLLM, Transformers, Keras, JAX, PyTorch

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

| Модель          | Параметры | VRAM (Q4) | VRAM (FP16) | Лучше всего для                          |
| --------------- | --------- | --------- | ----------- | ---------------------------------------- |
| Gemma 3 1B      | 1B        | 1.5ГБ     | 3GB         | Edge, мобильные устройства, тестирование |
| Gemma 3 4B      | 4B        | 4 ГБ      | 9 ГБ        | Бюджетные GPU, быстрые задачи            |
| Gemma 3 12B     | 12B       | 10GB      | 25ГБ        | Сбалансированное качество/скорость       |
| Gemma 3 27B     | 27B       | 18GB      | 54ГБ        | Лучшее качество, продакшен               |
| Gemma 3 27B QAT | 27B       | 14GB      | —           | Оптимизирована для потребительских GPU   |

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

| Компонент | Gemma 3 4B | Gemma 3 27B (Q4) | Gemma 3 27B (FP16) |
| --------- | ---------- | ---------------- | ------------------ |
| GPU       | RTX 3060   | RTX 4090         | 2× RTX 4090 / A100 |
| VRAM      | 6 ГБ       | 24 ГБ            | 48ГБ+              |
| ОЗУ       | 16GB       | 32GB             | 64GB               |
| Диск      | 10GB       | 25ГБ             | 55ГБ               |
| CUDA      | 11.8+      | 11.8+            | 12.0+              |

**Рекомендуемый GPU на Clore.ai**: RTX 4090 24ГБ (\~$0.5–2/день) для 27B в квантизованном виде — идеальный вариант

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

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

# Запуск разных размеров
ollama run gemma3:1b     # Крошечный — 1.5ГБ VRAM
ollama run gemma3:4b     # Малый — 4ГБ VRAM
ollama run gemma3:12b    # Средний — 10ГБ VRAM
ollama run gemma3:27b    # Большой — 18-20ГБ VRAM (квантизован)

# Версия QAT (оптимизированное квантование)
ollama run gemma3:27b-qat
```

### Ollama API Server

```bash
ollama serve &

curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemma3:27b",
    "messages": [{"role": "user", "content": "Сравните REST и GraphQL для нового API"}]
  }'
```

### Визуальные возможности с Ollama

```bash
# Проанализировать изображение
ollama run gemma3:27b "Подробно опишите это изображение" --images ./photo.jpg
```

## Настройка vLLM (Production)

```bash
pip install vllm

# Развернуть модель 27B
vllm serve google/gemma-3-27b-it \
  --max-model-len 8192 \
  --gpu-memory-utilization 0.90

# Развернуть с большим контекстом на 2 GPU
vllm serve google/gemma-3-27b-it \
  --tensor-parallel-size 2 \
  --max-model-len 65536

# Развернуть 4B для бюджетных конфигураций
vllm serve google/gemma-3-4b-it \
  --max-model-len 32768
```

## HuggingFace Transformers

### Генерация текста

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

model_name = "google/gemma-3-27b-it"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    load_in_4bit=True  # Помещается на 24ГБ GPU
)

messages = [
    {"role": "user", "content": "Напишите класс на Python для двоичного дерева поиска с методами insert, search и delete"}
]

input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
output = model.generate(input_ids, max_new_tokens=2048, temperature=0.7, do_sample=True)
print(tokenizer.decode(output[0][input_ids.shape[-1]:], skip_special_tokens=True))
```

### Видение (понимание изображений)

```python
import torch
from transformers import AutoProcessor, Gemma3ForConditionalGeneration
from PIL import Image

model_name = "google/gemma-3-27b-it"
processor = AutoProcessor.from_pretrained(model_name)
model = Gemma3ForConditionalGeneration.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

# Загрузить изображение
image = Image.open("screenshot.png")

messages = [
    {"role": "user", "content": [
        {"type": "image", "image": image},
        {"type": "text", "text": "Что показывает этот скриншот? Перечислите все элементы интерфейса."}
    ]}
]

inputs = processor.apply_chat_template(messages, return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=1024)
print(processor.decode(output[0], skip_special_tokens=True))
```

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

```bash
docker run --gpus all -p 8000:8000 \
  -v ~/.cache/huggingface:/root/.cache/huggingface \
  vllm/vllm-openai:latest \
  --model google/gemma-3-27b-it \
  --max-model-len 8192
```

## Основные моменты бенчмарков

| Бенчмарк               | Gemma 3 27B     | Llama 3.1 70B | Llama 3.1 405B  |
| ---------------------- | --------------- | ------------- | --------------- |
| LMArena ELO            | 1354            | 1298          | 1337            |
| MMLU                   | 75.6            | 79.3          | 85.2            |
| HumanEval              | 72.0            | 72.6          | 80.5            |
| VRAM (Q4)              | 18GB            | 40GB          | 200ГБ+          |
| **Стоимость на Clore** | **$0.5–2/день** | **$3–6/день** | **$12–24/день** |

Модель 27B обеспечивает качество разговорного интеллекта класса 405B при 1/10 затрат VRAM.

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

* **27B QAT — оптимальный вариант**: Quantization-Aware Training означает меньше потери качества по сравнению с пост-тренировочным квантованием — запускайте на одном RTX 4090
* **Визуальные возможности бесплатны**: Дополнительная настройка не требуется — Gemma 3 изначально понимает изображения. Отлично подходит для разбора документов, анализа скриншотов, чтения графиков
* **Начните с короткого контекста**: Используйте `--max-model-len 8192` первоначально; увеличивайте только при необходимости, чтобы экономить VRAM
* **4B для бюджетных запусков**: Если у вас RTX 3060/3070 ($0.15–0.3/день), модель 4B все ещё превосходит прошлое поколение 27B-моделей
* **Аутентификация Google не требуется**: В отличие от некоторых моделей, Gemma 3 скачивается без ограничений (просто примите лицензию на HuggingFace)

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

| Проблема                                    | Решение                                                                               |
| ------------------------------------------- | ------------------------------------------------------------------------------------- |
| `OutOfMemoryError` на 27B                   | Используйте версию QAT или уменьшите `--max-model-len` до 4096                        |
| Визуальные возможности не работают в Ollama | Обновите Ollama до последней версии: `curl -fsSL https://ollama.com/install.sh \| sh` |
| Медленная генерация                         | Проверьте, что вы используете bfloat16, а не float32. Используйте `--dtype bfloat16`  |
| Модель генерирует мусор                     | Убедитесь, что вы используете `-it` (instruct-tuned) вариант, а не базовую модель     |
| Ошибка 403 при загрузке                     | Примите лицензию Gemma по адресу <https://huggingface.co/google/gemma-3-27b-it>       |

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

* [Технический отчет Gemma 3](https://ai.google.dev/gemma)
* [Карточка модели на HuggingFace](https://huggingface.co/google/gemma-3-27b-it)
* [Библиотека Ollama](https://ollama.com/library/gemma3)
* [Google AI Studio](https://aistudio.google.com/) — попробуйте Gemma 3 онлайн, прежде чем арендовать GPU


---

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