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

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

HF 源站

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

Image-Text-to-TextGGUFLicense: apache-2.031Btransformershereticuncensoreddecensoredabliteratedaraconversational
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:
  • llmfan46/gemma-4-31B-it-uncensored-heretic


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

❤️ 支持我的工作

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

image/png

平台链接您将获得
🎉 Patreon按月支持优先模型定制请求
☕ Ko-fi单次赞助我无尽的感激

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


llmfan46/gemma-4-31B-it-uncensored-heretic 的 GGUF 量化版本。

这是一个基于 google/gemma-4-31B-it 的去审查版本,使用 Heretic v1.2.0 以及 任意秩消融(Arbitrary-Rank Ablation, ARA) 方法制作

消融参数(Abliteration parameters)

参数数值
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)

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

更低的拒绝率表示内容限制更少,而更低的 KL 散度表示越贴近原始模型的基准性能。较高的拒绝率会导致更多的拒绝回答、异议反驳、说教批评、内容审查、避重就轻以及话题转移。

MMLU 测试结果:

原始模型(Original):

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

  • 题目总数(Total questions): 7021

  • 正确答对(Correct): 6073

  • 准确率(Accuracy): 0.8650 (86.50%)

  • 解析失败(Parse failures): 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.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

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

各学科测试得分:

  • 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 个学科(数学、历史、法律、医学等)的多项选择题基准测试。


量化版本(Quantizations)

文件名量化级别说明
gemma-4-31B-it-uncensored-heretic-BF16.ggufBF16全精度
gemma-4-31B-it-uncensored-heretic-Q8_0.ggufQ8_0接近无损,推荐
gemma-4-31B-it-uncensored-heretic-Q6_K.ggufQ6_K极高品质
gemma-4-31B-it-uncensored-heretic-Q5_K_M.ggufQ5_K_M良好平衡
gemma-4-31B-it-uncensored-heretic-Q5_K_S.ggufQ5_K_S较小体积 Q5
gemma-4-31B-it-uncensored-heretic-Q4_K_M.ggufQ4_K_M显存受限时推荐
gemma-4-31B-it-uncensored-heretic-Q4_K_S.ggufQ4_K_S较小体积 Q4
gemma-4-31B-it-uncensored-heretic-Q3_K_L.ggufQ3_K_L低显存占用,质量尚可
gemma-4-31B-it-uncensored-heretic-Q3_K_M.ggufQ3_K_M低显存占用,更小体积

视觉投影器(Vision Projector)

文件名量化级别说明
gemma-4-31B-it-mmproj-BF16.ggufBF16原生精度

视觉/多模态功能必须搭配视觉投影器(Vision Projector)文件。请与上述任意量化模型一同使用。

使用方法(Usage)

支持与 llama.cpp、LM Studio、Ollama 以及其他兼容 GGUF 的工具配合使用。


Gemma 是由 Google DeepMind 构建的一系列开放模型。Gemma 4 模型具备多模态能力,可处理文本和图像输入(小型模型还支持音频输入)并生成文本输出。本系列发布包含了预训练和指令微调两种形态的开放权重模型。Gemma 4 拥有高达 256K tokens 的上下文窗口,并保持对超过 140 种语言的多语言支持。

Gemma 4 拥有稠密(Dense)和混合专家(MoE)两种架构,非常适合文本生成、编程和推理等任务。模型提供四种不同尺寸:E2B、E4B、26B A4B 以及 31B。丰富的尺寸使其能够部署在从高端手机、笔记本电脑到服务器的各类环境中,让最前沿的 AI 技术触手可及。

Gemma 4 引入了多项关键能力与架构突破:

  • 深度推理 – 该系列中的所有模型均被设计为具备强大推理能力的模型,支持可配置的思考模式。

  • 扩展多模态 – 处理文本、具备可变长宽比与分辨率支持的图像(所有模型)、视频,以及音频(E2B 和 E4B 模型原生支持)。

  • 多样且高效的架构 – 提供不同尺寸的稠密与混合专家(MoE)变体,实现灵活扩展部署。

  • 针对端侧设备优化 – 较小尺寸的模型专门针对笔记本电脑和移动设备上的高效本地运行进行了设计。

  • 更大的上下文窗口 – 小型模型支持 128K 上下文窗口,中型模型支持高达 256K 上下文窗口。

  • 增强的代码与智能体(Agentic)能力 – 在编程基准测试中取得显著提升,并具备原生函数调用(Function Calling)支持,助力构建高能力自主智能体。

  • 原生系统提示词支持 – Gemma 4 引入了对 system 角色的原生支持,能够实现结构更清晰、可控性更高的对话交互。

模型概览

Gemma 4 旨在为各种尺寸的模型提供前沿级性能,覆盖从移动端与边缘设备(E2B、E4B)到消费级 GPU 与工作站(26B A4B、31B)的多种部署场景。它们非常适合推理、智能体工作流、代码生成以及多模态理解。

