Transformers documentation

Higgs Audio V2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2026年2月19日にHugging Face Transformersに貢献されました。

Higgs Audio V2

FlashAttention SDPA

概要

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

モデルアーキテクチャ:

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

使用方法

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

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

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")

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

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")

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

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")

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

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")

バッチ推論

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"])

トレーニング

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

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氏とEustache Le Bihan氏によって提供されました。元のコードはこちらで確認できます。

HiggsAudioV2Config

クラス transformers.HiggsAudioV2Config

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 128256hidden_size: int = 3072intermediate_size: int = 8192num_hidden_layers: int = 28num_attention_heads: int = 24num_key_value_heads: int = 8hidden_act: str = 'silu'max_position_embeddings: int = 2048initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int | None = 128001bos_token_id: int | None = 1eos_token_id: int | list[int] | None = 128009pretraining_tp: int | None = 1tie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: int | float | None = 0.0mlp_bias: bool = Falsehead_dim: int | None = 128num_codebooks: int = 8codebook_size: int = 1024audio_token_id: int = 128016audio_bos_token_id: int = 128013audio_delay_token_id: int = 128014audio_stream_bos_id: int = 1024audio_stream_eos_id: int = 1025 )

パラメータ

  • 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、任意、デフォルトは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 ヘッドを、そのグループ内の元のすべてのヘッドの平均プーリングによって構築する必要があります。詳細については、この論文を参照してください。指定しない場合、デフォルトで 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 のランクです。詳細については、このドキュメントを参照してください。この値は、事前学習の結果を正確に再現するために必要です。詳細については、この issueを参照してください。
  • tie_word_embeddings (bool、任意、デフォルトは False) — モデルの tied_weights_keys マッピングに従って重み埋め込みを共有するかどうかを指定します。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 省略可) — 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, 任意、デフォルトは 128014) — マルチコードブック生成におけるオーディオ遅延パターンに使用されるトークン ID。
  • audio_stream_bos_id (int、任意、デフォルトは 1024) — 音声シーケンスにおけるストリーム開始トークンの ID です。
  • audio_stream_eos_id (int、任意、デフォルトは 1025)— 音声シーケンスにおけるストリーム終了トークンの ID です。

これは、bosonai/higgs-audio-v2-generation-3B-base と同様の設定をデフォルト値でインスタンス化できるように、指定された引数に基づいて Higgs Audio V2 モデルのアーキテクチャを定義し、HiggsAudioV2ForConditionalGeneration の設定を保存するための設定クラスです。

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

>>> 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

< >

( feature_extractortokenizeraudio_tokenizerchat_template = Noneaudio_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 = 1024audio_stream_eos_id = 1025 )

パラメータ

  • feature_extractor (DacFeatureExtractor) — DacFeatureExtractor のインスタンスです。フィーチャーエクストラクターは必須の入力です。
  • tokenizer (AutoTokenizer) — AutoTokenizer のインスタンスです。トークナイザーは必須の入力です。
  • audio_tokenizer (HiggsAudioV2TokenizerModel) — 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、任意、デフォルトは 1024) — 音声シーケンスにおけるストリーム開始トークンの ID です。
  • audio_stream_eos_id (int、任意、デフォルトは 1025)— 音声シーケンスにおけるストリーム終了トークンの ID です。

DacFeatureExtractor、AutoTokenizer、および HiggsAudioV2TokenizerModel を単一のプロセッサーにラップする Higgs Audio プロセッサーを構築します。音声特徴抽出、トークナイザー、および音声エンコード/デコードの機能を引き継ぎます。詳細は call() および decode() を参照してください。

__call__

< >

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

decode

< >

( audio_input_ids )

HiggsAudioV2Model

class transformers.HiggsAudioV2Model

< >

( config: HiggsAudioV2Config )

