Colab 매직

이 노트북에서는 PaLM용 Colab 매직 명령어를 소개합니다. Magics를 사용하면 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 키를 만들어야 합니다. (이 단계는 한 번만 수행하면 됩니다.)

노트북에서 API 키 설정

아래 셀을 실행하여 API 키를 설정하세요.

%env GOOGLE_API_KEY=YOUR PALM KEY

PaLM 매직 명령어: run, compile, compare, evaluate

PaLM 매직은 네 가지 명령어를 제공합니다.

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

명령어: palm run

run 명령어는 셀의 콘텐츠를 모델로 전송합니다.

프롬프트 실행이 매우 일반적이기 때문에 명령어가 제공되지 않으면 PaLM 매직은 기본적으로 run 명령어를 사용합니다. 예를 들어 다음 두 셀은 동일합니다.

%%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 Sheets에서 데이터 읽기

PaLM의 매직 기능은 Google Sheets를 읽고 쓸 수도 있습니다. Sheets 데이터에 액세스하려면 로그인해야 합니다. 이 섹션에서는 Sheets에서 데이터 읽기에 중점을 둡니다. 이후 섹션에서 Google 시트에 출력을 쓰는 방법을 보여줍니다.

로그인하여 Sheets 액세스 승인

<ph type="x-smartling-placeholder">

PaLM 매직에서 사용할 스프레드시트 형식 지정

Google 시트의 ID 또는 URL을 --sheets_input_names 플래그에 전달하여 템플릿 데이터로 로드합니다.

프롬프트 템플릿의 데이터를 사용하려면 스프레드시트에서 다음 형식을 사용합니다.

  1. 프롬프트 템플릿의 변수 이름을 시트의 첫 번째 행에 입력합니다.
  2. 아래 행의 각 변수를 대체할 데이터를 입력합니다.

예를 들어 프롬프트 템플릿에 nametemperament라는 두 개의 대체 변수가 있는 경우 스프레드시트를 다음과 같이 작성합니다.

이름 성격
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"

Sheets 입력과 Python 입력 결합

Sheets 입력은 --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 내에서 호출 가능한 함수로 변환합니다.

모든 플래그와 후처리가 '컴파일'됨 함수에 추가하고 호출 시 사용됩니다.

이 예에서는 beforeextract_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})

출력 형식

기본적으로 'compiled' 함수는 출력을 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 플래그를 사용하여 하나 이상의 커스텀 함수를 지정할 수 있습니다.

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.

모델

--model 플래그를 사용하여 사용할 PaLM 모델 변형을 지정합니다.

지원되는 모델을 검색하려면 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 사전 또는 DataFrame으로 강제 변환할 수 있습니다.

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에 쓰기

--sheets_output_names를 사용하여 출력을 Google Sheets에 다시 저장할 수 있습니다. 로그인해야 하며 비공개 시트에 액세스하려면 적절한 권한이 있어야 합니다.

이렇게 하려면 새 시트를 만들고 이름을 Translation results로 지정합니다. 입력 플래그와 마찬가지로 --sheets_output_names 플래그는 텍스트 이름 대신 시트 URL이나 ID를 사용할 수도 있습니다.

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

결과는 새 탭에 저장되며 여기 Colab에 표시되는 것과 동일한 데이터를 포함합니다.

저장된 시트의 예

여러 후보 생성

단일 프롬프트의 출력을 두 개 이상 생성하려면 --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 열은 마지막 열이며 evalcompare 명령어에서 최종 출력을 결정하는 데 사용됩니다.

다음은 후처리에 사용할 수 있는 몇 가지 샘플 함수입니다. 하나는 새 열을 추가하고 다른 하나는 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가 호출되면 원래 모델 출력이 단어 수를 계산하는 데 사용됩니다. 이 숫자를 바꾸면 단어 수는 추출된 첫 번째 문장의 단어 수가 됩니다.

추가 자료