Gemma 4 开源大语言模型

精选 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+ 种语言

#依赖安装 (Install)

$ 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

#采样参数设置 (Sampling Params)

参数名称 推荐取值
temperature 1.0
top_p 0.95
top_k 64

#最佳实践 (Best Practices)

  • 在 Prompt 中务必将图像/音频放置在文本之前
  • 多轮对话时:在对话历史中省略思维链 thought 代码块
  • 建议保留 75%+ 的 CoT 训练数据以维持推理能力
  • 仅微调文本能力时,请冻结 Vision 视觉层

#模型家族 (Model Family)

#模型规格规格表 (Model Specs)

模型类别 网络架构 总参数量 激活参数量 层数 上下文 支持模态
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 (全系列)

#架构创新特性 (Architecture Features)

混合注意力机制 (Hybrid Attention)

  • Local 本地层:滑动窗口 (512 或 1024 tokens)
  • Global 全局层:全上下文注意力,与 Local 层交错排列
  • 模型的最后一层始终为 Global 全局注意力层

PLE 边缘端优化 — (E2B/E4B)

  • 逐层嵌入 (Per-Layer Embeddings):每个 Decoder 解码层拥有独立的微型嵌入表
  • 静态嵌入表使用高速查表技术——避免密集矩阵乘法计算
  • 有效计算参数量 ≪ 实际加载的物理参数量
  • 支持在 1.5 GB 显存内流畅推理(配合 4-bit 量化)

p-RoPE 与共享 KV 缓存

  • 全局层采用 Proportional RoPE (p-RoPE) 维持长程一致性
  • 跨全局层共享 KV 缓存,大幅降低峰值显存占用
  • 稳定支持 256K 超长上下文且无性能衰减

MoE 混合专家 — 26B A4B

  • 128 个常规专家 + 1 个常驻激活的共享专家
  • 推理时每个 Token 激活 8 个专家
  • 推理速度等同于 4B 密集模型,回答质量逼近 30B
  • 视觉编码器:~550M 参数(与 31B 版本相同)

#显存配置要求 (Memory Requirements)

模型版本 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 缓存显存。

#选型建议指南 (Pick a Model)

可用显存容量 推荐模型版本
< 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

#基准测试 (Benchmarks)

#核心能力基准 (Core Benchmarks)

评测基准 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)。

#视觉理解评测 (Vision Benchmarks)

评测基准 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 指标为文档编辑距离(数值越低代表表现越优秀)。

#长上下文评测 (Long Context)

评测基准 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

#思维模式 (Thinking Mode)

#思考能力控制 (Thinking Control)

在 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 (Control Tokens)

Token 标记 详细用途与功能说明
<\|think\|> 在 System Prompt 中开启思考模式
<\|channel>thought\n 开启内部思考代码块
<channel\|> 结束内部思考代码块
<\|turn> 开启单轮对话交替
<turn\|> 结束单轮对话交替

#多轮对话规则 (Multi-turn Rules)

  • 严禁将思考过程的内容带入多轮历史对话上下文中
  • 在历史记录中仅传递 result["response"] 作为模型的回复
  • 对于复杂推理任务,需增大 max_new_tokens 参数上限
  • 面对 AIME 数学竞赛、定理证明、代码 Debug 时建议启用 enable_thinking=True

#多模态能力 (Multimodal)

#图像输入 (Image Inputs)

支持可变宽高比 + 可配置的视觉 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)

#音频输入 (Audio Inputs)

仅 E2B 与 E4B 支持(配备 ~300M 音频编码器)

  • 最大音频时长:30 秒
  • 主要任务:ASR 语音识别与语音翻译

ASR 语音识别 Prompt

Transcribe the following speech in
{LANGUAGE} into {LANGUAGE} text.

语音翻译 Prompt

Transcribe in {SRC_LANG}, then
translate to {TARGET_LANG}.

#视频输入 (Video Inputs)

处理为连续的图像帧序列

  • 最大时长:60 秒,以 1 fps 采样 = 60 帧
  • 每帧建议设置低 Token 预算 (70–140)
  • E2B/E4B:支持同步处理音频轨道