模型采用了一种混合注意力机制,将局部滑动窗口注意力与全局注意力交替穿插,确保最后一层始终是全局注意力。这种混合设计兼具轻量模型的处理速度与低显存占用,同时不失处理复杂长上下文任务所需的深度全局感知能力。为了优化长上下文的内存占用,全局层采用了统一的 Keys 和 Values,并应用了比例旋转位置编码(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 拥有自己的专属小型嵌入。这些嵌入表虽然占用空间,但仅用于快速查找,这就是为什么有效参数量远小于总参数量的原因。

混合专家模型(Mixture-of-Experts, MoE)

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

26B A4B 中的 "A" 代表推理时实际激活的“激活参数(active parameters)”,区别于模型包含的总参数量。由于在推理期间仅激活 4B 的参数子集,该混合专家模型的运行速度远快于其 26B 总量所暗示的速度。与 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%
视觉能力 (Vision)
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%-
音频能力 (Audio)
CoVoST--35.5433.47-
FLEURS (越低越好)--0.080.09-
长上下文 (Long Context)
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(包括多语言)、手写识别与点选定位(pointing)。支持多种长宽比和分辨率的图像输入。
  • 视频理解(Video Understanding) – 通过连续帧序列对视频内容进行分析。
  • 图文交错输入(Interleaved Multimodal Input) – 支持在单条提示词中任意顺序自由混合文本与图像。
  • 函数调用(Function Calling) – 原生支持结构化工具调用,助力智能体工作流。
  • 编程能力(Coding) – 代码生成、代码补全与代码纠错。
  • 多语言支持(Multilingual) – 开箱即用支持 35+ 种语言,预训练覆盖 140+ 种语言。
  • 音频处理(仅 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 即可生成输出:

# Prompt - 在文本前添加音频
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 即可生成输出:

# Prompt - 在文本前添加图像
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 即可生成输出:

# Prompt - 在文本前添加视频
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. 思考模式配置

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

  • 触发思考: 在系统提示词(system prompt)开头添加 <|think|> token 即可启用思考。如需禁用思考,移除该 token 即可。
  • 标准生成格式: 启用思考后,模型将输出内部推理过程,紧接着输出最终答案,结构如下:
    <|channel>thought [内部推理内容]<channel|>
  • 禁用思考时的行为: 除 E2B 和 E4B 变体外,对于其他所有模型,即使禁用了思考,模型仍会生成标签,但内容为一个空的思考块:
    <|channel>thought <channel|>[最终回答]

[!Note] 请注意,Transformers 和 llama.cpp 等众多开源库已在后台为您处理好了对话模板的复杂细节。

3. 多轮对话

  • 历史记录中不保留思考内容:在多轮对话中,以往轮次的模型输出应仅包含最终回答。在下一轮用户提问开始前,切勿添加前序模型轮次的思考内容。

4. 模态排列顺序

  • 为了在多模态输入下获得最佳表现,请在提示词中将图像和/或音频内容放置在文本之前。

5. 可变图像分辨率

除支持多种长宽比外,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 预训练模型安全可靠的一环,采用自动化技术从训练集中过滤了特定的个人身份信息和其他敏感数据。
  • 其他过滤手段:根据我们的政策进行了基于内容质量和安全性的过滤。

伦理与安全

随着开源模型逐渐成为企业基础设施的核心,模型溯源与安全性至关重要。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 可能会被滥用于生成虚假、误导性或有害的文本内容。
    • 我们为模型的负责任使用提供了指南,详情参见 负责任生成式 AI 工具包(Responsible Generative AI Toolkit)。
  • 透明度与问责制
    • 本模型卡概述了模型架构、能力、局限性以及评测流程的详细信息。
    • 一个以负责任态度开发的开放模型,通过让整个 AI 生态系统中的开发者和研究人员都能接触到前沿 VLM 技术,提供了共享创新的宝贵机遇。

识别的风险与缓解措施:

  • 有害内容的生成:内容安全机制与准则至关重要。鼓励开发者保持审慎态度,并根据其具体的产品政策和应用场景部署适当的内容安全防护措施。
  • 恶意目的的滥用:技术层面的限制以及对开发者和最终用户的教育有助于防范 VLM 的恶意应用。我们提供了教育资源以及供用户举报滥用行为的反馈机制。
  • 侵犯隐私:模型训练所用数据已过滤移除了某些个人身份信息和其他敏感数据。鼓励开发者通过采用隐私保护技术遵守各项隐私法规。
  • 偏见的持续存在:鼓励在模型训练、微调及其他应用过程中进行持续监控(利用评测指标、人工审核)并探索去偏技术。

核心优势

在发布之时,与同等尺寸的模型相比,该系列模型提供了从头开始专为负责任 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:
  • llmfan46/gemma-4-31B-it-uncensored-heretic


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.


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

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.).


Quantizations

FilenameQuantDescription
gemma-4-31B-it-uncensored-heretic-BF16.ggufBF16Full precision
gemma-4-31B-it-uncensored-heretic-Q8_0.ggufQ8_0Near-lossless, recommended
gemma-4-31B-it-uncensored-heretic-Q6_K.ggufQ6_KExcellent quality
gemma-4-31B-it-uncensored-heretic-Q5_K_M.ggufQ5_K_MGood balance
gemma-4-31B-it-uncensored-heretic-Q5_K_S.ggufQ5_K_SSmaller Q5
gemma-4-31B-it-uncensored-heretic-Q4_K_M.ggufQ4_K_MGood for limited VRAM
gemma-4-31B-it-uncensored-heretic-Q4_K_S.ggufQ4_K_SSmaller Q4
gemma-4-31B-it-uncensored-heretic-Q3_K_L.ggufQ3_K_LLow VRAM, decent quality
gemma-4-31B-it-uncensored-heretic-Q3_K_M.ggufQ3_K_MLow VRAM, smaller

Vision Projector

FilenameQuantDescription
gemma-4-31B-it-mmproj-BF16.ggufBF16Native precision

A Vision Projector File is Required for vision/multimodal capabilities. Use alongside any quantization above.

Usage

Works with llama.cpp, LM Studio, Ollama, and other GGUF-compatible tools.


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 下载量7.4万
HF 点赞量187

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

SITE STATS

本站统计

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

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

来源与版本

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