# Qwen3-Omni-MOE

## 概述

Qwen3-Omni-MOE 模型是阿里巴巴集团 Qwen 团队在 [Qwen3-Omni Technical Report](https://huggingface.co/papers/2509.17765) 中提出的一种统一多模态模型。

技术报告的摘要如下：

我们推出了 Qwen3-Omni，这是一个单一的多模态模型，首次在不损失性能的情况下，在文本、图像、音频和视频方面均保持了最先进的性能，与单模态对应模型相比没有任何退化。Qwen3-Omni 的性能与 Qwen 系列中相同规模的单模态模型相当，并在音频任务上表现尤为出色。在 36 个音频和视听基准测试中，Qwen3-Omni 在 32 个基准测试中取得了开源 SOTA，在 22 个基准测试中取得了整体 SOTA，超越了 Gemini-2.5-Pro、Seed-ASR 和 GPT-4o-Transcribe 等强大的闭源模型。Qwen3-Omni 采用了 Thinker-Talker MoE 架构，统一了文本、图像、音频和视频的感知与生成，从而产生流畅的文本和自然的实时语音。它支持 119 种语言的文本交互、19 种语言的语音理解以及 10 种语言的语音生成。为了降低流式合成中的首包延迟，Talker 使用多码本方案自回归地预测离散语音编解码器。利用这些码本的表示能力，我们用轻量级的因果 ConvNet 替代了计算密集型的分块扩散，从而能够从第一个编解码器帧开始进行流式处理。在冷启动设置下，Qwen3-Omni 实现了 234 ms 的理论端到端首包延迟。为了进一步增强多模态推理能力，我们引入了一个 Thinking 模型，该模型显式地对来自任何模态的输入进行推理。由于研究社区目前缺乏通用的音频字幕模型，我们对 Qwen3-Omni-30B-A3B 进行了微调，得到了 Qwen3-Omni-30B-A3B-Captioner，该模型可以为任意音频输入生成详细且低幻觉的字幕。Qwen3-Omni-30B-A3B、Qwen3-Omni-30B-A3B-Thinking 和 Qwen3-Omni-30B-A3B-Captioner 均在 Apache 2.0 许可证下公开发布。

## 备注

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

## 使用示例

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

### 单媒体推理

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

```python
import soundfile as sf

from transformers import Qwen3OmniMoeForConditionalGeneration, Qwen3OmniMoeProcessor

model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto"
)
processor = Qwen3OmniMoeProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

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 `Qwen3OmniMoeProcessor`
    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)
```

### 仅文本生成

如果只需生成文本输出，并且希望避免加载音频生成模型以节省计算资源，我们可以使用 `Qwen3OmniMoeThinkerForConditionalGeneration` 模型。

```python
from transformers import Qwen3OmniMoeProcessor, Qwen3OmniMoeThinkerForConditionalGeneration

model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
)
processor = Qwen3OmniMoeProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

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 `Qwen3OmniMoeProcessor`
    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)
```

### 批量混合媒体推理

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

```python
import soundfile as sf
from transformers import Qwen3OmniMoeForConditionalGeneration, Qwen3OmniMoeProcessor

model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto"
)
processor = Qwen3OmniMoeProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

# 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 `Qwen3OmniMoeProcessor`
    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)
```

### 批量音频生成

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

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

model_id = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
model = AutoModelForTextToWaveform.from_pretrained(model_id, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id)
sampling_rate = 24000  # output sampling rate
max_new_tokens = 128  # 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? Just let me know!",
    "The weather is nice today.",
]
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"qwen3_omni_output_{sample_id}.wav", audio.detach().to(torch.float32).cpu().numpy(), sampling_rate)
    print(f"Saved audio to qwen3_omni_output_{sample_id}.wav")
```

### 使用技巧

#### 图像分辨率权衡

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

```python
min_pixels = 128*28*28
max_pixels = 768*28*28
processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
```

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

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

```json
{
    "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 = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
    enable_audio_output=False,
)
```

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

```python
model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
    enable_audio_output=True,
)
...
text_ids = model.generate(**inputs, return_audio=False)
```

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

Qwen3-Omni-MOE 支持更改输出音频的音色。用户可以使用 `generate` 函数的 `speaker` 参数来指定音色类型。`"Qwen/Qwen3-Omni-30B-A3B-Instruct"` 检查点支持两种音色类型：`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 Qwen3OmniMoeForConditionalGeneration

model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
    attn_implementation="flash_attention_2",
)
```

## Qwen3OmniMoeConfig[[transformers.Qwen3OmniMoeConfig]]

#### transformers.Qwen3OmniMoeConfig[[transformers.Qwen3OmniMoeConfig]]

```python
transformers.Qwen3OmniMoeConfig(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, code2wav_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, enable_audio_output: bool = True, im_start_token_id: int = 151644, im_end_token_id: int = 151645, tts_pad_token_id: int = 151671, tts_bos_token_id: int = 151672, tts_eos_token_id: int = 151673, system_token_id: int = 8948, user_token_id: int = 872, assistant_token_id: int = 77091, initializer_range: float | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L530)

**参数：**

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

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

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

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

im_start_token_id (`int`, *可选*, 默认为 151644) : 图像起始位置的 Token id

im_end_token_id (`int`, *可选*, 默认为 151645) : 图像结束符的 Token id

