Transformers 文档

使用 @auto_docstring 装饰器

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

使用 @auto_docstring 装饰器

Hugging Face Transformers 库中的 @auto_docstring 装饰器有助于为模型类及其方法生成文档字符串,这些文档字符串将用于构建库的文档。它旨在通过自动包含标准参数描述并允许有针对性的覆盖和添加来提高一致性并减少样板代码。


📜 工作原理

@auto_docstring 装饰器通过以下方式构建文档字符串:

  1. 签名检查: 它检查被装饰类的方法或被装饰函数的签名(参数、类型、默认值)。
  2. 集中式文档字符串获取: 它从内部库源(例如 utils/args_doc.py 中的 ModelArgsImageProcessorArgs)检索常用参数(例如 input_idsattention_mask)的预定义文档字符串。
  3. 覆盖或添加参数描述
    • 直接文档字符串块: 它合并方法签名下方或 __init__ 文档字符串内的 r""" """ (或 """ """) 块中的自定义文档字符串内容。这用于文档化新参数或覆盖标准描述。
    • 装饰器参数 (custom_args): 可以将 custom_args 文档字符串块传递给装饰器,以便直接在装饰器调用中为特定参数提供文档字符串。如果新参数在建模文件中的多个位置重复,可以使用此方法一次性定义其文档字符串块。
  4. 添加类和函数介绍
    • custom_intro 参数: 允许在类或函数文档字符串之前添加自定义的介绍性段落。
    • 自动生成介绍: 对于具有标准命名模式(如 ModelForCausalLM)或属于管道的模型类,装饰器会使用 utils/args_doc.py 中的 ClassDocstring 作为源自动生成适当的介绍性段落。
  5. 模板化: 装饰器使用模板系统,允许预定义的文档字符串包含从库的 auto_modules 中推断出的动态信息,例如 {{processor_class}}{{config_class}}
  6. 推断相关示例: 装饰器尝试根据模型的任务或管道兼容性查找适当的使用示例。它从模型的配置类中提取检查点信息,以提供具有真实模型标识符的具体示例。
  7. 添加返回值文档: 对于 forward 等方法,装饰器可以根据方法的返回类型注解自动生成“Returns”部分。例如,对于返回 ModelOutput 子类的方法,它将从该类的文档字符串中提取字段描述,以创建全面的返回值描述。也可以在函数文档字符串块中手动指定自定义的 Returns 部分。
  8. 解包带 Unpack 运算符的 Kwargs: 对于特定方法 (在 UNROLL_KWARGS_METHODS 中定义) 或类 (在 UNROLL_KWARGS_CLASSES 中定义),装饰器处理使用 Unpack[KwargsTypedDict] 类型注解的 **kwargs 参数。它从 TypedDict 中提取文档并将其每个参数添加到函数的文档字符串中。目前,此功能仅支持 FastImageProcessorKwargs

🚀 如何使用 @auto_docstring

1. 导入装饰器

将装饰器导入到您的模型文件中

from ...utils import auto_docstring

2. 应用于类

@auto_docstring 直接放在类定义上方。它使用 __init__ 方法的签名及其文档字符串来描述参数。

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

高级类装饰:

参数可以直接传递给 @auto_docstring 以获得更多控制权。

