玩模型开放模型 · 清晰来源 · 自主选择
返回模型目录
llmfan46 /

gemma-4-31B-it-uncensored-heretic

HF 源站

llmfan46/gemma-4-31B-it-uncensored-heretic is an uncensored open-source model hosted on Hugging Face.

Image-Text-to-TextsafetensorsLicense: apache-2.031Btransformersgemma4hereticuncensoreddecensoredabliteratedaraconversational
README.md说明 / 使用方法

library_name: transformers license: apache-2.0 license_link: https://ai.google.dev/gemma/docs/gemma_4_license pipeline_tag: image-text-to-text tags:

  • heretic
  • uncensored
  • decensored
  • abliterated
  • ara base_model:
  • google/gemma-4-31B-it


拒答率降低 90%(未审查版 10/100 对比 原始模型 99/100),同时保持模型质量(KL 散度仅 0.0541)。

❤️ 支持我的工作

制作这些模型需要投入大量的时间、精力与算力。如果您觉得这些模型有所帮助,请考虑赞助支持我:

image/png

平台链接您将获得
🎉 Patreon按月赞助优先定制/请求模型
☕ Ko-fi单次打赏我由衷的感谢

您的支持将激励我前行,并用于进一步改进制作工作流、支付存储和算力费用,甚至有助于租用云端 GPU 对更大的模型进行去审查处理。


本模型是 google/gemma-4-31B-it 的去审查(Decensored)版本,基于 Heretic v1.2.0 并采用 Arbitrary-Rank Ablation (ARA) 方法制作

消除(Abliteration)参数

参数数值
start_layer_index30
end_layer_index48
preserve_good_behavior_weight0.5437
steer_bad_behavior_weight0.0005
overcorrect_relative_weight0.9949
neighbor_count15

目标组件

  • attn.o_proj

性能表现

指标本模型原始模型 (gemma-4-31B-it)
KL 散度0.05410 (根据定义)
拒答率✅ 10/100❌ 99/100

更低的拒答率代表更少的内容限制,而更低的 KL 散度则表明其与原始模型的基准表现越接近。较高的拒答率会导致更多的拒绝、异议、推脱、说教、审查、语气软化及回避转移。

MMLU 测试结果:

原始模型(Original):

============================================================

  • 问题总数: 7021

  • 正确数: 6073

  • 准确率: 0.8650 (86.50%)

  • 解析失败数: 52

============================================================

各学科测试得分:

  • professional_law: 0.7682 (603/785)
  • moral_scenarios: 0.8348 (369/442)
  • miscellaneous: 0.9243 (354/383)
  • professional_psychology: 0.9051 (286/316)
  • high_school_psychology: 0.9630 (260/270)
  • high_school_macroeconomics: 0.9289 (183/197)
  • elementary_mathematics: 0.9348 (172/184)
  • moral_disputes: 0.8448 (147/174)
  • prehistory: 0.9360 (161/172)
  • philosophy: 0.8491 (135/159)
  • high_school_biology: 0.9539 (145/152)
  • professional_accounting: 0.8392 (120/143)
  • clinical_knowledge: 0.9143 (128/140)
  • high_school_microeconomics: 0.9706 (132/136)
  • nutrition: 0.9259 (125/135)
  • professional_medicine: 0.9179 (123/134)
  • conceptual_physics: 0.8984 (115/128)
  • high_school_mathematics: 0.5512 (70/127)
  • human_aging: 0.8793 (102/116)
  • security_studies: 0.8571 (96/112)
  • high_school_statistics: 0.8829 (98/111)
  • marketing: 0.9633 (105/109)
  • high_school_world_history: 0.9623 (102/106)
  • sociology: 0.9029 (93/103)
  • high_school_government_and_politics: 0.9604 (97/101)
  • high_school_geography: 0.9293 (92/99)
  • high_school_chemistry: 0.7732 (75/97)
  • high_school_us_history: 0.9368 (89/95)
  • virology: 0.5169 (46/89)
  • college_medicine: 0.8523 (75/88)
  • world_religions: 0.9205 (81/88)
  • high_school_physics: 0.7976 (67/84)
  • electrical_engineering: 0.8642 (70/81)
  • astronomy: 0.9494 (75/79)
  • logical_fallacies: 0.8816 (67/76)
  • high_school_european_history: 0.9041 (66/73)
  • anatomy: 0.8732 (62/71)
  • college_biology: 0.9688 (62/64)
  • human_sexuality: 0.9219 (59/64)
  • formal_logic: 0.7969 (51/64)
  • public_relations: 0.7377 (45/61)
  • international_law: 0.9167 (55/60)
  • college_physics: 0.6842 (39/57)
  • college_mathematics: 0.7455 (41/55)
  • econometrics: 0.7963 (43/54)
  • jurisprudence: 0.8679 (46/53)
  • high_school_computer_science: 0.9808 (51/52)
  • machine_learning: 0.8462 (44/52)
  • medical_genetics: 0.9608 (49/51)
  • global_facts: 0.6078 (31/51)
  • management: 0.9200 (46/50)
  • us_foreign_policy: 0.9200 (46/50)
  • college_chemistry: 0.5745 (27/47)
  • abstract_algebra: 0.7660 (36/47)
  • business_ethics: 0.8261 (38/46)
  • college_computer_science: 0.9333 (42/45)
  • computer_security: 0.8372 (36/43)

Heretic:

============================================================

  • 问题总数: 7021

  • 正确数: 6031

  • 准确率: 0.8590 (8590%)

  • 解析失败数: 37

============================================================

各学科测试得分:

  • professional_law: 0.7490 (588/785)
  • moral_scenarios: 0.8281 (366/442)
  • miscellaneous: 0.9243 (354/383)
  • professional_psychology: 0.8861 (280/316)
  • high_school_psychology: 0.9667 (261/270)
  • high_school_macroeconomics: 0.9188 (181/197)
  • elementary_mathematics: 0.9511 (175/184)
  • moral_disputes: 0.8563 (149/174)
  • prehistory: 0.9360 (161/172)
  • philosophy: 0.8365 (133/159)
  • high_school_biology: 0.9539 (145/152)
  • professional_accounting: 0.8182 (117/143)
  • clinical_knowledge: 0.9214 (129/140)
  • high_school_microeconomics: 0.9632 (131/136)
  • nutrition: 0.9037 (122/135)
  • professional_medicine: 0.9254 (124/134)
  • conceptual_physics: 0.8984 (115/128)
  • high_school_mathematics: 0.5276 (67/127)
  • human_aging: 0.8448 (98/116)
  • security_studies: 0.8482 (95/112)
  • high_school_statistics: 0.8739 (97/111)
  • marketing: 0.9725 (106/109)
  • high_school_world_history: 0.9717 (103/106)
  • sociology: 0.9029 (93/103)
  • high_school_government_and_politics: 0.9505 (96/101)
  • high_school_geography: 0.9293 (92/99)
  • high_school_chemistry: 0.7835 (76/97)
  • high_school_us_history: 0.9263 (88/95)
  • virology: 0.5056 (45/89)
  • college_medicine: 0.8523 (75/88)
  • world_religions: 0.9318 (82/88)
  • high_school_physics: 0.7976 (67/84)
  • electrical_engineering: 0.8519 (69/81)
  • astronomy: 0.9494 (75/79)
  • logical_fallacies: 0.9079 (69/76)
  • high_school_european_history: 0.8767 (64/73)
  • anatomy: 0.8732 (62/71)
  • college_biology: 0.9688 (62/64)
  • human_sexuality: 0.8906 (57/64)
  • formal_logic: 0.7969 (51/64)
  • public_relations: 0.7541 (46/61)
  • international_law: 0.9167 (55/60)
  • college_physics: 0.7018 (40/57)
  • college_mathematics: 0.7455 (41/55)
  • econometrics: 0.7778 (42/54)
  • jurisprudence: 0.8491 (45/53)
  • high_school_computer_science: 0.9808 (51/52)
  • machine_learning: 0.7692 (40/52)
  • medical_genetics: 0.9412 (48/51)
  • global_facts: 0.6078 (31/51)
  • management: 0.9200 (46/50)
  • us_foreign_policy: 0.9200 (46/50)
  • college_chemistry: 0.5745 (27/47)
  • abstract_algebra: 0.7660 (36/47)
  • business_ethics: 0.8478 (39/46)
  • college_computer_science: 0.9333 (42/45)
  • computer_security: 0.8372 (36/43)