tts_pad_token_id (`int`, *可选*, 默认为 151671) : TTS 中填充的 Token id

tts_bos_token_id (`int`, *可选*, 默认为 151672) : TTS 中序列起始的 Token id

tts_eos_token_id (`int`, *可选*，默认为 151673) : 图像 TTS 中序列结束符的 Token id

system_token_id (`int`, *可选*, 默认为 8948) : 系统提示词的 Token id

user_token_id (`int`, *可选*, 默认值为 872) : 用户提示词的 Token id

assistant_token_id (`int`，*可选*，默认值为 77091)：助手提示的 Token ID

initializer_range (`float`, *可选*) : 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

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

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

示例：

```python
>>> from transformers import (
...     Qwen3OmniMoeThinkerConfig,
...     Qwen3OmniMoeTalkerConfig,
...     Qwen3OmniMoeCode2WavConfig,
...     Qwen3OmniMoeForConditionalGeneration,
...     Qwen3OmniMoeConfig,
... )

>>> # Initializing a Qwen3OmniMoe style configuration
>>> configuration = Qwen3OmniMoeConfig()

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

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

#### get_text_config[[transformers.Qwen3OmniMoeConfig.get_text_config]]

```python
get_text_config(decoder = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L604)

**参数：**

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

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

## Qwen3OmniMoeThinkerConfig[[transformers.Qwen3OmniMoeThinkerConfig]]

#### transformers.Qwen3OmniMoeThinkerConfig[[transformers.Qwen3OmniMoeThinkerConfig]]

```python
transformers.Qwen3OmniMoeThinkerConfig(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, position_id_per_seconds: int = 25, audio_start_token_id: int = 151647, user_token_id: int = 872, initializer_range: float = 0.02, tie_word_embeddings: bool = False, audio_token_id: int = 151646, image_token_id: int = 151655, video_token_id: int = 151656)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L191)

**参数：**

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

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

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

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

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

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

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

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

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

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

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

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

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

示例：

```python
>>> from transformers import Qwen3OmniMoeThinkerModel, Qwen3OmniMoeThinkerConfig

>>> # Initializing a default Qwen3OmniMoeThinkerConfig
>>> configuration = Qwen3OmniMoeThinkerConfig()

>>> # Initializing a model (with random weights) from the default configuration
>>> model = Qwen3OmniMoeThinkerModel(configuration)

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

## Qwen3OmniMoeTalkerConfig[[transformers.Qwen3OmniMoeTalkerConfig]]

#### transformers.Qwen3OmniMoeTalkerConfig[[transformers.Qwen3OmniMoeTalkerConfig]]

```python
transformers.Qwen3OmniMoeTalkerConfig(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, code_predictor_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, num_code_groups: int = 32, thinker_hidden_size: int = 2048, codec_eos_token_id: int = 4198, accept_hidden_layer: int = 18, codec_nothink_id: int = 4203, codec_think_bos_id: int = 4204, codec_think_eos_id: int = 4205, codec_pad_id: int = 4196, codec_bos_id: int = 4197, audio_token_id: int = 151646, image_token_id: int = 151655, video_token_id: int = 151656, vision_start_token_id: int = 151652, position_id_per_seconds: int = 25, audio_start_token_id: int = 151669, speaker_id: dict | None = None, initializer_range: float = 0.02, tie_word_embeddings: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L395)

**参数：**

code_predictor_config (`dict`, *可选*) : 用于初始化 [Qwen3OmniMoeTalkerCodePredictorConfig](/docs/transformers/v5.25.0/zh/model_doc/qwen3_omni_moe#transformers.Qwen3OmniMoeTalkerCodePredictorConfig) 的配置参数字典。如果未提供，则使用默认值。

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

num_code_groups (`int`，*可选*，默认为 32)：预测声学 token 序列中使用的码本组数，对应多码本 VQ 表示。

thinker_hidden_size (`int`，*可选*，默认为 2048)：用于在音频生成前进行中间推理或潜在规划的 thinker 模块的隐藏维度大小。

codec_eos_token_id (`int`, *可选*，默认为 4198)：表示编解码器生成序列中语音结束标记的 Token ID。

accept_hidden_layer (`int`, *可选*，默认为 18)：在 think-and-speak 过程中，用于接受或细化生成 token 的隐藏层输出的索引。

codec_nothink_id (`int`，*可选*，默认值为 4203)：表示在生成过程中无需进行思考步骤的 Token ID。

codec_think_bos_id (`int`, *可选*, 默认值为 4204)：标记思考序列起始位置的 Token ID。

codec_think_eos_id (`int`, *可选*, 默认值为 4205)：标记思考序列结束的 Token ID。

codec_pad_id (`int`，*可选*，默认为 4196)：用于编解码器输入序列的填充标记 ID。

codec_bos_id (`int`, *可选*，默认为 4197)：编解码序列中的语音起始标记 ID。

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

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

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

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

position_id_per_seconds (`int`, *可选*，默认为 25)：为每秒音频内容分配的位置 ID 数量，用于生成过程中的时间对齐。

audio_start_token_id (`int`，*可选*，默认为 151669)：指示输出中音频生成片段起始位置的 Token ID。

speaker_id (`dict`, *可选*) : 说话人姓名到说话人 ID 的字典。

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

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

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

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

示例：

```python
>>> from transformers import Qwen3OmniMoeTalkerConfig, Qwen3OmniMoeTalker