@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 `args_doc.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 `args_doc.py`.
    """
)
class MySpecialModel(PreTrainedModel):
    def __init__(self, config: ConfigType, custom_parameter: "type" = "default_value", internal_helper_arg=None):
        # ...

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

3. 应用于函数(例如,forward 方法)

将装饰器应用于方法定义上方,例如 forward 方法。

    @auto_docstring
    def forward(
        self,
        input_ids: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        new_custom_argument: Optional[torch.Tensor] = None,
        arg_documented_in_args_doc: Optional[torch.Tensor] = None,
        # ... other arguments
    ) -> Union[Tuple, ModelOutput]: # The description of the return value will automatically be generated from the ModelOutput class docstring.
        r"""
        new_custom_argument (`torch.Tensor`, *optional*):
            Description of this new custom argument and its expected shape or type.
        """
        # ...

高级函数装饰:

参数可以直接传递给 @auto_docstring 以获得更多控制权。ReturnsExamples 部分也可以手动指定。

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: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        common_arg_1: Optional[torch.Tensor] = None,
        common_arg_2: Optional[torch.Tensor] = None,
        #...
        function_specific_argument: Optional[torch.Tensor] = None,
        # ... other arguments
    ) -> torch.Tensor:
        r"""
        function_specific_argument (`torch.Tensor`, *optional*):
            Description of an argument specific to this function

        Returns:
            `torch.Tensor`: For a function returning a generic type, a custom "Returns" section can be specified.

        Example:

        (To override the default example with a custom one or to add an example for a model class that does not have a pipeline)

        ```python
        ...
        ```
        """
        # ...

✍️ 参数文档:方法与优先级

  1. 标准参数(例如,input_ids, attention_mask, pixel_values, encoder_hidden_states 等)

    • @auto_docstring 从中央源检索描述。如果它们的描述和形状与 args_doc.py 中相同,请不要在本地重新定义这些参数。
  2. 新参数或自定义参数

    • 主要方法: 在签名后面的 r""" """ 文档字符串块中(对于函数)或在 __init__ 方法的文档字符串中(对于类参数)文档化这些参数。
    • 格式
      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”。
    • 如果它有默认值,则添加“defaults to X”(如果默认值为 None,则无需指定“defaults to None”)。
  3. 覆盖标准参数

    • 如果标准参数的行为不同(例如,不同的预期形状、特定于模型的行为),请在其本地 r""" """ 文档字符串中提供其完整描述。此本地定义优先。
    • labels 参数通常针对每个模型进行自定义,并且通常需要特定的文档字符串。
  4. 使用装饰器参数覆盖或添加新参数 (custom_args)

    • 新参数或自定义参数的文档字符串也可以作为 custom_args 参数传递给 @auto_docstring。如果新参数在建模文件中的多个位置重复,可以使用此方法一次性定义其文档字符串块。

模块化文件使用

使用模块化文件时,请遵循以下指南应用 @auto_docstring 装饰器:

  • 对于模块化文件中的独立模型: 像在常规建模文件中一样应用 @auto_docstring 装饰器。

  • 对于继承自其他库模型的模型

    • 继承自父模型时,装饰器(包括 @auto_docstring)会自动传递到生成的建模文件,无需在您的模块化文件中添加它们。
    • 如果您需要修改 @auto_docstring 的行为,请在您的模块化文件中应用自定义的装饰器,并确保 包含所有其他装饰器,这些装饰器存在于原始函数/类上。

    警告:在模块化文件中覆盖任何装饰器时,您必须包含应用于父模型中该函数/类的所有装饰器。如果您只覆盖某些装饰器,则其他装饰器将不会包含在生成的建模文件中。

注意check_auto_docstrings 工具不直接检查模块化文件,但会检查(并在使用 --fix_and_overwrite 时修改)生成的建模文件。如果在生成的文件中发现问题,您需要相应地更新您的模块化文件。


✅ 使用 check_auto_docstrings 检查您的文档字符串

该库包含一个用于验证文档字符串的实用脚本。此检查通常在持续集成 (CI) 期间运行。

检查内容:

  • 装饰器存在性: 确保 @auto_docstring 应用于相关的模型类和公共方法。(待办)
  • 参数完整性和一致性
    • 标记签名中不是已知标准参数且缺少本地描述的参数。
    • 确保文档化的参数存在于签名中。(待办)
    • 验证文档字符串中的类型和默认值与签名匹配。(待办)
  • 占位符检测: 提醒您完成 <fill_type><fill_docstring> 等占位符。
  • 格式: 符合预期的文档字符串样式。

本地运行检查:

在提交前在本地运行此检查。常用的命令是

make fix-copies

或者,要只执行文档字符串和自动文档字符串检查,您可以使用

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

检查器工作流程:

  1. @auto_docstring(...) 添加到类或方法。
  2. 对于新的、自定义的或被覆盖的参数,在 r""" """ 块中添加描述。
  3. 运行 make fix-copies(或 check_docstrings.py 实用程序)。
    • 对于缺少文档的无法识别的参数,该实用程序将创建占位符条目。
  4. 手动编辑这些占位符,并填写准确的类型和描述。
  5. 重新运行检查以确保所有问题都已解决。

🔑 主要内容和最佳实践

  • @auto_docstring 用于新的 PyTorch 模型类(PreTrainedModel 子类)及其主要方法(例如,forwardget_text_features 等)。
  • 对于类,当在类上使用 @auto_docstring 时,__init__ 方法的文档字符串是参数描述的主要来源。
  • 依赖标准文档字符串;除非它们的行为在您的特定模型中有所不同,否则不要重新定义常用参数。
  • 清晰地文档化新的或自定义的参数。
  • 在本地迭代运行 check_docstrings

遵循这些指南,您将有助于为 Hugging Face Transformers 库维护一致且信息丰富的文档 🤗。

< > 在 GitHub 上更新