## 快速入门

```py
import torch
from transformers import pipeline

pipe = pipeline(
    task="text-generation",
    model="Qwen/Qwen3.5-35B-A3B",
    device_map="auto",
)
print(pipe("The capital of France is", max_new_tokens=20)[0]["generated_text"])
```

```py
import torch
from transformers import AutoTokenizer, Qwen3_5MoeForCausalLM

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-35B-A3B")
model = Qwen3_5MoeForCausalLM.from_pretrained(
    "Qwen/Qwen3.5-35B-A3B",
    device_map="auto",
)

inputs = tokenizer("Explain mixture-of-experts in one paragraph.", return_tensors="pt").to(model.device)
generated_ids = model.generate(**inputs, max_new_tokens=64)
print(tokenizer.decode(generated_ids[0], skip_special_tokens=True))
```

## 使用技巧与说明

- 在训练或微调时，请设置 `output_router_logits=True`，以便前向传播返回路由 logits，并将负载均衡辅助损失添加到总损失中（由 `router_aux_loss_coef` 进行缩放，默认值为 `0.001`）。如果不设置该参数，专家可能会坍缩到少数几个热门槽位上。
- `Qwen3_5MoeCausalLMOutputWithPast` 包含一个 `router_logits` 字段。通过位置解构模型输出的下游代码需要对此加以处理，或改用关键字访问。
- 对于 Qwen3.5-35B-A3B，其文本配置在 40 层中均使用 `hidden_size=2048`，每个 token 配备 256 个专家，其中 8 个为路由专家，1 个为共享专家，且 `moe_intermediate_size=512`。这与稠密 Qwen3.5 检查点的结构差异很大，因此权重不可互换。
- 原生上下文为 262,144 个 token。要达到宣传的约 100 万上下文，请通过配置中的 `rope_scaling` 字段启用 YaRN rope 缩放——直接加载仅能获得原生窗口。
- 与 Qwen3.5 一样，线性注意力层依赖于可选的 `causal_conv1d`（来自 [Dao-AILab](https://github.com/Dao-AILab/causal-conv1d)）。如果未安装该库，模型会静默回退到速度更慢且内存占用更高的 PyTorch 算子。
- 在 NVIDIA GB10（计算能力 12.1 / SM121）上，`causal_conv1d` 和 `fla` 没有 SM121 构建版本，因此 Gated DeltaNet 路径始终使用较慢的 PyTorch 参考实现。向 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 传入 `use_kernels=True`（`pip install -U kernels`）后，会将其替换为与稠密变体相同的、受计算能力限制的 Hub 内核（[`Atlas-Inference/gdn`](https://huggingface.co/kernels/Atlas-Inference/gdn)，由于 `Qwen3_5MoeGatedDeltaNet` 与 `Qwen3_5GatedDeltaNet` 具有相同的核心，因此共享该内核）；其他所有 GPU 均保留现有路径。该内核在数值上与回退实现保持一致（贪心解码输出完全相同），并加速了 prefill 阶段。在 `Qwen/Qwen3.6-35B-A3B`（bf16，GB10/SM121，1024 token 提示，256 token 贪心解码）上的实测结果如下：

  | `use_kernels` | TTFT（预填充） | 解码 |
  | --- | --- | --- |
  | `False`（PyTorch 回退） | 0.73 s | 16.3 tok/s |
  | `True` ([`Atlas-Inference/gdn`](https://huggingface.co/kernels/Atlas-Inference/gdn)) | 0.53 秒（快 1.38 倍） | 16.7 tok/s |

  Decode 阶段大致保持平稳，因为单 token 的 DeltaNet 递归受限于内存带宽；性能提升主要体现在分块预填充核心上，并随着提示词长度的增加而增大。目前，加载映射内核需要设置 `trust_remote_code=True`，直到 `Atlas-Inference` 被添加到受信任内核白名单中。

- 在批量生成时使用左侧填充。请参阅 [填充侧](../llm_tutorial#padding-side)。

## Qwen3_5MoeConfig[[transformers.Qwen3_5MoeConfig]]

#### transformers.Qwen3_5MoeConfig[[transformers.Qwen3_5MoeConfig]]

```python
transformers.Qwen3_5MoeConfig(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, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_id: int = 248056, video_token_id: int = 248057, vision_start_token_id: int = 248053, vision_end_token_id: int = 248054, tie_word_embeddings: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L166)

**参数：**

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

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

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

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

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

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

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

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

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

示例：

```python
>>> from transformers import Qwen3_5MoeForConditionalGeneration, Qwen3_5MoeConfig

>>> # Initializing a Qwen3.5-MoE style configuration
>>> configuration = Qwen3_5MoeConfig()

>>> # Initializing a model from the Qwen3.5-35B-A3B style configuration
>>> model = Qwen3_5MoeForConditionalGeneration(configuration)

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

## Qwen3_5MoeTextConfig[[transformers.Qwen3_5MoeTextConfig]]

#### transformers.Qwen3_5MoeTextConfig[[transformers.Qwen3_5MoeTextConfig]]

```python
transformers.Qwen3_5MoeTextConfig(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 = 248320, hidden_size: int = 2048, num_hidden_layers: int = 40, 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, attention_dropout: float | int = 0.0, head_dim: int = 256, linear_conv_kernel_dim: int = 4, linear_key_head_dim: int = 128, linear_value_head_dim: int = 128, linear_num_key_heads: int = 16, linear_num_value_heads: int = 32, moe_intermediate_size: int = 512, shared_expert_intermediate_size: int = 512, num_experts_per_tok: int = 8, num_experts: int = 256, output_router_logits: bool = False, router_aux_loss_coef: float = 0.001, layer_types: list[str] | 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/main/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L29)

**参数：**

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

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

num_hidden_layers (`int`，*可选*，默认为 `40`)：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`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

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

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

linear_conv_kernel_dim (`int`，*可选*，默认为 4)：线性注意力层中使用的卷积的核大小。

linear_key_head_dim (`int`，*可选*，默认为 128)：线性注意力中每个键头的维度。

linear_value_head_dim (`int`，*可选*，默认为 128)：线性注意力中每个值头的维度。

linear_num_key_heads (`int`，*可选*，默认为 16)：线性注意力层中使用的键头数量。

linear_num_value_heads (`int`，*可选*，默认为 32)：线性注意力层中使用的值头数量。

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

shared_expert_intermediate_size (`int`，*可选*，默认为 `512`)：共享专家 MLP 的中间层大小。

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

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

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

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

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

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_5MoeModel 配置的类。它根据指定的参数实例化 Qwen3 5 Moe 模型，并定义模型架构。使用默认值实例化配置，将得到与 [Qwen/Qwen3.5-35B-A3B](https://huggingface.co/Qwen/Qwen3.5-35B-A3B) 类似的配置。

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

```python
>>> from transformers import Qwen3_5MoeTextModel, Qwen3_5MoeTextConfig

>>> # Initializing a Qwen3.5-MoE style configuration
>>> configuration =  Qwen3_5MoeTextConfig()

>>> # Initializing a model from the Qwen3.5-35B-A3B style configuration
>>> model = Qwen3_5MoeTextModel(configuration)

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

## Qwen3_5MoeVisionConfig[[transformers.Qwen3_5MoeVisionConfig]]

#### transformers.Qwen3_5MoeVisionConfig[[transformers.Qwen3_5MoeVisionConfig]]

```python
transformers.Qwen3_5MoeVisionConfig(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, initializer_range: float = 0.02, rope_parameters: dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L136)

**参数：**

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)：该模型可能使用的最大序列长度

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

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

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

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

## Qwen3_5MoeVisionModel[[transformers.Qwen3_5MoeVisionModel]]

#### transformers.Qwen3_5MoeVisionModel[[transformers.Qwen3_5MoeVisionModel]]

```python
transformers.Qwen3_5MoeVisionModel(config: Qwen3_5MoeVisionConfig, *inputs, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1199)

#### forward[[transformers.Qwen3_5MoeVisionModel.forward]]

```python
forward(hidden_states: Tensor, grid_thw: Tensor, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1236)

**参数：**

hidden_states (`torch.Tensor`，形状为 `(seq_len, hidden_size)`)：模型的最终隐藏状态。

grid_thw (`torch.Tensor`，形状为 `(num_images_or_videos, 3)`)：LLM 中每张图片的特征形状的时间、高度和宽度。

**返回：** `torch.Tensor`

hidden_states.

## Qwen3_5MoeTextModel[[transformers.Qwen3_5MoeTextModel]]

#### transformers.Qwen3_5MoeTextModel[[transformers.Qwen3_5MoeTextModel]]

```python
transformers.Qwen3_5MoeTextModel(config: Qwen3_5MoeTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1285)

#### forward[[transformers.Qwen3_5MoeTextModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1300)

**参数：**

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

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

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

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

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

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

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

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

[Qwen3_5MoeTextModel](/docs/transformers/main/zh/model_doc/qwen3_5_moe#transformers.Qwen3_5MoeTextModel) 的 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](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

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

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

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **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 之后），这些术语用于计算混合专家模型的辅助损失。

## Qwen3_5MoeModel[[transformers.Qwen3_5MoeModel]]

#### transformers.Qwen3_5MoeModel[[transformers.Qwen3_5MoeModel]]

```python
transformers.Qwen3_5MoeModel(config: Qwen3_5MoeConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1374)

**参数：**

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

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

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

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, mm_token_type_ids: typing.Optional[torch.IntTensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1653)

**参数：**

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

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

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

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

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

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

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

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

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

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

mm_token_type_ids (`torch.IntTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：与每种模态匹配的输入序列 token 的索引。例如文本 (0)、图像 (1)、视频 (2)。可以使用 [AutoProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoProcessor) 获取多模态 token 类型 ID。有关详细信息，请参阅 [ProcessorMixin.__call__()](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessorMixin.__call__)。

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`），其包含的元素取决于配置（[Qwen3_5MoeConfig](/docs/transformers/main/zh/model_doc/qwen3_5_moe#transformers.Qwen3_5MoeConfig)）和输入。

[Qwen3_5MoeModel](/docs/transformers/main/zh/model_doc/qwen3_5_moe#transformers.Qwen3_5MoeModel) 的 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](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

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

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

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **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 之后），这些术语用于计算混合专家模型的辅助损失。

## Qwen3_5MoeForCausalLM[[transformers.Qwen3_5MoeForCausalLM]]

#### transformers.Qwen3_5MoeForCausalLM[[transformers.Qwen3_5MoeForCausalLM]]

```python
transformers.Qwen3_5MoeForCausalLM(config: Qwen3_5MoeTextConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1801)

**参数：**

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

用于因果语言建模的 Qwen3 5 Moe 模型。

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

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1821)

**参数：**

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

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

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

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

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

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

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

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

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

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

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

[Qwen3_5MoeForCausalLM](/docs/transformers/main/zh/model_doc/qwen3_5_moe#transformers.Qwen3_5MoeForCausalLM) 的 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](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

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

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

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

示例：

```python
>>> from transformers import AutoTokenizer, Qwen3_5MoeForCausalLM

>>> model = Qwen3_5MoeForCausalLM.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct")
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct")

>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```

## Qwen3_5MoeForConditionalGeneration[[transformers.Qwen3_5MoeForConditionalGeneration]]

#### transformers.Qwen3_5MoeForConditionalGeneration[[transformers.Qwen3_5MoeForConditionalGeneration]]

```python
transformers.Qwen3_5MoeForConditionalGeneration(config: Qwen3_5MoeConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1900)

#### forward[[transformers.Qwen3_5MoeForConditionalGeneration.forward]]

```python
forward(input_ids: LongTensor = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, mm_token_type_ids: typing.Optional[torch.IntTensor] = None, output_router_logits: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1942)

**参数：**

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

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

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

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

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

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

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

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

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

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

mm_token_type_ids (`torch.IntTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：与每种模态匹配的输入序列 token 的索引。例如文本 (0)、图像 (1)、视频 (2)。可以使用 [AutoProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoProcessor) 获取多模态 token 类型 ID。有关详细信息，请参阅 [ProcessorMixin.__call__()](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessorMixin.__call__)。

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

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

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`），其包含的元素取决于配置（[Qwen3_5MoeConfig](/docs/transformers/main/zh/model_doc/qwen3_5_moe#transformers.Qwen3_5MoeConfig)）和输入。

[Qwen3_5MoeForConditionalGeneration](/docs/transformers/main/zh/model_doc/qwen3_5_moe#transformers.Qwen3_5MoeForConditionalGeneration) 的 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](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

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

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

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

示例：
```python
>>> from transformers import AutoProcessor, Qwen3_5MoeForConditionalGeneration

>>> model = Qwen3_5MoeForConditionalGeneration.from_pretrained("Qwen/Qwen3.5-35B-A3B-Instruct", dtype="auto", device_map="auto")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3.5-35B-A3B-Instruct")

>>> messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/qwen_vl_demo.jpeg",
            },
            {"type": "text", "text": "Describe this image in short."},
        ],
    }
]

>>> # Preparation for inference
>>> inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt"
)
>>> inputs = inputs.to(model.device)

>>> # Generate
>>> generated_ids = model.generate(**inputs, max_new_tokens=128)
>>> generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
>>> processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"A woman in a plaid shirt sits on a sandy beach at sunset, smiling as she gives a high-five to a yellow Labrador Retriever wearing a harness. The ocean waves roll in the background."
```

