Transformers 文档

Mamba

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

此模型于 2023-12-01 发布,并于 2024-03-05 添加到 Hugging Face Transformers。

PyTorch

Mamba

Mamba 是一种选择性结构化状态空间模型 (SSM),旨在解决 Transformer 在处理长序列时计算效率低下的问题。它是一种完全无注意力的架构,由 H3 和门控 MLP 块(Mamba 块)的组合构成。Mamba 的“基于内容的推理”使其能够根据当前 token 专注于输入中的特定部分。Mamba 还使用了一种新的硬件感知并行算法来弥补卷积操作的不足。因此,Mamba 推理速度快,并且可以扩展到非常长的序列。

您可以在 State Space Models 组织下找到所有原始 Mamba 检查点。

此模型由 MolbapAntonV 贡献。单击右侧边栏中的 Mamba 模型,了解如何将 Mamba 应用于不同语言任务的更多示例。

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

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

pipeline = pipeline(
    task="text-generation",
    model="state-spaces/mamba-130m-hf",
    dtype=torch.float16,
    device=0
)
pipeline("Plants create energy through a process known as")

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

以下示例使用 torchao 将权重量化为 4 位整数。

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
from torchao.quantization import Int4WeightOnlyConfig

quantization_config = Int4WeightOnlyConfig(group_size=128)
quantization_config = TorchAoConfig(quant_type=quant_config)
tokenizer = AutoTokenizer.from_pretrained("state-spaces/mamba-2.8b-hf")
model = AutoModelForCausalLM.from_pretrained("state-spaces/mamba-2.8b-hf", dtype=torch.bfloat16, quantization_config=quantization_config, device_map="auto",)
input_ids = tokenizer("Plants create energy through a process known as", return_tensors="pt").to(model.device)

output = model.generate(**input_ids)
print(tokenizer.decode(output[0], skip_special_tokens=True))

注意事项

  • 当前实现使用原始 CUDA 内核。FlashAttention 等效实现托管在 mamba-ssmcausal_conv1d 存储库中。如果您的硬件支持,请确保安装它们!

  • Mamba 堆叠了 `mixer` 层,这些层等效于 `Attention` 层。您可以在 `MambaMixer` 类中找到 Mamba 的主要逻辑。

  • 以下示例演示了如何使用 PEFT 微调 Mamba。

    from datasets import load_dataset
    from trl import SFTConfig, SFTTrainer
    from peft import LoraConfig
    
    model_id = "state-spaces/mamba-130m-hf"
    dataset = load_dataset("Abirate/english_quotes", split="train")
    training_args = SFTConfig(dataset_text_field="quote")
    lora_config =  LoraConfig(target_modules=["x_proj", "embeddings", "in_proj", "out_proj"])
    trainer = SFTTrainer(
        model=model_id,
        args=training_args,
        train_dataset=dataset,
        peft_config=lora_config,
    )
    trainer.train()

MambaCache

class transformers.MambaCache

< >

( config: PreTrainedConfig max_batch_size: int dtype: dtype = torch.float16 device: torch.device | str | None = None )

参数

  • config (`PreTrainedConfig) — The configuration file defining the shape-related attributes required to initialize the static cache.
  • max_batch_size (int) — The maximum batch size with which the model will be used. Note that a new instance must be instantiated if a smaller batch size is used.
  • dtype (torch.dtype, optional, defaults to torch.float16) — The default dtype to use when initializing the layer.
  • device (torch.device or str, optional) — The device on which the cache should be initialized. Should be the same as the layer.

Mamba 模型缓存,它没有注意力机制和键值状态。

示例

>>> import torch
>>> from transformers import AutoTokenizer, MambaForCausalLM, MambaCache

>>> model = MambaForCausalLM.from_pretrained("state-spaces/mamba-130m-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("state-spaces/mamba-130m-hf")

>>> inputs = tokenizer(text="My name is Mamba", return_tensors="pt")

>>> # Prepare a cache class and pass it to model's forward
>>> cache_params = MambaCache(config=model.config, max_batch_size=1, device=model.device, dtype=model.dtype)
>>> cache_position = torch.arange(len(inputs["input_ids"][0]), device=model.device)  # sequence length
>>> outputs = model(**inputs, cache_params=cache_params, cache_position=cache_position, use_cache=True)
>>> outputs.cache_params

update_conv_state

< >

( layer_idx: int new_conv_state: Tensor cache_position: LongTensor )

update_ssm_state

< >

( layer_idx: int new_ssm_state: Tensor )

重置

< >

( )

MambaConfig

class transformers.MambaConfig

< >

( vocab_size = 50280 hidden_size = 768 state_size = 16 num_hidden_layers = 32 layer_norm_epsilon = 1e-05 pad_token_id = 0 bos_token_id = 0 eos_token_id = 0 expand = 2 conv_kernel = 4 use_bias = False use_conv_bias = True hidden_act = 'silu' initializer_range = 0.1 residual_in_fp32 = True time_step_rank = 'auto' time_step_scale = 1.0 time_step_min = 0.001 time_step_max = 0.1 time_step_init_scheme = 'random' time_step_floor = 0.0001 rescale_prenorm_residual = False use_cache = True use_mambapy = False tie_word_embeddings = True **kwargs )

参数

  • vocab_size (int, optional, defaults to 50280) — Vocabulary size of the MAMBA model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling MambaModel.
  • hidden_size (int, optional, defaults to 768) — Dimensionality of the embeddings and hidden states.
  • state_size (int, optional, defaults to 16) — shape of the state space latents.
  • num_hidden_layers (int, optional, defaults to 32) — Number of hidden layers in the model.
  • layer_norm_epsilon (float, optional, defaults to 1e-05) — The epsilon to use in the layer normalization layers.
  • pad_token_id (int, optional, defaults to 0) — Padding token id.
  • bos_token_id (int, optional, defaults to 0) — The id of the beginning of sentence token in the vocabulary.
  • eos_token_id (int, optional, defaults to 0) — The id of the end of sentence token in the vocabulary.
  • expand (int, optional, defaults to 2) — Expanding factor used to determine the intermediate size.
  • conv_kernel (int, optional, defaults to 4) — Size of the convolution kernel.
  • use_bias (bool, optional, defaults to False) — Whether or not to use bias in [“in_proj”, “out_proj”] of the mixer block
  • use_conv_bias (bool, optional, defaults to True) — Whether or not to use bias in the convolution layer of the mixer block.
  • hidden_act (str, optional, defaults to "silu") — The non-linear activation function (function or string) in the decoder.
  • initializer_range (float, optional, defaults to 0.1) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  • residual_in_fp32 (bool, 可选, 默认为 True) — 残差是否应为 float32 类型。如果设置为 False,残差将保持与模型其余部分相同的 dtype
  • time_step_rank (Union[int,str], 可选, 默认为 "auto") — 离散化投影矩阵的秩。"auto" 意味着它将默认为 math.ceil(self.hidden_size / 16)
  • time_step_scale (float, 可选, 默认为 1.0) — 用于缩放 dt_proj.bias 的比例因子。
  • time_step_min (float, 可选, 默认为 0.001) — 用于限制 dt_proj.bias 的最小 time_step
  • time_step_max (float, 可选, 默认为 0.1) — 用于限制 dt_proj.bias 的最大 time_step
  • time_step_init_scheme (float, 可选, 默认为 "random") — 用于 dt_proj.weight 的初始化方案。应为 ["random","uniform"] 中的一个
  • time_step_floor (float, 可选, 默认为 0.0001) — dt_proj.bias 层初始化的最小钳位值。
  • rescale_prenorm_residual (bool, 可选, 默认为 False) — 初始化时是否重新缩放 out_proj 权重。
  • use_cache (bool, 可选, 默认为 True) — 是否使用缓存。
  • use_mambapy (bool, 可选, 默认为 False) — 确定在训练期间,如果 CUDA 版本的 Mamba 官方实现不可用时的回退策略。如果为 True,则使用 mamba.py 实现。如果为 False,则使用朴素且较慢的实现。如果内存有限,请考虑切换到朴素版本。
  • tie_word_embeddings (bool, 可选, 默认为 True) — 是否绑定词嵌入权重

这是配置类,用于存储 MambaModel 的配置。它用于根据指定的参数实例化一个 MAMBA 模型,定义模型的架构。使用默认值实例化配置将产生与 MAMBA state-spaces/mamba-2.8b 架构相似的配置。

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

示例

>>> from transformers import MambaConfig, MambaModel

>>> # Initializing a Mamba configuration
>>> configuration = MambaConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = MambaModel(configuration)

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

MambaModel

class transformers.MambaModel

< >

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

输出原始隐藏状态的裸 Mamba 模型,顶部没有特定的头。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None inputs_embeds: torch.LongTensor | None = None cache_params: transformers.models.mamba.modeling_mamba.MambaCache | None = None use_cache: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.LongTensor | None = None attention_mask: torch.LongTensor | None = None **kwargs ) transformers.models.mamba.modeling_mamba.MambaOutputtuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

  • inputs_embeds (torch.LongTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 可选地,您可以直接传入嵌入表示,而不是传入 input_ids。当您希望比模型内部的嵌入查找矩阵对如何将 input_ids 索引转换为相关向量拥有更多控制时,这很有用。
  • cache_params (MambaCache, 可选) — 如果传入,模型将使用前一个状态在所有块中(这将为提供的 input_ids 提供输出,就好像模型将 state_input_ids + input_ids 作为上下文一样)。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 cache_params,可用于快速生成下一个 logits。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 如果为 True,则返回 ModelOutput 而不是普通元组。
  • cache_position (torch.LongTensor,形状为 (sequence_length)可选) — 与 position_ids 相反,此张量不受填充的影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • attention_mask (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 用于避免对填充 token 索引执行注意力的掩码。掩码值在 [0, 1] 中选择:

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

    什么是注意力掩码?

返回

transformers.models.mamba.modeling_mamba.MambaOutputtuple(torch.FloatTensor)

一个 transformers.models.mamba.modeling_mamba.MambaOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),其中包含根据配置(MambaConfig)和输入而变化的各种元素。

  • last_hidden_state (torch.FloatTensor | None.last_hidden_state, shape (batch_size, sequence_length, hidden_size), 默认为 None) — 模型最后一层的输出的隐藏状态序列。

  • cache_params (~models.mamba.modeling_mamba.MambaCache | None.cache_params, 默认为 None) — 模型在最后一步的状态。可以在具有下一个 input_ids 的前向方法中使用,以避免提供旧的 input_ids

    包括选择性扫描后的状态空间模型状态矩阵和卷积状态

  • hidden_states (tuple[torch.FloatTensor] | None.hidden_states, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出,如果模型有嵌入层,+ 每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

MambaModel 的前向方法,覆盖 __call__ 特殊方法。

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

MambaLMHeadModel

class transformers.MambaForCausalLM

< >

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

MAMBA 模型,顶部带有语言建模头(带有与输入嵌入绑定的权重)的 Transformer。

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

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

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None cache_params: transformers.models.mamba.modeling_mamba.MambaCache | None = None labels: torch.LongTensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None use_cache: bool | None = None cache_position: torch.Tensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) transformers.models.mamba.modeling_mamba.MambaCausalLMOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充(padding)。

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

    什么是输入 ID?

  • attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行注意力计算的掩码。掩码值选择在 [0, 1] 中:

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

    什么是注意力掩码?

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以直接传入嵌入表示,而不是传入 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有比模型内部嵌入查找矩阵更多的控制,这会很有用。
  • cache_params (MambaCache, optional) — 如果传入,模型将使用所有块中的先前状态(这将为提供的 input_ids 生成输出,就好像模型添加了 state_input_ids + input_ids 作为上下文一样)。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于语言建模的标签。请注意,标签在模型内部被移位,即您可以设置 labels = input_ids。索引选择在 [-100, 0, ..., config.vocab_size] 中。所有设置为 -100 的标签都将被忽略(掩码),损失仅在 [0, ..., config.vocab_size] 中的标签上计算。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 对象而不是一个普通的元组。
  • use_cache (bool, optional) — 如果设置为 True,则会返回 cache_params,并可用于快速生成下一个 logits。
  • cache_position (torch.Tensor of shape (sequence_length), optional) — 指示输入序列 token 在序列中位置的索引。与 position_ids 相反,此张量不受填充的影响。它用于在正确位置更新缓存并推断完整序列长度。
  • logits_to_keep (Union[int, torch.Tensor], optional, defaults to 0) — 如果是 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。仅在生成时需要最后一个 token 的 logits,并且仅为该 token 计算可以节省内存,这对于长序列或大词汇量来说非常显著。如果为 torch.Tensor,必须是 1D 的,对应于序列长度维度中要保留的索引。这在使用打包张量格式(批次和序列长度的单一维度)时很有用。

返回

transformers.models.mamba.modeling_mamba.MambaCausalLMOutputtuple(torch.FloatTensor)

根据配置(MambaConfig)和输入,transformers.models.mamba.modeling_mamba.MambaCausalLMOutputtorch.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 之前的每个词汇标记的分数)。

  • cache_params (~models.mamba.modeling_mamba.MambaCache | None.cache_params, 默认为 None) — 模型在最后一步的状态。可以在具有下一个 input_ids 的前向方法中使用,以避免提供旧的 input_ids

    包括选择性扫描后的状态空间模型状态矩阵和卷积状态

  • hidden_states (tuple[torch.FloatTensor] | None.hidden_states, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出,如果模型有嵌入层,+ 每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

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

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

示例

在 GitHub 上更新

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