使用 Hugging Face Transformers 執行 Gemma

在 ai.google.dev 上查看 在 Google Colab 中執行 在 Kaggle 中執行 在 Vertex AI 中開啟 在 GitHub 上查看來源

Gemma 開放模型可執行多種工作,包括生成文字、製作摘要和分析內容。本教學課程說明如何開始使用 Hugging Face Transformers 執行 Gemma,並使用文字和圖片輸入內容生成文字內容。Transformers Python 程式庫提供 API,可存取預先訓練的生成式 AI 模型,包括 Gemma。詳情請參閱 Transformers 說明文件。

設定

開始本教學課程前,請先完成下列步驟:

  • 登入 Hugging Face,然後選取 Gemma 模型的「Acknowledge license」(確認授權),即可存取 Gemma。
  • 選取有足夠資源的 Colab 執行階段,以便執行所需大小的 Gemma 模型。瞭解詳情
  • 產生 Hugging Face 存取權杖,並新增至 Colab 環境。

設定存取權杖

將存取權杖新增至 Colab,即可從 Hugging Face 網站下載 Gemma 模型。使用 Colab 的「密鑰」功能安全儲存權杖,不必將權杖新增至工作程式碼。

如要將 Hugging Face 存取權杖新增為密鑰,請按照下列步驟操作:

  1. 選取介面左側的鑰匙圖示,開啟祕密分頁標籤,或依序選取「Tools」>「Command pallete」,輸入 secrets,然後按下 Enter 鍵。
  2. 選取「新增密鑰」,新增密鑰項目。
  3. 在「Name」(名稱) 欄位中輸入 HF_TOKEN
  4. 在「Value」(值) 欄位中,輸入 Hugging Face 存取權杖的文字。
  5. 在「筆記本存取權」欄位中,選取切換按鈕來啟用存取權。

輸入存取權杖 (HF_TOKEN 和值) 後,您可以使用下列程式碼,在 Colab 筆記本環境中存取及設定權杖:

from google.colab import userdata
from huggingface_hub import login

# Login into Hugging Face Hub
hf_token = userdata.get('HF_TOKEN') # If you are running inside a Google Colab
login(hf_token)

安裝 Python 套件

安裝執行 Gemma 模型及發出要求所需的 Hugging Face 程式庫。

# Install Pytorch & other libraries
%pip install "torch>=2.4.0"

# Install a transformers version that supports Gemma 3 (>= 4.51.3)
%pip install "transformers>=4.51.3"

根據文字生成文字

以文字提示 Gemma 模型並取得文字回覆,是使用 Gemma 最簡單的方式,而且適用於幾乎所有 Gemma 變體。本節說明如何使用 Hugging Face Transformers 程式庫載入及設定 Gemma 模型,以生成文字。

載入模型

使用 torchtransformers 程式庫,透過 Gemma 建立模型執行 pipeline 類別的例項。如要使用模型生成輸出內容或按照指示操作,請選取指令調整 (IT) 模型,模型 ID 字串通常會包含 it。使用 pipeline 物件指定要使用的 Gemma 變體和要執行的工作類型,具體來說是文字轉文字生成,如以下程式碼範例所示:"text-generation"

import torch
from transformers import pipeline

pipeline = pipeline(
    task="text-generation",
    model="google/gemma-3-4b-it",
    device=0, # "cuda" for Colab, "msu" for iOS devices
    torch_dtype=torch.bfloat16
)

Gemma 僅支援少數生成設定 task,如要進一步瞭解可用的 task 設定,請參閱 Hugging Face Pipelines task() 說明文件。使用火炬資料型別 torch.bfloat16 降低模型精確度和所需運算資源,同時不大幅影響模型輸出品質。如要設定 device,您可以使用 Colab 的 "cuda"、iOS 裝置的 "msu",或將此值設為 0 (零),指定系統中的第一個 GPU。如要進一步瞭解如何使用 Pipeline 類別,請參閱 Hugging Face 的「Pipelines」說明文件。

執行文字生成

pipeline 物件中載入及設定 Gemma 模型後,即可將提示傳送至模型。以下程式碼範例顯示使用 text_inputs 參數的基本要求:

pipeline(text_inputs="roses are red")
[{'generated_text': 'roses are red, violets are blue, \ni love you more than you ever knew.\n\n**Explanation'}]

使用提示範本

如果使用更複雜的提示生成內容,請使用提示範本來建構要求。提示範本可讓您指定特定角色 (例如 usermodel) 的輸入內容,也是管理與 Gemma 模型多輪對話互動的必要格式。以下程式碼範例說明如何建構 Gemma 的提示範本:

messages = [
    [
        {
            "role": "system",
            "content": [{"type": "text", "text": "You are a helpful assistant."},]
        },
        {
            "role": "user",
            "content": [{"type": "text", "text": "Roses are red..."},]
        },
    ],
]

pipeline(messages, max_new_tokens=50)

從圖片資料生成文字

