# Qwen2.5-Omni

## 概述

[Qwen2.5-Omni](https://qwenlm.github.io/blog/qwen2.5-omni/) 模型是由阿里巴巴集团 Qwen 团队在 [Qwen2.5-Omni Technical Report](https://huggingface.co/papers/2503.20215) 中提出的一种统一多模态模型。

技术报告的摘要如下：

*我们提出了 Qwen2.5-Omni，这是一款端到端多模态模型，旨在感知包括文本、图像、音频和视频在内的多种模态，同时以流式方式生成文本和自然语音响应。为了实现多模态信息输入的流式处理，音频和视觉编码器均采用分块处理策略。该策略有效地解耦了长序列多模态数据的处理，将感知职责分配给多模态编码器，并将长序列的建模工作交给大语言模型。这种分工通过共享注意力机制增强了不同模态之间的融合。为了将视频输入的时间戳与音频同步，我们以交错的方式顺序组织音频和视频，并提出了一种名为 TMRoPE（Time-aligned Multimodal RoPE，时间对齐多模态 RoPE）的新型位置嵌入方法。为了在生成文本和语音的同时避免两种模态之间的干扰，我们提出了 Thinker-Talker 架构。在该框架中，Thinker 充当负责文本生成的大语言模型，而 Talker 是一个双轨自回归模型，它直接利用 Thinker 的隐藏表示来生成音频 token 作为输出。Thinker 和 Talker 模型均被设计为以端到端的方式进行训练和推理。为了以流式方式解码音频 token，我们引入了滑动窗口 DiT 来限制感受野，旨在降低初始包延迟。Qwen2.5-Omni 在图像和音频能力上均优于同等规模的 Qwen2-VL 和 Qwen2-Audio。此外，Qwen2.5-Omni 在 Omni-Bench 等多模态基准测试中达到了最先进的性能。值得注意的是，Qwen2.5-Omni 是首个在端到端语音指令遵循方面达到与文本输入能力相当水平的开源模型，MMLU 和 GSM8K 等基准测试证明了这一点。在语音生成方面，Qwen2.5-Omni 的流式 Talker 在鲁棒性和自然度上优于大多数现有的流式和非流式替代方案。*

> [!TIP]
> 在 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 中设置 `use_kernels=True`，即可用 Hub 上的优化内核替换受支持的层。有关详细信息，请参阅 [加载内核](../kernel_doc/loading_kernels)。

## 备注

- 使用 [Qwen2_5OmniForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniForConditionalGeneration) 生成音频和文本输出。若只需生成单一类型的输出，请使用 [Qwen2_5OmniThinkerForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniThinkerForConditionalGeneration) 生成纯文本，或使用 `Qwen2_5OmniTalkersForConditionalGeneration` 生成纯音频。
- 如果处理视频输入时出现内存不足错误，请降低 `processor.max_pixels`。默认情况下，最大值被设置为一个非常大的数值，高分辨率图像不会被调整大小，除非其分辨率超过 `processor.max_pixels`。
- 处理器拥有自己的 [apply_chat_template()](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) 方法，用于将聊天消息转换为模型输入。

## 使用示例

`Qwen2.5-Omni` 可在 [Huggingface Hub](https://huggingface.co/Qwen) 上找到。

### 单媒体推理

该模型可以接受文本、图像、音频和视频作为输入。以下是一个推理示例代码。

```python
import soundfile as sf

from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor

model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-Omni-7B",
    device_map="auto",
)
processor = Qwen2_5OmniProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

conversations = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "/path/to/video.mp4"},
            {"type": "text", "text": "What can't you hear and see in this video?"},
        ],
    },
]

inputs = processor.apply_chat_template(
    conversations,
    load_audio_from_video=True,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    fps=1,

    # kwargs to be passed to `Qwen2-5-OmniProcessor`
    padding=True,
    use_audio_in_video=True,
).to(model.device)

# Generation params for audio or text can be different and have to be prefixed with `thinker_` or `talker_`
text_ids, audio = model.generate(**inputs, use_audio_in_video=True, thinker_do_sample=False, talker_do_sample=True)
text = processor.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)

sf.write(
    "output.wav",
    audio.reshape(-1).detach().cpu().numpy(),
    samplerate=24000,
)
print(text)
```

### 仅文本生成

如果只需生成文本输出，并且希望在不加载音频生成模型的情况下节省计算资源，我们可以使用 `Qwen2_5OmniThinkerForConditionalGeneration` 模型。

```python
from transformers import Qwen2_5OmniProcessor, Qwen2_5OmniThinkerForConditionalGeneration

model = Qwen2_5OmniThinkerForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-Omni-7B",
    device_map="auto",
)
processor = Qwen2_5OmniProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

conversations = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "/path/to/video.mp4"},
            {"type": "text", "text": "What can't you hear and see in this video?"},
        ],
    },
]

inputs = processor.apply_chat_template(
    conversations,
    load_audio_from_video=True,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    fps=1,

    # kwargs to be passed to `Qwen2-5-OmniProcessor`
    padding=True,
    use_audio_in_video=True,
).to(model.device)

text_ids = model.generate(**inputs, use_audio_in_video=True)
text = processor.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)

print(text)
```

### 批量混合媒体推理

使用 `Qwen2_5OmniThinkerForConditionalGeneration` 模型时，模型可以批量处理由文本、图像、音频和视频等多种类型样本混合组成的输入。以下是一个示例。

```python
from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor

model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-Omni-7B",
    device_map="auto"
)
processor = Qwen2_5OmniProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

# Conversation with video only
conversation1 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "path": "/path/to/video.mp4"},
        ]
    }
]

# Conversation with audio only
conversation2 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "audio", "path": "/path/to/audio.wav"},
        ]
    }
]

# Conversation with pure text
conversation3 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [{"type": "text", "text": "who are you?"}],
    }
]

# Conversation with mixed media
conversation4 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "image", "path": "/path/to/image.jpg"},
            {"type": "video", "path": "/path/to/video.mp4"},
            {"type": "audio", "path": "/path/to/audio.wav"},
            {"type": "text", "text": "What are the elements can you see and hear in these media?"},
        ],
    }
]

conversations = [conversation1, conversation2, conversation3, conversation4]

inputs = processor.apply_chat_template(
    conversations,
    load_audio_from_video=True,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    fps=1,

    # kwargs to be passed to `Qwen2-5-OmniProcessor`
    padding=True,
    use_audio_in_video=True,
).to(model.thinker.device)

text_ids = model.generate(**inputs, use_audio_in_video=True)
text = processor.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)

print(text)
```

### 批量音频生成

[Qwen2_5OmniForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniForConditionalGeneration) 支持批量音频输出生成。例如，以下展示了文本转语音的批量生成。当批次包含多个样本时，生成的音频将以列表形式返回，每个样本对应一个波形，且每个波形已根据其自身长度进行裁剪，因此较短的样本不会被填充多余的音频。对于单样本调用，则仍返回单个张量。

```python
import soundfile as sf
from transformers import AutoModelForTextToWaveform, AutoProcessor
import torch

model_id = "Qwen/Qwen2.5-Omni-7B"
model = AutoModelForTextToWaveform.from_pretrained(model_id, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id)
sampling_rate = 24000  # output sampling rate
max_new_tokens = 200  # maximum number of tokens to generate

system_text = (
    "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of "
    "perceiving auditory and visual inputs, as well as generating text and speech."
)
texts = [
    "Hello, I'm Qwen. How can I help you today?",
    "The weather is nice today. Let's go for a walk.",
]
inputs = processor.apply_chat_template(
    [
        [
            {"role": "system", "content": [{"type": "text", "text": system_text}]},
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": (
                            "Please read the following text aloud exactly as written, with no "
                            f"additional commentary:\n\n{text}"
                        ),
                    }
                ],
            },
        ]
        for text in texts
    ],
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"padding": True},
).to(model.device, dtype=model.dtype)

gen_kwargs = {
    "talker_do_sample": True,
    "speaker": "Ethan",  # Ethan, Chelsie
    "talker_max_new_tokens": max_new_tokens,
}
_, pred_waveform = model.generate(**inputs, **gen_kwargs)

for sample_id, audio in enumerate(pred_waveform):
    sf.write(
        f"qwen2_5_omni_output_{sample_id}.wav",
        audio.detach().to(torch.float32).cpu().numpy(),
        sampling_rate,
    )
    print(f"Saved audio to qwen2_5_omni_output_{sample_id}.wav")
```

### 使用技巧

#### 图像分辨率权衡

该模型支持多种分辨率的输入。默认情况下，它使用原生分辨率作为输入，但更高的分辨率可以在增加计算开销的同时提升性能。用户可以设置最小和最大像素数，从而为自身需求实现最优配置。

```python
min_pixels = 128*28*28
max_pixels = 768*28*28
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B", min_pixels=min_pixels, max_pixels=max_pixels)
```

#### 用于音频输出的提示

如果用户需要音频输出，系统提示词必须设置为“你是 Qwen，由阿里巴巴集团 Qwen 团队开发的虚拟人，能够感知听觉和视觉输入，并生成文本和语音。”，否则音频输出可能无法按预期工作。

```python
{
    "role": "system",
    "content": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech.",
}
```

#### 是否使用音频输出

该模型同时支持文本和音频输出。如果用户不需要音频输出，可以在 `from_pretrained` 函数中设置 `enable_audio_output`。此选项可节省约 `~2GB` 的 GPU 显存，但 `generate` 函数的 `return_audio` 选项将只能设置为 `False`。

```python
model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-Omni-7B",
    device_map="auto",
    enable_audio_output=False,
)
```

为了获得更灵活的使用体验，我们建议用户在通过 `from_pretrained` 函数初始化模型时，将 `enable_audio_output` 设置为 `True`，然后在调用 `generate` 函数时再决定是否返回音频。当 `return_audio` 设置为 `False` 时，模型将仅返回文本输出，从而更快地获取文本响应。

```python
model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-Omni-7B",
    device_map="auto",
    enable_audio_output=True,
)
...
text_ids = model.generate(**inputs, return_audio=False)
```

#### 更改输出音频的语音类型

Qwen2.5-Omni 支持更改输出音频的音色。用户可以使用 `generate` 函数的 `speaker` 参数来指定音色类型。`"Qwen/Qwen2.5-Omni-7B"` 检查点支持两种音色类型：`Chelsie` 和 `Ethan`，其中 `Chelsie` 为女声，`Ethan` 为男声。默认情况下，如果未指定 `speaker`，则默认音色类型为 `Chelsie`。

```python
text_ids, audio = model.generate(**inputs, speaker="Chelsie")
```

```python
text_ids, audio = model.generate(**inputs, speaker="Ethan")
```

#### 使用 Flash-Attention 2 加速生成

首先，请确保安装最新版本的 Flash Attention 2：

```bash
pip install -U flash-attn --no-build-isolation
```

此外，您的硬件必须与 FlashAttention 2 兼容。有关详细信息，请参阅 [flash attention 仓库](https://github.com/Dao-AILab/flash-attention) 的官方文档。只有当模型以 `torch.float16` 或 `torch.bfloat16` 加载时，才能使用 FlashAttention-2。

要使用 FlashAttention-2 加载并运行模型，请在加载模型时添加 `attn_implementation="flash_attention_2"`：

```python
from transformers import Qwen2_5OmniForConditionalGeneration

model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-Omni-7B",
    device_map="auto",
    attn_implementation="flash_attention_2",
)
```

## Qwen2_5OmniConfig[[transformers.Qwen2_5OmniConfig]]

#### transformers.Qwen2_5OmniConfig[[transformers.Qwen2_5OmniConfig]]

```python
transformers.Qwen2_5OmniConfig(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, thinker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, talker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, token2wav_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, enable_audio_output: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L533)

**参数：**

thinker_config (`dict`, *可选*) : 底层 thinker 子模型的配置。

talker_config (`dict`, *可选*) : 底层 talker 子模型的配置。

token2wav_config (`dict`, *可选*) : 底层编解码器子模型的配置。

enable_audio_output (`bool`, *可选*, 默认为 `True`) : 是否启用音频输出并加载 talker 和 token2wav 模块。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import (
...     Qwen2_5OmniThinkerConfig,
...     Qwen2_5OmniTalkerConfig,
...     Qwen2_5OmniToken2WavConfig,
...     Qwen2_5OmniForConditionalGeneration,
...     Qwen2_5OmniConfig,
... )

>>> # Initializing sub-modules configurations.
>>> thinker_config = Qwen2_5OmniThinkerConfig()
>>> talker_config = Qwen2_5OmniTalkerConfig()
>>> token2wav_config = Qwen2_5OmniToken2WavConfig()

>>> # Initializing a module style configuration
>>> configuration = Qwen2_5OmniConfig(
...     thinker_config, talker_config, token2wav_config
... )

>>> # Initializing a model (with random weights)
>>> model = Qwen2_5OmniForConditionalGeneration(configuration)

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

#### get_text_config[[transformers.Qwen2_5OmniConfig.get_text_config]]

```python
get_text_config(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L586)

**参数：**

decoder (`Optional[bool]`，*可选*，默认为 `False`)：如果设置为 `True`，则仅搜索解码器配置名称。

返回用于文本 IO 的配置。在大多数模型中，它本身就是原始配置实例。在特定的复合模型中，它位于一组有效名称之下。

## Qwen2_5OmniVisionEncoderConfig[[transformers.Qwen2_5OmniVisionEncoderConfig]]

#### transformers.Qwen2_5OmniVisionEncoderConfig[[transformers.Qwen2_5OmniVisionEncoderConfig]]

```python
transformers.Qwen2_5OmniVisionEncoderConfig(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, depth: int = 32, hidden_size: int = 3584, hidden_act: str = 'silu', intermediate_size: int = 3420, num_heads: int = 16, in_channels: int = 3, patch_size: int | list[int] | tuple[int, int] = 14, spatial_merge_size: int = 2, temporal_patch_size: int | list[int] | tuple[int, int] = 2, window_size: int = 112, out_hidden_size: int = 3584, fullatt_block_indexes: list[int] | tuple[int, ...] = (7, 15, 23, 31), initializer_range: float = 0.02, rope_parameters: dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L30)

**参数：**

depth (`int`，*可选*，默认为 `32`)：视觉编码器中 Transformer 层的数量。

hidden_size (`int`，*可选*，默认为 `3584`)：隐藏表示的维度。

hidden_act (`str`，*可选*，默认为 `silu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

intermediate_size (`int`，*可选*，默认为 `3420`)：MLP 表示的维度。

num_heads (`int`，*可选*，默认为 `16`)：Transformer 解码器中每个注意力层的注意力头数量。

in_channels (`int`，*可选*，默认为 `3`)：输入通道数。

patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `14`)：每个 patch 的大小（分辨率）。

spatial_merge_size (`int`, *可选*，默认为 `2`)：用于通过合并相邻 patch 来减少视觉 token 数量的空间合并窗口大小。

temporal_patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `2`)：用于视频输入的 3D 补丁嵌入中的时间补丁大小。

window_size (`int`，*可选*，默认为 11)：窗口大小。

out_hidden_size (`int`，*可选*，默认值为 3584)：视觉模型的输出隐藏层大小。

fullatt_block_indexes (`int`, *可选*，默认为 `[7, 15, 23, 31]`) : 使用完整注意力的层索引

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

rope_parameters (`dict`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果您希望使用更长的 `max_position_embeddings` 来使用 RoPE，则可选地包含用于缩放的参数。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import Qwen2_5OmniVisionEncoderConfig, Qwen2_5OmniVisionEncoder

>>> # Initializing a Qwen2_5OmniVisionEncoderConfig
>>> configuration = Qwen2_5OmniVisionEncoderConfig()

>>> # Initializing a Qwen2_5OmniVisionEncoder (with random weights)
>>> model = Qwen2_5OmniVisionEncoder(configuration)

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

## Qwen2_5OmniTextConfig[[transformers.Qwen2_5OmniTextConfig]]

#### transformers.Qwen2_5OmniTextConfig[[transformers.Qwen2_5OmniTextConfig]]

```python
transformers.Qwen2_5OmniTextConfig(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 = 152064, hidden_size: int = 3584, intermediate_size: int = 18944, num_hidden_layers: int = 28, num_attention_heads: int = 28, num_key_value_heads: int | None = 4, hidden_act: str = 'silu', max_position_embeddings: int = 32768, initializer_range: float = 0.02, rms_norm_eps: float = 1e-06, use_cache: bool = True, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, use_sliding_window: bool = False, sliding_window: int | None = 32768, max_window_layers: int = 28, layer_types: list[str] | None = None, attention_dropout: float | int = 0.0, pad_token_id: int | None = None, bos_token_id: int | None = None, eos_token_id: int | list[int] | None = None, tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L128)

**参数：**

vocab_size (`int`，*可选*，默认值为 `152064`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同标记（token）的数量。

hidden_size (`int`，*可选*，默认为 `3584`)：隐藏表示的维度。

intermediate_size (`int`，*可选*，默认为 `18944`)：MLP 表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `28`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `28`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*，默认为 `4`) : 这是用于实现 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`，*可选*，默认值为 `32768`)：该模型可能使用的最大序列长度。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

rms_norm_eps (`float`，*可选*，默认为 `1e-06`)：rms 归一化层使用的 epsilon。

use_cache (`bool`，*可选*，默认为 `True`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

use_sliding_window (`bool`，*可选*，默认为 `False`)：是否使用滑动窗口注意力。

sliding_window (`int`, *可选*，默认为 `32768`)：滑动窗口注意力机制的窗口大小。如果为 `None`，则不应用滑动窗口。

max_window_layers (`int`, *可选*，默认为 `28`) : 使用完整注意力的层数。前 `max_window_layers` 层将使用完整注意力，而在此之后的任何额外层都将使用 SWA（滑动窗口注意力）。

layer_types (`list[str]`，*可选*)：一个列表，用于显式地将每个层索引与其层类型进行映射。如果未提供，将根据配置值自动生成。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

pad_token_id (`int`, *可选*) : 词表中用于填充的 Token id。

bos_token_id (`int`, *可选*) : 词表中用于表示流开始的 Token id。

eos_token_id (`Union[int, list[int]]`，*可选*)：词汇表中用于表示流结束（end-of-stream）的 Token ID。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import Qwen2_5OmniThinkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig

>>> # Initializing a Qwen2_5OmniAudioEncoder config
>>> audio_config = Qwen2_5OmniAudioEncoderConfig()

>>> # Initializing a Qwen2_5OmniVisionEncoder config
>>> vision_config = Qwen2_5OmniVisionEncoderConfig()

>>> # Initializing a Qwen2.5OmniThinker configuration
>>> configuration = Qwen2_5OmniThinkerConfig(audio_config, vision_config)

>>> # Initializing a model from the Qwen-Omni style configuration
>>> model = Qwen2_5OmniThinkerForConditionalGeneration(configuration)

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

## Qwen2_5OmniDiTConfig[[transformers.Qwen2_5OmniDiTConfig]]

#### transformers.Qwen2_5OmniDiTConfig[[transformers.Qwen2_5OmniDiTConfig]]

```python
transformers.Qwen2_5OmniDiTConfig(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, hidden_size: int = 1024, num_hidden_layers: int = 22, num_attention_heads: int = 16, ff_mult: int = 2, emb_dim: int = 512, head_dim: int = 64, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, max_position_embeddings: int = 32768, block_size: int = 24, look_ahead_layers: list[int] | tuple[int, ...] = (10,), look_backward_layers: list[int] | tuple[int, ...] = (0, 20), repeats: int = 2, num_embeds: int = 8193, mel_dim: int = 80, dropout: float | int = 0.1, enc_emb_dim: int = 192, enc_dim: int = 128, enc_channels: list[int] | tuple[int, ...] = (256, 256, 256, 256, 768), enc_kernel_sizes: list[int] | tuple[int, ...] = (5, 3, 3, 3, 1), enc_dilations: list[int] | tuple[int, ...] = (1, 2, 3, 4, 1), enc_attention_channels: int = 64, enc_res2net_scale: int = 2, enc_se_channels: int = 64)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L391)

**参数：**

hidden_size (`int`，*可选*，默认为 `1024`)：隐藏表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `22`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `16`)：Transformer 解码器中每个注意力层的注意力头数量。

ff_mult (`int`，*可选*，默认为 2)：每个 transformer 块中前馈层的乘数。

emb_dim (`int`，*可选*，默认为 512)：嵌入层的维度。

head_dim (`int`, *可选*, 默认为 `64`) : 注意力头维度。如果为 None，则默认为 hidden_size // num_attention_heads

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

max_position_embeddings (`int`，*可选*，默认值为 `32768`)：该模型可能使用的最大序列长度。

block_size (`int`，*可选*，默认为 64)：每个处理块中的 token（帧）数量。

look_ahead_layers (`list[int]`，*可选*，默认为 `[10]`)：允许关注未来块的 Transformer 层数

look_backward_layers (`list[int]`，*可选*，默认为 `[0, 20]`)：关注当前块边界之外过去块的 Transformer 层数

repeats (`int`，*可选*，默认为 2)：编解码器嵌入重复的次数。

num_embeds (`int`，*可选*，默认为 8193)：编解码器中唯一嵌入的数量。

mel_dim (`int`, *可选*, 默认为 80) : 梅尔频谱图的维度。

dropout (`Union[float, int]`，*可选*，默认为 `0.1`)：所有 dropout 层的比率。

enc_emb_dim (`int`，*可选*，默认为 192)：预训练说话人嵌入的维度。

enc_dim (`int`，*可选*，默认为 128)：编码器输出的维度。

enc_channels (`list[int]`, *可选*, 默认为 `[256, 256, 256, 256, 768]`) : 编码器中每个 TDNN/SERes2Net 层的输出通道列表。

enc_kernel_sizes (`list[int]`，*可选*，默认为 `[5, 3, 3, 3, 1]`)：编码器中每一层的核大小列表。

enc_dilations (`list[int]`，*可选*，默认为 `[1, 2, 3, 4, 1]`)：编码器中每一层的膨胀率列表。

enc_attention_channels (`int`, *可选*，默认为 64)：SqueezeExcitationBlock 中注意力通道的数量。

enc_res2net_scale (`int`，*可选*，默认为 2)：编码器中 Res2Net 块的缩放比例。

enc_se_channels (`int`, *可选*，默认为 64)：SqueezeExcitationBlock 中 squeeze 操作后的输出通道数。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## Qwen2_5OmniBigVGANConfig[[transformers.Qwen2_5OmniBigVGANConfig]]

#### transformers.Qwen2_5OmniBigVGANConfig[[transformers.Qwen2_5OmniBigVGANConfig]]

```python
transformers.Qwen2_5OmniBigVGANConfig(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, mel_dim: int = 80, upsample_initial_channel: int = 1536, resblock_kernel_sizes: list[int] | tuple[int, ...] = (3, 7, 11), resblock_dilation_sizes: list | tuple = ((1, 3, 5), (1, 3, 5), (1, 3, 5)), upsample_rates: list[int] | tuple[int, ...] = (5, 3, 2, 2, 2, 2), upsample_kernel_sizes: list[int] | tuple[int, ...] = (11, 7, 4, 4, 4, 4))
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L456)

**参数：**

mel_dim (`int`, *可选*, 默认为 80) : 梅尔频谱图的维度。

upsample_initial_channel (`int`，*可选*，默认为 1536)：初始上采样层中的通道数。

resblock_kernel_sizes (`list[int]`，*可选*，默认为 `[3, 7, 11]`)：每个残差块的核大小列表。

resblock_dilation_sizes (`list[list[int]]`，*可选*，默认为 `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`)：每个残差块的膨胀大小列表。

upsample_rates (`list[int]`，*可选*，默认为 `[5, 3, 2, 2, 2, 2]`)：每个上采样层的上采样率列表。

upsample_kernel_sizes (`list[int]`，*可选*，默认为 `[11, 7, 4, 4, 4, 4]`)：每个上采样层的核大小列表。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## Qwen2_5OmniAudioEncoderConfig[[transformers.Qwen2_5OmniAudioEncoderConfig]]

#### transformers.Qwen2_5OmniAudioEncoderConfig[[transformers.Qwen2_5OmniAudioEncoderConfig]]

```python
transformers.Qwen2_5OmniAudioEncoderConfig(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, num_mel_bins: int = 128, encoder_layers: int = 32, encoder_attention_heads: int = 20, encoder_ffn_dim: int = 5120, d_model: int = 1280, dropout: float | int = 0.0, attention_dropout: float | int = 0.0, activation_function: str = 'gelu', activation_dropout: float | int = 0.0, scale_embedding: bool = False, initializer_range: float = 0.02, max_source_positions: int = 1500, n_window: int = 100, output_dim: int = 3584)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L77)

**参数：**

num_mel_bins (`int`，*可选*，默认为 `128`)：每个输入帧使用的 mel 特征数量。应与 `AutoFeatureExtractor` 类中使用的值对应。

encoder_layers (`int`，*可选*，默认为 `32`)：Transformer 编码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

encoder_attention_heads (`int`，*可选*，默认为 `20`)：Transformer 编码器中每个注意力层的注意力头数量。

encoder_ffn_dim (`int`, *可选*，默认为 `5120`)：编码器中“中间”（通常称为前馈）层的维度。

d_model (`int`，*可选*，默认为 `1280`)：编码器层和池化层的大小。

dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：所有 dropout 层的比率。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

activation_function (`str`，*可选*，默认为 `gelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

activation_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：全连接层内部激活值的 dropout 比率。

scale_embedding (`bool`，*可选*，默认为 `False`)：是否通过将嵌入除以 sqrt(d_model) 来对其进行缩放。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

max_source_positions (`int`，*可选*，默认值为 1500)：该模型可能使用的 log-mel 滤波器组特征的最大序列长度。

n_window (`int`，*可选*，默认为 100)：AudioEncoder 中 conv 和 flash attn 的块大小。

output_dim (`int`, *可选*，默认为 3584)：AudioEncoder 的输出维度。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniAudioEncoder

>>> # Initializing a Qwen2_5OmniAudioEncoderConfig
>>> configuration = Qwen2_5OmniAudioEncoderConfig()

>>> # Initializing a Qwen2_5OmniAudioEncoder (with random weights)
>>> model = Qwen2_5OmniAudioEncoder(configuration)

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

## Qwen2_5OmniProcessor[[transformers.Qwen2_5OmniProcessor]]

#### transformers.Qwen2_5OmniProcessor[[transformers.Qwen2_5OmniProcessor]]

```python
transformers.Qwen2_5OmniProcessor(image_processor = None, video_processor = None, feature_extractor = None, tokenizer = None, chat_template = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py#L121)

**参数：**

image_processor (`Qwen2VLImageProcessor`)：图像处理器是必需的输入。

video_processor (`Qwen2VLVideoProcessor`)：视频处理器是必需的输入。

feature_extractor (`WhisperFeatureExtractor`)：特征提取器是必需的输入。

tokenizer (`Qwen2Tokenizer`)：分词器是必需的输入。

chat_template (`str`) : 一个 Jinja 模板，用于将聊天中的消息列表转换为可分词的字符串。

构建一个 Qwen2_5OmniProcessor，它将图像处理器、视频处理器、特征提取器和分词器封装为单一处理器。

[Qwen2_5OmniProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniProcessor) 提供了 [Qwen2VLImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor)、[Qwen2VLVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLVideoProcessor)、[WhisperFeatureExtractor](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 和 [Qwen2Tokenizer](/docs/transformers/v5.23.0/zh/model_doc/qwen2#transformers.Qwen2Tokenizer) 的全部功能。有关更多信息，请参阅 [~Qwen2VLImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor)、[~Qwen2VLVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLVideoProcessor)、[~WhisperFeatureExtractor](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 和 [~Qwen2Tokenizer](/docs/transformers/v5.23.0/zh/model_doc/qwen2#transformers.Qwen2Tokenizer)。

#### __调用__[[transformers.Qwen2_5OmniProcessor.__call__]]

```python
__call__(text: str | list[str] | list[list[str]] = None, images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.qwen2_5_omni.processing_qwen2_5_omni.Qwen2_5OmniProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py#L155)

**参数：**

text (`Union[str, list[str], list[list[str]]]`，*可选*)：要编码的序列或序列批次。每个序列可以是字符串或字符串列表（预分词字符串）。如果传入预分词输入，请设置 `is_split_into_words=True` 以避免与批量输入产生歧义。

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *可选*) : 要预处理的图像。期望输入单张图像或一批图像，其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`，*可选*)：要预处理的视频。期望输入单个视频或一批视频，其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间，请设置 `do_rescale=False`。

audio (`Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor]]`, *可选*) : 要准备的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。对于 NumPy 数组/PyTorch 张量，每个音频的形状应为 (C, T)，其中 C 是通道数，T 是音频的采样长度。

min_pixels (`int`, *kwargs*, *可选*) : 视频帧在调整大小后的最小像素数（高度 × 宽度）。小于此阈值的帧将被放大以满足最低要求。

max_pixels (`int`, *kwargs*, *可选*) : 视频帧在调整大小后的最大像素数（高度 × 宽度）。超过此阈值的帧将被缩小以符合该限制。

patch_size (`int`, *kwargs*, *可选*) : 视觉编码器使用的空间补丁大小。视频帧在高度和宽度两个维度上被划分为此大小的补丁。

temporal_patch_size (`int`, *kwargs*, *可选*) : 视觉编码器使用的时序补丁大小。这决定了将多少连续帧分组为一个时序补丁。

merge_size (`int`, *kwargs*, *可选*) : 用于合并空间补丁的合并大小。多个补丁会被合并在一起，以在保留空间信息的同时减少序列长度。

min_frames (`int`, *kwargs*, *可选*) : 从视频中提取的最少帧数。帧数较少的视频将被填充或重复，以满足此要求。

max_frames (`int`, *kwargs*, *可选*) : 从视频中提取的最大帧数。较长的视频将被截断或采样，以符合此限制。

use_audio_in_video (`bool`，*kwargs*，*可选*，默认为 `False`)：已弃用的参数 - 请改用 `load_audio_from_video`。

load_audio_from_video (`bool`, *kwargs*, *可选*，默认为 `False`) : 已弃用，请改用 `Qwen2_5OmniProcessorKwargs.load_audio_from_video`。是否在处理视频时纳入音频信息。启用后，音频 token 将根据时间对齐与视频 token 交错排列，从而构建统一的多模态表示。

seconds_per_chunk (`float`, *kwargs*, *可选*，默认值为 `2.0`)：已弃用，请改用 `Qwen2_5OmniProcessorKwargs.seconds_per_chunk`。在拆分长视频时，每个视频片段的时长（以秒为单位）。此参数控制视频如何被划分为时间片段以供处理。

position_id_per_seconds (`int`，*kwargs* 或 `float`，*可选*，默认为 `25`)：已弃用，请改用 `Qwen2_5OmniProcessorKwargs.position_id_per_seconds`。每秒视频分配的位置 ID 数量。此参数控制位置嵌入的时间分辨率，并在 `use_audio_in_video=True` 时用于对齐视频标记与音频标记。

return_mm_token_type_ids (`bool`, *kwargs*) : 是否返回多模态 token 类型 ID，以指示多模态占位符 token 的位置。

return_text_replacement_offsets (`bool`, *kwargs*) : 是否返回每个多模态占位符及其替换项的字符偏移量。

load_audio_from_video (`bool`, *kwargs*) : 是否加载输入视频的音轨。如果模型支持，音频标记将与视频标记交错排列。

seconds_per_chunk (`float`, *kwargs*, *可选*，默认为 `2.0`) : 在拆分长视频时，每个视频片段的时长（以秒为单位）。此参数控制视频如何被划分为时间片段以进行处理。

position_id_per_seconds (`int`、*kwargs* 或 `float`，*可选*，默认为 `25`)：每秒视频分配的位置 ID 数量。此参数控制位置嵌入的时间分辨率，并在 `load_audio_from_video=True` 时用于对齐视频标记与音频标记。

return_tensors (`str` 或 [TensorType](/docs/transformers/v5.23.0/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

**返回：** `~feature_extraction_utils.BatchFeature`

- **data** (`dict`, *可选*) -- 由 __call__/pad 方法返回的列表/数组/张量字典（'input_values'、'attention_mask' 等）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
- **skip_tensor_conversion** (`list[str]` 或 `set[str]`，*可选*) -- 即使指定了 `tensor_type`，也不应转换为张量的键的列表或集合。

## Qwen2_5OmniForConditionalGeneration[[transformers.Qwen2_5OmniForConditionalGeneration]]

#### transformers.Qwen2_5OmniForConditionalGeneration[[transformers.Qwen2_5OmniForConditionalGeneration]]

```python
transformers.Qwen2_5OmniForConditionalGeneration(config: Qwen2_5OmniConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L3715)