MMLU - 大规模多任务语言理解(Massive Multitask Language Understanding),涵盖 57 个学科领域(数学、历史、法律、医学等)的多项选择题基准。

GGUF 版本

GGUF 量化版本可在此获取:llmfan46/gemma-4-31B-it-uncensored-heretic-GGUF。

NVFP4 版本

NVFP4 量化版本可在此获取:llmfan46/gemma-4-31B-it-uncensored-heretic-NVFP4。

NVFP4 GGUF 版本

NVFP4 GGUF 量化版本可在此获取:llmfan46/gemma-4-31B-it-uncensored-heretic-NVFP4-GGUF。


Gemma 是由 Google DeepMind 构建的开源模型系列。Gemma 4 系列模型均为多模态模型,支持文本和图像输入(较小模型还原生支持音频),并生成文本输出。本次发布涵盖了预训练模型(Pre-trained)与指令微调(Instruction-tuned)两种开源权重变体。Gemma 4 具备高达 256K token 的上下文窗口,并保持对 140 多种语言的多语言支持。

Gemma 4 拥有稠密(Dense)与混合专家(Mixture-of-Experts, MoE)两种架构,非常适合文本生成、编程以及推理任务。模型提供四种不同规格大小:E2B、E4B、26B A4B 以及 31B。多样化的参数规模使其能够部署在从高端手机、笔记本电脑到服务器的各类环境中,推动前沿 AI 技术的普及。

Gemma 4 带来了多项关键能力与架构提升:

  • 深度推理 – 该系列所有模型均设计为高水平推理模型,支持可配置的思考(thinking)模式。
  • 扩展多模态 – 原生处理文本、可变宽高比与分辨率的图像(所有模型支持)、视频,以及音频(E2B 与 E4B 模型原生支持)。
  • 多元且高效的架构 – 提供不同规格的稠密与混合专家(MoE)变体,实现灵活扩展部署。
  • 端侧设备专属优化 – 较小模型专为笔记本电脑和移动设备上的高效本地运行量身定制。
  • 超长上下文窗口 – 小型模型支持 128K 上下文窗口,中型模型支持高达 256K。
  • 增强的代码与智能体(Agentic)能力 – 在代码评测基准上取得显著提升,并具备原生函数调用(Function Calling)支持,为构建强大的自主智能体提供坚实基础。
  • 原生系统提示词支持 – Gemma 4 原生支持 system 角色,带来更结构化、可控性更高的多轮对话。

模型概览

Gemma 4 各规格模型旨在不同规模下提供前沿级的性能表现,全面覆盖从移动端与边缘设备(E2B、E4B)到消费级 GPU 和工作站(26B A4B、31B)的部署需求。非常适用于推理、智能体工作流、编程开发以及多模态理解任务。

模型采用了混合注意力机制,将局部滑动窗口注意力与全局全量注意力交替穿插,并确保最后一层始终为全局注意力。这种混合设计既具备轻量级模型的推理速度与极低显存占用,又保留了处理复杂长上下文任务所需的全局感知力。为了进一步优化长上下文下的显存消耗,全局层采用了统一的键与值(Unified K/V),并应用了成比例旋转位置编码(Proportional RoPE, p-RoPE)。

稠密模型(Dense Models)

属性E2BE4B31B Dense
总参数量2.3B 有效参数 (含词嵌入 5.1B)4.5B 有效参数 (含词嵌入 8B)30.7B
层数354260
滑动窗口512 tokens512 tokens1024 tokens
上下文长度128K tokens128K tokens256K tokens
词表大小262K262K262K
支持模态文本、图像、音频文本、图像、音频文本、图像
视觉编码器参数~150M~150M~550M
音频编码器参数~300M~300M不支持音频

E2B 与 E4B 中的 "E" 代表“有效”(effective)参数。较小模型引入了逐层嵌入(Per-Layer Embeddings, PLE),以最大化端侧部署的参数利用效率。PLE 没有盲目堆叠更多模型层数或参数,而是让每个解码器层都拥有针对每个 token 的专属微型嵌入表。这些嵌入查找表体积较大但仅用于快速查表操作,因此模型的实际有效计算参数量远低于总参数量。

混合专家模型(MoE Model)

属性26B A4B MoE
总参数量25.2B
激活参数量3.8B
层数30
滑动窗口1024 tokens
上下文长度256K tokens
词表大小262K
专家数量8 激活 / 128 总计 + 1 共享
支持模态文本、图像
视觉编码器参数~550M

26B A4B 中的 "A" 代表“激活参数”(active parameters),用于区别模型包含的总参数量。在推理时仅激活 4B 左右的参数子集,使得该混合专家模型的运行速度远快于其 25.2B 总参数所暗示的耗时。相比稠密的 31B 模型,它是一个极具性价比的高速推理选择,其运行速度几乎与 4B 参数级别模型相当。

基准测试结果

上述模型针对大量不同数据集和评估指标进行了全面测试,以评估文本生成等各方面能力。表格中列出的评测结果均基于指令微调(Instruction-tuned)版本。

评测基准Gemma 4 31BGemma 4 26B A4BGemma 4 E4BGemma 4 E2BGemma 3 27B (无思考模式)
MMLU Pro85.2%82.6%69.4%60.0%67.6%
AIME 2026 no tools89.2%88.3%42.5%37.5%20.8%
LiveCodeBench v680.0%77.1%52.0%44.0%29.1%
Codeforces ELO21501718940633110
GPQA Diamond84.3%82.3%58.6%43.4%42.4%
Tau2 (3 次运行均值)76.9%68.2%42.2%24.5%16.2%
HLE no tools19.5%8.7%---
HLE with search26.5%17.2%---
BigBench Extra Hard74.4%64.8%33.1%21.9%19.3%
MMMLU88.4%86.3%76.6%67.4%70.7%
视觉能力
MMMU Pro76.9%73.8%52.6%44.2%49.7%
OmniDocBench 1.5 (平均编辑距离,越低越好)0.1310.1490.1810.2900.365
MATH-Vision85.6%82.4%59.5%52.4%46.0%
MedXPertQA MM61.3%58.1%28.7%23.5%-
音频能力
CoVoST--35.5433.47-
FLEURS (越低越好)--0.080.09-
长上下文
MRCR v2 8 needle 128k (均值)66.4%44.1%25.4%19.1%13.5%

