Transformers documentation
Qwen4 MoE
This model was contributed to Hugging Face Transformers on 2026-12-03.
Qwen4 MoE
Qwen4 MoE uses the mixture-of-experts and per-layer embedding architecture described in Qwen4-Exp.
Use Qwen4MoeForCausalLM for text generation and Qwen4MoeForConditionalGeneration for image and video inputs.
Qwen4MoeConfig
class transformers.Qwen4MoeConfig
< source >( 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 = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_id: int = 248056video_token_id: int = 248057vision_start_token_id: int = 248053vision_end_token_id: int = 248054tie_word_embeddings: bool = False )
Parameters
- text_config (
Union[dict, ~configuration_utils.PreTrainedConfig], optional) — The config object or dictionary of the text backbone. - vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig], optional) — The config object or dictionary of the vision backbone. - image_token_id (
int, optional, defaults to248056) — The image token index used as a placeholder for input images. - video_token_id (
int, optional, defaults to248057) — The video token index used as a placeholder for input videos. - vision_start_token_id (
int, optional, defaults to248053) — Token ID that marks the start of a visual segment in the multimodal input sequence. - vision_end_token_id (
int, optional, defaults to248054) — Token ID that marks the end of a visual segment in the multimodal input sequence. - tie_word_embeddings (
bool, optional, defaults toFalse) — Whether to tie weight embeddings according to model’stied_weights_keysmapping.
This is the configuration class to store the configuration of a Qwen4MoeModel. It is used to instantiate a Qwen4 Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Qwen/Qwen4
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Qwen4MoeTextConfig
class transformers.Qwen4MoeTextConfig
< source >( 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 = 248320hidden_size: int = 2048num_hidden_layers: int = 40num_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 = Falseattention_dropout: float | int = 0.0head_dim: int = 256linear_conv_kernel_dim: int = 4linear_key_head_dim: int = 128linear_value_head_dim: int = 128linear_num_key_heads: int = 16linear_num_value_heads: int = 32moe_intermediate_size: int = 512shared_expert_intermediate_size: int = 512num_experts_per_tok: int = 10num_experts: int = 512output_router_logits: bool = Falserouter_aux_loss_coef: float = 0.001layer_types: list[str] | None = Nonepad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Nonehc_count: int = 4hc_lowrank: int = 320ple_layer_ids: list[int] | None = Noneple_embed_dim: int | None = Noneple_conv_kernel_size: int = 4ngram_size: int = 3heads_per_ngram: int = 8ngram_vocab_size_base: int = 20000000make_ngram_vocab_size_divisible_by: int = 128seed: int = 1234split_ngram_parts: int = 512indexer_n_heads: int = 4indexer_kv_heads: int = 1indexer_head_dim: int = 256indexer_budget: int = 2048indexer_compress_ratio: int = 4norm_topk_prob: bool = Trueoutput_gate_type: str | None = None )
Parameters
- vocab_size (
int, optional, defaults to248320) — Vocabulary size of the model. Defines the number of different tokens that can be represented by theinput_ids. - hidden_size (
int, optional, defaults to2048) — Dimension of the hidden representations. - num_hidden_layers (
int, optional, defaults to40) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to16) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to2) — This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - hidden_act (
str, optional, defaults tosilu) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - max_position_embeddings (
int, optional, defaults to32768) — The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (
float, optional, defaults to1e-06) — The epsilon used by the rms normalization layers. - use_cache (
bool, optional, defaults toTrue) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=Trueor when the model is a decoder-only generative model. - tie_word_embeddings (
bool, optional, defaults toFalse) — Whether to tie weight embeddings according to model’stied_weights_keysmapping. - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings. - attention_bias (
bool, optional, defaults toFalse) — Whether to use a bias in the query, key, value and output projection layers during self-attention. - attention_dropout (
Union[float, int], optional, defaults to0.0) — The dropout ratio for the attention probabilities. - head_dim (
int, optional, defaults to256) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads - linear_conv_kernel_dim (
int, optional, defaults to 4) — Kernel size of the convolution used in linear attention layers. - linear_key_head_dim (
int, optional, defaults to 128) — Dimension of each key head in linear attention. - linear_value_head_dim (
int, optional, defaults to 128) — Dimension of each value head in linear attention. - linear_num_key_heads (
int, optional, defaults to 16) — Number of key heads used in linear attention layers. - linear_num_value_heads (
int, optional, defaults to 32) — Number of value heads used in linear attention layers. - moe_intermediate_size (
int, optional, defaults to512) — Intermediate size of the routed expert MLPs. - shared_expert_intermediate_size (
int, optional, defaults to512) — Intermediate size of the shared expert MLPs. - num_experts_per_tok (
int, optional, defaults to10) — Number of experts to route each token to. This is the top-k value for the token-choice routing. - num_experts (
int, optional, defaults to512) — Number of routed experts in MoE layers. - output_router_logits (
bool, optional, defaults toFalse) — Whether or not the router logits should be returned by the model. Enabling this will also allow the model to output the auxiliary loss, including load balancing loss and router z-loss. - router_aux_loss_coef (
float, optional, defaults to0.001) — Auxiliary load balancing loss coefficient. Used to penalize uneven expert routing in MoE models. - layer_types (
list[str], optional) — A list that explicitly maps each layer index with its layer type. If not provided, it will be automatically generated based on config values. - pad_token_id (
int, optional) — Token id used for padding in the vocabulary. - bos_token_id (
int, optional) — Token id used for beginning-of-stream in the vocabulary. - eos_token_id (
Union[int, list[int]], optional) — Token id used for end-of-stream in the vocabulary. - hc_count (
int, optional, defaults to 4) — Number of residual streams used by the hyper-connections. - hc_lowrank (
int, optional, defaults to 320) — Rank of the learned hyper-connection input mixer. - ple_layer_ids (
list[int], optional) — One-indexed decoder layer ids that use Per-Layer Embedding (PLE). - ple_embed_dim (
int, optional) — Total dimension of the embeddings concatenated from all n-gram heads in each PLE module. Defaults tohidden_size. - ple_conv_kernel_size (
int, optional, defaults to 4) — Kernel size of the dilated depthwise convolution in each PLE module. - ngram_size (
int, optional, defaults to 3) — Largest token n-gram represented by PLE. - heads_per_ngram (
int, optional, defaults to 8) — Number of independently hashed embedding heads for every n-gram order. - ngram_vocab_size_base (
int, optional, defaults to 20000000) — Lower bound used to derive a distinct prime vocabulary size for each hashed n-gram head. - make_ngram_vocab_size_divisible_by (
int, optional, defaults to 128) — Divisor used to pad the combined n-gram embedding vocabulary. - seed (
int, optional, defaults to 1234) — Seed used to deterministically derive the per-layer n-gram hash multipliers. - split_ngram_parts (
int, optional, defaults to 512) — Number of checkpoint shards used for each PLE n-gram embedding table. Loading concatenates the shards into a single runtime embedding, whilesave_pretrainedrestores the configured sharded layout. - indexer_n_heads (
int, optional) — Number of query heads used by the QSA token indexer. Setting this enables QSA on full-attention layers. - indexer_kv_heads (
int, optional) — Number of indexer key heads. Qwen4-Exp QSA requires one key head. - indexer_head_dim (
int, optional) — Dimension of every QSA indexer query and key head. - indexer_budget (
int, optional) — Maximum number of tokens selected from complete compressed blocks for each query. - indexer_compress_ratio (
int, optional) — Number of consecutive token keys averaged into one QSA index block. - norm_topk_prob (
bool, optional, defaults toTrue) — Whether to normalize the weights of the routed experts. - output_gate_type (
str, optional) — Activation used by the output gate of linear attention. If unset,hidden_actis used.
This is the configuration class to store the configuration of a Qwen4MoeModel. It is used to instantiate a Qwen4 Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Qwen/Qwen4
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Part of @strict-powered validation. Validates Qwen4-Exp architecture invariants.
Qwen4MoeVisionConfig
class transformers.Qwen4MoeVisionConfig
< source >( 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 = 2048num_position_embeddings: int = 2304initializer_range: float = 0.02rope_parameters: dict | None = None )
Parameters
- depth (
int, optional, defaults to27) — Number of Transformer layers in the vision encoder. - hidden_size (
int, optional, defaults to1152) — Dimension of the hidden representations. - hidden_act (
str, optional, defaults togelu_pytorch_tanh) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - intermediate_size (
int, optional, defaults to4304) — Dimension of the MLP representations. - num_heads (
int, optional, defaults to16) — Number of attention heads for each attention layer in the Transformer decoder. - in_channels (
int, optional, defaults to3) — The number of input channels. - patch_size (
Union[int, list[int], tuple[int, int]], optional, defaults to16) — The size (resolution) of each patch. - spatial_merge_size (
int, optional, defaults to2) — The size of the spatial merge window used to reduce the number of visual tokens by merging neighboring patches. - temporal_patch_size (
Union[int, list[int], tuple[int, int]], optional, defaults to2) — Temporal patch size used in the 3D patch embedding for video inputs. - out_hidden_size (
int, optional, defaults to 3584) — The output hidden size of the vision model. - num_position_embeddings (
int, optional, defaults to 2304) — The maximum sequence length that this model might ever be used with - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rope_parameters (
dict, optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings.
This is the configuration class to store the configuration of a Qwen4MoeModel. It is used to instantiate a Qwen4 Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Qwen/Qwen4
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Qwen4MoeVisionModel
class transformers.Qwen4MoeVisionModel
< source >( config: Qwen4MoeVisionConfig*inputs**kwargs )
Parameters
- config (Qwen4MoeVisionConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The bare Qwen4 Moe Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( hidden_states: Tensorgrid_thw: Tensor**kwargs ) → torch.Tensor
Qwen4MoeTextModel
class transformers.Qwen4MoeTextModel
< source >( config: Qwen4MoeTextConfig )
Parameters
- config (Qwen4MoeTextConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The bare Qwen4 Moe Text Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Noneple_input_ids: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — 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 thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache). - ple_input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Original token ids used by Per-Layer Embedding (PLE). This is only needed when PLE is enabled andinputs_embedsare passed instead ofinput_ids.
Returns
BaseModelOutputWithPast or tuple(torch.Tensor)
A BaseModelOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Qwen4MoeTextModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
last_hidden_state (
torch.Tensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.If
cacheis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output.cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.Tensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.Tensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple(torch.Tensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Qwen4MoeModel
class transformers.Qwen4MoeModel
< source >( config: Qwen4MoeConfig )
Parameters
- config (Qwen4MoeConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The bare Qwen4 Moe Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Nonevideo_grid_thw: typing.Optional[torch.LongTensor] = Nonemm_token_type_ids: typing.Optional[torch.IntTensor] = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Qwen4MoeBaseModelOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — 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 thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - pixel_values (
torch.Tensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained usingimage_processor_class. Seeimage_processor_class.__call__for details (processor_classusesimage_processor_classfor processing images). - pixel_values_videos (
torch.Tensorof shape(batch_size, num_frames, num_channels, frame_size, frame_size), optional) — The tensors corresponding to the input video. Pixel values for videos can be obtained usingvideo_processor_class. Seevideo_processor_class.__call__for details (processor_classusesvideo_processor_classfor processing videos). - image_grid_thw (
torch.LongTensorof shape(num_images, 3), optional) — The temporal, height and width of feature shape of each image in LLM. - video_grid_thw (
torch.LongTensorof shape(num_videos, 3), optional) — The temporal, height and width of feature shape of each video in LLM. - mm_token_type_ids (
torch.IntTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens matching each modality. For example text (0), image (1), video (2). Multimodal token type ids can be obtained using AutoProcessor. See ProcessorMixin.call() for details. - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], optional) — Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple that consists of (pooler_output, optional:last_hidden_states, optional:hidden_states, optional:attentions)pooler_outputof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of multimmodal features of the encoder merged into text embeddings.
Returns
Qwen4MoeBaseModelOutputWithPast or tuple(torch.Tensor)
A Qwen4MoeBaseModelOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Qwen4MoeModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
- last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the language model backbone. Ifcacheis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output. - cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide. Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally ifconfig.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding. - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size). Hidden-states of the language model backbone at the output of each layer plus the optional initial embedding outputs. - attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length). Attention weights of the language model backbone, after the attention softmax. - router_logits (
tuple(torch.Tensor), optional, returned whenoutput_router_logits=Trueis passed or whenconfig.output_router_logits=True) — Tuple oftorch.Tensor(one for each sparse layer) of shape(batch_size * sequence_length, num_experts). Raw router logits computed by the MoE routers. They can be used to compute a load-balancing loss or to inspect how tokens are dispatched to experts. - image_outputs (
BaseModelOutputWithPooling, optional) — Output of the image encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no images were processed. - video_outputs (
BaseModelOutputWithPooling, optional) — Output of the video encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no videos were processed. - audio_outputs (
BaseModelOutputWithPooling, optional) — Output of the audio encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no audio was processed.
Qwen4MoeForCausalLM
class transformers.Qwen4MoeForCausalLM
< source >( config: Qwen4MoeTextConfig )
Parameters
- config (Qwen4MoeTextConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The Qwen4 Moe Model for causal language modeling.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Noneoutput_router_logits: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — 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 thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for computing the causal language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size](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].The labels are shifted internally so that
labels[..., 1:]are used to predictlogits[..., :-1, :]. Pass unshifted labels matchinginput_ids(i.e.labels = input_ids). Do not shift the labels yourself before passing them.If the labels are already shifted (for example with sequence parallelism), pass them as the
shift_labelskeyword argument and they are used as is.labelsmust still be passed for the loss to be computed. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache). - output_router_logits (
bool, optional) — Whether or not to return the logits of all the routers. They are useful for computing the router loss, and should not be returned during inference. - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).
Returns
MoeCausalLMOutputWithPast or tuple(torch.Tensor)
A MoeCausalLMOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Qwen4MoeForCausalLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
loss (
torch.Tensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss (for next-token prediction).logits (
torch.Tensorof shape(batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).aux_loss (
torch.Tensor, optional, returned whenoutput_router_logits=Trueis passed or whenconfig.output_router_logits=True, and the model trains its router with a load-balancing loss) — Load-balancing auxiliary loss for the sparse modules. Models that balance their experts with a router bias instead (DeepSeek-V3 and the architectures derived from it) returnNonehere while still returningrouter_logits.router_logits (
tuple(torch.Tensor), optional, returned whenoutput_router_logits=Trueis passed or whenconfig.output_router_logits=True) — Tuple oftorch.Tensor(one for each sparse layer) of shape(batch_size * sequence_length, num_experts).Raw router logits computed by the MoE routers. They can be used to compute a load-balancing loss or to inspect how tokens are dispatched to experts.
cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
cacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.Tensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.Tensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple(torch.Tensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Example:
>>> from transformers import AutoTokenizer, Qwen4MoeForCausalLM
>>> checkpoint = "Qwen/Qwen4"
>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
>>> model = Qwen4MoeForCausalLM.from_pretrained(checkpoint, device_map="auto")
>>> inputs = tokenizer("Hello", return_tensors="pt").to(model.device)
>>> logits = model(**inputs).logitsQwen4MoeForConditionalGeneration
class transformers.Qwen4MoeForConditionalGeneration
< source >( config: Qwen4MoeConfig )
Parameters
- config (Qwen4MoeConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The Qwen4 Moe Model for token generation conditioned on other modalities (e.g. image-text-to-text generation).
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Nonevideo_grid_thw: typing.Optional[torch.LongTensor] = Nonemm_token_type_ids: typing.Optional[torch.IntTensor] = Noneoutput_router_logits: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Qwen4MoeCausalLMOutputWithPast or tuple(torch.Tensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — 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 thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 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]. - pixel_values (
torch.Tensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained usingimage_processor_class. Seeimage_processor_class.__call__for details (processor_classusesimage_processor_classfor processing images). - pixel_values_videos (
torch.Tensorof shape(batch_size, num_frames, num_channels, frame_size, frame_size), optional) — The tensors corresponding to the input video. Pixel values for videos can be obtained usingvideo_processor_class. Seevideo_processor_class.__call__for details (processor_classusesvideo_processor_classfor processing videos). - image_grid_thw (
torch.LongTensorof shape(num_images, 3), optional) — The temporal, height and width of feature shape of each image in LLM. - video_grid_thw (
torch.LongTensorof shape(num_videos, 3), optional) — The temporal, height and width of feature shape of each video in LLM. - mm_token_type_ids (
torch.IntTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens matching each modality. For example text (0), image (1), video (2). Multimodal token type ids can be obtained using AutoProcessor. See ProcessorMixin.call() for details. - output_router_logits (
bool, optional) — Whether or not to return the logits of all the routers. They are useful for computing the router loss, and should not be returned during inference. - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length). - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], optional) — Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple that consists of (pooler_output, optional:last_hidden_states, optional:hidden_states, optional:attentions)pooler_outputof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of multimmodal features of the encoder merged into text embeddings.
Returns
Qwen4MoeCausalLMOutputWithPast or tuple(torch.Tensor)
A Qwen4MoeCausalLMOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Qwen4MoeForConditionalGeneration forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
- loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss (for next-token prediction). - aux_loss (
torch.Tensor, optional, returned whenoutput_router_logits=Trueis passed or whenconfig.output_router_logits=True, and the model trains its router with a load-balancing loss) — Load-balancing auxiliary loss for the sparse modules. Models that balance their experts with a router bias instead (DeepSeek-V3 and the architectures derived from it) returnNonehere while still returningrouter_logits. - logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide. Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally ifconfig.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding. - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size). Hidden-states of the language model backbone at the output of each layer plus the optional initial embedding outputs. - attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length). Attention weights of the language model backbone, after the attention softmax. - router_logits (
tuple(torch.Tensor), optional, returned whenoutput_router_logits=Trueis passed or whenconfig.output_router_logits=True) — Tuple oftorch.Tensor(one for each sparse layer) of shape(batch_size * sequence_length, num_experts). Raw router logits computed by the MoE routers. They can be used to compute a load-balancing loss or to inspect how tokens are dispatched to experts. - image_outputs (
BaseModelOutputWithPooling, optional) — Output of the image encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no images were processed. - video_outputs (
BaseModelOutputWithPooling, optional) — Output of the video encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no videos were processed. - audio_outputs (
BaseModelOutputWithPooling, optional) — Output of the audio encoder:last_hidden_state,pooler_output,hidden_statesandattentions.Noneif no audio was processed.
Example:
>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen4MoeForConditionalGeneration
>>> checkpoint = "Qwen/Qwen4"
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> model = Qwen4MoeForConditionalGeneration.from_pretrained(checkpoint, device_map="auto")
>>> image = Image.new("RGB", (224, 224), "red")
>>> content = [{"type": "image", "image": image}, {"type": "text", "text": "What color is the image?"}]
>>> inputs = processor.apply_chat_template(
... [{"role": "user", "content": content}], tokenize=True, add_generation_prompt=True,
... return_dict=True, return_tensors="pt",
... ).to(model.device)
>>> logits = model(**inputs).logits