Transformers documentation

Music Flamingo

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

このモデルは2025年11月13日にHF papersで公開され、2026年3月30日にHugging Face Transformersに貢献されました。

Music Flamingo

FlashAttention SDPA

概要

Music Flamingo は、音楽に対する堅牢な理解と推論を目的として設計された、完全にオープンな大規模オーディオ言語モデルです。Audio Flamingo 3 のアーキテクチャを基盤とし、Rotary Time Embeddings (RoTE) を組み込むことで時間的位置情報を注入し、最大 20 分(1200 秒)のオーディオシーケンスを処理できるようにしています。

モデルのチェックポイントは、nvidia/music-flamingo-2601-hf で利用できます。

ハイライト:

  • 音声、サウンド、音楽にまたがる統合オーディオエンコーダー。
  • 時間モデリングを強化するためのRotary Time Embeddings (RoTE)により、最大20分間の音声のサポートが可能になりました。
  • ウィンドウ処理とプーリング後のアラインメントによる長時間音声のサポート(最大20分)。 モデルは30秒のウィンドウで音声を処理し、ウィンドウ数は最大40個(合計20分)に制限されています。20分を超える音声は切り捨てられます。
  • 音声シーケンスモデリングの向上のための、特別な音声境界トークン(<|sound_bos|> と <|sound_eos|>)。
  • 音声プレースホルダトークンを音声埋め込みで置き換えることでシーケンス長を維持する、決定論的な融合。

このモデルは、Lasha Koroshinadze氏とEric Bezzam氏によって提供されました。

論文

Music Flamingo: 音声言語モデルにおける音楽理解のスケーリング
S. Ghosh, A. Goel, L. Koroshinadze, S. Lee, Z. Kong, J. F. Santos, R. Duraiswami, D. Manocha, W. Ping, M. Shoeybi, B. Catanzaro
NVIDIA およびメリーランド大学
プロジェクト: https://research.nvidia.com/labs/adlr/MF/

使用方法

Audio Instruct モード

モデルは、マルチターン対話を含む音声テキスト指示をサポートし、すべてバッチ処理で処理されます。

➡️ 音声 + テキスト指示

from transformers import AutoProcessor, MusicFlamingoForConditionalGeneration


model_id = "nvidia/music-flamingo-2601-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Describe this track in full detail - tell me the genre, tempo, and key, then dive into the instruments, production style, and overall mood it creates."},
            {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3"},
        ],
    }
]

inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
).to(model.device)
inputs["input_features"] = inputs["input_features"].to(model.dtype)

outputs = model.generate(**inputs, max_new_tokens=500)

decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)
print(decoded_outputs)

➡️ マルチターン:

from transformers import AutoProcessor, MusicFlamingoForConditionalGeneration


model_id = "nvidia/music-flamingo-2601-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "Write a rich caption that blends the technical details (genre, BPM, key, chords, mix) with how the song feels emotionally and dynamically as it unfolds.",
            },
            {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3"},
        ],
    },
    {
        "role": "assistant",
        "content": [{"type": "text", "text": "This energetic Eurodance anthem at 150 BPM in E major combines bright synth arpeggios with a punchy four-on-the-floor beat..."}],
    },
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "What instruments stand out the most?"},
        ],
    },
]

inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
).to(model.device)
inputs["input_features"] = inputs["input_features"].to(model.dtype)

outputs = model.generate(**inputs, max_new_tokens=500)

decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)
print(decoded_outputs)

➡️ バッチ推論!

from transformers import AutoProcessor, MusicFlamingoForConditionalGeneration


model_id = "nvidia/music-flamingo-2601-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")

conversations = [
    [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe this track in full detail - tell me the genre, tempo, and key, then dive into the instruments, production style, and overall mood it creates."},
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3",
                },
            ],
        }
    ],
    [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Generate a structured lyric sheet from the input music.",
                },
                {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_2.mp3"},
            ],
        }
    ],
]

inputs = processor.apply_chat_template(
    conversations,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
).to(model.device)
inputs["input_features"] = inputs["input_features"].to(model.dtype)

outputs = model.generate(**inputs, max_new_tokens=500)

decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)
print(decoded_outputs)

➡️ 学習:

from transformers import AutoProcessor, MusicFlamingoForConditionalGeneration