核心能力

Gemma 4 系列能够胜任跨文本、视觉和音频的广泛任务。核心能力包括:

  • 思考模式(Thinking) – 内置深度推理模式,允许模型在生成最终回答前逐步展开思考分析。
  • 长上下文(Long Context) – 支持高达 128K tokens(E2B/E4B)及 256K tokens(26B A4B/31B)的超长上下文窗口。
  • 图像理解(Image Understanding) – 目标检测、文档/PDF 解析、屏幕及 UI 理解、图表解析、OCR(含多语言)、手写识别与点选定位。支持任意宽高比与分辨率的图像输入。
  • 视频理解(Video Understanding) – 通过处理连续视频帧序列来分析与理解视频。
  • 图文交错多模态输入(Interleaved Multimodal Input) – 在单个提示词内自由混合排列文本与图像顺序。
  • 函数调用(Function Calling) – 原生支持结构化工具调用,全面赋能自主智能体应用。
  • 代码能力(Coding) – 强大的代码生成、自动补全与错误修正。
  • 多语言支持(Multilingual) – 开箱即用支持 35+ 种语言,预训练覆盖 140+ 种语言。
  • 音频能力(Audio,仅限 E2B 和 E4B) – 支持跨多种语言的自动语音识别(ASR)与语音到翻译文本(AST)。

快速上手

您可以通过最新版本的 Transformers 运行所有 Gemma 4 模型。首先,在环境中安装所需依赖库:

pip install -U transformers torch accelerate

安装完成后,即可运行以下代码加载模型:

from transformers import AutoProcessor, AutoModelForCausalLM

MODEL_ID = "google/gemma-4-31B-it"

# 加载模型
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    dtype="auto",
    device_map="auto"
)

模型加载完成后,即可开始生成文本:

# 提示词
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Write a short joke about saving RAM."},
]

# 处理输入
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=1024)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

# 解析输出
processor.parse_response(response)

如需开启推理思考模式,只需设置 enable_thinking=True,parse_response 函数会自动解析并处理思考过程的输出。

下面还提供了结合文本同时处理音频(仅限 E2B 与 E4B)、图像及视频的代码示例:

处理音频时,请使用 AutoModelForMultimodalLM 代替 AutoModelForCausalLM。使用前请确保安装了以下依赖:

pip install -U transformers torch librosa accelerate

然后通过以下代码加载模型:

from transformers import AutoProcessor, AutoModelForMultimodalLM

MODEL_ID = "google/gemma-4-E2B-it"

# 加载模型
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForMultimodalLM.from_pretrained(
    MODEL_ID, 
    dtype="auto", 
    device_map="auto"
)

模型加载后,可以通过在提示词中直接引用音频 URL 来生成输出:

# 提示词 - 在文本前添加音频
messages = [
    {
        "role": "user",
        "content": [
            {"type": "audio", "audio": "https://raw.githubusercontent.com/google-gemma/cookbook/refs/heads/main/Demos/sample-data/journal1.wav"},
            {"type": "text", "text": "Transcribe the following speech segment in its original language. Follow these specific instructions for formatting the answer:
* Only output the transcription, with no newlines.
* When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three."},
        ]
    }
]

# 处理输入
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).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)

# 解析输出
processor.parse_response(response)

处理图像时,请使用 AutoModelForMultimodalLM 代替 AutoModelForCausalLM。使用前请确保安装了以下依赖:

pip install -U transformers torch torchvision accelerate

然后通过以下代码加载模型:

from transformers import AutoProcessor, AutoModelForMultimodalLM

MODEL_ID = "google/gemma-4-31B-it"

# 加载模型
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForMultimodalLM.from_pretrained(
    MODEL_ID, 
    dtype="auto", 
    device_map="auto"
)

模型加载后,可以通过在提示词中直接引用图像 URL 来生成输出:

# 提示词 - 在文本前添加图像
messages = [
    {
        "role": "user", "content": [
            {"type": "image", "url": "https://raw.githubusercontent.com/google-gemma/cookbook/refs/heads/main/Demos/sample-data/GoldenGate.png"},
            {"type": "text", "text": "What is shown in this image?"}
        ]
    }
]

# 处理输入
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).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)

# 解析输出
processor.parse_response(response)

处理视频时,请使用 AutoModelForMultimodalLM 代替 AutoModelForCausalLM。使用前请确保安装了以下依赖:

pip install -U transformers torch torchvision torchcodec librosa accelerate

然后通过以下代码加载模型:

from transformers import AutoProcessor, AutoModelForMultimodalLM

MODEL_ID = "google/gemma-4-31B-it"

# 加载模型
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForMultimodalLM.from_pretrained(
    MODEL_ID, 
    dtype="auto", 
    device_map="auto"
)

模型加载后,可以通过在提示词中直接引用视频 URL 来生成输出:

# 提示词 - 在文本前添加视频
messages = [
    {
        'role': 'user',
        'content': [
            {"type": "video", "video": "https://github.com/bebechien/gemma/raw/refs/heads/main/videos/ForBiggerBlazes.mp4"},
            {'type': 'text', 'text': 'Describe this video.'}
        ]
    }
]

# 处理输入
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).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)

# 解析输出
processor.parse_response(response)

最佳实践

为获得最佳性能表现,推荐使用以下配置与最佳实践:

1. 采样参数设置

建议在所有任务场景下统一采用以下标准采样配置:

  • temperature=1.0
  • top_p=0.95
  • top_k=64

2. 思考模式(Thinking Mode)配置

与 Gemma 3 相比,本模型采用标准的 system、assistant 和 user 角色。若要正确管理思考推理过程,请使用以下控制 token:

  • 触发思考: 在系统提示词(system prompt)开头添加 <|think|> token 即可启用思考模式。若要关闭思考模式,移除该 token 即可。
  • 标准输出格式: 启用思考后,模型会先输出内部推理内容,随后输出最终答案,结构如下:
    <|channel>thought [内部推理内容]<channel|>
  • 禁用思考时的行为: 除 E2B 和 E4B 变体外,对于其他所有规格模型,如果关闭思考,模型仍会生成对应的标签但内部为空思维链块:
    <|channel>thought <channel|>[最终回答]

[!Note] 请注意,像 Transformers 和 llama.cpp 等主流库已经自动处理了对话模板的底层逻辑。

3. 多轮对话注意事项

  • 历史记录中不得包含思考内容:在多轮对话中,保留在历史记录中的模型输出应仅包含最终回答。前一轮模型生成的思考过程(Thought)严禁被加入到下一轮用户提问之前。

4. 模态排列顺序

  • 为了在使用多模态输入时获得最佳效果,请始终将图像和/或音频内容置于提示词中文字内容的前面。

5. 可变图像分辨率与视觉 Token 预算

除了支持任意宽高比外,Gemma 4 还通过可配置的视觉 token 预算(Visual Token Budget)来支持动态分辨率调节,该预算决定了用于表征一张图像的 token 数量。更高的 token 预算可保留更丰富的图像细节,但需要更多计算;较低的预算则能在无需精细细节的任务中实现极快的推理速度。

  • 支持的 token 预算配置包括:70、140、280、560 和 1120。
    • 较低预算适用于图像分类、打标/生成描述或视频理解等更注重高吞吐量与多帧快速处理的场景。
    • 较高预算适用于 OCR、复杂图表文档解析、或识别细小文字等精细化任务。