パラメータ

  • config (HiggsAudioV2Config) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

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

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneaudio_input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Noneaudio_input_ids_mask: typing.Optional[torch.BoolTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ~models.modeling_outputs.BaseModelOutputWithPast

パラメータ

  • input_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。

    インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。

    入力IDとは何ですか?

  • audio_input_ids (torch.LongTensor 形状 (batch_size, num_audio_frames, num_codebooks), 省略可) — オーディオ・コードブック・トークンのインデックスです。

    インデックスは、HiggsAudioV2TokenizerModel.encode() を使用して取得できます。

  • attention_mask (torch.LongTensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

  • audio_input_ids_mask (torch.BoolTensor、shape (batch_size, num_audio_frames)、任意) — audio_input_ids 内のどのオーディオフレームが有効であるかを示します。
  • position_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、任意) — 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックス。範囲 [0, config.n_positions - 1].

    ポジションIDとは?

  • past_key_values (~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返した past_key_values であり、 use_cache=True または config.use_cache=True.

    入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。 past_key_values が渡されない場合、デフォルトで DynamicCache が初期化されます。

    モデルは、入力として与えられたのと同じキャッシュ形式を出力します。

    past_key_values を使用する場合、すべての input_ids(形状 (batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理の input_ids(形状 (batch_size, unprocessed_length))のみを入力することになります。

  • inputs_embeds (torch.Tensor、形状 (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 の forward メソッドは、__call__ という特殊メソッドをオーバーライドします。

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

例:

>>> 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

< >

( config: HiggsAudioV2Configuse_text_head: bool = False )

パラメータ

  • config (HiggsAudioV2Config) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
  • use_text_head (bool、省略可、デフォルトは False) — テキスト言語モデルのヘッドを使用するかどうか。生成にはこのヘッドは必要ありませんが、学習時にテキストの損失を計算するために使用できます。

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

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.BoolTensor] = Noneaudio_input_ids: typing.Optional[torch.LongTensor] = Noneaudio_input_ids_mask: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneaudio_labels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ~models.modeling_outputs.CausalLMOutputWithPast

パラメータ

  • input_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。

    インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。

    入力IDとは何ですか?

  • attention_mask (torch.BoolTensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

  • audio_input_ids (torch.LongTensor 形状 (batch_size, num_audio_frames, num_codebooks), 省略可) — オーディオ・コードブック・トークンのインデックスです。

    インデックスは、HiggsAudioV2TokenizerModel.encode() を使用して取得できます。

  • audio_input_ids_mask (torch.BoolTensor、shape (batch_size, num_audio_frames)、任意) — audio_input_ids 内のどのオーディオフレームが有効であるかを示します。
  • position_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、任意) — 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックス。範囲 [0, config.n_positions - 1].

    ポジションIDとは?

  • past_key_values (~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返した past_key_values であり、 use_cache=True または config.use_cache=True.

    入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。 past_key_values が渡されない場合、デフォルトで DynamicCache が初期化されます。

    モデルは、入力として与えられたのと同じキャッシュ形式を出力します。

    past_key_values を使用する場合、すべての input_ids(形状 (batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理の input_ids(形状 (batch_size, unprocessed_length))のみを入力することになります。

  • inputs_embeds (torch.Tensor、形状 (batch_size, sequence_length, hidden_size)、任意) — input_ids を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、input_ids のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。
  • labels (torch.LongTensor、shape (batch_size, sequence_length)、任意) — マスク言語モデリング損失を計算するためのラベルです。インデックスは [0, ..., config.vocab_size] の範囲内であるか、-100 である必要があります(input_ids の docstring を参照)。インデックスが -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 -100are 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.
  • 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のforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

例:

>>> 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

< >

( inputs: typing.Optional[torch.Tensor] = Nonegeneration_config: transformers.generation.configuration_utils.GenerationConfig | None = Nonelogits_processor: transformers.generation.logits_process.LogitsProcessorList | None = Nonestopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = Noneprefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = Nonesynced_gpus: bool | None = Noneassistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = Nonestreamer: typing.Optional[ForwardRef('BaseStreamer')] = Nonenegative_prompt_ids: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonecustom_generate: str | collections.abc.Callable | None = None**kwargs ) → ModelOutput or torch.LongTensor

パラメータ

  • inputs(torch.Tensor、モダリティによって形状が異なり、省略可) — 生成のプロンプトとして使用されるシーケンス、またはエンコーダーへのモデル入力です。None の場合、bos_token_id とバッチサイズ 1 で初期化されます。デコーダー専用モデルでは、inputs は input_ids の形式である必要があります。エンコーダーデコーダーモデルでは、inputs は input_ids、input_values、input_features、または pixel_values のいずれかを表すことができます。
  • generation_config (GenerationConfig、任意) — 生成呼び出しのベースパラメータ化として使用される生成設定です。**kwargs で generate に渡され、generation_config の属性と一致するものは、それらをオーバーライドします。 generation_config が指定されない場合、デフォルトが使用されます。その読み込み優先順位は以下の通りです: 1) 存在する場合、generation_config.json モデルファイルから; 2) モデル設定から。未指定のパラメータは 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 に記載されているような、プレフィックスに条件付けられた制約付き生成に有用です。
  • synced_gpus (bool, 省略可) — max_length まで while ループの実行を継続するかどうか。上書きされない場合、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、形状 (batch_size, sequence_length)、任意) — 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 を呼び出します。詳細については、ドキュメントを参照してください。
  • kwargs (dict[str, Any]、省略可) — generation_config のアドホックなパラメータ化、およびモデルの forward 関数に転送されるモデル固有の追加 kwargs です。モデルがエンコーダー・デコーダーモデルの場合、エンコーダー固有の kwargs にはプレフィックスを付与せず、デコーダー固有の kwargs には decoder_ をプレフィックスとして付与してください。

戻り値

ModelOutput または torch.LongTensor

return_dict_in_generate=True の場合、または config.return_dict_in_generate=True の場合は ModelOutput、それ以外は torch.LongTensor。

モデルがエンコーダー・デコーダーモデルでない場合(model.config.is_encoder_decoder=False)、考えられるModelOutputの型は以下の通りです:

モデルがエンコーダー・デコーダーモデル(model.config.is_encoder_decoder=True)の場合、考えられるModelOutputの型は以下の通りです:

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

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

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

Update on GitHub