Colab のマジック

このノートブックでは、PaLM 用の Colab マジック コマンドを紹介します。マジックを使用すると、Colab ノートブック内からプロンプトを簡単に開発、テスト、比較、評価できます。

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

設定

以下の手順に沿って、マジックをインストールしてテストします。

PaLM マジックのインストール

Colab または他の IPython 環境で PaLM マジック コマンドを使用するには、まず google-generativeai Python パッケージをダウンロードしてインストールする必要があります。

%pip install -q google-generativeai

PaLM マジックの読み込み

次に、%load_ext マジックを使用して %%palm マジックを読み込みます。

%load_ext google.generativeai.notebook

インストールをテストする

マジック コマンドが正しくインストールされているかどうかをテストするには、%%palm --help を実行します。PaLM API キーがない場合は、それも必要です(次のステップを参照)。

%%palm --help
usage: palm [-h] {run,compile,compare,eval} ...

A system for interacting with LLMs.

positional arguments:
  {run,compile,compare,eval}

options:
  -h, --help            show this help message and exit

PaLM API キーを取得する

PaLM API を使用するには、API キーを作成する必要があります。(この手順が必要なのは 1 回だけです)。

ノートブックで API キーを設定する

以下のセルを実行して API キーを設定します。

%env GOOGLE_API_KEY=YOUR PALM KEY

PaLM マジック コマンド: runcompilecompareevaluate

PaLM マジックには 4 種類のコマンドがあります。

  1. run
  2. compile
  3. compare
  4. evaluate

コマンド: palm run

run コマンドは、セルの内容をモデルに送信します。

プロンプトの実行はごく一般的なものであるため、コマンドが指定されていない場合、PaLM マジックはデフォルトで run コマンドを使用します。たとえば、次の 2 つのセルは同一です。

%%palm run
The opposite of hot is
%%palm
The opposite of hot is

出力の見方

Prompt 列にモデルに送信されたテキストが表示され、text_result 列に結果が表示されます。他の列については、このガイドを進めるにつれて紹介されます。

プロンプト テンプレート

プロンプトは固定文字列にする必要はありません。テンプレート プレースホルダを使用すると、{curly braces} を使用してプロンプトに値を挿入できます。

english_words = {
    # Each value here (hot, cold) will be substituted in for {word} in the prompt
    'word': ['hot', 'cold']
}
%%palm --inputs english_words
The opposite of {word} is

出力の見方

Input Num 列は、リスト内の入力単語のインデックスを追跡します。これらの例では、0Input Num'hot' で、1'cold' です。

複数の入力セットを指定する

一度に複数の入力セットを指定することもできます。

extreme_temperatures = {
    'word': ['hot', 'cold']
}
minor_temperatures = {
    'word': ['warm', 'chilly']
}
%%palm --inputs extreme_temperatures minor_temperatures
The opposite of {word} is

Google スプレッドシートからデータを読み取る

PaLM マジックでは、Google スプレッドシートの読み取りと書き込みも行えます。スプレッドシートのデータにアクセスするには、ログインする必要があります。このセクションでは、スプレッドシートからのデータの読み取りに焦点を当てます。後のセクションでは、Google スプレッドシートに出力を書き込む方法について説明します。

ログインしてスプレッドシートへのアクセスを承認する

PaLM マジックで使用するスプレッドシートの書式設定

Google スプレッドシートの ID または URL を --sheets_input_names フラグに渡して、テンプレート データとして読み込みます。

プロンプト テンプレートでデータを使用するには、スプレッドシートで次の形式を使用します。

  1. (プロンプト テンプレートの)変数の名前をシートの最初の行に入力します。
  2. 下の行に各変数に代入するデータを入力します。

たとえば、プロンプト テンプレートに nametemperament の 2 つの変数を代入する場合、スプレッドシートは次のように記述します。

name 気性
Milo 生意気
ビッグスリー リラックス
スブラ 恥ずかしい
%%palm --sheets_input_names https://docs.google.com/spreadsheets/d/1UHfpkmBqIX5RjeJcGXOevIEhMmEoKlf5f9teqwQyHqc/edit
Create a single sentence description of a monkey's personality. The monkey's name is {name} and it has a {temperament} temperament.

