Transformers documentation

プロンプトエンジニアリング

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

プロンプトエンジニアリング

プロンプトエンジニアリング(プロンプト)は、自然言語を用いて大規模言語モデル(LLM)の多様なタスクにおけるパフォーマンスを向上させる手法です。プロンプトによって、モデルが望ましい出力を生成するよう誘導できます。多くの場合、タスクのためにファインチューニングされたモデルは必要ありません。良いプロンプトさえあれば十分です。

LLMにテキストの分類を促すプロンプトを作成してみてください。プロンプトを作成する際は、タスクの内容や期待される結果の形式について、非常に具体的な指示を与えることが重要です。

from transformers import pipeline
import torch

pipeline = pipeline(task="text-generation", model="mistralai/Mistral-7B-Instruct-v0.1", dtype=torch.bfloat16, device_map="auto")
prompt = """Classify the text into neutral, negative or positive.
Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code amongst thieves and policemen.
Sentiment:
"""

outputs = pipeline(prompt, max_new_tokens=10)
for output in outputs:
    print(f"Result: {output['generated_text']}")
Result: Classify the text into neutral, negative or positive. 
Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code amongst thieves and policemen.
Sentiment:
Positive

課題は、言語が非常に微妙で表現力豊かであるため、期待通りの結果を生成するプロンプトを設計することにあります。

このガイドでは、言語処理および推論タスクを解決するためのプロンプトエンジニアリングのベストプラクティス、テクニック、および例について説明します。

ベストプラクティス

  1. 最高のパフォーマンスを得るには、最新のモデルを選択することをお勧めします。LLMには、baseとinstruction-tuned(またはチャット)という2つのバリアントがある点に注意してください。

    ベースモデルは、初期プロンプトを与えられた際のテキスト補完に優れていますが、指示の追従にはやや劣ります。インストラクションチューニング済みモデルは、ベースモデルを指示データや会話データで特別に訓練したバージョンです。そのため、インストラクションチューニング済みモデルの方が、プロンプト入力との相性が良くなります。

    最新のLLMは通常、デコーダーオンリーモデルですが、Flan-T5やBARTのようなエンコーダーデコーダー型のLLMもあり、プロンプト処理に使用できます。これらのモデルは、Pipelineを使用する代わりに、AutoModelForSeq2SeqLMクラスで直接読み込み、モデル自体から出力を生成します。

  2. 短くシンプルなプロンプトから始め、より良い結果を得られるよう反復して改善してください。

  3. プロンプトの先頭または末尾に指示を配置します。長いプロンプトの場合、モデルはアテンションの二次的なスケーリングを防ぐための最適化を適用する可能性があり、その場合、プロンプトの先頭と末尾に重点が置かれます。

  4. 指示と対象のテキストを明確に区切ってください。

  5. タスクと望ましい出力について、具体的かつ説明的に記述してください。例えば、形式、長さ、スタイル、言語などを指定します。曖昧な説明や指示は避けてください。

  6. 指示は「何をすべきか」に焦点を当て、「何をすべきでないか」に焦点を当てるべきではありません。

  7. モデルが正しい出力を生成するように導くには、最初の単語や、場合によっては最初の文を書き込みます。

  8. few-shotやchain-of-thoughtなどの他の手法を試して、結果を改善してください。

  9. 異なるモデルでプロンプトをテストし、その堅牢性を評価してください。

  10. プロンプトのバージョンを管理し、パフォーマンスを追跡します。

技術

ゼロショットプロンプティングとも呼ばれる、良いプロンプトの作成だけでは、望む結果を得るには不十分な場合があります。最適なパフォーマンスを得るには、いくつかのプロンプト作成テクニックを試す必要があるかもしれません。

このセクションでは、いくつかのプロンプト作成テクニックについて説明します。

Few-shotプロンプティング

Few-shot promptingは、入力に対してモデルが生成すべき内容の具体的な例を含めることで、精度とパフォーマンスを向上させます。明示的な例により、モデルはタスクや望ましい出力形式をより正確に理解できます。パフォーマンスへの影響を確認するために、例の数(2、4、8など)を変えて実験してみてください。以下の例では、モデルに返すべき出力形式(MM/DD/YYYY形式の日付)の例を1つ(1-shot)提供しています。

from transformers import pipeline
import torch

pipeline = pipeline(model="mistralai/Mistral-7B-Instruct-v0.1", dtype=torch.bfloat16, device_map="auto")
prompt = """Text: The first human went into space and orbited the Earth on April 12, 1961.
Date: 04/12/1961
Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates John F. Kennedy and Richard Nixon.
Date:"""

outputs = pipeline(prompt, max_new_tokens=12, do_sample=True, top_k=10)
for output in outputs:
    print(f"Result: {output['generated_text']}")
# Result: Text: The first human went into space and orbited the Earth on April 12, 1961.
# Date: 04/12/1961
# Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates John F. Kennedy and Richard Nixon.
# Date: 09/28/1960

Few-shot prompting のデメリットは、プロンプトが長くなるため、計算量とレイテンシが増加することです。また、プロンプトの長さに上限があります。さらに、モデルが例から意図しないパターンを学習してしまう可能性があり、複雑な推論タスクではうまく機能しない場合があります。

