# Gemma 3

Gemma 3，由 Google DeepMind 于 2025 年 3 月发布，构建在与 Gemini 2.0 相同的技术之上。其突出成就： **该 27B 模型在 LMArena 基准上击败了 Llama 3.1 405B** ——一个体量是它 15 倍的模型。它原生支持多模态（文本 + 图像 + 视频），支持 128K 上下文，并通过量化在单张 RTX 4090 上运行。

## 主要特性

* **以小博大**：27B 在主要基准上胜过 405B 级别的模型
* **原生多模态**：内置文本、图像和视频理解能力
* **128K 上下文窗口**：可处理长文档、代码库、对话
* **四个规模**：1B、4B、12B、27B——适合各种 GPU 预算
* **QAT 版本**：量化感知训练（Quantization-Aware Training）变体让 27B 能在消费级 GPU 上运行
* **广泛的框架支持**：Ollama、vLLM、Transformers、Keras、JAX、PyTorch

## 1024x1024

| A100            | 参数量 | 显存（Q4） | 显存（FP16） | 最适合          |
| --------------- | --- | ------ | -------- | ------------ |
| Gemma 3 1B      | 1B  | 1.5GB  | 3GB      | 边缘、移动、测试     |
| Gemma 3 4B      | 4B  | 4GB    | 9GB      | 预算型 GPU、快速任务 |
| Gemma 3 12B     | 12B | 10GB   | 25GB     | 质量/速度平衡      |
| Gemma 3 27B     | 27B | 18GB   | 54GB     | 最佳质量、生产环境    |
| Gemma 3 27B QAT | 27B | 14GB   | —        | 为消费级 GPU 优化  |

## 要求

| 组件   | Gemma 3 4B | Gemma 3 27B（Q4） | Gemma 3 27B（FP16）  |
| ---- | ---------- | --------------- | ------------------ |
| GPU  | 按小时费率      | 512x512         | 2× RTX 4090 / A100 |
| 显存   | 6GB        | 24GB            | 48GB+              |
| 内存   | 16GB       | 32GB            | 64GB               |
| 磁盘   | 10GB       | 25GB            | 55GB               |
| CUDA | 11.8+      | 11.8+           | 12.0+              |

**推荐的 Clore.ai GPU**：对 27B 量化模型来说，RTX 4090 24GB（约 $0.5–2/天）是性价比最佳点

## 使用 Ollama 快速入门

```bash
# 安装 Ollama
curl -fsSL https://ollama.com/install.sh | sh

# 运行不同规模
ollama run gemma3:1b     # 极小 — 1.5GB 显存
ollama run gemma3:4b     # 小型 — 4GB 显存
ollama run gemma3:12b    # 中型 — 10GB 显存
ollama run gemma3:27b    # 大型 — 18-20GB 显存（量化后）

# QAT 版本（优化的量化）
ollama run gemma3:27b-qat
```

### Ollama API 服务

```bash
ollama serve &

curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemma3:27b",
    "messages": [{"role": "user", "content": "Compare REST vs GraphQL for a new API"}]
  }'
```

### 使用 Ollama 的视觉能力

```bash
# 分析图像
ollama run gemma3:27b "Describe this image in detail" --images ./photo.jpg
```

## vLLM 设置（用于生产）

```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  # 可装入 24GB GPU
)

messages = [
    {"role": "user", "content": "Write a Python class for a binary search tree with insert, search, and delete methods"}
]

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 = [
    return processor.decode(output[0], skip_special_tokens=True).split("[/INST]")[-1].strip()
        {"type": "image", "image": image},
        {"type": "text", "text": "What does this screenshot show? List all UI elements."}
    ]}
]

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           |
| 显存（Q4）           | 18GB         | 40GB          | 200GB+         |
| **在 Clore 上的成本** | **$0.5–2/天** | **$3–6/天**    | **$12–24/天**   |

该 27B 在显存成本上以十分之一的代价提供了与 405B 级别相当的会话质量。

## 给 Clore.ai 用户的提示

* **27B QAT 是最佳选择**：量化感知训练相比训练后量化导致的质量损失更小——可在单张 RTX 4090 上运行
* **视觉功能是免费的**：无需额外设置——Gemma 3 原生理解图像。非常适合文档解析、截图分析、图表读取
* **从短上下文开始**：使用 `--max-model-len 8192` 最初如此；仅在需要时增加以节省显存
* **预算运行选 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` （经过指令微调的）变体，而不是基础模型                                |
| 下载 403 错误                  | 在 <https://huggingface.co/google/gemma-3-27b-it> 接受 Gemma 许可     |

## 延伸阅读

* [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/) — 在租用 GPU 之前先在线试用 Gemma 3


---

# Agent Instructions: 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:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/gemma3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
