Gemini API: Python を使用したモデルのチューニング

ai.google.dev で表示 Google Colab で実行 GitHub でソースを表示

このノートブックでは、Gemini API 用の Python クライアント ライブラリを使用してチューニング サービスを開始する方法を学びます。ここでは、Gemini API のテキスト生成サービスの背後にあるテキストモデルをチューニングする方法について説明します。

設定

認証

Gemini API を使用すると、独自のデータでモデルをチューニングできます。利用者自身のデータと調整済みモデルであるため、API キーが提供できるものよりも厳密なアクセス制御が必要になります。

このチュートリアルを実行する前に、プロジェクトに OAuth を設定する必要があります。

Colab でセットアップする最も簡単な方法は、client_secret.json ファイルのコンテンツを Colab の「シークレット マネージャー」(左側のパネルの鍵アイコンの下)にシークレット名 CLIENT_SECRET でコピーすることです。

この gcloud コマンドは、client_secret.json ファイルを、サービスでの認証に使用できる認証情報に変換します。

import os
if 'COLAB_RELEASE_TAG' in os.environ:
  from google.colab import userdata
  import pathlib
  pathlib.Path('client_secret.json').write_text(userdata.get('CLIENT_SECRET'))

  # Use `--no-browser` in colab
  !gcloud auth application-default login --no-browser --client-id-file client_secret.json --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.tuning'
else:
  !gcloud auth application-default login --client-id-file client_secret.json --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.tuning'

クライアント ライブラリをインストールする

pip install -q google-generativeai

ライブラリをインポートする

import google.generativeai as genai

既存のチューニング済みモデルは、genai.list_tuned_model メソッドで確認できます。

for i, m in zip(range(5), genai.list_tuned_models()):
  print(m.name)
tunedModels/my-model-8527
tunedModels/my-model-7092
tunedModels/my-model-2778
tunedModels/my-model-1298
tunedModels/my-model-3883

チューニング済みモデルを作成

チューニング済みモデルを作成するには、genai.create_tuned_model メソッドでデータセットをモデルに渡す必要があります。そのためには、呼び出しで入力値と出力値を直接定義するか、ファイルからデータフレームにインポートしてメソッドに渡します。

この例では、シーケンスの次の数値を生成するようにモデルをチューニングします。たとえば、入力が 1 の場合、モデルは 2 を出力する必要があります。入力が one hundred の場合、出力は one hundred one になります。

base_model = [
    m for m in genai.list_models()
    if "createTunedModel" in m.supported_generation_methods][0]
base_model
Model(name='models/gemini-1.0-pro-001',
      base_model_id='',
      version='001',
      display_name='Gemini 1.0 Pro',
      description=('The best model for scaling across a wide range of tasks. This is a stable '
                   'model that supports tuning.'),
      input_token_limit=30720,
      output_token_limit=2048,
      supported_generation_methods=['generateContent', 'countTokens', 'createTunedModel'],
      temperature=0.9,
      top_p=1.0,
      top_k=1)
import random

name = f'generate-num-{random.randint(0,10000)}'
operation = genai.create_tuned_model(
    # You can use a tuned model here too. Set `source_model="tunedModels/..."`
    source_model=base_model.name,
    training_data=[
        {
             'text_input': '1',
             'output': '2',
        },{
             'text_input': '3',
             'output': '4',
        },{
             'text_input': '-3',
             'output': '-2',
        },{
             'text_input': 'twenty two',
             'output': 'twenty three',
        },{
             'text_input': 'two hundred',
             'output': 'two hundred one',
        },{
             'text_input': 'ninety nine',
             'output': 'one hundred',
        },{
             'text_input': '8',
             'output': '9',
        },{
             'text_input': '-98',
             'output': '-97',
        },{
             'text_input': '1,000',
             'output': '1,001',
        },{
             'text_input': '10,100,000',
             'output': '10,100,001',
        },{
             'text_input': 'thirteen',
             'output': 'fourteen',
        },{
             'text_input': 'eighty',
             'output': 'eighty one',
        },{
             'text_input': 'one',
             'output': 'two',
        },{
             'text_input': 'three',
             'output': 'four',
        },{
             'text_input': 'seven',
             'output': 'eight',
        }
    ],
    id = name,
    epoch_count = 100,
    batch_size=4,
    learning_rate=0.001,
)

