Gemma 기본 텍스트 추론

ai.google.dev에서 보기 Google Colab에서 실행 Kaggle에서 실행 Vertex AI에서 열기 GitHub에서 소스 보기

Gemma는 Gemini 모델을 만드는 데 사용되는 것과 동일한 연구와 기술로 빌드된 최첨단 경량 개방형 모델군입니다. Gemma 4는 세계에서 가장 효율적인 개방형 가중치 모델군이 되도록 설계되었습니다.

이 문서는 Hugging Face transformers 라이브러리를 사용하여 Gemma 4로 기본 텍스트 추론을 실행하는 방법을 안내합니다. 여기에서는 환경 설정, 모델 로드, 단일 턴 프롬프트, 구조화된 멀티턴 대화, 시스템 안내 적용 등 다양한 텍스트 생성 시나리오를 다룹니다.

이 노트북은 T4 GPU에서 실행됩니다.

Python 패키지 설치

Gemma 모델을 실행하고 요청을 보내는 데 필요한 Hugging Face 라이브러리를 설치합니다.

# 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]

텍스트 생성 실행

pipeline 객체에 Gemma 모델을 로드하고 구성한 후 모델에 프롬프트를 보낼 수 있습니다. 다음 예시 코드는 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>

요약 및 다음 단계

이 가이드에서는 Hugging Face transformers 라이브러리를 사용하여 Gemma 4로 기본 텍스트 추론을 실행하는 방법을 알아보았습니다. 다음 내용을 다루었습니다.

  • 환경 설정 및 종속 항목 설치
  • pipeline 추상화를 사용하여 모델 로드
  • 기본 텍스트 생성 실행
  • 대화 추적을 위한 dialog 라이브러리 사용
  • 멀티턴 대화 구현 및 시스템 안내 적용

다음 단계