# 模型结构规则

Transformers 会对每个 `modeling_*.py`、`modular_*.py` 和 `configuration_*.py` 文件执行一组静态规则。[mlinter](https://github.com/huggingface/transformers-mlinter) 包提供了检查器引擎，而仓库在 `utils/rules.toml` 中维护其当前生效的规则集。该本地 TOML 文件让我们能够快速启用、禁用或调整规则，而无需等待新的 `transformers-mlinter` 版本发布。

> [!TIP]
> 请参阅 [mlinter 文档](https://huggingface.github.io/transformers-mlinter/)，了解完整的检查器参考和使用详情。

以下是添加或修改建模代码时应遵循的模型约定。这些约定可保持代码库的一致性，并确保与流水线并行、设备映射和权重绑定等功能兼容。

## 运行检查器

`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` 标志是开发期间最快的选项。它仅检查相对于主分支你所修改的文件。如果你直接调用 `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)中查找对应的修复方法。当[PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)的子类未调用`self.post_init()`时，会触发 TRF013。该方法执行必要的最终化步骤，省略它会导致运行时错误。

```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 是否为非空且不含空白字符的字符串字面量。无效的 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 存在时的形状。格式错误的值可能会破坏设备映射分区和分片。

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

### TRF006

检查 forward 签名中的缓存参数是否在函数体内被使用。未使用的缓存参数表明缓存支持不完整，且 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

Flags 用于标记从某个模型的随附实现文件（modeling_*、configuration_*、processing_*、image_processing_*、video_processing_*、feature_extraction_*、tokenization_* 和 generation_*.py）中导入到另一个模型包的内容。以下三种形式会被计入：包路径（`from transformers.models.other.modeling_other import X`）、相对路径（`from ..other.configuration_other import X`）以及公共 API（`from transformers import OtherModel`）——对于最后一种，所属目录会根据类名推断，并与该类定义的类进行核对，因此无法解析的名称会被保留原样。不在范围内的包括：`modular_*.py`（基于另一个模型构建正是其用途，且转换器会扁平化这些导入）、`convert_*.py`、`__init__.py` 以及 `auto` 下的文件。允许的目标：模型自身的目录、`auto` 和 `timm_wrapper`。一个模型，一个定义：模型 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)。如果没有该装饰器，新的配置将缺失仓库的运行时类型验证契约，并偏离基于 dataclass 的配置标准。

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

在原生模型集成文件中使用或传递（例如作为关键字参数）的 `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 字段。若缺少该字段，用户将无法控制权重绑定：模型会无条件地执行绑定，从而破坏序列化往返以及使用未绑定头部的微调。

```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_* 属性（do_resize、do_rescale、do_normalize、do_convert_rgb、...）并覆盖了 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

对于同时带有 @auto_docstring 和 @dataclass 的类，@auto_docstring 会先被检查。装饰器自下而上应用，因此位于上方的 @dataclass 会先执行 @auto_docstring，此时类中尚未生成合成的 __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 等）。跳过它会导致重写中遗漏的所有子模块保持未初始化状态——这能通过测试，但稍后会以微妙的权重初始化 bug 的形式暴露出来（参见 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 中覆盖，且会使代码臃肿。而在 Hub 上的 `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, ...)`）的注意力类：该扩展必须位于一个专用方法（例如 `expand_kv`）中，并由 `forward()` 调用，而不是内联实现。在模块化文件中，从导入的基类继承的方法也算数。外部后端（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 中，标记 `torch.tensor(<value>, ..., device=<non-cpu>)`，其中 `<value>` 可证明解析为 Python 标量——来自数字字面量及其算术运算、torch.finfo/iinfo 字段、返回标量的内置函数和 math.* 调用、恰好绑定一次的局部变量、在类体中赋值的 self.，以及伴随配置文件中（遵循 attribute_map）标注为 int/float/bool 的 config 字段。任何可能也是序列（`eos_token_id: int | list[int] | None`）或无法解析的内容均保持不变。__init__、_init_weights、__post_init__ 和 post_init 被豁免：它们永远不会在捕获区域内运行。torch.tensor(, device=) 会在主机上实例化该值，然后将其复制到设备；CUDA 图捕获禁止这种复制，因此模型无法被捕获。torch.full((), , dtype=..., device=...) 使用可捕获的内核在设备上填充相同的 0 维张量，且无需同步。

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

检查 `_no_split_modules` 列表（位于 modeling_*.py 或 modular_*.py 中）里的每个字符串是否都指向在该文件中定义、导入到该文件中，或由同一模型目录下的同级模块定义的类。此检查是对 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 之前添加的模型保留其原有名称。所有读取模型形状的部分——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 的类（例如 layers、attention modules 和 encoders 等普通的 nn.Module 块）内部，调用了 mask 工厂（即 masking_utils 的入口点 create_causal_mask、create_bidirectional_mask、create_sliding_window_causal_mask、create_chunked_causal_mask、create_masks_for_generate，以及任何 create_*_mask 辅助函数）。掩码构建是 O(序列长度平方) 级别的工作，且不随层数变化，因此在层内构建它意味着每层都要支付一次该成本，并且每层都会拥有自己的掩码，导致 attention 后端无法再接收单个预先准备好的掩码。请在模型中构建一次，然后向下传递。

```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 的非 PreTrainedModel 类，这些类在 __init__ 中恰好分配一个 self. 属性，且其 forward 函数体恰好为 `return self.<attr>(...)`（开头的文档字符串会被忽略）。如果 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

标记 `assert` 语句在 modeling_*.py、modular_*.py 和 configuration_*.py 中的使用。`python -O` 会移除断言，因此以断言形式编写的形状或配置检查在优化运行中会静默消失。此外，断言只会抛出裸的 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 中，标记那些 `__init__` 方法，它们除了接收 `config` 外，还接收一个名称明确指向配置字段的参数（hidden_size、num_attention_heads、intermediate_size、head_dim、num_hidden_layers、embed_dim、dropout、eps、patch_size、rope_theta 等）。如果该参数是可选的且默认值为 `None`，则予以豁免：这属于覆盖行为，而非第二个事实来源，这也是一个 MLP 类同时服务于 MoE 模型中稠密层宽度和专家层宽度的方式。但硬编码的默认值（例如 `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` 为根的属性链深度达到三层或更深。`config.hidden_size`（一跳）和 `config.text_config.hidden_size`（两跳，即常规的子配置访问）是可以接受的。每行计一次违规。如果某个模块访问 `config.diffusion_config.atom_encoder_config.hidden_size`，则它与整个配置层级耦合，而非仅与其自身的切片耦合，因此无法被复用、测试或赋予不同的子配置。将相关的子配置向下传递，该链就会缩短为一跳。

```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*` 的层，其统计量会被重新计算两次；以及不是模型 token mixer 的堆栈，表现为将 attention、modulation、mixer 或 SSM 模块赋值为 `self.x = Y(...)`。`gradient_checkpointing_enable()` 仅当层是 GradientCheckpointingLayer 时才会包装该层。主干上的普通 nn.Module 会被静默跳过，因此训练看起来已启用 checkpoint，但实际上仍分配了完整的激活值，导致 OOM 出现在远离根本原因的地方。在其他地方——例如 conv 主干、decode 头——权衡由作者决定，因此该规则不适用。

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

### TRF035

标记 `# noqa` 注释，无论是否带有代码，均位于 modeling_*.py、modular_*.py 和 configuration_*.py 中。在 modular 文件中，`F401`、`F821` 和 `F822` 是被接受的：该文件是生成源，有意不定义其使用的每个名称，因此 ruff 的未定义名称类规则会在正确的代码上触发——例如转换器填充的 `__all__` 条目、位于父模型中的类，以及为重新导出而保留的导入。仅命名这些代码的 `# noqa` 会被跳过；命名其他任何代码的注释则会在剩余的代码上被报告。裸的 `# noqa` 始终会被报告；在 modular 文件中，消息会要求提供代码，而不是重写。模型文件是遵循仓库 lint 规则的普通代码，因此抑制意味着底层问题被保留了下来——而且裸的 `# 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 有时是表达张量收缩最清晰的方式，因此这是可选功能，而非硬性约定。einsum 方程使用一种需要读者自行解码的记法来编码形状，而动态构建的方程则掩盖了实际执行的是哪种收缩。请将其展开为显式的 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，这是一个辅助文件，通过其 tokenizer 进行覆盖；tokenization__fast.py 映射到其慢速对应版本的测试文件。一个 modular_*.py 可以同时定义多个家族，因此其类按名称后缀路由——XxxModel/XxxPreTrainedModel/XxxFor 用于 modeling，XxxImageProcessor(Fast) 用于 image processing，XxxProcessor 用于 processing，XxxVideoProcessor 用于 video processing，XxxFeatureExtractor 用于 feature extraction，XxxTokenizer(Fast) 用于 tokenization，XxxConfig 跳过——每缺少一个测试文件就报告一次违规。`# trf-ignore: TRF038` 不受支持；请使用 `allowlist_models`，以便在代码审查中可见豁免项。没有测试文件的源文件没有回归覆盖：损坏的 forward pass、错误的转换映射，或丢弃特殊 token 的 tokenizer 都可能被合并并长期保持损坏状态。一个带有随机权重的 dummy 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__ 内部）未被引用时，标记该导入。ruff 的未使用导入检查不会清理这些代码：由于导入是可达的，因此该代码块单独来看似乎没有问题。一旦重构不再需要 PIL.Image、torch 等，受保护的导入就会作为无用代码残留下来，并对文件的实际依赖关系产生误导。

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

### TRF040

在 modeling_*.py 和 modular_*.py 中，标记了同时使用 @capture_outputs 和 @can_return_tuple 装饰器的方法。这与 TRF003 形成互补，后者涵盖了 forward() 中手动进行 return_dict 分支处理的情况。由于这两个装饰器都会弹出 return_dict，因此只有最外层的装饰器能看到其真实值。@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 中，标记所有 `if`/`elif` 以及条件表达式，只要其条件读取了 `config.*` 或 `self.config.*` 属性，且未附带 `# CODEPATH:` 注释（该注释可位于分支行，或位于其正上方的连续注释块中）。任何配置属性均计入，不仅限于布尔标志。按结构豁免：`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` 保留其逐行含义——且仅当条件读取的所有字段均被豁免时，该条件才会被跳过。由配置控制的分支相当于同一文件中的第二种架构，而代码无法说明这两部分是否仍然可达——这正是死掉的实验分支得以在发布版本中存活的原因。该规则并不禁止分支：就像 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` 命名约定——因此仅包含辅助函数的文件会被跳过，而混入该测试套件的辅助类也不满足真实测试类的规则。继承关系会追踪同一文件中的基类，以及按名称导入的另一个模型的 tokenizer 测试；无法解析的基类不计入。报告指向第一个未运行该套件的测试类。`auto` 在允许列表中：test_tokenization_auto.py 测试的是 AutoTokenizer 的解析，而非某个 tokenizer。TokenizerTesterMixin 是实际检查 encode/decode 往返、填充与截断、特殊 token 处理、添加 token 的持久化以及保存/加载等价性的地方。一个仅断言几个手写 token id 列表的测试，即使 tokenizer 在其中每一项上都是损坏的，也会通过，并且在代码审查中看起来像是已测试。

```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 无填充训练消耗，并且必须通过 **kwargs 传递。在签名中命名该参数会在注意力接口读取之前将其吞掉；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 签名里的遗留参数 output_attentions、output_hidden_states 和 return_dict。在截止日期之前贡献的模型不受此限制。装饰器栈负责输出控制：@capture_outputs 根据配置解析 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 或静态形状的值应放在 __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 所需的状态。请返回该值，或通过方法链传递该值。

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

Flags list/tuple/set literals in class-level _tied_weights_keys declarations. v5 changed _tied_weights_keys to a dict mapping each tied target parameter to its source. The list form no longer says which parameter is the source, so tying, device_map computation and saving misbehave silently.

```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__ 方法中，标记 init 调用：包括 nn.init.* / init.* 原语，以及对自身参数的就地初始化器（self.weight.data.normal_()）。模型在 meta 设备上实例化，因此在加载之前，__init__ 中写入的张量值会被丢弃：如果某个参数仅在此处初始化，那么从头开始微调或在 meta 设备重新加载后，该参数将包含随机内容。请在 __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 中的 Hub 注意力内核永远无法被它们使用。通过接口进行分发的单一注意力类将取代该字典；请勿从旧版父类中继承此模式。

```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` 参数未加注解或指向其他配置的 `__init__`。由子配置构建的类（`AcmeTextModel(config.text_config)`）必须声明该子配置。`modular_*.py` 文件通过其生成的文件进行检查。`PreTrainedModel` 从 `config` 注解推导 `config_class`。赋值或手写的 `config_class` 会保留或偏离父类的值，而不匹配的 `__init__` 会用一种配置构建模型，却对外声明另一种配置。

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

`@auto_docstring` 会检查公开的 `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__`。`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__` 的副作用而存在，因此想要调整其中一个缓冲区的模块化文件必须重新定义整个 `__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

对于张量并行计划中分配了 `moe_tp_experts` 的模型目录，会检查路由的 `*Experts` 类是否将隐藏状态、top-k 索引和 top-k 路由权重作为 `forward` 的前三个位置参数。接受诸如 `selected_experts` 和 `routing_weights` 之类的别名。`MoeExpertsParallel` 会对第 3 个位置参数应用梯度变换。如果签名不同，则会静默地对错误的张量应用该变换，或者跳过该变换。

```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` 脚本会被跳过。包内的绝对导入会经过顶层的惰性加载 `transformers/__init__.py`，这可能导致循环导入，并且可能解析到另一个已安装的 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` 的子类以及向后兼容的别名不会被标记。转换器会内联从其他模型导入的基类，但会保留同一文件中的基类，因此生成的 modeling 文件会保留继承关系，其类无法再逐个读取。

```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` 内部调用的就地 `torch.nn.init` 初始化器（无论以何种方式导入的 `nn.init.normal_(...)`）都会被标记。仅用于计算值的辅助函数（例如 `calculate_gain`）不会被标记。Transformers 的 `init` 函数会跳过已从检查点加载的张量。`torch.nn.init` 依赖于在 `from_pretrained` 期间应用的补丁，而按名称导入的函数会绕过该补丁，因此已加载的权重可能会被静默地重新初始化。

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

跟踪模型文件在导入时执行的每个相对导入，并在被导入的文件需要导入文件未声明的后端时发出标记：通过其基础依赖项、其 `__all__` 对象中最弱的 `@requires`，或 `is_<backend>_available()` 守卫。通过 `modular_*.py` 文件生成的文件对其进行检查。延迟模块在其声明的后端安装后导入该文件。如果该文件导入了需要更多后端的同级文件，`from transformers import *` 将在该环境中崩溃：仅视觉的处理器导入 torchvision 图像处理器，会破坏安装了 Pillow 但未安装 torch 的环境。

```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 中，标记了 `ProcessingKwargs` 子类，该子类会分配或重新注释 `_defaults`、`text_kwargs`、`images_kwargs`、`videos_kwargs` 或 `audio_kwargs`。`ProcessingKwargs._defaults` 已弃用：默认值是处理器的类属性，与其他属性一样被继承和覆盖。模态字段保留其默认类型，因为可用的参数只有在运行时加载子处理器后才会确定。

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

In processing_*.py, flags any class extending `ImagesKwargs`, `TextKwargs`, `AudioKwargs` or `VideosKwargs`, directly or through another model's subclass. In modular_*.py, which also holds sub-processors, a subclass is allowed when named `<Model>ImageProcessorKwargs`, `<Model>VideoProcessorKwargs`, `<Model>VideoProcessorInitKwargs` or `<Model>AudioProcessorKwargs`. Modality kwargs belong in the sub-processor files (`image_processing_*.py`, `video_processing_*.py`, ...). In processing_*.py they stay untyped, since sub-processors are loaded dynamically.

```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` 也会被标记。该截止规则将旧模型豁免于除装饰器位置错误之外的所有检查。重复后端要求会掩盖方法实际新增的依赖关系。函数开头的无条件检查应放在 `@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 中，标记了那些开启所有隐藏状态（`output_hidden_states=True`，或在 `**kwargs` 中设置）的调用，而该函数随后仅通过索引读取 `.hidden_states[...]`。使用整个元组（进行迭代、切片、堆叠或返回）的代码以及带有 `@filter_output_hidden_states` 的骨干网络不受此限制。每一层的隐藏状态都会保持存活，直到调用返回，因此峰值内存会随深度增加而增长。`output_hidden_states` 还接受一个索引或索引列表，并仅捕获这些索引：使用 `@select_hidden_states` 装饰一个转发 `**kwargs` 的方法，或直接传入索引。

```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` 文件通过其在磁盘上生成的文件进行检查，因此在运行 lint 之前请重新生成。accelerate 会将这些名称与子模块的类名进行匹配。如果某个名称不是类，则永远不会匹配，因此该层可以被拆分到不同的设备上。这种情况通常源于继承 `_no_split_modules` 的 modular 文件：转换器会重命名前缀，而不是类名。

```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"]
```