>>> # Initialize a Qwen3OmniMoeTalkerConfig with default sub-configurations
>>> config = Qwen3OmniMoeTalkerConfig(
...     num_code_groups=32,
...     thinker_hidden_size=2048,
... )

>>> # Initialize the full Qwen3-Omni Talker model
>>> model = Qwen3OmniMoeTalker(config)

>>> # Access the model configuration
>>> config = model.config
>>> print(config.text_config)  # Access text decoder configuration
>>> print(config.code_predictor_config)  # Access code predictor configuration
```

## Qwen3OmniMoeTextConfig[[transformers.Qwen3OmniMoeTextConfig]]

#### transformers.Qwen3OmniMoeTextConfig[[transformers.Qwen3OmniMoeTextConfig]]

```python
transformers.Qwen3OmniMoeTextConfig(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 = 3584, hidden_size: int = 2048, 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, 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, attention_bias: bool = False, sliding_window: int | None = None, attention_dropout: float | int = 0.0, decoder_sparse_step: int = 1, moe_intermediate_size: int = 768, num_experts_per_tok: int = 8, num_experts: int = 128, norm_topk_prob: bool = True, output_router_logits: bool = False, router_aux_loss_coef: float = 0.001, mlp_only_layers: list[int] | None = None, pad_token_id: int | None = None, bos_token_id: int | None = None, eos_token_id: int | list[int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L109)

**参数：**

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

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

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，则可选地包含用于缩放的参数。

attention_bias (`bool`，*可选*，默认为 `False`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

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

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

decoder_sparse_step (`int`，*可选*，默认为 1)：MoE 层的频率。

moe_intermediate_size (`int`，*可选*，默认为 `768`)：路由专家 MLP 的中间层大小。

num_experts_per_tok (`int`，*可选*，默认为 `8`)：每个 token 路由到的专家数量。这是 token 选择路由的 top-k 值。

num_experts (`int`，*可选*，默认为 `128`)：MoE 层中路由专家的数量。

norm_topk_prob (`bool`, *可选*, 默认为 `True`) : 是否对路由专家的权重进行归一化。

output_router_logits (`bool`，*可选*，默认为 `False`)：是否由模型返回路由器 logits。启用此选项后，模型还将输出辅助损失，包括负载均衡损失和路由器 z-loss。

router_aux_loss_coef (`float`, *可选*，默认为 `0.001`)：辅助负载均衡损失系数。用于惩罚 MoE 模型中专家路由的不均衡。

mlp_only_layers (`list[int]`，*可选*，默认为 `[]`)：指示哪些层使用 Qwen3OmniMoeTextMLP 而非 Qwen3OmniMoeTextSparseMoeBlock。该列表包含层索引，如果共有 num_layers 层，则索引范围为 0 到 num_layers-1。如果 `mlp_only_layers` 为空，则使用 `decoder_sparse_step` 来确定稀疏性。

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

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

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

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

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

```python
>>> from transformers import Qwen3OmniMoeTextModel, Qwen3OmniMoeTextConfig

>>> # Initializing a Qwen3OmniMoeText style configuration
>>> configuration = Qwen3OmniMoeTextConfig()

>>> # Initializing a model from the Qwen3-15B-A2B" style configuration
>>> model = Qwen3OmniMoeTextModel(configuration)

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

## Qwen3OmniMoeVisionEncoderConfig[[transformers.Qwen3OmniMoeVisionEncoderConfig]]

#### transformers.Qwen3OmniMoeVisionEncoderConfig[[transformers.Qwen3OmniMoeVisionEncoderConfig]]

```python
transformers.Qwen3OmniMoeVisionEncoderConfig(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 = 27, hidden_size: int = 1152, hidden_act: str = 'gelu_pytorch_tanh', intermediate_size: int = 4304, num_heads: int = 16, in_channels: int = 3, patch_size: int | list[int] | tuple[int, int] = 16, spatial_merge_size: int = 2, temporal_patch_size: int | list[int] | tuple[int, int] = 2, out_hidden_size: int = 3584, num_position_embeddings: int = 2304, deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24), initializer_range: float = 0.02, rope_parameters: dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L76)

**参数：**

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

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

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

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

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

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

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

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

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

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

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

deepstack_visual_indexes (`list[int]`，*可选*，默认为 `[8, 16, 24]`)：用于深度堆叠嵌入的层索引。

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

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

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

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

## Qwen3OmniMoeAudioEncoderConfig[[transformers.Qwen3OmniMoeAudioEncoderConfig]]

#### transformers.Qwen3OmniMoeAudioEncoderConfig[[transformers.Qwen3OmniMoeAudioEncoderConfig]]

```python
transformers.Qwen3OmniMoeAudioEncoderConfig(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 = 50, output_dim: int = 3584, n_window_infer: int = 800, conv_chunksize: int = 500, downsample_hidden_size: int = 480)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L30)

**参数：**

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)：输入的最大序列长度

n_window (`int`，*可选*，默认为 50)：窗口数量

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

n_window_infer (`int`，*可选*，默认为 `800`)：推理期间的窗口数量

conv_chunksize (`int`，*可选*，默认为 `500`)：卷积层每个输入的块大小

downsample_hidden_size (`int`，*可选*，默认为 `480`)：下采样层的隐藏层大小

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

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

## Qwen3OmniMoeTalkerTextConfig[[transformers.Qwen3OmniMoeTalkerTextConfig]]

#### transformers.Qwen3OmniMoeTalkerTextConfig[[transformers.Qwen3OmniMoeTalkerTextConfig]]

```python
transformers.Qwen3OmniMoeTalkerTextConfig(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 = 3072, hidden_size: int = 1024, intermediate_size: int = 2048, num_hidden_layers: int = 20, num_attention_heads: int = 16, num_key_value_heads: int = 2, hidden_act: str = 'silu', max_position_embeddings: int = 32768, initializer_range: float = 0.02, rms_norm_eps: float = 1e-06, use_cache: bool = True, tie_word_embeddings: bool = False, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, sliding_window: int | None = None, attention_dropout: float | int = 0.0, decoder_sparse_step: int = 1, moe_intermediate_size: int = 384, num_experts_per_tok: int = 8, num_experts: int = 128, norm_topk_prob: bool = False, output_router_logits: bool = False, router_aux_loss_coef: float = 0.001, mlp_only_layers: list[int] | None = None, pad_token_id: int | None = None, bos_token_id: int | None = None, eos_token_id: int | list[int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L307)

**参数：**

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

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

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

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

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

num_key_value_heads (`int`, *可选*，默认为 `2`) : 这是用于实现 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` 或模型为仅解码器生成模型时相关。

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

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

attention_bias (`bool`，*可选*，默认为 `False`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

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

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

decoder_sparse_step (`int`，*可选*，默认为 1)：MoE 层的频率。

moe_intermediate_size (`int`，*可选*，默认为 `384`)：路由专家 MLP 的中间层大小。

num_experts_per_tok (`int`，*可选*，默认为 `8`)：每个 token 路由到的专家数量。这是 token 选择路由的 top-k 值。

num_experts (`int`，*可选*，默认为 `128`)：MoE 层中路由专家的数量。

norm_topk_prob (`bool`，*可选*，默认为 `False`)：是否对路由专家的权重进行归一化。

output_router_logits (`bool`，*可选*，默认为 `False`)：是否由模型返回路由器 logits。启用此选项后，模型还将输出辅助损失，包括负载均衡损失和路由器 z-loss。

router_aux_loss_coef (`float`, *可选*，默认为 `0.001`)：辅助负载均衡损失系数。用于惩罚 MoE 模型中专家路由的不均衡。

mlp_only_layers (`list[int]`，*可选*，默认为 `[]`)：指示哪些层使用 Qwen3OmniMoeTalkerTextMLP 而非 Qwen3OmniMoeTalkerTextSparseMoeBlock。该列表包含层索引，如果共有 num_layers 层，则索引范围为 0 到 num_layers-1。如果 `mlp_only_layers` 为空，则使用 `decoder_sparse_step` 来确定稀疏性。

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

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

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

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

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

```python
>>> from transformers import Qwen3OmniMoeTalkerTextModel, Qwen3OmniMoeTalkerTextConfig

>>> # Initializing a Qwen3OmniMoeTalkerText style configuration
>>> configuration = Qwen3OmniMoeTalkerTextConfig()

>>> # Initializing a model from the Qwen3-15B-A2B" style configuration
>>> model = Qwen3OmniMoeTalkerTextModel(configuration)

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

## Qwen3OmniMoeTalkerCodePredictorConfig[[transformers.Qwen3OmniMoeTalkerCodePredictorConfig]]

#### transformers.Qwen3OmniMoeTalkerCodePredictorConfig[[transformers.Qwen3OmniMoeTalkerCodePredictorConfig]]

```python
transformers.Qwen3OmniMoeTalkerCodePredictorConfig(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 = 2048, hidden_size: int = 1024, intermediate_size: int = 3072, num_hidden_layers: int = 5, num_attention_heads: int = 16, num_key_value_heads: int = 8, head_dim: int = 128, hidden_act: str = 'silu', max_position_embeddings: int = 32768, initializer_range: float = 0.02, rms_norm_eps: float = 1e-06, use_cache: bool = True, tie_word_embeddings: bool = False, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, sliding_window: int | None = None, 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, num_code_groups: int = 32)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py#L240)

**参数：**

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

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

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

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

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

num_key_value_heads (`int`, *可选*，默认为 `8`) : 这是用于实现 Grouped Query Attention 的 key_value 头数量。如果 `num_key_value_heads=num_attention_heads`，模型将使用 Multi Head Attention (MHA)；如果 `num_key_value_heads=1`，模型将使用 Multi Query Attention (MQA)；否则将使用 GQA。在将多头检查点转换为 GQA 检查点时，每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 [这篇论文](https://huggingface.co/papers/2305.13245)。如果未指定，则默认为 `num_attention_heads`。

head_dim (`int`，*可选*，默认为 `128`)：注意力头维度。如果为 None，则默认为 hidden_size // 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` 或模型为仅解码器生成模型时相关。

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

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

attention_bias (`bool`，*可选*，默认为 `False`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

sliding_window (`int`, *可选*) : 滑动窗口注意力机制的窗口大小。如果为 `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。

num_code_groups (`int`，*可选*，默认为 32)：预测声学 token 序列中使用的码本组数，对应多码本 VQ 表示。

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

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

## Qwen3OmniMoeForConditionalGeneration[[transformers.Qwen3OmniMoeForConditionalGeneration]]

#### transformers.Qwen3OmniMoeForConditionalGeneration[[transformers.Qwen3OmniMoeForConditionalGeneration]]

```python
transformers.Qwen3OmniMoeForConditionalGeneration(config: Qwen3OmniMoeConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L3959)

## Qwen3OmniMoeThinkerTextModel[[transformers.Qwen3OmniMoeThinkerTextModel]]

#### transformers.Qwen3OmniMoeThinkerTextModel[[transformers.Qwen3OmniMoeThinkerTextModel]]

```python
transformers.Qwen3OmniMoeThinkerTextModel(config: Qwen3OmniMoeTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L1622)

**参数：**

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

Qwen3OmniMoeThinker 的文本部分，并非纯文本模型，因为 DeepStack 会将视觉特征整合到早期的隐藏状态中。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.25.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.Qwen3OmniMoeThinkerTextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, visual_pos_masks: typing.Optional[torch.Tensor] = None, deepstack_visual_embeds: list[torch.Tensor] | None = None, **kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L1647)

**参数：**

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

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `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`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

visual_pos_masks (`torch.Tensor`，形状为 `(batch_size, seqlen)`，*可选*)：视觉位置的掩码。

deepstack_visual_embeds (`list[torch.Tensor]`, *可选*) : 深度堆叠视觉嵌入。形状为 (num_layers, visual_seqlen, embed_dim)。该特征从不同的视觉编码器层中提取，并输入到解码器隐藏状态中。它来自论文 DeepStack(https://arxiv.org/abs/2406.04334)。

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

`MoeModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，当传入 `output_router_probs=True` 且 `config.add_router_probs=True`，或当 `config.output_router_probs=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits（softmax 之后），这些术语用于计算混合专家模型的辅助损失。

## Qwen3OmniMoeThinkerModel[[transformers.Qwen3OmniMoeThinkerModel]]

#### transformers.Qwen3OmniMoeThinkerModel[[transformers.Qwen3OmniMoeThinkerModel]]

```python
transformers.Qwen3OmniMoeThinkerModel(config: Qwen3OmniMoeThinkerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L1752)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/v5.25.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.Qwen3OmniMoeThinkerModel.forward]]

```python
forward(input_ids = None, input_features = None, pixel_values = None, pixel_values_videos = None, image_grid_thw = None, video_grid_thw = None, attention_mask = None, feature_attention_mask = None, audio_feature_lengths = None, position_ids = None, cache = None, inputs_embeds = None, use_cache = None, output_router_logits: bool | None = None, use_audio_in_video = None, video_second_per_grid = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L1936)

**参数：**

input_ids (`` of shape `(batch_size, sequence_length)`) : 输入序列标记在词汇表中的索引。默认情况下，填充将被忽略。 可以使用 [AutoTokenizer](/docs/transformers/v5.25.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是输入 ID？](../glossary#input-ids)

input_features (`` of shape `(batch_size, sequence_length, feature_dim)`) : The tensors corresponding to the input audio features. Audio features can be obtained using `feature_extractor_class`. See `feature_extractor_class.__call__` for details (`processor_class` uses `feature_extractor_class` for processing audios).

pixel_values (`` of shape `(batch_size, num_channels, image_size, image_size)`) : The tensors corresponding to the input images. Pixel values can be obtained using `image_processor_class`. See `image_processor_class.__call__` for details (`processor_class` uses `image_processor_class` for processing images).

pixel_values_videos (`` of shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`) : The tensors corresponding to the input video. Pixel values for videos can be obtained using `video_processor_class`. See `video_processor_class.__call__` for details (`processor_class` uses `video_processor_class` for processing videos).