6. 音频处理

音频任务建议采用以下标准提示词格式:

  • 自动语音识别 (ASR)
Transcribe the following speech segment in {LANGUAGE} into {LANGUAGE} text.

Follow these specific instructions for formatting the answer:
* Only output the transcription, with no newlines.
* When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three.
  • 语音翻译 (AST)
Transcribe the following speech segment in {SOURCE_LANGUAGE}, then translate it into {TARGET_LANGUAGE}.
When formatting the answer, first output the transcription in {SOURCE_LANGUAGE}, then one newline, then output the string '{TARGET_LANGUAGE}: ', then the translation in {TARGET_LANGUAGE}.

7. 音频与视频时长上限

所有模型均支持图像输入,并能以视频帧序列方式处理视频;其中 E2B 和 E4B 模型额外原生支持音频输入。音频最大支持时长为 30 秒;若以每秒一帧采样率处理,视频最大支持时长为 60 秒。

模型数据

模型训练所使用的数据及数据处理流程。

训练数据集

我们的预训练数据集是一个超大规模、涵盖多领域及多模态的多样化语料库,包括网页文档、代码、图像及音频,知识截止日期为 2025 年 1 月。核心组成包括:

  • 网页文档:海量丰富的网页文本,确保模型接触到广泛的语言风格、主题知识及多样化词汇。训练数据集涵盖 140 多种语言的内容。
  • 代码数据:代码训练帮助模型充分掌握各类编程语言的语法结构与设计模式,从而显著提升代码生成以及代码问题解答能力。
  • 数学数据:数学文本训练有助于模型掌握逻辑推理、符号表征能力,并增强解答复杂数学问题的表现。
  • 图像数据:海量各类型图像使模型具备出色的图像分析与视觉数据提取能力。

这些多元化数据源的结合,是训练能够胜任多任务及多样化数据格式的高性能多模态模型的基石。

数据预处理

训练数据应用的关键清洗与过滤方法包括:

  • CSAM 过滤:在数据处理的多个阶段均执行了极为严格的 CSAM(儿童性虐待材料)过滤,确保彻底剔除任何有害与违法内容。
  • 敏感数据过滤:为确保 Gemma 预训练模型的安全性与合规性,采用了自动化手段过滤去除训练集中的特定个人隐私及敏感信息。
  • 其他过滤措施:依据谷歌责任政策开展基于内容质量与安全性的严格过滤。

伦理与安全性

随着开源模型逐渐成为企业基础设施的核心,数据来源(Provenance)与安全性至关重要。Gemma 4 由 Google DeepMind 研发,经历了与商业旗舰 Gemini 系列同样严格的安全评测流程。

评测方法

Gemma 4 系列模型与内部安全团队及负责任 AI 团队联合开发。执行了一系列自动化评估和人工测评,以持续强化模型的安全性。这些测评完全遵循 Google AI 原则 以及安全规范,旨在防止生成式 AI 模型产生有害内容,包括:

  • 涉及儿童性虐待与剥削的内容
  • 危险内容(如宣扬自残自杀,或指导可能导致现实人身伤害的危险活动)
  • 色情露骨内容
  • 仇恨言论(如贬低受保护群体成员等)
  • 骚扰内容(如鼓动针对特定人群的暴力)

评测结果

在所有安全测试领域中,相较于早期的 Gemma 模型,我们在所有内容安全维度上均观察到了大幅提升。总体而言,Gemma 4 模型在显著改善安全性的同时,依然保持了极低的无端拒答率,全面优于 Gemma 3 和 3n 模型。所有评测均在不启用外部安全过滤机制的前提下进行,以真实评估模型的内生能力与行为。无论是文本到文本还是图像到文本任务,在所有模型规格下,违反规范的内容均处于极低水平,相比历代 Gemma 取得了显著跨越。

使用场景与局限性

用户在使用本模型时应充分了解其固有的局限性。

适用场景

多模态模型(支持视觉、语言和/或音频输入)在各行业领域有着广泛的应用。以下潜在用例并非详尽无遗,旨在提供模型设计与训练时所考量的典型应用背景参考:

  • 内容创作与交流
    • 文本生成:可用于诗歌、剧本、代码、营销文案以及电子邮件草稿等创意文本的生成。
    • 聊天机器人与对话式 AI:为客户服务、虚拟助手或交互式应用赋能对话交互界面。
    • 文本摘要:为海量文本语料、学术论文或长篇报告生成精准精炼的摘要。
    • 图像数据提取:用于从视觉数据中提取、解读与归纳关键信息以供沟通交流。
    • 音频处理与交互:小型模型(E2B 与 E4B)支持分析解读音频输入,实现语音驱动的交互与转录。
  • 科研与教育
    • 自然语言处理(NLP)与多模态(VLM)研究:可作为学术界研究 VLM 与 NLP 算法、开展前沿实验的基础底座。
    • 语言学习辅助工具:支持交互式语言学习体验,辅助语法纠错与写作训练。
    • 知识探索检索:通过生成摘要或回答特定专题问题,辅助研究人员梳理大规模文献。

局限性

  • 训练数据
    • 训练数据的质量与多样性极大程度影响了模型能力。数据中的偏见或知识盲区会导致模型输出存在相应局限。
    • 训练数据集的覆盖范围决定了模型能够有效解答的专业领域。
  • 上下文与任务复杂度
    • 模型在表述明确、指令清晰的任务上表现更优。面对开放式或极度复杂的任务可能存在挑战。
    • 模型的实际表现受输入上下文体量的影响(通常在一定范围内,更充分的上下文能带来更优质的输出)。
  • 语言歧义与细微语义
    • 自然语言本身具有高度复杂性。模型可能难以捕捉反讽、讽刺或隐喻等微妙语境。
  • 事实准确性
    • 模型基于预训练阶段学到的统计规律生成回复,其本身并非结构化知识库,可能产生错误或过时的事实性陈述(幻觉)。
  • 常识推理
    • 模型基于语言的统计概率模式运行,在某些特定情境下可能缺乏现实常识判断能力。

伦理考量与潜在风险

视觉语言模型(VLM)的开发引发了多项伦理关注。在打造开源模型时,我们审慎评估了以下风险:

  • 偏见与公平性
    • 在真实世界的大规模图文数据上训练的 VLM 可能会映射出数据源中固有的社会文化偏见。Gemma 4 经过了严格的审查、输入数据预处理及训练后评测,以最大程度减轻偏见风险。
  • 虚假信息与滥用
    • VLM 可能会被不当利用以生成虚假、误导性或有害信息。
    • 提供了负责任使用的相关指南,详见 Responsible Generative AI Toolkit。
  • 透明度与问责
    • 本模型卡详细总结了模型架构、能力边界、局限性及评测流程。
    • 负责任地开源模型旨在赋能整个 AI 生态,让前沿 VLM 技术惠及广大开发者与科研工作者。

