# 모델 중간 출력 추적

모든 모델의 `forward()` 메서드는 `output_attentions`와 같은 `None` 플래그를 설정값의 기본값에서 수동으로 해석하고, 레이어별 어텐션 가중치와 히든 상태를 튜플에 누적하며, `return_dict=False`인 경우 `ModelOutput` 데이터클래스를 일반 튜플로 변환하는 역할을 했습니다. 두 개의 데코레이터가 이러한 모든 보일러플레이트 코드를 대체합니다.

- `@capture_outputs`은 출력 플래그를 해석하고, 중간 값을 수집하며, `return_dict` 변환을 처리합니다.
- `@merge_with_config_defaults`는 config에서 `use_cache`를 해석합니다. 캐시를 사용하지 않는 [CLIPModel](/docs/transformers/v5.24.0/ko/model_doc/clip#transformers.CLIPModel)과 같은 모델에는 생략하세요.

새 모델을 통합할 때 주로 이러한 데코레이터를 만나게 됩니다. 단계별 가이드는 [🤗 Transformers에 모델 추가하기](./modular_transformers)를 참고하세요.

## 필요한 hidden states만 캡처하기

`output_hidden_states=True`는 forward pass가 끝날 때까지 모든 레이어의 hidden state를 메모리에 유지합니다. 하나 또는 소수만 필요한 경우, 대신 인덱스 하나나 인덱스 목록을 전달하세요. 인덱스는 `output_hidden_states=True`가 반환하는 tuple에서 선택하며, 인덱스 0은 embedding 출력이고 음수 인덱스는 끝에서부터 세어집니다.

```py
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`일 때와 동일한 레이어를 가리킵니다. 선택하지 않은 hidden states는 `None`이며, 선택한 hidden states는 전체 캡처와 동일합니다.

- `config.num_hidden_layers` 값에 임베딩 출력을 위한 1을 더한 값 기준으로, 포워드 패스 전에 음수 인덱스가 해석됩니다. 설정에 `num_hidden_layers`가 정의되지 않은 경우, 음수 인덱스는 `ValueError`를 발생시킵니다. 해당 모델에는 양수 인덱스를 사용하세요.
- 범위를 벗어난 인덱스는 오류 없이 제거되며, 아무것도 선택하지 않습니다.
- `config.output_hidden_states=True`를 설정해도 모든 hidden state가 캡처됩니다.

> [!CAUTION]
> v5.17에서 v5.22까지, 리스트 인덱스 `k`는 `k`번째 레이어의 출력을 선택하고 임베딩 출력을 제외했습니다. 이제 `hidden_states[k]`를 선택하므로, 해당 버전용으로 작성된 양의 인덱스에는 1을 더해야 합니다.

## 캡처할 서브모듈을 선언

기본 모델의 `forward()` 메서드에 `@capture_outputs`를 적용합니다. 이는 다음과 같은 forward 훅을 연결합니다:

- forward 패스 중에 지정된 서브모듈 클래스의 출력을 가로채되, 해당 서브모듈이 관찰되고 있다는 사실을 알지 못하도록 합니다.
- 레이어별 attention weights와 hidden states를 tuple로 수집합니다.
- 수집된 값을 반환된 `ModelOutput` dataclass에 주입합니다.
- `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` 인스턴스, 또는 하나의 키 아래 여러 모듈 유형을 기록하기 위한 이러한 것들의 목록입니다.

## OutputRecorder를 통한 세밀한 제어

`OutputRecorder`는 수집할 출력을 가진 `nn.Module` 하위 클래스인 `target_class`와 모듈 출력 튜플에서 가져올 요소를 선택하기 위한 선택적 `index`를 받습니다. 특정 속성 이름을 가진 모듈에만 훅을 연결하려면 `layer_name`을 전달하세요. 셀프 어텐션과 크로스 어텐션처럼 두 레이어가 동일한 클래스를 공유하는 경우 `layer_name`을 사용하세요. 설정에 레이어 수가 `num_hidden_layers`가 아닌 다른 이름으로 저장되어 있다면, 음수 `output_hidden_states` 인덱스가 올바르게 해석되도록 해당 속성으로 `num_hidden_layers_key`를 설정하세요.

아래 예제는 서로 다른 출력 제어 수준으로 두 데코레이터를 실제 적용하는 방법을 보여줍니다. 실제 사용 사례는 [LlamaModel](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py)을 참고하세요.

```python
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
        )
```

## hidden states를 사용하는 메서드만 캡처

`get_image_features`와 같은 feature extraction 메서드는 vision tower와 같은 서브모델에서 하나 또는 소수의 hidden states를 읽는 경우가 많습니다. `output_hidden_states=True`를 요청하면 실제로 사용하는 소수의 레이어만 필요함에도 모든 레이어가 유지됩니다. 대신 해당 메서드에 `@select_hidden_states`를 적용하세요. 이 데코레이터는 `output_hidden_states`를 메서드가 사용하는 인덱스로 설정하고, kwargs를 받는 서브모델의 `@capture_outputs`는 해당 인덱스만 캡처합니다.

인덱스를 포함하는 메서드 인수의 이름을 전달합니다. 데코레이터는 해당 인수의 값(기본값 포함)을 읽고 `output_hidden_states`로 전달합니다.

```python
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](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava/modeling_llava.py)은 `vision_feature_layer`에 대해 이렇게 처리합니다.

인덱스가 인수가 아닌 모델에서 온다면, 모델을 받아 해당 인덱스를 반환하는 함수를 전달하세요. [CLIPSegForImageSegmentation](https://github.com/huggingface/transformers/blob/main/src/transformers/models/clipseg/modeling_clipseg.py)는 임베딩 출력을 건너뛰기 위해 `extract_layers`의 각 레이어에 1을 더합니다.

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

> [!NOTE]
> 호출자가 `output_hidden_states`로 hidden states를 요청하면 해당 요청이 우선하므로, `output_hidden_states=True`인 경우에도 모든 hidden state가 반환됩니다.

## Patch layer 클래스

Output tracing은 `_can_record_outputs`가 모델의 레이어가 인스턴스화하는 *정확한* 클래스를 가리키도록 하는 것에 의존합니다. 레이어 구현을 커스텀 어텐션 커널, 양자화 전문가 레이어 또는 아키텍처 변형으로 교체하는 경우, 해당 포인터는 동기화 상태를 유지해야 합니다. [패칭 API](./monkey_patching)는 `_can_record_outputs`의 일관성을 유지하기 위한 깔끔한 전역 레지스트리를 제공합니다.

`register_patch_mapping`은 원래 클래스 이름을 대체할 `nn.Module` 하위 클래스로 매핑합니다. 키는 정확한 클래스 이름이거나 정규식 패턴일 수 있습니다. 정확한 일치 항목이 우선합니다. 패턴은 `re.search()`로 테스트되므로, 앵커가 없는 패턴은 클래스 이름의 어디에나 일치할 수 있습니다. 동일한 키를 두 번 등록하면 `overwrite=True`를 전달하지 않는 한 `ValueError`가 발생합니다.

`unregister_patch_mapping`로 항목을 제거합니다.

```python
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`를 등록된 대체 객체로 업데이트합니다.

> [!TIP]
> [from_pretrained()](/docs/transformers/v5.24.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드는 `patch_output_recorders`를 자동으로 호출합니다. 모델을 직접 구성할 때만 직접 호출해야 합니다.

```python
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)
```

