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

追踪模型的中间输出

每个模型的 forward() 方法过去都需要手动从配置默认值中解析 None 标志(例如 output_attentions),将各层的注意力权重和隐藏状态累积到元组中,并在 return_dict=False 时将 ModelOutput 数据类转换为普通元组。两个装饰器取代了所有这些样板代码。

  • @capture_outputs 负责解析输出标志、收集中间值,并处理 return_dict 转换。
  • @merge_with_config_defaults 从配置中解析 use_cache。对于不使用缓存的模型(例如 CLIPModel),请省略它。

在集成新模型时,您通常会遇到这些装饰器。有关分步指南,请参阅向 🤗 Transformers 添加模型。

仅捕获所需的隐藏状态

output_hidden_states=True 会在前向传播结束前将每一层的隐藏状态保留在内存中。如果只需要一个或少数几个,请改为传入索引或索引列表。这些索引用于从 output_hidden_states=True 返回的元组中进行选择,其中索引 0 对应嵌入输出,负索引则从末尾开始计数。

from transformers import AutoModel, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
model = AutoModel.from_pretrained("Qwen/Qwen3-0.6B")
inputs = tokenizer("Hello world", return_tensors="pt")

outputs = model(**inputs, output_hidden_states=[0, -2])
len(outputs.hidden_states)
# 29
[i for i, h in enumerate(outputs.hidden_states) if h is not None]
# [0, 27]

返回的元组保持其完整长度,因此 hidden_states[k] 指向的层与使用 output_hidden_states=True 时相同。您未选择的隐藏状态为 None,而您选择的隐藏状态与完整捕获的结果完全一致。

  • 负索引会在前向传播之前,基于 config.num_hidden_layers 加一(用于嵌入输出)进行解析。如果配置未定义 num_hidden_layers,使用负索引将引发 ValueError。对于这些模型,请使用正索引。
  • 超出范围的索引会被丢弃且不会引发错误,它们不会选中任何内容。
  • config.output_hidden_states=True 仍然会捕获所有隐藏状态。

从 v5.17 到 v5.22,列表索引 k 会选择第 k 层的输出,并排除嵌入输出。现在它选择的是 hidden_states[k],因此对于为这些版本编写的任何正索引,都需要加一。

声明要捕获哪些子模块

将 @capture_outputs 应用于基础模型的 forward() 方法。它会附加前向钩子,这些钩子会:

  • 在前向传播过程中,拦截来自指定子模块类的输出,而无需这些子模块感知到它们正在被观察。
  • 将每层的注意力权重和隐藏状态收集到元组中。
  • 将收集到的值注入返回的 ModelOutput 数据类中。
  • 当 return_dict=False 时,将 dataclass 转换为普通元组。
  • 当 None 时,从 kwargs 或 self.config 中解析 output_attentions 和 output_hidden_states。

将输出字段映射到子模块

@capture_outputs 需要知道哪个子模块生成了哪个输出。请在你的 PreTrainedModel 子类中声明一个 _can_record_outputs 类级别字典。每个键是一个输出字段名("hidden_states"、"attentions"、"cross_attentions"),每个值是一个模块类、类名字符串、一个 OutputRecorder 实例,或这些类型的列表,以便在同一个键下记录多种模块类型。

使用 OutputRecorder 实现细粒度控制

OutputRecorder 接受一个 target_class(一个 nn.Module 子类,用于指定要收集输出的模块)以及一个可选的 index,用于选择模块输出元组中的哪个元素。传入 layer_name 可以将钩子仅附加到具有特定属性名称的模块上。当两个层共享相同的类时(例如自注意力与交叉注意力),请使用 layer_name。如果配置文件中层数的存储名称不是 num_hidden_layers,请将 num_hidden_layers_key 设置为该属性,以便负数的 output_hidden_states 索引能够正确解析。

下面的示例展示了这两个装饰器在实际应用中的不同输出控制级别。请参阅 LlamaModel 以获取实际参考。

from ...processing_utils import Unpack
from ...utils import TransformersKwargs
from ...utils.generic import merge_with_config_defaults
from ...utils.output_capturing import capture_outputs, OutputRecorder

class MyPreTrainedModel(PreTrainedModel):
    _can_record_outputs = {
        # Capture hidden_states: hook fires after each MyDecoderBlock forward,
        # grabbing its first output (index 0 by default).
        "hidden_states": MyDecoderBlock,

        # Capture self-attention weights: hook fires after each MyAttention
        # forward, grabbing its second output (index=1 by default).
        "attentions": MyAttention,

        # Capture cross-attention weights: same class, different submodule.
        # layer_name targets the attribute `self.crossattention` inside the block.
        # Captures second output as requested (index=1)
        "cross_attentions": OutputRecorder(
            MyAttention, layer_name="crossattention", index=1
        ),
    }

