Transformers documentation

模型结构规则

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

模型结构规则

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

请参阅 mlinter 文档,了解完整的检查器参考和使用详情。

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

运行检查器

make typing 通过仓库包装器同时运行 mlinter 和 ty 类型检查器,因此会加载 utils/rules.toml。可以直接使用以下命令运行相同的包装器。

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 在 规则参考 中查找对应的修复方法。当 PreTrainedModel 的子类未调用 self.post_init() 时,会触发 TRF013。该方法会执行必要的最终化步骤,省略它会导致运行时错误。

 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 可能会破坏权重加载的键映射以及基础模型的访问。

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 来处理。

-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 类属性中声明绑定的权重。

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

TRF005

检查 _no_split_modules 存在时的形状。格式错误的值可能会破坏设备映射分区和分片。

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

TRF006

检查 forward 签名中的缓存参数是否在函数体内被使用。未使用的缓存参数表明缓存支持不完整,且 API 行为不一致。

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

TRF007

检查 init 中在 self.post_init() 之后对 self 属性的赋值。在 post_init 之后修改模型结构会绕过其初始化和收尾工作。

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

TRF008

检查模型类上的 add_start_docstrings 是否接收了非空参数。空参数会导致生成的 API 文档内容模糊、质量低下。

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

TRF009

Flags imports into another model’s package from a model’s shipped implementation files: modeling*, configuration, processing_, imageprocessing, videoprocessing, featureextraction, tokenization_ and generation*.py. Three forms count: package path (from transformers.models.other.modeling_other import X), relative path (from ..other.configuration_other import X) and public API (from transformers import OtherModel) — for the last the owning directory is inferred from the class name and confirmed against the classes it defines, so an unresolvable name is left alone. Out of scope: `modular.py(building on another model is its purpose, and the converter flattens those imports away),convert_.py,init.pyand files underauto. Allowed targets: the model's own directory,autoandtimm_wrapper`. One model, one definition: model A’s behavior lives in its own files, and a change to model B must not silently change model A — for every file kind, not just modeling. Reach sub-configs through AutoConfig and CONFIG_MAPPING, and use a modular file to build on another model’s code.

-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

检查 *.py 和 modular*.py 中直接继承自 PreTrainedConfig/PretrainedConfig 的子类是否带有 @strict(accept_kwargs=True)。如果缺少该装饰器,新的配置将不符合仓库的运行时类型验证约定,并偏离基于 dataclass 的配置标准。

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

TRF011

在 PreTrainedModel 子类的 forward() 中,对循环变量(遍历 self.layers)以及 self.<submodule>.<attr>(其中 <attr> 不是标准的 nn.Module 属性)进行标志子模块属性访问时,torch.nn.Identity 不会具备这些属性。流水线并行可能会将任意子模块替换为 torch.nn.Identity,因此从中读取自定义属性(例如 decoder_layer.attention_type)会在运行时引发 AttributeError。请从 self.config 中读取每层的元数据。

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.

+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 负责关键的最终初始化工作(权重初始化、梯度检查点设置等);跳过它会导致难以察觉的运行时错误。

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 中接受审查或维护。

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 字段。若缺少该字段,用户将无法控制权重绑定:模型会无条件地执行绑定,从而破坏序列化往返以及使用未绑定头部的微调。

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

TRF016

当图像processing.py 或视频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 不会生效,操作仍会执行,且按调用进行的覆写会静默失效。

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,而不是子类的。

-@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)。

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 中,这些配置会随检查点一起分发,并且无需修改代码即可更新。

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 旨在实现的内存节省。

+    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

