Transformers documentation

生成戦略

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

生成戦略

デコーディング戦略は、モデルが次に生成するトークンをどのように選択すべきかを決定します。デコーディング戦略には多くの種類があり、適切な戦略の選択は生成テキストの品質に大きな影響を与えます。

このガイドでは、Transformers で利用可能なさまざまなデコーディング戦略、およびそれらの使用方法と適用タイミングについて理解を深めることができます。

基本的なデコーディング手法

これらは確立されたデコーディング手法であり、テキスト生成タスクの出発点として推奨されます。

貪欲探索

Greedy searchはデフォルトのデコーディング戦略です。各ステップで最も確率の高い次のトークンを選択します。GenerationConfigで指定されない限り、この戦略は最大20個の新しいトークンを生成します。

Greedy searchは、創造性が重視されない比較的短い出力を生成するタスクでは有効に機能します。ただし、より長いシーケンスを生成する際には、繰り返しが発生し始めるため、機能しなくなります。

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from accelerate import Accelerator

device = Accelerator().device

tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to(device)

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.float16).to(device)
# explicitly set to default length because Llama2 generation length is 4096
outputs = model.generate(**inputs, max_new_tokens=20)
tokenizer.batch_decode(outputs, skip_special_tokens=True)
'Hugging Face is an open-source company that provides a suite of tools and services for building, deploying, and maintaining natural language processing'

サンプリング

サンプリング(多項分布サンプリング)は、モデルの語彙全体に対する確率分布に基づいてトークンをランダムに選択します(グリーディサーチのように最も確率の高いトークンを選択するのとは対照的です)。これにより、確率がゼロでないすべてのトークンが選択される可能性があります。サンプリング戦略は繰り返しを軽減し、より創造的で多様な出力を生成できます。

do_sample=True と num_beams=1 を設定して、多項分布サンプリングを有効にします。

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from accelerate import Accelerator

device = Accelerator().device

tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to(device)

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.float16).to(device)
# explicitly set to 100 because Llama2 generation length is 4096
outputs = model.generate(**inputs, max_new_tokens=50, do_sample=True, num_beams=1)
tokenizer.batch_decode(outputs, skip_special_tokens=True)
'Hugging Face is an open-source company 🤗\nWe are open-source and believe that open-source is the best way to build technology. Our mission is to make AI accessible to everyone, and we believe that open-source is the best way to achieve that.'

ビームサーチ

ビームサーチは、各タイムステップにおいて複数の生成シーケンス(ビーム)を追跡します。一定のステップ数を経過した後、全体としての確率が最も高いシーケンスを選択します。グリーディサーチとは異なり、この戦略は「先読み」を行うことができ、初期トークンの確率が低くても、全体として確率の高いシーケンスを選択できます。画像の説明や音声認識など、入力に基づいたタスクに最も適しています。ビームサーチとdo_sample=Trueを併用して各ステップでサンプリングを行うことも可能ですが、ビームサーチはステップ間で確率の低いシーケンスをグリーディに除去し続けます。

ビームサーチの動作を確認するには、ビームサーチビジュアライザーをご覧ください。

num_beams パラメータでビームサーチを有効にします(1 より大きい値を指定する必要があります。それ以外の場合は貪欲探索と同等になります)。

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from accelerate import Accelerator

device = Accelerator().device

tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to(device)

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.float16).to(device)
# explicitly set to 100 because Llama2 generation length is 4096
outputs = model.generate(**inputs, max_new_tokens=50, num_beams=2)
tokenizer.batch_decode(outputs, skip_special_tokens=True)
"['Hugging Face is an open-source company that develops and maintains the Hugging Face platform, which is a collection of tools and libraries for building and deploying natural language processing (NLP) models. Hugging Face was founded in 2018 by Thomas Wolf']"

カスタム生成メソッド

カスタム生成メソッドにより、以下のような特殊な動作を有効にできます。

  • モデルが不確実な場合、考え続けるようにします。
  • モデルが詰まった場合、生成を巻き戻す;
  • カスタムロジックで特殊トークンを処理します;
  • 専用のKVキャッシュを使用します;

モデルリポジトリを通じてカスタムな生成メソッドを有効化します。この機能は特定のモデルタグとファイル構造を前提としています(以下の小節を参照)。この機能はカスタムモデリングコードの拡張であり、同様にtrust_remote_code=Trueを設定する必要があります。

モデルリポジトリにカスタムの生成メソッドが含まれている場合、それを試す最も簡単な方法は、モデルを読み込んで生成を実行することです。

from transformers import AutoModelForCausalLM, AutoTokenizer

# `transformers-community/custom_generate_example` holds a copy of `Qwen/Qwen2.5-0.5B-Instruct`, but
# with custom generation code -> calling `generate` uses the custom generation method!
tokenizer = AutoTokenizer.from_pretrained("transformers-community/custom_generate_example")
model = AutoModelForCausalLM.from_pretrained(
    "transformers-community/custom_generate_example", device_map="auto", trust_remote_code=True
)

inputs = tokenizer(["The quick brown"], return_tensors="pt").to(model.device)
# The custom generation method is a minimal greedy decoding implementation. It also prints a custom message at run time.
gen_out = model.generate(**inputs)
# you should now see its custom message, "✨ using a custom generation method ✨"
print(tokenizer.batch_decode(gen_out, skip_special_tokens=True))
'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is'

カスタムな生成メソッドを持つモデルリポジトリには、特別なプロパティがあります。generate() の custom_generate 引数を通じて、任意のモデルからその生成メソッドを読み込むことができます。これにより、ユーザーが追加の Python パッケージをインストールする必要なく、誰でもカスタムな生成メソッドを作成・共有し、Transformers のあらゆるモデルで動作する可能性があります。

from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", device_map="auto")

inputs = tokenizer(["The quick brown"], return_tensors="pt").to(model.device)
# `custom_generate` replaces the original `generate` by the custom generation method defined in
# `transformers-community/custom_generate_example`
gen_out = model.generate(**inputs, custom_generate="transformers-community/custom_generate_example", trust_remote_code=True)
print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is'

カスタムな生成戦略を含むリポジトリのREADME.mdファイルを読み、新しい引数や出力型の違いがある場合は確認してください。それ以外の場合は、ベースのgenerate()メソッドと同様に動作すると仮定して問題ありません。

カスタムタグを検索することで、すべてのカスタム生成メソッドを見つけることができます。custom_generate

Hubのリポジトリ transformers-community/custom_generate_example を例として考えます。README.md には、プロンプトの前にパディングトークンを追加する追加の入力引数 left_padding があると記載されています。

gen_out = model.generate(
    **inputs, custom_generate="transformers-community/custom_generate_example", trust_remote_code=True, left_padding=5
)
print(tokenizer.batch_decode(gen_out)[0])
'<|endoftext|><|endoftext|><|endoftext|><|endoftext|><|endoftext|>The quick brown fox jumps over the lazy dog.\n\nThe sentence "The quick'

カスタムメソッドが、現在の環境を満たしていない固定された Python の要件を指定している場合、要件の欠落に関する例外が発生します。例えば、transformers-community/custom_generate_bad_requirements は、その custom_generate/requirements.txt ファイルに不可能な要件のセットが定義されており、実行しようとすると以下のエラーメッセージが表示されます。

ImportError: Missing requirements in your local environment for `transformers-community/custom_generate_bad_requirements`:
foo (installed: None)
bar==0.0.0 (installed: None)
torch>=99.0 (installed: 2.6.0)

Python の要件を適切に更新すると、このエラーメッセージは解消されます。

カスタムな生成メソッドの作成

新しい生成メソッドを作成するには、新しいModelリポジトリを作成し、いくつかのファイルをプッシュする必要があります。

  1. 生成方法の設計に使用したモデル。
  2. custom_generate/generate.py。カスタムな生成メソッドのすべてのロジックが含まれています。
  3. custom_generate/requirements.txt は、メソッドを正しく使用するために、新しい Python の依存関係を任意で追加したり、特定のバージョンを固定したりするために使用されます。
  4. README.md に、custom_generate タグを追加し、カスタムメソッドの新しい引数や出力型の違いをここに記載してください。

必要なファイルをすべて追加した後、リポジトリは次のようになります

your_repo/
├── README.md          # include the 'custom_generate' tag
├── config.json
├── ...
└── custom_generate/
    ├── generate.py
    └── requirements.txt

ベースモデルの追加

カスタムな生成手法の起点は、他のモデルリポジトリと同様にモデルリポジトリです。このリポジトリに追加するモデルは、手法を設計した際に使用したモデルであり、動作する自己完結型のモデルと生成のペアの一部として機能するよう意図されています。このリポジトリのモデルが読み込まれると、カスタムな生成手法がgenerateをオーバーライドします。心配はいりません。上記のセクションで説明したように、生成手法は他のTransformersモデルでも引き続き読み込むことができます。

既存のモデルをコピーしたいだけの場合は、

from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("source/model_repo")
model = AutoModelForCausalLM.from_pretrained("source/model_repo")
tokenizer.save_pretrained("your/generation_method", push_to_hub=True)
model.save_pretrained("your/generation_method", push_to_hub=True)

generate.py

これは生成メソッドの中核です。必ずgenerate という名前のメソッドを含み、このメソッドは必ず最初の引数としてmodel を受け取る必要があります。model はモデルのインスタンスであり、GenerationMixin で定義されたもの(ベースのgenerate メソッドなど)を含む、モデル内のすべての属性とメソッドにアクセスできます。

generate.py は、リポジトリのルートレベルではなく、custom_generate という名前のフォルダ内に配置する必要があります。この機能のファイルパスはハードコードされています。

内部では、custom_generate 引数付きでベースの generate() メソッドが呼び出されると、まず Python の要件(ある場合)を確認し、次に generate.py 内のカスタム generate メソッドを特定し、最後にカスタム generate を呼び出します。カスタム生成をトリガーするために使用される引数(trust_remote_code と custom_generate)を除き、受け取ったすべての引数と model は、ユーザーのカスタム generate メソッドに転送されます。

これは、以下に示すように、generateが元の引数とカスタム引数の両方(および異なる出力型)を混在して使用できることを意味します。

import torch

def generate(model, input_ids, generation_config=None, left_padding=None, **kwargs):
    generation_config = generation_config or model.generation_config  # default to the model generation config
    cur_length = input_ids.shape[1]
    max_length = generation_config.max_length or cur_length + generation_config.max_new_tokens

    # Example of custom argument: add `left_padding` (integer) pad tokens before the prompt
    if left_padding is not None:
        if not isinstance(left_padding, int) or left_padding < 0:
            raise ValueError(f"left_padding must be an integer larger than 0, but is {left_padding}")

        pad_token = kwargs.pop("pad_token", None) or generation_config.pad_token_id or model.config.pad_token_id
        if pad_token is None:
            raise ValueError("pad_token is not defined")
        batch_size = input_ids.shape[0]
        pad_tensor = torch.full(size=(batch_size, left_padding), fill_value=pad_token).to(input_ids.device)
        input_ids = torch.cat((pad_tensor, input_ids), dim=1)
        cur_length = input_ids.shape[1]

    # Simple greedy decoding loop
    while cur_length < max_length:
        logits = model(input_ids).logits
        next_token_logits = logits[:, -1, :]
        next_tokens = torch.argmax(next_token_logits, dim=-1)
        input_ids = torch.cat((input_ids, next_tokens[:, None]), dim=-1)
        cur_length += 1

    return input_ids

カスタム生成メソッドが期待通りに動作することを保証するために、以下の推奨事項に従ってください。

  • 元のgenerate()の検証および入力準備のロジックを再利用して構いません。
  • modelのプライベートなメソッドや属性を使用する場合は、requirementsでtransformersのバージョンを固定してください。
  • ユーザーが自分の環境でコードの健全性を確認できるよう、モデルの検証、入力の検証、さらには独立したテストファイルの追加を検討してください。

カスタムのgenerateメソッドでは、custom_generateフォルダー内のコードを相対インポートできます。例えば、utils.pyファイルがある場合、次のようにインポートできます。

from .utils import some_function

同一階層のcustom_generateフォルダからの相対インポートのみがサポートされています。親フォルダや兄弟フォルダからのインポートは有効ではありません。custom_generate引数は、custom_generate構造を含む任意のディレクトリに対してローカルでも動作します。これは、カスタム生成手法を開発するための推奨されるワークフローです。

gen_out = model.generate(**inputs, custom_generate="path/to/local/dir", trust_remote_code=True)

ローカルディレクトリを読み込む場合も、その custom_generate/generate.py が実行されるため、Hub リポジトリと同様に trust_remote_code=True が必要です。trust_remote_code=True は、自分で作成したコードまたはレビュー済みのコードに対してのみ指定してください。

requirements.txt

custom_generate フォルダ内に requirements.txt ファイルを配置して、追加の Python 要件を任意で指定できます。これらは実行時にチェックされ、不足している場合は例外がスローされるため、ユーザーが環境を適切に更新するよう促されます。

README.md

モデルリポジトリのルートレベルにあるREADME.mdは、通常、そのリポジトリに含まれるモデルについて説明しています。ただし、このリポジトリの焦点はカスタムな生成手法にあるため、その焦点をカスタムな生成手法の説明に移すことを強く推奨します。手法の説明に加えて、元のgenerate()との入力および/または出力の違いについてもドキュメント化することを推奨します。これにより、ユーザーは新しい部分に集中でき、一般的な実装の詳細については Transformers のドキュメントに委ねることができます。

検索しやすさのため、リポジトリにcustom_generateタグを追加することを強くお勧めします。そのためには、README.mdファイルの先頭を、以下の例のようにしてください。ファイルをプッシュすると、リポジトリにタグが表示されるようになります。

---
library_name: transformers
tags:
  - custom_generate
---

(your markdown content here)

推奨されるプラクティス:

  • generate()における入力と出力の違いを文書化します。
  • 迅速な実験を可能にするため、自己完結型の例を追加します。
  • あるモデルファミリーでのみ良好に動作するといった、ソフトな要件を記述します。

generate の入力準備の再利用

新しいデコーディングループを追加する場合、generate に実装されている入力準備処理(バッチの展開、アテンションマスク、logits プロセッサ、停止条件など)を保持したい場合があります。また、custom_generate に callable を渡すことで、generate() の完全な準備パイプラインを再利用しつつ、デコーディングループのみをオーバーライドすることもできます。

def custom_loop(model, input_ids, attention_mask, logits_processor, stopping_criteria, generation_config, **model_kwargs):
    next_tokens = input_ids
    while input_ids.shape[1] < stopping_criteria[0].max_length:
        logits = model(next_tokens, attention_mask=attention_mask, **model_kwargs).logits
        next_token_logits = logits_processor(input_ids, logits[:, -1, :])
        next_tokens = torch.argmax(next_token_logits, dim=-1)[:, None]
        input_ids = torch.cat((input_ids, next_tokens), dim=-1)
        attention_mask = torch.cat((attention_mask, torch.ones_like(next_tokens)), dim=-1)
    return input_ids

output = model.generate(
    **inputs,
    custom_generate=custom_loop,
    max_new_tokens=10,
)

custom_generate リポジトリを公開する場合、generate の実装内でコールバックを定義し、model.generate() に渡すことができます。これにより、Transformers の組み込みの入力準備ロジックの恩恵を受けながら、デコーディングループをカスタマイズできます。

カスタム生成メソッドの検索

カスタムタグを検索することで、すべてのカスタム生成メソッドを見つけることができます。custom_generate。タグに加えて、custom_generateメソッドのコレクションを2つキュレーションしています:

リソース

Read the How to generate text: using different decoding methods for language generation with Transformers blog post for an explanation of how common decoding strategies work.

Update on GitHub