**参数：**

config ([Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

完整的 Qwen2.5Omni 模型，一个由 3 个子模型组成的多模态模型：
- [Qwen2_5OmniThinkerForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniThinkerForConditionalGeneration)：
因果自回归 Transformer 以文本、音频、图像、视频作为输入，并预测文本 token。
- [Qwen2_5OmniTalkerForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniTalkerForConditionalGeneration)：
因果自回归 Transformer 以思考者的隐藏状态和响应作为输入，并预测语音 token。
- [Qwen2_5OmniToken2WavModel](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniToken2WavModel)：
DiT 模型以语音 token 作为输入并预测梅尔频谱，而 BigVGAN 声码器则以梅尔频谱作为输入并预测波形。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Qwen2_5OmniForConditionalGeneration.forward]]

```python
forward(*args, **kwargs)
```

点分路径（例如 `torch.float32`）的模拟值：属性访问链和调用行为如同透传装饰器，`repr` 为点分路径，将其用作基类时会替换为普通的 `type` 基类（PEP 560 `__mro_entries__`），因此真实的子类保留正常的元类，且 `inspect.signature` 读取的是它们真实的 `__init__`，而非模拟对象的。

## Qwen2_5OmniPreTrainedModelForConditionalGeneration[[transformers.Qwen2_5OmniPreTrainedModelForConditionalGeneration]]

