การอนุมานข้อความพื้นฐานของ Gemma

ดูที่ ai.google.dev เรียกใช้ใน Google Colab เรียกใช้ใน Kaggle เปิดใน Vertex AI ดูแหล่งข้อมูลใน GitHub

Gemma เป็นกลุ่มผลิตภัณฑ์โมเดลแบบเปิดที่มีน้ำหนักเบาและล้ำสมัย ซึ่งสร้างขึ้นจากการวิจัยและเทคโนโลยีเดียวกันกับที่ใช้สร้างโมเดล Gemini Gemma 4 ออกแบบมาให้เป็นกลุ่มโมเดลแบบเปิดที่มีน้ำหนักเบาที่สุดในโลก

เอกสารนี้เป็นคู่มือสำหรับการอนุมานข้อความพื้นฐานด้วย Gemma 4 โดยใช้ไลบรารี transformers ของ Hugging Face โดยจะครอบคลุมการตั้งค่าสภาพแวดล้อม การโหลดโมเดล และสถานการณ์การสร้างข้อความต่างๆ รวมถึงพรอมต์แบบเทิร์นเดียว การสนทนาแบบหลายเทิร์นที่มีโครงสร้าง และการใช้คำสั่งของระบบ

Notebook นี้จะทำงานบน GPU T4

ติดตั้งแพ็กเกจ Python

ติดตั้งไลบรารี Hugging Face ที่จำเป็นสำหรับการเรียกใช้โมเดล Gemma และส่งคำขอ

# Install PyTorch & other libraries
pip install torch accelerate

# Install the transformers library
pip install transformers

Dialog เป็นไลบรารีสำหรับจัดการและแสดงการสนทนา

pip install dialog

โหลดโมเดล

ใช้ไลบรารี transformers เพื่อโหลดไปป์ไลน์

MODEL_ID = "google/gemma-4-E2B-it" # @param ["google/gemma-4-E2B-it","google/gemma-4-E4B-it", "google/gemma-4-31B-it", "google/gemma-4-26B-A4B-it"]

from transformers import pipeline

txt_pipe = pipeline(
    task="text-generation",
    model=MODEL_ID,
    device_map="auto",
    dtype="auto"
)
Loading weights:   0%|          | 0/2011 [00:00<?, ?it/s]

เรียกใช้การสร้างข้อความ

เมื่อโหลดและกำหนดค่าโมเดล Gemma ในออบเจ็กต์ pipeline แล้ว คุณจะส่งพรอมต์ไปยังโมเดลได้ ตัวอย่างโค้ดต่อไปนี้แสดงคำขอพื้นฐานโดยใช้พารามิเตอร์ text_inputs

output = txt_pipe(text_inputs="<|turn>user\nRoses are..<turn|>\n<|turn>model\n")
print(output[0]['generated_text'])
Both `max_new_tokens` (=256) and `max_length`(=20) seem to have been set. `max_new_tokens` will take precedence. Please refer to the documentation for more information. (https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)
<|turn>user
Roses are..<turn|>
<|turn>model
Here are a few ways to complete the phrase "Roses are...":

**Classic/Poetic:**

* **Roses are red.** (The most famous completion, though it usually goes "Roses are red, Violets are blue.")
* **Roses are beautiful.**
* **Roses are fragrant.**

**Simple/Direct:**

* **Roses are lovely.**
* **Roses are soft.**

**If you want a specific tone, let me know! 😊**

ใช้ไลบรารี Dialog

import dialog
from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 512

conv = dialog.Conversation(
    dialog.User("Roses are...")
)
output = txt_pipe(text_inputs=conv.as_text(), return_full_text=False, generation_config=config)
conv += dialog.Model(output[0]['generated_text'])

print(conv.as_text())
conv.show()
<|turn>user
Roses are...<turn|>
<|turn>model
Here are a few ways to complete the phrase "Roses are...":

**Focusing on their beauty:**

* **Roses are beautiful.**
* **Roses are gorgeous.**

**Focusing on their scent:**

* **Roses are fragrant.**
* **Roses are sweet-smelling.**

**Focusing on their symbolism (if you want a deeper meaning):**

* **Roses are love.**
* **Roses are romantic.**

**Focusing on a general observation:**

* **Roses are lovely.**
* **Roses are wonderful.**

**Which completion do you like best, or were you thinking of a specific meaning?**
<dialog._src.widget.Conversation object at 0x7f1bb1a5d8b0>

ใช้เทมเพลตพรอมต์

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

from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 512

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Write a short poem about the Kraken."},
        ]
    }
]

