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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.