#### transformers.Qwen2_5OmniPreTrainedModelForConditionalGeneration[[transformers.Qwen2_5OmniPreTrainedModelForConditionalGeneration]]

```python
transformers.Qwen2_5OmniPreTrainedModelForConditionalGeneration(config: PreTrainedConfig, *inputs, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L155)

#### get_chunked_index[[transformers.Qwen2_5OmniPreTrainedModelForConditionalGeneration.get_chunked_index]]

```python
get_chunked_index(token_indices: Tensor, tokens_per_chunk: int, remove_index: int)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L178)

**参数：**

token_indices (`torch.Tensor`，形状为 `(seq_len, )`)：一个单调递增的 token 索引值列表。

t_ntoken_per_chunk (`int`) : 每个块中的 token 数量（用作块大小阈值）。

remove_index (`int`) 在分块之前从 `token_indices` 中减去的索引 id --

**返回：** `list[tuple[int, int]]`

一个元组列表，每个元组表示 `token_indices` 中某个分块的起始（包含）和结束（不包含）索引。

根据 token 值范围将 token 索引列表拆分为多个块。

给定一个 token 索引列表，返回一个由 (start, end) 索引元组组成的列表，这些元组表示列表中 token 值落在 `t_ntoken_per_chunk` 的连续区间内的切片。

