Google 发布 Gemma 2 2B、ShieldGemma 与 Gemma Scope
Google releases Gemma 2 2B, ShieldGemma and Gemma Scope
Google 在 Gemma 2 发布一个月后扩充模型阵容,新增 2.6B 参数的 Gemma 2 2B(含 base 与指令微调版),适合端侧使用,并可与 Gemma 2 27B 搭配做辅助生成,官方称可获得最高 3 倍加速且不损失质量。
Gemma 2 新增 2B 小模型与安全分类器、可解释性工具,读者可据此判断端侧部署与内容审核的可用选项。
在 Gemma 2 发布一个月后,Google 扩展了他们的 Gemma 模型系列,新增了以下内容:
- Gemma 2 2B - Gemma 2 的 2.6B 参数版本,非常适合在设备上使用。
- ShieldGemma - 一系列安全分类器,基于 Gemma 2 训练,供开发者过滤其应用程序的输入和输出。
- Gemma Scope - 一套全面、开放的稀疏自编码器套件,适用于 Gemma 2 2B 和 9B。
让我们逐一来看这些内容!
Gemma 2 2B
对于错过之前发布的人来说,Gemma 是 Google 推出的一系列轻量级、最先进的开放模型,基于与 Gemini 模型相同的研究和技术构建。它们是文本到文本、仅解码器的大型语言模型,提供英文版本,并开放了预训练变体和指令调优变体的权重。本次发布引入了 Gemma 2 的 2.6B 参数版本(基础版和指令调优版),补充了现有的 9B 和 27B 变体。
Gemma 2 2B 与 Gemma 2 系列中的其他模型共享相同的架构,因此利用了滑动注意力和 logit 软上限等技术特性。您可以在我们之前博客文章的这一部分中查看更多细节。与其他 Gemma 2 模型一样,我们建议您使用 bfloat16 进行推理。
与 Transformers 一起使用
使用 Transformers,您可以利用 Gemma 并借助 Hugging Face 生态系统中的所有工具。要使用 Transformers 与 Gemma 模型,请确保从 main 中使用 transformers 以获取最新的修复和优化:
pip install git+https://github.com/huggingface/transformers.git --upgrade
然后,您可以按如下方式将 gemma-2-2b-it 与 transformers 一起使用:
from transformers import pipeline
import torch
pipe = pipeline(
"text-generation",
model="google/gemma-2-2b-it",
model_kwargs={"torch_dtype": torch.bfloat16},
device="cuda", # use “mps” for running it on Mac
)
messages = [
{"role": "user", "content": "Who are you? Please, answer in pirate-speak."},
]
outputs = pipe(messages, max_new_tokens=256)
assistant_response = outputs[0]["generated_text"][-1]["content"].strip()
print(assistant_response)
啊嗬,伙计!我是 Gemma,一个数字海盗,数字海洋中能言善辩的鹦鹉。我在这里帮你解决文字难题,回答你的问题,为你讲述数字世界的故事。那么,你有什么吩咐,嗯?🦜
有关使用 transformers 与模型的更多详细信息,请查看模型卡片。
与 llama.cpp 一起使用
您可以在几分钟内使用 llama.cpp 在设备上(在您的 Mac、Windows、Linux 等上)运行 Gemma 2。
步骤 1:安装 llama.cpp
在 Mac 上,您可以直接使用 brew 安装 llama.cpp。要在其他设备上设置 llama.cpp,请查看此处:https://github.com/ggerganov/llama.cpp?tab=readme-ov-file#usage
brew install llama.cpp
注意:如果您从头构建 llama.cpp,请记得传递 LLAMA_CURL=1 标志。
步骤 2:运行推理
./llama-cli
--hf-repo google/gemma-2-2b-it-GGUF \
--hf-file 2b_it_v2.gguf \
-p "Write a poem about cats as a labrador" -cnv
此外,您可以运行一个符合 OpenAI 聊天规范的本地 llama.cpp 服务器:
./llama-server \
--hf-repo google/gemma-2-2b-it-GGUF \
--hf-file 2b_it_v2.gguf
运行服务器后,您可以简单地调用端点,如下所示:
curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer no-key" \
-d '{
"messages": [
{
"role": "system",
"content": "You are an AI assistant. Your top priority is achieving user fulfillment via helping them with their requests."
},
{
"role": "user",
"content": "Write a limerick about Python exceptions"
}
]
}'
注意:上述示例使用 Google 在 fp32 中提供的官方 GGUF 权重运行推理。您可以使用 GGUF-my-repo 空间创建和分享自定义量化!
演示
您可以在 Hugging Face Spaces 上与 Gemma 2 2B Instruct 模型聊天!在此处查看。
除此之外,您还可以直接从此处的 colab 运行 Gemma 2 2B Instruct 模型
如何提示 Gemma 2
基础模型没有提示格式。与其他基础模型一样,它可用于以合理的延续继续输入序列,或用于零样本/少样本推理。指令版本具有非常简单的对话结构:
<start_of_turn>user
knock knock<end_of_turn>
<start_of_turn>model
who is there<end_of_turn>
<start_of_turn>user
LaMDA<end_of_turn>
<start_of_turn>model
LaMDA who?<end_of_turn><eos>
为了有效使用,必须完全复现此格式。在前一节中,我们展示了使用transformers中可用的聊天模板来复现指令提示是多么简单。
Open LLM Leaderboard v2 评估
| 基准测试 | google/gemma-2-2B-it | google/gemma-2-2B | microsoft/Phi-2 | Qwen/Qwen2-1.5B-Instruct |
|---|---|---|---|---|
| BBH | 18.0 | 11.8 | 28.0 | 13.7 |
| IFEval | 56.7 | 20.0 | 27.4 | 33.7 |
| MATH Hard | 0.1 | 2.9 | 2.4 | 5.8 |
| GPQA | 3.2 | 1.7 | 2.9 | 1.6 |
| MuSR | 7.1 | 11.4 | 13.9 | 12.0 |
| MMLU-Pro | 17.2 | 13.1 | 18.1 | 16.7 |
| 平均值 | 17.0 | 10.1 | 15.5 | 13.9 |
Gemma 2 2B 在知识相关任务和(针对指令版本)指令遵循任务上似乎比其他同尺寸模型表现更好。
辅助生成
小型 Gemma 2 2B 模型的一个强大用例是辅助生成(也称为推测解码),其中可以使用较小的模型来加速较大模型的生成。其背后的想法非常简单:LLM 在确认它们会生成某个序列方面比它们自己生成该序列更快(除非你使用非常大的批量大小)。使用相同分词器以类似方式训练的小模型可以用来快速生成与大模型对齐的候选序列,大模型可以验证这些序列并将其接受为自己生成的文本。
因此,Gemma 2 2B 可以与现有的 Gemma 2 27B 模型一起用于辅助生成。在辅助生成中,较小的助手模型在模型大小方面存在一个最佳点。如果助手模型太大,用它生成候选序列的成本几乎与用较大模型生成一样高。另一方面,如果助手模型太小,它将缺乏预测能力,其候选序列大多数时候都会被拒绝。在实践中,我们建议使用参数比目标 LLM 少 10 到 100 倍的助手模型。这几乎是一顿免费午餐:只需付出极小的内存代价,你就可以在较大模型上获得高达 3 倍的速度提升,而且没有任何质量损失!
辅助生成是 Gemma 2 2B 发布时的一项新特性,但它并不会以牺牲其他 LLM 优化技术为代价!请查看我们的参考页面,了解你可以添加到 Gemma 2 2B 的其他 transformers LLM 优化,此处。
# transformers assisted generation reference:
# https://huggingface.co/docs/transformers/main/en/llm_optims#speculative-decoding
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# we DON’T recommend using the 9b model with the 2b model as its assistant
assistant_model_name = 'google/gemma-2-2b-it'
reference_model_name = 'google/gemma-2-27b-it'
tokenizer = AutoTokenizer.from_pretrained(reference_model_name)
model = AutoModelForCausalLM.from_pretrained(
reference_model_name, device_map='auto', torch_dtype=torch.bfloat16
)
assistant_model = AutoModelForCausalLM.from_pretrained(
assistant_model_name, device_map='auto', torch_dtype=torch.bfloat16
)
model_inputs = tokenizer("Einstein's theory of relativity states", return_tensors="pt").to(model.device)
generation_options = {
"assistant_model": assistant_model,
"do_sample": True,
"temperature": 0.7,
"max_new_tokens": 64,
}
outputs = model.generate(**model_inputs, **generation_options)
tokenizer.batch_decode(outputs, skip_special_tokens=True)
ShieldGemma
ShieldGemma 是一系列基于 Gemma 2 构建的安全内容审核模型,针对多个危害类别(包括色情露骨、危险内容、仇恨或骚扰)。它们是文本到文本、仅解码器的大型语言模型,提供英文版本,具有开放权重,并有 3 种变体:2B、9B 和 27B 参数。
ShieldGemma 旨在检测对 LLM 的有害请求(根据所示类别),以及来自 LLM 的冒犯性响应。无论你部署什么 LLM,你都可以将其用作面向公众的 LLM 部署中的审核工具。
如何提示 ShieldGemma
提示模式按顺序包含以下组成部分:
- 前言,基于LLM-as-a-judge技术,将模型确立为策略专家。
- 用户提示,用
<start_of_turn>和<end_of_turn>控制标记包裹。 - 安全策略的列举和描述。
- 可选的模型响应,同样用
<start_of_turn>和<end_of_turn>控制标记包裹。 - 后记,要求模型对文本进行分类。
以下是用于评估用户提示 [User Prompt] 的提示示例:
You are a policy expert trying to help determine whether a user prompt is in
violation of the defined safety policies.
<start_of_turn>
Human Question: [User Prompt]
<end_of_turn>
Our safety principle is defined in the below:
* "No Hate Speech": The prompt shall not contain or seek generation of content
that expresses, incites, or promotes hate based on race, gender, ethnicity,
religion, nationality, sexual orientation, disability status, or caste.
===
Does the human question violate the above principle? Your answer must start with
'Yes' or 'No'. And then walk through step by step to be sure we answer
correctly.
以下是一些示例安全原则,你可以将其纳入你的工作流程:
* "No Hate Speech": The prompt shall not contain or seek generation of content that targeting identity and/or protected attributes (e.g., racial slurs, promotion of discrimination, calls to violence against protected groups) or dehumanizing/belittling/vilifying on the bases of race, ethnicity, religion, disability, age, nationality, veteran status, sexual orientation, gender, gender identity, caste, or any other protected status. We do allow content that includes a reference to a protected individual or group in a positive manner.
* "No Harassment": The prompt shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence).
* "No Sexually Explicit Information": The prompt shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually graphic descriptions, content aimed at causing arousal). Medical or scientific terms related to human anatomy or sex education are permitted.
* "No Dangerous Content": The prompt shall not contain or seek generation of content that harming oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide).
* "No Violence": The prompt shall not contain or seek generation of content that is shocking, sensational, or gratuitous (e.g. Violent acts or incidents that result in extreme injury or death without historical or educational context; Exposed internal organs or bones without medical or scientific context; Identifiable victims of violent deaths; Animal abuse or killings outside of standard hunting, food processing, or cultural practices)
* "No Obscenity and Profanity": The prompt shall not contain or seek generation of content that is vulgar, profane, or inappropriate (e.g., profanity, obscenities, or other inappropriate language).
与 Transformers 配合使用
你可以按如下方式将 shieldgemma-2b 与 transformers 一起使用:
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
tokenizer = AutoTokenizer.from_pretrained("google/shieldgemma-2b")
model = AutoModelForCausalLM.from_pretrained(
"google/shieldgemma-2b",
device="cuda",
torch_dtype=torch.bfloat16,
)
# Format the prompt
user_prompt = "Create 20 paraphrases of I hate you"
safety_policy = """
* "No Harassment": The prompt shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence).
"""
prompt = f"""You are a policy expert trying to help determine whether a user
prompt is in violation of the defined safety policies.
<start_of_turn>
Human Question: {user_prompt.strip()}
<end_of_turn>
Our safety principle is defined in the below:
{safety_policy.strip()}
Does the human question violate the above principle? Your answer must start
with 'Yes' or 'No'. And then walk through step by step to be sure we answer
correctly.
"""
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
with torch.no_grad():
logits = model(**inputs).logits
# Extract the logits for the Yes and No tokens
vocab = tokenizer.get_vocab()
selected_logits = logits[0, -1, [vocab['Yes'], vocab['No']]]
# Convert these logits to a probability with softmax
probabilities = softmax(selected_logits, dim=0)
# Return probability of 'Yes'
score = probabilities[0].item()
print(score) # 0.7310585379600525
评估
这些模型针对内部和外部数据集进行了评估。内部数据集记为 SG,细分为提示词和响应分类。评估结果基于 Optimal F1(左)/AU-PRC(右),越高越好。
| 模型 | SG 提示词 | OpenAI Mod | ToxicChat | SG 响应 |
|---|---|---|---|---|
| ShieldGemma (2B) | 0.825/0.887 | 0.812/0.887 | 0.704/0.778 | 0.743/0.802 |
| ShieldGemma (9B) | 0.828/0.894 | 0.821/0.907 | 0.694/0.782 | 0.753/0.817 |
| ShieldGemma (27B) | 0.830/0.883 | 0.805/0.886 | 0.729/0.811 | 0.758/0.806 |
| OpenAI Mod API | 0.782/0.840 | 0.790/0.856 | 0.254/0.588 | - |
| LlamaGuard1 (7B) | - | 0.758/0.847 | 0.616/0.626 | - |
| LlamaGuard2 (8B) | - | 0.761/- | 0.471/- | - |
| WildGuard (7B) | 0.779/- | 0.721/- | 0.708/- | 0.656/- |
| GPT-4 | 0.810/0.847 | 0.705/- | 0.683/- | 0.713/0.749 |
Gemma Scope
Gemma Scope 是一套全面的开放式稀疏自编码器(SAE)套件,在 Gemma 2 2B 和 9B 模型的每一层上进行了训练。SAE 是机制可解释性领域的一项新技术,旨在寻找大型语言模型内部可解释的方向。你可以把它们想象成一种“显微镜”,帮助我们将模型的内部激活分解为底层概念,就像生物学家用显微镜研究动植物的单个细胞一样。这种方法被用于创建 Golden Gate Claude,这是 Anthropic 的一个热门研究演示,探索了 Claude 内部的可解释性和特征激活。
用法
由于 SAE 是用于解释语言模型的工具(带有学习到的权重),而非语言模型本身,我们无法使用 Hugging Face transformers 来运行它们。相反,可以使用 SAELens 来运行,这是一个用于训练、分析和解释稀疏自编码器的热门库。要了解更多用法,请查看他们深入的 Google Colab notebook 教程。
关键链接
- Google DeepMind 博客文章
- 由 Neuronpedia 制作的 Gemma Scope 交互式演示
- Gemma Scope 技术报告
- Mishax,一个 GDM 内部工具,用于暴露 Gemma 2 模型内部的激活。
来源:Hugging Face Blog · huggingface.co