Transformers documentation

Qwen3-Omni-MOE

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

and get access to the augmented documentation experience

to get started

该模型于 2025-09-22 在 HF papers 上发布,并于 2025-09-21 贡献至 Hugging Face Transformers。

Qwen3-Omni-MOE

FlashAttention SDPA

概述

Qwen3-Omni-MOE 模型是阿里巴巴集团 Qwen 团队在 Qwen3-Omni Technical Report 中提出的一种统一多模态模型。

技术报告的摘要如下:

我们推出了 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 许可证下公开发布。

备注

使用示例

Qwen3-Omni 可在 Huggingface Hub 上找到。

单媒体推理

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

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 模型。

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 模型时,模型可以批量处理由文本、图像、音频和视频等多种类型样本混合组成的输入。以下是一个示例。

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 支持批量音频输出生成。例如,以下示例展示了文本转语音的批量生成。当批次包含多个样本时,生成的音频将以列表形式返回,每个样本对应一个波形,且每个波形已根据其自身长度进行裁剪,因此较短的样本不会被填充多余的音频。对于单样本调用,则仍返回单个张量。

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

使用技巧

图像分辨率权衡

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

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 团队开发的虚拟人,能够感知听觉和视觉输入,并生成文本和语音。”,否则音频输出可能无法按预期工作。

{
    "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。

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 时,模型将仅返回文本输出,从而更快地获取文本响应。

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。

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

使用 Flash-Attention 2 加速生成

首先,请确保安装最新版本的 Flash Attention 2:

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

此外,您的硬件必须与 FlashAttention 2 兼容。有关详细信息,请参阅 flash attention 仓库 的官方文档。只有当模型以 torch.float16 或 torch.bfloat16 加载时,才能使用 FlashAttention-2。

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

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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonethinker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetalker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonecode2wav_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneenable_audio_output: bool = Trueim_start_token_id: int = 151644im_end_token_id: int = 151645tts_pad_token_id: int = 151671tts_bos_token_id: int = 151672tts_eos_token_id: int = 151673system_token_id: int = 8948user_token_id: int = 872assistant_token_id: int = 77091initializer_range: float | None = None )

参数

  • 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

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

< >

( decoder = False )

参数

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

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

Qwen3OmniMoeThinkerConfig

类 transformers.Qwen3OmniMoeThinkerConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneposition_id_per_seconds: int = 25audio_start_token_id: int = 151647user_token_id: int = 872initializer_range: float = 0.02tie_word_embeddings: bool = Falseaudio_token_id: int = 151646image_token_id: int = 151655video_token_id: int = 151656 )

参数

  • 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) — 用于编码音频提示的音频起始 token 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) — 用作输入图像占位符的图像 token 索引。
  • video_token_id (int,可选,默认为 151656) — 用作输入视频占位符的视频 token 索引。

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

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> 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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonecode_predictor_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonenum_code_groups: int = 32thinker_hidden_size: int = 2048codec_eos_token_id: int = 4198accept_hidden_layer: int = 18codec_nothink_id: int = 4203codec_think_bos_id: int = 4204codec_think_eos_id: int = 4205codec_pad_id: int = 4196codec_bos_id: int = 4197audio_token_id: int = 151646image_token_id: int = 151655video_token_id: int = 151656vision_start_token_id: int = 151652position_id_per_seconds: int = 25audio_start_token_id: int = 151669speaker_id: dict | None = Noneinitializer_range: float = 0.02tie_word_embeddings: bool = False )