例如，如果 `t_ntoken_per_chunk` 为 1000，该函数将创建如下分块：
- 第一个块包含 token 值 < 1000，
- 第二个块包含大于等于 1000 且小于 2000 的值，依此类推。

#### get_rope_index[[transformers.Qwen2_5OmniPreTrainedModelForConditionalGeneration.get_rope_index]]

```python
get_rope_index(input_ids: typing.Optional[torch.LongTensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, use_audio_in_video: bool = False, audio_seqlens: typing.Optional[torch.LongTensor] = None, second_per_grids: typing.Optional[torch.Tensor] = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L215)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`)：输入序列中 token 在词汇表中的索引。如果您提供了填充，默认情况下将被忽略。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 3)`，*可选*)：LLM 中每个视频的特征形状的时间、高度和宽度。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。

use_audio_in_video (`bool`, *可选*) : 如果设置为 `True`，则使用视频中的音频。

audio_seqlens (`torch.LongTensor`，形状为 `(num_audios)`，*可选*)：LLM 中每个音频的特征形状长度。

second_per_grids (`torch.LongTensor`，形状为 `(num_videos)`，*可选*)：3D 位置 ID 中沿时间维度每个网格的时间间隔（以秒为单位）。

**返回值：**

position_ids (`torch.LongTensor`，形状为 `(3, batch_size, sequence_length)`) mrope_position_deltas (`torch.Tensor`，形状为 `(batch_size)`)

在 LLM 中，根据图像和视频的时间、高度和宽度计算 3D rope 索引。

说明：每个嵌入序列包含视觉嵌入和文本嵌入，或者仅包含文本嵌入。

对于纯文本嵌入序列，旋转位置嵌入与现代 LLM 没有区别。示例：input_ids: [T T T T T]，其中 T 代表文本。temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4]

对于视觉和文本嵌入序列，我们为视觉部分计算 3D 旋转位置嵌入，为文本部分计算 1D 旋转位置嵌入。示例：时间（Time）：3 个 patch，表示视频在时间轴上的不同片段。高度：2 个 patch，将每一帧在垂直方向上进行划分。宽度：2 个 patch，将每一帧在水平方向上进行划分。我们还有一些重要参数：fps（Frames Per Second）：视频的帧率，设置为 1。这意味着每秒处理一帧。tokens_per_second：这是一个关键参数。它决定了在概念上，视频的一秒间隔内打包了多少个“时间步”或“时间 token”。在这种情况下，我们每秒有 25 个 token。因此，视频的每一秒将由 25 个独立的时间点来表示。它本质上定义了时间粒度。temporal_patch_size：组成一个时间 patch 的帧数。在这里，它是 2 帧。interval：时间位置 ID 的步长，计算方式为 tokens_per_second * temporal_patch_size / fps。在这种情况下，25 * 2 / 1 = 50。这意味着每个时间 patch 在时间位置 ID 上的差值为 50。input_ids: [V V V V V V V V V V V V T T T T T]，其中 V 代表视觉。vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [101, 102, 103, 104, 105] text height position_ids: [101, 102, 103, 104, 105] text width position_ids: [101, 102, 103, 104, 105] 在这里，我们将文本起始 position_ids 计算为视觉 position_ids 的最大值加 1。

## Qwen2_5OmniThinkerConfig[[transformers.Qwen2_5OmniThinkerConfig]]

#### transformers.Qwen2_5OmniThinkerConfig[[transformers.Qwen2_5OmniThinkerConfig]]

```python
transformers.Qwen2_5OmniThinkerConfig(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, audio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, audio_token_index: int = 151646, image_token_index: int = 151655, video_token_index: int = 151656, position_id_per_seconds: int = 25, seconds_per_chunk: int = 2, audio_start_token_id: int = 151647, audio_end_token_id: int = 151648, user_token_id: int = 872, initializer_range: float = 0.02, tie_word_embeddings: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L212)

