เรียกใช้ Gemma โดยใช้ PyTorch

คู่มือนี้จะแสดงวิธีเรียกใช้ Gemma โดยใช้เฟรมเวิร์ก PyTorch รวมถึงวิธีใช้ข้อมูลรูปภาพเพื่อแสดงโมเดล Gemma เวอร์ชัน 3 ขึ้นไป โปรดดูรายละเอียดเพิ่มเติมเกี่ยวกับการใช้งาน Gemma PyTorch ที่ที่เก็บข้อมูลโครงการ README

ตั้งค่า

ส่วนต่อไปนี้จะอธิบายวิธีตั้งค่าสภาพแวดล้อมการพัฒนา รวมถึงวิธีเข้าถึงโมเดล Gemma เพื่อดาวน์โหลดจาก Kaggle การตั้งค่าตัวแปรการตรวจสอบสิทธิ์ การติดตั้งข้อกําหนดเบื้องต้น และการนําเข้าแพ็กเกจ

ข้อกำหนดของระบบ

ไลบรารี Gemma Pytorch นี้ต้องใช้โปรเซสเซอร์ GPU หรือ TPU เพื่อเรียกใช้โมเดล Gemma รันไทม์ Python ของ CPU ใน Colab มาตรฐานและรันไทม์ Python ของ GPU T4 เพียงพอที่จะเรียกใช้โมเดล Gemma ขนาด 1, 2 และ 4 พันล้าน สำหรับกรณีการใช้งานขั้นสูงสำหรับ GPU หรือ TPU อื่นๆ โปรดดูREADME ในที่เก็บ Gemma PyTorch

รับสิทธิ์เข้าถึง Gemma ใน Kaggle

หากต้องการทําตามบทแนะนํานี้ให้เสร็จสมบูรณ์ ก่อนอื่นคุณต้องทําตามวิธีการตั้งค่าที่หัวข้อการตั้งค่า Gemma ซึ่งจะแสดงวิธีทําสิ่งต่อไปนี้

  • รับสิทธิ์เข้าถึง Gemma ใน kaggle.com
  • เลือกรันไทม์ Colab ที่มีทรัพยากรเพียงพอที่จะเรียกใช้โมเดล Gemma
  • สร้างและกําหนดค่าชื่อผู้ใช้และคีย์ API ของ Kaggle

หลังจากตั้งค่า Gemma เสร็จแล้ว ให้ไปยังส่วนถัดไปเพื่อตั้งค่าตัวแปรสภาพแวดล้อมสําหรับสภาพแวดล้อม Colab

ตั้งค่าตัวแปรสภาพแวดล้อม

ตั้งค่าตัวแปรสภาพแวดล้อมสําหรับ KAGGLE_USERNAME และ KAGGLE_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 = '4b-it' 
MACHINE_TYPE = 'cuda'

CONFIG = VARIANT[:2]
if CONFIG == '4b':
  CONFIG = '4b-v1'
import kagglehub