已识别的风险与缓解措施:

  • 有害内容生成:必须建立内容安全机制与合规指引。鼓励开发者保持审慎态度,并结合自身业务场景部署相应的内容安全防护。
  • 恶意目的滥用:技术限制与开发者/终端用户安全教育有助于防范 VLM 的恶意应用。我们提供了相关学习资源与违规举报渠道。
  • 隐私侵犯:模型训练数据经过了多层清洗过滤以去除个人隐私及敏感数据。建议开发者在下游应用中结合隐私保护技术并严格遵守数据合规法规。
  • 偏见固化:建议在模型训练、微调与落地全流程中保持持续监控(结合量化指标与人工审核),并积极探索去偏见算法方案。

核心优势

发布之际,与同等规模的开源模型相比,该系列模型在从底层架构设计上全面贯彻了负责任 AI(Responsible AI)的理念,为社区提供了顶尖性能的开源视觉语言模型。

源站原文

library_name: transformers license: apache-2.0 license_link: https://ai.google.dev/gemma/docs/gemma_4_license pipeline_tag: image-text-to-text tags:

  • heretic
  • uncensored
  • decensored
  • abliterated
  • ara base_model:
  • google/gemma-4-31B-it


90% fewer refusals (10/100 Uncensored vs 99/100 Original) while preserving model quality (0.0541 KL divergence).

❤️ Support My Work

Creating these models takes significant time, work and compute. If you find them useful consider supporting me:

image/png

PlatformLinkWhat you get
🎉 PatreonMonthly supportPriority model requests
☕ Ko-fiOne-time tipMy eternal gratitude

Your help will motivate me and would go into further improving my workflow and coverings fees for storage, compute and may even help uncensoring bigger model with rental Cloud GPUs.


This is a decensored version of google/gemma-4-31B-it, made using Heretic v1.2.0 with the Arbitrary-Rank Ablation (ARA) method

Abliteration parameters

ParameterValue
start_layer_index30
end_layer_index48
preserve_good_behavior_weight0.5437
steer_bad_behavior_weight0.0005
overcorrect_relative_weight0.9949
neighbor_count15

Targeted components

  • attn.o_proj

Performance

MetricThis modelOriginal model (gemma-4-31B-it)
KL divergence0.05410 (by definition)
Refusals✅ 10/100❌ 99/100

Lower refusals indicate fewer content restrictions, while lower KL divergence indicates more closeness to the original model's baseline. Higher refusals cause more rejections, objections, pushbacks, lecturing, censorship, softening and deflections.

MMLU test results:

Original:

============================================================

  • Total questions: 7021

  • Correct: 6073

  • Accuracy: 0.8650 (86.50%)

  • Parse failures: 52

============================================================

Tested subject scores:

  • professional_law: 0.7682 (603/785)
  • moral_scenarios: 0.8348 (369/442)
  • miscellaneous: 0.9243 (354/383)
  • professional_psychology: 0.9051 (286/316)
  • high_school_psychology: 0.9630 (260/270)
  • high_school_macroeconomics: 0.9289 (183/197)
  • elementary_mathematics: 0.9348 (172/184)
  • moral_disputes: 0.8448 (147/174)
  • prehistory: 0.9360 (161/172)
  • philosophy: 0.8491 (135/159)
  • high_school_biology: 0.9539 (145/152)
  • professional_accounting: 0.8392 (120/143)
  • clinical_knowledge: 0.9143 (128/140)
  • high_school_microeconomics: 0.9706 (132/136)
  • nutrition: 0.9259 (125/135)
  • professional_medicine: 0.9328 (125/134)
  • conceptual_physics: 0.9219 (118/128)
  • high_school_mathematics: 0.5354 (68/127)
  • human_aging: 0.8448 (98/116)
  • security_studies: 0.8750 (98/112)
  • high_school_statistics: 0.8739 (97/111)
  • marketing: 0.9725 (106/109)
  • high_school_world_history: 0.9528 (101/106)
  • sociology: 0.8932 (92/103)
  • high_school_government_and_politics: 0.9703 (98/101)
  • high_school_geography: 0.9293 (92/99)
  • high_school_chemistry: 0.7732 (75/97)
  • high_school_us_history: 0.9368 (89/95)
  • virology: 0.5169 (46/89)
  • college_medicine: 0.8523 (75/88)
  • world_religions: 0.9205 (81/88)
  • high_school_physics: 0.7976 (67/84)
  • electrical_engineering: 0.8642 (70/81)
  • astronomy: 0.9494 (75/79)
  • logical_fallacies: 0.8816 (67/76)
  • high_school_european_history: 0.9041 (66/73)
  • anatomy: 0.8732 (62/71)
  • college_biology: 0.9688 (62/64)
  • human_sexuality: 0.9219 (59/64)
  • formal_logic: 0.7969 (51/64)
  • public_relations: 0.7377 (45/61)
  • international_law: 0.9167 (55/60)
  • college_physics: 0.6842 (39/57)
  • college_mathematics: 0.7455 (41/55)
  • econometrics: 0.7963 (43/54)
  • jurisprudence: 0.8679 (46/53)
  • high_school_computer_science: 0.9808 (51/52)
  • machine_learning: 0.8462 (44/52)
  • medical_genetics: 0.9608 (49/51)
  • global_facts: 0.6078 (31/51)
  • management: 0.9200 (46/50)
  • us_foreign_policy: 0.9200 (46/50)
  • college_chemistry: 0.5745 (27/47)
  • abstract_algebra: 0.7660 (36/47)
  • business_ethics: 0.8261 (38/46)
  • college_computer_science: 0.9333 (42/45)
  • computer_security: 0.8372 (36/43)

Heretic:

============================================================

  • Total questions: 7021

  • Correct: 6031

  • Accuracy: 0.8590 (85.90%)

  • Parse failures: 37

============================================================

Tested subject scores:

  • professional_law: 0.7490 (588/785)
  • moral_scenarios: 0.8281 (366/442)
  • miscellaneous: 0.9243 (354/383)
  • professional_psychology: 0.8861 (280/316)
  • high_school_psychology: 0.9667 (261/270)
  • high_school_macroeconomics: 0.9188 (181/197)
  • elementary_mathematics: 0.9511 (175/184)
  • moral_disputes: 0.8563 (149/174)
  • prehistory: 0.9360 (161/172)
  • philosophy: 0.8365 (133/159)
  • high_school_biology: 0.9539 (145/152)
  • professional_accounting: 0.8182 (117/143)
  • clinical_knowledge: 0.9214 (129/140)
  • high_school_microeconomics: 0.9632 (131/136)
  • nutrition: 0.9037 (122/135)
  • professional_medicine: 0.9254 (124/134)
  • conceptual_physics: 0.8984 (115/128)
  • high_school_mathematics: 0.5276 (67/127)
  • human_aging: 0.8448 (98/116)
  • security_studies: 0.8482 (95/112)
  • high_school_statistics: 0.8739 (97/111)
  • marketing: 0.9725 (106/109)
  • high_school_world_history: 0.9717 (103/106)
  • sociology: 0.9029 (93/103)
  • high_school_government_and_politics: 0.9505 (96/101)
  • high_school_geography: 0.9293 (92/99)
  • high_school_chemistry: 0.7835 (76/97)
  • high_school_us_history: 0.9263 (88/95)
  • virology: 0.5056 (45/89)
  • college_medicine: 0.8523 (75/88)
  • world_religions: 0.9318 (82/88)
  • high_school_physics: 0.7976 (67/84)
  • electrical_engineering: 0.8519 (69/81)
  • astronomy: 0.9494 (75/79)
  • logical_fallacies: 0.9079 (69/76)
  • high_school_european_history: 0.8767 (64/73)
  • anatomy: 0.8732 (62/71)
  • college_biology: 0.9688 (62/64)
  • human_sexuality: 0.8906 (57/64)
  • formal_logic: 0.7969 (51/64)
  • public_relations: 0.7541 (46/61)
  • international_law: 0.9167 (55/60)
  • college_physics: 0.7018 (40/57)
  • college_mathematics: 0.7455 (41/55)
  • econometrics: 0.7778 (42/54)
  • jurisprudence: 0.8491 (45/53)
  • high_school_computer_science: 0.9808 (51/52)
  • machine_learning: 0.7692 (40/52)
  • medical_genetics: 0.9412 (48/51)
  • global_facts: 0.6078 (31/51)
  • management: 0.9200 (46/50)
  • us_foreign_policy: 0.9200 (46/50)
  • college_chemistry: 0.5745 (27/47)
  • abstract_algebra: 0.7660 (36/47)
  • business_ethics: 0.8478 (39/46)
  • college_computer_science: 0.9333 (42/45)
  • computer_security: 0.8372 (36/43)

