Transformers 文档
HunYuanMoEV1
并获得增强的文档体验
开始使用
该模型于 {release_date} 发布,并于 2025-08-22 添加到 Hugging Face Transformers。
HunYuanMoEV1
概述
将与官方模型发布一同推出。
模型详情
将与官方模型发布一同推出。
使用技巧
将与官方模型发布一同推出。
HunYuanMoEV1Config
class transformers.HunYuanMoEV1Config
< source >( vocab_size: int | None = 290943 hidden_size: int | None = 4096 intermediate_size: int | None = 11008 num_hidden_layers: int | None = 32 num_attention_heads: int | None = 32 num_key_value_heads: int | None = None hidden_act: str | None = 'silu' max_position_embeddings: int | None = 2048 initializer_range: float | None = 0.02 rms_norm_eps: float | None = 1e-05 use_cache: bool | None = True pad_token_id: int | None = 0 bos_token_id: int | None = 1 eos_token_id: int | None = 2 eod_token_id: int | None = 3 sep_token_id: int | None = 4 pretraining_tp: int | None = 1 tie_word_embeddings: bool | None = False rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict[str, transformers.modeling_rope_utils.RopeParameters] | None = None attention_bias: bool | None = False attention_dropout: float | None = 0.0 num_experts: int | list = 1 moe_topk: int | list = 1 head_dim: int | None = None **kwargs )
参数
- vocab_size (
int, optional, defaults to 290943) — HunYuan 模型词汇量。定义通过调用 HunYuanMoEV1Model 传递的inputs_ids可以表示的不同 token 的数量。 - hidden_size (
int, optional, defaults to 4096) — 隐藏表示的维度。 - intermediate_size (
int, optional, defaults to 11008) — MLP 表示或共享 MLP 表示的维度。 - num_hidden_layers (
int, optional, defaults to 32) — Transformer decoder中的隐藏层数量。 - num_attention_heads (
int, optional, defaults to 32) — Transformer decoder中的每个注意力层的注意力头数量。 - num_key_value_heads (
int, optional) — 这是实现分组查询注意力(Grouped Query Attention)所需的 key_value 头的数量。如果num_key_value_heads=num_attention_heads,则模型将使用多头注意力 (MHA);如果num_key_value_heads=1,则模型将使用多查询注意力 (MQA);否则使用 GQA。将多头检查点转换为 GQA 检查点时,应通过平均池化组内所有原始头来构造每个组的键和值头。有关更多详细信息,请参阅 [此论文](https://huggingface.co/papers/2305.13245)。如果未指定,则默认为num_attention_heads。 - hidden_act (
str或function, optional, defaults to"silu") — 解码器中的非线性激活函数(函数或字符串)。 - max_position_embeddings (
int, optional, defaults to 2048) — 该模型可能使用的最大序列长度。 - initializer_range (
float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - rms_norm_eps (
float, optional, defaults to 1e-05) — rms 归一化层使用的 epsilon。 - use_cache (
bool, optional, defaults toTrue) — 是否应该返回最后一个键/值注意力(并非所有模型都使用)。仅当config.is_decoder=True时相关。 - pad_token_id (
int, optional, defaults to 0) — 填充 token ID。 - bos_token_id (
int, optional, defaults to 1) — 开始流 token ID。 - eos_token_id (
int, optional, defaults to 2) — 结束流 token ID。 - eod_token_id (int, optional, defaults to 3) — 表示文档结束标记的 token ID。用于指示文本序列的终止。例如:在多文档处理中,此 token 帮助模型区分不同的文档。
- sep_token_id (
int, optional, defaults to 4) — 分隔符 token ([SEP]) 的 ID,用于分隔不同文本段落的边界。 - pretraining_tp (
int, optional, defaults to 1) — 实验性功能。预训练期间使用的张量并行等级。请参考 [此文档](https://huggingface.co/docs/transformers/parallelism) 了解更多关于它的信息。此值对于确保预训练结果的精确可复现性是必要的。请参考 [此 issue](https://github.com/pytorch/pytorch/issues/76232)。 - tie_word_embeddings (
bool, optional, defaults toFalse) — 是否绑定词嵌入权重 - rope_parameters (
RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,以及在希望使用更长的max_position_embeddings来使用 RoPE 时用于缩放的可选参数。 - attention_bias (
bool, defaults toFalse, optional, defaults toFalse) — 在自注意力过程中是否在查询、键、值和输出投影层中使用偏置。 - attention_dropout (
float, optional, defaults to 0.0) — 注意力概率的 dropout 比率。 - num_experts (
int或List, optional, defaults to 1) — moe 的专家数量。如果它是列表,它将用作每个层的专家数量。 - moe_topk (int 或 List, optional, defaults to 1) — 每个 token 选择的专家数量(Top-K 路由)。列表形式允许按层定制。
- head_dim (
int, optional, defaults to 128) — 注意力头的维度。
这是用于存储 HunYuanMoEV1Model 配置的配置类。它用于根据指定的参数实例化一个 HunYuan 模型,定义了模型的架构。使用默认值实例化配置将产生一个与 HunYuan-7B 类似的配置。Hunyuan-A13B-Instruct tencent/Hunyuan-A13B-Instruct。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。
HunYuanMoEV1Model
class transformers.HunYuanMoEV1Model
< source >( config: HunYuanMoEV1Config )
参数
- config (HunYuanMoEV1Config) — 模型配置类,包含模型的所有参数。使用配置文件初始化模型不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
The bare Hunyuan V1 Moe Model outputting raw hidden-states without any specific head on top。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None cache_position: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.BaseModelOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引进行 attention 计算的掩码。掩码值选择在[0, 1]中:- 1 表示未掩码的 token,
- 0 表示已掩码的 token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列 token 在位置 embedding 中的索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 可用于加速序列解码的预计算隐藏状态(自注意力块和交叉注意力块中的键和值)。这通常由模型在先前解码阶段返回的past_key_values组成,当use_cache=True或config.use_cache=True时。只允许 Cache 实例作为输入,请参阅我们的 kv cache 指南。如果未传入
past_key_values,则默认初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,则用户应仅输入未处理的input_ids(其 past key value 状态未提供给此模型)形状为(batch_size, unprocessed_length),而不是所有input_ids形状为(batch_size, sequence_length)。 - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选,您也可以直接传入 embedding 表示,而不是传入input_ids。如果您希望比模型内部的 embedding 查找矩阵拥有更多控制权来将input_ids索引转换为相关的向量,这将非常有用。 - cache_position (
torch.LongTensorof shape(sequence_length), optional) — 用于描述输入序列 token 在序列中位置的索引。与position_ids相反,此张量不受填充的影响。它用于在正确的位置更新缓存并推断完整的序列长度。 - use_cache (
bool, optional) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(请参阅past_key_values)。
返回
transformers.modeling_outputs.BaseModelOutputWithPast or tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPast 或一个 torch.FloatTensor 元组(如果传入了 return_dict=False 或当 config.return_dict=False 时),根据配置(HunYuanMoEV1Config)和输入包含各种元素。
-
last_hidden_state (
torch.FloatTensor, 形状为(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。如果使用了
past_key_values,则只输出形状为(batch_size, 1, hidden_size)的序列的最后一个隐藏状态。 -
past_key_values (
Cache, optional, 当传递use_cache=True或当config.use_cache=True时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南。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 (seepast_key_valuesinput) to speed up sequential decoding. -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
transformers.HunYuanMoEV1Model 的 forward 方法,覆盖了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
HunYuanMoEV1ForCausalLM
class transformers.HunYuanMoEV1ForCausalLM
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (HunYuanMoEV1ForCausalLM) — 模型配置类,包含模型的所有参数。使用配置文件初始化模型不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
Hunyuan V1 Moe Model for causal language modeling。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引进行 attention 计算的掩码。掩码值选择在[0, 1]中:- 1 表示未掩码的 token,
- 0 表示已掩码的 token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列 token 在位置 embedding 中的索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 可用于加速序列解码的预计算隐藏状态(自注意力块和交叉注意力块中的键和值)。这通常由模型在先前解码阶段返回的past_key_values组成,当use_cache=True或config.use_cache=True时。只允许 Cache 实例作为输入,请参阅我们的 kv cache 指南。如果未传入
past_key_values,则默认初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,则用户应仅输入未处理的input_ids(其 past key value 状态未提供给此模型)形状为(batch_size, unprocessed_length),而不是所有input_ids形状为(batch_size, sequence_length)。 - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选,您也可以直接传入 embedding 表示,而不是传入input_ids。如果您希望比模型内部的 embedding 查找矩阵拥有更多控制权来将input_ids索引转换为相关的向量,这将非常有用。 - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 用于计算掩码语言模型损失的标签。索引应在[0, ..., config.vocab_size]或 -100 范围内(请参阅input_ids文档字符串)。索引设置为-100的 token 将被忽略(掩码),损失仅为标签在[0, ..., config.vocab_size]范围内的 token 计算。 - use_cache (
bool, optional) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(请参阅past_key_values)。 - cache_position (
torch.LongTensorof shape(sequence_length), optional) — 用于描述输入序列 token 在序列中位置的索引。与position_ids相反,此张量不受填充的影响。它用于在正确的位置更新缓存并推断完整的序列长度。 - 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).
返回
transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)
A transformers.modeling_outputs.CausalLMOutputWithPast or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (HunYuanMoEV1Config) and inputs.
-
loss (
torch.FloatTensor形状为(1,),可选,当提供labels时返回) — 语言建模损失(用于下一个 token 预测)。 -
logits (形状为
(batch_size, sequence_length, config.vocab_size)的torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values (
Cache, optional, 当传递use_cache=True或当config.use_cache=True时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The HunYuanMoEV1ForCausalLM forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, HunYuanMoEV1ForCausalLM
>>> model = HunYuanMoEV1ForCausalLM.from_pretrained("meta-hunyuan_v1_moe/HunYuanMoEV1-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-hunyuan_v1_moe/HunYuanMoEV1-2-7b-hf")
>>> 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."HunYuanMoEV1ForSequenceClassification
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.SequenceClassifierOutputWithPast or tuple(torch.FloatTensor)
参数
- 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]. - past_key_values (
~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 thepast_key_valuesreturned 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
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare 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.FloatTensorof 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]. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values).
返回
transformers.modeling_outputs.SequenceClassifierOutputWithPast 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.SequenceClassifierOutputWithPast or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (None) and inputs.
-
loss (形状为
(1,)的torch.FloatTensor,可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
logits (形状为
(batch_size, config.num_labels)的torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。 -
past_key_values (
Cache, optional, 当传递use_cache=True或当config.use_cache=True时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The GenericForSequenceClassification forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。