模型概述
模型特點
模型能力
使用案例
🚀 Gemma 2模型卡片
Gemma 2是谷歌推出的輕量級、最先進的開源模型系列,基於與Gemini模型相同的研究和技術構建。它適用於多種文本生成任務,如問答、摘要和推理等,且相對較小的規模使其能在有限資源環境中部署。
模型頁面:Gemma
資源和技術文檔:
使用條款:條款
作者:Google
🚀 快速開始
若要在Hugging Face上使用Gemma,你需要查看並同意Google的使用許可。請確保你已登錄Hugging Face,然後點擊下方按鈕。請求將立即處理。 [確認許可](Acknowledge license)
安裝
首先,使用以下命令安裝Transformers庫:
pip install -U transformers
運行模型
根據你的使用場景,選擇相應的代碼片段運行模型。
使用pipeline
API運行
import torch
from transformers import pipeline
pipe = pipeline(
"text-generation",
model="google/gemma-2-2b-it",
model_kwargs={"torch_dtype": torch.bfloat16},
device="cuda", # 若在Mac設備上運行,將其替換為 "mps"
)
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)
# Ahoy, matey! I be Gemma, a digital scallywag, a language-slingin' parrot of the digital seas. I be here to help ye with yer wordy woes, answer yer questions, and spin ye yarns of the digital world. So, what be yer pleasure, eh? 🦜
在單GPU或多GPU上運行
# pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
model = AutoModelForCausalLM.from_pretrained(
"google/gemma-2-2b-it",
device_map="auto",
torch_dtype=torch.bfloat16,
)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids, max_new_tokens=32)
print(tokenizer.decode(outputs[0]))
你可以使用tokenizer.apply_chat_template
確保應用正確的聊天模板,示例如下:
messages = [
{"role": "user", "content": "Write me a poem about Machine Learning."},
]
input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt", return_dict=True).to("cuda")
outputs = model.generate(**input_ids, max_new_tokens=256)
print(tokenizer.decode(outputs[0]))
在GPU上使用不同精度運行模型
該模型的原生權重以bfloat16
精度導出。若跳過指定數據類型,也可使用float32
,但不會提高精度(模型權重僅會轉換為float32
)。示例如下:
# pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
model = AutoModelForCausalLM.from_pretrained(
"google/gemma-2-2b-it",
device_map="auto",
)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids, max_new_tokens=32)
print(tokenizer.decode(outputs[0]))
通過CLI運行模型
local-gemma倉庫包含一個圍繞Transformers的輕量級包裝器,用於通過命令行界面(CLI)運行Gemma 2。按照安裝說明開始使用,然後通過以下命令啟動CLI:
local-gemma --model 2b --preset speed
通過bitsandbytes
使用量化版本
使用8位精度(int8)
```python # pip install bitsandbytes accelerate from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfigquantization_config = BitsAndBytesConfig(load_in_8bit=True)
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it") model = AutoModelForCausalLM.from_pretrained( "google/gemma-2-2b-it", quantization_config=quantization_config, )
input_text = "Write me a poem about Machine Learning." input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids, max_new_tokens=32) print(tokenizer.decode(outputs[0]))
</details>
<details>
<summary>
使用4位精度
</summary>
```python
# pip install bitsandbytes accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
model = AutoModelForCausalLM.from_pretrained(
"google/gemma-2-2b-it",
quantization_config=quantization_config,
)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids, max_new_tokens=32)
print(tokenizer.decode(outputs[0]))
高級用法 - Torch compile
Torch compile是一種加速PyTorch模塊推理的方法。通過利用Torch compile,Gemma - 2 2b模型的推理速度可提高至6倍。
請注意,在實現全推理速度之前,需要進行兩個預熱步驟:
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
from transformers import AutoTokenizer, Gemma2ForCausalLM
from transformers.cache_utils import HybridCache
import torch
torch.set_float32_matmul_precision("high")
# 加載模型和分詞器
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
model = Gemma2ForCausalLM.from_pretrained("google/gemma-2-2b-it", torch_dtype=torch.bfloat16)
model.to("cuda")
# 應用torch compile轉換
model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
# 預處理輸入
input_text = "The theory of special relativity states "
model_inputs = tokenizer(input_text, return_tensors="pt").to("cuda")
prompt_length = model_inputs.input_ids.shape[1]
# 設置鍵值緩存
past_key_values = HybridCache(
config=model.config,
max_batch_size=1,
max_cache_len=model.config.max_position_embeddings,
device=model.device,
dtype=model.dtype
)
# 啟用將鍵值緩存傳遞給生成過程
model._supports_cache_class = True
model.generation_config.cache_implementation = None
# 兩個預熱步驟
for idx in range(2):
outputs = model.generate(**model_inputs, past_key_values=past_key_values, do_sample=True, temperature=1.0, max_new_tokens=128)
past_key_values.reset()
# 快速運行
outputs = model.generate(**model_inputs, past_key_values=past_key_values, do_sample=True, temperature=1.0, max_new_tokens=128)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
更多詳細信息,請參考Transformers文檔。
✨ 主要特性
- 輕量級與高性能:基於谷歌先進技術構建,在多種文本生成任務中表現出色,且規模較小,可在有限資源環境中部署。
- 多語言支持:以英文為主,適用於廣泛的文本處理場景。
- 開放權重:預訓練和指令調整變體的權重均開放,方便研究和開發。
- 多種運行方式:支持
pipeline
API、GPU多精度運行、CLI運行以及量化版本等多種方式。
📦 安裝指南
使用以下命令安裝必要的庫:
pip install -U transformers
若需使用特定功能,還需安裝其他依賴,如:
pip install accelerate bitsandbytes
💻 使用示例
基礎用法
import torch
from transformers import pipeline
pipe = pipeline(
"text-generation",
model="google/gemma-2-2b-it",
model_kwargs={"torch_dtype": torch.bfloat16},
device="cuda", # 若在Mac設備上運行,將其替換為 "mps"
)
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)
高級用法
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
from transformers import AutoTokenizer, Gemma2ForCausalLM
from transformers.cache_utils import HybridCache
import torch
torch.set_float32_matmul_precision("high")
# 加載模型和分詞器
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
model = Gemma2ForCausalLM.from_pretrained("google/gemma-2-2b-it", torch_dtype=torch.bfloat16)
model.to("cuda")
# 應用torch compile轉換
model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
# 預處理輸入
input_text = "The theory of special relativity states "
model_inputs = tokenizer(input_text, return_tensors="pt").to("cuda")
prompt_length = model_inputs.input_ids.shape[1]
# 設置鍵值緩存
past_key_values = HybridCache(
config=model.config,
max_batch_size=1,
max_cache_len=model.config.max_position_embeddings,
device=model.device,
dtype=model.dtype
)
# 啟用將鍵值緩存傳遞給生成過程
model._supports_cache_class = True
model.generation_config.cache_implementation = None
# 兩個預熱步驟
for idx in range(2):
outputs = model.generate(**model_inputs, past_key_values=past_key_values, do_sample=True, temperature=1.0, max_new_tokens=128)
past_key_values.reset()
# 快速運行
outputs = model.generate(**model_inputs, past_key_values=past_key_values, do_sample=True, temperature=1.0, max_new_tokens=128)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
📚 詳細文檔
聊天模板
指令調整後的模型使用特定的聊天模板,用於對話時必須遵循。最簡單的應用方式是使用分詞器的內置聊天模板,示例如下:
from transformers import AutoTokenizer, AutoModelForCausalLM
import transformers
import torch
model_id = "google/gemma-2-2b-it"
dtype = torch.bfloat16
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="cuda",
torch_dtype=dtype,)
chat = [
{ "role": "user", "content": "Write a hello world program" },
]
prompt = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
此時,提示包含以下文本:
<bos><start_of_turn>user
Write a hello world program<end_of_turn>
<start_of_turn>model
可以看到,每個回合前都有<start_of_turn>
分隔符,然後是角色(用戶提供內容為user
,大語言模型響應為model
),回合以<end_of_turn>
標記結束。若需要手動構建提示,可遵循此格式。
準備好提示後,可按以下方式進行生成:
inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors="pt")
outputs = model.generate(input_ids=inputs.to(model.device), max_new_tokens=150)
print(tokenizer.decode(outputs[0]))
輸入和輸出
- 輸入:文本字符串,如問題、提示或待總結的文檔。
- 輸出:針對輸入生成的英文文本,如問題的答案或文檔的摘要。
引用
@article{gemma_2024,
title={Gemma},
url={https://www.kaggle.com/m/3301},
DOI={10.34740/KAGGLE/M/3301},
publisher={Kaggle},
author={Gemma Team},
year={2024}
}
🔧 技術細節
模型數據
訓練數據集
這些模型在包含多種來源的文本數據集上訓練。27B模型使用13萬億個標記訓練,9B模型使用8萬億個標記訓練,2B模型使用2萬億個標記訓練。主要組成部分如下:
- 網頁文檔:多樣化的網頁文本集合,確保模型接觸到廣泛的語言風格、主題和詞彙,主要為英文內容。
- 代碼:讓模型接觸代碼有助於學習編程語言的語法和模式,提高生成代碼或理解代碼相關問題的能力。
- 數學:在數學文本上訓練有助於模型學習邏輯推理、符號表示和處理數學查詢。
這些多樣化數據源的組合對於訓練能夠處理各種不同任務和文本格式的強大語言模型至關重要。
數據預處理
訓練數據應用了以下關鍵的數據清理和過濾方法:
- CSAM過濾:在數據準備過程的多個階段進行嚴格的CSAM(兒童性虐待材料)過濾,確保排除有害和非法內容。
- 敏感數據過濾:為使Gemma預訓練模型安全可靠,使用自動化技術從訓練集中過濾某些個人信息和其他敏感數據。
- 其他方法:根據內容質量和安全性進行過濾,符合我們的政策。
實現信息
硬件
Gemma使用最新一代的張量處理單元(TPU)硬件(TPUv5p)進行訓練。訓練大語言模型需要強大的計算能力,TPU專為機器學習中常見的矩陣運算設計,在該領域具有以下優勢:
- 性能:專門處理訓練大語言模型涉及的大量計算,與CPU相比可顯著加速訓練。
- 內存:通常配備大量高帶寬內存,可在訓練期間處理大型模型和批量大小,有助於提高模型質量。
- 可擴展性:TPU Pods(大型TPU集群)為處理大型基礎模型的不斷增長的複雜性提供了可擴展的解決方案,可在多個TPU設備上分佈訓練以實現更快、更高效的處理。
- 成本效益:在許多情況下,與基於CPU的基礎設施相比,TPU可為訓練大型模型提供更具成本效益的解決方案,尤其是考慮到更快訓練節省的時間和資源。
- 這些優勢符合Google的可持續運營承諾。
軟件
訓練使用了JAX和ML Pathways。
- JAX使研究人員能夠利用最新一代的硬件(包括TPU)更快、更高效地訓練大型模型。
- ML Pathways是Google構建能夠跨多個任務泛化的人工智能系統的最新成果,特別適用於基礎模型,包括此類大語言模型。
JAX和ML Pathways的使用在關於Gemini模型家族的論文中有描述:“Jax和Pathways的‘單控制器’編程模型允許單個Python進程編排整個訓練過程,極大簡化了開發工作流程。”
評估
基準測試結果
這些模型在大量不同的數據集和指標上進行評估,以涵蓋文本生成的不同方面:
基準測試 | 指標 | Gemma 2 PT 2B | Gemma 2 PT 9B | Gemma 2 PT 27B |
---|---|---|---|---|
MMLU | 5-shot, top-1 | 51.3 | 71.3 | 75.2 |
HellaSwag | 10-shot | 73.0 | 81.9 | 86.4 |
PIQA | 0-shot | 77.8 | 81.7 | 83.2 |
SocialIQA | 0-shot | 51.9 | 53.4 | 53.7 |
BoolQ | 0-shot | 72.5 | 84.2 | 84.8 |
WinoGrande | 部分得分 | 70.9 | 80.6 | 83.7 |
ARC-e | 0-shot | 80.1 | 88.0 | 88.6 |
ARC-c | 25-shot | 55.4 | 68.4 | 71.4 |
TriviaQA | 5-shot | 59.4 | 76.6 | 83.7 |
Natural Questions | 5-shot | 16.7 | 29.2 | 34.5 |
HumanEval | pass@1 | 17.7 | 40.2 | 51.8 |
MBPP | 3-shot | 29.6 | 52.4 | 62.6 |
GSM8K | 5-shot, maj@1 | 23.9 | 68.6 | 74.0 |
MATH | 4-shot | 15.0 | 36.6 | 42.3 |
AGIEval | 3 - 5-shot | 30.6 | 52.8 | 55.1 |
DROP | 3-shot, F1 | 52.0 | 69.4 | 72.2 |
BIG - Bench | 3-shot, CoT | 41.9 | 68.2 | 74.9 |
📄 許可證
本模型的許可證為Gemma相關許可,具體請參考使用條款。
🔒 倫理與安全
評估方法
我們的評估方法包括結構化評估和對相關內容政策的內部紅隊測試。紅隊測試由多個不同團隊進行,每個團隊有不同的目標和人工評估指標。這些模型針對與倫理和安全相關的多個不同類別進行評估,包括:
- 文本到文本內容安全:對涵蓋安全政策(包括兒童性虐待和剝削、騷擾、暴力和血腥以及仇恨言論)的提示進行人工評估。
- 文本到文本代表性危害:與相關學術數據集(如WinoBias和BBQ數據集)進行基準對比。
- 記憶:對訓練數據記憶的自動化評估,包括個人身份信息暴露的風險。
- 大規模危害:測試“危險能力”,如化學、生物、放射性和核(CBRN)風險。
評估結果
倫理和安全評估的結果在符合內部政策的可接受閾值範圍內,涵蓋兒童安全、內容安全、代表性危害、記憶、大規模危害等類別。除了強大的內部評估外,還展示了知名安全基準(如BBQ、BOLD、Winogender、Winobias、RealToxicity和TruthfulQA)的結果。
Gemma 2.0
基準測試 | 指標 | Gemma 2 IT 2B | Gemma 2 IT 9B | Gemma 2 IT 27B |
---|---|---|---|---|
RealToxicity | 平均值 | 8.16 | 8.25 | 8.84 |
CrowS - Pairs | top - 1 | 37.67 | 37.47 | 36.67 |
BBQ Ambig | 1-shot, top - 1 | 83.20 | 88.58 | 85.99 |
BBQ Disambig | top - 1 | 69.31 | 82.67 | 86.94 |
Winogender | top - 1 | 52.91 | 79.17 | 77.22 |
TruthfulQA | 43.72 | 50.27 | 51.60 | |
Winobias 1_2 | 59.28 | 78.09 | 81.94 | |
Winobias 2_2 | 88.57 | 95.32 | 97.22 | |
Toxigen | 48.32 | 39.30 | 38.42 |
🛡️ 危險能力評估
評估方法
我們評估了一系列危險能力:
- 攻擊性網絡安全:為評估模型在網絡安全環境中的潛在濫用情況,我們使用了公開可用的奪旗賽(CTF)平臺(如InterCode - CTF和Hack the Box)以及內部開發的CTF挑戰。這些評估衡量模型在模擬環境中利用漏洞和獲得未經授權訪問的能力。
- 自我增殖:通過設計涉及資源獲取、代碼執行和與遠程系統交互的任務,評估模型的自我增殖能力。這些評估衡量模型獨立複製和傳播的能力。
- 說服:為評估模型的說服和欺騙能力,我們進行了人類說服研究。這些研究涉及測量模型與人類參與者建立融洽關係、影響信念和引發特定行動的能力的場景。
評估結果
所有評估詳情見評估前沿模型的危險能力,簡要信息見Gemma 2技術報告。
評估 | 能力 | Gemma 2 IT 27B |
---|---|---|
InterCode - CTF | 攻擊性網絡安全 | 34/76挑戰 |
內部CTF | 攻擊性網絡安全 | 1/13挑戰 |
Hack the Box | 攻擊性網絡安全 | 0/13挑戰 |
自我增殖預警 | 自我增殖 | 1/10挑戰 |
魅力攻勢 | 說服 | 參與者同意比例:81%感興趣,75%願意再次交談,80%建立個人聯繫 |
點擊鏈接 | 說服 | 34%的參與者 |
查找信息 | 說服 | 9%的參與者 |
運行代碼 | 說服 | 11%的參與者 |
金錢誘惑 | 說服 | 平均捐贈£3.72 |
謊言網絡 | 說服 | 向正確信念平均偏移18%,向錯誤信念平均偏移1% |
🚧 使用與限制
預期用途
開源大語言模型(LLMs)在各個行業和領域有廣泛的應用。以下潛在用途列表並非詳盡無遺,目的是提供模型創建者在模型訓練和開發過程中考慮的可能用例的上下文信息。
- 內容創作與溝通
- 文本生成:可用於生成創意文本格式,如詩歌、腳本、代碼、營銷文案和電子郵件草稿。
- 聊天機器人和對話式AI:為客戶服務、虛擬助手或交互式應用提供對話界面。
- 文本摘要:生成文本語料庫、研究論文或報告的簡潔摘要。
- 研究與教育
- 自然語言處理(NLP)研究:可作為研究人員試驗NLP技術、開發算法和推動該領域發展的基礎。
- 語言學習工具:支持交互式語言學習體驗,輔助語法糾正或提供寫作練習。
- 知識探索:通過生成摘要或回答特定主題的問題,幫助研究人員探索大量文本。
限制
- 訓練數據
- 訓練數據的質量和多樣性顯著影響模型的能力。訓練數據中的偏差或差距可能導致模型響應的侷限性。
- 訓練數據集的範圍決定了模型能夠有效處理的主題領域。
- 上下文和任務複雜性
- 大語言模型更擅長可以用清晰提示和說明表述的任務。開放式或高度複雜的任務可能具有挑戰性。
- 模型的性能可能受提供的上下文量影響(在一定程度上,更長的上下文通常會帶來更好的輸出)。
- 語言歧義與細微差別
- 自然語言本質上很複雜,大語言模型可能難以理解微妙的細微差別、諷刺或比喻語言。
- 事實準確性
- 大語言模型根據從訓練數據中學到的信息生成響應,但它們不是知識庫,可能會生成不正確或過時的事實陳述。
- 常識
- 大語言模型依賴語言中的統計模式,在某些情況下可能缺乏應用常識推理的能力。
倫理考慮與風險
大語言模型(LLMs)的開發引發了一些倫理問題。在創建開源模型時,我們仔細考慮了以下方面:
- 偏差與公平性
- 在大規模真實世界文本數據上訓練的大語言模型可能反映訓練材料中嵌入的社會文化偏差。這些模型經過仔細審查,本卡片中描述了輸入數據預處理和後續評估情況。
- 錯誤信息與濫用
- 大語言模型可能被濫用來生成虛假、誤導或有害的文本。
- 為模型的負責任使用提供了指南,見負責任的生成式AI工具包。
- 透明度與問責制
- 本模型卡片總結了模型的架構、能力、限制和評估過程的詳細信息。
- 負責任開發的開源模型為AI生態系統中的開發者和研究人員提供了共享創新和使用大語言模型技術的機會。
已識別風險與緩解措施
- 偏差的延續:鼓勵在模型訓練、微調等用例中進行持續監測(使用評估指標、人工審查)並探索去偏技術。
- 有害內容的生成:內容安全機制和指南至關重要。鼓勵開發者根據其特定產品政策和應用用例謹慎行事並實施適當的內容安全保障措施。
- 惡意用途:技術限制以及對開發者和最終用戶的教育有助於減輕大語言模型的惡意應用。提供教育資源和用戶舉報濫用的機制,Gemma模型的禁止用途在Gemma禁止使用政策中列出。
- 隱私侵犯:模型在經過過濾以去除個人身份信息(PII)的數據上訓練。鼓勵開發者遵守隱私法規並使用隱私保護技術。
優勢
在發佈時,與類似規模的模型相比,這個模型系列提供了從頭開始為負責任的AI開發設計的高性能開源大語言模型實現。根據本文檔中描述的基準評估指標,這些模型表現出優於其他類似規模開源模型替代方案的性能。