# Load model weights
weights_dir = kagglehub.model_download(f'google/gemma-3/pyTorch/gemma-3-{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!'

กำหนดค่าสภาพแวดล้อมการเรียกใช้

ส่วนต่อไปนี้จะอธิบายวิธีเตรียมสภาพแวดล้อม PyTorch เพื่อเรียกใช้ Gemma

เตรียมสภาพแวดล้อมการเรียกใช้ PyTorch

เตรียมสภาพแวดล้อมการเรียกใช้โมเดล PyTorch โดยการโคลนที่เก็บ Gemma Pytorch

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/gemma')
from gemma_pytorch.gemma.config import get_model_config
from gemma_pytorch.gemma.gemma3_model import Gemma3ForMultimodalLM

import os
import torch

ตั้งค่าการกําหนดค่ารูปแบบ

ก่อนเรียกใช้โมเดล คุณต้องตั้งค่าพารามิเตอร์การกําหนดค่าบางอย่าง ซึ่งรวมถึงตัวแปร Gemma, ตัวแยกวิเคราะห์ และระดับการแปลงค่า

# Set up model config.
model_config = get_model_config(VARIANT)
model_config.dtype = "float32" if MACHINE_TYPE == "cpu" else "float16"
model_config.tokenizer = tokenizer_path

กำหนดค่าบริบทของอุปกรณ์

โค้ดต่อไปนี้จะกําหนดค่าบริบทอุปกรณ์สําหรับการเรียกใช้โมเดล

@contextlib.contextmanager
def _set_default_tensor_type(dtype: torch.dtype):
    """Sets the default torch dtype to the given dtype."""
    torch.set_default_dtype(dtype)
    yield
    torch.set_default_dtype(torch.float)

สร้างอินสแตนซ์และโหลดโมเดล

โหลดโมเดลด้วยน้ำหนักเพื่อเตรียมเรียกใช้คำขอ

device = torch.device(MACHINE_TYPE)
with _set_default_tensor_type(model_config.get_dtype()):
    model = Gemma3ForMultimodalLM(model_config)
    model.load_state_dict(torch.load(ckpt_path)['model_state_dict'])
    model = model.to(device).eval()
print("Model loading done.")

print('Generating requests in chat mode...')

เรียกใช้การอนุมาน

ด้านล่างนี้คือตัวอย่างการสร้างในโหมดแชทและการสร้างด้วยคำขอหลายรายการ

โมเดล Gemma ที่ปรับแต่งคำสั่งได้รับการฝึกด้วยเครื่องมือจัดรูปแบบที่เฉพาะเจาะจงซึ่งกำกับเนื้อหาตัวอย่างการปรับแต่งคำสั่งด้วยข้อมูลเพิ่มเติม ทั้งในระหว่างการฝึกและการทำนาย คําอธิบายประกอบ (1) ระบุบทบาทในการสนทนา และ (2) แบ่งการพูดในการสนทนา

โทเค็นคำอธิบายประกอบที่เกี่ยวข้อง ได้แก่

  • user: การเปลี่ยนผู้ใช้
  • model: เปลี่ยนรุ่น
  • <start_of_turn>: เริ่มต้นของรอบการสนทนา
  • <start_of_image>: แท็กสําหรับการป้อนข้อมูลรูปภาพ
  • <end_of_turn><eos>: สิ้นสุดรอบการสนทนา

ดูข้อมูลเพิ่มเติมได้ที่บทความเกี่ยวกับการจัดรูปแบบพรอมต์สําหรับโมเดล Gemma ที่ปรับแต่งคําสั่ง [ที่นี่](https://ai.google.dev/gemma/core/prompt-structure

สร้างข้อความด้วยข้อความ

ต่อไปนี้คือตัวอย่างข้อมูลโค้ดที่แสดงวิธีจัดรูปแบบพรอมต์สำหรับโมเดล Gemma ที่ปรับตามคำสั่งโดยใช้เทมเพลตแชทของผู้ใช้และโมเดลในการสนทนาแบบหลายรอบ

# 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=256,
)
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"

สร้างข้อความพร้อมรูปภาพ

เมื่อใช้ Gemma เวอร์ชัน 3 ขึ้นไป คุณจะใช้รูปภาพกับพรอมต์ได้ ตัวอย่างต่อไปนี้แสดงวิธีรวมข้อมูลภาพไว้ในพรอมต์

print('Chat with images...\n')

def read_image(url):
    import io
    import requests
    import PIL

    contents = io.BytesIO(requests.get(url).content)
    return PIL.Image.open(contents)

image_url = 'https://storage.googleapis.com/keras-cv/models/paligemma/cow_beach_1.png'
image = read_image(image_url)

print(model.generate(
    [['<start_of_turn>user\n',image, 'What animal is in this image?<end_of_turn>\n', '<start_of_turn>model\n']],
    device=device,
    output_len=OUTPUT_LEN,
))

ดูข้อมูลเพิ่มเติม

เมื่อได้ทราบวิธีใช้ Gemma ใน Pytorch แล้ว คุณสามารถสำรวจสิ่งอื่นๆ อีกมากมายที่ Gemma ทำได้ที่ ai.google.dev/gemma โปรดดูแหล่งข้อมูลอื่นๆ ที่เกี่ยวข้องเหล่านี้ด้วย