# Now in base model's forward we need the decorators and `Unpack` `kwargs`
class MyModel(MyPreTrainedModel):

    @merge_with_config_defaults # ← resolves use_cache
    @capture_outputs            # ← handles output collection + return_dict
    def forward(
        self,
        input_ids: torch.LongTensor | None = None,
        cache: Cache = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutputWithPast:

        # No manual collection needed. Just run your layers normally.
        hidden_states = self.embed_tokens(input_ids)
        for layer in self.layers:
            hidden_states = layer(hidden_states, **kwargs)

        # Return the primary outputs. The decorator will fill in
        # hidden_states/attentions/cross_attentions automatically.
        return BaseModelOutputWithPast(
            last_hidden_state=hidden_states,
            cache=cache
        )

仅捕获方法使用的隐藏状态

像 get_image_features 这样的特征提取方法通常只从子模型(例如视觉塔)中读取一个或少数几个隐藏状态。请求 output_hidden_states=True 会使所有层都保持活跃,尽管实际只用到其中少数几层。请改用 @select_hidden_states 来装饰该方法。它会将 output_hidden_states 设置为该方法所使用的索引,而接收这些 kwargs 的子模型的 @capture_outputs 也只会捕获这些索引对应的状态。

传递持有索引的方法参数名称。装饰器会读取该参数的值(包括其默认值),并将其作为 output_hidden_states 转发。

from ...utils.output_capturing import select_hidden_states

class MyVisionLanguageModel(MyPreTrainedModel):

    @select_hidden_states("vision_feature_layer")
    def get_image_features(
        self,
        pixel_values: torch.Tensor,
        vision_feature_layer: int | list[int] = -2,
        **kwargs: Unpack[TransformersKwargs],
    ):
        # kwargs["output_hidden_states"] is now vision_feature_layer
        image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
        image_features = image_outputs.hidden_states[vision_feature_layer]
        return self.multi_modal_projector(image_features)

如果参数默认值为 None 且其值来自 config,请将 @merge_with_config_defaults 放在 @select_hidden_states 上方,以便装饰器能看到解析后的值。LlavaModel 对 vision_feature_layer 就是这样做的。

如果索引来自模型而非参数,请传入一个接收模型并返回这些索引的函数。CLIPSegForImageSegmentation 会在 extract_layers 中的每一层加一,以跳过嵌入输出。

@select_hidden_states(lambda self: [i + 1 for i in self.extract_layers])

如果调用者通过 output_hidden_states 请求隐藏状态,则该请求具有优先权,因此 output_hidden_states=True 仍会返回所有隐藏状态。

补丁层类

输出追踪依赖于 _can_record_outputs 指向模型各层所实例化的确切类。如果你将某个层的实现替换为自定义注意力内核、量化专家层或架构变体,这些指针必须保持同步。补丁 API 提供了一个简洁的全局注册表,用于保持 _can_record_outputs 的一致性。

register_patch_mapping 将原始类名映射到替换用的 nn.Module 子类。键可以是精确的类名,也可以是正则表达式模式。精确匹配具有优先权。模式通过 re.search() 进行测试,因此未锚定的模式可以匹配类名中的任意位置。如果两次注册相同的键,除非传入 overwrite=True,否则将引发 ValueError。

使用 unregister_patch_mapping 删除条目。

from transformers.monkey_patching import register_patch_mapping, unregister_patch_mapping

# Exact name – replaces only Qwen2MoeExperts
register_patch_mapping({"Qwen2MoeExperts": SequentialExperts})

# Regex – replaces every class whose name ends in "Attention"
register_patch_mapping({".*Attention$": FusedAttention})

# Anchored version – only matches Llama2Attention, Llama3Attention, …
register_patch_mapping({"^Llama\\d+Attention$": CustomLlamaAttention})

# Same way, custom keys can be removed from the registry by passing the name that was registered
unregister_patch_mapping(["Qwen2MoeExperts", ".*Attention$"])

映射注册完成后,patch_output_recorders 会遍历每个子模块,并将每个 OutputRecorder.target_class 更新为已注册的替换类。

from_pretrained() 方法会自动调用 patch_output_recorders。只有在直接构建模型时,才需要您手动调用它。

from transformers.monkey_patching import patch_output_recorders
# Built manually, outside from_pretrained
model = Qwen2MoeModel(config)

# Without this, _can_record_outputs still points at the original Qwen2MoeExperts class
# and hooks will never fire on CustomExperts instances.
patch_output_recorders(model)
Update on GitHub