> 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-zh/yu-yan-mo-xing/gemma3.md).

# Gemma 3

在 Clore.ai 上运行 Google Gemma 3 多模态模型——比 Llama-405B 小 15 倍却表现更强

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

## 主要特性

* **表现远超其体量**: 27B 在主要基准测试中击败 405B 级别模型
* **原生多模态**: 内置文本、图像和视频理解
* **128K 上下文窗口**: 处理长文档、代码库、对话
* **四种尺寸**: 1B、4B、12B、27B——满足各种 GPU 预算
* **QAT 版本**: 量化感知训练变体让 27B 可在消费级 GPU 上运行
* **广泛的框架支持**: Ollama、vLLM、Transformers、Keras、JAX、PyTorch

## 模型变体

| 模型              | 参数  | 显存（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  | RTX 3060   | RTX 4090        | 2× RTX 4090 / A100 |
| 显存   | 6GB        | 24GB            | 48GB+              |
| 内存   | 16GB       | 32GB            | 64GB               |
| 磁盘   | 10GB       | 25GB            | 55GB               |
| CUDA | 12.8+      | 12.8+           | 12.8+              |

**推荐的 Clore.ai GPU**: RTX 4090 24GB（$0.14–0.42/小时）适合量化后的 27B——最佳选择

## 使用 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": "比较新 API 的 REST 和 GraphQL"}]
  }'
```

### 使用 Ollama 进行视觉任务

```bash
# 分析一张图片
ollama run gemma3:27b "详细描述这张图片" --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": "编写一个带有 insert、search 和 delete 方法的二叉搜索树 Python 类"}
]

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": "这张截图展示了什么？列出所有 UI 元素。"}
    ]}
]

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.14–0.42/小时** （1× 4090） | **$0.28–0.84/小时** （2× 4090） | **市场上没有**      |

27B 以 1/10 的显存成本，提供了 405B 级别的对话质量。

## 给 Clore.ai 用户的建议

* **27B QAT 是最佳选择**: 量化感知训练意味着比训练后量化更少的质量损失——可在单张 RTX 4090 上运行
* **视觉功能免费**: 无需额外设置——Gemma 3 原生理解图像。非常适合文档解析、截图分析、图表阅读
* **从短上下文开始**：使用 `--max-model-len 8192` 起初如此；只有在需要时再增加，以节省显存
* **低预算运行可用 4B**: 如果你使用的是 RTX 3060/3070（$0.03–0.07/小时），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
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-zh/yu-yan-mo-xing/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.