在建模*.py 和 modular.py 中,标记 torch.tensor(<value>, ..., device=<non-cpu>),其中 <value> 可证明解析为 Python 标量——来自数字字面量及其算术运算、torch.finfo/iinfo 字段、返回标量的内置函数和 math. 调用、恰好绑定一次的局部变量、在类体中赋值的 self.<attr>,以及伴随配置文件中(遵循 attribute_map)标注为 int/float/bool 的配置字段。任何可能也是序列(eos_token_id: int | list[int] | None)或无法解析的内容均保持不变。init、_init_weights、post_init 和 post_init 被豁免:它们永远不会在捕获区域内运行。torch.tensor(<python scalar>, device=<accelerator>) 会在主机上实例化该值,然后将其复制到设备;CUDA 图捕获禁止这种复制,因此模型无法被捕获。torch.full((), <value>, dtype=…, device=…) 使用可捕获的内核在设备上填充相同的 0 维张量,且无需同步。

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。

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

TRF023

In configuration*.py and modular.py, flags `Configfields named after an upstream paper's abbreviation instead of the canonical name: 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. Fields are read from the class body and from __init__/__post_init__ assignments and defaults. Ambiguous but idiomatic names (num_heads, num_layers, embed_dim, mlp_ratio) are not flagged, and models added before cutoff_date keep theirs. Everything that reads a model's shape -- device_map planning, tensor/pipeline parallel plans, quantization, PEFT, attention-backend selection,attribute_mapconsumers -- looks up the canonical names, so a config spelling the same quantityd_model` silently opts out of all of them. Map the checkpoint’s own spelling in the conversion script.

@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、Convd、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 之前添加的模型不受此限制。硬编码的宽度会将模块固定到某一个 checkpoint 尺寸:同一架构在其他规模下加载时会出现形状不匹配,而 from_pretrained 无法指出哪个值有误,因为没有任何 config 字段指向它。这还会分裂真实来源,导致修改 config 后构建出的模型不再随之改变。

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 工厂(即 maskingutils 入口点 create_causal_mask、create_bidirectional_mask、create_sliding_window_causal_mask、create_chunked_causal_mask、create_masks_for_generate,以及任何 create_mask 辅助函数)时,会触发此警告。掩码构建是 O(序列长度平方) 级别的工作,且不随层数变化,因此在每一层中构建掩码意味着每层都要支付一次该成本,并且每层都会拥有自己的掩码,导致 attention 后端无法再接收一个统一准备好的掩码。应在模型中构建一次,然后向下传递。

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.<attr>,且 forward 的主体恰好是 return self.<attr>(...)(开头的 docstring 会被忽略)。如果 forward 中存在任何其他方法、额外属性、return 之前的语句或 super() 调用,则意味着该类执行了自身的工作。该包装器会为每个权重名称、_no_split_modules、并行化方案以及每个转换映射增加一层,同时不执行任何计算——而读者必须打开另一个类才能发现这一点。PreTrainedModel 的子类除外:即使 forward 仅进行委托,它们也存在于 from_pretrained 和 auto 类中。

-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 可以指明出错的值并说明应如何处理。

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 和 videoprocessing.py 的前 25 行,查找 Licensed under the <name> License 这一行,以及紧随其后的标准保修段落中的每一条条款,范围从 You may obtain a copy of the License at 到 limitations under the License.。首先会对各行进行展平并转换为小写,因此换行和注释风格不影响结果。许可证名称和版权行不在检查范围内,因为它们因模型而异。如果文件发布时缺少该头部,其来源将变得不明确,而事后补加则意味着需要修改一个已经发布的文件。仅匹配 Apache License 会放过实际发生的缺陷:段落中途被截断、头部在 URL 之后停止,或因错误的查找替换而损坏。

+# 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 不再会改变最终构建的模型。此外,这还将架构知识外溢到了每一个调用点,而这些本不属于调用点的职责。

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,说明它与整个配置层级耦合,而非仅与其自身的配置切片耦合,因此无法被复用、测试或替换为不同的子配置。应将相关的子配置向下传递,这样属性链就会缩短为一跳。

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 可以免费获得以上全部三项特性。

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

TRF032