実際に試す

独自のデータでこれを試すには、新しいスプレッドシートを作成して ID を --sheets_input_names に渡します。ID や URL だけでなく、タイトルでシートを検索することもできます(例: %%palm --sheets_input_names "Animal adjectives")。

スプレッドシートの入力と Python の入力を組み合わせる

スプレッドシートの入力は --inputs と組み合わせることもできます。

new_monkeys = {
    'name': ['Hackerella'],
    'temperament': ['clever'],
}
%%palm --inputs new_monkeys --sheets_input_names 1UHfpkmBqIX5RjeJcGXOevIEhMmEoKlf5f9teqwQyHqc 1UHfpkmBqIX5RjeJcGXOevIEhMmEoKlf5f9teqwQyHqc
Create a single sentence description of a monkey's personality. The monkey's name is {name} and it has a {temperament} temperament.

コマンド: palm eval

%%palm eval を使用して、プロンプトの出力を既知のグラウンド トゥルース データと比較します。

test_data = {
    "word": ["dog", "cat", "house"]
}
ground_truth = ["chien", "chat", "maison"]
%%palm eval --inputs test_data --ground_truth ground_truth
English: Hello
French: Bonjour
English: {word}
French:

後処理モデルの出力

グラウンド トゥルース テストを実行するには、モデル出力の後処理が必要になることがあります。

後処理関数を使用すると、モデルの出力を処理する関数を定義できます。eval コマンドの場合、最終的な等価チェックでは結果列のみが使用されます。

post_process_replace_fn デコレータを使用して、結果を後処理する関数を定義します。

from google.generativeai.notebook import magics

# Define a function to extract only the first response.
@magics.post_process_replace_fn
def extract_and_normalize(input):
  first_line, *unused = input.split('English:')
  return first_line.strip().lower()

上で定義した extract_and_normalize 関数は、モデルからの出力を受け取り、繰り返されている言語ペアをカットし、最初のレスポンスのみを残します。後処理について詳しくは、後処理のセクションをご覧ください。

%%palm eval --inputs test_data --ground_truth ground_truth | extract_and_normalize
English: Hello
French: Bonjour
English: {word}
French:

コマンド: palm compile

%%palm compile コマンドを使用して、プレースホルダを含むプロンプトを Python 内から呼び出し可能な関数に変換します。

すべてのフラグと後処理は関数に「コンパイル」され、呼び出されたときに使用されます。

この例では、extract_and_normalize 後処理関数を使用して、translate_en_to_fr という関数を作成しています。

%%palm compile translate_en_to_fr | extract_and_normalize
English: Hello
French: Bonjour
English: {word}
French:
'Saved function to Python variable: translate_en_to_fr'
en_words = ['cat', 'dog']
translate_en_to_fr({'word': en_words})

出力形式

デフォルトでは、「コンパイル済み」関数は、Pandas DataFrame として表示されるオブジェクトとして出力を返します。ただし、.as_dict() または .as_dataframe() を使用して、それぞれ結果オブジェクトを DataFrame またはディクショナリに変換できます。

詳細については、--outputs フラグをご覧ください。

results = translate_en_to_fr({'word': en_words}).as_dict()

fr_words = results['text_result']

for en, fr in zip(en_words, fr_words):
  print(f'{fr} is French for {en}')
chat is French for cat
chien is French for dog

コマンド: palm compare

%%palm compare はコンパイルされたプロンプトを実行し、比較結果を並べて並べたテーブルを生成するため、相違点を調べることができます。

%%palm compile few_shot_prompt
English: Hello
French: Bonjour
English: {word}
French:
'Saved function to Python variable: few_shot_prompt'
%%palm compile zero_shot_prompt
{word} translated to French is:
'Saved function to Python variable: zero_shot_prompt'
words = {
    "word": ["dog", "cat", "house"]
}
%%palm compare few_shot_prompt zero_shot_prompt --inputs words

カスタム比較関数

デフォルトでは、compare は返された結果の等価性をチェックするだけです。ただし、--compare_fn フラグを使用して 1 つ以上のカスタム関数を指定できます。

