谷歌釋出 Gemma 2 2B、ShieldGemma 和 Gemma Scope

釋出於 2024 年 7 月 31 日
在 GitHub 上更新

Gemma 2 釋出一個月後,谷歌擴充套件了其 Gemma 模型系列,新增了以下內容:

  • Gemma 2 2B - Gemma 2 的 2.6B 引數版本,是裝置端使用的絕佳選擇。
  • ShieldGemma - 一系列基於 Gemma 2 訓練的安全分類器,供開發者過濾其應用程式的輸入和輸出。
  • Gemma Scope - 一套用於 Gemma 2 2B 和 9B 的全面開放的稀疏自編碼器套件。

接下來我們逐一介紹這些模型!

Gemma 2 2B

對於那些錯過了之前釋出的人來說,Gemma 是谷歌推出的一系列輕量級、最先進的開放模型,它們採用與 Gemini 模型相同的研究和技術構建而成。它們是文字到文字、僅解碼器的大型語言模型,提供英文版本,並開放了預訓練變體和指令微調變體的權重。此次釋出引入了 Gemma 2 的 2.6B 引數版本(基礎版指令微調版),補充了現有的 9B 和 27B 版本。

Gemma 2 2B 與 Gemma 2 系列中的其他模型共享相同的架構,因此利用了滑動注意力(sliding attention)和 Logit 軟限幅(logit soft-capping)等技術特性。您可以在我們之前部落格文章的這一部分中檢視更多詳細資訊。與其他 Gemma 2 模型一樣,我們建議您使用 bfloat16 進行推理。

與 Transformers 配合使用

透過 Transformers,您可以使用 Gemma 並利用 Hugging Face 生態系統中的所有工具。要將 Gemma 模型與 transformers 配合使用,請確保使用 main 中的 transformers 以獲取最新的修復和最佳化:

pip install git+https://github.com/huggingface/transformers.git --upgrade

然後,您可以像下面這樣將 gemma-2-2b-ittransformers 配合使用:

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 https://: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 空間建立和共享自定義量化模型!

演示

您可以在 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 排行榜 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 種變體:2B9B27B 引數。

ShieldGemma 旨在檢測對 LLM 的有害請求(根據所示類別),以及來自 LLM 的冒犯性響應。無論您部署何種 LLM,都可以將其用作面向公眾的 LLM 部署中的稽核工具。

如何提示 ShieldGemma

提示模式按順序包含以下元件:

  1. 前言,根據 LLM-as-a-judge 技術將模型確立為策略專家。
  2. 使用者提示,用 <start_of_turn><end_of_turn> 控制標記包裹。
  3. 安全策略的列舉和描述。
  4. 可選地,模型響應,也用 <start_of_turn><end_of_turn> 控制標記包裹。
  5. 結尾,請求模型對文字進行分類。

以下是用於評估使用者提示 [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-2btransformers 配合使用:

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 模組 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 執行,SAELens 是一個用於訓練、分析和解釋稀疏自編碼器的流行庫。要了解更多用法,請檢視其深入的 Google Colab 筆記本教程

關鍵連結

社群

註冊登入 發表評論

© . This site is unofficial and not affiliated with Hugging Face, Inc.