**参数：**

audio_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：音频骨干网络的配置对象或字典。

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：文本骨干网络的配置对象或字典。

audio_token_index (`int`，*可选*，默认为 `151646`)：用作输入音频占位符的音频 token 索引。

image_token_index (`int`, *可选*, 默认为 `151655`) : 用作输入图像占位符的图像标记索引。

video_token_index (`int`，*可选*，默认为 `151656`)：用作输入视频占位符的视频 token 索引。

position_id_per_seconds (`int`，*可选*，默认为 25)：每秒位置 ID 的增量。

seconds_per_chunk (`int`，*可选*，默认为 2)：音频和视频数据块的时长（以秒为单位）。

audio_start_token_id (`int`, *可选*, 默认为 151647) : 用于编码音频提示的音频起始标记索引。

audio_end_token_id (`int`, *可选*, 默认为 151648) : 用于编码音频提示的音频结束标记索引。

user_token_id (`int, *可选*，默认为 872) : 用于编码用户 token 的用户 token 索引。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

tie_word_embeddings (`bool`，*可选*，默认为 `False`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import Qwen2_5OmniThinkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig

>>> # Initializing a Qwen2_5OmniAudioEncoder config
>>> audio_config = Qwen2_5OmniAudioEncoderConfig()

>>> # Initializing a Qwen2_5OmniVisionEncoder config
>>> vision_config = Qwen2_5OmniVisionEncoderConfig()

>>> # Initializing a Qwen2_5OmniTextConfig config
>>> text_config = Qwen2_5OmniTextConfig()

>>> # Initializing a Qwen2.5OmniThinker configuration
>>> configuration = Qwen2_5OmniThinkerConfig(audio_config, vision_config, text_config)

>>> # Initializing a model from the Qwen-Omni style configuration
>>> model = Qwen2_5OmniThinkerForConditionalGeneration(configuration)

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

## Qwen2_5OmniThinkerModel[[transformers.Qwen2_5OmniThinkerModel]]

#### transformers.Qwen2_5OmniThinkerModel[[transformers.Qwen2_5OmniThinkerModel]]

```python
transformers.Qwen2_5OmniThinkerModel(config: Qwen2_5OmniThinkerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1668)

**参数：**

config ([Qwen2_5OmniThinkerConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniThinkerConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

由音频骨干网络和语言模型组成的 Qwen2.5OmniThinker 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Qwen2_5OmniThinkerModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, input_features: typing.Optional[torch.Tensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, feature_attention_mask: typing.Optional[torch.Tensor] = None, audio_feature_lengths: 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, use_cache: bool | None = None, use_audio_in_video: bool | None = None, video_second_per_grid: typing.Optional[torch.LongTensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1843)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

input_features (`torch.Tensor`，形状为 `(batch_size, sequence_length, feature_dim)`，*可选*) : 与输入音频特征对应的张量。可以使用 [WhisperFeatureExtractor](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 获取音频特征。有关详细信息，请参阅 [WhisperFeatureExtractor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)（[Qwen2_5OmniProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniProcessor) 使用 [WhisperFeatureExtractor](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 处理音频）。

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [Qwen2VLImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) 获取像素值。有关详细信息，请参阅 [Qwen2VLImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[Qwen2_5OmniProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniProcessor) 使用 [Qwen2VLImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) 处理图像）。

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 [Qwen2VLVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLVideoProcessor) 获取视频的像素值。有关详细信息，请参阅 [Qwen2VLVideoProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2VideoProcessor.__call__)（[Qwen2_5OmniProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniProcessor) 使用 [Qwen2VLVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLVideoProcessor) 来处理视频）。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 3)`，*可选*)：LLM 中每个视频的特征形状的时间、高度和宽度。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

feature_attention_mask (`torch.Tensor`，形状为 `(batch_size, feature_sequence_length)`，*可选*)：用于避免对填充特征索引执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 对于**未掩码**的 token，值为 1； - 对于**已掩码**的 token，值为 0。

audio_feature_lengths (`torch.LongTensor`，形状为 `(num_audios)`，*可选*)：LLM 中每个音频的特征形状长度。

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

use_audio_in_video (`bool`, *可选*) : 是否使用视频中的音轨，应与 `process_audio_info` 中的参数保持一致。

video_second_per_grid (`torch.LongTensor`，形状为 `(num_videos)`，*可选*)：每个视频中每个网格对应的秒数，用于时间特征映射。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** [BaseModelOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

[Qwen2_5OmniThinkerModel](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniThinkerModel) 的 forward 方法会重写 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

## Qwen2_5OmniThinkerForConditionalGeneration[[transformers.Qwen2_5OmniThinkerForConditionalGeneration]]

#### transformers.Qwen2_5OmniThinkerForConditionalGeneration[[transformers.Qwen2_5OmniThinkerForConditionalGeneration]]

```python
transformers.Qwen2_5OmniThinkerForConditionalGeneration(config: Qwen2_5OmniThinkerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1959)

#### forward[[transformers.Qwen2_5OmniThinkerForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, input_features: typing.Optional[torch.Tensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, feature_attention_mask: typing.Optional[torch.Tensor] = None, audio_feature_lengths: 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, use_cache: bool | None = None, use_audio_in_video: bool | None = None, video_second_per_grid: typing.Optional[torch.LongTensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L2017)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

input_features (`torch.Tensor`，形状为 `(batch_size, sequence_length, feature_dim)`，*可选*) : 与输入音频特征对应的张量。可以使用 [WhisperFeatureExtractor](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 获取音频特征。有关详细信息，请参阅 [WhisperFeatureExtractor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)（[Qwen2_5OmniProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniProcessor) 使用 [WhisperFeatureExtractor](/docs/transformers/v5.23.0/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 处理音频）。

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [Qwen2VLImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) 获取像素值。有关详细信息，请参阅 [Qwen2VLImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[Qwen2_5OmniProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniProcessor) 使用 [Qwen2VLImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLImageProcessor) 处理图像）。

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 [Qwen2VLVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLVideoProcessor) 获取视频的像素值。有关详细信息，请参阅 [Qwen2VLVideoProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2VideoProcessor.__call__)（[Qwen2_5OmniProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniProcessor) 使用 [Qwen2VLVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/qwen2_vl#transformers.Qwen2VLVideoProcessor) 来处理视频）。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 3)`，*可选*)：LLM 中每个视频的特征形状的时间、高度和宽度。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

feature_attention_mask (`torch.Tensor`，形状为 `(batch_size, feature_sequence_length)`，*可选*)：用于避免对填充特征索引执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 对于**未掩码**的 token，值为 1； - 对于**已掩码**的 token，值为 0。

audio_feature_lengths (`torch.LongTensor`，形状为 `(num_audios)`，*可选*)：LLM 中每个音频的特征形状长度。

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(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` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

use_audio_in_video (`bool`, *可选*) : 是否使用视频中的音轨，应与 `process_audio_info` 中的参数保持一致。

video_second_per_grid (`torch.LongTensor`，形状为 `(num_videos)`，*可选*)：每个视频中每个网格对应的秒数，用于时间特征映射。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** [CausalLMOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [CausalLMOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

[Qwen2_5OmniThinkerForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniThinkerForConditionalGeneration) 的 forward 方法会重写 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from transformers import Qwen2_5OmniProcessor, Qwen2_5OmniThinkerForConditionalGeneration

>>> thinker = Qwen2_5OmniThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-Omni-7B")
>>> processor = Qwen2_5OmniProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

>>> conversations = [
>>>         {'role': 'system', 'content': 'You are a helpful voice chat bot, and please respond to me in a casual conversation manner using random voice.'},
>>>         {"role": "user", "content": [
>>>             {"type": "image", "image": "https://www.ilankelman.org/stopsigns/australia.jpg"},
>>>             {"type": "audio", "audio": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/audio/glass_breaking.mp3"},
>>>         ]},
>>> ]

>>> inputs = processor.apply_chat_template(
    conversations,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt"
)

>>> # Generate
>>> generation = thinker.generate(**inputs, max_new_tokens=2048)
>>> generate_ids = generation[:, inputs.input_ids.size(1):]

>>> response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
```

#### get_audio_features[[transformers.Qwen2_5OmniThinkerForConditionalGeneration.get_audio_features]]

```python
get_audio_features(input_features: Tensor, feature_attention_mask: typing.Optional[torch.LongTensor] = None, audio_feature_lengths: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1999)

**参数：**

input_features (`torch.Tensor`) : 与输入音频对应的张量。

feature_attention_mask (`torch.LongTensor`, *可选*) : 用于避免对填充特征索引执行注意力机制的掩码。掩码值选自 `[0, 1]`：

audio_feature_lengths (`torch.LongTensor`，形状为 `(num_audios)`，*可选*)：LLM 中每个音频的特征形状长度。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen2_5OmniThinkerForConditionalGeneration

>>> model = Qwen2_5OmniThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-Omni-7B")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

#### get_image_features[[transformers.Qwen2_5OmniThinkerForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, image_grid_thw: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1986)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：LLM 中每张图片特征形状的时间、高度和宽度。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen2_5OmniThinkerForConditionalGeneration

>>> model = Qwen2_5OmniThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-Omni-7B")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

#### get_video_features[[transformers.Qwen2_5OmniThinkerForConditionalGeneration.get_video_features]]

```python
get_video_features(pixel_values_videos: Tensor, video_grid_thw: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1973)

**参数：**

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入视频对应的张量。

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 3)`，*可选*)：LLM 中每个视频的特征形状的时间、高度和宽度。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen2_5OmniThinkerForConditionalGeneration

>>> model = Qwen2_5OmniThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-Omni-7B")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

## Qwen2_5OmniThinkerTextModel[[transformers.Qwen2_5OmniThinkerTextModel]]

#### transformers.Qwen2_5OmniThinkerTextModel[[transformers.Qwen2_5OmniThinkerTextModel]]

```python
transformers.Qwen2_5OmniThinkerTextModel(config: Qwen2_5OmniTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1548)

**参数：**

config ([Qwen2_5OmniTextConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniTextConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Qwen2 5 Omni Text Model，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Qwen2_5OmniThinkerTextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = 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.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L1575)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

**返回：** [BaseModelOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

[Qwen2_5OmniThinkerTextModel](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniThinkerTextModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

## Qwen2_5OmniTalkerConfig[[transformers.Qwen2_5OmniTalkerConfig]]

#### transformers.Qwen2_5OmniTalkerConfig[[transformers.Qwen2_5OmniTalkerConfig]]

```python
transformers.Qwen2_5OmniTalkerConfig(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, audio_token_index: int = 151646, image_token_index: int = 151655, video_token_index: int = 151656, vocab_size: int = 8448, tts_text_start_token_id: int = 151860, tts_text_end_token_id: int = 151861, tts_text_pad_token_id: int = 151859, tts_codec_start_token_id: int = 8293, tts_codec_end_token_id: int = 8294, tts_codec_pad_token_id: int = 8292, tts_codec_mask_token_id: int = 8296, vision_start_token_id: int = 151652, vision_end_token_id: int = 151653, embedding_size: int = 3584, hidden_size: int = 3584, intermediate_size: int = 18944, num_hidden_layers: int = 28, num_attention_heads: int = 28, num_key_value_heads: int = 4, hidden_act: str = 'silu', max_position_embeddings: int = 32768, rms_norm_eps: float = 1e-06, head_dim: int = 128, use_cache: bool = True, tie_word_embeddings: bool = False, use_sliding_window: bool = False, sliding_window: int | None = 32768, max_window_layers: int = 28, attention_dropout: float | int = 0.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, position_id_per_seconds: int = 25, seconds_per_chunk: int = 2, audio_start_token_id: int = 151647, audio_end_token_id: int = 151648, initializer_range: float = 0.02, spatial_merge_size: int = 2, layer_types: list[str] | None = None, pad_token_id: int | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L278)

**参数：**

audio_token_index (`int`，*可选*，默认为 `151646`)：用作输入音频占位符的音频 token 索引。

image_token_index (`int`, *可选*, 默认为 `151655`) : 用作输入图像占位符的图像标记索引。

video_token_index (`int`，*可选*，默认为 `151656`)：用作输入视频占位符的视频 token 索引。

vocab_size (`int`，*可选*，默认为 `8448`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 数量。

tts_text_start_token_id (`int`, *可选*, 默认值为 151860) : 用于编码 tts 文本起始位置的 tts 文本起始标记索引。

tts_text_end_token_id (`int`, *可选*，默认为 151861)：用于编码 tts 文本结尾的 tts 文本结束标记索引。

tts_text_pad_token_id (`int`, *可选*，默认为 151859)：用于编码 tts 文本填充的 tts 文本填充 token 索引。

tts_codec_start_token_id (`int`, *可选*，默认为 8293)：用于编码 tts codec 起始位置的 tts codec 起始标记索引。

tts_codec_end_token_id (`int`, *可选*，默认为 8294)：用于编码 tts codec 结束位置的 tts codec 结束标记索引。

tts_codec_pad_token_id (`int`, *可选*，默认为 8292)：用于编码 tts codec 填充的 tts codec pad token 索引。

tts_codec_mask_token_id (`int`, *可选*，默认为 8296)：用于编码 tts codec 掩码的 tts codec 掩码标记索引。

vision_start_token_id (`int`, *可选*，默认为 `151652`)：用于标记多模态输入序列中视觉片段起始位置的 Token ID。

vision_end_token_id (`int`, *可选*，默认为 `151653`)：用于标记多模态输入序列中视觉片段结束的 Token ID。

embedding_size (`int`，*可选*，默认为 `3584`)：嵌入和隐藏状态的维度。

hidden_size (`int`，*可选*，默认为 `3584`)：隐藏表示的维度。

intermediate_size (`int`，*可选*，默认为 `18944`)：MLP 表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `28`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `28`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*，默认为 `4`) : 这是用于实现 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`，*可选*，默认值为 `32768`)：该模型可能使用的最大序列长度。

rms_norm_eps (`float`，*可选*，默认为 `1e-06`)：rms 归一化层使用的 epsilon。

head_dim (`int`，*可选*，默认为 `128`)：注意力头维度。如果为 None，则默认为 hidden_size // num_attention_heads

use_cache (`bool`，*可选*，默认为 `True`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

tie_word_embeddings (`bool`，*可选*，默认为 `False`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

use_sliding_window (`bool`，*可选*，默认为 `False`)：是否使用滑动窗口注意力。

sliding_window (`int`, *可选*，默认为 `32768`)：滑动窗口注意力机制的窗口大小。如果为 `None`，则不应用滑动窗口。

max_window_layers (`int`, *可选*，默认为 `28`) : 使用完整注意力的层数。前 `max_window_layers` 层将使用完整注意力，而在此之后的任何额外层都将使用 SWA（滑动窗口注意力）。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

position_id_per_seconds (`int`，*可选*，默认为 25)：每秒位置 ID 的增量。

seconds_per_chunk (`int`，*可选*，默认为 2)：音频和视频数据块的时长（以秒为单位）。

audio_start_token_id (`int`, *可选*, 默认为 151647) : 用于编码音频提示的音频起始标记索引。

audio_end_token_id (`int`, *可选*, 默认为 151648) : 用于编码音频提示的音频结束标记索引。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

spatial_merge_size (`int`, *可选*，默认为 `2`)：用于通过合并相邻 patch 来减少视觉 token 数量的空间合并窗口大小。

layer_types (`list[str]`，*可选*)：一个列表，用于显式地将每个层索引与其层类型进行映射。如果未提供，将根据配置值自动生成。

pad_token_id (`int`, *可选*) : 词表中用于填充的 Token id。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import Qwen2_5OmniTalkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig

>>> # Initializing a Qwen2_5OmniAudioEncoder config
>>> audio_config = Qwen2_5OmniAudioEncoderConfig()

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

>>> # Initializing a Qwen2_5Omni configuration
>>> configuration = Qwen2_5OmniThinkerConfig(audio_config, text_config)

>>> # Initializing a model from the qwen2-audio style configuration
>>> model = Qwen2_5OmniTalkerForConditionalGeneration(configuration)

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

## Qwen2_5OmniTalkerForConditionalGeneration[[transformers.Qwen2_5OmniTalkerForConditionalGeneration]]

#### transformers.Qwen2_5OmniTalkerForConditionalGeneration[[transformers.Qwen2_5OmniTalkerForConditionalGeneration]]

```python
transformers.Qwen2_5OmniTalkerForConditionalGeneration(config: Qwen2_5OmniTalkerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L2300)

#### forward[[transformers.Qwen2_5OmniTalkerForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, thinker_reply_part: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, input_text_ids: typing.Optional[torch.LongTensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, use_audio_in_video: bool | None = None, audio_feature_lengths: typing.Optional[torch.LongTensor] = None, video_second_per_grid: typing.Optional[torch.LongTensor] = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L2334)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

thinker_reply_part (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：来自 thinker 模型输出的隐藏状态，表示待处理的文本回复部分。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

input_text_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于纯文本内容的输入 token ID，在多模态上下文中用于位置计算。

image_grid_thw (`torch.LongTensor`，形状为 `(num_images, 3)`，*可选*)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`torch.LongTensor`，形状为 `(num_videos, 3)`，*可选*)：LLM 中每个视频的特征形状的时间、高度和宽度。

use_audio_in_video (`bool`, *可选*) : 是否使用视频中的音轨，应与 `process_audio_info` 中的参数保持一致。

audio_feature_lengths (`torch.LongTensor`，形状为 `(num_audios)`，*可选*)：LLM 中每个音频的特征形状长度。

video_second_per_grid (`torch.LongTensor`，形状为 `(num_videos)`，*可选*)：每个视频中每个网格对应的秒数，用于时间特征映射。

**返回：** `Qwen2_5OmniTalkerCausalLMOutputWithPast` 或 `tuple(torch.Tensor)`

`Qwen2_5OmniTalkerCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

[Qwen2_5OmniTalkerForConditionalGeneration](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniTalkerForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。
- **thinker_reply_part**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 来自 thinker 模型的隐藏状态，用作 talker 模型的输入。这些状态表示编码后的响应，talker 模型将使用它们来生成语音 token。

示例：

```python
>>> from transformers import AutoProcessor, Qwen2_5OmniTalkerForConditionalGeneration
>>> from transformers.audio_utils import load_audio

>>> model = Qwen2_5OmniTalkerForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B")

>>> prompt = "<|audio_bos|><|AUDIO|><|audio_eos|>Generate the caption in English:"
>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/audio/glass_breaking.mp3"
>>> audio = load_audio(url, sampling_rate=processor.feature_extractor.sampling_rate)

>>> inputs = processor(text=prompt, audio=audio, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=30)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Generate the caption in English: Glass is breaking."
```

## Qwen2_5OmniTalkerModel[[transformers.Qwen2_5OmniTalkerModel]]

#### transformers.Qwen2_5OmniTalkerModel[[transformers.Qwen2_5OmniTalkerModel]]

```python
transformers.Qwen2_5OmniTalkerModel(config: Qwen2_5OmniTalkerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L2185)

**参数：**

config ([Qwen2_5OmniTalkerConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniTalkerConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Qwen2 5 Omni 模型，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Qwen2_5OmniTalkerModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = 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.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L2212)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

**返回：** [BaseModelOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPast](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Qwen2_5OmniConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniConfig)）和输入。

[Qwen2_5OmniTalkerModel](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniTalkerModel) 的 forward 方法会重写 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

## Qwen2_5OmniToken2WavConfig[[transformers.Qwen2_5OmniToken2WavConfig]]

#### transformers.Qwen2_5OmniToken2WavConfig[[transformers.Qwen2_5OmniToken2WavConfig]]

```python
transformers.Qwen2_5OmniToken2WavConfig(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, dit_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, bigvgan_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py#L484)

**参数：**

dit_config (`DiT_Args`, *可选*) : 用于配置负责生成梅尔频谱图的 Diffusion Transformer (DiT) 模块的配置类。

bigvgan_config (`BigVGAN_Args`, *可选*) : 用于配置负责将梅尔频谱图转换为波形的 BigVGAN 模块的配置类。

这是用于存储 Qwen2 5 OmniModel 配置的类。它根据指定的参数实例化 Qwen2 5 Omni 模型，并定义模型架构。使用默认值实例化配置将得到与 [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import Qwen2_5OmniToken2WavModel, DiT_Args, BigVGAN_Args

>>> # Initialize DiT configuration
>>> dit_config = DiT_Args(
...     dim=1024,
...     depth=22,
...     heads=16,
...     ff_mult=2
... )

>>> # Initialize BigVGAN configuration
>>> bigvgan_config = BigVGAN_Args(
...     mel_dim=80,
...     upsample_rates=[5,3,2,2,2,2]
... )

>>> # Initialize main configuration
>>> config = Qwen2_5OmniToken2WavConfig(dit_config, bigvgan_config)

>>> # Initialize model with config
>>> model = Qwen2_5OmniToken2Wav(config)

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

## Qwen2_5OmniToken2WavModel[[transformers.Qwen2_5OmniToken2WavModel]]

#### transformers.Qwen2_5OmniToken2WavModel[[transformers.Qwen2_5OmniToken2WavModel]]

```python
transformers.Qwen2_5OmniToken2WavModel(config: Qwen2_5OmniToken2WavConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L3644)

**参数：**

config ([Qwen2_5OmniToken2WavConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniToken2WavConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

完整的 Qwen2.5Omni Token2Wav 模型。由一个 DiT 模型和一个 BigVGAN 声码器组成：DiT 模型以语音 token 作为输入并预测 mel 频谱图，BigVGAN 声码器以 mel 频谱图作为输入并预测波形。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Qwen2_5OmniToken2WavModel.forward]]

```python
forward(code, conditioning, reference_mel, num_steps = 10, guidance_scale = 0.5, sway_coefficient = -1.0, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L3673)

根据输入代码和条件参数生成波形。

## Qwen2_5OmniToken2WavDiTModel[[transformers.Qwen2_5OmniToken2WavDiTModel]]

#### transformers.Qwen2_5OmniToken2WavDiTModel[[transformers.Qwen2_5OmniToken2WavDiTModel]]

```python
transformers.Qwen2_5OmniToken2WavDiTModel(config: Qwen2_5OmniDiTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L3473)

**参数：**

config ([Qwen2_5OmniDiTConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniDiTConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

完整的 Qwen2.5Omni Token2WavDiT 模型。它以语音 token 作为输入，并预测 mel 频谱图。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

## Qwen2_5OmniToken2WavBigVGANModel[[transformers.Qwen2_5OmniToken2WavBigVGANModel]]

#### transformers.Qwen2_5OmniToken2WavBigVGANModel[[transformers.Qwen2_5OmniToken2WavBigVGANModel]]

```python
transformers.Qwen2_5OmniToken2WavBigVGANModel(config: Qwen2_5OmniBigVGANConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py#L3335)

**参数：**

config ([Qwen2_5OmniBigVGANConfig](/docs/transformers/v5.23.0/zh/model_doc/qwen2_5_omni#transformers.Qwen2_5OmniBigVGANConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

完整的 Qwen2.5Omni Token2WavBigVGAN 模型。它以梅尔频谱作为输入，并预测波形。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

