# 모듈형 transformers로 모델 추가

Modular transformers는 [단일 모델, 단일 파일](https://huggingface.co/blog/transformers-design-philosophy) 정책과 달리 import와 상속을 허용하여 모델을 추가하는 데 필요한 코드를 줄입니다. 모델 구성 요소를 여러 파일에 반복해서 작성하는 대신, 모델 폴더에 *modular* 파일을 추가하고 기존 클래스를 상속받습니다.

컨버터는 모듈형 파일에서 독립적인 파일을 생성합니다. 사용자는 이미 익숙한 단일 파일 인터페이스를 그대로 사용할 수 있습니다.

> [!NOTE]
> Modular transformers는 [레거시 모델링 코드](./add_new_model)를 대체하기 위한 것이 아닙니다. 기존 모델에 기반하지 않은 모델의 경우, `modeling.py` 파일을 수동으로 추가하세요. 유사한 파일에서 깔끔하게 상속할 수 없는 configuration, tokenization, processing 파일에도 동일한 규칙이 적용됩니다.
>
> 단 하나의 정답이 되는 순서도 없습니다. 일부 기여자는 모듈형 파일을 먼저 작성하고 이를 기반으로 생성합니다. 다른 기여자는 수동으로 작성한 `modeling.py`로 시작하고 나중에 이를 모듈형 파일로 리팩터링합니다. 두 가지 접근 방식 모두 유효합니다.

## 모듈형 파일 구현

Transformers에서 사용 중인 모델과 유사한 모델을 찾아 시작하세요. 좋은 출발점은 [Mistral](./model_doc/mistral), [Qwen2](./model_doc/qwen2), [Cohere](./model_doc/cohere), [Cohere2](./model_doc/cohere2), [Llama](./model_doc/llama)입니다. 아래 표는 일반적인 구성 요소를 상속할 수 있는 모델에 매핑합니다.

| 구성 요소 | 모델 |
|---|---|
| 전문가 혼합 | Mixtral 또는 Qwen2-MoE |
| 인터리브드(및/또는 부분) 로테리 임베딩 | GLM, Phi |
| 상태 공간 모델 | Jamba, Bamba, Zamba, Mamba2 |
| 재귀적 은닉 상태 | Gemma2 |
| 레이어별 Sliding window attention/Full attention 패턴 | Gemma2, Cohere2 |
| QKV 클리핑 | Olmo |
| QK 정규화 | Olmo2, Cohere |
| Fused QKV (권장하지 않음) | Phi3 |

> [!TIP]
> [modular-detector-v2](https://huggingface.co/spaces/Molbap/modular-detector-v2) 도구를 사용하여 상속할 기존 구현을 찾아보세요. 코드 스니펫을 붙여넣으면 Transformers에 이미 존재하는 가장 유사한 메서드들을 반환하므로, 코드를 작성하기 전에 최적의 부모 클래스를 식별할 수 있습니다.

새로운 모델의 상속을 작동시키기 위해 기존 모델을 수정하지 마세요. 부모 클래스를 이름 변경하거나 서브클래스로 만드는 것이 너무 번거롭다면, 관련 코드를 직접 복사하는 것이 좋습니다.

`src/transformers/models/<name>/modular_<name>.py` 파일을 생성합니다. 여기서 `<name>`은 snake_case 형식의 모델 디렉터리 이름과 일치해야 합니다. 이 섹션에서는 [Olmo](./model_doc/olmo)에서 [Olmo2](./model_doc/olmo2)를 모듈식 방식으로 구현하는 과정을 안내합니다(원본 [modular_olmo2.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modular_olmo2.py) 파일을 참조하세요).

### 설정

[Olmo2Config](/docs/transformers/v5.24.0/ko/model_doc/olmo2#transformers.Olmo2Config)와 [OlmoConfig](/docs/transformers/v5.24.0/ko/model_doc/olmo#transformers.OlmoConfig)는 두 가지 점에서 차이가 있습니다.

1. 새로운 인자 `rms_norm_eps`가 있습니다.
2. `clip_qkv` 인자는 더 이상 사용되지 않습니다.

새로운 인수는 기본값이 포함된 클래스 수준의 타입 어노테이션으로 선언합니다. 제거된 인수의 경우, 생성된 파일에서 상속된 속성을 억제하기 위해 `AttributeError()`를 할당합니다(자세한 내용은 [속성 제거](#removing-attributes)를 참조).

```diff
- @auto_docstring(checkpoint="allenai/OLMo-7B-hf")
+ @auto_docstring(checkpoint="allenai/Olmo2-7B-1124-hf")
+ @strict
- class OlmoConfig(PreTrainedConfig):
+ class Olmo2Config(OlmoConfig):
      ...
-     model_type = "olmo"
+     model_type = "olmo2"
      ...
+     rms_norm_eps: float = 1e-5
-     clip_qkv: float | None = None
+     clip_qkv = AttributeError()
```

`@auto_docstring`은 표준 인자 문서를 자동으로 생성합니다([@auto_docstring](./auto_docstring) 가이드 참조). `@strict`는 인스턴스화 시점에 알려지지 않은 kwargs를 거부하여 오타나 오래된 인자를 조기에 잡아줍니다. 데코레이터는 부모 클래스에서 상속되지 않으므로 모든 config 클래스에 둘 다 추가하세요. 부모 config에 이미 선언되어 있더라도 명시적으로 선언해야 합니다.

파생 속성을 설정하거나 하위 호환성 로직을 처리하려면 `__init__` 대신 `__post_init__`를 사용하세요. 예를 들어, Cohere2는 초기화 시점에 `head_dim`을 계산하고 `layer_types`를 파생합니다.

```py
def __post_init__(self, **kwargs):
    if self.num_key_value_heads is None:
        self.num_key_value_heads = self.num_attention_heads
    self.head_dim = self.hidden_size // self.num_attention_heads
    super().__post_init__(**kwargs)
```

텐서 또는 파이프라인 병렬성을 지원하는 모델의 경우, config에 `base_model_tp_plan`과 `base_model_pp_plan`을 클래스 수준의 딕셔너리로 정의합니다. 두 딕셔너리 모두 모델을 여러 디바이스에 걸쳐 샤딩하는 방식을 정의합니다. [Olmo2](https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modular_olmo2.py)나 [Cohere2](https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere2/modular_cohere2.py)와 같은 기존 config를 참고하여 예시를 확인해 보세요.

```py
class MyNewModelConfig(PreTrainedConfig):
    model_type = "my_new_model"

    # Tensor parallelism: maps layer name patterns to sharding strategies.
    # Use "colwise" / "rowwise" for standard sharding, or the "gather_output" /
    # "split_input" variants when an extra op (e.g. a QK norm) prevents fusing.
    base_model_tp_plan = {
        "layers.*.self_attn.q_proj": "colwise",
        "layers.*.self_attn.k_proj": "colwise",
        "layers.*.self_attn.v_proj": "colwise",
        "layers.*.self_attn.o_proj": "rowwise",
        "layers.*.mlp.gate_proj": "colwise",
        "layers.*.mlp.up_proj": "colwise",
        "layers.*.mlp.down_proj": "rowwise",
    }

    # Pipeline parallelism: maps submodule names to their (input, output) tensor names.
    base_model_pp_plan = {
        "embed_tokens": (["input_ids"], ["inputs_embeds"]),
        "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
        "norm": (["hidden_states"], ["hidden_states"]),
    }
```

### Norm

변경 사항 없이 부모 클래스를 복사하려면 `pass`를 사용하여 상속합니다. 린터는 부모의 내용을 복사하고 새 모델에 맞게 모든 참조를 이름 변경합니다.

```py
from ..olmo.modeling_olmo import OlmoRotaryEmbedding

class Olmo2RotaryEmbedding(OlmoRotaryEmbedding):
    pass
```

특정 동작을 변경하려면, 다른 부분만 상속하여 오버라이드하세요. `Olmo2RMSNorm`은 `LlamaRMSNorm`과 한 줄만 다릅니다. 곱셈은 입력 dtype으로 캐스팅하기 *전에* 수행됩니다.

```diff
  from ..llama.modeling_llama import LlamaRMSNorm

  class Olmo2RMSNorm(LlamaRMSNorm):
      def forward(self, hidden_states):
          input_dtype = hidden_states.dtype
          hidden_states = hidden_states.to(torch.float32)
          variance = hidden_states.pow(2).mean(-1, keepdim=True)
          hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
-         return self.weight * hidden_states.to(input_dtype)
+         return (self.weight * hidden_states).to(input_dtype)
```

### Attention

Olmo2의 attention은 Olmo와 동일하지만, queries와 keys에 `RMSNorm`을 적용하고 qkv clipping을 제거한 것이 다릅니다. `super().__init__(...)`은 부모 클래스의 body를 복사하고 두 개의 새로운 norm 라인을 추가합니다. queries와 keys가 projection 전에 norm을 통과하게 되었기 때문에 `forward`는 완전히 재정의됩니다. linter는 생성된 파일에 가져온 함수들, 즉 `apply_rotary_pos_emb`, `eager_attention_forward` 및 이들의 의존성도 함께 가져옵니다.

```diff
  class Olmo2Attention(OlmoAttention):
      def __init__(self, config: Olmo2Config, layer_idx: int | None = None):
          super().__init__(config, layer_idx=layer_idx)
+         self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)
+         self.k_norm = Olmo2RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)

      def forward(self, ...):
          ...
-         query_states = self.q_proj(hidden_states)
-         key_states = self.k_proj(hidden_states)
+         query_states = self.q_norm(self.q_proj(hidden_states))
+         key_states = self.k_norm(self.k_proj(hidden_states))
          value_states = self.v_proj(hidden_states)

-         if self.config.clip_qkv is not None:
-             query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
-             key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
-             value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
-
          ...
```

### DecoderLayer

`super().__init__(...)` 이후, norm 속성을 `Olmo2RMSNorm` 인스턴스로 덮어쓰고 `self.self_attn`를 새로운 `Olmo2Attention` 클래스로 다시 할당합니다. `del self.input_layernorm`는 Olmo2가 attention 전에而不是가 아니라 attention *이후*에 norm을 적용하기 때문에 부모 클래스의 `input_layernorm` 할당을 제거합니다. `del`이 무엇을 제거하고 무엇을 제거하지 않는지에 대한 자세한 내용은 [속성 제거](#removing-attributes)를 참조하세요.

`forward`는 attention 이후의 norm 배치에 맞게 다시 작성됩니다. 속성이 이름만 변경된 경우에만 `forward` 재작성이 필요하며, 타입만 변경된 경우에는 필요하지 않습니다.

```diff
  class Olmo2DecoderLayer(OlmoDecoderLayer):
      def __init__(self, config: Olmo2Config, layer_idx: int):
          super().__init__(config, layer_idx=layer_idx)
-         self.self_attn = OlmoAttention(config=config, layer_idx=layer_idx)
-         self.input_layernorm = OlmoLayerNorm(config.hidden_size)
-         self.post_attention_layernorm = OlmoLayerNorm(config.hidden_size)
+         self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)
+         del self.input_layernorm
+         self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+         self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)

      def forward(self, ...):
          residual = hidden_states
-         hidden_states = self.input_layernorm(hidden_states)
          # Self Attention
          hidden_states, _ = self.self_attn(...)
-         hidden_states = residual + hidden_states
+         hidden_states = self.post_attention_layernorm(hidden_states)
+         hidden_states = residual + hidden_states

          # Fully Connected
          residual = hidden_states
-         hidden_states = self.post_attention_layernorm(hidden_states)
          hidden_states = self.mlp(hidden_states)
-         hidden_states = residual + hidden_states
+         hidden_states = self.post_feedforward_layernorm(hidden_states)
+         hidden_states = residual + hidden_states
          return hidden_states
```

### 모델

여기서는 `self.norm`의 타입만 변경됩니다. `forward` 메서드는 부모 클래스와 동일하므로, linter가 자동으로 가져옵니다.

```diff
  class Olmo2Model(OlmoModel):
      def __init__(self, config: Olmo2Config):
          super().__init__(config)
-         self.layers = nn.ModuleList(
-             [OlmoDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
-         )
-         self.norm = OlmoLayerNorm(config.hidden_size)
+         self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+         self.layers = nn.ModuleList(
+             [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+         )
```

### 모델 헤드

논리는 [OlmoForCausalLM](/docs/transformers/v5.24.0/ko/model_doc/olmo#transformers.OlmoForCausalLM)과 동일하므로 변경이 필요하지 않습니다.

```py
from ..olmo.modeling_olmo import OlmoForCausalLM

class Olmo2ForCausalLM(OlmoForCausalLM):
    pass
```

### 기타 클래스

linter가 생성한 [modeling_olmo2.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modeling_olmo2.py)에는 `modular_olmo2.py`에 명시적으로 정의되지 않은 클래스(`Olmo2MLP`, `Olmo2RotaryEmbedding`, `Olmo2PreTrainedModel`)도 포함되어 있습니다.

linter는 명시적으로 재정의하지 않는 한, 상속된 클래스가 의존하는 모든 클래스를 가져옵니다. `apply_rotary_pos_emb`와 같은 import된 함수도 동일한 규칙을 따릅니다.

예를 들어, `OlmoDecoderLayer`에는 `self.mlp = OlmoMLP(config)`가 있습니다. `Olmo2MLP`는 모듈러 파일에서 정의된 적이 없으므로, linter가 `pass`를 사용하는 것과 동등하게 자동으로 생성합니다.

```py
from ..olmo.modeling_olmo import OlmoMLP

class Olmo2MLP(OlmoMLP):
    pass
```

`Olmo2MLP`가 다른 모델에서 상속되도록 하려면 명시적으로 지정하세요.

```py
# switch to Mistral definition
from ..mistral.modeling_mistral import MistralMLP

class Olmo2MLP(MistralMLP):
    pass
```

### 파일 마무리하기

모든 모듈 파일은 모듈 수준에서 `logger`와 `__all__` 리스트를 선언해야 합니다.

```py
logger = logging.get_logger(__name__)

__all__ = [
    "Olmo2Config",
    "Olmo2ForCausalLM",
    "Olmo2Model",
    "Olmo2PreTrainedModel",
]
```

`__all__`에는 파일 내의 모든 공개 클래스를 나열해야 합니다. 컨버터와 하위 임포트가 이 값에 의존합니다. `__all__`에 누락된 클래스는 올바르게 내보내지지 않습니다.

## 모델링 파일 생성

`modular_model_converter.py` 스크립트는 모듈러 파일에서 독립적인 `modeling.py`, `configuration.py` 및 기타 파일을 생성합니다. 각 상속된 클래스에 대해, 부모 클래스의 본문을 자식 클래스로 복사하고 모든 참조를 새 모델에 맞게 이름 변경하며, 해당 부모 클래스가 의존하는 헬퍼 함수나 클래스를 가져옵니다.

출력 파일에는 모델 간 import가 없으며 다른 모델 디렉터리로부터의 상속도 없습니다. Linter는 상속을 단일 레벨로 평탄화합니다. `Olmo2Attention`이 `OlmoAttention`을 상속하는 경우, 생성된 `Olmo2Attention`는 완전히 자체적으로 완결됩니다. 그러나 `OlmoAttention` 자체가 다른 것을 상속했다면, Linter는 그 조상 클래스를 인라인하지 않습니다.

…

```bash
python utils/modular_model_converter.py your_model
```

다음 실행 시 변경 사항이 덮어쓰기되므로 생성된 파일을 직접 편집하지 마세요.

## 모듈형 파일 패턴

아래 섹션에서는 모듈러 파일 작업 시 속성 제거 또는 데코레이터가 적용된 메서드 오버라이드와 같은 일반적인 사용 패턴을 문서화합니다.

### 속성 제거

상속된 속성을 제거하는 방법은 config 클래스를 다루고 있는지 `nn.Module` 하위 클래스를 다루고인지에 따라 달라집니다.

config 클래스의 경우, 클래스 수준에서 해당 속성에 `AttributeError()`를 할당합니다.

```py
class MyNewConfig(ParentConfig):
    removed_attr = AttributeError()
```

linter는 생성된 config 파일에서 해당 속성 선언을 완전히 제거합니다. Config 클래스는 `__init__`가 없는 dataclass 스타일의 레이아웃을 사용하므로, 클래스 수준에서 `AttributeError()`를 할당하는 것이 올바른 접근 방식입니다.

`nn.Module` 하위 클래스의 경우, `super().__init__(...)` 이후에 `del self.attribute`를 사용하세요.

```py
class MyNewModel(ParentModel):
    def __init__(self, config: MyNewConfig):
        super().__init__(config)
        del self.attribute
```

`del self.attribute`는 복사된 부모 본문에서 `self.attribute = ...` 할당 줄만 제거합니다. `self.attribute`를 참조하는 다른 줄은 제거하지 않습니다. 부모의 `forward`나 다른 메서드에서도 해당 속성을 참조하는 경우, 해당 메서드도 오버라이드해야 합니다.

```py
class DummyModel(nn.Module):
    def __init__(self, config: DummyConfig):
        super().__init__()
        self.attribute = config.attribute
        if self.attribute:
            # do more stuff with `self.attribute` here
            ...

class MyNewDummyModel(DummyModel):
    def __init__(self, config: MyNewDummyConfig):
        super().__init__(config)
        del self.attribute
        # 'self.attribute = config.attribute' is removed, but the 'if self.attribute:' block remains.
        # Override forward() or any other method that references self.attribute.
```

### `super()` 사용

`super().__init__(config)`은 변환기가 부모의 본문을 자식으로 복사하도록 지시합니다. 이 동작을 오버라이드하는 두 가지 패턴이 있습니다.

- 생성된 출력이 modular parent가 아닌 조상 클래스(`nn.Module.__init__`)를 호출해야 하는 경우, 특정 parent 클래스를 직접 호출하세요.
- `**super_kwargs`를 사용하여 부모 메서드의 전체 시그니처를 상속하면서 커스텀 docstring을 추가하거나 데코레이터를 교체할 수 있습니다.

#### 조상 클래스를 직접 호출

`super()`를 사용할 때 modular parent가 아닌 생성된 클래스의 parent를 대상으로 해야 하는 경우, 어떤 클래스를 호출하는지 명시적으로 작성하세요. 아래 예시에서는 `nn.Module.__init__(self)`을 직접 호출합니다. `DummyModule` 자체가 `nn.Module`이므로, 변환기는 생성된 `MyNewDummyModule`에서 이를 `super().__init__()`로 작성합니다.

```py
class MyNewDummyModule(DummyModule):                   |     class MyNewDummyModule(nn.Module):
                                                       |
  def __init__(self):                                  |       def __init__(self):
    nn.Module.__init__(self)                           |         super().__init__()
    self.foo = config.foo                              |         self.foo = config.foo
    ...                                                |         ...
```

#### super_kwargs

`**super_kwargs`를 사용하면 부모 메서드의 전체 시그니처를 상속하면서 커스텀 docstring을 추가하거나 데코레이터를 교체할 수 있습니다. 오버라이드된 시그니처에서 `**super_kwargs`는 린터가 생성된 출력에 부모의 모든 인수를 확장하도록 지시합니다.

가장 일반적인 사용법은 `labels` 인자처럼 모델에 특화된 docstring을 추가하는 것이며, 전체 시그니처를 다시 작성하지 않아도 됩니다.

```py
# modular_gemma.py
class GemmaForCausalLM(LlamaForCausalLM):
    def forward(**super_kwargs):
        r"""
        Example:

        ```python
        >>> from transformers import AutoTokenizer, GemmaForCausalLM
        >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
        ...
        ```"""
        return super().forward(**super_kwargs)
```

생성된 `GemmaForCausalLM.forward`에는 수동 복사가 필요 없는 `LlamaForCausalLM`의 전체 시그니처가 포함되어 있습니다.

`**super_kwargs`는 특수한 경우를 위한 단축 방법입니다. 동작을 변경하는 경우 대신 전체 시그니처를 작성하세요.

### 사용하지 않는 메서드 삭제

`raise AttributeError("")` 문장으로 오버라이드하여 부모 메서드를 제거합니다. 린터는 생성된 파일에서 해당 메서드를 제거합니다.

```py
class GemmaTokenizer(LlamaTokenizer):
    ...

    def get_spm_processor(self):
        raise AttributeError("Not needed for Gemma")

    def unk_token_length(self):
        raise AttributeError("Not needed for Gemma")
```

### 장식된 메서드 오버라이딩

장식된 부모 메서드를 오버라이드하면 부모의 데코레이터가 자동으로 상속됩니다. 자체 데코레이터를 추가하면 부모의 데코레이터를 대체합니다.

라이브러리 전반에 두 개의 데코레이터가 등장하며, 하나는 [모델의 중간 출력을 캡처](./model_output_tracing)하는 데코레이터이고, 다른 하나는 [문서 문자열을 자동 생성](./auto_docstring)하는 데코레이터입니다.

…

```py
class NewModel(DummyModel):       |   class NewModel(nn.Module):
  ...                             |     ...
                                  |
  def forward(...):               |     @decorator(...)
    ...                           |     def forward(...):
                                  |       ...
```

새로운 데코레이터를 추가하면, 해당 데코레이터가 부모의 데코레이터를 대체합니다.

```py
class NewModel(DummyModel):       |   class NewModel(nn.Module):
  ...                             |     ...
                                  |
  @my_new_decorator(...)          |     @my_new_decorator(...)
  def forward(...):               |     def forward(...):
    ...                           |       ...
```

### 특별한 명명

linter는 클래스를 상속할 때 모든 이름을 자동으로 변경합니다. 같은 파일 내의 모든 클래스에 동일한 클래스 이름 접두사를 사용하세요.

아래 예시처럼 접두사를 혼합하는 것을 피하세요. `MyModelIncredibleMLP`은 네이밍 규칙을 위반하며, 상위 의존성을 이름 변경할 때 linter가 `MyModelIncredible`을 사용할지 `MyModel`을 사용할지 알 수 없습니다.

```py
class MyModelIncredibleMLP(LlamaMLP):
    ...

class MyModelDecoderLayer(LlamaDecoderLayer):
    ...
```

[암시적 의존성](#other-classes)이 없으므로, 단일 클래스를 로컬에서 이름 변경할 수 있습니다. 해당 클래스의 다른 모든 언급을 새 이름 패턴으로 명시적으로 재정의하세요. 그렇지 않으면 linter가 `MyModelIncredibleMLP` 옆에 원치 않는 `MyModelMLP` 클래스를 추가합니다.

linter는 모호한 접두사를 감지하면 경고를 표시합니다.

```text
We detected multiple prefix names when inheriting from transformers.models.llama.modeling_llama: ('Emu3Text', 'Emu3'). We will only use the most used 'Emu3' prefix when grabbing args and dependencies. Make sure to subclass the intermediate classes with the prefix you want (if different from 'Emu3') or use a single prefix in all the modular (best).
```

모호한 접두사는 `Text`와 같은 모달리티 한정자가 클래스 이름에 포함된 멀티모달 모델에서 가장 흔합니다. 특정 의존성에 구체적인 접두사를 부여하려면 `pass`를 사용하여 명시적으로 이름을 변경하세요.

```py
class Emu3TextMLP(LlamaMLP):
    pass
```

### Config docstring

linter는 아직 부분적인 docstring 상속을 지원하지 않습니다. config 속성을 추가하거나 제거할 때는 클래스 정의 아래에 있는 modular 파일에 전체 docstring을 직접 추가하세요.

## Checkpoint 변환

모델링 파일을 생성한 후에는 실제 가중치가 올바르게 로드되는지 확인하세요. Transformers와 호환되는 형식으로 업스트림 체크포인트 형식을 변환하는 변환 스크립트를 작성한 후, Hub에 저장하세요.

### 변환 스크립트 작성

`src/transformers/models/<model>/`에 `convert_<model>_to_hf.py` 파일을 추가합니다. 이 스크립트는 업스트림 가중치를 로드하고, 모듈의 파라미터 이름에 맞게 키를 이름 변경 및 리사이즈한 뒤, [save_pretrained()](/docs/transformers/v5.24.0/ko/main_classes/model#transformers.PreTrainedModel.save_pretrained)로 결과를 저장합니다.

> [!TIP]
> 복사하여 수정할 기존 스크립트를 찾아보세요. `src/transformers/models/` 아래에 있는 모델에는 시작점으로 사용할 수 있는 `convert_*_to_hf.py`가 포함되어 있습니다.

[from_pretrained()](/docs/transformers/v5.24.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained)로 저장된 체크포인트를 로드한 후, 모든 예상된 가중치가 올바르게 로드되었는지 확인하세요. 사용되지 않는 체크포인트 키는 이름 불일치를 나타내므로, 이를 출력하여 문제를 조기에 발견하세요.

```py
model = YourModelForTask.from_pretrained("path/to/output/")
```

keys를 반복할 때 shape과 이름이 일치하는지 확인하세요. shape 불일치는 일반적으로 config의 매개변수가 잘못되었거나, 아키텍처가 원래와 다르거나, 가중치를 전치해야 하는 경우를 의미합니다.

```py
for key, tensor in original_state_dict.items():
    hf_tensor = hf_model.state_dict().get(mapped_key)
    assert hf_tensor.shape == tensor.shape, (
        f"Shape mismatch for {key}: expected {tensor.shape}, got {hf_tensor.shape}"
    )
```

모듈러 파일, 생성된 modeling 파일, 변환 스크립트 사이를 반복하며 모든 가중치가 깨끗하게 로드될 때까지 문제를 수정하세요.

체크포인트가 정상적으로 로드되면 [push_to_hub()](/docs/transformers/v5.24.0/ko/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub)를 사용하여 Hub에 업로드하세요. 자세한 내용은 [모델 공유](./model_sharing) 가이드를 참고하세요.

```py
model.push_to_hub("username/your-model-name")
```

### 런타임 변환 매핑

게시된 가중치가 모듈의 매개변수 레이아웃과 일치하지 않는 경우 `src/transformers/conversion_mapping.py`에 런타임 매핑을 추가합니다. 일반적인 사례로는 별도로 저장된 융합 가중치와 스택링이 필요한 MoE 전문가 텐서가 있습니다. 이 매핑을 통해 [from_pretrained()](/docs/transformers/v5.24.0/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained)가 별도의 내보내기 단계 없이 Hub 체크포인트를 로드할 수 있습니다.

`WeightRenaming` 및 [WeightConverter](/docs/transformers/v5.24.0/ko/internal/modeling_utils#transformers.WeightConverter) 규칙을 작성하고 `model_type`에 등록하는 방법은 [동적 가중치 로딩](./weightconverter) 가이드를 참고하세요.

## 다음 단계

- [모델 구조 규칙](./modeling_rules)은 모든 `modeling_*.py`, `modular_*.py`, `configuration_*.py` 파일에 적용되는 정적 규칙입니다. PR을 열기 전에 `make typing`을 실행하여 이를 확인하세요.
- [비전 처리 구성 요소 추가](./add_vision_processing_components)에서는 멀티모달 모델에 이미지 프로세서, 비디오 프로세서, 프로세서를 추가하는 방법을 안내합니다.
- [Auto-generating docstrings](./auto_docstring)에서는 공유 모델 API에 대해 인자 문서를 수동으로 작성하지 않도록 `@auto_docstring`을 사용하는 방법을 보여 줍니다.
- [모델 테스트 작성](./testing)에서는 새 모델에 대한 통합 테스트를 작성하고 로컬에서 실행하는 방법을 다룹니다.
- [Pull request checks](./pr_checks)는 PR이 병합되기 전에 통과해야 하는 CI 체크 항목과 이를 로컬에서 재현하고 수정하는 방법을 설명합니다.

