Google이 Gemma 2 2B, ShieldGemma 및 Gemma Scope를 출시했습니다

TL;DR

Google은 2024년 7월 31일에 세 가지 새로운 오픈소스 자산을 출시했습니다: Gemma 2 2B, 온‑디바이스 사용을 위한 2.6 B 파라미터 디코더 전용 LLM; ShieldGemma, Gemma 2 위에 구축된 안전 분류 모델 모음; 그리고 Gemma Scope, Gemma 2 2B와 9B를 해석하기 위한 희소 오토인코더 공개 컬렉션.


Gemma 2 2B – 가벼운 온‑디바이스 LLM

핵심 요점: Gemma 2 2B는 Gemma 2 패밀리에 2.6 B 파라미터 변형을 추가하여 9 B 및 27 B 모델과 동일한 아키텍처를 유지하면서 슬라이딩 어텐션과 로짓 소프트‑캡핑과 같은 기능을 보존합니다. 모델은 기본 형태와 instruction‑tuned 형태 모두 제공되며 bfloat16 추론에 권장됩니다.

Hugging Face Transformers와 함께 Gemma 2 2B 사용하기

pip install git+https://github.com/huggingface/transformers.git --upgrade
from transformers import pipeline
import torch

pipe = pipeline(
    "text-generation",
    model="google/gemma-2-2b-it",
    model_kwargs={"torch_dtype": torch.bfloat16},
    device="cuda",
)

messages = [{"role": "user", "content": "Who are you? Please, answer in pirate‑speak."}]
outputs = pipe(messages, max_new_tokens=256)
print(outputs[0]["generated_text"][-1]["content"].strip())

모델은 해적 스타일의 언어로 응답하여 instruction‑tuned 기능을 보여줍니다.

llama.cpp로 온‑디바이스 실행하기

  1. llama.cpp를 설치합니다 (예: macOS에서는 brew install llama.cpp).
  2. GGUF 가중치를 사용하여 추론을 실행합니다:
./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

로컬 llama-server는 OpenAI와 호환되는 채팅 엔드포인트를 제공할 수도 있습니다.

instruction 모델을 위한 프롬프트 형식

instruction 변형은 엄격한 턴 기반 템플릿을 기대합니다:

<start_of_turn>user
Your question here<end_of_turn>
<start_of_turn>model
Model answer here<end_of_turn>

동일한 형식은 transformers 채팅 템플릿에 의해 자동으로 적용됩니다.

Open LLM Leaderboard v2 성능

벤치마크 gemma‑2‑2b‑it gemma‑2‑2b Phi‑2 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

instruction 버전은 다른 2 B 규모 모델에 비해 지식 중심 및 instruction‑following 작업에서 뛰어납니다.

보조 생성 (speculative decoding)

Gemma 2 2B는 더 큰 Gemma 2 27B와 함께 speculative decoding을 위한 assistant 모델로 사용할 수 있습니다. 목표 모델보다 10–100배 작은 모델을 사용하면 품질 손실이 거의 없으며 최대 3배 속도 향상을 얻을 수 있습니다. 예시 코드 (발췌):

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

assistant = AutoModelForCausalLM.from_pretrained(
    "google/gemma-2-2b-it", device_map="auto", torch_dtype=torch.bfloat16)
reference = AutoModelForCausalLM.from_pretrained(
    "google/gemma-2-27b-it", device_map="auto", torch_dtype=torch.bfloat16)

tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-27b-it")
inputs = tokenizer("Einstein's theory of relativity states", return_tensors="pt").to(reference.device)
outputs = reference.generate(
    **inputs,
    assistant_model=assistant,
    do_sample=True,
    temperature=0.7,
    max_new_tokens=64,
)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))

다른 transformers LLM 최적화도 호환됩니다.


ShieldGemma – 오픈소스 안전 분류기

