# Higgs Audio V2

    
        
        
    

## 概要

Higgs Audio V2 は、[Boson AI](https://www.boson.ai/) によって開発された強力なオーディオ基盤モデルです。このモデルは、1,000 万時間以上のオーディオデータと多様なテキストデータセットで事前学習されています。後続の学習やファインチューニングを行っていないにもかかわらず、Higgs Audio v2 は、深い言語理解と音響理解を備えているため、表現力豊かなオーディオ生成において優れた性能を発揮します。

**モデルアーキテクチャ:**

    

Higgs Audio v2は、上記のアーキテクチャ図に示されている「生成バリアント」を採用しています。その優れたパフォーマンスは、以下の3つの主要な技術革新によって支えられています。

- 複数のASRモデル、サウンドイベント分類モデル、および自社開発の音声理解モデルを活用した自動アノテーションパイプラインを開発しました。このパイプラインを用いて、1,000万時間の音声データをクリーニングおよびアノテーションし、これをAudioVerseと呼んでいます。自社開発の理解モデルは、アーキテクチャ図に示されている「understanding variant」を採用したHiggs Audio v1 Understandingをベースにファインチューニングされています。
- 意味的特徴と音響的特徴の両方を捉える統合オーディオトークナイザーをゼロから学習しました。
- 計算オーバーヘッドを最小限に抑えながら、LLMの音響トークンのモデリング能力を高めることを提案するDualFFNアーキテクチャ。

## 使用方法

以下のすべてのスニペットは`test_higgs_audio.py`の統合テストを反映しており、ドキュメントが公式にサポートされているワークフローと同期して保たれることを保証しています。

### 単一話者のスマートボイス

```python
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration

model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")

conversation = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "Generate audio following instruction."
            }
        ],
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
            }
        ]
    }
]

inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    sampling_rate=24000,
    return_tensors="pt"
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_single_speaker_smart_voice.wav")
```

### マルチスピーカー対応スマートボイス

```python
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration

model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")

system_message = """You are an AI assistant designed to convert text into speech.
If the user's message includes a [SPEAKER*] tag, do not read out the tag and generate speech for the following text, using the specified voice.
If no speaker tag is present, select a suitable voice on your own."""

user_message = """[SPEAKER0] I can't believe you did that without even asking me first!
[SPEAKER1] Oh, come on! It wasn't a big deal, and I knew you would overreact like this.
[SPEAKER0] Overreact? You made a decision that affects both of us without even considering my opinion!
[SPEAKER1] Because I didn't have time to sit around waiting for you to make up your mind! Someone had to act."""

conversation = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": system_message
            }
        ]
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            },
            {
                "type": "text",
                "text": "SPEAKER0: feminine"
            },
            {
                "type": "text",
                "text": "SPEAKER1: masculine"
            },
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": user_message
            }
        ]
    }
]

inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    sampling_rate=24000,
    return_tensors="pt"
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=50, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_multi_speaker_smart_voice.wav")
```

### ゼロショットボイスクローニング

```python
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration

model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")

conversation = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "Generate audio following instruction."
            }
        ]
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
            }
        ]
    },
    {
        "role": "assistant",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
            }
        ]
    }
]

inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    sampling_rate=24000,
    return_tensors="pt"
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_zero_shot_voice_cloning.wav")
```

### マルチスピーカー音声クローニング

```python
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration

model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")

user_message = """[SPEAKER0] I can't believe you did that without even asking me first!
[SPEAKER1] Oh, come on! It wasn't a big deal, and I knew you would overreact like this.
[SPEAKER0] Overreact? You made a decision that affects both of us without even considering my opinion!
[SPEAKER1] Because I didn't have time to sit around waiting for you to make up your mind! Someone had to act."""

conversation = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "Generate audio following instruction."
            }
        ]
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            },
            {
                "type": "text",
                "text": "SPEAKER0:"
            },
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/audio/voice_sample.wav"
            },
            {
                "type": "text",
                "text": "SPEAKER1:"
            },
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/audio/mr_quiller.flac"
            },
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": user_message
            }
        ]
    },
]

inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    sampling_rate=24000,
    return_tensors="pt"
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, "output_multi_speaker_voice_cloning.wav")
```

### バッチ推論

```python
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration

model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")

conversation1 = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "Generate audio following instruction."
            }
        ]
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
            }
        ]
    },
    {
        "role": "assistant",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
            }
        ]
    }
]

conversation2 = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "Generate audio following instruction."
            }
        ]
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": " It's super important to assess fairly the fact that our former model is over. And this is not a question of adjustment. This is not the same world, 2024, 2025. And on top of that, we are making the same mistakes, on top of the key elements I mentioned. We are over-regulating and under-investing. So just if, in the two to three years to come, if we follow our classical agenda, we will be out of the market. I have no doubts."
            }
        ]
    },
    {
        "role": "assistant",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/macron.wav"
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "Hey, here is a clone from the given voice."
            }
        ]
    }
]

inputs = processor.apply_chat_template(
    [conversation1, conversation2],
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    sampling_rate=24000,
    return_tensors="pt"
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=1000, do_sample=False)
decoded = processor.batch_decode(outputs)
processor.save_audio(decoded, ["output_batched_1.wav", "output_batched_2.wav"])
```

### トレーニング

> [!TIP]
> デフォルトでは、モデルはテキスト言語モデリングヘッドを読み込みません。これは生成には不要であり、メモリを節約するためです（約1.5GiBの削減）。ただし、モデルをトレーニングする際には、テキストトークンに対する損失を計算するためにテキストヘッドが必要です。これを有効にするには、モデルをインスタンス化する際に`use_text_head=True`を設定してください（以下の例を参照）。

```python
from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration

model_id = "eustlb/higgs-audio-v2-generation-3B-base"
processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto", use_text_head=True)

conversation1 = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "Generate audio following instruction."
            }
        ]
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
            }
        ]
    },
    {
        "role": "assistant",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
            }
        ]
    }
]

conversation2 = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "text": "Generate audio following instruction."
            }
        ]
    },
    {
        "role": "scene",
        "content": [
            {
                "type": "text",
                "text": "Audio is recorded from a quiet room."
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": " I would imagine so. A wand with a dragon heartstring core is capable of dazzling magic, and the bond between you and your wand should only grow stronger. Do not be surprised at your new wand's ability to perceive your intentions, particularly in a moment of need"
            }
        ]
    },
    {
        "role": "assistant",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/broom_salesman.wav"
            }
        ]
    }
]

inputs = processor.apply_chat_template(
    [conversation1, conversation2],
    tokenize=True,
    return_dict=True,
    sampling_rate=24000,
    return_tensors="pt",
    output_labels=True,
).to(model.device)

outputs = model(**inputs)
outputs.loss.backward()
```

このモデルは、[Shuai Zheng](https://huggingface.co/szhengac)氏と[Eustache Le Bihan](https://huggingface.co/eustlb)氏によって提供されました。元のコードは[こちら](https://github.com/boson-ai/higgs-audio)で確認できます。

## HiggsAudioV2Config[[transformers.HiggsAudioV2Config]]

#### transformers.HiggsAudioV2Config[[transformers.HiggsAudioV2Config]]

```python
transformers.HiggsAudioV2Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 128256, hidden_size: int = 3072, intermediate_size: int = 8192, num_hidden_layers: int = 28, num_attention_heads: int = 24, num_key_value_heads: int = 8, hidden_act: str = 'silu', max_position_embeddings: int = 2048, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = 128001, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 128009, pretraining_tp: int | None = 1, tie_word_embeddings: bool = False, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, attention_dropout: int | float | None = 0.0, mlp_bias: bool = False, head_dim: int | None = 128, num_codebooks: int = 8, codebook_size: int = 1024, audio_token_id: int = 128016, audio_bos_token_id: int = 128013, audio_delay_token_id: int = 128014, audio_stream_bos_id: int = 1024, audio_stream_eos_id: int = 1025)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/configuration_higgs_audio_v2.py#L32)

**パラメータ:**

vocab_size (`int`、*任意*、デフォルトは`128256`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

hidden_size (`int`、*任意*、デフォルトは`3072`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは`8192`) : MLP 表現の次元数。

num_hidden_layers (`int`、*任意*、デフォルトは`28`) : Transformerデコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `24`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

num_key_value_heads (`int`, *optional*, デフォルトは `8`) : Grouped Query Attention を実装するために使用する key_value ヘッドの数です。`num_key_value_heads=num_attention_heads` の場合、モデルは Multi Head Attention (MHA) を使用し、`num_key_value_heads=1` の場合は Multi Query Attention (MQA) を使用し、それ以外の場合は GQA が使用されます。マルチヘッドのチェックポイントを GQA のチェックポイントに変換する際は、各グループの key ヘッドと value ヘッドは、そのグループ内の元のすべてのヘッドを平均プーリングして構築する必要があります。詳細については、[この論文](https://huggingface.co/papers/2305.13245)を参照してください。指定されない場合、デフォルトで `num_attention_heads` が使用されます。

hidden_act (`str`、*任意*、デフォルトは`silu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

max_position_embeddings (`int`、*任意*、デフォルトは`2048`)：このモデルが使用される可能性のある最大シーケンス長です。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

rms_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : rms 正規化レイヤーで使用する epsilon。

use_cache (`bool`、*任意*、デフォルトは `True`) : モデルが最後のキー/バリューアテンションを返すかどうか（すべてのモデルで利用されるわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

pad_token_id (`int`、*任意*、デフォルトは `128001`) : 語彙内でパディングに使用されるトークン ID。

bos_token_id (`int`, *任意*, デフォルトは `1`) : 語彙内でストリームの開始に使用されるトークン ID。

eos_token_id (`Union[int, list[int]]`、*任意*、デフォルトは`128009`) : 語彙内でストリームの終了に使用されるトークン ID。

pretraining_tp (`int`、*任意*、デフォルトは `1`) : 実験的な機能です。事前学習中に使用される Tensor parallelism のランクです。詳細については、[このドキュメント](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism)を参照してください。この値は、事前学習の結果を正確に再現するために必要です。[この issue](https://github.com/pytorch/pytorch/issues/76232)を参照してください。

tie_word_embeddings (`bool`, *任意*, デフォルトは `False`) : モデルの `tied_weights_keys` マッピングに従って重み埋め込みを共有するかどうか。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれていなければならず、より長い `max_position_embeddings` で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

attention_bias (`bool`、*任意*、デフォルトは`False`) : セルフアテンションにおけるクエリ、キー、バリュー、出力の投影層でバイアスを使用するかどうか。

attention_dropout (`Union[int, float]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

mlp_bias (`bool`, *任意*, デフォルトは `False`) : MLP 層の up_proj、down_proj、gate_proj 層でバイアスを使用するかどうか。

head_dim (`int`、*任意*、デフォルトは`128`) : アテンションヘッドの次元です。None の場合、hidden_size // num_attention_heads がデフォルトとして使用されます。

num_codebooks (`int`、*任意*、デフォルトは`8`) : モデルが使用する並列コードブックの数。

codebook_size (`int`、*任意*、デフォルトは `1024`) : モデルが使用する並列コードブックの数。

audio_token_id (`int`、*任意*、デフォルトは `128016`) : 入力音声のプレースホルダーとして使用される音声トークンインデックスです。

audio_bos_token_id (`int`、*任意*、デフォルトは 128013) : 音声出力用のシーケンス開始トークンのトークン ID。

audio_delay_token_id (`int`、*optional*、デフォルトは 128014) : マルチコードブック生成におけるオーディオ遅延パターンに使用されるトークン ID。

audio_stream_bos_id (`int`、*optional*、デフォルトは 1024) : 音声シーケンスにおけるストリーム開始トークンの ID。

audio_stream_eos_id (`int`、*optional*、デフォルトは 1025) : 音声シーケンスにおけるストリーム終了トークンの ID。

これは [bosonai/higgs-audio-v2-generation-3B-base](https://huggingface.co/bosonai/higgs-audio-v2-generation-3B-base) の設定に類似した設定をデフォルト値で生成する、HiggsAudioV2ForConditionalGeneration の設定を保存するための設定クラスです。指定された引数に基づいて Higgs Audio V2 モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import HiggsAudioV2Model, HiggsAudioV2Config

>>> # Initializing a HiggsAudioV2 style configuration
>>> configuration = HiggsAudioV2Config()

>>> # Initializing a model from the configuration
>>> model = HiggsAudioV2Model(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## HiggsAudioV2Processor[[transformers.HiggsAudioV2Processor]]

#### transformers.HiggsAudioV2Processor[[transformers.HiggsAudioV2Processor]]

```python
transformers.HiggsAudioV2Processor(feature_extractor, tokenizer, audio_tokenizer, chat_template = None, audio_token = '<|AUDIO_OUT|>', audio_bos_token = '<|audio_out_bos|>', audio_eos_token = '<|audio_eos|>', audio_delay_token = '<|reserved_special_token_6|>', audio_stream_bos_id = 1024, audio_stream_eos_id = 1025)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/processing_higgs_audio_v2.py#L53)

**パラメータ:**

feature_extractor (`DacFeatureExtractor`) : [DacFeatureExtractor](/docs/transformers/main/ja/model_doc/dac#transformers.DacFeatureExtractor)のインスタンスです。フィーチャーエクストラクターは必須の入力です。

tokenizer (`AutoTokenizer`) : [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer)のインスタンスです。トークナイザーは必須の入力です。

audio_tokenizer (`HiggsAudioV2TokenizerModel`) : [HiggsAudioV2TokenizerModel](/docs/transformers/main/ja/model_doc/higgs_audio_v2_tokenizer#transformers.HiggsAudioV2TokenizerModel)のインスタンスです。オーディオトークナイザーは必須の入力です。

chat_template (`str`, *省略可能*) : テキストと音声のインタラクションを組み合わせる際のチャットフォーマット用のテンプレート文字列。

audio_token (`str`、*任意*、デフォルトは `"<|AUDIO_OUT|>"`) : テキストシーケンス内で音声出力を表すために使用されるトークン。

audio_bos_token (`str`、*任意*、デフォルトは `"<|audio_out_bos|>"`) : 音声出力のシーケンス開始トークン。

audio_eos_token (`str`、*任意*、デフォルトは `"<|audio_eos|>"`) : 音声出力のシーケンス終了トークンです。

audio_delay_token (`str`、*任意*、デフォルトは `"<|reserved_special_token_6|>"`) : マルチコードブック生成におけるオーディオ遅延パターンに使用されるトークン。

audio_stream_bos_id (`int`、*optional*、デフォルトは 1024) : 音声シーケンスにおけるストリーム開始トークンの ID。

audio_stream_eos_id (`int`、*optional*、デフォルトは 1025) : 音声シーケンスにおけるストリーム終了トークンの ID。

[DacFeatureExtractor](/docs/transformers/main/ja/model_doc/dac#transformers.DacFeatureExtractor)、[AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer)、および [HiggsAudioV2TokenizerModel](/docs/transformers/main/ja/model_doc/higgs_audio_v2_tokenizer#transformers.HiggsAudioV2TokenizerModel) を単一のプロセッサーにラップする Higgs Audio プロセッサーを構築します。音声特徴抽出、トークナイザー、および音声エンコード/デコードの機能を継承します。詳細については、[__call__()](/docs/transformers/main/ja/model_doc/higgs_audio_v2#transformers.HiggsAudioV2Processor.__call__) および [decode()](/docs/transformers/main/ja/model_doc/higgs_audio_v2#transformers.HiggsAudioV2Processor.decode) を参照してください。

#### __call__[[transformers.HiggsAudioV2Processor.__call__]]

```python
__call__(text: str | list[str] | list[list[str]] | None = None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, output_labels: bool | None = False, **kwargs: *<class 'transformers.models.higgs_audio_v2.processing_higgs_audio_v2.HiggsAudioV2ProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/processing_higgs_audio_v2.py#L129)

#### decode[[transformers.HiggsAudioV2Processor.decode]]

```python
decode(audio_input_ids)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/processing_higgs_audio_v2.py#L287)

## HiggsAudioV2Model[[transformers.HiggsAudioV2Model]]

#### transformers.HiggsAudioV2Model[[transformers.HiggsAudioV2Model]]

```python
transformers.HiggsAudioV2Model(config: HiggsAudioV2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/modeling_higgs_audio_v2.py#L381)

**パラメータ:**

config ([HiggsAudioV2Config](/docs/transformers/main/ja/model_doc/higgs_audio_v2#transformers.HiggsAudioV2Config)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

特定のヘッドを付加せずに、生のhidden-statesを出力する、素のHiggs Audio V2 Model。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.HiggsAudioV2Model.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, audio_input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, audio_input_ids_mask: typing.Optional[torch.BoolTensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/modeling_higgs_audio_v2.py#L399)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

audio_input_ids (`torch.LongTensor`、shape `(batch_size, num_audio_frames, num_codebooks)`、*optional*) : 音声コードブックトークンのインデックス。[HiggsAudioV2TokenizerModel.encode()](/docs/transformers/main/ja/model_doc/higgs_audio_v2_tokenizer#transformers.HiggsAudioV2TokenizerModel.encode) を使用してインデックスを取得できます。

attention_mask (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンインデックスに対する attention を行わないためのマスク。`[0, 1]` から選択されるマスク値:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

audio_input_ids_mask (`torch.BoolTensor`、shape `(batch_size, num_audio_frames)`、*optional*) : `audio_input_ids` 内のどの音声フレームが有効であるかを示します。

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.Tensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

**戻り値:** `~models.modeling_outputs.BaseModelOutputWithPast`

プレースホルダーの位置が対応するオーディオ埋め込みに置き換えられた、通常のデコーダーの出力です。

[HiggsAudioV2Model](/docs/transformers/main/ja/model_doc/higgs_audio_v2#transformers.HiggsAudioV2Model) の forward メソッドは、`__call__` という特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

例:

```python
>>> from transformers import AutoProcessor, HiggsAudioV2Model
>>> import torch
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> processor = AutoProcessor.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
>>> model = HiggsAudioV2Model.from_pretrained("eustlb/higgs-audio-v2-generation-3B-base", device_map=device)
>>> conversation = [
...     {
...         "role": "system",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "Generate audio following instruction."
...             }
...         ]
...     },
...     {
...         "role": "scene",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "Audio is recorded from a quiet room."
...             }
...         ]
...     },
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
...             }
...         ]
...     },
...     {
...         "role": "assistant",
...         "content": [
...             {
...                 "type": "audio",
...                 "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
...             }
...         ]
...     },
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
...             }
...         ]
...     }
... ]
>>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
>>> inputs = inputs.to(model.device)
>>> outputs = model(**inputs)
```

## HiggsAudioV2ForConditionalGeneration[[transformers.HiggsAudioV2ForConditionalGeneration]]

#### transformers.HiggsAudioV2ForConditionalGeneration[[transformers.HiggsAudioV2ForConditionalGeneration]]

```python
transformers.HiggsAudioV2ForConditionalGeneration(config: HiggsAudioV2Config, use_text_head: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/modeling_higgs_audio_v2.py#L580)

**パラメータ:**

config ([HiggsAudioV2Config](/docs/transformers/main/ja/model_doc/higgs_audio_v2#transformers.HiggsAudioV2Config)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

use_text_head (`bool`、*任意*、デフォルトは False) : テキスト言語モデルヘッドを使用するかどうか。生成にはこのヘッドは必要ありませんが、学習時にテキストの損失を計算するために使用できます。

Higgs Audioモデルは、dual-FFNを備えたllama風の自己回帰型transformerモデルです。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.HiggsAudioV2ForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.BoolTensor] = None, audio_input_ids: typing.Optional[torch.LongTensor] = None, audio_input_ids_mask: typing.Optional[torch.LongTensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, audio_labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/higgs_audio_v2/modeling_higgs_audio_v2.py#L629)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

attention_mask (`torch.BoolTensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスク。`[0, 1]` から選択されるマスクの値:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

audio_input_ids (`torch.LongTensor`、shape `(batch_size, num_audio_frames, num_codebooks)`、*optional*) : 音声コードブックトークンのインデックス。[HiggsAudioV2TokenizerModel.encode()](/docs/transformers/main/ja/model_doc/higgs_audio_v2_tokenizer#transformers.HiggsAudioV2TokenizerModel.encode) を使用してインデックスを取得できます。

audio_input_ids_mask (`torch.BoolTensor`、shape `(batch_size, num_audio_frames)`、*optional*) : `audio_input_ids` 内のどの音声フレームが有効であるかを示します。

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.Tensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

labels (`torch.LongTensor`、形状 `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` の範囲内であるか、-100 である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` の範囲内のラベルを持つトークンに対してのみ計算されます。

audio_labels (`torch.LongTensor` of shape `(batch_size, num_audio_frames, num_codebooks)`, *optional*) : Labels for the audio codebook tokens for computing the masked language modeling loss. Indices should either be in `[0, ..., config.codebook_size]. Token with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.codebook_size]`. Can be obtained using `output_labels=True` when calling [HiggsAudioV2Processor](/docs/transformers/main/ja/model_doc/higgs_audio_v2#transformers.HiggsAudioV2Processor).

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

logits_to_keep (`Union[int, torch.Tensor]`、*任意*、デフォルトは `0`) : `int` の場合、最後の `logits_to_keep` トークンについて logits を計算します。`0` の場合、すべての `input_ids` について logits を計算します（特殊ケース）。生成には最後のトークンの logits だけで十分であり、そのトークンのみについて計算することでメモリを節約できます。これは、長いシーケンスや大規模な語彙サイズの場合に特に顕著な効果があります。`torch.Tensor` の場合、シーケンス長次元で保持するインデックスに対応する 1 次元である必要があります。これは、パックされたテンソル形式（バッチとシーケンス長を単一の次元にまとめる形式）を使用する場合に有用です。

**戻り値:** `~models.modeling_outputs.CausalLMOutputWithPast`

`~models.modeling_outputs.CausalLMOutputWithPast` を含むオブジェクト。logits、loss（ラベルが提供されている場合）、およびモデルからのその他の出力が含まれます。

[HiggsAudioV2ForConditionalGeneration](/docs/transformers/main/ja/model_doc/higgs_audio_v2#transformers.HiggsAudioV2ForConditionalGeneration)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

例:

```python
>>> from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
>>> model_id = "eustlb/higgs-audio-v2-generation-3B-base"
>>> processor = AutoProcessor.from_pretrained(model_id, device_map="auto")
>>> model = HiggsAudioV2ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
>>> conversation = [
...     {
...         "role": "system",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "Generate audio following instruction."
...             }
...         ]
...     },
...     {
...         "role": "scene",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "Audio is recorded from a quiet room."
...             }
...         ]
...     },
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "It was the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year."
...             }
...         ]
...     },
...     {
...         "role": "assistant",
...         "content": [
...             {
...                 "type": "audio",
...                 "url": "https://huggingface.co/datasets/eustlb/dummy-audio-samples-higgs/resolve/main/belinda.wav"
...             }
...         ]
...     },
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "text",
...                 "text": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years."
...             }
...         ]
...     }
... ]
>>> inputs = processor.apply_chat_template(conversation, return_dict=True, tokenize=True, sampling_rate=24000, return_tensors="pt")
>>> inputs = inputs.to(model.device)
>>> outputs = model(**inputs)
```

#### generate[[transformers.HiggsAudioV2ForConditionalGeneration.generate]]

```python
generate(inputs: typing.Optional[torch.Tensor] = None, generation_config: transformers.generation.configuration_utils.GenerationConfig | None = None, logits_processor: transformers.generation.logits_process.LogitsProcessorList | None = None, stopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = None, prefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = None, synced_gpus: bool | None = None, assistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = None, streamer: typing.Optional[ForwardRef('BaseStreamer')] = None, negative_prompt_ids: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, custom_generate: str | collections.abc.Callable | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/generation/utils.py#L2581)

**パラメータ:**

inputs (`torch.Tensor`、モダリティによって形状が異なる、*任意*) : 生成のプロンプトとして使用されるシーケンス、またはエンコーダーへのモデル入力です。`None` の場合、`bos_token_id` とバッチサイズ 1 で初期化されます。デコーダー専用モデルの場合、`inputs` は `input_ids` の形式である必要があります。エンコーダーデコーダーモデルの場合、*inputs* は `input_ids`、`input_values`、`input_features`、`pixel_values` のいずれかを表すことができます。

generation_config ([GenerationConfig](/docs/transformers/main/ja/main_classes/text_generation#transformers.GenerationConfig), *任意*) : 生成呼び出しのベースパラメータ化として使用される生成設定です。 `**kwargs` で `generation_config` の属性に一致するものが generate に渡された場合、それらは上書きされます。 `generation_config` が指定されない場合、デフォルトが使用されます。その読み込み優先順位は以下の通りです: 1) 存在する場合、`generation_config.json` モデルファイルから; 2) モデル設定から。未指定のパラメータは [GenerationConfig](/docs/transformers/main/ja/main_classes/text_generation#transformers.GenerationConfig) のデフォルト値を継承することに注意してください。生成をパラメータ化するには、そのドキュメントを確認する必要があります。

logits_processor (`LogitsProcessorList`, *任意*) : 引数や生成設定から構築されるデフォルトの logits プロセッサを補完する、カスタムの logits プロセッサです。引数や生成設定で既に作成済みの logits プロセッサが渡された場合、エラーが発生します。この機能は上級ユーザー向けです。

stopping_criteria (`StoppingCriteriaList`、*任意*) : 引数と生成設定から構築されるデフォルトの停止条件を補完する、カスタムの停止条件です。引数や生成設定からすでに作成された停止条件が渡された場合、エラーが発生します。停止条件が`scores`入力を依存している場合は、`generate`に`return_dict_in_generate=True, output_scores=True`を渡すことを確認してください。この機能は上級ユーザー向けです。

prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], list[int]]`、*任意*) : 指定された場合、この関数はビームサーチを各ステップで許可されたトークンのみに制限します。指定されない場合、制約は適用されません。この関数は2つの引数を受け取ります: バッチID `batch_id` と `input_ids`。バッチID `batch_id` と以前に生成されたトークン `inputs_ids` に条件付けられた次の生成ステップの許可トークンのリストを返す必要があります。この引数は、[Autoregressive Entity Retrieval](https://huggingface.co/papers/2010.00904) に記載されているような、プレフィックスに条件付けられた制約付き生成に有用です。

synced_gpus (`bool`, *optional*) : `FullyShardedDataParallel` または DeepSpeed ZeRO Stage 3 を複数 GPU で使用する場合、ある GPU が他の GPU より先に生成を完了した場合のデッドロックを回避するために、このフラグは `True` に設定されます（上書きされない限り）。それ以外の場合は、デフォルトで `False` になります。

assistant_model (`PreTrainedModel`、*任意*) : 生成を高速化するために使用できるアシスタントモデルです。アシスタントモデルは、呼び出し元のモデルと完全に同一のトークナイザーを備えている必要があります。アシスタントモデルによる候補トークンの予測が、呼び出し元のモデルで generate を実行するよりもはるかに高速な場合に、高速化が実現されます。そのため、アシスタントモデルは呼び出し元のモデルよりもはるかに小さいものである必要があります。

streamer (`BaseStreamer`、*任意*) : 生成されたシーケンスのストリーミングに使用される Streamer オブジェクトです。生成されたトークンは `streamer.put(token_ids)` を介して渡され、その後の処理はすべて streamer が担当します。

negative_prompt_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*optional*) : CFG などの一部のプロセッサに必要なネガティブプロンプトです。バッチサイズは入力バッチサイズと一致する必要があります。これは実験的な機能であり、将来のバージョンで API が破壊的に変更される可能性があります。

negative_prompt_attention_mask (`torch.LongTensor`、形状 `(batch_size, sequence_length)`、*任意*) : `negative_prompt_ids` 用の Attention_mask。

custom_generate (`str` または `Callable`、*省略可能*) : 以下のいずれかです: - `str` (Hugging Face Hub リポジトリ名): 標準の `generate` メソッドの代わりに、そのリポジトリ内の `custom_generate/generate.py` で定義されたカスタムの `generate` 関数を実行します。リポジトリが生成ロジックを完全に置き換え、戻り値の型が異なる場合があります。 - `str` (ローカルリポジトリのパス): 上記と同様ですが、ローカルパスから読み込みます。ローカルの `custom_generate/generate.py` が実行されるため、ローカルディレクトリの場合も `trust_remote_code=True` が必要です。 - `Callable`: `generate` は通常の入力準備手順を実行した後、デコーディングループを実行するために提供された callable を呼び出します。詳細については、[ドキュメント](../../generation_strategies#custom-generation-methods)を参照してください。

kwargs (`dict[str, Any]`、*任意*) : `generation_config` のアドホックなパラメータ化、およびモデルの `forward` 関数に転送される追加のモデル固有の kwargs です。モデルがエンコーダー・デコーダーモデルの場合、エンコーダー固有の kwargs にはプレフィックスを付与せず、デコーダー固有の kwargs には *decoder_* をプレフィックスとして付与してください。

**戻り値:** [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) または `torch.LongTensor`

`return_dict_in_generate=True` の場合、または `config.return_dict_in_generate=True` の場合は [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput)、それ以外は `torch.LongTensor`。

モデルがエンコーダー・デコーダーモデルで*ない*場合（`model.config.is_encoder_decoder=False`）、考えられる[ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput)の型は以下の通りです：

- [GenerateDecoderOnlyOutput](/docs/transformers/main/ja/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput)、
- [GenerateBeamDecoderOnlyOutput](/docs/transformers/main/ja/internal/generation_utils#transformers.generation.GenerateBeamDecoderOnlyOutput)

モデルがエンコーダー・デコーダーモデル（`model.config.is_encoder_decoder=True`）の場合、考えられる[ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput)の型は以下の通りです：

- [GenerateEncoderDecoderOutput](/docs/transformers/main/ja/internal/generation_utils#transformers.generation.GenerateEncoderDecoderOutput)、
- [GenerateBeamEncoderDecoderOutput](/docs/transformers/main/ja/internal/generation_utils#transformers.generation.GenerateBeamEncoderDecoderOutput)

言語モデリングヘッドを持つモデルに対して、トークンIDのシーケンスを生成します。

生成を制御するほとんどのパラメータは`generation_config`で設定されます。この引数が渡されない場合、モデルのデフォルトの生成設定が使用されます。`generation_config`の任意の値は、generate()に該当するパラメータを渡すことで上書きできます。例: `.generate(inputs, num_beams=4, do_sample=True)`。

生成戦略の概要とコード例については、[次のガイド](../generation_strategies)を参照してください。

