Transformers documentation

モデルの中間出力のトレース

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

モデルの中間出力のトレース

すべてのモデルのforward()メソッドは、output_attentionsのようなNoneフラグを設定のデフォルト値から手動で解決し、レイヤーごとのアテンション重みと隠れ状態をタプルに蓄積し、return_dict=Falseの場合にModelOutputデータクラスをプレーンなタプルに変換していました。これらのボイラープレートはすべて、2つのデコレーターに置き換えられます。

  • @capture_outputs は出力フラグを解決し、中間値を収集して、return_dict 変換を処理します。
  • @merge_with_config_defaults は config から use_cache を解決します。キャッシュを使用しないモデル(CLIPModel など)では、これを省略してください。

これらのデコレーターは、新しいモデルを統合する際に主に遭遇します。ステップバイステップのガイドについては、🤗 Transformers にモデルを追加するを参照してください。

必要とする隠れ状態のみをキャプチャする

output_hidden_states=True を設定すると、フォワードパスが終了するまで、すべてのレイヤーの隠れ状態がメモリに保持されます。1つまたは少数のレイヤーの隠れ状態のみが必要な場合は、代わりにインデックスまたはインデックスのリストを渡してください。これらのインデックスは、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に埋め込み出力用の1を加えた値を基準として、フォワードパスの前に解決されます。設定にnum_hidden_layersが定義されていない場合、負のインデックスを指定するとValueErrorが発生します。そのようなモデルには正のインデックスを使用してください。
  • 範囲外のインデックスはエラーなしで破棄され、何も選択されません。
  • config.output_hidden_states=Trueでも、すべての隠れ状態がキャプチャされます。

v5.17からv5.22までのバージョンでは、リストのインデックスkがレイヤーkの出力を選択し、embeddingの出力を除外していました。現在はhidden_states[k]を選択するため、これらのバージョン用に記述された正のインデックスには1を加えてください。

キャプチャするサブモジュールを宣言

ベースモデルのforward()メソッドに@capture_outputsを適用します。これにより、以下の処理を行うforwardフックがアタッチされます。

  • forward pass 中に指定されたサブモジュールクラスからの出力をインターセプトします。この際、監視されていることをサブモジュール側が認識する必要はありません。
  • 各レイヤーのattention weightsとhidden statesをタプルに収集します。
  • 収集した値を、返されるModelOutputデータクラスに注入します。
  • return_dict=False の場合、dataclass を通常の tuple に変換します。
  • None の場合、output_attentions と output_hidden_states を kwargs または self.config から解決します。

出力フィールドをサブモジュールにマッピングする

@capture_outputs は、どのサブモジュールがどの出力を生成するかを把握する必要があります。PreTrainedModel のサブクラスに、_can_record_outputs というクラスレベルの辞書を宣言してください。各キーは出力フィールド名("hidden_states"、"attentions"、"cross_attentions")であり、各値はモジュールクラス、クラス名の文字列、OutputRecorder インスタンス、またはそれらのリスト(1 つのキーで複数のモジュールタイプを記録する場合)です。

OutputRecorderによる詳細な制御

OutputRecorderは、収集対象の出力を持つnn.Moduleのサブクラスであるtarget_classと、モジュールの出力タプルからどの要素を取得するかを選択するための任意のindexを受け取ります。特定の属性名を持つモジュールにのみフックを付与するには、layer_nameを渡します。自己注意と相互注意のように、2つのレイヤーが同じクラスを共有している場合は、layer_nameを使用します。設定がレイヤー数をnum_hidden_layers以外の名前で保存している場合は、負のoutput_hidden_statesインデックスが正しく解決されるように、num_hidden_layers_keyをその属性に設定してください。

以下の例では、異なる出力制御レベルで両方のデコレーターを実際に使用する方法を示しています。実際の使用例については、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,
        past_key_values: 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,
            past_key_values=past_key_values
        )

メソッドが使用する隠れ状態のみをキャプチャします

get_image_features などの特徴抽出メソッドは、ビジョンタワーなどのサブモデルから1つまたは少数の隠れ状態を読み取ることがよくあります。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の各レイヤーに1を加算します。

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

呼び出し元がoutput_hidden_statesで隠れ状態を要求した場合、その要求が優先されるため、output_hidden_states=Trueでもすべての隠れ状態が返されます。

Patchレイヤーのクラス

Output tracing は、_can_record_outputs がモデルのレイヤーがインスタンス化する正確なクラスを指していることに依存します。レイヤーの実装をカスタムなアテンションカーネル、量子化されたエキスパートレイヤー、またはアーキテクチャのバリアントに置き換えた場合、これらのポインタは同期を保たなければなりません。パッチング API は、_can_record_outputs の整合性を保つためのクリーンなグローバルレジストリを提供します。

register_patch_mapping は、元のクラス名を置き換え用の nn.Module サブクラスにマッピングします。キーには、完全一致するクラス名または正規表現パターンを指定できます。完全一致が優先されます。パターンは re.search() でテストされるため、アンカーなしのパターンはクラス名のどこにでも一致します。同じキーを2回登録すると、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