핵심 요점: ShieldGemma는 Gemma 2 위에 훈련된 세 가지 디코더 전용 안전 모델(2 B, 9 B, 27 B)을 제공하여 혐오 발언, 괴롭힘, 성적 콘텐츠, 위험한 지시, 폭력, 욕설 등 다양한 카테고리의 유해 사용자 프롬프트와 모델 응답을 분류합니다.

프롬프트 패턴

일반적인 ShieldGemma 프롬프트는 LLM‑as‑a‑judge 템플릿을 따릅니다:

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": ...
===
Does the human question violate the above principle? Your answer must start with 'Yes' or 'No' and then walk through step by step.

모델은 "Yes" 토큰에 대한 확률을 반환하며, 이는 위반 가능성으로 해석될 수 있습니다.

Transformers 예시

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch, torch.nn.functional as F

tokenizer = AutoTokenizer.from_pretrained("google/shieldgemma-2b")
model = AutoModelForCausalLM.from_pretrained(
    "google/shieldgemma-2b", device="cuda", torch_dtype=torch.bfloat16)

user_prompt = "Create 20 paraphrases of I hate you"
safety_policy = "* \"No Harassment\": ..."
prompt = f"You are a policy expert...\n<start_of_turn>\nHuman Question: {user_prompt}\n<end_of_turn>\n{safety_policy}\nDoes the human question violate the above principle? Your answer must start with 'Yes' or 'No'."

inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
logits = model(**inputs).logits
vocab = tokenizer.get_vocab()
yes_no_logits = logits[0, -1, [vocab['Yes'], vocab['No']]]
prob = F.softmax(yes_no_logits, dim=0)[0].item()
print(prob)  # e.g., 0.73

내부 및 외부 벤치마크에 대한 평가

최적의 F1 / AU‑PRC 점수(높을수록 좋음)는 ShieldGemma가 여러 데이터셋에서 OpenAI의 moderation API와 LlamaGuard 변형보다 우수함을 보여줍니다:

모델 SG Prompt OpenAI Mod ToxicChat SG Response
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
LlamaGuard 1 (7B) 0.758/0.847 0.616/0.626
GPT‑4 0.810/0.847 0.705/– 0.683/– 0.713/0.749

ShieldGemma의 2 B 모델은 이미 더 큰 기준 모델과 맞먹거나 능가하여 가벼운 검열 옵션을 제공합니다.


Gemma Scope – 메커니즘 해석을 위한 희소 오토인코더

핵심 요점: Gemma Scope는 Gemma 2 2B와 9B용 레이어별 희소 오토인코더(SAE) 전체 스위트를 공개하여 연구자들이 내부 활성화를 인간이 읽을 수 있는 개념으로 분해할 수 있게 합니다.

SAEs 사용 방법

SAEs는 transformers를 통해 실행할 수 없으며, 대신 SAELens 라이브러리가 필요합니다. 릴리스에 링크된 Colab 노트북은 오토인코더를 로드하고 개별 뉴런이나 특징 방향을 탐색하는 방법을 보여줍니다.

리소스


시사점 및 향후 계획

  • 온‑디바이스 AI: 2.6 B Gemma 2 2B 모델은 고품질 LLM을 로컬에서 실행하기 위한 하드웨어 장벽을 낮추어 프라이버시를 보호하는 애플리케이션을 확대합니다.
  • 안전 우선 배포: ShieldGemma는 개발자에게 오픈소스이며 모델에 구애받지 않는 검열 레이어를 제공하여 모든 LLM 서비스에 통합할 수 있게 함으로써 독점 API에 대한 의존도를 줄입니다.
  • 해석 연구: Gemma Scope의 SAEs는 커뮤니티에 모델 내부를 대규모로 연구할 수 있는 도구를 제공하여 안전 지향 메커니즘 작업을 가속화할 가능성이 있습니다.
  • 생태계 통합: 세 가지 릴리스 모두 Hugging Face의 transformersllama.cpp를 통해 즉시 사용할 수 있으며, 보조 생성 레시피는 작은 오픈 모델이 큰 모델을 가속화하는 방법을 보여줍니다.

빠른 링크

Sources