Transformers documentation

自定义层和实用工具

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

自定义层和实用工具

本页列出了该库使用的所有自定义层,以及它为建模提供的实用函数和类。

其中大部分内容仅在你研究库中模型的代码时才有用。

WeightRenaming

class transformers.GroupWeightRename

< >

( source_patterns: list[str]target_patterns: list[str] )

应用一组配对的 WeightRenaming 转换,由第一个(“guard”)源模式惰性激活。当两个重命名共享一个中间名称(例如 norm0→norm1 和 norm1→norm2)时,请使用此功能,以确保加载已转换的检查点(其中包含 norm1 和 norm2,但不包含 norm0)时不会错误地重新应用这些重命名。

NOTE: 请对 source_patterns 进行排序,使在已转换的检查点中缺失的那个排在最前面。状态字典按排序后的键顺序进行迭代,因此守卫模式必须按字典序小于依赖模式。否则,依赖项将在第一轮中被跳过,且永远不会被重试。

WeightConverter

class transformers.WeightConverter

< >

( source_patterns: str | list[str]target_patterns: str | list[str]operations: list[ConversionOps]force_cpu: bool = False )

转换操作

class transformers.ConversionOps

< >

( )

权重转换操作的基础类。

class transformers.Chunk

< >

( dim: int = 0num_shards_attribute: str | None = None )

沿 dim 将张量拆分为大小相等的块。此外,num_shards_attribute 是一个配置字段,用于读取需要拆分为多少个张量。在拼接任意数量的张量时非常有用。

class transformers.Concatenate

< >

( dim: int = 0num_shards_attribute: str | None = None )

沿 dim 拼接张量。此外,如果拼接任意数量的张量,num_shards_attribute 是一个配置字段,用于读取在使用相反 Ops 时需要重建的张量数量。

class transformers.MergeModulelist

< >

( dim: int = 0 )

将张量列表沿第一个维度合并为单个张量。 我们显式地定义此操作,因为在 EP 或 TP 中,你需要确保清楚自己正在做什么!

class transformers.SplitModulelist

< >

( dim: int = 0 )

使用每个组的显式拆分大小,作为 MergeModulelist 的逆操作。

class transformers.PermuteForRope

< >

( subconfig_key: str | None = Nonepermute_layer_names: list[str] | None = Noneinverse: bool = False )

应用所需的置换,以将复数 RoPE 权重转换为拆分后的 sin/cos 格式。

class transformers.VisionFuseAndPermuteForRope

< >

( dim: int = 0permute_layer_names: list[str] | None = Noneinverse: bool = True )

应用所需的置换,以将复数 RoPE 权重转换为融合 QKV 上的拆分 sin/cos 格式。 与调用 PermuteForRope() + Concatenate() 相同,但允许我们仅对分块张量的子集调用 Permute。

注意:此转换仅适用于多模态模型中的视觉骨干网络,因为它会检查 config.vision_config

class transformers.VisionUnfuseAndPermuteForRope

< >

( dim: int = 0permute_layer_names: list[str] | None = Noneinverse: bool = False )

应用所需的置换,以将复数 RoPE 权重转换为融合 QKV 上的拆分 sin/cos 格式。 与调用 Chunk() + PermuteForRope() 相同,但允许我们仅对分块张量的子集调用 Permute。

注意:此转换仅适用于多模态模型中的视觉骨干网络,因为它会检查 config.vision_config

层

类 transformers.GradientCheckpointingLayer

< >

( *args**kwargs )

用于带有梯度检查点(gradient checkpointing)的层的基类。

此类为层启用梯度检查点功能。默认情况下,梯度检查点处于禁用状态(gradient_checkpointing = False)。当调用 model.set_gradient_checkpointing() 时,通过将 gradient_checkpointing = True 并分配一个检查点函数给 _gradient_checkpointing_func 来启用梯度检查点。

重要:

在使用梯度检查点且 use_reentrant=True 时,需要梯度的输入(例如隐藏状态)必须作为位置参数(*args)传递,而不是作为关键字参数,以便正确传播梯度。

示例:

>>> # Correct - hidden_states passed as positional arg
>>> out = self.layer(hidden_states, attention_mask=attention_mask)

>>> # Incorrect - hidden_states passed as keyword arg
>>> out = self.layer(hidden_states=hidden_states, attention_mask=attention_mask)

注意力函数

class transformers.AttentionInterface

< >

( )

用于跟踪允许的注意力函数的类字典对象。您可以通过调用 register() 轻松添加新的注意力函数。如果某个模型需要局部覆盖现有的注意力函数(例如 sdpa),则需要在 modeling_<model>.py 中声明此类的一个新实例,并在该实例上进行声明。

注册

< >

( key: strvalue: Callable )

注意力掩码函数

class transformers.AttentionMaskInterface

< >

( )

注册

< >

( key: strvalue: Callable )

旋转位置嵌入函数

transformers.dynamic_rope_update

< >

( rope_forward )

参数

  • rope_forward (Callable) — RoPE 实现的前向传播。

用于在前向传播中更新 RoPE 参数的装饰器函数,适用于模型使用动态 RoPE 的情况(即在前向传播中可能会重新计算其频率的 RoPE 实现)。

Pytorch 自定义模块

class transformers.Conv1D

< >

( nfnx )

参数

  • nf (int) — 输出特征的数量。
  • nx (int) — 输入特征的数量。

1D-convolutional layer,由 Radford 等人为 OpenAI GPT 定义(同样用于 GPT-2)。

基本上与线性层的工作方式相同,但权重是转置的。

PyTorch 辅助函数

transformers.apply_chunking_to_forward

< >

( forward_fn: Callable[..., torch.Tensor]chunk_size: intchunk_dim: int*input_tensors ) → torch.Tensor

参数

  • forward_fn (Callable[..., torch.Tensor]) — 模型的前向函数。
  • chunk_size (int) — 分块张量的块大小:num_chunks = len(input_tensors[0]) / chunk_size。
  • chunk_dim (int) — input_tensors 应进行分块的维度。
  • input_tensors (tuple[torch.Tensor]) — forward_fn 的输入张量,将被分块处理

返回值

torch.Tensor

一个与 forward_fn 应用后返回的张量具有相同形状的张量`。

此函数将 input_tensors 沿维度 chunk_dim 切分为大小为 chunk_size 的较小输入张量块。随后,它对每个块独立应用层 forward_fn,以节省内存。

如果 forward_fn 在 chunk_dim 上是相互独立的,那么该函数将产生与直接对 input_tensors 应用 forward_fn 相同的结果。

示例:

# rename the usual forward() fn to forward_chunk()
def forward_chunk(self, hidden_states):
    hidden_states = self.decoder(hidden_states)
    return hidden_states


# implement a chunked forward function
def forward(self, hidden_states):
    return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states)

transformers.pytorch_utils.prune_linear_layer

< >

( layer: nn.Linearindex: torch.LongTensordim: int = 0 ) → torch.nn.Linear

参数

  • layer (torch.nn.Linear) — 要剪枝的层。
  • index (torch.LongTensor) — 要在该层中保留的索引。
  • dim (int,可选,默认为 0) — 需要保留索引的维度。

返回值

torch.nn.Linear

将剪枝后的层作为新层,并设置 requires_grad=True。

修剪线性层,仅保留 index 中的条目。

用于移除注意力头。

Update on GitHub