最新の指示チューニング済み LLM における few-shot prompting を改善するには、モデル固有の chat template を使用してください。これらのモデルは、「user」と「assistant」の間のターンベースの会話を含むデータセットで学習されています。プロンプトをこの構造に合わせて整えることで、パフォーマンスが向上する可能性があります。

プロンプトをターンベースの会話として構成し、apply_chat_template メソッドを使用してトークナイズおよびフォーマットします。

from transformers import pipeline
import torch

pipeline = pipeline(model="mistralai/Mistral-7B-Instruct-v0.1", dtype=torch.bfloat16, device_map="auto")

messages = [
    {"role": "user", "content": "Text: The first human went into space and orbited the Earth on April 12, 1961."},
    {"role": "assistant", "content": "Date: 04/12/1961"},
    {"role": "user", "content": "Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates John F. Kennedy and Richard Nixon."}
]

prompt = pipeline.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)

outputs = pipeline(prompt, max_new_tokens=12, do_sample=True, top_k=10)

for output in outputs:
    print(f"Result: {output['generated_text']}")

基本的な few-shot prompting のアプローチでは、例が単一の文字列内に埋め込まれていましたが、chat template 形式には以下の利点があります。

  • モデルは、ユーザーの入力とアシスタントの出力の期待される役割をより正確に認識できるため、理解が向上する可能性があります。
  • モデルは、学習中の入力と同様の構造を持つため、望ましい出力形式をより一貫して出力する可能性があります。

具体的な指示チューニング済みモデルのドキュメントを必ず参照し、そのチャットテンプレートの形式について詳しく学んでください。これにより、フェューショットプロンプトを適切に構成できます。

Chain-of-thought

Chain-of-thought (CoT) は、モデルがトピックについてより徹底的に「考える」のを助ける一連のプロンプトを提供することで、より一貫性があり、論理的に整った出力を生成する点で効果的です。

以下の例では、モデルに複数のプロンプトを与え、中間の推論ステップを処理させます。

from transformers import pipeline
import torch

pipeline = pipeline(model="mistralai/Mistral-7B-Instruct-v0.1", dtype=torch.bfloat16, device_map="auto")
prompt = """Let's go through this step-by-step:
1. You start with 15 muffins.
2. You eat 2 muffins, leaving you with 13 muffins.
3. You give 5 muffins to your neighbor, leaving you with 8 muffins.
4. Your partner buys 6 more muffins, bringing the total number of muffins to 14.
5. Your partner eats 2 muffins, leaving you with 12 muffins.
If you eat 6 muffins, how many are left?"""

outputs = pipeline(prompt, max_new_tokens=20, do_sample=True, top_k=10)
for output in outputs:
    print(f"Result: {output['generated_text']}")
Result: Let's go through this step-by-step:
1. You start with 15 muffins.
2. You eat 2 muffins, leaving you with 13 muffins.
3. You give 5 muffins to your neighbor, leaving you with 8 muffins.
4. Your partner buys 6 more muffins, bringing the total number of muffins to 14.
5. Your partner eats 2 muffins, leaving you with 12 muffins.
If you eat 6 muffins, how many are left?
Answer: 6

few-shotプロンプトと同様に、CoTのデメリットは、複雑なタスクに対してモデルが推論を進めるのを助ける一連のプロンプトを設計する手間がかかることと、プロンプトの長さがレイテンシを増加させることです。

ファインチューニング

プロンプトはLLMを扱う上で強力な手法ですが、ファインチューニング済みのモデル、あるいはモデル自体のファインチューニングの方が適しているシナリオもあります。

ファインチューニングされたモデルが有効な例として、次のようなシナリオが挙げられます。

  • あなたのドメインは、LLMが事前学習で用いられたデータと非常に異なっており、広範なプロンプト設計を行っても、望むような結果が得られていません。
  • モデルは、リソースが少ない言語でも良好に動作する必要があります。
  • モデルは、厳格な規制要件が課される機密データで訓練する必要があります。
  • コスト、プライバシー、インフラストラクチャ、その他の制約により、小型モデルを使用しています。

これらのすべてのシナリオにおいて、モデルの学習に十分な規模のドメイン固有のデータセットを確保していること、十分な時間とリソースがあること、そしてファインチューニングのコストに見合う価値があることを確認してください。そうでない場合は、プロンプトの最適化を試みる方が適切である可能性があります。

例

以下の例では、異なるタスクに対してLLMにプロンプトを与える方法を示しています。

名詞句認識
翻訳
要約
質問応答
from transformers import pipeline
import torch

pipeline = pipeline(model="mistralai/Mistral-7B-Instruct-v0.1", dtype=torch.bfloat16, device_map="auto")
prompt = """Return a list of named entities in the text.
Text: The company was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf in New York City, originally as a company that developed a chatbot app targeted at teenagers.
Named entities:
"""

outputs = pipeline(prompt, max_new_tokens=50, return_full_text=False)
for output in outputs:
    print(f"Result: {output['generated_text']}")
Result:  [Clément Delangue, Julien Chaumond, Thomas Wolf, company, New York City, chatbot app, teenagers]
Update on GitHub