# 将视频帧作为图像列表传入
inputs = processor(
    text=text,
    images=[frame1, frame2, ..., frame60],
    return_tensors="pt"
)

#模态排列顺序 (Modality Order)

在 content 数组中务必遵循图像/音频在前,文本在后

# ✅ 正确排列顺序
content = [
    {"type": "image", "image": img},
    {"type": "text",  "text": "Describe it."},
]

# ❌ 文本在前会导致模态对齐破坏
content = [
    {"type": "text",  "text": "Describe it."},
    {"type": "image", "image": img},
]

#部署部署指南 (Deployment)

#HuggingFace

$ 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 本地运行

$ 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 高性能服务

$ 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 服务

#云端与 API (Cloud & API)

部署平台 备注说明
Gemini API 直接调用 gemma-4-31b-it
AI Studio 浏览器在线 Playground
Vertex AI 部署托管自定义 Endpoint
Cloud Run Serverless GPU 无服务器部署
GKE + vLLM Kubernetes 弹性自动扩缩容

#边缘与移动端 (Edge & Mobile)

运行环境 适用场景
AICore (Android) 系统级 API 调用
LiteRT-LM IoT 嵌入式、树莓派
AI Edge Gallery 端侧性能测试评测
LM Studio 桌面端 GUI 应用
llama.cpp CPU/GPU 混合推理

#模型微调 (Fine-Tuning)

#QLoRA 微调设置

单张 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,
)

#MoE 专家架构微调

对于 26B A4B 模型——全量参数微调会破坏专家路由策略:

  • 必须仅使用 LoRA bf16 进行微调 (切勿使用全量微调 FFT)
  • 参数设置推荐从 r=16, lora_alpha=16 开始
  • 在 Loss 收敛后再逐步调大上下文长度
  • 避免对 Expert Router 路由器的权重矩阵施加 LoRA

#数据格式要求 (Data Requirements)

训练要求 详细规范与标准
CoT 占比 建议占训练集总量的 ≥ 75%
思维链格式 显式包含 <\|think\|> 触发标记
多模态顺序 训练集中图像/音频放置在文本前
对话模板格式 采用 ShareGPT 或 OpenAI 格式
强化学习 Reward 基于可验证答案的客观 Reward

#视觉微调技巧 (Vision Fine-tune Tips)

  1. 首选冻结视觉编码器finetune_vision_layers=False
  2. 仅对 LLM 语言层 + Attention + MLP 投影层进行微调
  3. 解冻前先验证文本领域的回答质量未下降
  4. 仅在面对特定专业领域图像时再解冻视觉层
  5. 设置低 Token 预算 (70–280) 可在训练阶段大幅节省 VRAM

#Gemma 生态全景 (Gemmaverse)

#领域专用模型 (Specialist Models)

模型名称 应用领域 详细功能介绍
MedGemma 4B 医疗影像 多模态 X光片/MRI 影像诊断分析
MedGemma 27B 临床文本 电子病历 (EHR) 与医疗报告推理分析
CodeGemma 编程代码 代码自动补全与重构优化
PaliGemma 2 视觉-语言 精细粒度 VLM 视觉推理
ShieldGemma 内容安全 LLM 输入输出安全防护分类器
DataGemma 事实数据 结合 Google Data Commons 的事实增强
FunctionGemma 函数调用 低资源消耗的 Function Call 解析模型

#开源生态 (Ecosystem)

开发库与框架

  • ADK (Agent Development Kit 开发套件)
  • JAX Gemma 代码库 (google-deepmind/gemma)
  • Gemma Cookbook (google-gemma/gemma-cookbook)
  • google/adk-samples 官方 Agent 范例

社区衍生模型

  • 100K+ 社区微调衍生模型
  • RecurrentGemma (基于 Griffin 循环架构)
  • EmbeddingGemma, T5Gemma 2
  • VaultGemma (差分隐私保护模型)

#🔗 参考资源