def average_word_length(lhs, rhs):
  """Count the average number of words used across prompts."""
  return (len(lhs.split(' ')) + len(rhs.split(' '))) / 2

def shortest_answer(lhs, rhs):
  """Label the prompt that generated the shortest output."""
  if len(lhs) < len(rhs):
    return 'first'
  elif len(lhs) > len(rhs):
    return 'second'
  else:
    return 'same'
%%palm compare few_shot_prompt zero_shot_prompt --inputs words --compare_fn average_word_length shortest_answer

その他のコマンド

ヘルプ

--help フラグは、%%palm に直接渡すことができるサポートされているコマンドを表示します。

各コマンドの詳細なドキュメントを表示するには、--help を追加してください。例:

%%palm run --help
usage: palm run [-h] [--model_type {echo,text}] [--temperature TEMPERATURE]
                [--model MODEL] [--candidate_count CANDIDATE_COUNT] [--unique]
                [--inputs INPUTS [INPUTS ...]]
                [--sheets_input_names SHEETS_INPUT_NAMES [SHEETS_INPUT_NAMES ...]]
                [--outputs OUTPUTS [OUTPUTS ...]]
                [--sheets_output_names SHEETS_OUTPUT_NAMES [SHEETS_OUTPUT_NAMES ...]]

options:
  -h, --help            show this help message and exit
  --model_type {echo,text}, -mt {echo,text}
                        The type of model to use.
  --temperature TEMPERATURE, -t TEMPERATURE
                        Controls the randomness of the output. Must be
                        positive. Typical values are in the range: [0.0, 1.0].
                        Higher values produce a more random and varied
                        response. A temperature of zero will be deterministic.
  --model MODEL, -m MODEL
                        The name of the model to use. If not provided, a
                        default model will be used.
  --candidate_count CANDIDATE_COUNT, -cc CANDIDATE_COUNT
                        The number of candidates to produce.
  --unique              Whether to dedupe candidates returned by the model.
  --inputs INPUTS [INPUTS ...], -i INPUTS [INPUTS ...]
                        Optional names of Python variables containing inputs
                        to use to instantiate a prompt. The variable must be
                        either: a dictionary {'key1': ['val1', 'val2'] ...},
                        or an instance of LLMFnInputsSource such as
                        SheetsInput.
  --sheets_input_names SHEETS_INPUT_NAMES [SHEETS_INPUT_NAMES ...], -si SHEETS_INPUT_NAMES [SHEETS_INPUT_NAMES ...]
                        Optional names of Google Sheets to read inputs from.
                        This is equivalent to using --inputs with the names of
                        variables that are instances of SheetsInputs, just
                        more convenient to use.
  --outputs OUTPUTS [OUTPUTS ...], -o OUTPUTS [OUTPUTS ...]
                        Optional names of Python variables to output to. If
                        the Python variable has not already been defined, it
                        will be created. If the variable is defined and is an
                        instance of LLMFnOutputsSink, the outputs will be
                        written through the sink's write_outputs() method.
  --sheets_output_names SHEETS_OUTPUT_NAMES [SHEETS_OUTPUT_NAMES ...], -so SHEETS_OUTPUT_NAMES [SHEETS_OUTPUT_NAMES ...]
                        Optional names of Google Sheets to write inputs to.
                        This is equivalent to using --outputs with the names
                        of variables that are instances of SheetsOutputs, just
                        more convenient to use.

モデル

使用する PaLM モデル バリアントを指定するには、--model フラグを使用します。

サポートされているモデルを取得するには、list_models() メソッドをご覧ください。PaLM マジックは、generateText メソッドをサポートするすべてのモデルで使用できます。

%%palm run --model models/text-bison-001
My favourite color is

モデル パラメータ

--candidate_count--temperature などのモデル パラメータを構成することもできます。

%%palm run --model models/text-bison-001 --temperature 0.5
My favourite color is

デバッグ: エコーモデル

プロンプトをエコーする echo モデルも使用できます。API 呼び出しや割り当ての消費がないため、出力や後処理を迅速かつ簡単にテストできます。

%%palm --model_type echo
A duck's quack does not echo.

出力を Python にエクスポートする