チューニング済みモデルはチューニング済みモデルのリストにすぐに追加されますが、モデルのチューニング中はステータスが「作成中」になります。

model = genai.get_tuned_model(f'tunedModels/{name}')

model
TunedModel(name='tunedModels/generate-num-2946',
           source_model='models/gemini-1.0-pro-001',
           base_model='models/gemini-1.0-pro-001',
           display_name='',
           description='',
           temperature=0.9,
           top_p=1.0,
           top_k=1,
           state=<State.CREATING: 1>,
           create_time=datetime.datetime(2024, 2, 21, 20, 4, 16, 448050, tzinfo=datetime.timezone.utc),
           update_time=datetime.datetime(2024, 2, 21, 20, 4, 16, 448050, tzinfo=datetime.timezone.utc),
           tuning_task=TuningTask(start_time=datetime.datetime(2024, 2, 21, 20, 4, 16, 890698, tzinfo=datetime.timezone.utc),
                                  complete_time=None,
                                  snapshots=[],
                                  hyperparameters=Hyperparameters(epoch_count=100,
                                                                  batch_size=4,
                                                                  learning_rate=0.001)))
model.state
<State.CREATING: 1>

チューニングの進行状況を確認する

metadata を使用して状態を確認します。

operation.metadata
total_steps: 375
tuned_model: "tunedModels/generate-num-2946"

operation.result() または operation.wait_bar() を使用してトレーニングが完了するまで待ちます。

import time

for status in operation.wait_bar():
  time.sleep(30)
0%|          | 0/375 [00:00<?, ?it/s]

チューニング ジョブは、cancel() メソッドを使用していつでもキャンセルできます。以下の行のコメント化を解除してコードセルを実行し、ジョブが完了する前にキャンセルします。

# operation.cancel()

チューニングが完了すると、チューニングの結果から損失曲線を表示できます。損失曲線は、モデルの予測が理想的な出力からどの程度逸脱しているかを示します。

import pandas as pd
import seaborn as sns

model = operation.result()

snapshots = pd.DataFrame(model.tuning_task.snapshots)

sns.lineplot(data=snapshots, x = 'epoch', y='mean_loss')
<Axes: xlabel='epoch', ylabel='mean_loss'>

png

モデルを評価する

genai.generate_text メソッドを使用して、モデルの名前を指定してモデルのパフォーマンスをテストできます。

model = genai.GenerativeModel(model_name=f'tunedModels/{name}')
result = model.generate_content('55')
result.text
'56'
result = model.generate_content('123455')
result.text
'123456'
result = model.generate_content('four')
result.text
'five'
result = model.generate_content('quatre') # French 4
result.text                               # French 5 is "cinq"
'cinq'
result = model.generate_content('III')    # Roman numeral 3
result.text                               # Roman numeral 4 is IV
'IV'
result = model.generate_content('七')  # Japanese 7
result.text                            # Japanese 8 is 八!
'八'

例が限られているにもかかわらず、タスクに成功したように思えますが、「次」は単純な概念です。パフォーマンスを向上させる方法については、チューニング ガイドをご覧ください。

説明を更新する

チューニング済みモデルの説明は、genai.update_tuned_model メソッドを使用していつでも更新できます。

genai.update_tuned_model(f'tunedModels/{name}', {"description":"This is my model."});
model = genai.get_tuned_model(f'tunedModels/{name}')

model.description
'This is my model.'

モデルを削除する

チューニング済みモデルリストは、不要になったモデルを削除することでクリーンアップできます。モデルを削除するには、genai.delete_tuned_model メソッドを使用します。チューニング ジョブをキャンセルした場合は、パフォーマンスが予測できないため、これらのジョブを削除することをおすすめします。

genai.delete_tuned_model(f'tunedModels/{name}')

モデルが存在しません:

try:
  m = genai.get_tuned_model(f'tunedModels/{name}')
  print(m)
except Exception as e:
  print(f"{type(e)}: {e}")
<class 'google.api_core.exceptions.NotFound'>: 404 Tuned model tunedModels/generate-num-2946 does not exist.