精选 Gemma 4 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 Gemma 4 是 Google DeepMind 采用 Apache 2.0 协议开源的全模态开源大语言模型,涵盖从移动端边缘部署到服务器级推理的四种模型尺寸。
from transformers import AutoProcessor, AutoModelForCausalLM
import torch
MODEL_ID = "google/gemma-4-E4B-it"
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
dtype=torch.bfloat16,
device_map="auto"
)
messages = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Explain MoE briefly."},
]
text = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False
)
inputs = processor(
text=text, return_tensors="pt"
).to(model.device)
input_len = inputs["input_ids"].shape[-1]
outputs = model.generate(**inputs, max_new_tokens=512)
response = processor.decode(
outputs[0][input_len:], skip_special_tokens=False
)
result = processor.parse_response(response)
# result["thinking"] → 内部思维链推理过程 (Cot)
# result["response"] → 展示给用户的最终回答
发布时间:2026-03-31 · Apache 2.0 协议 · 基于 Gemini 3 研究成果构建 · 支持 140+ 种语言
$ pip install -U transformers torch accelerate
所有模型在 HuggingFace 上的路径格式为:google/<model-id>
| 尺寸类别 | 官方 Model ID |
|---|---|
| E2B | gemma-4-E2B-it |
| E4B | gemma-4-E4B-it |
| 31B | gemma-4-31b-it |
| 26B A4B | gemma-4-26b-a4b-it |
| 参数名称 | 推荐取值 |
|---|---|
temperature |
1.0 |
top_p |
0.95 |
top_k |
64 |
| 模型类别 | 网络架构 | 总参数量 | 激活参数量 | 层数 | 上下文 | 支持模态 |
|---|---|---|---|---|---|---|
| E2B | Dense+PLE | 5.1B (2.3B 有效) | 2.3B | 35 | 128K | 文本+图像+音频 |
| E4B | Dense+PLE | 8B (4.5B 有效) | 4.5B | 42 | 128K | 文本+图像+音频 |
| 31B | Dense | 30.7B | 30.7B | 60 | 256K | 文本+图像 |
| 26B A4B | MoE | 25.2B | 3.8B | 30 | 256K | 文本+图像 |
滑动窗口:512 tokens (E2B/E4B) · 1024 tokens (31B/26B) · 词表大小:262K (全系列)
混合注意力机制 (Hybrid Attention)
PLE 边缘端优化 — (E2B/E4B)
p-RoPE 与共享 KV 缓存
MoE 混合专家 — 26B A4B
| 模型版本 | BF16 (16-bit) | 8-bit 量化 | 4-bit 量化 |
|---|---|---|---|
| E2B | 9.6 GB | 4.6 GB | 3.2 GB |
| E4B | 15 GB | 7.5 GB | 5 GB |
| 31B | 58.3 GB | 30.4 GB | 17.4 GB |
| 26B A4B | 48 GB | 25 GB | 15.6 GB |
以上仅为基础权重显存 — 实际使用时需额外预留 KV 缓存显存。
| 可用显存容量 | 推荐模型版本 |
|---|---|
| < 5 GB | E2B (4-bit) |
| 5–8 GB | E4B (4-bit) |
| 15–20 GB | E4B (BF16) |
| 24–32 GB | 31B (4-bit) |
| 48–80 GB | 31B (BF16) |
| 极高吞吐量需求 | 26B A4B |
| 评测基准 | 31B | 26B A4B | E4B | E2B | Gemma 3 27B |
|---|---|---|---|---|---|
| MMLU Pro | 85.2% | 82.6% | 69.4% | 60.0% | 67.6% |
| MMMLU (多语言) | 88.4% | 86.3% | 76.6% | 67.4% | 70.7% |
| AIME 2026 (数学) | 89.2% | 88.3% | 42.5% | 37.5% | 20.8% |
| GPQA Diamond | 84.3% | 82.3% | 58.6% | 43.4% | 42.4% |
| LiveCodeBench v6 | 80.0% | 77.1% | 52.0% | 44.0% | 29.1% |
| Code强制执行s ELO | 2150 | 1718 | 940 | 633 | 110 |
| BigBench Extra Hard | 74.4% | 64.8% | 33.1% | 21.9% | 19.3% |
| Tau2 avg (Agent 智能) | 76.9% | 68.2% | 42.2% | 24.5% | 16.2% |
| HLE (无外部工具) | 19.5% | 8.7% | — | — | — |
| HLE (结合搜索工具) | 26.5% | 17.2% | — | — | — |
以上测试结果均基于已微调版本并开启思维模式 (Thinking Mode)。
| 评测基准 | 31B | 26B A4B | E4B | E2B |
|---|---|---|---|---|
| MMMU Pro | 76.9% | 73.8% | 52.6% | 44.2% |
| MATH-Vision | 85.6% | 82.4% | 59.5% | 52.4% |
| MedXPertQA MM | 61.3% | 58.1% | 28.7% | 23.5% |
| OmniDocBench↓ | 0.131 | 0.149 | 0.181 | 0.290 |
OmniDocBench 指标为文档编辑距离(数值越低代表表现越优秀)。
| 评测基准 | 31B | 26B A4B | E4B | E2B |
|---|---|---|---|---|
| MRCR v2 128K | 66.4% | 44.1% | 25.4% | 19.1% |
Arena AI 竞技场 (LMSYS ELO)
| 模型名称 | ELO 分数 | 开源模型排名 |
|---|---|---|
| Gemma 4 31B | 1452 | #3 |
| Gemma 4 26B A4B | 1441 | #6 |
在 System Prompt 的开头添加 <|think|> 触发标记:
messages = [
{
"role": "system",
"content": "<|think|>You are a math expert."
},
{"role": "user", "content": "Solve: 3x + 7 = 22"}
]
text = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True
)
outputs = model.generate(**inputs, max_new_tokens=2048)
response = processor.decode(
outputs[0][input_len:], skip_special_tokens=False
)
result = processor.parse_response(response)
# result["thinking"] → 逐步分析的思维链内容
# result["response"] → 最终输出答案
思维模式输出结构
<|channel>thought
[内部逐步推理过程 — 对最终用户隐藏]
<channel|>
[呈现给用户的最终答案]
禁用思考时的响应格式
在 31B/26B A4B 模型中即便设置 enable_thinking=False,仍会输出空标签:
<|channel>thought
<channel|>
[最终答案]
E2B/E4B 模型在禁用时则会彻底跳过空标签。
| Token 标记 | 详细用途与功能说明 |
|---|---|
<\|think\|> |
在 System Prompt 中开启思考模式 |
<\|channel>thought\n |
开启内部思考代码块 |
<channel\|> |
结束内部思考代码块 |
<\|turn> |
开启单轮对话交替 |
<turn\|> |
结束单轮对话交替 |
result["response"] 作为模型的回复max_new_tokens 参数上限enable_thinking=True支持可变宽高比 + 可配置的视觉 Token 预算:
| Token 预算 | 适用场景 |
|---|---|
| 70 | 快速图像分类、视频帧分析 |
| 140 | 图像 Caption 描述、缩略图生成 |
| 280 | 通用图像理解 |
| 560 | 图表、流程图解析 |
| 1120 | OCR 识别、PDF 解析、极精细细节 |
# 图像必须放置在文本之前 (必填)
messages = [{"role": "user", "content": [
{"type": "image", "image": image},
{"type": "text", "text": "Describe this chart."},
]}]
inputs = processor(
text=text,
images=image,
return_tensors="pt"
).to(model.device)
视觉编码器:~150M 参数 (E2B/E4B) · ~550M 参数 (31B/26B)
仅 E2B 与 E4B 支持(配备 ~300M 音频编码器)
ASR 语音识别 Prompt
Transcribe the following speech in
{LANGUAGE} into {LANGUAGE} text.
语音翻译 Prompt
Transcribe in {SRC_LANG}, then
translate to {TARGET_LANG}.
处理为连续的图像帧序列:
# 将视频帧作为图像列表传入
inputs = processor(
text=text,
images=[frame1, frame2, ..., frame60],
return_tensors="pt"
)
在 content 数组中务必遵循图像/音频在前,文本在后:
# ✅ 正确排列顺序
content = [
{"type": "image", "image": img},
{"type": "text", "text": "Describe it."},
]
# ❌ 文本在前会导致模态对齐破坏
content = [
{"type": "text", "text": "Describe it."},
{"type": "image", "image": img},
]
$ pip install -U transformers accelerate
BF16 (默认加载)
from transformers import (
AutoProcessor, AutoModelForCausalLM
)
import torch
mid = "google/gemma-4-31b-it"
processor = AutoProcessor.from_pretrained(mid)
model = AutoModelForCausalLM.from_pretrained(
mid,
torch_dtype=torch.bfloat16,
device_map="auto"
)
4-bit 量化加载
from transformers import BitsAndBytesConfig
bnb = BitsAndBytesConfig(load_in_4bit=True)
model = AutoModelForCausalLM.from_pretrained(
mid,
quantization_config=bnb,
device_map="auto"
)
$ ollama pull gemma4 # 31B (默认)
$ ollama pull gemma4:e4b # 边缘端 4B 版本
$ ollama pull gemma4:e2b # 边缘端 2B 版本
$ ollama run gemma4 # 交互式对话
自定义 GGUF (Modelfile)
FROM /path/to/fine-tuned.gguf
SYSTEM "You are a coding assistant."
$ ollama create mygemma -f Modelfile
$ ollama run mygemma
$ vllm serve google/gemma-4-31B-it \
--max-model-len 8192 \
--enable-auto-tool-choice \
--tool-call-parser gemma4 \
--reasoning-parser gemma4
启动位于 http://localhost:8000/v1 的兼容 OpenAI API 服务
| 部署平台 | 备注说明 |
|---|---|
| Gemini API | 直接调用 gemma-4-31b-it |
| AI Studio | 浏览器在线 Playground |
| Vertex AI | 部署托管自定义 Endpoint |
| Cloud Run | Serverless GPU 无服务器部署 |
| GKE + vLLM | Kubernetes 弹性自动扩缩容 |
| 运行环境 | 适用场景 |
|---|---|
| AICore (Android) | 系统级 API 调用 |
| LiteRT-LM | IoT 嵌入式、树莓派 |
| AI Edge Gallery | 端侧性能测试评测 |
| LM Studio | 桌面端 GUI 应用 |
| llama.cpp | CPU/GPU 混合推理 |
单张 16 GB 显存 GPU 即可运行 (如 T4/免费 Colab 或 Kaggle):
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(
"google/gemma-4-E4B-it",
load_in_4bit=True,
max_seq_length=4096
)
model = FastModel.get_peft_model(
model,
r=16,
lora_alpha=16,
lora_dropout=0,
target_modules=[
"q_proj", "k_proj",
"v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"
],
)
视觉微调设置 (E2B / E4B)
from unsloth import FastVisionModel
model, tokenizer = FastVisionModel.from_pretrained(
"google/gemma-4-E4B-it",
finetune_vision_layers=False, # 冻结视觉编码器
finetune_language_layers=True,
load_in_4bit=True,
)
对于 26B A4B 模型——全量参数微调会破坏专家路由策略:
r=16, lora_alpha=16 开始| 训练要求 | 详细规范与标准 |
|---|---|
| CoT 占比 | 建议占训练集总量的 ≥ 75% |
| 思维链格式 | 显式包含 <\|think\|> 触发标记 |
| 多模态顺序 | 训练集中图像/音频放置在文本前 |
| 对话模板格式 | 采用 ShareGPT 或 OpenAI 格式 |
| 强化学习 Reward | 基于可验证答案的客观 Reward |
finetune_vision_layers=False| 模型名称 | 应用领域 | 详细功能介绍 |
|---|---|---|
| MedGemma 4B | 医疗影像 | 多模态 X光片/MRI 影像诊断分析 |
| MedGemma 27B | 临床文本 | 电子病历 (EHR) 与医疗报告推理分析 |
| CodeGemma | 编程代码 | 代码自动补全与重构优化 |
| PaliGemma 2 | 视觉-语言 | 精细粒度 VLM 视觉推理 |
| ShieldGemma | 内容安全 | LLM 输入输出安全防护分类器 |
| DataGemma | 事实数据 | 结合 Google Data Commons 的事实增强 |
| FunctionGemma | 函数调用 | 低资源消耗的 Function Call 解析模型 |
开发库与框架
google-deepmind/gemma)google-gemma/gemma-cookbook)google/adk-samples 官方 Agent 范例社区衍生模型