Transformers 文档
GraniteMoeShared
并获得增强的文档体验
开始使用
此模型于 2024-08-23 发布,并于 2025-02-14 添加到 Hugging Face Transformers。
GraniteMoeShared
概述
GraniteMoe 模型在 Power Scheduler: A Batch Size and Token Number Agnostic Learning Rate Scheduler 中提出,作者是 Yikang Shen、Matthew Stallone、Mayank Mishra、Gaoyuan Zhang、Shawn Tan、Aditya Prasad、Adriana Meza Soria、David D. Cox 和 Rameswar Panda。
此外,GraniteMoeSharedModel 类为 Moe 添加了共享专家。
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_path = "ibm-research/moe-7b-1b-active-shared-experts"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto")
model.eval()
# change input text as desired
prompt = "Write a code to find the maximum value in a list of numbers."
# tokenize the text
input_tokens = tokenizer(prompt, return_tensors="pt")
# generate output tokens
output = model.generate(**input_tokens, max_new_tokens=100)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# loop over the batch to print, in this example the batch size is 1
for i in output:
print(i)此 Hugging Face 实现由 Mayank Mishra、Shawn Tan 和 Sukriti Sharma 贡献。
GraniteMoeSharedConfig
( vocab_size: int | None = 32000 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: int | None = 1e-06 use_cache: bool | None = True pad_token_id: int | None = None bos_token_id: int | None = 1 eos_token_id: int | None = 2 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 embedding_multiplier: float | None = 1.0 logits_scaling: float | None = 1.0 residual_multiplier: float | None = 1.0 attention_multiplier: float | None = 1.0 num_local_experts: int | None = 8 num_experts_per_tok: int | None = 2 output_router_logits: bool | None = False router_aux_loss_coef: float | None = 0.001 shared_intermediate_size: int | None = 0 **kwargs )
参数
- vocab_size (
int, optional, defaults to 32000) — GraniteMoeShared 模型的词汇表大小。定义通过调用 GraniteMoeSharedModel 传递的inputs_ids所能表示的不同 token 的数量。 - hidden_size (
int, optional, defaults to 4096) — 隐藏表示的维度。 - intermediate_size (
int, optional, defaults to 11008) — MLP 表示的维度。 - num_hidden_layers (
int, optional, defaults to 32) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int, optional, defaults to 32) — Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, optional) — 这是实现分组查询注意力所需的 key_value 头数。如果num_key_value_heads=num_attention_heads,模型将使用多头注意力 (MHA);如果num_key_value_heads=1,模型将使用多查询注意力 (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的键和值头应通过平均池化组内的所有原始头来构建。有关更多详细信息,请参阅 此论文。如果未指定,则默认为num_attention_heads。 - hidden_act (
strorfunction, optional, defaults to"silu") — 解码器中的非线性激活函数(函数或字符串)。 - max_position_embeddings (
int, optional, defaults to 2048) — 此模型可能使用的最大序列长度。 - initializer_range (
float, optional, defaults to 0.02) — 初始化所有权重矩阵的截断正态分布初始化的标准差。 - rms_norm_eps (
float, optional, defaults to 1e-06) — RMS 归一化层使用的 epsilon。 - use_cache (
bool, optional, defaults toTrue) — 是否应返回模型最后生成的键/值注意力(并非所有模型都使用)。仅在config.is_decoder=True时相关。 - pad_token_id (
int, optional) — 填充 token ID。 - bos_token_id (
int, optional, defaults to 1) — 开始流 token ID。 - eos_token_id (
int, optional, defaults to 2) — 结束流 token ID。 - tie_word_embeddings (
bool, optional, defaults toFalse) — 是否绑定词嵌入 - rope_parameters (
RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。字典应包含rope_theta的值,以及用于在希望使用更长的max_position_embeddings时进行缩放的参数。 - attention_bias (
bool, optional, defaults toFalse) — 是否在自注意力过程中使用查询、键、值和输出投影层的偏置。 - attention_dropout (
float, optional, defaults to 0.0) — 注意力概率的 dropout 比率。 - embedding_multiplier (
float, optional, defaults to 1.0) — embedding 乘数 - logits_scaling (
float, optional, defaults to 1.0) — 输出 logits 的除数 - residual_multiplier (
float, optional, defaults to 1.0) — residual multiplier - attention_multiplier (
float, optional, defaults to 1.0) — attention multiplier - num_local_experts (
int, optional, defaults to 8) — total number of experts - num_experts_per_tok (
int, optional, defaults to 2) — number of experts per token - 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. - router_aux_loss_coef (
float, optional, defaults to 0.001) — router auxiliary loss coefficient - shared_intermediate_size (
int, optional, defaults to 0) — intermediate size for shared experts. 0 implies no shared experts.
This is the configuration class to store the configuration of a GraniteMoeSharedModel. It is used to instantiate an GraniteMoeShared 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 ibm-research/moe-7b-1b-active-shared-experts.
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。
>>> from transformers import GraniteMoeSharedModel, GraniteMoeSharedConfig
>>> # Initializing a GraniteMoeShared granitemoe-3b style configuration
>>> configuration = GraniteMoeSharedConfig()
>>> # Initializing a model from the granitemoe-7b style configuration
>>> model = GraniteMoeSharedModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configGraniteMoeSharedModel
( config: GraniteMoeSharedConfig )
参数
- config (GraniteMoeSharedConfig) — 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 Granitemoeshared Model outputting raw hidden-states without any specific head on top.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
( 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.MoeModelOutputWithPast 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. - 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). - cache_position (
torch.LongTensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
A transformers.modeling_outputs.MoeModelOutputWithPast 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 (GraniteMoeSharedConfig) and inputs.
-
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=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 后的注意力权重,用于计算自注意力头中的加权平均值。
-
router_logits (
tuple(torch.FloatTensor), 可选, 当传递output_router_probs=True且config.add_router_probs=True时,或config.output_router_probs=True时返回) — 形状为(batch_size, sequence_length, num_experts)的torch.FloatTensor元组(每一层一个)。由 MoE 路由器计算的原始路由器对数(softmax 后),这些术语用于计算专家混合模型的辅助损失。
The GraniteMoeSharedModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
GraniteMoeSharedForCausalLM
( config: GraniteMoeSharedConfig )
参数
- config (GraniteMoeSharedConfig) — 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 Granitemoeshared Model for causal language modeling.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
( 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 output_router_logits: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) → transformers.modeling_outputs.MoeCausalLMOutputWithPast or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor, 形状为(batch_size, sequence_length), 可选) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。索引可以通过 AutoTokenizer 获取。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor, 形状为(batch_size, sequence_length), 可选) — 用于避免对填充 token 索引执行 attention 的掩码。掩码值选择在[0, 1]中:- 1 表示 **未掩码** 的 token,
- 0 表示 **已掩码** 的 token。
- position_ids (
torch.LongTensor, 形状为(batch_size, sequence_length), 可选) — 输入序列 token 在位置嵌入中的位置索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速序列解码。这通常包括在使用use_cache=True或config.use_cache=True时,在解码的先前阶段由模型返回的past_key_values。仅允许 Cache 实例作为输入,请参阅我们的 kv 缓存指南。如果未传入
past_key_values,则默认初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,则用户应仅输入未处理的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 计算。 - 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 计算它们可以节省内存,这对于长序列或大词汇量来说非常可观。如果为torch.Tensor,则必须是 1D 的,对应于序列长度维度中要保留的索引。这在使用打包张量格式(批处理和序列长度的单维度)时很有用。
根据配置(None)和输入,transformers.modeling_outputs.MoeCausalLMOutputWithPast 或 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时)。
-
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=True且config.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 后的注意力权重,用于计算自注意力头中的加权平均值。
GraniteMoeSharedForCausalLM 的 forward 方法重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, GraniteMoeSharedForCausalLM
>>> model = GraniteMoeSharedForCausalLM.from_pretrained("ibm/PowerMoE-3b")
>>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")
>>> 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."