Transformers 文档
Bamba
并获得增强的文档体验
开始使用
该模型于 2024-12-18 发布,并于 2024-12-19 添加到 Hugging Face Transformers。
Bamba
Bamba 是一个 9B 参数的 decoder-only 语言模型,基于 Mamba-2 架构构建。它分两个阶段进行预训练——首先在 Dolma v1.7 数据集上的 2T 个 token 上训练,然后在中国 FineWeb 和 Cosmopedia 的另外 200B 个 token 上进行训练。
您可以在 Bamba 集合下找到所有原始 Bamba 检查点。
单击侧边栏右侧的 Bamba 模型,以获取有关如何将 Bamba 应用于不同文本生成任务的更多示例。
以下示例展示了如何使用 Pipeline、AutoModel 和命令行生成文本。
import torch
from transformers import pipeline
pipeline = pipeline(
task="text-generation",
model="ibm-ai-platform/Bamba-9B-v2",
dtype=torch.bfloat16,
device=0
)
pipeline("Plants create energy through a process known as")量化通过以较低精度表示权重来减少大型模型的内存负担。有关更多可用量化后端,请参阅量化概述。
以下示例使用torchao仅将权重量化为int4。
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
quantization_config = TorchAoConfig("int4_weight_only", group_size=128)
tokenizer = AutoTokenizer.from_pretrained("ibm-ai-platform/Bamba-9B-v2")
model = AutoModelForCausalLM.from_pretrained(
"ibm-ai-platform/Bamba-9B-v2",
quantization_config=quantization_config,
device_map="auto",
attn_implementation="sdpa"
)
inputs = tokenizer("Plants create energy through a process known as", return_tensors="pt").to(model.device)
output = model.generate(**inputs)
print(tokenizer.decode(output[0], skip_special_tokens=True))注意事项
Bamba 支持无填充训练,它将不同的训练示例串联起来,同时仍将输入作为单独的批次进行处理。通过 约 2 倍(取决于模型和数据分布)的速度显著加速推理,并通过避免填充 token 造成的不必要计算和内存开销,在示例长度不一时减少内存使用。
无填充训练需要
flash-attn、mamba-ssm和causal-conv1d包,并且除了input_ids和labels之外,还必须将以下参数传递给模型。position_ids: torch.LongTensor:每个序列中每个 token 的位置索引。seq_idx: torch.IntTensor:批次中每个序列的索引。- 每个
FlashAttentionKwargscu_seq_lens_q: torch.LongTensor:所有查询的累积序列长度。cu_seq_lens_k: torch.LongTensor:所有键的累积序列长度。max_length_q: int:批次中最长的查询长度。max_length_k: int:批次中最长的键长度。
不应提供
attention_mask输入。DataCollatorWithFlattening会通过使用return_seq_idx=True和return_flash_attn_kwargs=True来以编程方式生成上述附加参数集。有关更多信息,请参阅 通过 Flash Attention 提高 Hugging Face 训练效率 博客文章。from transformers import DataCollatorWithFlattening # Example of using padding-free training data_collator = DataCollatorWithFlattening( tokenizer=tokenizer, return_seq_idx=True, return_flash_attn_kwargs=True )
BambaConfig
class transformers.BambaConfig
< source >( vocab_size: int | None = 128000 tie_word_embeddings: bool | None = False hidden_size: int | None = 4096 intermediate_size: int | None = 14336 num_hidden_layers: int | None = 32 num_attention_heads: int | None = 32 num_key_value_heads: int | None = 8 hidden_act: str | None = 'silu' initializer_range: float | None = 0.02 rms_norm_eps: float | None = 1e-05 use_cache: bool | None = True num_logits_to_keep: int | None = 1 pad_token_id: int | None = 0 bos_token_id: int | None = 1 eos_token_id: int | None = 2 max_position_embeddings: int | None = 262144 attention_dropout: float | None = 0.0 attn_layer_indices: list[int] | None = None mamba_n_heads: int | None = 128 mamba_d_head: str | None = 'auto' mamba_n_groups: int | None = 1 mamba_d_state: int | None = 256 mamba_d_conv: int | None = 4 mamba_expand: int | None = 2 mamba_chunk_size: int | None = 256 mamba_conv_bias: bool | None = True mamba_proj_bias: bool | None = False time_step_min: float | None = 0.001 time_step_max: float | None = 0.1 time_step_limit: tuple[float, float] | None = (0.0, inf) z_loss_coefficient: float | None = 0.0 rope_parameters: transformers.modeling_rope_utils.RopeParameters | None = None **kwargs )
参数
- vocab_size (
int, optional, defaults to 128000) — Bamba 模型的词汇表大小。定义通过调用 BambaModel 传递的inputs_ids可以表示的不同 token 的数量。 - tie_word_embeddings (
bool, optional, defaults toFalse) — 是否应绑定模型的输入和输出词嵌入。请注意,这仅在模型具有输出词嵌入层时才相关。 - hidden_size (
int, optional, defaults to 4096) — 隐藏表示的维度。 - intermediate_size (
int, optional, defaults to 14336) — 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, defaults to 8) — 这是实现分组查询注意力 (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 检查点时,每个组的键和值头应通过对该组内的所有原始头进行平均池化来构建。有关更多详细信息,请参阅 此论文。如果未指定,则默认为8。 - hidden_act (
strorfunction, optional, defaults to"silu") — 解码器中的非线性激活函数(函数或字符串)。 - initializer_range (
float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - rms_norm_eps (
float, optional, defaults to 1e-05) — rms normalization层使用的 epsilon。 - use_cache (
bool, optional, defaults toTrue) — 模型是否应返回最后一个键/值注意力(并非所有模型都使用)。仅在config.is_decoder=True时相关。 - num_logits_to_keep (
intorNone, optional, defaults to 1) — 生成过程中计算的 prompt logits 的数量。如果为None,将计算所有 logits。如果为整数值,则只计算最后一个num_logits_to_keeplogits。默认值为 1,因为生成只需要最后一个 prompt token 的 logits。对于长序列,整个序列的 logits 可能会占用大量内存,因此将num_logits_to_keep设置为 1 将显著减少内存占用。 - pad_token_id (
int, optional, defaults to 0) — padding token 的 ID。 - bos_token_id (
int, optional, defaults to 1) — “beginning-of-sequence” token 的 ID。 - eos_token_id (
int, optional, defaults to 2) — “end-of-sequence” token 的 ID。 - max_position_embeddings (
int, optional, defaults to 262144) — 模型最大缓存序列长度。 - attention_dropout (
float, optional, defaults to 0.0) — 注意力概率的 dropout 比率。 - attn_layer_indices (
list, optional) — 指定将具有完全注意力的层索引。必须包含小于 num_hidden_layers 的值。 - mamba_n_heads (
int, optional, defaults to 128) — The number of mamba heads used in the v2 implementation. - mamba_d_head (
int, optional, defaults to"auto") — Head embedding dimension size - mamba_n_groups (
int, optional, defaults to 1) — The number of the mamba groups used in the v2 implementation. - mamba_d_state (
int, optional, defaults to 256) — The dimension the mamba state space latents - mamba_d_conv (
int, optional, defaults to 4) — The size of the mamba convolution kernel - mamba_expand (
int, optional, defaults to 2) — Expanding factor (relative to hidden_size) used to determine the mamba intermediate size - mamba_chunk_size (
int, optional, defaults to 256) — The chunks in which to break the sequence when doing prefill/training - mamba_conv_bias (
bool, optional, defaults toTrue) — Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block. - mamba_proj_bias (
bool, optional, defaults toFalse) — Flag indicating whether or not to use bias in the input and output projections ([“in_proj”, “out_proj”]) of the mamba mixer block - time_step_min (
float, optional, defaults to 0.001) — Minimumtime_stepused to bounddt_proj.bias. - time_step_max (
float, optional, defaults to 0.1) — Maximumtime_stepused to bounddt_proj.bias. - time_step_limit (
tuple, optional, defaults to(0.0, inf)) — Accepted range of time step values for clamping. - z_loss_coefficient (
float, optional, defaults to 0.0) — Coefficient for auxiliary z-loss used to control logit growth during training - rope_parameters (
RopeParameters, 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 BambaModel. It is used to instantiate a BambaModel model according to the specified arguments, defining the model architecture. Instantiating a configuration with defaults taken from ibm-fms/Bamba-9.8b-2.2T-hf.
The BambaModel is a hybrid mamba2 architecture with SwiGLU. The checkpoints are jointly trained by IBM, Princeton, and UIUC.
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。
BambaModel
class transformers.BambaModel
< source >( config: BambaConfig )
参数
- config (BambaConfig) — 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 Bamba 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.models.bamba.modeling_bamba.HybridMambaAttentionDynamicCache | None = None inputs_embeds: torch.FloatTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None cache_position: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.models.bamba.modeling_bamba.BambaFlashAttentionKwargs] ) → transformers.modeling_outputs.BaseModelOutputWithPast 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 (
~models.bamba.modeling_bamba.HybridMambaAttentionDynamicCache, 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). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - 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.
返回
transformers.modeling_outputs.BaseModelOutputWithPast or tuple(torch.FloatTensor)
A transformers.modeling_outputs.BaseModelOutputWithPast 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 (BambaConfig) and inputs.
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
The BambaModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
BambaForCausalLM
class transformers.BambaForCausalLM
< 源码 >( 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 (BambaForCausalLM) — 模型配置类,包含模型的所有参数。使用配置文件初始化模型不会加载与模型关联的权重,只会加载配置。查看 from_pretrained() 方法来加载模型权重。
Bamba 模型用于因果语言建模。
此模型继承自 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.models.bamba.modeling_bamba.HybridMambaAttentionDynamicCache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) → transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor, shape(batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。可以通过 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。 - attention_mask (
torch.Tensor, shape(batch_size, sequence_length), optional) — 用于避免在填充 token 索引上进行注意力的掩码。掩码值选择在[0, 1]:- 1 表示未被掩码的 token,
- 0 表示被掩码的 token。
- position_ids (
torch.LongTensor, shape(batch_size, sequence_length), optional) — 输入序列 token 在位置嵌入中的索引。选择范围在[0, config.n_positions - 1]。 - past_key_values (
~models.bamba.modeling_bamba.HybridMambaAttentionDynamicCache, 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.FloatTensor, shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以直接传递嵌入表示,而不是传递input_ids。如果您希望比模型内部的嵌入查找矩阵更精细地控制如何将input_ids索引转换为关联的向量,这将非常有用。 - labels (
torch.LongTensor, 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)。 - output_attentions (
bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回的张量下的attentions。 - output_hidden_states (
bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回的张量下的hidden_states。 - cache_position (
torch.LongTensor, shape(sequence_length), optional) — 指示输入序列 token 在序列中的位置的索引。与position_ids不同,此张量不受填充影响。它用于在正确的位置更新缓存并推断完整的序列长度。 - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — 如果是int,则计算最后logits_to_keep个 token 的 logits。如果为0,则计算所有input_ids的 logits(特殊情况)。仅生成需要最后一个 token 的 logits,并且仅为该 token 计算可以节省内存,这对于长序列或大词汇量来说非常重要。如果是torch.Tensor,则必须是 1D 的,对应于序列长度维度的要保留的索引。当使用打包张量格式(批处理和序列长度的单维)时,这很有用。
返回
transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(BambaConfig)和输入的不同而包含各种元素。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
BambaForCausalLM 的 forward 方法,覆盖了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, BambaForCausalLM
>>> model = BambaForCausalLM.from_pretrained("...")
>>> tokenizer = AutoTokenizer.from_pretrained("...")
>>> 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."