在 modeling*.py 和 modular*.py 中,以绝对值大于等于 1e3 的取反数值字面量调用 maskedfill、masked_fill、full、full_like 和 new_full。硬编码的 -1e9 在 float16 中会溢出为 -inf,且远非 float32 中的最小值,因此同一掩码在不同 dtype 下表现不同,并在 softmax 之后可能产生 NaN。torch.finfo(dtype).min 是实际运行 dtype 所能表示的最小值。

-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_ 开头的方法被标记为 flags,但 PreTrainedModel 契约方法 set_input_embeddings、set_output_embeddings、set_decoder、set_encoder、set_attn_implementation 和 set_default_language 除外。setter 会使行为依赖于调用顺序:该值不在 config 中,因此不会被保存,不会被 from_pretrained 恢复,也不会被 device-map 或并行规划所感知。用户必须知道需要调用它,而遗漏调用时不会有任何提示。

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

In modeling*.py and modular.py, flags a locally-defined `Layer/Blockclass instantiated in annn.ModuleList(…)that does not reachGradientCheckpointingLayerthrough its base chain; modular files follow relative imports into sibling models, and unresolved chains are inconclusive. Out of scope: a model that never setssupports_gradient_checkpointing = True, which raises fromgradient_checkpointing_enable()instead of skipping a layer; a layer holdingnn.BatchNorm/nn.InstanceNorm*, whose statistics would be recomputed twice; and a stack that is not the model's token mixer, shown by an attention, modulation, mixer or SSM module assigned asself.x = Y(…).gradient_checkpointing_enable()` wraps a layer only if it is a GradientCheckpointingLayer. A plain nn.Module on the trunk is skipped silently, so training looks checkpointed while still allocating full activations, and the OOM surfaces far from the cause. Elsewhere — a conv backbone, a decode head — the trade is the author’s call, so the rule stays out.

-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 还会隐藏该行上未来可能出现的所有违规。请修复代码本身。

-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 转换和残差在其发生处不可见。

-        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 操作。

-        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、imageprocessing.py、videoprocessing.py、featureextraction.py 和 tokenization*.py 文件是否都有对应的 tests/models/<model>/test.py(modelingacme.py -> tests/models/acme/test_modeling_acme.py)。豁免项:configuration.py,由配套的 testmodeling.py 中的 ConfigTester 覆盖;以及 tokenization_utils.py,这是一个通过其 tokenizer 覆盖的辅助文件;tokenization<name>_fast.py 映射到其慢速对应文件的测试文件。一个模块化*.py 可以一次定义多个系列,因此其类按名称后缀路由——XxxModel/XxxPreTrainedModel/XxxFor<Task> 对应 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,或一个小型手写词汇表,就足以测试其中任何一项。

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 等,受保护的导入就会作为无用的冗余代码残留下来,并对文件的实际依赖关系产生误导。

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 变得多余。

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

TRF041

In modeling*.py and modular.py, flags every if/elif and conditional expression whose condition reads a `config.orself.config.attribute without a# CODEPATH:comment, accepted on the branch line or in the contiguous comment block directly above it. Any config attribute counts, not just boolean flags. Exempt by structure:X if X is not None else fallback, where the tested field is itself one of the results --getattr(config, x, default)spelled long, which cannot fork the graph; and a guard, anifwith noelsewhose body only raises or only warns/logs, since one side aborts and nothing diverges past it. Merely mentioning None does not qualify:config.visionconfig is not Nonestill owes a note. Exempt by field: framework plumbing that gates no checkpoint divergence --problem_typeselecting a loss,hidden_actlooking up an activation,num_labels,use_cache,is_decoder, the special token ids, thesummaryhead settings; the full list isDEFAULT_EXEMPT_ATTRIBUTESinmlinter/trf041.py, extended per project byignored_attributes = […]on the rule table. A model exempts one of its own fields file-wide with a module-level# trf-ignore: TRF041 config.scale_embedding, config.auxiliary_lossat column 0 (self.config.x,config.xandxare the same field). It must name at least one field -- a bare# trf-ignore: TRF041keeps its per-line meaning -- and a condition is skipped only when every field it reads is exempt. A config-gated branch is a second architecture in the same file, and the code cannot say whether both halves are still reachable -- which is how dead experimental branches survive for releases. The rule does not forbid the branch: like Rust's// SAFETY:`, it asks for the checkpoints taking each side to be written down next to it. A branch nobody can name one for is a branch to delete.