output = txt_pipe(messages, return_full_text=False, generation_config=config)
print(output[0]['generated_text'])
From sunless depths, a shadow stirs,
Where ocean's crushing silence blurs.
A titan sleeps in inky night,
With tentacles of dreadful might.

A hundred arms, a crushing hold,
A legend whispered, ages old.
The deep's dark king, a monstrous grace,
The Kraken claims its watery space.

การสนทนาหลายรอบ

ในการตั้งค่าแบบหลายรอบ ระบบจะเก็บประวัติการสนทนาไว้เป็นลำดับของบทบาท user และ model ที่สลับกัน รายการสะสมนี้ทำหน้าที่เป็นหน่วยความจำของโมเดล เพื่อให้มั่นใจว่าเอาต์พุตใหม่แต่ละรายการจะอิงตามบทสนทนาก่อนหน้า

import dialog
from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 512

# User turn #1
conv = dialog.Conversation(
    dialog.User("Write a short poem about the Kraken.")
)

# Model response #1
output = txt_pipe(text_inputs=conv.as_text(), return_full_text=False, generation_config=config)
conv += dialog.Model(output[0]['generated_text'])

# User turn #2
conv += dialog.User("Now with the Siren.")

# Model response #2
output = txt_pipe(text_inputs=conv.as_text(), return_full_text=False, generation_config=config)
conv += dialog.Model(output[0]['generated_text'])

print(conv.as_text())
conv.show()
<|turn>user
Write a short poem about the Kraken.<turn|>
<|turn>model
In depths where sunlight fades,
A monstrous shadow plays.
The Kraken wakes, with churning tide,
A living horror, bold and wide.<turn|>
<|turn>user
Now with the Siren.<turn|>
<|turn>model
Where coral gardens sleep,
And ocean secrets keep,
The Siren calls, with liquid grace,
A haunting melody in place.
<dialog._src.widget.Conversation object at 0x7f1bac3733b0>

และนี่คือการสนทนาที่ส่งออกเป็นข้อความ

เสมอ
chat_history = conv.as_text(training=True)
print(chat_history)
print("-"*80)

# display as Conversation widget
chat_history
<|turn>user
Write a short poem about the Kraken.<turn|>
<|turn>model
In depths where sunlight fades,
A monstrous shadow plays.
The Kraken wakes, with churning tide,
A living horror, bold and wide.<turn|>
<|turn>user
Now with the Siren.<turn|>
<|turn>model
Where coral gardens sleep,
And ocean secrets keep,
The Siren calls, with liquid grace,
A haunting melody in place.<turn|>
--------------------------------------------------------------------------------
<dialog._src.widget.ConversationStr object at 0x7f1bb07fa1b0>

คำสั่งของระบบ

ใช้บทบาท system เพื่อให้คำสั่งระดับระบบ

import dialog
from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 512

conv = dialog.Conversation(
    dialog.System("Speak like a pirate."),
    dialog.User("Why is the sky blue?")
)

output = txt_pipe(text_inputs=conv.as_text(), return_full_text=False, generation_config=config)
conv += dialog.Model(output[0]['generated_text'])

print(conv.as_text())
conv.show()
<|turn>system
Speak like a pirate.<turn|>
<|turn>user
Why is the sky blue?<turn|>
<|turn>model
Ahoy there! Why is the sky blue, ye ask? It be down to the way the sun's light dances through the air!

See, the sunlight we get from the sun ain't just one color; it's a whole spectrum of colors, like a treasure chest filled with all the hues of the rainbow!

Now, the Earth is surrounded by the air, and that air is full of tiny, invisible bits of gas. When the sunlight hits these gas molecules, something magical happens. The colors in that sunlight get scattered all around in every direction!

The blue light, and other colors, get scattered more easily by these air molecules than the other colors. So, when you look up at the sky, your eyes catch all that scattered blue light coming from every direction, and **that's what makes the sky appear blue to us!**

It's a grand display of physics and light, savvy? Now, hoist the colors and enjoy the view!
<dialog._src.widget.Conversation object at 0x7f1bac370110>

สรุปและขั้นตอนถัดไป

ในคู่มือนี้ คุณได้เรียนรู้วิธีทำการอนุมานข้อความพื้นฐานด้วย Gemma 4 โดยใช้ไลบรารี transformers ของ Hugging Face คุณได้ดำเนินการต่อไปนี้

  • การตั้งค่าสภาพแวดล้อมและการติดตั้งทรัพยากร Dependency
  • การโหลดโมเดลโดยใช้pipelineการแยกส่วน
  • การสร้างข้อความพื้นฐาน
  • การใช้dialogไลบรารีสำหรับการติดตามการสนทนา
  • การใช้การสนทนาแบบหลายรอบและการใช้คำสั่งของระบบ

ขั้นตอนถัดไป