# 自动生成文档字符串

`@auto_docstring` 装饰器会为模型类和方法生成一致的文档字符串。它会自动引入标准的参数描述，因此您只需为新参数或自定义参数编写文档。在[添加新模型](./modular_transformers)时，可以跳过样板代码，专注于新增内容。

## @auto_docstring

在 `modular_model.py` 文件（对于较旧的模型，则为 `modeling_model.py`）中导入该装饰器。

```python
from ...utils import auto_docstring
```

如果你的模型在模块化文件中继承自另一个库的模型，`@auto_docstring` 已在父类中应用。`make fix-repo` 会将其复制到生成的 `modeling_model.py` 文件中。仅在需要自定义其行为时（例如独立模型、自定义介绍或覆盖参数），才显式应用该装饰器。

> [!WARNING]
> 在模块化文件中重写任何装饰器时，请包含父函数或类中的**所有**装饰器。如果只重写其中一部分，其余的装饰器将不会出现在生成的 modeling 文件中。

该装饰器接受以下可选参数：

| 参数 | 描述 |
|---|---|
| `custom_intro` | 类或方法的描述，插入在 Args 部分之前。对于不以 [可识别的后缀](#how-it-works)（如 `ForCausalLM` 或 `ForTokenClassification`）结尾的类，此项为必填。 |
| `custom_args` | 特定参数的文档字符串文本。当相同的自定义参数在建模文件的多个位置出现时，此功能非常有用。 |
| `checkpoint` | 用于生成使用示例的模型检查点标识符（`"org/my-model"`）。它会覆盖从配置类自动推断出的检查点。通常设置在配置类上。 |

## 用法

`@auto_docstring` 的工作方式取决于你所装饰的对象。模型类会从 `__init__` 中提取参数文档，配置类会从类级别的注解中提取，处理器类会根据其组件自动生成简介，而 `forward` 等方法则会获得返回类型和使用示例。

### 模型类

将 `@auto_docstring` 直接放在类定义上方。该装饰器会根据 `__init__` 方法的签名和文档字符串推导参数描述。

```python
from transformers.modeling_utils import PreTrainedModel
from ...utils import auto_docstring

@auto_docstring
class MyAwesomeModel(PreTrainedModel):
    def __init__(self, config, custom_parameter: int = 10, another_custom_arg: str = "default"):
        r"""
        custom_parameter (`int`, *optional*, defaults to 10):
            Description of the custom_parameter for MyAwesomeModel.
        another_custom_arg (`str`, *optional*, defaults to "default"):
            Documentation for another unique argument.
        """
        super().__init__(config)
        self.custom_parameter = custom_parameter
        self.another_custom_arg = another_custom_arg
        # ... rest of your init

    # ... other methods
```

`custom_intro` 和 `custom_args` 以获取更精细的控制。自定义参数可以放在 `custom_args` 中，也可以放在 `__init__` 的 docstring 中。当相同的参数在多个方法中重复出现时，请使用 `custom_args`。

```python
@auto_docstring(
    custom_intro="""This model performs specific synergistic operations.
    It builds upon the standard Transformer architecture with unique modifications.""",
    custom_args="""
    custom_parameter (`type`, *optional*, defaults to `default_value`):
        A concise description for custom_parameter if not defined or overriding the description in `auto_docstring.py`.
    internal_helper_arg (`type`, *optional*, defaults to `default_value`):
        A concise description for internal_helper_arg if not defined or overriding the description in `auto_docstring.py`.
    """
)
class MySpecialModel(PreTrainedModel):
    def __init__(self, config: ConfigType, custom_parameter: "type" = "default_value", internal_helper_arg=None):
        # ...
```

同样将 `@auto_docstring` 应用于继承自 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 的类。

```python
@auto_docstring(
    custom_intro="""
    Custom model outputs with additional fields.
    """
)
@dataclass
class MyModelOutput(ImageClassifierOutput):
    r"""
    loss (`torch.Tensor`, *optional*):
        The loss of the model.
    custom_field (`torch.Tensor` of shape `(batch_size, hidden_size)`, *optional*):
        A custom output field specific to this model.
    """

    # Standard fields (hidden_states, logits, attentions, etc.) are documented automatically when
    # the description matches the standard text. Loss typically varies per model, so document it above.
    loss: Optional[torch.Tensor] = None
    logits: Optional[torch.Tensor] = None
    hidden_states: Optional[tuple[torch.Tensor, ...]] = None
    attentions: Optional[tuple[torch.Tensor, ...]] = None
    # Custom fields need to be documented in the docstring above
    custom_field: Optional[torch.Tensor] = None
```

### 配置类

将 `@auto_docstring` 直接放在 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 子类的上方，与 `@strict` 装饰器并列。 `@strict` 会添加运行时类型验证，并将该类转换为经过验证的数据类。配置参数是 *类级别注解*（而非 `__init__` 参数），`@auto_docstring` 会从类主体中读取这些注解以生成文档。

`ConfigArgs` 提供了诸如 `vocab_size`、`hidden_size` 和 `num_hidden_layers` 等标准参数，因此除非其行为有所不同，否则无需对其进行描述。[PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的基类参数会被自动排除。`checkpoint` 参数用于生成使用示例。

```python
from huggingface_hub.dataclasses import strict
from ...configuration_utils import PreTrainedConfig
from ...utils import auto_docstring

@strict
@auto_docstring(checkpoint="org/my-model-checkpoint")
class MyModelConfig(PreTrainedConfig):
    r"""
    custom_param (`int`, *optional*, defaults to 64):
        Description of a parameter specific to this model.
    another_param (`str`, *optional*, defaults to `"gelu"`):
        Description of another model-specific parameter.

    ```python
    from transformers import MyModelConfig, MyModel

    configuration = MyModelConfig()
    model = MyModel(configuration)
    configuration = model.config
    ```
    """

    model_type = "my_model"

    # 标准参数（vocab_size、hidden_size 等）会从 ConfigArgs 中自动记录文档。 vocab_size: int = 32000 hidden_size: int = 768 num_hidden_layers: int = 12 # 模型特定参数必须在上方类文档字符串中记录文档。 custom_param: int = 64 another_param: str = "gelu"
```

### Processor classes

Multimodal processors ([ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin) subclasses, `processing_*.py`) always use the bare `@auto_docstring`. The class intro is auto-generated. Document only `__init__` parameters not already covered by `ProcessorArgs` (`image_processor`, `tokenizer`, `chat_template`, and others).

If every parameter is standard, omit the docstring. Decorate `__call__` with `@auto_docstring` too. Its body docstring holds only a `Returns:` section plus any extra model-specific call arguments. `return_tensors` is appended automatically.

```python
from ...processing_utils import ProcessorMixin, ProcessingKwargs, Unpack
from ...utils import auto_docstring

class MyModelProcessorKwargs(ProcessingKwargs, total=False):
    """
    custom_call_kwarg (`bool`, *optional*, defaults to `False`):
        A parameter with a default that can passed to __call__ which is not
        covered by the standard processor arguments (including each modality).
    """
    custom_call_kwarg: bool

@auto_docstring
class MyModelProcessor(ProcessorMixin):
    valid_processor_kwargs = MyModelProcessorKwargs
    custom_call_kwarg = False

    def __init__(self, image_processor=None, tokenizer=None, custom_param: int = 4, **kwargs):
        r"""
        custom_param (`int`, *optional*, defaults to 4):
            A parameter specific to this processor not covered by the standard ProcessorArgs.
        """
        super().__init__(image_processor, tokenizer)
        self.custom_param = custom_param

    @auto_docstring
    def __call__(self, images=None, text=None, **kwargs: Unpack[MyModelProcessorKwargs]):
        r"""
        Returns:
            [BatchFeature](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.BatchFeature): A [BatchFeature](/docs/transformers/v5.23.0/zh/main_classes/feature_extractor#transformers.BatchFeature) with the following fields:

            - **input_ids** -- Token ids to be fed to the model.
            - **pixel_values** -- Pixel values to be fed to the model.
        """
        # ...
```

#### 图像和视频处理器

图像和视频处理器（`BaseImageProcessor` 的子类，`image_processing_*.py`）遵循两种模式之一。

如果处理器具有模型特定的参数，请定义一个带有这些参数文档字符串的 `XxxImageProcessorKwargs(ImagesKwargs, total=False)` TypedDict，在类上设置 `valid_kwargs`，并使用裸的 `@auto_docstring`。`__init__` 没有文档字符串。

```python
class MyModelImageProcessorKwargs(ImagesKwargs, total=False):
    r"""
    custom_threshold (`float`, *optional*, defaults to `self.custom_threshold`):
        A parameter specific to this image processor.
    """
    custom_threshold: float | None

@auto_docstring
class MyModelImageProcessor(TorchvisionBackend):
    valid_kwargs = MyModelImageProcessorKwargs
    custom_threshold: float = 0.5

    def __init__(self, **kwargs: Unpack[MyModelImageProcessorKwargs]):
        super().__init__(**kwargs)
```

如果该类仅设置了标准的类级属性（`size`、`resample`、`image_mean` 等），且没有自定义 kwargs，请改用 `@auto_docstring(custom_intro="Constructs a MyModel image processor.")`。

```python
@auto_docstring(custom_intro="Constructs a MyModel image processor.")
class MyModelImageProcessor(TorchvisionBackend):
    resample = PILImageResampling.BICUBIC
    image_mean = IMAGENET_STANDARD_MEAN
    image_std = IMAGENET_STANDARD_STD
    size = {"height": 224, "width": 224}
```

重写 `preprocess` 时，请使用 `@auto_docstring` 对其进行装饰，并仅记录 `ImageProcessorArgs` 中未包含的参数。标准参数和 `return_tensors` 会自动包含在内。

### 函数

将 `@auto_docstring` 直接放在函数定义上方。该装饰器会根据函数签名推导参数描述。

该装饰器根据 `ModelOutput` 类的文档字符串生成返回值文本。

```python
class MyModel(PreTrainedModel):
    # ...
    @auto_docstring
    def forward(
        self,
        input_ids: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        new_custom_argument: Optional[torch.Tensor] = None,
        # ... other arguments
    ) -> Union[Tuple, ModelOutput]:
        r"""
        new_custom_argument (`torch.Tensor`, *optional*):
            Description of this new custom argument and its expected shape or type.
        """
        # ...
```

传入 `custom_intro` 和 `custom_args` 以获得更多控制。当相同参数出现在多个方法中时，使用 `custom_args` 一次性定义共享的参数文档。

```python
MODEL_COMMON_CUSTOM_ARGS = r"""
    common_arg_1 (`torch.Tensor`, *optional*, defaults to `default_value`):
        Description of common_arg_1
    common_arg_2 (`torch.Tensor`, *optional*, defaults to `default_value`):
        Description of common_arg_2
"""

class MyModel(PreTrainedModel):
    # ...
    @auto_docstring(
        custom_intro="""This is a custom introduction for the function.""",
        custom_args=MODEL_COMMON_CUSTOM_ARGS
    )
    def forward(self, input_ids=None, common_arg_1=None, common_arg_2=None) -> ModelOutput:
        r"""method-specific args go here"""
        # ...
```

在 docstring 中手动编写 `Returns` 和 `Examples` 部分，以覆盖自动生成的版本。

```python
    def forward(self, input_ids=None) -> torch.Tensor:
        r"""
        Returns:
            `torch.Tensor`: A custom Returns section for non-ModelOutput return types.

        Example:

        ```python
        model = MyModel.from_pretrained("org/my-model")
        output = model(input_ids)
        ```
        """
        # ...
```

### Documenting arguments

Follow these rules when documenting different argument types.

- `auto_docstring.py` defines standard arguments (`input_ids`, `attention_mask`, `pixel_values`, etc.) and includes them automatically. Don't redefine them locally unless the argument behaves differently in your model.

    If a standard argument behaves differently in your model, override it locally in a `r""" """` block. The local definition takes priority. The `labels` argument, for instance, is commonly customized per model and often needs an override.

- Standard config arguments (`vocab_size`, `hidden_size`, `num_hidden_layers`, etc.) follow the same principle but come from `ConfigArgs`. Standard processor arguments (`image_processor`, `tokenizer`, `do_resize`, `return_tensors`, etc.) come from `ProcessorArgs` and `ImageProcessorArgs`. Only document a parameter if it is model-specific or behaves differently from the standard description.

- Document new or custom arguments in an `r""" """` block. Place them after the signature for functions, in the `__init__` docstring for model or processor classes, in the class body docstring for config classes, or in the `XxxImageProcessorKwargs` TypedDict body for image processors.

    ```py
    argument_name (`type`, *optional*, defaults to `X`):
        Description of the argument.
        Explain its purpose, expected shape/type if complex, and default behavior.
        This can span multiple lines.
    ```

  * 将 `type` 放在反引号中。
  * 如果参数不是必需的或具有默认值，请添加 *optional*。
  * 如果存在默认值，请添加“默认为 X”。如果默认值为 `None`，则无需添加“默认为 `None`”。
  * 当相同的参数在多个方法中重复出现时，请将相同的代码块传入 `custom_args`（参见上方的 [函数示例](#functions)）。

- 该装饰器会自动从函数签名中提取类型。如果参数带有类型注解，则无需在文档字符串的格式字符串中重复该类型。当两者同时存在时，签名中的类型优先。文档字符串中的类型作为未注解参数的后备方案。

## 检查文档字符串

当你打开一个拉取请求时，一个实用脚本会验证文档字符串。CI 会运行该脚本并检查以下内容。

> [!TIP]
> 如果在输出中看到 `[ERROR]`，请将相应参数的描述添加到 `auto_docstring.py` 中的 docstring 或对应的 Args 类中。

* 检查 `@auto_docstring` 是否已应用于相关的模型类和公共方法。
* 验证参数的完整性和一致性：文档中记录的参数必须存在于函数签名中，且类型和默认值必须匹配。未提供本地描述的未知参数将被标记。
* 标记不完整的占位符，例如 `<fill_type>` 和 `<fill_docstring>`。
* 验证文档字符串是否符合预期的格式风格。

在提交之前，在本地运行检查。

```bash
make fix-repo
```

`make fix-repo` 还会运行其他几项检查。如果只想运行 docstring 和 auto-docstring 检查，请使用以下命令。

```bash
# to only check files included in the diff without fixing them
python utils/check_docstrings.py
# to fix and overwrite the files in the diff
# python utils/check_docstrings.py --fix_and_overwrite
# to fix and overwrite all files
# python utils/check_docstrings.py --fix_and_overwrite --check_all
```

## 快速参考清单

| 执行 | 不要 |
|---|---|
| 将 `@auto_docstring` 应用于模型、配置和处理器类及其主要方法（`forward`、`__call__`、`preprocess`）。 | 在模块化文件中，为继承的模型添加 `@auto_docstring`，因为它会自动继承。 |
| 仅记录新增的或特定于模型的参数。 | 重新定义标准参数（`input_ids`、`attention_mask`、`vocab_size` 等），使其行为与默认描述保持一致。 |
| 将配置参数作为类级别注释，放在类主体的文档字符串中。 | 将配置参数放在 `__init__` 中。 |
| 将图像处理器参数放入 `XxxImageProcessorKwargs` TypedDict 中。 | 将图像处理器参数放入 `__init__` 中。 |
| 在提交之前，请运行 `python utils/check_docstrings.py --fix_and_overwrite`。 | 忽略 `[ERROR]` 输出，因为它表示某个参数没有文档说明。 |

## 工作原理

`@auto_docstring` 装饰器通过以下步骤生成文档字符串。

1. 该装饰器会检查签名，以从被装饰类的 `__init__` 或被装饰的函数中读取参数、类型和默认值。对于配置类，它会沿继承链向上遍历类级别的注解，并在到达 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 之前停止，从而排除基类字段。

    它会自动过滤掉诸如 `self`、`kwargs`、`args`、`deprecated_arguments` 以及以 `_` 为前缀的名称。部分私有参数会被重命名为其对应的公开参数（例如，对于 backbone 模型，`_out_features` → `out_features`）。

2. 常见的参数描述来自 `auto_docstring.py`：`ModelArgs`（模型输入）、`ModelOutputArgs`（输出字段，例如 `hidden_states`）、`ImageProcessorArgs`（图像预处理）、`ProcessorArgs`（多模态处理器组件）以及 `ConfigArgs`（配置超参数）。

3. 每个参数的描述遵循以下优先级链：

    - 手动编写的文档字符串（`r""" """` 块或 `custom_args`）具有更高的优先级。
    - 预定义的源字典（`ModelArgs`、`ModelForArgs`、`ConfigArgs`、`ImageProcessorArgs`、`ProcessorArgs`、`ModelOutputArgs`）是回退方案。
    - 如果两个来源都没有描述，该参数将在构建输出中被标记为 `[ERROR]`。

4. 对于具有标准名称（如 `ModelForCausalLM`）的模型类，或映射到某个 pipeline 的类，`@auto_docstring` 会生成简介。对于多模态处理器，简介会列出该类封装了哪些组件（例如 tokenizer、image processor 等）。完整的列表请参阅 [ClassDocstring](https://github.com/huggingface/transformers/blob/main/src/transformers/utils/auto_docstring.py#L2437)。

    如果类名不在 `ClassDocstring` 中，请设置 `custom_intro`。

5. 预定义的文档字符串可以引用 Transformers 的 [auto_modules](https://github.com/huggingface/transformers/tree/main/src/transformers/models/auto) 中的动态值，例如 `{processor_class}`、`{image_processor_class}` 和 `{config_class}`。这些占位符会自动解析。

6. 该装饰器会根据模型的任务或流水线兼容性来选择使用示例。它会从配置类中读取检查点元数据，以便示例使用真实的模型 ID。`checkpoint` 参数会覆盖从配置类文档字符串中推断出的检查点。请在配置类上设置 `checkpoint`，或者在检查点推断失败时设置。如果看到类似 `"Config not found for <model_name>"` 的错误，请在 `auto_docstring.py` 中的 `HARDCODED_CONFIG_FOR_MODELS` 添加一个条目。

7. 对于 `forward` 之类的方法，装饰器会根据方法的返回类型编写 `Returns` 部分。当返回类型是 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 的子类时，`@auto_docstring` 会从该类的文档字符串中提取字段描述。函数文档字符串中自定义的 `Returns` 块具有优先权。

8. 对于 `UNROLL_KWARGS_METHODS` 中的方法和 `UNROLL_KWARGS_CLASSES` 中的类，该装饰器会展开使用 `Unpack[KwargsTypedDict]` 进行类型标注的 `**kwargs`。`TypedDict` 中的每个键都会成为一个有文档记录的参数。

    同样的展开规则也适用于 [BaseImageProcessor](/docs/transformers/v5.23.0/zh/main_classes/image_processor#transformers.BaseImageProcessor) 和 [ProcessorMixin](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessorMixin) 子类的 `__call__` 和 `preprocess` 方法。通用基类类型（`TextKwargs`、`ImagesKwargs`、`VideosKwargs`、`AudioKwargs`）会被跳过。只有模型特定的子类会被展开。

