KerasNLP를 사용하여 Gemma 시작하기

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

이 튜토리얼에서는 KerasNLP를 사용하여 Gemma를 시작하는 방법을 보여줍니다. Gemma는 Gemini 모델을 만드는 데 사용된 연구와 기술로 빌드된 경량의 최첨단 개방형 모델 제품군입니다. KerasNLP는 Keras에서 구현되고 JAX, PyTorch, TensorFlow에서 실행 가능한 자연어 처리 (NLP) 모델 컬렉션입니다.

이 튜토리얼에서는 Gemma를 사용하여 여러 프롬프트에 대한 텍스트 응답을 생성합니다. Keras를 처음 사용하는 경우 시작하기 전에 Keras 시작하기를 읽어보는 것도 좋지만 꼭 읽어야 할 필요는 없습니다. 이 튜토리얼을 진행하면서 Keras에 관해 자세히 알아보겠습니다.

설정

Gemma 설정

이 튜토리얼을 완료하려면 먼저 Gemma 설정에서 설정 안내를 완료해야 합니다. Gemma 설정 안내에서는 다음 작업을 실행하는 방법을 보여줍니다.

  • kaggle.com에서 젬마에 액세스하세요.
  • Gemma 2B 모델을 실행하기에 충분한 리소스가 포함된 Colab 런타임을 선택합니다.
  • Kaggle 사용자 이름과 API 키를 생성하고 구성합니다.

Gemma 설정을 완료한 후에는 다음 섹션으로 이동하여 Colab 환경의 환경 변수를 설정합니다.

환경 변수 설정하기

KAGGLE_USERNAMEKAGGLE_KEY의 환경 변수를 설정합니다.

import os
from google.colab import userdata

# Note: `userdata.get` is a Colab API. If you're not using Colab, set the env
# vars as appropriate for your system.
os.environ["KAGGLE_USERNAME"] = userdata.get('KAGGLE_USERNAME')
os.environ["KAGGLE_KEY"] = userdata.get('KAGGLE_KEY')

종속 항목 설치

Keras 및 KerasNLP를 설치합니다.

# Install Keras 3 last. See https://keras.io/getting_started/ for more details.
pip install -q -U keras-nlp
pip install -q -U keras>=3

백엔드 선택

Keras는 단순성과 사용 편의성을 위해 설계된 높은 수준의 다중 프레임워크 딥 러닝 API입니다. Keras 3에서는 백엔드(TensorFlow, JAX, PyTorch)를 선택할 수 있습니다. 세 가지 모두 이 튜토리얼에서 작동합니다.

import os

os.environ["KERAS_BACKEND"] = "jax"  # Or "tensorflow" or "torch".
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.9"

패키지 가져오기

Keras 및 KerasNLP를 가져옵니다.

import keras
import keras_nlp

모델 만들기

KerasNLP는 널리 사용되는 여러 모델 아키텍처의 구현을 제공합니다. 이 튜토리얼에서는 인과적 언어 모델링을 위한 엔드 투 엔드 Gemma 모델인 GemmaCausalLM를 사용하여 모델을 만듭니다. 인과적 언어 모델은 이전 토큰을 기반으로 다음 토큰을 예측합니다.

from_preset 메서드를 사용하여 모델을 만듭니다.

gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset("gemma_2b_en")
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/1' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/1' to your Colab notebook...
Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_2b_en/1' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_2b_en/1' to your Colab notebook...
Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_2b_en/1' to your Colab notebook...

from_preset는 미리 설정된 아키텍처와 가중치에서 모델을 인스턴스화합니다. 위의 코드에서 문자열 "gemma_2b_en"는 미리 설정된 아키텍처, 즉 20억 개의 매개변수가 있는 Gemma 모델을 지정합니다.

summary를 사용하여 모델에 대한 자세한 정보를 가져옵니다.

gemma_lm.summary()

요약에서 볼 수 있듯이 이 모델에는 25억 개의 학습 가능한 매개변수가 있습니다.

텍스트 생성

이제 텍스트를 생성할 차례입니다. 모델에는 프롬프트를 기반으로 텍스트를 생성하는 generate 메서드가 있습니다. 선택사항인 max_length 인수는 생성된 시퀀스의 최대 길이를 지정합니다.

"What is the meaning of life?" 프롬프트로 시도해 보세요.

gemma_lm.generate("What is the meaning of life?", max_length=64)
'What is the meaning of life?\n\nThe question is one of the most important questions in the world.\n\nIt’s the question that has been asked by philosophers, theologians, and scientists for centuries.\n\nAnd it’s the question that has been asked by people who are looking for answers to their own lives'

다른 메시지로 generate를 다시 호출해 보세요.

gemma_lm.generate("How does the brain work?", max_length=64)
'How does the brain work?\n\nThe brain is the most complex organ in the human body. It is responsible for controlling all of the body’s functions, including breathing, heart rate, digestion, and more. The brain is also responsible for thinking, feeling, and making decisions.\n\nThe brain is made up'

JAX 또는 TensorFlow 백엔드에서 실행 중인 경우 두 번째 generate 호출이 거의 즉시 반환됩니다. 지정된 배치 크기 및 max_length의 각 generate 호출이 XLA로 컴파일되기 때문입니다. 첫 번째 실행은 비용이 많이 들지만 후속 실행은 훨씬 빠릅니다.

목록을 입력으로 사용하여 일괄 프롬프트를 제공할 수도 있습니다.

gemma_lm.generate(
    ["What is the meaning of life?",
     "How does the brain work?"],
    max_length=64)
['What is the meaning of life?\n\nThe question is one of the most important questions in the world.\n\nIt’s the question that has been asked by philosophers, theologians, and scientists for centuries.\n\nAnd it’s the question that has been asked by people who are looking for answers to their own lives',
 'How does the brain work?\n\nThe brain is the most complex organ in the human body. It is responsible for controlling all of the body’s functions, including breathing, heart rate, digestion, and more. The brain is also responsible for thinking, feeling, and making decisions.\n\nThe brain is made up']

선택사항: 다른 샘플러 사용해 보기

compile()sampler 인수를 설정하여 GemmaCausalLM의 생성 전략을 제어할 수 있습니다. 기본적으로 "greedy" 샘플링이 사용됩니다.

"top_k" 전략을 실험해 보세요.

gemma_lm.compile(sampler="top_k")
gemma_lm.generate("What is the meaning of life?", max_length=64)
'What is the meaning of life? That was a question I asked myself as I was driving home from work one night in 2012. I was driving through the city of San Bernardino, and all I could think was, “What the heck am I doing?”\n\nMy life was completely different. I'

기본 그리디 알고리즘은 항상 확률이 가장 큰 토큰을 선택하지만, Top-K 알고리즘은 최상위 K 확률의 토큰 중에서 다음 토큰을 무작위로 선택합니다.

샘플러를 지정할 필요는 없으며, 사용 사례에 도움이 되지 않는다면 마지막 코드 스니펫을 무시해도 됩니다. 사용 가능한 샘플러에 관해 자세히 알아보려면 샘플러를 참고하세요.

다음 단계

이 튜토리얼에서는 KerasNLP 및 Gemma를 사용하여 텍스트를 생성하는 방법을 알아봤습니다. 다음에 학습할 내용에 관한 몇 가지 제안사항은 다음과 같습니다.