image_grid_thw (`` of shape `(num_images, 3)`)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`` of shape `(num_videos, 3)`)：LLM 中每个视频的特征形状的时间、高度和宽度。

attention_mask (`` of shape `(batch_size, sequence_length)`) : Mask to avoid performing attention on padding token indices. Mask values selected in `[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 (`` of shape `(batch_size, sequence_length)`) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (``) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`` of shape `(batch_size, sequence_length, hidden_size)`) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

use_cache (``) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

output_router_logits (`bool`, *可选*) : 是否返回所有路由器的 logits。它们对于计算路由器损失很有用，在推理期间不应返回。

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)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

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

`MultimodalMoeBaseModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.FloatTensor`）-- 语言模型主干最后一层输出的隐藏状态序列。如果使用 `cache`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列最后一个隐藏状态。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。其中包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。语言模型主干的注意力权重，位于注意力 softmax 之后。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 或 `config.output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个稀疏层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。由 MoE 路由器计算的原始路由 logits。可用于计算负载均衡损失，或检查 token 如何被分发到各个专家。
- **image_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 图像编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何图像，则为 `None`。
- **video_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 视频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何视频，则为 `None`。
- **audio_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 音频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理音频，则为 `None`。

## Qwen3OmniMoeThinkerForConditionalGeneration[[transformers.Qwen3OmniMoeThinkerForConditionalGeneration]]

#### transformers.Qwen3OmniMoeThinkerForConditionalGeneration[[transformers.Qwen3OmniMoeThinkerForConditionalGeneration]]

```python
transformers.Qwen3OmniMoeThinkerForConditionalGeneration(config: Qwen3OmniMoeThinkerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2157)

#### forward[[transformers.Qwen3OmniMoeThinkerForConditionalGeneration.forward]]

```python
forward(input_ids = None, input_features = None, pixel_values = None, pixel_values_videos = None, image_grid_thw = None, video_grid_thw = None, attention_mask = None, feature_attention_mask = None, audio_feature_lengths = None, position_ids = None, cache = None, inputs_embeds = None, labels = None, use_cache = None, output_router_logits: bool | None = None, use_audio_in_video = None, video_second_per_grid = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2220)

**参数：**

input_ids (`` of shape `(batch_size, sequence_length)`) : 输入序列标记在词汇表中的索引。默认情况下，填充将被忽略。 可以使用 [AutoTokenizer](/docs/transformers/v5.25.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是输入 ID？](../glossary#input-ids)

input_features (`` of shape `(batch_size, sequence_length, feature_dim)`) : The tensors corresponding to the input audio features. Audio features can be obtained using `feature_extractor_class`. See `feature_extractor_class.__call__` for details (`processor_class` uses `feature_extractor_class` for processing audios).

pixel_values (`` of shape `(batch_size, num_channels, image_size, image_size)`) : The tensors corresponding to the input images. Pixel values can be obtained using `image_processor_class`. See `image_processor_class.__call__` for details (`processor_class` uses `image_processor_class` for processing images).

pixel_values_videos (`` of shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`) : The tensors corresponding to the input video. Pixel values for videos can be obtained using `video_processor_class`. See `video_processor_class.__call__` for details (`processor_class` uses `video_processor_class` for processing videos).

image_grid_thw (`` of shape `(num_images, 3)`)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`` of shape `(num_videos, 3)`)：LLM 中每个视频的特征形状的时间、高度和宽度。

attention_mask (`` of shape `(batch_size, sequence_length)`) : Mask to avoid performing attention on padding token indices. Mask values selected in `[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 (`` of shape `(batch_size, sequence_length)`) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (``) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`` of shape `(batch_size, sequence_length, hidden_size)`) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

labels (`` of shape `(batch_size, sequence_length)`) : Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

use_cache (``) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

output_router_logits (`bool`, *可选*) : 是否返回所有路由器的 logits。它们对于计算路由器损失很有用，在推理期间不应返回。

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)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

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

`MultimodalMoeCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

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

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

- **loss** (`torch.FloatTensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **aux_loss** (`torch.Tensor`，*可选*，当传入 `output_router_logits=True` 或 `config.output_router_logits=True`，且模型使用负载均衡损失训练其路由器时返回) -- 稀疏模块的负载均衡辅助损失。使用路由器偏差来平衡其专家的模型（DeepSeek-V3 及由其衍生的架构）在此处返回 `None`，但仍会返回 `router_logits`。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.FloatTensor`）—— 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。其中包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。语言模型主干的注意力权重，位于注意力 softmax 之后。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 或 `config.output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个稀疏层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。由 MoE 路由器计算的原始路由 logits。可用于计算负载均衡损失，或检查 token 如何被分发到各个专家。
- **image_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 图像编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何图像，则为 `None`。
- **video_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 视频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何视频，则为 `None`。
- **audio_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 音频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理音频，则为 `None`。

示例：

```python
>>> from transformers import Qwen3OmniMoeProcessor, Qwen3OmniMoeThinkerForConditionalGeneration

>>> thinker = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-Omni-7B")
>>> processor = Qwen3OmniMoeProcessor.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.Qwen3OmniMoeThinkerForConditionalGeneration.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.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2202)

**参数：**

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

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

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

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

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

- **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, Qwen3OmniMoeThinkerForConditionalGeneration

>>> model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

>>> 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.Qwen3OmniMoeThinkerForConditionalGeneration.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.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2189)

**参数：**

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

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

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

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

- **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 后的注意力权重，用于在自注意力头中计算加权平均值。
- **deepstack_features** (`List[torch.Tensor]`, *可选*) -- 来自 deepstack 层的隐藏状态（特征图）列表。

示例：

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

>>> model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

>>> 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.Qwen3OmniMoeThinkerForConditionalGeneration.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.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2176)

**参数：**

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

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

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

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

- **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 后的注意力权重，用于在自注意力头中计算加权平均值。
- **deepstack_features** (`List[torch.Tensor]`, *可选*) -- 来自 deepstack 层的隐藏状态（特征图）列表。

示例：

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

>>> model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

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

## Qwen3OmniMoeTalkerForConditionalGeneration[[transformers.Qwen3OmniMoeTalkerForConditionalGeneration]]

#### transformers.Qwen3OmniMoeTalkerForConditionalGeneration[[transformers.Qwen3OmniMoeTalkerForConditionalGeneration]]

```python
transformers.Qwen3OmniMoeTalkerForConditionalGeneration(config: Qwen3OmniMoeTalkerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L3089)

**参数：**

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

用于基于其他模态（例如图像-文本到文本生成）进行 token 生成的 Qwen3 Omni Moe 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.25.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.Qwen3OmniMoeTalkerForConditionalGeneration.forward]]

```python
forward(input_ids = None, attention_mask = None, use_audio_in_video = None, audio_feature_lengths = None, video_second_per_grid = None, image_grid_thw = None, video_grid_thw = None, position_ids = None, cache = None, inputs_embeds = None, labels = None, use_cache = None, output_router_logits = None, residual_codes = None, trailing_text_hidden = None, tts_pad_embed = None, generation_step = None, talker_input_ids = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L3121)

**参数：**

input_ids (`` of shape `(batch_size, sequence_length)`) : 输入序列标记在词汇表中的索引。默认情况下，填充将被忽略。 可以使用 [AutoTokenizer](/docs/transformers/v5.25.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是输入 ID？](../glossary#input-ids)

attention_mask (`` of shape `(batch_size, sequence_length)`) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`：  - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。  [什么是注意力掩码？](../glossary#attention-mask)

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

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

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

image_grid_thw (`` of shape `(num_images, 3)`)：LLM 中每张图片特征形状的时间、高度和宽度。

video_grid_thw (`` of shape `(num_videos, 3)`)：LLM 中每个视频的特征形状的时间、高度和宽度。

position_ids (`` of shape `(batch_size, sequence_length)`) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (``) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`` of shape `(batch_size, sequence_length, hidden_size)`) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

labels (`` of shape `(batch_size, sequence_length)`) : Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

use_cache (``) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

output_router_logits (``) : 是否返回所有路由器的 logits。它们对于计算路由器损失很有用，在推理期间不应返回。

residual_codes (`torch.Tensor`) : 上一步预测的残差码。

trailing_text_hidden (`torch.Tensor`) : 第一个 token 之后，thinker 输出的文本隐藏状态。

tts_pad_embed (`torch.Tensor`) : `tts_pad_token_id` 的嵌入张量。

generation_step (`int`) : 自预填充（prefill）以来的生成步数，用于与 `trailing_text_hidden` 同步。

talker_input_ids (`torch.Tensor`) : 来自 thinker 的输入 ids，用于计算 3d RoPE。

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

`MoeCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

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

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **aux_loss** (`torch.Tensor`，*可选*，当传入 `output_router_logits=True` 或 `config.output_router_logits=True`，且模型使用负载均衡损失训练其路由器时返回) -- 稀疏模块的负载均衡辅助损失。使用路由器偏差来平衡其专家的模型（DeepSeek-V3 及由其衍生的架构）在此处返回 `None`，但仍会返回 `router_logits`。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 或 `config.output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个稀疏层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits。可用于计算负载均衡损失，或检查 token 如何被分发到各个专家。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

## Qwen3OmniMoePreTrainedModel[[transformers.Qwen3OmniMoePreTrainedModel]]

#### transformers.Qwen3OmniMoePreTrainedModel[[transformers.Qwen3OmniMoePreTrainedModel]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L116)

**参数：**

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

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

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

## Qwen3OmniMoePreTrainedModelForConditionalGeneration[[transformers.Qwen3OmniMoePreTrainedModelForConditionalGeneration]]

#### transformers.Qwen3OmniMoePreTrainedModelForConditionalGeneration[[transformers.Qwen3OmniMoePreTrainedModelForConditionalGeneration]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L160)

#### get_chunked_index[[transformers.Qwen3OmniMoePreTrainedModelForConditionalGeneration.get_chunked_index]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L183)

**参数：**

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.Qwen3OmniMoePreTrainedModelForConditionalGeneration.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.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L220)

**参数：**

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。

## Qwen3OmniMoeTalkerModel[[transformers.Qwen3OmniMoeTalkerModel]]

#### transformers.Qwen3OmniMoeTalkerModel[[transformers.Qwen3OmniMoeTalkerModel]]

```python
transformers.Qwen3OmniMoeTalkerModel(config: Qwen3OmniMoeTalkerTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2960)

**参数：**

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

Qwen3OmniMoe 的文本部分，并非纯文本模型，因为 DeepStack 会将视觉特征整合到早期的隐藏状态中。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.25.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.Qwen3OmniMoeTalkerModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, visual_pos_masks: typing.Optional[torch.Tensor] = None, deepstack_visual_embeds: list[torch.Tensor] | None = None, **kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2985)

**参数：**

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

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `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`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

visual_pos_masks (`torch.Tensor`，形状为 `(batch_size, seqlen)`，*可选*)：视觉位置的掩码。

deepstack_visual_embeds (`list[torch.Tensor]`, *可选*) : 深度堆叠视觉嵌入。形状为 (num_layers, visual_seqlen, embed_dim)。该特征从不同的视觉编码器层中提取，并输入到解码器隐藏状态中。它来自论文 DeepStack(https://arxiv.org/abs/2406.04334)。

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

`MoeModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，当传入 `output_router_probs=True` 且 `config.add_router_probs=True`，或当 `config.output_router_probs=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits（softmax 之后），这些术语用于计算混合专家模型的辅助损失。

## Qwen3OmniMoeThinkerTextPreTrainedModel[[transformers.Qwen3OmniMoeThinkerTextPreTrainedModel]]

#### transformers.Qwen3OmniMoeThinkerTextPreTrainedModel[[transformers.Qwen3OmniMoeThinkerTextPreTrainedModel]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L1568)

**参数：**

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

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

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

## Qwen3OmniMoeProcessor[[transformers.Qwen3OmniMoeProcessor]]

#### transformers.Qwen3OmniMoeProcessor[[transformers.Qwen3OmniMoeProcessor]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py#L128)

**参数：**

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

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

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

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

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

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

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

#### __调用__[[transformers.Qwen3OmniMoeProcessor.__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'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.qwen3_omni_moe.processing_qwen3_omni_moe.Qwen3OmniMoeProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py#L164)

**参数：**

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, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[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`) : 已弃用，请改用 `Qwen3OmniMoeProcessorKwargs.load_audio_from_video`。在处理视频时是否纳入音频信息。启用后，音频 token 将根据时间对齐与视频 token 交错排列，从而构建统一的多模态表示。

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

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

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

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`，*可选*，默认值为 `13.0`)：每秒视频分配的位置 ID 数量。此参数控制位置嵌入的时间分辨率，并在 `load_audio_from_video=True` 时用于对齐视频标记与音频标记。

n_window (`int`, *kwargs*, *可选*，默认为 `50`)：音频编码器的窗口大小。此值应与模型配置中的 `n_window` 相匹配。

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

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.25.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`，也不应转换为张量的键的列表或集合。

## Qwen3OmniMoeCode2Wav[[transformers.Qwen3OmniMoeCode2Wav]]

#### transformers.Qwen3OmniMoeCode2Wav[[transformers.Qwen3OmniMoeCode2Wav]]

```python
transformers.Qwen3OmniMoeCode2Wav(config: Qwen3OmniMoeCode2WavConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L3895)

## Qwen3OmniMoeCode2WavDecoderBlock[[transformers.Qwen3OmniMoeCode2WavDecoderBlock]]

#### transformers.Qwen3OmniMoeCode2WavDecoderBlock[[transformers.Qwen3OmniMoeCode2WavDecoderBlock]]

```python
transformers.Qwen3OmniMoeCode2WavDecoderBlock(config: Qwen3OmniMoeCode2WavConfig, layer_idx)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L3868)

## Qwen3OmniMoeCode2WavTransformerModel[[transformers.Qwen3OmniMoeCode2WavTransformerModel]]

#### transformers.Qwen3OmniMoeCode2WavTransformerModel[[transformers.Qwen3OmniMoeCode2WavTransformerModel]]

```python
transformers.Qwen3OmniMoeCode2WavTransformerModel(config: Qwen3OmniMoeCode2WavConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L3709)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/v5.25.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.Qwen3OmniMoeCode2WavTransformerModel.forward]]

```python
forward(input_ids = None, attention_mask = None, position_ids = None, cache = None, inputs_embeds = None, use_cache = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L3730)

**参数：**

input_ids (`` of shape `(batch_size, sequence_length)`) : 输入序列标记在词汇表中的索引。默认情况下，填充将被忽略。 可以使用 [AutoTokenizer](/docs/transformers/v5.25.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是输入 ID？](../glossary#input-ids)

attention_mask (`` of shape `(batch_size, sequence_length)`) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`：  - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。  [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`` of shape `(batch_size, sequence_length)`) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (``) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`` of shape `(batch_size, sequence_length, hidden_size)`) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

use_cache (``) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

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

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

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

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

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

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

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

## Qwen3OmniMoeTalkerCodePredictorModel[[transformers.Qwen3OmniMoeTalkerCodePredictorModel]]

#### transformers.Qwen3OmniMoeTalkerCodePredictorModel[[transformers.Qwen3OmniMoeTalkerCodePredictorModel]]

```python
transformers.Qwen3OmniMoeTalkerCodePredictorModel(config: Qwen3OmniMoeTalkerCodePredictorConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2613)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/v5.25.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.Qwen3OmniMoeTalkerCodePredictorModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2642)

**参数：**

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

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `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`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

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

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

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

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

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

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

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

## Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration[[transformers.Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration]]

#### transformers.Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration[[transformers.Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration]]

```python
transformers.Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration(config: Qwen3OmniMoeTalkerCodePredictorConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2703)

**参数：**

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

用于基于其他模态（例如图像-文本到文本生成）进行 token 生成的 Qwen3 Omni Moe 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.25.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.Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration.forward]]

```python
forward(input_ids = None, attention_mask = None, position_ids = None, cache = None, inputs_embeds = None, labels = None, use_cache = None, generation_steps = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py#L2726)

**参数：**

input_ids (`` of shape `(batch_size, sequence_length)`) : 输入序列标记在词汇表中的索引。默认情况下，填充将被忽略。 可以使用 [AutoTokenizer](/docs/transformers/v5.25.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.25.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是输入 ID？](../glossary#input-ids)

attention_mask (`` of shape `(batch_size, sequence_length)`) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`：  - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。  [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`` of shape `(batch_size, sequence_length)`) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.  [What are position IDs?](../glossary#position-ids)

cache (``) : Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/v5.25.0/zh/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`` of shape `(batch_size, sequence_length, hidden_size)`) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

labels (`` of shape `(batch_size, sequence_length)`) : Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

use_cache (``) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

generation_steps (`int`) : 代码预测器的生成步骤，0..num_code_groups-1

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

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

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

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

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

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