参数

  • code_predictor_config (dict, 可选) — 用于初始化 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) — 表示 codec 生成序列中语音结束标记的 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) — 用于编解码器输入序列的填充 token ID。
  • codec_bos_id (int, 可选,默认为 4197) — 编解码器序列中的语音起始 token ID。
  • audio_token_id (int,可选,默认为 151646) — 用作输入音频占位符的音频 token 索引。
  • image_token_id (int,可选,默认为 151655) — 用作输入图像占位符的图像 token 索引。
  • video_token_id (int,可选,默认为 151656) — 用作输入视频占位符的视频 token 索引。
  • vision_start_token_id (int,可选,默认为 151652) — 用于标记多模态输入序列中视觉片段起始位置的 Token ID。
  • position_id_per_seconds (int, optional, defaults to 25) — Number of position IDs allocated per second of audio content, used for temporal alignment in generation.
  • 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> 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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 3584hidden_size: int = 2048intermediate_size: int = 18944num_hidden_layers: int = 28num_attention_heads: int = 28num_key_value_heads: int = 4hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truerope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falsesliding_window: int | None = Noneattention_dropout: float | int = 0.0decoder_sparse_step: int = 1moe_intermediate_size: int = 768num_experts_per_tok: int = 8num_experts: int = 128norm_topk_prob: bool = Trueoutput_router_logits: bool = Falserouter_aux_loss_coef: float = 0.001mlp_only_layers: list[int] | None = Nonepad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = None )

参数

  • 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 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 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 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> 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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonedepth: int = 27hidden_size: int = 1152hidden_act: str = 'gelu_pytorch_tanh'intermediate_size: int = 4304num_heads: int = 16in_channels: int = 3patch_size: int | list[int] | tuple[int, int] = 16spatial_merge_size: int = 2temporal_patch_size: int | list[int] | tuple[int, int] = 2out_hidden_size: int = 3584num_position_embeddings: int = 2304deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24)initializer_range: float = 0.02rope_parameters: dict | None = None )

参数

  • 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]) — 用于 deepstack 嵌入的层索引。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。

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

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

Qwen3OmniMoeAudioEncoderConfig

类 transformers.Qwen3OmniMoeAudioEncoderConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonenum_mel_bins: int = 128encoder_layers: int = 32encoder_attention_heads: int = 20encoder_ffn_dim: int = 5120d_model: int = 1280dropout: float | int = 0.0attention_dropout: float | int = 0.0activation_function: str = 'gelu'activation_dropout: float | int = 0.0scale_embedding: bool = Falseinitializer_range: float = 0.02max_source_positions: int = 1500n_window: int = 50output_dim: int = 3584n_window_infer: int = 800conv_chunksize: int = 500downsample_hidden_size: int = 480 )

参数

  • 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

Qwen3OmniMoeTalkerTextConfig

类 transformers.Qwen3OmniMoeTalkerTextConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 3072hidden_size: int = 1024intermediate_size: int = 2048num_hidden_layers: int = 20num_attention_heads: int = 16num_key_value_heads: int = 2hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truetie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falsesliding_window: int | None = Noneattention_dropout: float | int = 0.0decoder_sparse_step: int = 1moe_intermediate_size: int = 384num_experts_per_tok: int = 8num_experts: int = 128norm_topk_prob: bool = Falseoutput_router_logits: bool = Falserouter_aux_loss_coef: float = 0.001mlp_only_layers: list[int] | None = Nonepad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = None )

参数

  • 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 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 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 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> 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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 2048hidden_size: int = 1024intermediate_size: int = 3072num_hidden_layers: int = 5num_attention_heads: int = 16num_key_value_heads: int = 8head_dim: int = 128hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truetie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falsesliding_window: int | None = Nonemax_window_layers: int = 28layer_types: list[str] | None = Noneattention_dropout: float | int = 0.0pad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Nonenum_code_groups: int = 32 )

参数

  • 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 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 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 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • sliding_window (int, 可选) — 滑动窗口注意力的窗口大小。如果为 None,则不应用滑动窗口。
  • max_window_layers (int,可选,默认为 28) — 使用完整注意力的层数。前 max_window_layers 层将使用完整注意力,而在此之后的任何额外层都将使用 SWA(滑动窗口注意力)。
  • layer_types (list[str], 可选) — 一个列表,用于显式地将每个层索引映射到其层类型。如果未提供,将根据 config 值自动生成。
  • 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