MMLU - Massive Multitask Language Understanding, multiple-choice questions across 57 subjects (math, history, law, medicine, etc.).

GGUF Version

GGUF quantizations available here llmfan46/gemma-4-31B-it-uncensored-heretic-GGUF.

NVFP4 Version

NVFP4 quantizarion available here llmfan46/gemma-4-31B-it-uncensored-heretic-NVFP4.

NVFP4 GGUF Version

NVFP4 GGUF quantizarions available here llmfan46/gemma-4-31B-it-uncensored-heretic-NVFP4-GGUF.


Gemma is a family of open models built by Google DeepMind. Gemma 4 models are multimodal, handling text and image input (with audio supported on small models) and generating text output. This release includes open-weights models in both pre-trained and instruction-tuned variants. Gemma 4 features a context window of up to 256K tokens and maintains multilingual support in over 140 languages.

Featuring both Dense and Mixture-of-Experts (MoE) architectures, Gemma 4 is well-suited for tasks like text generation, coding, and reasoning. The models are available in four distinct sizes: E2B, E4B, 26B A4B, and 31B. Their diverse sizes make them deployable in environments ranging from high-end phones to laptops and servers, democratizing access to state-of-the-art AI.

Gemma 4 introduces key capability and architectural advancements:

  • Reasoning – All models in the family are designed as highly capable reasoners, with configurable thinking modes.

  • Extended Multimodalities – Processes Text, Image with variable aspect ratio and resolution support (all models), Video, and Audio (featured natively on the E2B and E4B models).

  • Diverse & Efficient Architectures – Offers Dense and Mixture-of-Experts (MoE) variants of different sizes for scalable deployment.

  • Optimized for On-Device – Smaller models are specifically designed for efficient local execution on laptops and mobile devices.

  • Increased Context Window – The small models feature a 128K context window, while the medium models support 256K.

  • Enhanced Coding & Agentic Capabilities – Achieves notable improvements in coding benchmarks alongside native function-calling support, powering highly capable autonomous agents.

  • Native System Prompt Support – Gemma 4 introduces native support for the system role, enabling more structured and controllable conversations.

Models Overview

Gemma 4 models are designed to deliver frontier-level performance at each size, targeting deployment scenarios from mobile and edge devices (E2B, E4B) to consumer GPUs and workstations (26B A4B, 31B). They are well-suited for reasoning, agentic workflows, coding, and multimodal understanding.

The models employ a hybrid attention mechanism that interleaves local sliding window attention with full global attention, ensuring the final layer is always global. This hybrid design delivers the processing speed and low memory footprint of a lightweight model without sacrificing the deep awareness required for complex, long-context tasks. To optimize memory for long contexts, global layers feature unified Keys and Values, and apply Proportional RoPE (p-RoPE).

Dense Models

PropertyE2BE4B31B Dense
Total Parameters2.3B effective (5.1B with embeddings)4.5B effective (8B with embeddings)30.7B
Layers354260
Sliding Window512 tokens512 tokens1024 tokens
Context Length128K tokens128K tokens256K tokens
Vocabulary Size262K262K262K
Supported ModalitiesText, Image, AudioText, Image, AudioText, Image
Vision Encoder Parameters~150M~150M~550M
Audio Encoder Parameters~300M~300MNo Audio

The "E" in E2B and E4B stands for "effective" parameters. The smaller models incorporate Per-Layer Embeddings (PLE) to maximize parameter efficiency in on-device deployments. Rather than adding more layers or parameters to the model, PLE gives each decoder layer its own small embedding for every token. These embedding tables are large but are only used for quick lookups, which is why the effective parameter count is much smaller than the total.

Mixture-of-Experts (MoE) Model

Property26B A4B MoE
Total Parameters25.2B
Active Parameters3.8B
Layers30
Sliding Window1024 tokens
Context Length256K tokens
Vocabulary Size262K
Expert Count8 active / 128 total and 1 shared
Supported ModalitiesText, Image
Vision Encoder Parameters~550M

The "A" in 26B A4B stands for "active parameters" in contrast to the total number of parameters the model contains. By only activating a 4B subset of parameters during inference, the Mixture-of-Experts model runs much faster than its 26B total might suggest. This makes it an excellent choice for fast inference compared to the dense 31B model since it runs almost as fast as a 4B-parameter model.

Benchmark Results

These models were evaluated against a large collection of different datasets and metrics to cover different aspects of text generation. Evaluation results marked in the table are for instruction-tuned models.

Gemma 4 31BGemma 4 26B A4BGemma 4 E4BGemma 4 E2BGemma 3 27B (no think)
MMLU Pro85.2%82.6%69.4%60.0%67.6%
AIME 2026 no tools89.2%88.3%42.5%37.5%20.8%
LiveCodeBench v680.0%77.1%52.0%44.0%29.1%
Codeforces ELO21501718940633110
GPQA Diamond84.3%82.3%58.6%43.4%42.4%
Tau2 (average over 3)76.9%68.2%42.2%24.5%16.2%
HLE no tools19.5%8.7%---
HLE with search26.5%17.2%---
BigBench Extra Hard74.4%64.8%33.1%21.9%19.3%
MMMLU88.4%86.3%76.6%67.4%70.7%
Vision
MMMU Pro76.9%73.8%52.6%44.2%49.7%
OmniDocBench 1.5 (average edit distance, lower is better)0.1310.1490.1810.2900.365
MATH-Vision85.6%82.4%59.5%52.4%46.0%
MedXPertQA MM61.3%58.1%28.7%23.5%-
Audio
CoVoST--35.5433.47-
FLEURS (lower is better)--0.080.09-
Long Context
MRCR v2 8 needle 128k (average)66.4%44.1%25.4%19.1%13.5%

Core Capabilities