model_id = "nvidia/music-flamingo-2601-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")
model.train()

conversation = [
    [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Break the track down like a critic - list its tempo, key, and chordal motion, then explain the textures, dynamics, and emotional impact of the performance."},
                {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3"},
            ],
        },
        {
            "role": "assistant",
            "content": [{"type": "text", "text": "This Eurodance track operates at 150 BPM in E major, with harmonic movement centering on the I-vi-IV-V family. The production features layered synth arpeggios, a four-on-the-floor kick pattern, and a mezzo-soprano lead vocal with bright timbre. Dynamically, the track builds through verses into an anthemic chorus with full synth orchestration and backing vocals, creating an uplifting, euphoric atmosphere characteristic of late 2000s dance-pop."}],
        }
    ],
    [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Describe this song from both a technical and artistic lens: mention tempo, harmony, and instrumentation, but also mood, lyrical themes, and structure.",
                },
                {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_2.mp3"},
            ],
        },
        {
            "role": "assistant",
            "content": [{"type": "text", "text": "This electronic pop track combines upbeat production with playful lyrical themes centered around late-night pizza cravings. The structure follows a verse-chorus format with recurring melodic motifs and rhythmic patterns that emphasize the celebratory, lighthearted mood of the piece."}],
        }

    ]
]

inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    processor_kwargs={"output_labels": True},
).to(model.device)
inputs["input_features"] = inputs["input_features"].to(model.dtype)

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

モデルの動作

アーキテクチャ

  • Audio Encoder Whisper 風の feature extractor + encoder → 時間方向の平均プーリング(stride 2)→ LayerNorm。 プーリング後のレートで、フレームごとの hidden states を生成します。

  • Rotary Time Embeddings (RoTE)はエンコーダーの出力に適用され、時間的位置情報を注入することで、モデルが最大20分(1200秒)の音声シーケンスを処理できるようにします。RoTEは、バッチ次元と時間次元に対して2D軸方向のロータリー埋め込みを使用し、時間ベースの角度変調を行います。

  • MusicFlamingoMultiModalProjector エンコーダーの特徴量を言語モデルの隠れ層サイズにマッピングする小さなMLPです。

  • MusicFlamingoForConditionalGeneration は、各オーディオプレースホルダトークンスロットが、その場でオーディオフレーム埋め込みによって置き換えられるテキスト埋め込みを受け入れる因果言語モデルです。オーディオシーケンスをマークするために、特別な境界トークン(<|sound_bos|> および <|sound_eos|>)を使用します。フュージョンによってシーケンス長の変化は生じません。

プロセッサレベルの整合性

  1. 各生波形は、フィーチャーエクストラクターのchunk_length(秒)とsampling_rate(Hz)に基づいて、固定長のウィンドウに分割されます。
  2. 各ウィンドウについて、プロセッサはエンコーダーが出力するプールの後のフレーム数post_pool_lenを計算します(conv/poolのスケジュールに一致させます)。
  3. プロセッサは、すべてのウィンドウにわたるプールの後のフレームの総数に応じて、音声プレースホルダートークンを展開します。
  4. その後、モデルはこれらのトークン位置を、対応する投影されたオーディオ埋め込みで置き換えます。

長い音声とウィンドウ処理

重要: 音声の最大長は20分です。 これを超える音声は切り捨てられます。

  • デフォルトのセットアップでは、16 kHzのモノラルで30秒のウィンドウを処理します。

  • プロセッサは1サンプルあたり40ウィンドウという上限を強制するため、音声の最大長は20分(40ウィンドウ × 30秒)となります。

  • Rotary Time Embeddings (RoTE) は、最大 20 分(1200 秒)までのシーケンスに対して位置情報を提供します。

  • 各ウィンドウについて:

    • mel_lenは、パディング後のメル長です。
    • Convスタックにより、conv_output_len = (mel_len - 1) // 2 + 1 となるため、時間が短縮されます。
    • ウィンドウあたりのプーリング後フレーム数: post_pool_len = (conv_output_len - 2) // 2 + 1。
    • 音声プレースホルダトークンは、すべてのウィンドウのpost_pool_lenの合計に展開されます。

MusicFlamingoConfig

class transformers.MusicFlamingoConfig

< >