從 Gemma 3 開始,對於 4B 以上的模型大小,您可以在提示中使用圖片資料。本節說明如何使用 Transformers 程式庫載入及設定 Gemma 模型,以便使用圖片資料和文字輸入內容生成文字輸出內容。

載入模型

載入 Gemma 模型以搭配圖片資料使用時,請專為圖片設定 Transformer pipeline 執行個體。具體來說,您必須將 task 參數設為 "image-text-to-text",選取可處理視覺資料的管道設定,如下列程式碼範例所示:

import torch
from transformers import pipeline

pipeline = pipeline(
    task="image-text-to-text", # required for image input
    model="google/gemma-3-4b-it",
    device=0,
    torch_dtype=torch.bfloat16
)

執行文字生成

設定 Gemma 模型,透過 pipeline 執行個體處理圖片輸入內容後,即可將含有圖片的提示傳送給模型。使用 <start_of_image> 權杖將圖片新增至提示文字。以下程式碼範例顯示使用 pipeline 參數的基本要求:

pipeline(
    "https://ai.google.dev/static/gemma/docs/images/thali-indian-plate.jpg",
    text="<start_of_image> What is shown in this image?"
)
[{'input_text': '<start_of_image> What is shown in this image?',
  'generated_text': '<start_of_image> What is shown in this image?\n\nThis image showcases a traditional Indian Thali. A Thali is a platter that contains a variety'}]

使用提示範本

如果使用較複雜的提示生成內容,請使用提示範本來建構要求。提示範本可讓您指定特定角色 (例如 usermodel) 的輸入內容,也是管理與 Gemma 模型多輪對話互動的必要格式。以下程式碼範例說明如何建構 Gemma 的提示範本:

messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://ai.google.dev/static/gemma/docs/images/thali-indian-plate.jpg"},
            {"type": "text", "text": "What is shown in this image?"},
        ]
    },
    {
        "role": "assistant",
        "content": [
            {"type": "text", "text": "This image shows"},
        ],
    },
]

pipeline(text=messages, max_new_tokens=50, return_full_text=False)

如要在提示中加入多張圖片,請在 content 清單中加入其他 "type": "image", 項目。

從音訊資料生成文字

Gemma 3n 可在提示中使用音訊資料。本節說明如何使用 Transformers 程式庫載入及設定 Gemma 模型,以便使用音訊資料和文字輸入內容產生文字輸出內容。

安裝 Python 套件

如要搭配 Gemma 使用音訊輸入,必須使用最新版的 Transformers 程式庫。如要執行 Gemma 模型並使用音訊資料提出要求,請安裝 Hugging Face 程式庫,如下所示。

# Install Pytorch & other libraries
%pip install "torch>=2.4.0"

# Install a transformers version that supports Gemma 3n (>= 4.53)
%pip install "transformers>=4.53.0"

載入模型

載入 Gemma 模型以搭配音訊資料使用時,請設定 Transformer 執行個體,專門用於音訊資料。特別是您必須使用 AutoProcessorAutoModelForImageTextToText 類別定義 processormodel 物件,如以下程式碼範例所示:

import torch
from transformers import AutoProcessor, AutoModelForImageTextToText

GEMMA_MODEL_ID = "google/gemma-3n-E4B-it"

processor = AutoProcessor.from_pretrained(GEMMA_MODEL_ID, device_map="auto")
model = AutoModelForImageTextToText.from_pretrained(
            GEMMA_MODEL_ID, torch_dtype="auto", device_map="auto")

使用提示範本

使用提示範本來建構要求,生成含音訊的內容。提示範本可讓您指定特定角色 (例如 usermodel) 的輸入內容,也是管理與 Gemma 模型多輪對話互動的必要格式。以下程式碼範例說明如何使用音訊資料輸入,為 Gemma 建構提示範本:

messages = [
    {
        "role": "user",
        "content": [
            {"type": "audio", "audio": "https://ai.google.dev/gemma/docs/audio/roses-are.wav"},
            {"type": "text", "text": "Transcribe this audio and complete the statement"},
        ]
    }
]

如要在提示中加入多個音訊檔案,請在 content 清單中加入其他 "type": "audio", 項目。如果使用音訊資料提示,但沒有範本,請在提示文字中使用 <audio_soft_token> 語法。

執行文字生成

使用 processormodel 物件設定 Gemma 模型,並使用提示範本建立含有音訊資料的提示後,即可傳送提示來生成輸出內容。下列範例程式碼會顯示使用即時通訊範本的要求、輸出內容生成作業,以及回應的解碼作業:

input_ids = processor.apply_chat_template(
        messages,
        add_generation_prompt=True,
        tokenize=True, return_dict=True,
        return_tensors="pt",
)
input_ids = input_ids.to(model.device, dtype=model.dtype)

# Generate output from the model
outputs = model.generate(**input_ids, max_new_tokens=128)

# decode and print the output as text
text = processor.batch_decode(
    outputs,
    skip_special_tokens=False,
    clean_up_tokenization_spaces=False
)
print(text[0])

後續步驟

使用 Gemma 模型建構及探索更多內容: