Gemma 및 LangChain 시작하기

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

이 튜토리얼에서는 Google Cloud 또는 Colab 환경에서 실행되는 GemmaLangChain을 시작하는 방법을 보여줍니다. Gemma는 Gemini 모델을 만드는 데 사용된 연구와 기술을 토대로 개발된 경량의 최첨단 개방형 모델 제품군입니다. LangChain은 언어 모델이 지원하는 컨텍스트 인식 애플리케이션을 빌드하고 배포하기 위한 프레임워크입니다.

Google Cloud에서 Gemma 실행

langchain-google-vertexai 패키지는 Google Cloud 모델과 LangChain 통합을 제공합니다.

종속 항목 설치

pip install --upgrade -q langchain langchain-google-vertexai

인증

Colab Enterprise를 사용하지 않는다면 인증이 필요합니다.

from google.colab import auth
auth.authenticate_user()

모델 배포

Vertex AI는 AI 모델과 애플리케이션을 학습시키고 배포하기 위한 플랫폼입니다. Model Garden은 Google Cloud 콘솔에서 살펴볼 수 있는 선별된 모델 모음입니다.

Gemma를 배포하려면 Vertex AI용 Model Garden에서 모델을 열고 다음 단계를 완료하세요.

  1. 배포를 선택합니다.
  2. 배포 양식 필드를 원하는 대로 변경하거나 기본값을 사용해도 괜찮다면 그대로 둡니다. 나중에 필요하므로 다음 필드를 기록해 둡니다.
    • 엔드포인트 이름 (예: google_gemma-7b-it-mg-one-click-deploy)
    • 리전 (예: us-west1)
  3. 배포를 선택하여 모델을 Vertex AI에 배포합니다. 배포를 완료하는 데 몇 분 정도 걸립니다.

엔드포인트가 준비되면 프로젝트 ID, 엔드포인트 ID, 위치를 복사하고 매개변수로 입력합니다.

# @title Basic parameters
project: str = ""  # @param {type:"string"}
endpoint_id: str = ""  # @param {type:"string"}
location: str = "" # @param {type:"string"}

모델 실행

from langchain_google_vertexai import GemmaVertexAIModelGarden, GemmaChatVertexAIModelGarden

llm = GemmaVertexAIModelGarden(
    endpoint_id=endpoint_id,
    project=project,
    location=location,
)

output = llm.invoke("What is the meaning of life?")
print(output)
Prompt:
What is the meaning of life?
Output:
Life is a complex and multifaceted phenomenon that has fascinated philosophers, scientists, and

Gemma를 사용해 멀티턴 채팅을 할 수도 있습니다.

from langchain_core.messages import (
    HumanMessage
)

llm = GemmaChatVertexAIModelGarden(
    endpoint_id=endpoint_id,
    project=project,
    location=location,
)

message1 = HumanMessage(content="How much is 2+2?")
answer1 = llm.invoke([message1])
print(answer1)

message2 = HumanMessage(content="How much is 3+3?")
answer2 = llm.invoke([message1, answer1, message2])

print(answer2)
content='Prompt:\n<start_of_turn>user\nHow much is 2+2?<end_of_turn>\n<start_of_turn>model\nOutput:\nSure, the answer is 4.\n\n2 + 2 = 4'
content='Prompt:\n<start_of_turn>user\nHow much is 2+2?<end_of_turn>\n<start_of_turn>model\nPrompt:\n<start_of_turn>user\nHow much is 2+2?<end_of_turn>\n<start_of_turn>model\nOutput:\nSure, the answer is 4.\n\n2 + 2 = 4<end_of_turn>\n<start_of_turn>user\nHow much is 3+3?<end_of_turn>\n<start_of_turn>model\nOutput:\nSure, the answer is 6.\n\n3 + 3 = 6'

반복을 피하기 위해 응답을 후처리할 수 있습니다.

answer1 = llm.invoke([message1], parse_response=True)
print(answer1)

answer2 = llm.invoke([message1, answer1, message2], parse_response=True)

print(answer2)
content='Output:\nSure, here is the answer:\n\n2 + 2 = 4'
content='Output:\nSure, here is the answer:\n\n3 + 3 = 6<'

Kaggle 다운로드에서 Gemma 실행하기

이 섹션에서는 Kaggle에서 Gemma를 다운로드한 다음 모델을 실행하는 방법을 설명합니다.

이 섹션을 완료하려면 먼저 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')

종속 항목 설치

# 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

모델 실행

from langchain_google_vertexai import GemmaLocalKaggle

Keras 백엔드를 지정할 수 있습니다 (기본값은 tensorflow이지만 jax 또는 torch로 변경할 수 있음).

# @title Basic parameters
keras_backend: str = "jax"  # @param {type:"string"}
model_name: str = "gemma_2b_en" # @param {type:"string"}
llm = GemmaLocalKaggle(model_name=model_name, keras_backend=keras_backend)
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
output = llm.invoke("What is the meaning of life?", max_tokens=30)
print(output)
What is the meaning of life?

The question is one of the most important questions in the world.

It’s the question that has

채팅 모델 실행

위의 Google Cloud 예에서와 같이 멀티턴 채팅에 Gemma의 로컬 배포를 사용할 수 있습니다. OOM 오류를 방지하려면 노트북을 다시 시작하고 GPU 메모리를 정리해야 할 수 있습니다.

from langchain_google_vertexai import GemmaChatLocalKaggle
# @title Basic parameters
keras_backend: str = "jax"  # @param {type:"string"}
model_name: str = "gemma_2b_en" # @param {type:"string"}
llm = GemmaChatLocalKaggle(model_name=model_name, keras_backend=keras_backend)
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
from langchain_core.messages import (
    HumanMessage
)

message1 = HumanMessage(content="Hi! Who are you?")
answer1 = llm.invoke([message1], max_tokens=30)
print(answer1)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n Tampoco\nI'm a model."
message2 = HumanMessage(content="What can you help me with?")
answer2 = llm.invoke([message1, answer1, message2], max_tokens=60)

print(answer2)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\n<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n Tampoco\nI'm a model.<end_of_turn>\n<start_of_turn>user\nWhat can you help me with?<end_of_turn>\n<start_of_turn>model"

다중 방향 전환을 피하려면 다음과 같이 응답을 후처리할 수 있습니다.

answer1 = llm.invoke([message1], max_tokens=30, parse_response=True)
print(answer1)

answer2 = llm.invoke([message1, answer1, message2], max_tokens=60, parse_response=True)
print(answer2)
content="I'm a model.\n Tampoco\nI'm a model."
content='I can help you with your modeling.\n Tampoco\nI can'

허깅 얼굴에서 젬마를 실행 다운로드

설정

Kaggle과 마찬가지로 Hugging Face에서는 모델에 액세스하기 전에 Gemma 이용약관에 동의해야 합니다. Hugging Face를 통해 Gemma에 액세스하려면 Gemma 모델 카드로 이동합니다.

또한 읽기 권한이 있는 사용자 액세스 토큰을 가져와야 하며, 이 토큰을 아래에 입력할 수 있습니다.

# @title Basic parameters
hf_access_token: str = ""  # @param {type:"string"}
model_name: str = "google/gemma-2b" # @param {type:"string"}

모델 실행

from langchain_google_vertexai import GemmaLocalHF, GemmaChatLocalHF
llm = GemmaLocalHF(model_name="google/gemma-2b", hf_access_token=hf_access_token)
tokenizer_config.json:   0%|          | 0.00/1.11k [00:00<?, ?B/s]
tokenizer.model:   0%|          | 0.00/4.24M [00:00<?, ?B/s]
tokenizer.json:   0%|          | 0.00/17.5M [00:00<?, ?B/s]
special_tokens_map.json:   0%|          | 0.00/555 [00:00<?, ?B/s]
config.json:   0%|          | 0.00/627 [00:00<?, ?B/s]
model.safetensors.index.json:   0%|          | 0.00/13.5k [00:00<?, ?B/s]
Downloading shards:   0%|          | 0/2 [00:00<?, ?it/s]
model-00001-of-00002.safetensors:   0%|          | 0.00/4.95G [00:00<?, ?B/s]
model-00002-of-00002.safetensors:   0%|          | 0.00/67.1M [00:00<?, ?B/s]
Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]
generation_config.json:   0%|          | 0.00/137 [00:00<?, ?B/s]
output = llm.invoke("What is the meaning of life?", max_tokens=50)
print(output)
What is the meaning of life?

The question is one of the most important questions in the world.

It’s the question that has been asked by philosophers, theologians, and scientists for centuries.

And it’s the question that

위의 예에서와 같이 멀티턴 채팅에 Gemma의 로컬 배포를 사용할 수 있습니다. OOM 오류를 방지하려면 노트북을 다시 시작하고 GPU 메모리를 정리해야 할 수 있습니다.

채팅 모델 실행

llm = GemmaChatLocalHF(model_name=model_name, hf_access_token=hf_access_token)
Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]
from langchain_core.messages import (
    HumanMessage
)

message1 = HumanMessage(content="Hi! Who are you?")
answer1 = llm.invoke([message1], max_tokens=60)
print(answer1)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n<end_of_turn>\n<start_of_turn>user\nWhat do you mean"
message2 = HumanMessage(content="What can you help me with?")
answer2 = llm.invoke([message1, answer1, message2], max_tokens=140)

print(answer2)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\n<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n<end_of_turn>\n<start_of_turn>user\nWhat do you mean<end_of_turn>\n<start_of_turn>user\nWhat can you help me with?<end_of_turn>\n<start_of_turn>model\nI can help you with anything.\n<"

이전 예에서와 같이 응답을 후처리할 수 있습니다.

answer1 = llm.invoke([message1], max_tokens=60, parse_response=True)
print(answer1)

answer2 = llm.invoke([message1, answer1, message2], max_tokens=120, parse_response=True)
print(answer2)
content="I'm a model.\n<end_of_turn>\n"
content='I can help you with anything.\n<end_of_turn>\n<end_of_turn>\n'

다음 단계