+        # 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//testtokenization.py 中,检查该文件是否定义了一个继承自 TokenizerTesterMixin 的被收集测试类。只有 runner 收集的类才计入——即 TestCase 基类,或者当基类是另一个模型的测试类时采用 *Test 命名约定——因此仅包含辅助函数的文件会被跳过,而混入该测试套件的辅助类也不满足真实测试类的规则。继承关系会沿着同一文件中的基类以及按名称导入的另一个模型的 tokenizer 测试进行追踪;无法解析的基类不计入。报告指向第一个未运行该套件的测试类。auto 在允许列表中:test_tokenization_auto.py 测试的是 AutoTokenizer 的解析,而非某个 tokenizer。TokenizerTesterMixin 是实际检查 encode/decode 往返、填充与截断、特殊 token 处理、添加 token 的持久化以及保存/加载等价性的地方。一个仅断言几个手写 token id 列表的测试,即使 tokenizer 在其中每一项上都是损坏的,也会通过,并且在代码审查中看起来像是已经测试过。

-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 传递。如果在签名中显式命名该参数,它会在注意力接口读取之前就被吞掉;llama 标准做法是传递 position_embeddings 以及kwargs。

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),无需传递 position。

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

Flags the legacy outputattentions, output_hidden_states and return_dict parameters in forward signatures in modeling.py and modular_.py. Models contributed before the cutoff date are exempt. The decorator stack owns output control: @captureoutputs resolves the output* flags against the config and records tensors via _can_record_outputs, and @can_return_tuple handles return_dict. Declaring them in the signature reintroduces manual flag threading that drifts from the decorators.

+@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 中。

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

Flags assignments to self attributes in preprocess, preprocess, call and post_process* methods in image_processing.py and videoprocessing.py. A processor carrying state between calls breaks preprocess-many-then-postprocess batching: the second preprocess overwrites the state the first postprocess needs. Return the value or pass it through the method chain.

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.

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

TRF049

Flags init calls in init methods in modeling*.py and modular.py: nn.init. / init.* primitives and in-place initializers on own parameters (self.weight.data.normal_()). Models instantiate on the meta device, so tensor values written in init are discarded before loading: a parameter initialized only there holds random content when fine-tuning from scratch or after a meta-device reload. Allocate with torch.empty in init, initialize in _init_weights.

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 的约定。

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

将针对 attn_implementation 属性在 modeling.py 和 modular_.py 中的比较。后端分发应归属于 ALL_ATTENTION_FUNCTIONS.get_interface,而依赖后端的张量处理(填充、重塑)应放在 integrations/ 下的共享包装器中。内联分支会使模型主体感知内核,并在注册新后端时失效。

-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

标记以 ATTENTION_CLASSES 结尾的模块级赋值,位于 modeling.py 和 modular_.py 中。从字典中选取的按后端划分的注意力类是接口引入前的惯用写法:这些几乎相同的类会逐渐产生差异,且注册到 ALL_ATTENTION_FUNCTIONS 中的 hub 注意力内核永远无法到达它们。通过接口进行分发的单一注意力类将取代该字典;请勿从旧版父类中传播它。

