Google 發佈 Gemma 2 2B、ShieldGemma 和 Gemma Scope
Google releases Gemma 2 2B, ShieldGemma and Gemma Scope
Google 發佈 Gemma 2 2B、ShieldGemma 安全分類模型及 Gemma Scope 稀疏自編碼器套件。Gemma 2 2B 有 2.6B 參數,補充既有 9B、27B 版本,並可作 Gemma 2 27B 的輔助模型,最高提速 3x 且不損失品質。
這次更新同時涵蓋小型模型部署、安全內容分類與模型內部分析,讀者可據此比較 Gemma 系列在推理、安全防護及可解釋性研究中的用途。
Google 發布 Gemma 2 一個月後,擴充 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 模型,請使用 transformers 的 main 分支版本,以取得最新修正和最佳化:
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 提供的官方 GGUF 權重,以 fp32 執行推理。你可以在 GGUF-my-repo Space 建立並分享自訂量化版本!
示範
你可以在 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 的一項強大用途是輔助生成(亦稱推測解碼),即使用較小的模型加快較大型模型的生成速度。背後概念相當簡單:除非使用非常大的批次大小,否則大型語言模型確認某段序列是否會由自己生成,比直接生成該序列更快。使用相同 tokenizer、以相似方式訓練的小型模型,可以快速產生與大型模型輸出相符的候選序列,再由大型模型驗證並接受為自己的生成內容。
因此,Gemma 2 2B 可配合現有的 Gemma 2 27B 模型進行輔助生成。選擇較小的輔助模型時,存在一個理想的規模平衡點。如果輔助模型太大,用它生成候選序列的成本就會接近大型模型;相反,如果輔助模型太小,它的預測能力不足,候選序列大多會被拒絕。實際上,我們建議輔助模型的參數量比目標大型語言模型少 10 至 100 倍。這幾乎等於免費提升效能:只需付出少量額外記憶體,就能令大型模型加快最多 3 倍,而且不會損失品質!
Gemma 2 2B 發布時首次引入輔助生成,但不會影響其他大型語言模型最佳化技術!請參閲參考頁面,瞭解可套用至 Gemma 2 2B 的其他 transformers 大型語言模型最佳化方法這裏。
# 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 旨在偵測向大型語言模型提出的有害請求(按指定類別分類),以及模型產生的不當回應。無論你部署哪款大型語言模型,都可以在面向公眾的部署環境中使用 ShieldGemma 作審核工具。
如何向 ShieldGemma 提示
提示模式依次包含以下部分:
- 前言:根據 LLM-as-a-judge 技術,把模型設定為政策專家。
- 使用者提示:以
<start_of_turn>和<end_of_turn>控制 token 包起來。 - 列出並描述安全政策。
- 可選的模型回應:同樣以
<start_of_turn>和<end_of_turn>控制 token 包起來。 - 結語:要求模型分類文字。
以下是用來評估使用者提示 [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 表示,細分為提示分類和回應分類。評估結果以最佳 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 是機制可解釋性研究中的新技術,旨在大型語言模型中找出可解釋的方向。你可以把它們想像成「顯微鏡」,協助我們把模型的內部啟動拆解為背後的概念,正如生物學家使用顯微鏡研究動植物的個別細胞。Anthropic 的熱門研究示範 Golden Gate Claude 亦採用這種方法,探索 Claude 中的可解釋性和特徵啟動。
使用方法
SAE 是用來解釋語言模型的工具(具有學習所得的權重),而非語言模型本身,因此不能使用 Hugging Face transformers 執行。你可以改用熱門函式庫 SAELens,訓練、分析和解釋稀疏自編碼器。想了解更多用法,請參閲這份內容深入的 Google Colab 筆記本教學。
重要連結
- Google DeepMind 網誌文章
- Gemma Scope 互動示範由 Neuronpedia 製作
- Gemma Scope 技術報告
- Mishax,GDM 內部工具,用來顯示 Gemma 2 模型的內部啟動。
來源:Hugging Face Blog · huggingface.co