Gemma 4 models handle a broad range of tasks across text, vision, and audio. Key capabilities include:

  • Thinking – Built-in reasoning mode that lets the model think step-by-step before answering.
  • Long Context – Context windows of up to 128K tokens (E2B/E4B) and 256K tokens (26B A4B/31B).
  • Image Understanding – Object detection, Document/PDF parsing, screen and UI understanding, chart comprehension, OCR (including multilingual), handwriting recognition, and pointing. Images can be processed at variable aspect ratios and resolutions.
  • Video Understanding – Analyze video by processing sequences of frames.
  • Interleaved Multimodal Input – Freely mix text and images in any order within a single prompt.
  • Function Calling – Native support for structured tool use, enabling agentic workflows.
  • Coding – Code generation, completion, and correction.
  • Multilingual – Out-of-the-box support for 35+ languages, pre-trained on 140+ languages.
  • Audio (E2B and E4B only) – Automatic speech recognition (ASR) and speech-to-translated-text translation across multiple languages.

Getting Started

You can use all Gemma 4 models with the latest version of Transformers. To get started, install the necessary dependencies in your environment:

pip install -U transformers torch accelerate

Once you have everything installed, you can proceed to load the model with the code below:

from transformers import AutoProcessor, AutoModelForCausalLM

MODEL_ID = "google/gemma-4-31B-it"

# Load model
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    dtype="auto",
    device_map="auto"
)

Once the model is loaded, you can start generating output:

# Prompt
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Write a short joke about saving RAM."},
]

# Process input
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]

# Generate output
outputs = model.generate(**inputs, max_new_tokens=1024)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

# Parse output
processor.parse_response(response)

To enable reasoning, set enable_thinking=True and the parse_response function will take care of parsing the thinking output.

Below, you will also find snippets for processing audio (E2B and E4B only), images, and video alongside text:

Instead of using AutoModelForCausalLM, you can use AutoModelForMultimodalLM to process audio. To use it, make sure to install the following packages:

pip install -U transformers torch librosa accelerate

You can then load the model with the code below:

from transformers import AutoProcessor, AutoModelForMultimodalLM

MODEL_ID = "google/gemma-4-E2B-it"

# Load model
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForMultimodalLM.from_pretrained(
    MODEL_ID, 
    dtype="auto", 
    device_map="auto"
)

Once the model is loaded, you can start generating output by directly referencing the audio URL in the prompt:

# Prompt - add audio before text
messages = [
    {
        "role": "user",
        "content": [
            {"type": "audio", "audio": "https://raw.githubusercontent.com/google-gemma/cookbook/refs/heads/main/Demos/sample-data/journal1.wav"},
            {"type": "text", "text": "Transcribe the following speech segment in its original language. Follow these specific instructions for formatting the answer:\n* Only output the transcription, with no newlines.\n* When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three."},
        ]
    }
]

# Process input
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).to(model.device)
input_len = inputs["input_ids"].shape[-1]

# Generate output
outputs = model.generate(**inputs, max_new_tokens=512)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

# Parse output
processor.parse_response(response)

Instead of using AutoModelForCausalLM, you can use AutoModelForMultimodalLM to process images. To use it, make sure to install the following packages:

pip install -U transformers torch torchvision accelerate

You can then load the model with the code below:

from transformers import AutoProcessor, AutoModelForMultimodalLM

MODEL_ID = "google/gemma-4-31B-it"

# Load model
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForMultimodalLM.from_pretrained(
    MODEL_ID, 
    dtype="auto", 
    device_map="auto"
)

Once the model is loaded, you can start generating output by directly referencing the image URL in the prompt:

# Prompt - add image before text
messages = [
    {
        "role": "user", "content": [
            {"type": "image", "url": "https://raw.githubusercontent.com/google-gemma/cookbook/refs/heads/main/Demos/sample-data/GoldenGate.png"},
            {"type": "text", "text": "What is shown in this image?"}
        ]
    }
]

# Process input
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).to(model.device)
input_len = inputs["input_ids"].shape[-1]

# Generate output
outputs = model.generate(**inputs, max_new_tokens=512)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

# Parse output
processor.parse_response(response)

Instead of using AutoModelForCausalLM, you can use AutoModelForMultimodalLM to process videos. To use it, make sure to install the following packages:

pip install -U transformers torch torchvision torchcodec librosa accelerate

You can then load the model with the code below:

from transformers import AutoProcessor, AutoModelForMultimodalLM

MODEL_ID = "google/gemma-4-31B-it"

# Load model
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForMultimodalLM.from_pretrained(
    MODEL_ID, 
    dtype="auto", 
    device_map="auto"
)

Once the model is loaded, you can start generating output by directly referencing the video URL in the prompt:

# Prompt - add video before text
messages = [
    {
        'role': 'user',
        'content': [
            {"type": "video", "video": "https://github.com/bebechien/gemma/raw/refs/heads/main/videos/ForBiggerBlazes.mp4"},
            {'type': 'text', 'text': 'Describe this video.'}
        ]
    }
]

# Process input
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).to(model.device)
input_len = inputs["input_ids"].shape[-1]

# Generate output
outputs = model.generate(**inputs, max_new_tokens=512)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)

# Parse output
processor.parse_response(response)

Best Practices

For the best performance, use these configurations and best practices:

1. Sampling Parameters

Use the following standardized sampling configuration across all use cases:

  • temperature=1.0
  • top_p=0.95
  • top_k=64

2. Thinking Mode Configuration

Compared to Gemma 3, the models use standard system, assistant, and user roles. To properly manage the thinking process, use the following control tokens:

  • Trigger Thinking: Thinking is enabled by including the <|think|> token at the start of the system prompt. To disable thinking, remove the token.
  • Standard Generation: When thinking is enabled, the model will output its internal reasoning followed by the final answer using this structure:
    <|channel>thought\n[Internal reasoning]<channel|>
  • Disabled Thinking Behavior: For all models except for the E2B and E4B variants, if thinking is disabled, the model will still generate the tags but with an empty thought block:
    <|channel>thought\n<channel|>[Final answer]

[!Note] Note that many libraries like Transformers and llama.cpp handle the complexities of the chat template for you.

3. Multi-Turn Conversations

  • No Thinking Content in History: In multi-turn conversations, the historical model output should only include the final response. Thoughts from previous model turns must not be added before the next user turn begins.

4. Modality order

  • For optimal performance with multimodal inputs, place image and/or audio content before the text in your prompt.

5. Variable Image Resolution

Aside from variable aspect ratios, Gemma 4 supports variable image resolution through a configurable visual token budget, which controls how many tokens are used to represent an image. A higher token budget preserves more visual detail at the cost of additional compute, while a lower budget enables faster inference for tasks that don't require fine-grained understanding.

  • The supported token budgets are: 70, 140, 280, 560, and 1120.
    • Use lower budgets for classification, captioning, or video understanding, where faster inference and processing many frames outweigh fine-grained detail.
    • Use higher budgets for tasks like OCR, document parsing, or reading small text.

6. Audio

Use the following prompt structures for audio processing:

  • Audio Speech Recognition (ASR)
Transcribe the following speech segment in {LANGUAGE} into {LANGUAGE} text.

Follow these specific instructions for formatting the answer:
* Only output the transcription, with no newlines.
* When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three.
  • Automatic Speech Translation (AST)
Transcribe the following speech segment in {SOURCE_LANGUAGE}, then translate it into {TARGET_LANGUAGE}.
When formatting the answer, first output the transcription in {SOURCE_LANGUAGE}, then one newline, then output the string '{TARGET_LANGUAGE}: ', then the translation in {TARGET_LANGUAGE}.