-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:])来构建 shiftlogits/shift_labels(以及 shifted 变体)的赋值操作会被标记。接收已经移位过的标签(shift_labels = kwargs.pop(“shift_labels”, labels))是正确的惯用写法,不会被标记。由于 self.loss_function 会自行对标签进行移位,因此在 modeling 代码中预先移位会导致在双重移位的目标上进行训练,或者强制使用自定义的损失路径。仅解码器模型应传入原始标签,让损失函数自行移位。编码器-解码器模型是相反的情况:它们的标签已经通过前置的解码器起始 token 进行了移位,因此应传入 shift_labels=labels 以防止损失函数再次移位。

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__ 会用一种配置构建模型,却对外声明另一种配置。

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 无法对其进行追踪,因此会导致图断裂。

-        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 会与其生成的文件进行比对检查。如果没有它,该类及其方法将缺少参数、返回值和示例文档,这些文档随后需要为每个模型手动编写。

+@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 中,标记那些 buffer 名称为字符串字面量的 register_buffer("<name>", ...) 调用,无论接收者是谁(self,或其他模块,例如 layer.mamba)。对于计算得出的名称——即变量或 f-string,例如在循环中为每一层创建一个 buffer——没有等价的属性赋值形式,因此予以豁免。由于 torch>=2.5 中 nn.Buffer 通过普通的属性赋值来注册 buffer,类似于 nn.Parameter。通过方法调用创建的 buffer 仅作为运行 __init__ 的副作用而存在,因此希望调整某个 buffer 的 modular 文件必须重新定义整个 __init__。如果将其作为属性赋值,则可以单独继承和覆盖。

-        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 个位置参数应用梯度变换。如果签名不同,则会静默地对错误的张量应用该变换,或者跳过该变换。

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 副本。

-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 文件会保留继承关系,其类无法再逐个读取。

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 期间应用的补丁,而按名称导入的函数会绕过该补丁,因此已加载的权重可能会被静默地重新初始化。

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 的环境。

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

TRF064

在处理*.py 和 modular*.py 中,标记了分配或重新注释 _defaults、text_kwargs、images_kwargs、videos_kwargs 或 audio_kwargs 的 ProcessingKwargs 子类。ProcessingKwargs._defaults 已弃用:默认值是处理器的类属性,与其他属性一样被继承和覆盖。模态字段保留其默认类型,因为只有在运行时加载子处理器后,才能确定可用的参数。

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

在处理*.py 中,标记任何直接或间接(通过另一个模型的子类)继承自 ImagesKwargs、TextKwargs、AudioKwargs 或 VideosKwargs 的类。在同样包含子处理器的 modular.py 中,当子类命名为 <Model>ImageProcessorKwargs、<Model>VideoProcessorKwargs、<Model>VideoProcessorInitKwargs 或 <Model>AudioProcessorKwargs 时,是允许存在子类的。模态 kwargs 应位于子处理器文件中(`imageprocessing.py,videoprocessing.py`,……)。在 processing_.py 中,它们保持无类型状态,因为子处理器是动态加载的。

-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:它必须位于这些装饰器下方。

# 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[...] 时,会标记出那些开启所有隐藏状态的调用(即 output_hidden_states=True,或在 **kwargs 中设置该值)。使用整个元组的代码(例如进行迭代、切片、堆叠或返回该元组)以及带有 @filter_output_hidden_states 的骨干网络不受此限制。由于每一层的隐藏状态在调用返回之前都会保持存活,因此峰值内存会随深度增加而增长。output_hidden_states 还接受一个索引或索引列表,并仅捕获这些索引对应的状态:可以使用 @select_hidden_states 装饰一个转发 **kwargs 的方法,或者直接传入索引。

+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 文件:转换器会重命名前缀,而不是类名。

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

抑制违规

如果需要抑制规则违规,请使用以下两种选项之一。

内联抑制

在违规行上添加 # trf-ignore: RULE_ID 注释。请包含说明,以便审阅者理解为何该抑制是合理的。

# 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 中相应规则的 allowlist_models 列表中。

[rules.TRF004]
allowlist_models = ["existing_model", "your_model_name"]
Update on GitHub