( 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 = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneaudio_token_id: int = 151669projector_hidden_act: str = 'gelu'projector_bias: bool = Trueaudio_bos_token_id: int = 151670audio_eos_token_id: int = 151671audio_frame_step: float = 0.01rope_parameters: dict | None = None )

パラメータ

  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — オーディオバックボーンの config オブジェクトまたは辞書。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig]、省略可) — テキストバックボーンの設定オブジェクトまたは辞書。
  • audio_token_id (int、任意、デフォルトは 151669) — 入力音声のプレースホルダーとして使用されるオーディオトークンのインデックスです。
  • projector_hidden_act (str、任意、デフォルトは gelu) — マルチモーダルプロジェクターで使用する活性化関数です。
  • projector_bias (bool、任意、デフォルトは True) — マルチモーダルプロジェクターでバイアスを使用するかどうか。
  • audio_bos_token_id (int、任意、デフォルトは 151670) — 音声スパンの開始を示すために使用される、音声の開始トークンインデックスです。
  • audio_eos_token_id (int、任意、デフォルトは 151671) — 音声スパンの終了を示すために使用される、音声の終了トークンインデックスです。
  • audio_frame_step (float、任意、デフォルト値 0.01) — 1 つの入力 mel フレームの秒数(sampling_rate 16000 で hop_length 160 を用いて学習済み)。
  • rope_parameters (dict, 任意) — RoPE 埋め込みの設定パラメータを含む辞書です。辞書には rope_theta の値が含まれており、より長い max_position_embeddings で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

これは MusicFlamingoModel の設定を保存するための設定クラスです。指定された引数に基づいて Musicflamingo モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、nvidia/music-flamingo-2601-hf と同様の設定が得られます。

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

例:

>>> from transformers import MusicFlamingoForConditionalGeneration, MusicFlamingoConfig, AudioFlamingo3EncoderConfig, Qwen2Config

>>> # Initializing an MusicFlamingoEncoder config
>>> audio_config = AudioFlamingo3EncoderConfig()

>>> # Initializing a Qwen2 config
>>> text_config = Qwen2Config()

>>> # Initializing an MusicFlamingo configuration
>>> configuration = MusicFlamingoConfig(audio_config, text_config)

>>> # Initializing a model from the musicflamingo style configuration
>>> model = MusicFlamingoForConditionalGeneration(configuration)

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

MusicFlamingoProcessor

class transformers.MusicFlamingoProcessor

< >

( feature_extractortokenizerchat_template = Noneaudio_token = '<sound>'audio_bos_token = '<|sound_bos|>'audio_eos_token = '<|sound_eos|>'max_audio_len = 1200 )

パラメータ

  • feature_extractor (feature_extractor_class) — フィーチャーエクストラクターは必須の入力です。
  • tokenizer (tokenizer_class) — トークナイザーは必須の入力です。
  • chat_template (str) — チャット内のメッセージのリストをトークン化可能な文字列に変換するための Jinja テンプレート。
  • audio_token (Optional[str]、任意、デフォルトは "<sound>") — チャットテンプレート内でオーディオ入力を表すために使用される特殊トークンです。
  • audio_bos_token (Optional[str]、任意、デフォルトは "<|sound_bos|>") — 音声の開始を表すために使用される特殊トークンです。
  • audio_eos_token (Optional[str]、任意、デフォルトは "<|sound_eos|>") — 音声の終了を表すために使用される特殊トークンです。
  • max_audio_len (int、任意、デフォルト値は 1200)— 音声シーケンスの最大長(秒)。この長さを超える音声は切り詰められます。

MusicFlamingoProcessor を構築します。このプロセッサーは、フィーチャーエクストラクターとトークナイザーを単一のプロセッサーにラップします。

MusicFlamingoProcessor は、feature_extractor_class と tokenizer_class のすべての機能を提供します。詳細については、~feature_extractor_class および ~tokenizer_class を参照してください。

MusicFlamingoModel

class transformers.MusicFlamingoModel

< >

( config: MusicFlamingoConfig )

パラメータ

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

MusicFlamingoモデル(ファインチューニング済みのWhisperエンコーダー、マルチモーダルプロジェクター、Qwen2言語モデル)、言語モデリングヘッドなし。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneinput_features: typing.Optional[torch.FloatTensor] = Noneinput_features_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MusicFlamingoModelOutputWithPast or tuple(torch.FloatTensor)

