Transformers 文档

Qwen2MoE

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2024-07-15 发布,并于 2024-03-27 添加到 Hugging Face Transformers。

PyTorch FlashAttention SDPA Tensor parallelism

Qwen2MoE

Qwen2MoEQwen2 的一个专家混合(MoE)变体,提供基础模型和对齐的聊天模型。它使用 SwiGLU 激活、分组查询注意力以及滑动窗口注意力和全注意力混合。分词器还可以适应多种语言和代码。

MoE 架构使用了来自密集语言模型的“升级”模型。例如,Qwen1.5-MoE-A2.7B 是从 Qwen-1.8B 升级而来。它有 143 亿参数,但在运行时只有 27 亿参数被激活。

您可以在 Qwen1.5 集合中找到所有原始的检查点。

点击侧边栏右侧的 Qwen2MoE 模型,了解更多如何将 Qwen2MoE 应用于不同语言任务的示例。

以下示例展示了如何使用 PipelineAutoModel 和命令行生成文本。

流水线
自动模型
Transformers CLI
import torch
from transformers import pipeline

pipe = pipeline(
    task="text-generation",
    model="Qwen/Qwen1.5-MoE-A2.7B",
    dtype=torch.bfloat16,
    device_map=0
)

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Tell me about the Qwen2 model family."},
]
outputs = pipe(messages, max_new_tokens=256, do_sample=True, temperature=0.7, top_k=50, top_p=0.95)
print(outputs[0]["generated_text"][-1]['content'])

量化通过以较低精度表示权重来减少大型模型的内存负担。有关更多可用量化后端,请参阅量化概述。

下面的示例使用 bitsandbytes 将权重量化到 8 位。

# pip install -U flash-attn --no-build-isolation
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(
    load_in_8bit=True
)

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B-Chat")
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen1.5-MoE-A2.7B-Chat",
    dtype=torch.bfloat16,
    device_map="auto",
    quantization_config=quantization_config,
    attn_implementation="flash_attention_2"
)

inputs = tokenizer("The Qwen2 model family is", return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=100)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

Qwen2MoeConfig

class transformers.Qwen2MoeConfig

< >

( vocab_size: int | None = 151936 hidden_size: int | None = 2048 intermediate_size: int | None = 5632 num_hidden_layers: int | None = 24 num_attention_heads: int | None = 16 num_key_value_heads: int | None = 16 hidden_act: str | None = 'silu' max_position_embeddings: int | None = 32768 initializer_range: float | None = 0.02 rms_norm_eps: int | None = 1e-06 use_cache: bool | None = True tie_word_embeddings: bool | None = False rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict[str, transformers.modeling_rope_utils.RopeParameters] | None = None use_sliding_window: bool | None = False sliding_window: int | None = 4096 max_window_layers: int | None = 28 attention_dropout: float | None = 0.0 decoder_sparse_step: int | None = 1 moe_intermediate_size: int | None = 1408 shared_expert_intermediate_size: int | None = 5632 num_experts_per_tok: int | None = 4 num_experts: int | None = 60 norm_topk_prob: bool | None = False output_router_logits: bool | None = False router_aux_loss_coef: float | None = 0.001 mlp_only_layers: bool | None = None qkv_bias: bool | None = True layer_types: list[str] | None = None pad_token_id: int | None = None bos_token_id: int | None = None eos_token_id: int | None = None **kwargs )

参数

  • vocab_size (int, optional, defaults to 151936) — Qwen2MoE 模型的词汇表大小。定义传递给 Qwen2MoeModelinputs_ids 时可以表示的不同 token 的数量。
  • hidden_size (int, optional, defaults to 2048) — 隐藏表示的维度。
  • intermediate_size (int, optional, defaults to 5632) — MLP 表示的维度。
  • num_hidden_layers (int, optional, defaults to 24) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 16) — Transformer 编码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, optional, defaults to 16) — 这是实现分组查询注意力(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 头应通过对该分组内的所有原始头进行平均池化来构建。更多细节请参见 这篇论文。如果未指定,将默认为 32
  • hidden_act (strfunction, optional, defaults to "silu") — 解码器中的非线性激活函数(函数或字符串)。
  • max_position_embeddings (int, optional, defaults to 32768) — 该模型可能使用的最大序列长度。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的截断正态分布(truncated_normal_initializer)的标准差。
  • rms_norm_eps (float, optional, defaults to 1e-06) — rms 归一化层使用的 epsilon。
  • use_cache (bool, optional, defaults to True) — 模型是否应返回最后一个 key/values 注意力(并非所有模型都使用)。仅当 config.is_decoder=True 时相关。
  • tie_word_embeddings (bool, optional, defaults to False) — 模型输入的词嵌入和输出的词嵌入是否应该被绑定。
  • rope_parameters (RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。字典应包含 rope_theta 的值,并且在您想将 RoPE 与更长的 max_position_embeddings 一起使用时,可选地包含用于缩放的参数。
  • use_sliding_window (bool, optional, defaults to False) — 是否使用滑动窗口注意力。
  • sliding_window (int, optional, defaults to 4096) — 滑动窗口注意力 (SWA) 的窗口大小。如果未指定,则默认为 4096
  • max_window_layers (int, optional, defaults to 28) — 使用全注意力的层数。前 max_window_layers 层将使用全注意力,而之后的任何附加层将使用 SWA(滑动窗口注意力)。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力概率的 dropout 比率。
  • decoder_sparse_step (int, optional, defaults to 1) — MoE 层的频率。
  • moe_intermediate_size (int, optional, defaults to 1408) — 路由专家 (routed expert) 的中间大小。
  • shared_expert_intermediate_size (int, optional, defaults to 5632) — 共享专家 (shared expert) 的中间大小。
  • num_experts_per_tok (int, optional, defaults to 4) — 选择的专家数量。
  • num_experts (int, optional, defaults to 60) — 路由专家 (routed experts) 的数量。
  • norm_topk_prob (bool, optional, defaults to False) — 是否对 topk 概率进行归一化。
  • output_router_logits (bool, optional, defaults to False) — 模型是否应返回路由器的 logits。启用此选项还将允许模型输出辅助损失,包括负载均衡损失和路由器 z-loss。
  • router_aux_loss_coef (float, optional, defaults to 0.001) — 总损失的辅助损失系数。
  • mlp_only_layers (list[int], 可选, 默认 []) — 指示哪些层使用 Qwen2MoeMLP 而不是 Qwen2MoeSparseMoeBlock。列表包含层索引,从 0 到 num_layers-1(如果 num_layers 层)。如果 mlp_only_layers 为空,则使用 decoder_sparse_step 来确定稀疏性。
  • qkv_bias (bool, 可选, 默认 True) — 是否为 queries, keys 和 values 添加偏置。
  • layer_types (dict[int, str], 可选) — 一个字典,显式地将层索引与注意力类型进行映射。注意力类型是 sliding_attentionfull_attention 之一。
  • pad_token_id (int, 可选) — 填充 token ID。
  • bos_token_id (int, 可选) — 开始流 token ID。
  • eos_token_id (int, 可选) — 结束流 token ID。

这是用于存储 Qwen2MoeModel 配置的配置类。它用于根据指定的参数实例化一个 Qwen2MoE 模型,定义了模型的架构。实例化一个具有默认值的配置将产生一个与 Qwen/Qwen1.5-MoE-A2.7B 类似的配置。

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

>>> from transformers import Qwen2MoeModel, Qwen2MoeConfig

>>> # Initializing a Qwen2MoE style configuration
>>> configuration = Qwen2MoeConfig()

>>> # Initializing a model from the Qwen1.5-MoE-A2.7B" style configuration
>>> model = Qwen2MoeModel(configuration)

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

Qwen2MoeModel

class transformers.Qwen2MoeModel

< >

( config: Qwen2MoeConfig )

参数

  • config (Qwen2MoeConfig) — 带有模型所有参数的配置类。使用配置文件初始化不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。

没有经过任何特定头部处理的原始 Qwen2 Moe 模型,直接输出原始隐藏状态。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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 use_cache: bool | None = None cache_position: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.MoeModelOutputWithPasttuple(torch.FloatTensor)

参数

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

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

    什么是 input IDs?

  • attention_mask (torch.Tensor, 形状为 (batch_size, sequence_length), 可选) — 用于避免对填充 token 索引执行 attention 的掩码。掩码值选择在 [0, 1] 中:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

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

    什么是 position IDs?

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

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

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

    如果使用了 past_key_values,则用户应只输入未处理的 input_ids(即没有将其 past key value 状态传递给此模型的那些),形状为 (batch_size, unprocessed_length),而不是所有 input_ids,其形状为 (batch_size, sequence_length)

  • inputs_embeds (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以直接传入嵌入表示,而不是传入 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量的控制程度高于模型的内部嵌入查找矩阵,这会很有用。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • cache_position (torch.LongTensor, 形状为 (sequence_length), 可选) — 描绘输入序列 token 在序列中位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新 cache 并推断完整序列长度。

返回

transformers.modeling_outputs.MoeModelOutputWithPasttuple(torch.FloatTensor)

transformers.modeling_outputs.MoeModelOutputWithPasttorch.FloatTensor 的元组(如果传入 return_dict=False 或当 config.return_dict=False 时),根据配置(Qwen2MoeConfig)和输入包含各种元素。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, sequence_length, 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=True in the cross-attention blocks) that can be used (see past_key_values input) 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 后的注意力权重,用于计算自注意力头中的加权平均值。

  • router_logits (tuple(torch.FloatTensor), 可选, 当传递 output_router_probs=Trueconfig.add_router_probs=True 时,或 config.output_router_probs=True 时返回) — 形状为 (batch_size, sequence_length, num_experts)torch.FloatTensor 元组(每一层一个)。

    由 MoE 路由器计算的原始路由器对数(softmax 后),这些术语用于计算专家混合模型的辅助损失。

transformers.Qwen2MoeModel 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

Qwen2MoeForCausalLM

class transformers.Qwen2MoeForCausalLM

< >

( 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 (Qwen2MoeForCausalLM) — 带有模型所有参数的配置类。使用配置文件初始化不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。

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

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( 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 output_router_logits: 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.MoeCausalLMOutputWithPasttuple(torch.FloatTensor)

参数

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

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

    什么是 input IDs?

  • attention_mask (torch.Tensor, 形状为 (batch_size, sequence_length), 可选) — 用于避免对填充 token 索引执行 attention 的掩码。掩码值选择在 [0, 1] 中:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

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

    什么是位置 ID?

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

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

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

    如果使用 past_key_values,用户应只输入未处理的 input_ids(即尚未获得其 past key value 状态的 input_ids),其形状为 (batch_size, unprocessed_length),而不是所有 input_ids,其形状为 (batch_size, sequence_length)

  • inputs_embeds (torch.FloatTensor, 形状为 (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。它们对于计算路由器损失很有用,在推理期间不应返回。
  • cache_position (torch.LongTensor, 形状为 (sequence_length), 可选) — 描述输入序列 token 在序列中位置的索引。与 position_ids 不同,此张量不受填充的影响。它用于在正确的位置更新缓存并推断完整的序列长度。
  • logits_to_keep (Union[int, torch.Tensor], 可选, 默认值为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。仅生成需要最后一个 token 的 logits,并且仅为该 token 计算 logits 可以节省内存,这对于长序列或大词汇量来说非常显著。如果为 torch.Tensor,则必须是 1D 的,对应于序列长度维度中要保留的索引。这在使用打包张量格式(批处理和序列长度的单维度)时很有用。

返回

transformers.modeling_outputs.MoeCausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.modeling_outputs.MoeCausalLMOutputWithPast 对象,或者一个 torch.FloatTensor 的元组(如果传入了 return_dict=False 或当 config.return_dict=False 时),其中包含各种元素,具体取决于配置(Qwen2MoeConfig)和输入。

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

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

  • aux_loss (torch.FloatTensor可选,当提供 labels 时返回) — 稀疏模块的辅助损失。

  • router_logits (tuple(torch.FloatTensor), 可选, 当传递 output_router_probs=Trueconfig.add_router_probs=True 时,或 config.output_router_probs=True 时返回) — 形状为 (batch_size, sequence_length, num_experts)torch.FloatTensor 元组(每一层一个)。

    由 MoE 路由器计算的原始路由器对数(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 后的注意力权重,用于计算自注意力头中的加权平均值。

transformers.Qwen2MoeForCausalLM 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, Qwen2MoeForCausalLM

>>> model = Qwen2MoeForCausalLM.from_pretrained("mistralai/Qwen2Moe-8x7B-v0.1")
>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Qwen2Moe-8x7B-v0.1")

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

Qwen2MoeForSequenceClassification

class transformers.Qwen2MoeForSequenceClassification

< >

( config )

forward

< >

( 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.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor, 形状为 (batch_size, sequence_length), 可选) — 词汇表中输入序列 token 的索引。默认会忽略填充。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor, 形状为 (batch_size, sequence_length), 可选) — 用于避免对填充 token 索引执行注意力操作的掩码。掩码值选择在 [0, 1] 之间:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

    如果使用 past_key_values,用户应只输入未处理的 input_ids(即尚未获得其 past key value 状态的 input_ids),其形状为 (batch_size, unprocessed_length),而不是所有 input_ids,其形状为 (batch_size, sequence_length)

  • inputs_embeds (torch.FloatTensor, 形状为 (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)。

返回

transformers.modeling_outputs.SequenceClassifierOutputWithPasttuple(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 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

Qwen2MoeForTokenClassification

class transformers.Qwen2MoeForTokenClassification

< >

( config )

forward

< >

( 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.TokenClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor, 形状为 (batch_size, sequence_length), 可选) — 词汇表中输入序列 token 的索引。默认会忽略填充。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor, 形状为 (batch_size, sequence_length), 可选) — 用于避免对填充 token 索引执行注意力操作的掩码。掩码值选择在 [0, 1] 之间:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是注意力掩码?

  • position_ids (torch.LongTensor of 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].

    位置ID是什么?

  • 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 the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (torch.LongTensor of 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 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

A transformers.modeling_outputs.TokenClassifierOutput 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 时返回) — 分类损失。

  • logits (形状为 (batch_size, sequence_length, config.num_labels)torch.FloatTensor) — 分类分数(SoftMax 之前)。

  • 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 GenericForTokenClassification forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

Qwen2MoeForQuestionAnswering

class transformers.Qwen2MoeForQuestionAnswering

< >

( config )

forward

< >

( 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 start_positions: torch.LongTensor | None = None end_positions: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.QuestionAnsweringModelOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of 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.

    输入ID是什么?

  • attention_mask (torch.Tensor of 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.LongTensor of 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].

    位置ID是什么?

  • 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 the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • start_positions (torch.LongTensor of shape (batch_size,), optional) — Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
  • end_positions (torch.LongTensor of shape (batch_size,), optional) — Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

A transformers.modeling_outputs.QuestionAnsweringModelOutput 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 (torch.FloatTensor of shape (1,), 可选, 当提供 labels 时返回) — 总范围提取损失是起始位置和结束位置的交叉熵之和。

  • start_logits (torch.FloatTensor of shape (batch_size, sequence_length)) — 范围起始分数(SoftMax 之前)。

  • end_logits (torch.FloatTensor of shape (batch_size, sequence_length)) — 范围结束分数(SoftMax 之前)。

  • 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 GenericForQuestionAnswering forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.