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-03-30 贡献至 Hugging Face Transformers。

Music Flamingo

FlashAttention SDPA

概述

Music Flamingo 是一款完全开放的大型音频-语言模型,旨在对音乐进行稳健的理解与推理。它在 Audio Flamingo 3 架构的基础上引入了 Rotary Time Embeddings (RoTE),通过注入时间位置信息,使模型能够处理长达 20 分钟(1200 秒)的音频序列。

模型检查点可在以下位置获取:nvidia/music-flamingo-2601-hf

亮点:

  • 统一语音、声音和音乐的音频编码器。
  • 采用 旋转时间嵌入(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/

用法

音频指令模式

该模型支持音频-文本指令,包括多轮交互,且均以批量方式处理。

➡️ 音频 + 文本指令

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

模型的工作原理

架构

  • 音频编码器 Whisper 风格的特征提取器 + 编码器 → 沿时间维度进行平均池化(步长为 2)→ LayerNorm。 输出池化后速率下的逐帧隐藏状态。

  • 应用于编码器输出的旋转时间嵌入(RoTE),用于注入时间位置信息,使模型能够处理长达 20 分钟(1200 秒)的音频序列。RoTE 针对批次维度和时间维度使用 2D 轴向旋转嵌入,并采用基于时间的角度调制。

  • MusicFlamingoMultiModalProjector 一个小型 MLP,用于将编码器特征映射到语言模型的隐藏层维度。

  • MusicFlamingoForConditionalGeneration 一种因果语言模型,接受文本嵌入,其中每个音频占位符标记槽位会被就地替换为音频帧嵌入。使用特殊边界标记(<|sound_bos|> 和 <|sound_eos|>)来标记音频序列。融合过程不会引入序列长度的变化。

处理器级对齐

  1. 每个原始波形会根据特征提取器的 chunk_length(秒)和 sampling_rate(Hz)被分割为固定长度的窗口。
  2. 对于每个窗口,处理器会计算编码器将输出的池化后帧数 post_pool_len(与卷积/池化计划相匹配)。
  3. 处理器会根据所有窗口中池化后帧的总数来扩展音频占位符标记。
  4. 模型随后会用对应的投影音频嵌入替换这些 token 位置。

长音频与分窗

重要:音频最大长度为 20 分钟。 超过此长度的音频将被截断。

  • 默认设置以 16 kHz 单声道处理 30 秒的窗口。

  • 处理器对每个样本强制执行 40 个窗口的硬性限制,因此最多可处理 20 分钟的音频(40 个窗口 × 30 秒)。

  • 旋转时间嵌入(RoTE)为最长 20 分钟(1200 秒)的序列提供位置信息。

  • 对于每个窗口:

    • mel_len 是填充后的 mel 长度。
    • 卷积堆栈会缩短时间,因为 conv_output_len = (mel_len - 1) // 2 + 1。
    • 每个窗口的池化后帧数:post_pool_len = (conv_output_len - 2) // 2 + 1。
    • 音频占位符 token 会被扩展为所有窗口中 post_pool_len 的总和。

MusicFlamingoConfig

类 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], 可选) — 音频骨干网络的配置对象或字典。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • audio_token_id (int,可选,默认为 151669) — 用作输入音频占位符的音频 token 索引。
  • projector_hidden_act (str, 可选, 默认为 gelu) — 多模态投影器使用的激活函数。
  • projector_bias (bool,可选,默认为 True) — 是否在多模态投影器中使用偏置。
  • audio_bos_token_id (int,可选,默认为 151670) — 用于标记音频片段起始位置的音频起始 token 索引。
  • audio_eos_token_id (int,可选,默认值为 151671) — 用于标记音频片段结束位置的音频结束标记索引。
  • audio_frame_step (float,可选,默认为 0.01) — 单个输入 mel 帧的时长(秒)(训练时 hop_length 为 160,sampling_rate 为 16000)。
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。

这是用于存储 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.Tensor] = 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.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MusicFlamingoModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 feature_extractor_class 获取音频特征。有关详细信息,请参阅 feature_extractor_class.__call__(MusicFlamingoProcessor 使用 feature_extractor_class 处理音频)。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 用于避免对填充特征索引执行注意力机制的掩码。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [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, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

MusicFlamingoModelOutputWithPast 或 tuple(torch.Tensor)

MusicFlamingoModelOutputWithPast 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(MusicFlamingoConfig)和输入而定的各种元素。

MusicFlamingoModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • audio_hidden_states (torch.Tensor,可选) — 投影后的音频隐藏状态。

MusicFlamingoForConditionalGeneration

class 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.Tensor] = 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.Tensor] = 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.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 feature_extractor_class 获取音频特征。有关详细信息,请参阅 feature_extractor_class.__call__(MusicFlamingoProcessor 使用 feature_extractor_class 处理音频)。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 用于避免对填充特征索引执行注意力机制的掩码。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [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, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选)— 用于计算掩码语言建模损失的标签。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

MusicFlamingoCausalLMOutputWithPast 或 tuple(torch.Tensor)

MusicFlamingoCausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(MusicFlamingoConfig)和输入。

MusicFlamingoForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • audio_hidden_states (torch.Tensor,可选) — 音频编码器投影后的隐藏状态。

示例:

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