パラメータ

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

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

    入力IDとは何ですか?

  • input_features (torch.FloatTensor、形状 (batch_size, sequence_length, feature_dim)、任意) — 入力音声特徴に対応するテンソルです。音声特徴は feature_extractor_class を使用して取得できます。詳細は feature_extractor_class.__call__ を参照してください(MusicFlamingoProcessor は音声の処理に feature_extractor_class を使用します)。
  • input_features_mask (torch.Tensor、形状 (batch_size, feature_sequence_length)) — パディングされた特徴インデックスに対するアテンションの計算を回避するためのマスク。
  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

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

  • 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.FloatTensor、形状 (batch_size, sequence_length, hidden_size)、任意) — input_ids を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込みルックアップ行列よりも、input_ids のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。
  • use_cache (bool、任意) — True に設定すると、past_key_values のキーバリュー状態が返され、デコーディングの高速化に利用できます(past_key_values を参照)。

戻り値

MusicFlamingoModelOutputWithPast または tuple(torch.FloatTensor)

MusicFlamingoModelOutputWithPast、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(MusicFlamingoConfig)や入力に応じて、さまざまな要素で構成されます。

MusicFlamingoModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

  • audio_hidden_states (torch.FloatTensor、任意) — 投影されたオーディオの隠れ状態。

MusicFlamingoForConditionalGeneration

クラス transformers.MusicFlamingoForConditionalGeneration

< >

( config: MusicFlamingoConfig )

パラメータ

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

MusicFlamingoモデルは、ファインチューニングされたWhisperエンコーダー、回転位置埋め込み、マルチモーダルプロジェクター、およびQwen2言語モデルで構成されています。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneinput_features: typing.Optional[torch.FloatTensor] = Noneinput_features_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MusicFlamingoCausalLMOutputWithPast or tuple(torch.FloatTensor)

パラメータ

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

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

    入力IDとは何ですか?

  • input_features (torch.FloatTensor、形状 (batch_size, sequence_length, feature_dim)、任意) — 入力音声特徴に対応するテンソルです。音声特徴は feature_extractor_class を使用して取得できます。詳細は feature_extractor_class.__call__ を参照してください(MusicFlamingoProcessor は音声の処理に feature_extractor_class を使用します)。
  • input_features_mask (torch.Tensor、形状 (batch_size, feature_sequence_length)) — パディングされた特徴インデックスに対するアテンションの計算を回避するためのマスク。
  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

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

  • 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.FloatTensor、形状 (batch_size, sequence_length, hidden_size)、任意) — input_ids を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込みルックアップ行列よりも、input_ids のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。
  • labels (torch.LongTensor、shape (batch_size, sequence_length)、任意) — マスク言語モデリング損失を計算するためのラベル。
  • 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 次元テンソルである必要があります。これは、パックされたテンソル形式(バッチとシーケンス長を単一の次元にまとめた形式)を使用する場合に有用です。

戻り値

MusicFlamingoCausalLMOutputWithPast または tuple(torch.FloatTensor)

MusicFlamingoCausalLMOutputWithPast または、torch.FloatTensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(MusicFlamingoConfig)や入力に応じて、さまざまな要素で構成されます。

MusicFlamingoForConditionalGenerationのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

  • loss (torch.FloatTensor、shape (1,)、optional、labels が指定された場合に返されます) — 言語モデリングの損失(次のトークン予測用)。

  • logits (torch.FloatTensor、shape (batch_size, sequence_length, config.vocab_size)) — 言語モデリングヘッドの予測スコア。

  • past_key_values (Cache、任意、use_cache=True が渡された場合または config.use_cache=True の場合に返されます)— Cache のインスタンスです。

  • hidden_states (tuple[torch.FloatTensor]、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返される) — torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。

    各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。

  • attentions (tuple[torch.FloatTensor]、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

  • audio_hidden_states (torch.FloatTensor、任意) — 投影後のオーディオエンコーダーの隠れ状態。

例:

>>> from transformers import MusicFlamingoForConditionalGeneration, AutoProcessor

>>> model_id = "nvidia/audio-flamingo-3-hf"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")
Update on GitHub