Qwen3OmniMoeForConditionalGeneration

类 transformers.Qwen3OmniMoeForConditionalGeneration

< >

( config: Qwen3OmniMoeConfig )

Qwen3OmniMoeThinkerTextModel

类 transformers.Qwen3OmniMoeThinkerTextModel

< >

( config: Qwen3OmniMoeTextConfig )

参数

  • config (Qwen3OmniMoeTextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonevisual_pos_masks: typing.Optional[torch.Tensor] = Nonedeepstack_visual_embeds: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → MoeModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • visual_pos_masks(形状为 (batch_size, seqlen) 的 torch.Tensor,可选) — 视觉位置的掩码。
  • deepstack_visual_embeds (list[torch.Tensor], 可选) — Deepstack 视觉嵌入。其形状为 (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 时),其包含的元素取决于配置(Qwen3OmniMoeConfig)和输入。

Qwen3OmniMoeThinkerTextModel 的 forward 方法会重写 __call__ 特殊方法。

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

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

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

  • 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

< >

( config: Qwen3OmniMoeThinkerConfig )

参数

  • config (Qwen3OmniMoeThinkerConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids = Noneinput_features = Nonepixel_values = Nonepixel_values_videos = Noneimage_grid_thw = Nonevideo_grid_thw = Noneattention_mask = Nonefeature_attention_mask = Noneaudio_feature_lengths = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Noneuse_cache = Noneoutput_router_logits: bool | None = Noneuse_audio_in_video = Nonevideo_second_per_grid = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs ) → MoeModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (`of shape(batch_size, sequence_length)`) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • input_features (`of shape(batch_size, sequence_length, feature_dim)`) — 与输入音频特征对应的张量。可以使用 WhisperFeatureExtractor 获取音频特征。有关详细信息,请参阅 WhisperFeatureExtractor.call()(Qwen3OmniMoeProcessor 使用 WhisperFeatureExtractor 处理音频)。
  • pixel_values (`of shape(batch_size, num_channels, image_size, image_size)`) — 对应输入图像的张量。可以使用 Qwen2VLImageProcessor 获取像素值。有关详细信息,请参阅 Qwen2VLImageProcessor.call()(Qwen3OmniMoeProcessor 使用 Qwen2VLImageProcessor 处理图像)。
  • pixel_values_videos (`of shape(batch_size, num_frames, num_channels, frame_size, frame_size)`) — 对应输入视频的张量。可以使用 Qwen2VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 Qwen2VLVideoProcessor.call()(Qwen3OmniMoeProcessor 使用 Qwen2VLVideoProcessor 来处理视频)。
  • 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 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • feature_attention_mask (torch.Tensor 形状为 (batch_size, feature_sequence_length), ,可选) — 用于避免对填充特征索引执行注意力的掩码。掩码值在 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。
  • audio_feature_lengths(形状为 (num_audios) 的 torch.LongTensor,可选) — 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]`。

    什么是位置 ID?

  • past_key_values (`) -- 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 past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True`。

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids` indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • 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),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

MoeModelOutputWithPast 或 tuple(torch.Tensor)

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

Qwen3OmniMoeThinkerModel 的 forward 方法会重写 __call__ 特殊方法。

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

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

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

  • 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 之后),这些术语用于计算混合专家模型的辅助损失。

Qwen3OmniMoeThinkerForConditionalGeneration

class transformers.Qwen3OmniMoeThinkerForConditionalGeneration

< >

( config: Qwen3OmniMoeThinkerConfig )

forward

< >

