# 모델 구조 규칙

Transformers는 모든 `modeling_*.py`, `modular_*.py`, `configuration_*.py` 파일에 대해 일련의 정적 규칙을 적용합니다. [mlinter](https://github.com/huggingface/transformers-mlinter) 패키지가 체크어 엔진을 제공하며, 저장소는 활성 규칙 집합을 `utils/rules.toml`에 유지합니다. 이 로컬 TOML을 사용하면 새로운 `transformers-mlinter` 릴리스를 기다리지 않고도 규칙을 빠르게 활성화, 비활성화하거나 조정할 수 있습니다.

> [!TIP]
> 완전한 checker 참고 자료 및 사용법에 대해서는 [mlinter 문서](https://huggingface.github.io/transformers-mlinter/)를 참조하세요.

모델링 코드를 추가하거나 변경할 때 기대되는 모델 규약입니다. 이를 통해 코드베이스의 일관성을 유지하고, pipeline parallelism, device maps, weight tying 등의 기능과의 호환성을 보장합니다.

## 검사기 실행

`make typing`은 리포지토리 래퍼를 통해 `mlinter`와 `ty` 타입 체커를 함께 실행하므로 `utils/rules.toml`를 자동으로 적용합니다. 아래 명령어로 동일한 래퍼를 직접 실행할 수 있습니다.

```bash
python utils/check_modeling_structure.py                 # check all modeling files
python utils/check_modeling_structure.py --changed-only  # check only files changed vs origin/main
python utils/check_modeling_structure.py --list-rules    # list all rules and their enabled status
python utils/check_modeling_structure.py --rule TRF001   # show built-in docs for a specific rule
```

`--changed-only` 플래그는 개발 중 가장 빠른 옵션입니다. main branch 대비 수정한 파일만 검사합니다. 래퍼 대신 `mlinter`를 직접 호출하는 경우, 로컬 오버라이드가 적용되도록 `--rules-toml utils/rules.toml`를 전달하세요.

## 위반 사항 수정

규칙 위반이 감지되면 오류는 다음과 같이 표시됩니다:

```
src/transformers/models/acme/modeling_acme.py:18: TRF013: AcmeModel.__init__ does not call self.post_init().
```

규칙 ID를 사용하여 [rules reference](#rules-reference)에서 수정 사항을 조회합니다. TRF013은 [PreTrainedModel](/docs/transformers/v5.25.0/ko/main_classes/model#transformers.PreTrainedModel) 하위 클래스가 `self.post_init()`을 호출하지 않을 때 발생합니다. 해당 메서드는 필수적인 최종 처리 단계를 수행하며, 이를 생략하면 런타임 버그가 발생합니다.

```diff
 class AcmeModel(AcmePreTrainedModel):
     def __init__(self, config):
         super().__init__(config)
         self.layers = nn.ModuleList(
             [AcmeDecoderLayer(config) for _ in range(config.num_hidden_layers)]
         )
+        self.post_init()
```

## 규칙 참조

아래 각 규칙은 강제하는 사항과 수정 사항을 보여주는 diff를 나열합니다. 저장소의 현재 규칙 집합에서 특정 규칙의 내장 문서를 보려면 `python utils/check_modeling_structure.py --rule TRF001`을 실행하세요.

### TRF002

base_model_prefix가 공백이 없는 비어 있지 않은 문자열 리터럴인지 확인합니다. 잘못된 접두사는 가중치 로딩 키 매핑 및 베이스 모델 접근을 깨뜨릴 수 있습니다.

```diff
class AcmePreTrainedModel(PreTrainedModel):
-    base_model_prefix = ""
+    base_model_prefix = "model"
```

### TRF003

forward에서 구식 `if not return_dict: return (x,)` 패턴을 감지합니다. 수동 return_dict 분기는冗長하고 실수가 쉽습니다. @capture_output 또는 @can_return_tuple를 사용하세요.

```diff
-def forward(self, x, return_dict=None):
-    if not return_dict:
-        return (x,)
-    return AcmeModelOutput(last_hidden_state=x)
+@can_return_tuple
+def forward(self, x):
+    return AcmeModelOutput(last_hidden_state=x)
```

### TRF004

모델 클래스가 tie_weights 메서드를 정의하지 않는지 확인합니다. tie_weights를 오버라이드하면 로딩, device_map 계산 및 저장 기능이 깨집니다. _tied_weights_keys 클래스 속성에 묶인 가중치를 선언하세요.

```diff
-def tie_weights(self):
-    self.lm_head.weight = self.emb.weight
+class AcmeForCausalLM(AcmePreTrainedModel):
+    _tied_weights_keys = ["lm_head.weight"]
```

### TRF005

존재하는 경우 _no_split_modules의 shape를 확인합니다. 잘못된 값은 device-map 파티셔닝과 샤딩을 깨뜨릴 수 있습니다.

```diff
-_no_split_modules = [SomeLayerClass, ""]
+_no_split_modules = ["AcmeDecoderLayer", "AcmeAttention"]
```

### TRF006

forward 시그니처의 cache 인자가 본문에서 사용되었는지 확인합니다. 사용되지 않는 cache 인자는 캐싱 지원이 불완전하고 API 동작이 일관되지 않음을 시사합니다.

```diff
def forward(self, x, cache=None, use_cache=False):
+    if use_cache:
+        ...
     return x
```

### TRF007

__init__에서 self.post_init() 호출 이후에 self 속성이 할당되는지 확인합니다. post_init 이후에 모델 구조를 변경하면 초기화 및 마무리 처리가 우회됩니다.

```diff
def __init__(self, config):
     ...
-    self.post_init()
-    self.proj = nn.Linear(...)
+    self.proj = nn.Linear(...)
+    self.post_init()
```

### TRF008

모델 클래스에 add_start_docstrings가 비어 있지 않은 인수를 받는지 확인합니다. 인수가 비어 있으면 명확하지 않고 품질이 낮은 API 문서가 생성됩니다.

```diff
-@add_start_docstrings("")
+@add_start_docstrings("The Acme model.")
 class AcmeModel(AcmePreTrainedModel):
     ...
```

### TRF009

모델의 제공 구현 파일(modeling_*, configuration_*, processing_*, image_processing_*, video_processing_*, feature_extraction_*, tokenization_* 및 generation_*.py)에서 다른 모델의 패키지로의 import를 플래그합니다. 세 가지 형태가 해당됩니다: 패키지 경로(`from transformers.models.other.modeling_other import X`), 상대 경로(`from ..other.configuration_other import X`), 공개 API(`from transformers import OtherModel`). 마지막 경우의 경우, 클래스 이름에서 소유 디렉터리를 추론하고 해당 클래스가 정의하는 클래스와 대조하여 확인하므로, 해석할 수 없는 이름은 그대로 두어 처리합니다. 범위 밖 항목: `modular_*.py`(다른 모델을 기반으로 구축하는 것이 그 목적이며, 변환기가 이러한 import를 평탄화하여 제거함), `convert_*.py`, `__init__.py`, `auto` 하위 파일. 허용되는 대상: 모델 자체의 디렉터리, `auto`, `timm_wrapper`. 하나의 모델, 하나의 정의: 모델 A의 동작은 모델 A 자신의 파일에 존재해야 하며, 모델 B에 대한 변경이 모델 A를 은밀하게 변경해서는 안 됩니다 -- modeling뿐 아니라 모든 파일 종류에 대해 해당됩니다. AutoConfig와 CONFIG_MAPPING를 통해 하위 설정에 접근하고, 다른 모델의 코드를 기반으로 구축하려면 modular 파일을 사용하세요.

```diff
-from transformers.models.llama.modeling_llama import LlamaAttention
-from transformers import CLIPTextModelWithProjection
+# Keep implementation local to this model's own files.
+# To build on another model, write modular_acme.py; to reuse a snippet,
+# copy it with a # Copied from comment.
```

### TRF010

configuration_*.py와 modular_*.py에 있는 PreTrainedConfig/PretrainedConfig의 직접 하위 클래스가 @strict(accept_kwargs=True)를 포함하는지 확인합니다. 이 데코레이터가 없으면 새로운 config가 저장소의 런타임 타입 검증 계약에서 누락되고, dataclass 기반 config 표준에서 벗어납니다.

```diff
+@strict(accept_kwargs=True)
 class AcmeConfig(PreTrainedConfig):
     ...
```

### TRF011

PreTrainedModel 하위 클래스의 forward()에서, self.layers에 대한 반복 변수와 self. 뒤에 오는 표준 nn.Module 속성이 아닌 속성에 대한 플래그가 torch.nn.Identity가 갖지 않는 서브모듈 속성 접근을 나타냅니다. 파이프라인 병렬화는 어떤 서브모듈이든 torch.nn.Identity로 대체할 수 있으므로, 해당 서브모듈에서 커스텀 속성(예: decoder_layer.attention_type)을 읽으면 런타임에 AttributeError가 발생합니다. 레이어별 메타데이터는 self.config에서 읽어 주십시오.

```diff
def forward(self, ...):
-    for decoder_layer in self.layers:
+    for i, decoder_layer in enumerate(self.layers):
         hidden_states = decoder_layer(
             hidden_states,
-            attention_mask=causal_mask_mapping[decoder_layer.attention_type],
+            attention_mask=causal_mask_mapping[self.config.layer_types[i]],
         )
```

### TRF012

Flags in-place ops (.normal_(), .zero_(), ...) on module weights inside _init_weights. Parameters carry internal flags tracking whether they still need re-initialization; in-place ops bypass them. Use the `init` primitives.

```diff
+from transformers import initialization as init
+
 def _init_weights(self, module):
-    module.weight.normal_(mean=0.0, std=0.02)
+    init.normal_(module.weight, mean=0.0, std=0.02)
```

### TRF013

__init__을 정의하는 모든 PreTrainedModel 하위 클래스가 self.post_init()을 호출하는지 확인합니다. 모듈러 파일에서는 super().__init__()도 해당되며, 이는 부모의 post_init을 전파하기 때문입니다. post_init은 가중치 초기화, 그래디언트 체크포인트 설정 등 필수적인 최종 처리를 수행하며, 이를 건너뛰면 미묘한 런타임 버그가 발생합니다.

```diff
class AcmeModel(AcmePreTrainedModel):
     def __init__(self, config):
         super().__init__(config)
         self.layers = nn.ModuleList(...)
+        self.post_init()
```

### TRF014

네이티브 모델 통합 파일에서 사용되거나 전달(예: kwarg로)된 `trust_remote_code` 플래그. `trust_remote_code`는 바이너리를 포함한 임의의 코드를 로드합니다. 이는 사용자에게 유용한 강력한 기능이지만, 원격 코드는 transformers에서 검토하거나 유지보수할 수 없으므로 네이티브 통합이 의존해서는 안 됩니다.

```diff
class AcmeModel(AcmePreTrainedModel):
     def __init__(self, config):
         super().__init__(config)
-        self.model = AutoModel.from_pretrained(..., trust_remote_code=True)
+        self.model = AutoModel.from_pretrained(...)
```

### TRF015

PreTrainedModel의 하위 클래스가 비어 있지 않은 _tied_weights_keys를 설정하면, tie_word_embeddings 필드가 있는지 동반 구성 파일(companion configuration file)을 검사합니다. 이 필드가 없으면 사용자가 가중치 연결(weight tying)을 제어할 수 없으며, 모델은 무조건적으로 가중치를 연결하게 되어 직렬화 왕복(serialization round-trip)과 연결되지 않은 헤드(untied heads)를 사용한 미세 조정(fine-tuning)이 깨집니다.

```diff
# configuration_foo.py
 @strict(accept_kwargs=True)
 class FooConfig(PreTrainedConfig):
     hidden_size: int = 768
+    tie_word_embeddings: bool = True
```

### TRF016

image_processing_*.py 또는 video_processing_*.py 클래스가 do_resize, do_rescale, do_normalize, do_convert_rgb, ...와 같은 do_* 불리언 속성을 선언하고 preprocess() 또는 _preprocess()를 오버라이드하는 경우, 각 플래그가 해당 메서드에서 여전히 소비되는지 확인합니다. 직접 참조되거나, super().preprocess/_preprocess(..., **kwargs)를 통해 위임되거나, 또는 -- 이미지 프로세서의 경우 -- _preprocess_image_like_inputs/_prepare_image_like_inputs를 통해 전달되는지 확인합니다. do_sample_frames는 예외입니다. 베이스 preprocess()가 _preprocess() 실행 전에 이를 소비하기 때문입니다. 오버라이드에서 참조하지 않는 do_X는 죽은 코드입니다. do_X=False로 설정해도 효과가 없으며, 해당 연산은 여전히 실행되고, 호출 단위 오버라이드가 조용히 깨집니다.

```diff
class AcmeVideoProcessor(BaseVideoProcessor):
     do_resize = True
     do_normalize = True

     def _preprocess(
         self,
         videos,
+        do_resize: bool,
+        do_normalize: bool,
         size,
         image_mean,
         image_std,
         **kwargs,
     ):
         for video in videos:
-            video = self.resize(video, size=size)
-            video = self.normalize(video, image_mean, image_std)
+            if do_resize:
+                video = self.resize(video, size=size)
+            if do_normalize:
+                video = self.normalize(video, image_mean, image_std)
```

### TRF017

과 를 모두 가진 클래스에서 이 먼저 적용되는지 확인합니다. 데코레이터는 아래에서 위로 적용되므로, 위에 있는 가 먼저 실행되어 아직 생성된 __init__이 없는 클래스에 적용됩니다. 그러면 서브클래스의 대신 부모 클래스의 __init____doc__를 수정하게 됩니다.

```diff
-@dataclass
 @auto_docstring(
     custom_intro="""
     Output type of `AcmeForPreTraining`.
     """
 )
+@dataclass
 class AcmeForPreTrainingOutput(ModelOutput):
     ...
```

### TRF018

모든 `_init_weights(self, module, ...)`를 오버라이드하는 PreTrainedModel 하위 클래스가 `super()._init_weights(...)`를 통해 체이닝되는지 확인합니다. 모듈러 파일은 `PreTrainedModel._init_weights(self, module)`, `PreTrainedModel._init_weights(module)` 및 `raise AttributeError(...)`라는 센티널도 허용합니다. 의도적인 전체 오버라이드의 경우, 해당 메서드 위에 `# trf-ignore: TRF018`를 추가하여 억제할 수 있습니다. 기본 `_init_weights`는 표준 모듈 유형(Linear, Embedding, LayerNorm, RotaryEmbedding, ...)을 처리합니다. 이를 건너뛰면 오버라이드가 놓친 모든 서브모듈이 초기화되지 않은 상태로 남아, 테스트는 통과하지만 나중에 미묘한 가중치 초기화 버그로 드러나는 문제가 발생합니다(https://github.com/huggingface/transformers/pull/45597 참조).

```diff
from ... import initialization as init

 def _init_weights(self, module):
+    super()._init_weights(module)
     if isinstance(module, AcmeCustomLayer):
-        module.gate.data.zero_()
+        init.zeros_(module.gate)
```

### TRF019

`processing_*.py`의 `*ProcessorKwargs` TypedDict에서 비어 있지 않은 `_defaults`를 플래그로 표시합니다. 기준일 이전에 릴리스된 모델은 예외로 처리됩니다. 하드코딩된 `_defaults`는 프로세서 설정을 Python 소스에 분산시켜 config에서 오버라이드하기 어렵고, 코드 부피를 증가시킵니다. 허브의 `processor_config.json`에는 체크포인트와 함께 저장되어 코드 변경 없이 업데이트할 수 있습니다.

```diff
class Gemma4ProcessorKwargs(ProcessingKwargs, total=False):
-    _defaults = {
-        "text_kwargs": {"padding": False},
-        "images_kwargs": {"return_tensors": "pt"},
-    }
     images_kwargs: Gemma4ImageProcessorKwargs
```

### TRF020

`kv_lora_rank`(Multi-head Latent Attention)을 선언하는 모델 디렉터리에서, KV LoRA 확장 투영(`kv_b_proj` 또는 `nn.Linear(config.kv_lora_rank, ...)`)을 소유하는 어텐션 클래스를 검사합니다. 확장은 `forward()`가 호출하는 전용 메서드(예: `expand_kv`)에 포함되어야 하며, 인라인으로 작성되어서는 안 됩니다. 모듈러 파일의 경우, 가져온 베이스에서 상속된 메서드도 해당됩니다. 외부 백엔드(vLLM/SGLang)는 확장을 오버라이드하여 압축된 KV 캐시를 직접 소비합니다. `forward()`에 인라인으로 작성되면 오버라이드할 대상이 없으므로, 백엔드가 전체 캐시를 물리적으로 생성해야 하며, 이는 MLA가 존재하는 목적인 메모리 절감 효과를 잃게 됩니다.

```diff
+    def expand_kv(self, k_nope, k_pe):
+        key_shape = (*k_nope.shape[:-1], -1, self.qk_nope_head_dim + self.v_head_dim)
+        k_nope = self.kv_b_proj(k_nope).view(key_shape).transpose(1, 2)
+        k_nope, value_states = torch.split(k_nope, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
+        k_pe = k_pe.expand(*k_nope.shape[:-1], -1)
+        key_states = torch.cat((k_nope, k_pe), dim=-1)
+        return key_states, value_states
+
     def forward(self, hidden_states, ...):
         ...
-        k_nope = self.kv_b_proj(k_pass).view(key_shape).transpose(1, 2)
-        k_nope, value_states = torch.split(k_nope, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
-        k_pe = k_rot.expand(*k_nope.shape[:-1], -1)
-        key_states = torch.cat((k_nope, k_pe), dim=-1)
+        key_states, value_states = self.expand_kv(k_pass, k_rot)
```

### TRF021

modeling_*.py와 modular_*.py에서, `<value>`가 Python 스칼라로 증명 가능하게 해석되는 경우 `torch.tensor(<value>, ..., device=<non-cpu>)` 플래그가 설정됩니다. 여기에는 숫자 리터럴 및 이에 대한 산술 연산, torch.finfo/iinfo 필드, 스칼라를 반환하는 내장 함수 및 math.* 호출, 정확히 한 번만 바인딩된 로컬 변수, 클래스 본문에서 self.에 할당된 값, 그리고 동반 구성 파일에서 int/float/bool로 주석 처리된 config 필드(attribute_map을 따름)가 포함됩니다. 시퀀스일 수도 있는 것(`eos_token_id: int | list[int] | None`)이나 해석할 수 없는 것은 그대로 두는 것입니다. __init__, _init_weights, __post_init__ 및 post_init은 예외입니다. 이들은 캡처 영역 내에서 절대 실행되지 않기 때문입니다. torch.tensor(, device=)는 값을 호스트에 구현한 다음 디바이스로 복사합니다. CUDA 그래프 캡처는 이 복사를 금지하므로 모델을 캡처할 수 없습니다. torch.full((), , dtype=..., device=...)는 캡처 가능한 커널과 동기화 없이 동일한 0-d 텐서를 디바이스에서 채웁니다.

```diff
def get_placeholder_mask(self, input_ids, inputs_embeds):
     special_image_mask = (
         inputs_embeds
         == self.get_input_embeddings()(
-            torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+            torch.full((), self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
         )
     ).all(-1)
```

### TRF022

modeling_*.py 또는 modular_*.py 파일의 `_no_split_modules` 목록에 포함된 모든 문자열이 해당 파일에서 정의된 클래스, 해당 파일로 가져온 클래스, 또는 동일한 모델 디렉토리의 형제 모듈에서 정의된 클래스를 가리키는지 확인합니다. 값의 형태만 검사하는 TRF005를 보완합니다. `device_map`은 런타임에 이러한 문자열을 `module.__class__.__name__`와 비교하므로, 오래되었거나 오타가 있는 이름은 아무것도 일치하지 않고 조용히 무시됩니다. 그 결과, 함께 유지되어야 할 모듈이 여러 디바이스에 걸쳐 분리될 수 있습니다. 다른 모델의 클래스를 가리키는 항목은 수정하지 말고 삭제하세요. `post_init`이 이미 자식 서브모델에서 `_no_split_modules`를 수집하기 때문입니다.

```diff
class VideoLlavaPreTrainedModel(PreTrainedModel):
-    _no_split_modules = ["VideoLlavaVisionAttention"]
```

### TRF023

configuration_*.py와 modular_*.py에서, `*Config` 필드가 정석적인 이름 대신 업스트림 논문의 약칭으로 명명된 경우를 플래그합니다: d_model/n_embd -> hidden_size, d_ff/d_inner/ffn_dim/ffn_hidden_size/expansion_ratio -> intermediate_size, d_head -> head_dim, n_head/n_heads -> num_attention_heads, n_layer/n_layers/num_blocks -> num_hidden_layers. 필드는 클래스 본문과 __init__/__post_init__의 할당 및 기본값에서 읽힙니다. 모호하지만 관용적인 이름(num_heads, num_layers, embed_dim, mlp_ratio)은 플래그하지 않으며, cutoff_date 이전에 추가된 모델은 기존 이름을 유지합니다. 모델의 shape을 읽는 모든 것 -- device_map 계획, 텐서/파이프라인 병렬 계획, 양자화, PEFT, 어텐션 백엔드 선택, `attribute_map` 소비자 -- 은 정석적인 이름을 조회하므로, 설정이 동일한 양을 `d_model`로 표기하면 이 모든 것에서 조용히 제외됩니다. 변환 스크립트에서 체크포인트 자체의 표기를 매핑하세요.

```diff
@strict(accept_kwargs=True)
 class AcmeConfig(PreTrainedConfig):
-    d_model: int = 1024
-    d_ff: int = 4096
-    n_heads: int = 16
-    n_layers: int = 24
+    hidden_size: int = 1024
+    intermediate_size: int = 4096
+    num_attention_heads: int = 16
+    num_hidden_layers: int = 24
```

### TRF024

modeling_*.py와 modular_*.py에서, torch.nn 생성자(Linear, Embedding, LayerNorm, RMSNorm, GroupNorm, BatchNorm*, InstanceNorm*, Conv*d, ConvTranspose*d, Bilinear, MultiheadAttention)의 차원 인수로 8보다 큰 정수 리터럴이 위치 인자 또는 키워드 인자(in_features, out_features, in_channels, out_channels, num_embeddings, embedding_dim, embed_dim, normalized_shape, num_channels, hidden_size)로 지정된 경우를 플래그로 표시합니다. 연산자 형태 인자(kernel_size, stride, padding, num_groups)는 무시하며, 8 이하의 리터럴은 스칼라 헤드, 바이너리 분류기, RGB 채널 수를 깔끔하게 유지합니다. cutoff_date 이전에 추가된 모델은 예외입니다. 하드코딩된 폭은 모듈을 하나의 체크포인트 크기에 고정시킵니다. 동일한 아키텍처를 다른 스케일로 로드하면 형태 불일치가 발생하며, 어떤 값이 잘못된지 알 수 없도록 설정 필드가 해당 값을 가리키지 않기 때문에 `from_pretrained`가 이를 알려줄 수 없습니다. 또한 진실의 원천이 분리되어 설정을 수정해도 생성되는 모델이 더 이상 변경되지 않습니다.

```diff
class AcmeAtomEmbedding(nn.Module):
     def __init__(self, config):
         super().__init__()
-        self.proj = nn.Linear(768, 3072, bias=False)
-        self.norm = nn.LayerNorm(3072)
+        self.proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
+        self.norm = nn.LayerNorm(config.intermediate_size)
```

### TRF025

modeling_*.py와 modular_*.py에서, PreTrainedModel을 상속하지 않는 클래스(레이어, 어텐션 모듈, 인코더와 같은 일반 nn.Module 블록) 내부에서 마스크 팩토리를 호출하는 플래그가 있습니다(마스킹 유틸리티의 진입점인 create_causal_mask, create_bidirectional_mask, create_sliding_window_causal_mask, create_chunked_causal_mask, create_masks_for_generate 및 기타 create_*_mask 헬퍼 포함). 마스크 생성은 시퀀스 길이의 제곱에 비례하는 O(sequence length squared) 작업이며 레이어마다 변하지 않으므로, 레이어에서 이를 생성하면 레이어마다 해당 비용을 한 번씩 지불하게 됩니다. 또한 각 레이어가 자체 마스크를 소유하게 되어 어텐션 백엔드에 단일 준비된 마스크를 전달할 수 없게 됩니다. 모델에서 한 번만 생성하고 아래로 전달하세요.

```diff
class AcmeLayer(nn.Module):
     def forward(self, hidden_states, attention_mask=None, **kwargs):
-        attention_mask = create_causal_mask(
-            config=self.config, input_embeds=hidden_states, attention_mask=attention_mask, ...
-        )
         return self.self_attn(hidden_states, attention_mask, **kwargs)

 class AcmeModel(AcmePreTrainedModel):
     def forward(self, input_ids=None, attention_mask=None, **kwargs):
+        causal_mask = create_causal_mask(
+            config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, ...
+        )
         for layer in self.layers:
-            hidden_states = layer(hidden_states, attention_mask, **kwargs)
+            hidden_states = layer(hidden_states, causal_mask, **kwargs)
```

### TRF026

modeling_*.py와 modular_*.py에서, __init__와 forward만 정의하고 __init__에서 정확히 하나의 self.를 할당하며, forward 본문이 해당 속성에 대해 정확히 `return self.<attr>(...)`인(선두의 docstring은 무시됨) PreTrainedModel이 아닌 클래스를 플래그합니다. forward에서 다른 메서드, 추가 속성, return 이전의 문장, 또는 `super()` 호출이 있으면 해당 클래스가 자체적인 작업을 수행한다고 간주됩니다. 래퍼는 모든 가중치 이름, _no_split_modules, 병렬화 계획 및 모든 변환 매핑에 레벨을 하나 추가하지만 아무것도 계산하지 않으며, 이를 확인하려면 독자가 한 클래스를 더 열어야 합니다. PreTrainedModel 하위 클래스는 예외입니다: forward가 위임만 하더라도 from_pretrained와 auto 클래스를 위해 존재하기 때문입니다.

```diff
-class AcmeAtomTransformer(nn.Module):
-    def __init__(self, config):
-        super().__init__()
-        self.encoder = AcmeEncoder(config)
-
-    def forward(self, hidden_states, **kwargs):
-        return self.encoder(hidden_states, **kwargs)
-
 class AcmeModel(AcmePreTrainedModel):
     def __init__(self, config):
         super().__init__(config)
-        self.atom_transformer = AcmeAtomTransformer(config)
+        self.encoder = AcmeEncoder(config)
```

### TRF027

modeling_*.py, modular_*.py, configuration_*.py 파일 내의 모든 `assert` 문장을 감지합니다. `python -O`는 assert를 제거하므로, `assert`로 작성된 shape 또는 config 검증은 최적화 실행 시 조용히 사라집니다. 또한 `assert`는 단순한 AssertionError만 반환하지만, ValueError는 문제의 값과 그에 대한 조치 방법을 명시할 수 있습니다.

```diff
def forward(self, hidden_states):
-    assert hidden_states.dim() == 3
+    if hidden_states.dim() != 3:
+        raise ValueError(f"Expected a 3D tensor, got shape {tuple(hidden_states.shape)}.")
```

### TRF028

modeling_*.py, modular_*.py, configuration_*.py, processing_*.py, image_processing_*.py 및 video_processing_*.py 파일의 첫 25줄을 검사하여 `Licensed under the <name> License` 줄 뒤에 표준 보증 문단의 모든 조항이 `You may obtain a copy of the License at`부터 `limitations under the License.`까지 연속적으로 존재하는지 확인합니다. 줄은 먼저 평탄화되고 소문자로 변환되므로 줄바꿈이나 주석 스타일은 검사 대상이 아닙니다. 라이선스 이름과 저작권 줄은 모델마다 달라지므로 검사하지 않습니다. 헤더 없이 배포된 파일은 출처가 불분명해지며, 나중에 헤더를 추가하려면 이미 릴리스된 파일을 수정해야 합니다. `Apache License`만 일치하도록 검사하면 실제로 발생하는 결함을 놓치게 됩니다. 예를 들어 문단이 중간에 잘리거나, 헤더가 URL 이후로 중단되거나, 잘못된 검색 및 치환으로 인해 헤더가 손상되는 경우 등이 해당됩니다.

```diff
+# Copyright 2026 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# ...
 """PyTorch Acme model."""
```

### TRF029

modeling_*.py와 modular_*.py에서, `config`와 함께 이름이 명확하게 config 필드(hidden_size, num_attention_heads, intermediate_size, head_dim, num_hidden_layers, embed_dim, dropout, eps, patch_size, rope_theta, ...)인 인수를 받는 `__init__`를 플래그로 표시합니다. 기본값이 `None`인 선택적 파라미터는 예외입니다. 이는 오버라이드이며 두 번째 진실의 원천이 아니므로, 하나의 MLP 클래스가 MoE 모델의 dense 폭과 expert 폭을 모두 처리하는 방식입니다. `hidden_size: int = 1024`와 같은 하드코딩된 기본값은 예외가 아닙니다. 호출자가 아무것도 전달하지 않으면 config보다 우선하기 때문입니다. kosmos2는 허용 목록에 포함되어 있습니다. 해당 문서 페이지가 디렉터리 이름에서 유도될 수 없으므로, 기준 시점 이전의 기존 상태를 인정할 수 없습니다. 이제 동일한 숫자가 두 개의 진실의 원천을 가지게 되어 호출자가 승자를 선택하므로, config를 수정해도 생성되는 모델이 더 이상 변경되지 않습니다. 또한 아키텍처 지식을 그 자리에 속하지 않는 모든 호출 지점으로 밀어냅니다.

```diff
class AcmeAttention(nn.Module):
-    def __init__(self, config, embed_dim, num_heads, dropout):
+    def __init__(self, config, layer_idx=None):
         super().__init__()
-        self.embed_dim = embed_dim
-        self.num_heads = num_heads
+        self.embed_dim = config.hidden_size
+        self.num_heads = config.num_attention_heads

 class AcmeMLP(nn.Module):
     # an optional override is fine: omitting it reads the config
     def __init__(self, config, intermediate_size=None):
         super().__init__()
         self.intermediate_size = intermediate_size or config.intermediate_size
```

### TRF030

modeling_*.py와 modular_*.py에서 `config` 또는 `self.config`를 루트로 하는 3단계 이상의 플래그 속성 체인을 사용합니다. `config.hidden_size`(1단계)와 `config.text_config.hidden_size`(2단계, 일반적인 서브-설정 접근)는 문제없습니다. 한 줄당 위반 사항이 하나입니다. `config.diffusion_config.atom_encoder_config.hidden_size`를 탐색하는 모듈은 자신의 슬라이스 전체가 아닌 전체 설정 계층에 결합되어 있어 재사용, 테스트 또는 다른 서브-설정 할당이 불가능합니다. 관련 서브-설정을 아래로 전달하면 체인이 1단계로 축소됩니다.

```diff
class AcmeAtomEncoder(nn.Module):
     def __init__(self, config):
         super().__init__()
-        self.norm = AcmeLayerNorm(config.diffusion_config.atom_encoder_config.hidden_size)
+        self.norm = AcmeLayerNorm(config.hidden_size)
```

### TRF031

modeling_*.py와 modular_*.py에서, 상위 레벨의 `@dataclass`가 `Output`로 끝나는 베이스 클래스를 포함하지 않는 경우, 필수 필드가 두 개 이상인 경우를 제외하고는 플래그가 설정됩니다. 이러한 클래스는 내부 인자 번들이며, `ModelOutput`는 런타임에 이를 거부합니다. 일반 출력 dataclass는 튜플처럼 인덱싱할 수 없고, `return_dict=False`를 유지하지 못하며, @auto_docstring에 의해 감지되지 않으므로 해당 필드가 생성된 API 문서에 반영되지 않습니다. ModelOutput은 이 세 가지 기능을 모두 자동으로 제공합니다.

```diff
@auto_docstring
 @dataclass
-class AcmeStructureOutput:
+class AcmeStructureOutput(ModelOutput):
     positions: torch.Tensor
     confidence: Optional[torch.Tensor] = None
```

### TRF032

modeling_*.py와 modular_*.py에서, 크기가 1e3 이상인 부호 반전된 숫자 리터럴로 호출된 masked_fill, masked_fill_, full, full_like, new_full 플래그가 있습니다. 하드코딩된 -1e9는 float16에서 -inf로 오버플로우되며 float32의 최소값과는 매우 멀기 때문에, 동일한 마스크가 dtype별로 다르게 동작하여 softmax 이후 NaN을 생성할 수 있습니다. `torch.finfo(dtype).min`은 실제로 실행 중인 dtype에서 표현 가능한 최소값입니다.

```diff
-attention_scores = attention_scores.masked_fill(~mask, -1e9)
+attention_scores = attention_scores.masked_fill(~mask, torch.finfo(attention_scores.dtype).min)
```

### TRF033

modeling_*.py와 modular_*.py에서 `set_`로 시작하는 메서드를 플래그로 표시합니다. 단, PreTrainedModel 계약 메서드인 set_input_embeddings, set_output_embeddings, set_decoder, set_encoder, set_attn_implementation, set_default_language는 제외합니다. 세터(setter)는 동작을 호출 순서에 의존하게 만듭니다. 해당 값은 config에 존재하지 않으므로 저장되지 않고, from_pretrained에 의해 복원되지 않으며, device-map이나 병렬화 계획에서도 보이지 않습니다. 사용자가 이를 호출해야 한다는 사실을 알아야 하며, 호출을 잊으면 아무런 경고 없이 무시됩니다.

```diff
class AcmeTriangleAttention(nn.Module):
-    def set_chunk_size(self, chunk_size):
-        self.chunk_size = chunk_size
+    def __init__(self, config):
+        super().__init__()
+        self.chunk_size = config.chunk_size
```

### TRF034

modeling_*.py와 modular_*.py에서, `nn.ModuleList(...)`에 인스턴스화되었지만 베이스 체인을 통해 `GradientCheckpointingLayer`에 도달하지 않는 로컬 정의 `*Layer`/`*Block` 클래스를 플래그로 표시합니다. modular 파일은 형제 모델로의 상대적 가져오기를 따르며, 해결되지 않은 체인은 결론을 내릴 수 없습니다. 범위 밖: `supports_gradient_checkpointing = True`를 설정하지 않는 모델은 레이어를 건너뛰는 대신 `gradient_checkpointing_enable()`에서 예외를 발생시키며, `nn.BatchNorm*`/`nn.InstanceNorm*`를 보유하는 레이어는 통계값이 두 번 재계산되고, `self.x = Y(...)`로 할당된 attention, modulation, mixer 또는 SSM 모듈로 확인되는 모델의 토크 믹서가 아닌 스택입니다. `gradient_checkpointing_enable()`는 레이어가 GradientCheckpointingLayer인 경우에만 해당 레이어를 래핑합니다. 트렁크의 일반 nn.Module은 조용히 건너뛰어, 전체 활성화가 할당되는 동안에도 학습이 체크포인트된 것처럼 보이며, OOM은 원인과 먼 곳에서 표면화됩니다. 다른 곳 -- 컨볼루션 백본, 디코딩 헤드 -- 에서는 트레이드오프가 저자의 판단에 맡겨지므로, 이 규칙은 해당 범위를 벗어나 있습니다.

```diff
-class AcmeDecoderLayer(nn.Module):
+class AcmeDecoderLayer(GradientCheckpointingLayer):
     def __init__(self, config, layer_idx):
         super().__init__()
```

### TRF035

modeling_*.py, modular_*.py, configuration_*.py 파일에서 코드가 있든 없든 `# noqa` 주석을 플래그로 표시합니다. modular 파일에서는 `F401`, `F821`, `F822`가 허용됩니다. modular 파일은 의도적으로 사용하는 모든 이름을 정의하지 않는 생성 소스이므로, ruff의 undefined-name 계열이 올바른 코드에서 발동합니다. 예를 들어 컨버터가 채워 넣는 `__all__` 항목, 부모 모델에 있는 클래스, 재수출을 위해 유지되는 import 등이 해당됩니다. 이러한 코드만 명시한 `# noqa`는 건너뛰며, 다른 것을 명시한 경우 남은 코드에 대해 보고합니다. 단독 `# noqa`는 항상 보고됩니다. modular 파일에서는 재작성 대신 코드를 명시하도록 메시지에 요청합니다. 모델 파일은 저장소의 lint 규칙에 따라 관리되는 일반 코드이므로, 억제(suppression)는 근본적인 문제가 그대로 남아 있음을 의미합니다. 또한 단독 `# noqa`는 해당 줄의 모든 향후 위반도 숨깁니다. 대신 코드를 수정하세요.

```diff
-from ...modeling_utils import PreTrainedModel  # noqa: F401
+from ...modeling_utils import PreTrainedModel
```

### TRF036

modeling_*.py와 modular_*.py에서 `nn.Sequential(...)` 구성을 모두 플래깅합니다. Sequential은 자식 모듈을 위치로 이름 붙이므로 가중치가 `mlp.0.weight`와 `mlp.2.weight`에 배치됩니다. 따라서 변환 매핑, _tied_weights_keys, 그리고 모든 병렬화 계획이 인덱스를 참조하게 되며, 레이어를 삽입하면 그 이후의 모든 이름이 변경됩니다. 또한 forward를 가리므로, 단계 사이의 dtype 캐스트와 잔차가 발생하는 위치에서 보이지 않게 됩니다.

```diff
-        self.mlp = nn.Sequential(
-            nn.Linear(config.hidden_size, config.intermediate_size),
-            nn.GELU(),
-            nn.Linear(config.intermediate_size, config.hidden_size),
-        )
+        self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+        self.act = ACT2FN[config.hidden_act]
+        self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
```

### TRF037

modeling_*.py와 modular_*.py에서 einsum 호출을 플래그로 표시하며, 리터럴인 경우 해당 수식을 보고합니다. 기본적으로 비활성화되어 있습니다. einsum이 수축(contraction)을 표현하는 가장 명확한 방법이 될 수 있으므로, 이는 강제 규약이 아닌 선택적(opt-in) 옵션입니다. einsum 수식은 독자가 해석해야 하는 표기로 형태(shape)를 인코딩하며, 동적으로 생성된 수식은 어떤 수축이 실행되는지 가립니다. 이를 명시적인 matmul/transpose 연산으로 전개하세요.

```diff
-        pair_bias = torch.einsum("bqhc,bkhc->bhqk", query_states, key_states)
+        pair_bias = query_states.permute(0, 2, 1, 3) @ key_states.permute(0, 2, 3, 1)
```

### TRF038

모든 modeling_*.py, processing_*.py, image_processing_*.py, video_processing_*.py, feature_extraction_*.py 및 tokenization_*.py 파일에 해당하는 tests/models//test_*.py 파일이 있는지 확인합니다(modeling_acme.py -> tests/models/acme/test_modeling_acme.py). 예외: configuration_*.py는 동반 test_modeling_*.py의 ConfigTester에 의해 커버되며, tokenization_utils*.py는 토크나이저를 통해 커버되는 헬퍼입니다. tokenization__fast.py는 느린 버전의 테스트 파일에 매핑됩니다. modular_*.py는 여러 가지를 한 번에 정의할 수 있으므로, 클래스는 이름 접미사에 따라 라우팅됩니다 -- modeling은 XxxModel/XxxPreTrainedModel/XxxFor, image processing은 XxxImageProcessor(Fast), processing은 XxxProcessor, video processing은 XxxVideoProcessor, feature extraction은 XxxFeatureExtractor, tokenization은 XxxTokenizer(Fast), 건너뜀은 XxxConfig -- 그리고 누락된 테스트 파일마다 위반 사항이 하나씩 보고됩니다. `# trf-ignore: TRF038`은 지원되지 않으며, 예외가 리뷰에서 보이도록 `allowlist_models`를 사용하십시오. 테스트 파일이 없는 소스 파일은 회귀 테스트 커버리지가 없습니다: 손상된 forward pass, 잘못된 변환 매핑, 특수 토큰을 드롭하는 토크나이저 등이 커밋된 후 무기한으로 손상된 상태로 남아 있을 수 있습니다. 랜덤 가중치를 가진 더미 config나 작은 수작업 어휘만으로도 이 중 어떤 것을든 검증할 수 있습니다.

```diff
src/transformers/models/acme/modeling_acme.py
+tests/models/acme/test_modeling_acme.py
 src/transformers/models/acme/tokenization_acme.py
+tests/models/acme/test_tokenization_acme.py
```

### TRF039

`if is_*_available(): import ...` 블록(예: `is_vision_available() and is_torch_available()`과 같은 조합 포함)을 찾아, 해당 이름이 파일 내 다른 어디에서도 참조되지 않는 경우(문자열 타입 힌트 및 __all__ 내부 포함) 해당 import를 플래깅합니다. ruff의 미사용 import 체크는 이를 정리하지 않습니다. import가 도달 가능하기 때문에 블록 자체는 정상적으로 보입니다. 리팩토링 이후 PIL.Image, torch 등이 더 이상 필요하지 않게 되면, 가드된 import는 불필요한 부하이자 파일의 실제 의존성에 대한 오해의 소지를 남깁니다.

```diff
if is_vision_available():
-    from PIL import Image
```

### TRF040

modeling_*.py와 modular_*.py에서 @capture_outputs와 @can_return_tuple로 모두 장식된 플래그 메서드를 감지합니다. forward()의 수동 return_dict 분기를 다루는 TRF003를 보완합니다. 두 장식자 모두 return_dict를 pop하므로 가장 바깥쪽 장식자만 실제 값을 확인합니다. @capture_outputs는 이미 to_tuple 변환을 처리하므로 @can_return_tuple은 중복됩니다.

```diff
-@can_return_tuple
 @merge_with_config_defaults
 @capture_outputs
 @auto_docstring
 def forward(self, x):
     return AcmeModelOutput(last_hidden_state=x)
```

### TRF041

modeling_*.py와 modular_*.py에서, `# CODEPATH:` 주석이 없는 `config.*` 또는 `self.config.*` 속성을 읽는 조건을 가진 모든 `if`/`elif` 및 조건식 표현을 플래그합니다. 해당 주석은 분기 라인에서, 또는 그 바로 위에 연속된 주석 블록 내에서 허용됩니다. 불리언 플래그뿐만 아니라 모든 config 속성이 대상입니다. 구조적으로 면제되는 경우: 테스트되는 필드 자체가 결과 중 하나인 `X if X is not None else fallback`, 그래프를 갈라놓을 수 없는 긴 표기인 `getattr(config, x, default)`, 그리고 한쪽이 중단되어 그 이후로 발산하는 것이 없으므로 본문이 예외를 발생시키거나 경고/로그만 기록하는 `else`가 없는 가드인 `if`입니다. 단순히 None을 언급하는 것만으로는 해당되지 않습니다: `config.vision_config is not None`에도 여전히 주석이 필요합니다. 필드별로 면제되는 경우: 체크포인트 발산을 게이트하지 않는 프레임워크 배선인 `problem_type`이 손실을 선택하는 경우, `hidden_act`가 활성화 함수를 조회하는 경우, `num_labels`, `use_cache`, `is_decoder`, 특수 토큰 id, `summary_*` 헤드 설정입니다. 전체 목록은 `mlinter/trf041.py`의 `DEFAULT_EXEMPT_ATTRIBUTES`이며, 규칙 테이블의 `ignored_attributes = [...]`로 프로젝트별로 확장됩니다. 모델은 0열에 모듈 레벨의 `# trf-ignore: TRF041 config.scale_embedding, config.auxiliary_loss`를 사용하여 파일 전체에서 자신의 필드 중 하나를 면제할 수 있습니다(`self.config.x`, `config.x`, `x`는 동일한 필드입니다). 최소한 하나의 필드를 명시해야 하며, 맨 `# trf-ignore: TRF041`은 라인별 의미를 유지합니다. 조건은 읽는 모든 필드가 면제될 때만 건너뜁니다. config 게이트 분기는 동일한 파일 내의 두 번째 아키텍처이며, 코드는 두쪽이 모두 여전히 도달 가능한지 말할 수 없습니다 -- 이것이 죽은 실험적 분기가 릴리스까지 살아남는 방식입니다. 이 규칙은 분기를 금지하지 않습니다: Rust의 `// SAFETY:`처럼, 각 쪽을 취하는 체크포인트를 그 옆에 기록해 달라고 요구합니다. 아무도 하나를 지목할 수 없는 분기는 삭제해야 할 분기입니다.

```diff
+        # CODEPATH: ESMC-6B ships pre-normalised embeddings, the 300M/600M checkpoints do not.
         if config.use_embedding_norm:
             hidden_states = self.embedding_norm(hidden_states)

-        if config.msa_encoder_enabled:
-            hidden_states = self.msa_encoder(hidden_states)
+        # no released checkpoint sets msa_encoder_enabled -> branch removed
```

### TRF042

tests/models/*/test_tokenization_*.py 파일에서, 해당 파일이 TokenizerTesterMixin을 상속하는 수집 대상 테스트 클래스를 정의하는지 확인합니다. 러너가 수집하는 클래스만 해당됩니다. 즉, `TestCase` 기반 클래스이거나, 기반 클래스가 다른 모델의 테스트 클래스인 경우 `*Test` 네이밍 규칙을 따르는 클래스입니다. 따라서 헬퍼 전용 파일은 건너뛰며, 스위트가 믹스인된 헬퍼만으로는 실제 테스트 클래스에 대한 규칙을 충족하지 못합니다. 상속은 같은 파일 내의 기반 클래스를 따라가며, 이름으로 가져온 다른 모델의 토크나이저 테스트까지 추적합니다. 해석할 수 없는 기반 클래스는 절대 계산되지 않습니다. 스위트를 실행하지 않는 첫 번째 테스트 클래스에 대해 보고됩니다. `auto`는 허용 목록에 포함되어 있습니다. test_tokenization_auto.py는 토크나이저가 아닌 AutoTokenizer의 해석을 테스트하기 때문입니다. TokenizerTesterMixin은 인코딩/디코딩 왕복, 패딩 및 잘라내기, 특수 토큰 처리, 추가된 토큰의 영속성, 저장/로드 동등성이 실제로 확인되는 곳입니다. 몇 개의 수동으로 작성된 토큰 ID 목록만 주장하는 테스트는 토크나이저가 그 모든 항목에서 깨져 있어도 통과하며, 리뷰에서는 테스트가 된 것처럼 보입니다.

```diff
-class AcmeTokenizationTest(unittest.TestCase):
+class AcmeTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
+    tokenizer_class = AcmeTokenizer
+    test_slow_tokenizer = True
```

### TRF043

이름이 Attention으로 끝나는 클래스의 forward 시그니처에서 선언된 position_ids 파라미터를 플래그로 표시합니다. position_ids는 하류에서 flash-attention의 padding-free 학습에 의해 소비되며, 반드시 **kwargs를 통해 전달되어야 합니다. 시그니처에 이름을 명시하면 attention 인터페이스가 읽기 전에 파라미터가 흡수됩니다. llama 표준은 position_embeddings와 **kwargs를 함께 전달합니다.

```diff
class AcmeAttention(nn.Module):
     def forward(
         self,
         hidden_states,
         position_embeddings,
         attention_mask=None,
-        position_ids=None,
         **kwargs: Unpack[TransformersKwargs],
     ):
```

### TRF044

modeling_*.py와 modular_*.py의 모든 함수에서 cache_position이라는 이름의 파라미터를 감지합니다. cache_position은 v5에서 모든 모델에서 제거되었습니다. 이를 다시 도입하는 경우(보통 v5 이전 소스에서 복사한 경우) 모든 레이어에 걸쳐 더 이상 사용되지 않는 인자가 전달됩니다. 캐시 업데이트는 cache.update(key_states, value_states, self.layer_idx)이며, 위치 전달이 없습니다.

```diff
def forward(
     self,
     hidden_states,
     cache=None,
-    cache_position=None,
     **kwargs,
 ):
-    key_states, value_states = cache.update(key_states, value_states, self.layer_idx, cache_position)
+    key_states, value_states = cache.update(key_states, value_states, self.layer_idx)
```

### TRF045

modeling_*.py 및 modular_*.py의 forward 시그니처에서 legacy인 output_attentions, output_hidden_states, return_dict 파라미터를 플래깅합니다. 해당 기한 이전에 기여된 모델은 예외입니다. 데코레이터 스택이 출력 제어를 담당합니다. @capture_outputs는 config에 대해 output_* 플래그를 해석하고 _can_record_outputs를 통해 텐서를 기록하며, @can_return_tuple은 return_dict를 처리합니다. 시그니처에 이를 선언하면 데코레이터와 괴리되는 수동 플래그 스레딩을 다시 도입하게 됩니다.

```diff
+@capture_outputs
 def forward(
     self,
     input_ids,
-    output_attentions=None,
-    output_hidden_states=None,
-    return_dict=None,
     **kwargs: Unpack[TransformersKwargs],
 ):
```

### TRF046

modeling_*.py 및 modular_*.py의 forward 메서드에서 self 속성에 대한 플래그 할당을 표시합니다. forward 중에 기록되는 상태는 배치 처리, torch.compile, 모듈 추론을 방해합니다. 전달되는 상태는 명시적으로 전달됩니다(cache 객체, generate 루프). config 또는 정적 shape에만 의존하는 값은 __init__에 속합니다.

```diff
def forward(self, hidden_states):
-    self.sequence_length = hidden_states.shape[1]
-    embeddings = self.compute_embeddings(self.sequence_length)
+    embeddings = self.compute_embeddings(hidden_states.shape[1])
```

### TRF047

image_processing_*.py 및 video_processing_*.py의 preprocess, _preprocess, __call__, post_process* 메서드에서 self 속성에 대한 플래그 할당을 수행합니다. 호출 사이에 상태를 유지하는 프로세서가 preprocess를 여러 번 수행한 후 postprocess를 수행하는 배치 처리를 깨뜨립니다. 두 번째 preprocess가 첫 번째 postprocess에 필요한 상태를 덮어쓰기 때문입니다. 값을 반환하거나 메서드 체인을 통해 전달하세요.

```diff
def _preprocess(self, images, **kwargs):
-    self.original_sizes = [image.shape[-2:] for image in images]
+    original_sizes = [image.shape[-2:] for image in images]
     ...
+    return BatchFeature(data={"pixel_values": pixel_values, "original_sizes": original_sizes})
```

### TRF048

클래스 레벨의 _tied_weights_keys 선언에서 list/tuple/set 리터럴을 사용합니다. v5에서는 _tied_weights_keys가 각 tied 대상 파라미터를 소스로 매핑하는 dict로 변경되었습니다. list 형식은 더 이상 어떤 파라미터가 소스인지 명시하지 않으므로, tying, device_map 계산 및 저장 과정에서 오류가 조용히 발생합니다.

```diff
class AcmeForCausalLM(AcmePreTrainedModel):
-    _tied_weights_keys = ["lm_head.weight"]
+    _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
```

### TRF049

modeling_*.py와 modular_*.py의 __init__ 메서드에서 초기화 호출을 플래그 처리합니다: nn.init.* / init.* 프리미티브 및 자체 파라미터에 대한 인플레이스 초기화기(self.weight.data.normal_()). 모델은 메타 디바이스에서 인스턴스화되므로 __init__에 기록된 텐서 값은 로딩 전에 폐기됩니다: 해당 위치에서만 초기화된 파라미터는 처음부터 파인튜닝하거나 메타 디바이스에서 다시 로드한 후 랜덤한 내용을 보유하게 됩니다. __init__에서 torch.empty로 할당하고 _init_weights에서 초기화하세요.

```diff
class AcmeEmbeddings(nn.Module):
     def __init__(self, config):
         super().__init__()
         self.position_embedding = nn.Parameter(torch.empty(config.num_positions, config.hidden_size))
-        nn.init.trunc_normal_(self.position_embedding, std=config.initializer_range)

 class AcmePreTrainedModel(PreTrainedModel):
     def _init_weights(self, module):
         super()._init_weights(module)
+        if isinstance(module, AcmeEmbeddings):
+            init.trunc_normal_(module.position_embedding, std=self.config.initializer_range)
```

### TRF050

이름이 Attention으로 끝나는 클래스의 __init__에서 *RotaryEmbedding 클래스에 대한 호출을 플래그 처리합니다. Model은 rotary_emb를 하나만 소유하며, inv_freq를 한 번만 생성한 뒤 cos/sin을 position_embeddings로 아래로 전달합니다. 어텐션 레이어마다 하나의 rotary 모듈을 두면 버퍼가 중복되고, 레이어마다 주파수를 다시 계산하며, 어텐션이 position_embeddings를 받는다는 계약에서 벗어나게 됩니다.

```diff
class AcmeAttention(nn.Module):
     def __init__(self, config, layer_idx):
         super().__init__()
-        self.rotary_emb = AcmeRotaryEmbedding(config)

 class AcmeModel(AcmePreTrainedModel):
     def __init__(self, config):
         super().__init__(config)
+        self.rotary_emb = AcmeRotaryEmbedding(config)
```

### TRF051

modeling_*.py와 modular_*.py에서 _attn_implementation 속성과의 플래그 비교를 수행합니다. 백엔드 디스패치는 ALL_ATTENTION_FUNCTIONS.get_interface에, 백엔드 조건부 텐서 조작(패딩, 리셰이핑)은 integrations/ 아래에 있는 공유 래퍼에 속합니다. 인라인 분기는 모델 본문을 커널 인식 상태로 유지하지만, 새로운 백엔드가 등록되면 깨집니다.

```diff
-if self.config._attn_implementation == "flash_attention_2":
-    attn_output = flash_path(query_states, key_states, value_states)
-else:
-    attn_output = eager_path(query_states, key_states, value_states)
+attention_interface = ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, eager_attention_forward)
+attn_output, attn_weights = attention_interface(self, query_states, key_states, value_states, ...)
```

### TRF052

modeling_*.py 및 modular_*.py 파일에서 _ATTENTION_CLASSES로 끝나는 이름에 대한 모듈 수준 할당을 플래그로 표시합니다. 딕셔너리에서 선택되는 백엔드별 어텐션 클래스는 인터페이스 이전의 관용적 표현입니다. 거의 동일한 클래스들이 서로 달라지고, ALL_ATTENTION_FUNCTIONS에 등록된 허브 어텐션 커널이 이 클래스들에 도달하지 못합니다. 인터페이스를 통해 디스패치되는 단일 어텐션 클래스가 딕셔너리를 대체합니다. 레거시 부모 클래스에서 이를 전파하지 마세요.

```diff
-ACME_ATTENTION_CLASSES = {
-    "eager": AcmeAttention,
-    "flash_attention_2": AcmeFlashAttention2,
-    "sdpa": AcmeSdpaAttention,
-}
+class AcmeAttention(nn.Module):
+    def forward(self, ...):
+        attention_interface = ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, eager_attention_forward)
```

### TRF053

modeling_*.py와 modular_*.py에서, labels[..., 1:]와 같이 슬라이싱을 통해 shift_logits/shift_labels(및 shifted_ 변형)를 구성하는 플래그 할당은 플래그가 지정됩니다. 이미 시프트된 라벨을 받는 것(shift_labels = kwargs.pop("shift_labels", labels))은 올바른 관용 표현이며 플래그가 지정되지 않습니다. self.loss_function은 라벨을 자체적으로 시프트하므로, 모델링 코드에서 사전 시프트를 수행하면 이중 시프트된 대상에 대해 학습하거나 맞춤형 손실 경로를 강제하게 됩니다. 디코더 전용 모델은 원시 라벨을 전달하고 손실 함수가 시프트하도록 합니다. 인코더-디코더 모델은 반대 경우입니다: 이 모델의 라벨은 앞에 붙은 디코더 시작 토큰에 의해 이미 시프트되어 있으므로, 손실 함수가 다시 시프트하는 것을 방지하기 위해 shift_labels=labels를 전달합니다.

```diff
if labels is not None:
-    shift_logits = logits[..., :-1, :].contiguous()
-    shift_labels = labels[..., 1:].contiguous()
-    loss = nn.functional.cross_entropy(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
+    # decoder-only: labels are unshifted, the loss shifts them
+    loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
+    # encoder-decoder: labels are already shifted, hand them over as shift_labels
+    loss = self.loss_function(logits=logits, labels=labels, shift_labels=labels, vocab_size=self.config.vocab_size)
```

### TRF055

`config_class` 플래그, `config = SomeConfig` 할당, `config` 주석이 없는 `<Model>PreTrainedModel`, 그리고 `config` 인자가 주석되지 않았거나 다른 config를 가리키는 `__init__`를 검사합니다. 서브-구성으로 생성된 클래스(`AcmeTextModel(config.text_config)`)는 해당 서브-구성을 선언해야 합니다. `modular_*.py` 파일은 생성하는 파일들을 통해 검사됩니다. `PreTrainedModel`은 `config` 주석에서 `config_class`를 파생합니다. 할당이나 수동으로 작성한 `config_class`는 부모의 값과 일치하거나 벗어나며, 불일치하는 `__init__`는 하나의 config로 모델을 생성하면서 다른 config를 광고하게 됩니다.

```diff
class Gemma4VisionModel(Gemma4PreTrainedModel):
     """The Gemma 4 Vision Encoder."""
-    config = Gemma4VisionConfig
+    config: Gemma4VisionConfig

-    def __init__(self, config):
+    def __init__(self, config: Gemma4VisionConfig):
```

### TRF056

modeling_*.py와 modular_*.py에서 `forward` 내부의 `.item()` 및 `.tolist()` 호출을 플래그로 표시합니다. `split(...)`의 split-size 인수로 전달되는 `.tolist()`는 예외입니다. torch.split은 Python int를 필요로 하기 때문입니다. 두 호출 모두 텐서를 호스트로 다시 읽는데, dynamo는 이를 추적할 수 없으므로 그래프가 끊어집니다.

```diff
-        for grid, item in zip(grid_thw.tolist(), split_items):
-            _, height, width = grid
-            merged.append(self.patch_merger(item, size=(height, width)))
+        for grid, item in zip(grid_thw, split_items):
+            merged.append(self.patch_merger(item, size=(grid[1], grid[2])))
```

### TRF057

공개 `PreTrainedModel` 하위 클래스(`<Model>PreTrainedModel`, `<Model>Model`, `<Model>For<Task>`, backbones), `PreTrainedConfig` 하위 클래스, `ModelOutput` 하위 클래스, 이미지 프로세서, 비디오 프로세서 및 `ProcessorMixin` 하위 클래스, 그리고它们的 공개 메서드 `forward`, `get_image_features`, `get_video_features`, `get_audio_features`, `get_text_features`, `preprocess` 및 `__call__`에 대해 `@auto_docstring`을 확인합니다. `modular_*.py`는 해당 파일에서 생성된 파일과 대조하여 확인됩니다. 이 파일이 없으면 클래스와 그 메서드는 매개변수, 반환 값 및 예시 문서 없이 배포되며, 이후 각 모델에 대해 수동으로 작성해야 합니다.

```diff
+@auto_docstring
 @dataclass
 class AcmeModelOutputWithPast(ModelOutput):
     logits: torch.Tensor | None = None

+@auto_docstring
 class AcmeForConditionalGeneration(AcmePreTrainedModel):
+    @auto_docstring
     def forward(self, input_ids, pixel_values=None, **kwargs):
         ...
```

### TRF058

modeling_*.py와 modular_*.py에서, 버퍼 이름이 문자열 리터럴인 `register_buffer("<name>", ...)` 호출을 플래그합니다. 수신자는 `self`이거나 `layer.mamba`와 같은 다른 모듈일 수 있습니다. 변수나 f-string과 같이 계산된 이름(예: 루프 내에서 레이어당 하나의 버퍼)은 속성 할당과 동등한 표현이 없으므로 예외로 처리됩니다. torch>=2.5부터 `nn.Buffer`는 `nn.Parameter`와 마찬가지로 일반 속성 할당을 통해 버퍼를 등록합니다. 메서드 호출로 생성된 버퍼는 `__init__` 실행의 부수 효과로만 존재하므로, 이를 조정하려는 modular 파일은 `__init__` 전체를 다시 정의해야 합니다. 속성으로 할당되면, 버퍼는 단독으로 상속되고 오버라이드될 수 있습니다.

```diff
-        self.register_buffer("inv_freq", inv_freq, persistent=False)
-        self.register_buffer(
-            "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
-        )
+        self.inv_freq = nn.Buffer(inv_freq, persistent=False)
+        self.position_ids = nn.Buffer(torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
```

### TRF059

tensor-parallel plan에서 `moe_tp_experts`가 할당된 모델 디렉터리의 경우, 라우팅된 `*Experts` 클래스가 hidden states, top-k indices, top-k routing weights를 `forward`의 첫 세 개의 위치 인자로 받는지 확인합니다. `selected_experts`나 `routing_weights`와 같은 별칭도 허용됩니다. `MoeExpertsParallel`은 위치 인자 3에 gradient transform을 적용합니다. 서명이 다르면 잘못된 텐서에 적용되거나 적용이 건너뛰어질 수 있습니다.

```diff
class AcmeExperts(nn.Module):
-    def forward(self, hidden_states):
+    def forward(self, hidden_states, top_k_index, top_k_weights):
         ...
```

### TRF060

`from transformers... import X` 및 `import transformers...` 플래그를 `src/transformers/models/` 아래에서 설정하고 상대 경로 형태(`from ...modeling_utils import X`)를 권장합니다. `convert_*.py` 스크립트는 건너뜁니다. 패키지 내부의 절대적 import는 지연된 최상위 `transformers/__init__.py`를 통해 처리되므로 순환 import를 유발할 수 있으며, transformers의 다른 설치된 복사본으로 해석될 수 있습니다.

```diff
-from transformers.modeling_utils import PreTrainedModel
-from transformers.models.acme.configuration_acme import AcmeConfig
-from transformers import initialization as init
+from ...modeling_utils import PreTrainedModel
+from .configuration_acme import AcmeConfig
+from ... import initialization as init
```

### TRF061

modular_*.py에서 같은 파일의 앞부분에 베이스가 정의된 클래스를 플래그합니다. 다른 모델에서 가져온 베이스, `<Model>PreTrainedModel` 서브클래스 및 하위 호환성 별칭은 플래그되지 않습니다. 컨버터는 다른 모델에서 가져온 베이스는 인라인으로 처리하지만 같은 파일의 베이스는 유지하므로, 생성된 모델링 파일은 상속 관계를 유지하게 되며 더 이상 클래스를 하나씩 읽을 수 없게 됩니다.

```diff
from ..llama.modeling_llama import LlamaDecoderLayer

 class AcmeDecoderLayer(LlamaDecoderLayer):
     pass

-class AcmeSparseDecoderLayer(AcmeDecoderLayer):
+class AcmeSparseDecoderLayer(LlamaDecoderLayer):
     def __init__(self, config, layer_idx):
         super().__init__(config, layer_idx)
         self.mlp = AcmeSparseMoeBlock(config)
```

### TRF062

`_init_weights` 내부에서 호출되는 in-place `torch.nn.init` 초기화 함수(`nn.init.normal_(...)`, 어떤 방식으로 import되었든)에 플래그를 지정합니다. `calculate_gain`처럼 값을 계산만 하는 헬퍼 함수에는 플래그가 지정되지 않습니다. Transformers의 `init` 함수는 체크포인트에서 이미 로드된 텐서를 건너뜁니다. `torch.nn.init`은 `from_pretrained` 동안 적용되는 패치에 의존하는데, 이름으로 import된 함수는 이 패치를 우회할 수 있으므로 로드된 가중치가 조용히 다시 초기화될 수 있습니다.

```diff
from torch import nn
+
+from ... import initialization as init

 def _init_weights(self, module):
     super()._init_weights(module)
     if isinstance(module, AcmeLayerScale):
-        nn.init.constant_(module.lambda1, self.config.layer_scale_init_value)
+        init.constant_(module.lambda1, self.config.layer_scale_init_value)
```

### TRF063

모델 파일이 import 시점에 실행하는 모든 상대 import를 추적하며, import된 파일이 import하는 파일이 선언하지 않은 백엔드를 필요로 하면 이를 플래깅합니다. 해당 백엔드는 기본 요구 사항, `__all__` 객체 중 가장 약한 `@requires`, 또는 `is_<backend>_available()` 가드를 통해 결정됩니다. `modular_*.py` 파일은 해당 파일이 생성하는 파일들을 통해 검사됩니다. lazy module은 선언된 백엔드가 설치되면 파일을 import합니다. 해당 파일이 더 많은 백엔드가 필요한 형제 파일을 import하는 경우, `from transformers import *`는 해당 환경에서 충돌합니다. 예를 들어, Pillow만 설치되고 torch가 없는 환경에서 torchvision 이미지 프로세서를 import하는 비전 전용 프로세서는 실패합니다.

```diff
if is_vision_available():
-    from .image_processing_acme import AcmeImageProcessorKwargs
+    from .image_processing_pil_acme import AcmeImageProcessorKwargs
 
 @requires(backends=("vision",))
 class AcmeProcessor(ProcessorMixin):
```

### TRF064

processing_*.py와 modular_*.py에서 `_defaults`, `text_kwargs`, `images_kwargs`, `videos_kwargs` 또는 `audio_kwargs`를 할당하거나 재주석하는 `ProcessingKwargs` 하위 클래스를 플래그로 표시합니다. `ProcessingKwargs._defaults`는 비추천(deprecated)되었습니다. 기본값은 프로세서의 클래스 속성이며, 다른 속성과 마찬가지로 상속되고 재정의됩니다. 모달리티 필드는 런타임에 서브 프로세서가 로드될 때만 사용 가능한 인자가 알려지기 때문에 기본 타입을 유지합니다.

```diff
class AcmeProcessorKwargs(ProcessingKwargs, total=False):
-    images_kwargs: AcmeImagesKwargs
-    _defaults = {
-        "text_kwargs": {"padding": False},
-        "images_kwargs": {"num_crops": 4},
-    }
+    num_crops: int

 class AcmeProcessor(ProcessorMixin):
     valid_processor_kwargs = AcmeProcessorKwargs
+    text_kwargs = {"padding": False}
+    num_crops: int = 4
```

### TRF065

processing_*.py 파일에서는 `ImagesKwargs`, `TextKwargs`, `AudioKwargs` 또는 `VideosKwargs`를 직접 또는 다른 모델의 하위 클래스를 통해 확장하는 모든 클래스를 플래그로 표시합니다. 서브 프로세서도 포함하는 modular_*.py 파일에서는 `<Model>ImageProcessorKwargs`, `<Model>VideoProcessorKwargs`, `<Model>VideoProcessorInitKwargs` 또는 `<Model>AudioProcessorKwargs`로 이름이 지정된 경우 하위 클래스가 허용됩니다. 모달리티 kwargs는 서브 프로세서 파일(`image_processing_*.py`, `video_processing_*.py`, ...)에 포함되어야 합니다. processing_*.py 파일에서는 서브 프로세서가 동적으로 로드되므로 타입이 지정되지 않은 상태로 유지됩니다.

```diff
-class AcmeImagesKwargs(ImagesKwargs, total=False):
-    num_crops: int
-
-
 class AcmeProcessorKwargs(ProcessingKwargs, total=False):
-    images_kwargs: AcmeImagesKwargs
+    num_crops: int
```

### TRF066

`@requires`에서 파일의 암시적 요구 사항 또는 메서드의 경우 해당 메서드를 포함하는 클래스의 명시적 요구 사항을 반복하는 backends를 플래그로 표시합니다. 또한 `requires_backends(...)`가 `@requires` 데코레이터로 작성될 수 있는 경우와, `@classmethod` 또는 `@staticmethod` 위에 `@requires`가 배치된 경우에도 플래그를 표시합니다. cutoff는 잘못된 위치의 데코레이터를 제외하고 모든 항목에서 이전 모델을 면제합니다. 백엔드 요구 사항을 반복하면 메서드가 실제로 추가하는 의존성이 무엇인지가 가려집니다. 함수 시작 부분의 무조건적인 체크는 `@requires(backends=...)`에 속하며, 이는 의존성 메타데이터를 노출하고 함수가 호출될 때 체크를 수행합니다. 조건부 요구 사항은 `requires_backends`를 유지하세요. `@requires`는 일반 함수를 래핑하므로, `@classmethod` 또는 `@staticmethod` 위에 놓이면 대신 디스크립터를 래핑하여 모든 호출에서 `TypeError`가 발생합니다. 따라서 이 두 데코레이터 아래에 위치해야 합니다.

```diff
# image_processing_pil_acme.py already requires vision.
-@requires(backends=("vision", "torch"))
+@requires(backends=("torch",))
 class AcmeImageProcessorPil(PilBackend):
-    @requires(backends=("torch",))
     def post_process(self, outputs):
         return outputs

+    @requires(backends=("scipy",))
     def refine(self, outputs):
-        requires_backends(self, ["scipy"])
         return outputs
```

### TRF067

modeling_*.py와 modular_*.py에서, 함수가 `.hidden_states[...]`를 인덱스로만 읽는 경우, 모든 hidden state를 활성화하는 호출(`output_hidden_states=True` 또는 `**kwargs`에서 설정)을 플래그합니다. 전체 튜플을 사용하는 코드(반복, 슬라이싱, 스택킹 또는 반환)와 `@filter_output_hidden_states` 백본은 예외입니다. 모든 레이어의 hidden state는 호출이 반환될 때까지 유지되므로, 피크 메모리는 깊이와 함께 증가합니다. `output_hidden_states`는 인덱스 또는 인덱스 목록도 받아 해당 항목만 캡처합니다: `**kwargs`를 전달하는 메서드에 `@select_hidden_states`를 적용하거나, 인덱스를 직접 전달하세요.

```diff
+from ...utils.output_capturing import select_hidden_states
 ...
+    @select_hidden_states("vision_feature_layer")
     def get_image_features(self, pixel_values, vision_feature_layer=None, **kwargs):
-        kwargs["output_hidden_states"] = True
         image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
         selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
 ...
-        outputs = self.img_processor(img_embeds, output_hidden_states=True)
+        outputs = self.img_processor(img_embeds, output_hidden_states=self.layer_idx)
         return outputs.hidden_states[self.layer_idx]
```

### TRF068

각 `_no_split_modules` 항목을 모델링 파일이 정의하거나 가져온 클래스와 대조합니다. `modular_*.py` 파일은 디스크에 생성된 파일들을 통해 검사되므로, 린팅 전에 재생성해야 합니다. accelerate는 이러한 이름을 서브모듈 클래스 이름과 대조합니다. 클래스가 아닌 이름은 절대 일치하지 않으므로 해당 레이어는 여러 디바이스에 걸쳐 분할될 수 있습니다. 이는 일반적으로 `_no_split_modules`를 상속하는 모듈러 파일에서 비롯됩니다. 변환기는 클래스가 아닌 접두사를 이름 변경합니다.

```diff
class Qwen4ExpModel(Qwen3_5MoeModel):
-    # inherits ["Qwen3_5MoeDecoderLayer"] -> converted to "Qwen4ExpDecoderLayer", which does not exist
+    _no_split_modules = ["Qwen4ExpTextDecoderLayer"]
```

## 위반 사항 억제

규칙 위반을 억제해야 하는 경우, 아래 두 옵션 중 하나를 사용하세요.

### 인라인 억제

위반된 줄에 `# trf-ignore: RULE_ID` 주석을 추가합니다. 리뷰어가 왜 억제하는 것이 타당한지 이해할 수 있도록 설명을 포함합니다.

```py
# trf-ignore: TRF011 — mask is derived from self.config, not the layer
hidden_states = layer(hidden_states, attention_mask=mask_from_config)
```

코드에서 수정해야 하는 위반 사항을 무시하기 위해 `trf-ignore`를 사용하지 마세요.

### `allowlist_models`

즉시 수정할 수 없는 레거시 코드가 있는 모델의 경우, 해당 모델의 디렉터리 이름을 [mlinter rules.toml](https://github.com/huggingface/transformers-mlinter/blob/main/mlinter/rules.toml)의 관련 규칙 `allowlist_models` 목록에 추가하세요.

```toml
[rules.TRF004]
allowlist_models = ["existing_model", "your_model_name"]
```

