ai.google.dev で表示 | Google Colab で実行 | GitHub のソースを表示 |
このノートブックでは、Gemini API 用の Python クライアント ライブラリを使用してチューニング サービスの使用を開始する方法を学習します。ここでは Gemini API のテキスト生成サービスの 背後にあるテキストモデルをチューニングする方法を説明します
始める前に: プロジェクトと API キーを設定する
Gemini API を呼び出す前に、プロジェクトをセットアップして 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'>
モデルを評価する
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 八!
'八'
例は限られていますが、実際にはタスクを問題なく受け取っているようですが、「next」は比較的シンプルなコンセプトです。パフォーマンス改善に関する詳細なガイダンスについては、チューニング ガイドをご覧ください。
説明を更新する
チューニング済みモデルの説明は、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.