( input_ids = Noneinput_features = Nonepixel_values = Nonepixel_values_videos = Noneimage_grid_thw = Nonevideo_grid_thw = Noneattention_mask = Nonefeature_attention_mask = Noneaudio_feature_lengths = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Nonelabels = Noneuse_cache = Noneoutput_router_logits: bool | None = Noneuse_audio_in_video = Nonevideo_second_per_grid = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (`of shape(batch_size, sequence_length)`) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • input_features (`of shape(batch_size, sequence_length, feature_dim)`) — 与输入音频特征对应的张量。可以使用 WhisperFeatureExtractor 获取音频特征。有关详细信息,请参阅 WhisperFeatureExtractor.call()(Qwen3OmniMoeProcessor 使用 WhisperFeatureExtractor 处理音频)。
  • pixel_values (`of shape(batch_size, num_channels, image_size, image_size)`) — 对应输入图像的张量。可以使用 Qwen2VLImageProcessor 获取像素值。有关详细信息,请参阅 Qwen2VLImageProcessor.call()(Qwen3OmniMoeProcessor 使用 Qwen2VLImageProcessor 处理图像)。
  • pixel_values_videos (`of shape(batch_size, num_frames, num_channels, frame_size, frame_size)`) — 对应输入视频的张量。可以使用 Qwen2VLVideoProcessor 获取视频的像素值。有关详细信息,请参阅 Qwen2VLVideoProcessor.call()(Qwen3OmniMoeProcessor 使用 Qwen2VLVideoProcessor 来处理视频)。
  • 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 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • feature_attention_mask (torch.Tensor 形状为 (batch_size, feature_sequence_length), ,可选) — 用于避免对填充特征索引执行注意力的掩码。掩码值在 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。
  • audio_feature_lengths(形状为 (num_audios) 的 torch.LongTensor,可选) — 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]`。

    什么是位置 ID?

  • past_key_values (`) -- 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 past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True`。

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_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 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, …, config.vocab_size]`.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • 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),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

MoeCausalLMOutputWithPast 或 tuple(torch.Tensor)

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

Qwen3OmniMoeThinkerForConditionalGeneration 的 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 如何被分发到各个专家。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

示例:

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

< >

( input_features: Tensorfeature_attention_mask: typing.Optional[torch.LongTensor] = Noneaudio_feature_lengths: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor) — 与输入音频对应的张量。
  • feature_attention_mask (torch.LongTensor, 可选) — 用于避免对填充特征索引执行注意力机制的掩码。掩码值在 [0, 1] 中选取:
  • audio_feature_lengths(形状为 (num_audios) 的 torch.LongTensor,可选) — LLM 中每个音频的特征长度。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen3OmniMoeConfig)和输入。

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

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

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

< >

