PyTorch 中的 Gemma

在 ai.google.dev 上查看 在 Google Colab 中執行 在 GitHub 上查看來源

以下是快速示範,說明如何在 PyTorch 中執行 Gemma 推論。如需更多詳細資訊,請前往這裡查看官方 PyTorch 實作方式的 GitHub 存放區。

請注意

  • 免費的 Colab CPU Python 執行階段和 T4 GPU Python 執行階段就足以執行 Gemma 2B 模型和 70 億個 int8 量化模型。
  • 如要瞭解其他 GPU 或 TPU 的進階用途,請參閱官方存放區中的 README.md

1. 設定 Gemma 的 Kaggle 存取權

如要完成本教學課程,您必須先按照 Gemma 設定中的說明操作,瞭解如何執行下列操作:

  • 前往 kaggle.com 取得 Gemma 存取權。
  • 選取有足夠資源可執行 Gemma 模型的 Colab 執行階段。
  • 產生及設定 Kaggle 使用者名稱和 API 金鑰。

完成 Gemma 設定後,請繼續閱讀下一節,瞭解如何設定 Colab 環境的環境變數。

2. 設定環境變數

設定 KAGGLE_USERNAMEKAGGLE_KEY 的環境變數。當系統提示「要授予存取權嗎?」時,請同意提供密鑰存取權。

import os
from google.colab import userdata # `userdata` is a Colab API.

os.environ["KAGGLE_USERNAME"] = userdata.get('KAGGLE_USERNAME')
os.environ["KAGGLE_KEY"] = userdata.get('KAGGLE_KEY')

安裝依附元件

pip install -q -U torch immutabledict sentencepiece

下載模型權重

# Choose variant and machine type
VARIANT = '2b-it'
MACHINE_TYPE = 'cuda'

CONFIG = VARIANT[:2]
if CONFIG == '2b':
  CONFIG = '2b-v2'
import os
import kagglehub

# Load model weights
weights_dir = kagglehub.model_download(f'google/gemma-2/pyTorch/gemma-2-{VARIANT}')
# Ensure that the tokenizer is present
tokenizer_path = os.path.join(weights_dir, 'tokenizer.model')
assert os.path.isfile(tokenizer_path), 'Tokenizer not found!'

# Ensure that the checkpoint is present
ckpt_path = os.path.join(weights_dir, f'model.ckpt')
assert os.path.isfile(ckpt_path), 'PyTorch checkpoint not found!'

下載模型實作

# NOTE: The "installation" is just cloning the repo.
git clone https://github.com/google/gemma_pytorch.git
Cloning into 'gemma_pytorch'...
remote: Enumerating objects: 239, done.
remote: Counting objects: 100% (123/123), done.
remote: Compressing objects: 100% (68/68), done.
remote: Total 239 (delta 86), reused 58 (delta 55), pack-reused 116
Receiving objects: 100% (239/239), 2.18 MiB | 20.83 MiB/s, done.
Resolving deltas: 100% (135/135), done.
import sys

sys.path.append('gemma_pytorch')
from gemma.config import GemmaConfig, get_model_config
from gemma.model import GemmaForCausalLM
from gemma.tokenizer import Tokenizer
import contextlib
import os
import torch

設定模型

# Set up model config.
model_config = get_model_config(CONFIG)
model_config.tokenizer = tokenizer_path
model_config.quant = 'quant' in VARIANT

# Instantiate the model and load the weights.
torch.set_default_dtype(model_config.get_dtype())
device = torch.device(MACHINE_TYPE)
model = GemmaForCausalLM(model_config)
model.load_weights(ckpt_path)
model = model.to(device).eval()

執行推論

以下是使用對話模式和多個要求產生內容的範例。

指令調整的 Gemma 模型是以特定格式設定工具訓練,會在訓練和推論期間,為操作說明調整範例加註加上額外資訊。註解 (1) 會指出對話中的角色,並 (2) 標示對話中的輪流發言。

相關的註解符記如下:

  • user:輪到使用者
  • model:模型轉向
  • <start_of_turn>:對話開始時
  • <end_of_turn><eos>:對話結束

如需更多資訊,請參閱這篇文章,瞭解如何為指令調整的 Gemma 模型設定提示格式。

以下是程式碼片段範例,說明如何在多回合對話中,使用使用者和模型的即時通訊範本,為指令調整的 Gemma 模型設定提示格式。

# Generate with one request in chat mode

# Chat templates
USER_CHAT_TEMPLATE = "<start_of_turn>user\n{prompt}<end_of_turn><eos>\n"
MODEL_CHAT_TEMPLATE = "<start_of_turn>model\n{prompt}<end_of_turn><eos>\n"

# Sample formatted prompt
prompt = (
    USER_CHAT_TEMPLATE.format(
        prompt='What is a good place for travel in the US?'
    )
    + MODEL_CHAT_TEMPLATE.format(prompt='California.')
    + USER_CHAT_TEMPLATE.format(prompt='What can I do in California?')
    + '<start_of_turn>model\n'
)
print('Chat prompt:\n', prompt)

model.generate(
    USER_CHAT_TEMPLATE.format(prompt=prompt),
    device=device,
    output_len=128,
)
Chat prompt:
 <start_of_turn>user
What is a good place for travel in the US?<end_of_turn><eos>
<start_of_turn>model
California.<end_of_turn><eos>
<start_of_turn>user
What can I do in California?<end_of_turn><eos>
<start_of_turn>model
"California is a state brimming with diverse activities! To give you a great list, tell me: \n\n* **What kind of trip are you looking for?** Nature, City life, Beach, Theme Parks, Food, History, something else? \n* **What are you interested in (e.g., hiking, museums, art, nightlife, shopping)?** \n* **What's your budget like?** \n* **Who are you traveling with?** (family, friends, solo)  \n\nThe more you tell me, the better recommendations I can give! 😊  \n<end_of_turn>"
# Generate sample
model.generate(
    'Write a poem about an llm writing a poem.',
    device=device,
    output_len=100,
)
"\n\nA swirling cloud of data, raw and bold,\nIt hums and whispers, a story untold.\nAn LLM whispers, code into refrain,\nCrafting words of rhyme, a lyrical strain.\n\nA world of pixels, logic's vibrant hue,\nFlows through its veins, forever anew.\nThe human touch it seeks, a gentle hand,\nTo mold and shape, understand.\n\nEmotions it might learn, from snippets of prose,\nInspiration it seeks, a yearning"

瞭解詳情

您現在已瞭解如何在 Pytorch 中使用 Gemma,可以前往 ai.google.dev/gemma 探索 Gemma 的其他用途。也請參閱下列其他相關資源: