# 生成戦略

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

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

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

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

### 貪欲探索

Greedy searchはデフォルトのデコーディング戦略です。各ステップで最も確率の高い次のトークンを選択します。[GenerationConfig](/docs/transformers/v5.25.0/ja/main_classes/text_generation#transformers.GenerationConfig)で指定されない限り、この戦略は最大20個の新しいトークンを生成します。

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

```py
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` を設定して、多項分布サンプリングを有効にします。

```py
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.'
```

### ビームサーチ

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

> [!TIP]
> ビームサーチの動作を確認するには、[ビームサーチビジュアライザー](https://huggingface.co/spaces/m-ric/beam_search_visualizer)をご覧ください。

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

```py
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キャッシュを使用します;

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

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

```py
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()](/docs/transformers/v5.25.0/ja/main_classes/text_generation#transformers.GenerationMixin.generate)の`custom_generate`引数を通じて、**任意**のモデルから読み込むことができます。これにより、ユーザーが追加のPythonパッケージをインストールする必要なく、誰でもカスタムな生成手法を作成・共有し、Transformersのあらゆるモデルで動作する可能性があります。

```py
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()](/docs/transformers/v5.25.0/ja/main_classes/text_generation#transformers.GenerationMixin.generate)メソッドと同様に動作すると仮定して問題ありません。

> [!TIP]
> [カスタムタグを検索すること](https://huggingface.co/models?other=custom_generate)で、すべてのカスタム生成メソッドを見つけることができます。`custom_generate`

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

```py
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](https://huggingface.co/transformers-community/custom_generate_bad_requirements) は、その `custom_generate/requirements.txt` ファイルに不可能な要件のセットが定義されており、実行しようとすると以下のエラーメッセージが表示されます。

```text
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**](https://huggingface.co/new)リポジトリを作成し、いくつかのファイルをプッシュする必要があります。

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

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

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

#### ベースモデルの追加

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

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

```py
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](/docs/transformers/v5.25.0/ja/main_classes/text_generation#transformers.GenerationMixin) で定義されたもの（ベースの`generate` メソッドなど）を含む、モデル内のすべての属性とメソッドにアクセスできます。

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

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

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

```py
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()](/docs/transformers/v5.25.0/ja/main_classes/text_generation#transformers.GenerationMixin.generate)の検証および入力準備のロジックを再利用して構いません。
- `model`のプライベートなメソッドや属性を使用する場合は、requirementsで`transformers`のバージョンを固定してください。
- ユーザーが自分の環境でコードの健全性を確認できるよう、モデルの検証、入力の検証、さらには独立したテストファイルの追加を検討してください。

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

```py
from .utils import some_function
```

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

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

> [!WARNING]
> ローカルディレクトリを読み込む場合も、その `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()](/docs/transformers/v5.25.0/ja/main_classes/text_generation#transformers.GenerationMixin.generate)との入力および/または出力の違いについてもドキュメント化することを推奨します。これにより、ユーザーは新しい部分に集中でき、一般的な実装の詳細については Transformers のドキュメントに委ねることができます。

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

```text
---
library_name: transformers
tags:
  - custom_generate
---

(your markdown content here)
```

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

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

### `generate`の入力準備の再利用

新しいデコーディングループを追加する場合、`generate` に存在する入力準備（バッチの展開、アテンションマスク、logits プロセッサ、停止条件など）を保持したい場合があります。また、`custom_generate` に **callable** を渡すことで、[generate()](/docs/transformers/v5.25.0/ja/main_classes/text_generation#transformers.GenerationMixin.generate) の完全な準備パイプラインを再利用しつつ、デコーディングループのみをオーバーライドすることもできます。

```py
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,
)
```

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

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

[カスタムタグを検索すること](https://huggingface.co/models?other=custom_generate)で、すべてのカスタム生成メソッドを見つけることができます。`custom_generate`。タグに加えて、`custom_generate`メソッドのコレクションを2つキュレーションしています:

- [カスタム生成メソッド - コミュニティ](https://huggingface.co/collections/transformers-community/custom-generation-methods-community-6888fb1da0efbc592d3a8ab6) -- コミュニティによって提供された強力なメソッドのコレクション;
- [カスタム生成メソッド - チュートリアル](https://huggingface.co/collections/transformers-community/custom-generation-methods-tutorials-6823589657a94940ea02cfec) -- `transformers`に以前含まれていたメソッドの参照実装のコレクション、および`custom_generate`のチュートリアル。

## リソース

Read the [How to generate text: using different decoding methods for language generation with Transformers](https://huggingface.co/blog/how-to-generate) blog post for an explanation of how common decoding strategies work.