( pixel_values: Tensorimage_grid_thw: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithDeepstackFeatures or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。
  • image_grid_thw (torch.LongTensor,形状为 (num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。

返回值

BaseModelOutputWithDeepstackFeatures 或 tuple(torch.Tensor)

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

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

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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 层的隐藏状态(特征图)列表。

示例:

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

< >

( pixel_values_videos: Tensorvideo_grid_thw: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithDeepstackFeatures or tuple(torch.Tensor)

参数

  • pixel_values_videos(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入视频对应的张量。
  • video_grid_thw(形状为 (num_videos, 3) 的 torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。

返回值

BaseModelOutputWithDeepstackFeatures 或 tuple(torch.Tensor)

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

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

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 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 层的隐藏状态(特征图)列表。

示例:

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

class transformers.Qwen3OmniMoeTalkerForConditionalGeneration

< >

( config: Qwen3OmniMoeTalkerConfig )

参数

  • config (Qwen3OmniMoeTalkerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids = Noneattention_mask = Noneuse_audio_in_video = Noneaudio_feature_lengths = Nonevideo_second_per_grid = Noneimage_grid_thw = Nonevideo_grid_thw = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Nonelabels = Noneuse_cache = Noneoutput_router_logits = Noneresidual_codes = Nonetrailing_text_hidden = Nonetts_pad_embed = Nonegeneration_step = Nonetalker_input_ids = None**kwargs ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (`of shape(batch_size, sequence_length)`) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • use_audio_in_video (bool, 可选) — 如果设置为 True,则使用视频中的音频。
  • audio_feature_lengths(形状为 (num_audios) 的 torch.LongTensor,可选) — 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]`。

    什么是位置 ID?

  • past_key_values (`) -- 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 past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True`。

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_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 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, …, config.vocab_size]`.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • 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 时),其包含的元素取决于配置(Qwen3OmniMoeConfig)和输入。

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 如何被分发到各个专家。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

Qwen3OmniMoePreTrainedModel

类 transformers.Qwen3OmniMoePreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

参数

  • config (PreTrainedConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

Qwen3OmniMoePreTrainedModelForConditionalGeneration

类 transformers.Qwen3OmniMoePreTrainedModelForConditionalGeneration

< >

( config: PreTrainedConfig*inputs**kwargs )

get_chunked_index

< >

( token_indices: Tensortokens_per_chunk: intremove_index: int ) → list[tuple[int, int]]

参数

  • token_indices(形状为 (seq_len, ) 的 torch.Tensor)— 一个单调递增的 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

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Nonevideo_grid_thw: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneuse_audio_in_video: bool = Falseaudio_seqlens: typing.Optional[torch.LongTensor] = Nonesecond_per_grids: typing.Optional[torch.Tensor] = None )

参数

  • input_ids(形状为 (batch_size, sequence_length) 的 torch.LongTensor)— 输入序列中各个 token 在词汇表中的索引。如果您提供了填充(padding),默认情况下会被忽略。
  • image_grid_thw (torch.LongTensor,形状为 (num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。
  • video_grid_thw(形状为 (num_videos, 3) 的 torch.LongTensor,可选) — LLM 中每个视频的特征形状的时间、高度和宽度。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。
  • use_audio_in_video (bool, 可选) — 如果设置为 True,则使用视频中的音频。
  • audio_seqlens(形状为 (num_audios) 的 torch.LongTensor,可选) — LLM 中每个音频的特征形状长度。
  • second_per_grids (torch.LongTensor,形状为 (num_videos),可选) — 3D 位置 ID 中沿时间维度每个网格的时间间隔(以秒为单位)。

在 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(每秒帧数):视频的帧率,设置为 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

< >

( config: Qwen3OmniMoeTalkerTextConfig )

参数

  • config (Qwen3OmniMoeTalkerTextConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonevisual_pos_masks: typing.Optional[torch.Tensor] = Nonedeepstack_visual_embeds: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → MoeModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • visual_pos_masks(形状为 (batch_size, seqlen) 的 torch.Tensor,可选) — 视觉位置的掩码。
  • deepstack_visual_embeds (list[torch.Tensor], 可选) — Deepstack 视觉嵌入。其形状为 (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 时),其包含的元素取决于配置(Qwen3OmniMoeConfig)和输入。

Qwen3OmniMoeTalkerModel 的 forward 方法会重写 __call__ 特殊方法。

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

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

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

  • 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

class transformers.Qwen3OmniMoeThinkerTextPreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

参数

  • config (PreTrainedConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

Qwen3OmniMoeProcessor

类 transformers.Qwen3OmniMoeProcessor

< >

( image_processor = Nonevideo_processor = Nonefeature_extractor = Nonetokenizer = Nonechat_template = None )

参数

  • image_processor (Qwen2VLImageProcessor) — 图像处理器是必需的输入。
  • video_processor (Qwen2VLVideoProcessor) — 视频处理器是必需的输入。
  • feature_extractor(WhisperFeatureExtractor)— 特征提取器是必需的输入。
  • tokenizer (Qwen2Tokenizer) — 分词器是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。

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

Qwen3OmniMoeProcessor 提供了 Qwen2VLImageProcessor、Qwen2VLVideoProcessor、WhisperFeatureExtractor 和 Qwen2Tokenizer 的所有功能。有关更多信息,请参阅 ~Qwen2VLImageProcessor、~Qwen2VLVideoProcessor、~WhisperFeatureExtractor 和 ~Qwen2Tokenizer。

__call__

< >

( text: str | list[str] | list[list[str]] = Noneimages: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonevideos: 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] = Noneaudio: 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'> ) → ~feature_extraction_utils.BatchFeature

参数

  • 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, optional) — 视觉编码器使用的空间 patch 大小。视频帧在高度和宽度两个维度上都会被划分为该大小的 patch。
  • temporal_patch_size (int, kwargs, 可选) — 视觉编码器使用的时序 patch 大小。它决定了将多少连续帧组合为一个时序 patch。
  • merge_size (int, kwargs, 可选) — 用于合并空间补丁的合并大小。多个补丁会被合并在一起,以在保留空间信息的同时缩短序列长度。
  • min_frames (int, kwargs, 可选) — 从视频中提取的最少帧数。帧数较少的视频将被填充或重复,以满足此要求。
  • max_frames (int, kwargs, 可选) — 从视频中提取的最大帧数。较长的视频将被截断或采样,以符合此限制。
  • use_audio_in_video(bool,kwargs,可选,默认值为 False)— 已弃用的参数,请改用 load_audio_from_video。
  • load_audio_from_video (bool,kwargs,可选,默认为 False) — 在处理视频时是否纳入音频信息。启用后,音频 token 将根据时间对齐与视频 token 交错排列,从而构建统一的多模态表示。
  • seconds_per_chunk (float,kwargs,可选,默认值为 2.0) — 在拆分长视频时,每个视频片段的时长(以秒为单位)。该参数控制视频如何被划分为时间片段以供处理。
  • position_id_per_seconds (int, kwargs or float, optional, defaults to 25) — The number of position IDs allocated per second of video. This parameter controls the temporal resolution of position embeddings and is used to align video tokens with audio tokens when use_audio_in_video=True.
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (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

class transformers.Qwen3OmniMoeCode2Wav

< >

( config: Qwen3OmniMoeCode2WavConfig )

Qwen3OmniMoeCode2WavDecoderBlock

class transformers.Qwen3OmniMoeCode2WavDecoderBlock

< >

( config: Qwen3OmniMoeCode2WavConfiglayer_idx )

Qwen3OmniMoeCode2WavTransformerModel

class transformers.Qwen3OmniMoeCode2WavTransformerModel

< >

( config: Qwen3OmniMoeCode2WavConfig )

参数

  • config (Qwen3OmniMoeCode2WavConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids = Noneattention_mask = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Noneuse_cache = None**kwargs ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (`of shape(batch_size, sequence_length)`) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

    什么是位置 ID?

  • past_key_values (`) -- 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 past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True`。

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids` indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen3OmniMoeConfig)和输入。

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

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

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

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

Qwen3OmniMoeTalkerCodePredictorModel

class transformers.Qwen3OmniMoeTalkerCodePredictorModel

< >

( config: Qwen3OmniMoeTalkerCodePredictorConfig )

参数

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

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

参数

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

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

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

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

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen3OmniMoeConfig)和输入。

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

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

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

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration

类 transformers.Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration

< >

( config: Qwen3OmniMoeTalkerCodePredictorConfig )

参数

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids = Noneattention_mask = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Nonelabels = Noneuse_cache = Nonegeneration_steps = None**kwargs ) → CausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (`of shape(batch_size, sequence_length)`) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

    什么是位置 ID?

  • past_key_values (`) -- 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 past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True`。

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_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 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, …, config.vocab_size]`.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • generation_steps (int) — 代码预测器的生成步骤,取值范围为 0 到 num_code_groups-1

返回值

CausalLMOutputWithPast 或 tuple(torch.Tensor)

一个 CausalLMOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Qwen3OmniMoeConfig)和输入。

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

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

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

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

Update on GitHub