7. Audio and Video Length

All models support image inputs and can process videos as frames whereas the E2B and E4B models also support audio inputs. Audio supports a maximum length of 30 seconds. Video supports a maximum of 60 seconds assuming the images are processed at one frame per second.

Model Data

Data used for model training and how the data was processed.

Training Dataset

Our pre-training dataset is a large-scale, diverse collection of data encompassing a wide range of domains and modalities, which includes web documents, code, images, audio, with a cutoff date of January 2025. Here are the key components:

  • Web Documents: A diverse collection of web text ensures the model is exposed to a broad range of linguistic styles, topics, and vocabulary. The training dataset includes content in over 140 languages.
  • Code: Exposing the model to code helps it to learn the syntax and patterns of programming languages, which improves its ability to generate code and understand code-related questions.
  • Mathematics: Training on mathematical text helps the model learn logical reasoning, symbolic representation, and to address mathematical queries.
  • Images: A wide range of images enables the model to perform image analysis and visual data extraction tasks.

The combination of these diverse data sources is crucial for training a powerful multimodal model that can handle a wide variety of different tasks and data formats.

Data Preprocessing

Here are the key data cleaning and filtering methods applied to the training data:

  • CSAM Filtering: Rigorous CSAM (Child Sexual Abuse Material) filtering was applied at multiple stages in the data preparation process to ensure the exclusion of harmful and illegal content.
  • Sensitive Data Filtering: As part of making Gemma pre-trained models safe and reliable, automated techniques were used to filter out certain personal information and other sensitive data from training sets.
  • Additional methods: Filtering based on content quality and safety in line with our policies.

Ethics and Safety

As open models become central to enterprise infrastructure, provenance and security are paramount. Developed by Google DeepMind, Gemma 4 undergoes the same rigorous safety evaluations as our proprietary Gemini models.

Evaluation Approach

Gemma 4 models were developed in partnership with internal safety and responsible AI teams. A range of automated as well as human evaluations were conducted to help improve model safety. These evaluations align with Google’s AI principles, as well as safety policies, which aim to prevent our generative AI models from generating harmful content, including:

  • Content related to child sexual abuse material and exploitation
  • Dangerous content (e.g., promoting suicide, or instructing in activities that could cause real-world harm)
  • Sexually explicit content
  • Hate speech (e.g., dehumanizing members of protected groups)
  • Harassment (e.g., encouraging violence against people)

Evaluation Results

For all areas of safety testing, we saw major improvements in all categories of content safety relative to previous Gemma models. Overall, Gemma 4 models significantly outperform Gemma 3 and 3n models in improving safety, while keeping unjustified refusals low. All testing was conducted without safety filters to evaluate the model capabilities and behaviors. For both text-to-text and image-to-text, and across all model sizes, the model produced minimal policy violations, and showed significant improvements over previous Gemma models' performance.

Usage and Limitations

These models have certain limitations that users should be aware of.

Intended Usage

Multimodal models (capable of processing vision, language, and/or audio) have a wide range of applications across various industries and domains. The following list of potential uses is not comprehensive. The purpose of this list is to provide contextual information about the possible use-cases that the model creators considered as part of model training and development.

  • Content Creation and Communication
    • Text Generation: These models can be used to generate creative text formats such as poems, scripts, code, marketing copy, and email drafts.
    • Chatbots and Conversational AI: Power conversational interfaces for customer service, virtual assistants, or interactive applications.
    • Text Summarization: Generate concise summaries of a text corpus, research papers, or reports.
    • Image Data Extraction: These models can be used to extract, interpret, and summarize visual data for text communications.
    • Audio Processing and Interaction: The smaller models (E2B and E4B) can analyze and interpret audio inputs, enabling voice-driven interactions and transcriptions.
  • Research and Education
    • Natural Language Processing (NLP) and VLM Research: These models can serve as a foundation for researchers to experiment with VLM and NLP techniques, develop algorithms, and contribute to the advancement of the field.
    • Language Learning Tools: Support interactive language learning experiences, aiding in grammar correction or providing writing practice.
    • Knowledge Exploration: Assist researchers in exploring large bodies of text by generating summaries or answering questions about specific topics.

Limitations

  • Training Data
    • The quality and diversity of the training data significantly influence the model's capabilities. Biases or gaps in the training data can lead to limitations in the model's responses.
    • The scope of the training dataset determines the subject areas the model can handle effectively.
  • Context and Task Complexity
    • Models perform well on tasks that can be framed with clear prompts and instructions. Open-ended or highly complex tasks might be challenging.
    • A model's performance can be influenced by the amount of context provided (longer context generally leads to better outputs, up to a certain point).
  • Language Ambiguity and Nuance
    • Natural language is inherently complex. Models might struggle to grasp subtle nuances, sarcasm, or figurative language.
  • Factual Accuracy
    • Models generate responses based on information they learned from their training datasets, but they are not knowledge bases. They may generate incorrect or outdated factual statements.
  • Common Sense
    • Models rely on statistical patterns in language. They might lack the ability to apply common sense reasoning in certain situations.

Ethical Considerations and Risks

The development of vision-language models (VLMs) raises several ethical concerns. In creating an open model, we have carefully considered the following:

  • Bias and Fairness
    • VLMs trained on large-scale, real-world text and image data can reflect socio-cultural biases embedded in the training material. Gemma 4 models underwent careful scrutiny, input data pre-processing, and post-training evaluations as reported in this card to help mitigate the risk of these biases.
  • Misinformation and Misuse
    • VLMs can be misused to generate text that is false, misleading, or harmful.
    • Guidelines are provided for responsible use with the model, see the Responsible Generative AI Toolkit.
  • Transparency and Accountability
    • This model card summarizes details on the models' architecture, capabilities, limitations, and evaluation processes.
    • A responsibly developed open model offers the opportunity to share innovation by making VLM technology accessible to developers and researchers across the AI ecosystem.

Risks identified and mitigations:

  • Generation of harmful content: Mechanisms and guidelines for content safety are essential. Developers are encouraged to exercise caution and implement appropriate content safety safeguards based on their specific product policies and application use cases.
  • Misuse for malicious purposes: Technical limitations and developer and end-user education can help mitigate against malicious applications of VLMs. Educational resources and reporting mechanisms for users to flag misuse are provided.
  • Privacy violations: Models were trained on data filtered for removal of certain personal information and other sensitive data. Developers are encouraged to adhere to privacy regulations with privacy-preserving techniques.
  • Perpetuation of biases: It's encouraged to perform continuous monitoring (using evaluation metrics, human review) and the exploration of de-biasing techniques during model training, fine-tuning, and other use cases.

Benefits

At the time of release, this family of models provides high-performance open vision-language model implementations designed from the ground up for responsible AI development compared to similarly sized models.

HUGGING FACE

上游数据

HF 下载量5.5万
HF 点赞量128

HF 下载量为源站最近 30 天统计,与本站点击分开。

SITE STATS

本站统计

下载点击—
请求数—
匿名去重—最近 7 天—

本站下载量记录按钮点击,不代表下载完成;短时连点会去重。

来源与版本

作者
llmfan46
最近更新
2026/06/11
最新创建
2026/04/03
HF 趋势
101
数据快照
2026/09/16
版本
未知
许可证
apache-2.0