PaLM マジックでは、表形式の出力を表示するだけでなく、モデル出力を Python 変数に保存できるため、出力をさらに操作したり、結果をエクスポートしたりできます。

この例では、出力は Python 変数 fave_colors に保存されます。

%%palm --outputs fave_colors
The best colors to wear in spring-time are

出力変数は、デフォルトで Pandas の DataFrame として表示されるカスタム オブジェクトです。as_dict() または as_pandas_dataframe() を呼び出すことで、明示的に Python の辞書またはデータフレームに強制変換できます。

from pprint import pprint

pprint(fave_colors.as_dict())
{'Input Num': [0],
 'Prompt': ['The best colors to wear in spring-time are'],
 'Prompt Num': [0],
 'Result Num': [0],
 'text_result': ['* Pastels: These soft, muted colors are perfect for the '
                 'springtime, as they are fresh and airy. Some popular pastel '
                 'colors include baby blue, mint green, and pale pink.\n'
                 '* Brights: If you want to make a statement, bright colors '
                 'are a great option for spring. Some popular bright colors '
                 'include fuchsia, cobalt blue, and yellow.\n'
                 '* Neutrals: Neutral colors are always a good choice, as they '
                 'can be easily dressed up or down. Some popular neutrals '
                 'include beige, gray, and white.\n'
                 '\n'
                 'When choosing colors to wear in the spring, it is important '
                 'to consider the occasion and your personal style. For '
                 'example, if you are attending a formal event, you may want '
                 'to choose a more muted color palette, such as pastels or '
                 'neutrals. If you are going for a more casual look, you may '
                 'want to choose brighter colors, such as brights or pastels.']}

Google スプレッドシートに書き込む

--sheets_output_names を使用すると、出力を Google スプレッドシートに保存し直すことができます。限定公開のスプレッドシートにアクセスするには、ログインしている必要があります。また、適切な権限が必要です。

この機能を試すには、新しいスプレッドシートを作成して「Translation results」という名前を付けます。入力フラグと同様に、--sheets_output_names フラグには、テキスト名の代わりにシートの URL または ID も指定できます。

%%palm --inputs english_words --sheets_output_names "Translation results"
English: Hello
French: Bonjour
English: {word}
French:

結果は新しいタブに保存され、ここ Colab で表示されるものと同じデータが含まれます。

保存したシートの例

複数の候補の生成

1 つのプロンプトに対して複数の出力を生成するには、--candidate_count をモデルに渡します。これはデフォルトでは 1 に設定されており、最上位の結果のみを出力します。

場合によっては、複数の候補に対して同じ出力が生成されることもあります。これらは --unique フラグを使用してフィルタできます。これにより、候補バッチから結果の重複が除去されます(ただし、複数のプロンプトにまたがっては除去されません)。

%%palm run --temperature 1.0 --candidate_count 8 --unique
In a single word, my favourite color is

Result Num 列では、同じプロンプトから生成された複数の候補を区別できます。

モデル出力の後処理

出力と構造の選択肢が多岐にわたるため、モデルの出力を問題領域に適応させるのは困難です。PaLM マジックには後処理オプションがあり、Python コードを使用してモデル出力を変更または処理できます。

後処理関数は、出力に新しい列を追加するか、text_result 列を変更できます。text_result 列は最後の列であり、eval コマンドと compare コマンドで最終出力を決定するために使用されます。

後処理で使用するサンプル関数を次に示します。1 つは新しい列を追加し、もう 1 つは post_process_replace_fn デコレータを使用して結果列を更新します。

import re
from google.generativeai.notebook import magics

# Add a new column.
def word_count(result):
  return len(result.split(' '))

# Modify the text_result column
@magics.post_process_replace_fn
def extract_first_sentence(result):
  """Extracts the first word from the raw result."""
  first, *_ = re.split(r'\.\s*', result)
  return first

これらの関数を使用するには、パイプ(|)演算子を使用して、%%palm コマンドに追加します。

%%palm run | word_count | extract_first_sentence
The happiest thing I can imagine is

ここでは順序が重要です。word_count が呼び出されると、元のモデル出力を使用して単語数が計算されます。これらを入れ替えると、単語数は、抽出された最初の文の単語数になります。

関連情報