# ドキュメント文字列の自動生成

`@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]
> モジュール化ファイルでデコレーターをオーバーライドする場合は、親の関数またはクラスから**すべての**デコレーターを含める必要があります。一部のデコレーターのみをオーバーライドすると、残りは生成されるモデリングファイルに反映されません。

このデコレーターは、以下の任意の引数を受け取ります:

| 引数 | 説明 |
|---|---|
| `custom_intro` | Args セクションの前に挿入される、クラスまたはメソッドの説明。クラス名が`ForCausalLM`や`ForTokenClassification`のような[認識されるサフィックス](#how-it-works)で終わらない場合は必須です。 |
| `custom_args` | 特定の引数に関するDocstringのテキストです。モデリングファイル内で同じカスタム引数が複数の箇所に出現する場合に便利です。 |
| `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/main/ja/main_classes/output#transformers.utils.ModelOutput)を継承するクラスにも適用します。

```python
@auto_docstring(
    custom_intro="""
    Custom model outputs with additional fields.
    """
)
@dataclass
class MyModelOutput(ImageClassifierOutput):
    r"""
    loss (`torch.FloatTensor`, *optional*):
        The loss of the model.
    custom_field (`torch.FloatTensor` 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.FloatTensor] = None
    logits: Optional[torch.FloatTensor] = None
    hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
    attentions: Optional[tuple[torch.FloatTensor, ...]] = None
    # Custom fields need to be documented in the docstring above
    custom_field: Optional[torch.FloatTensor] = None
```

### 設定クラス

`@auto_docstring` を [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のサブクラスに、`@strict` デコレータの隣に直接配置します。`@strict` はランタイムでの型検証を追加し、クラスを検証済みのデータクラスに変換します。設定パラメータは`__init__` の引数ではなく、*クラスレベルのアノテーション*であり、`@auto_docstring` はクラス本体からそれを読み取ってドキュメントを生成します。

`ConfigArgs` は `vocab_size`、`hidden_size`、`num_hidden_layers` などの標準的なパラメータを提供します。そのため、動作が異なる場合を除き、説明は不要です。[PreTrainedConfig](/docs/transformers/main/ja/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 # モデル固有のパラメータは、上記のクラスの docstring に記載する必要があります。custom_param: int = 64 another_param: str = "gelu"
```

### Processor classes

Multimodal processors ([ProcessorMixin](/docs/transformers/main/ja/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):
    _defaults = {"text_kwargs": {"padding": False}}

@auto_docstring
class MyModelProcessor(ProcessorMixin):
    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/main/ja/main_classes/feature_extractor#transformers.BatchFeature): A [BatchFeature](/docs/transformers/main/ja/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`）は、2つのパターンのいずれかを採用しています。

プロセッサにモデル固有のパラメータがある場合は、それらのパラメータのドキュメント文字列を持つ`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)
```

クラスがカスタム kwarg を持たず、標準的なクラスレベル属性（`size`、`resample`、`image_mean` など）のみを設定する場合、代わりに`@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"""
        # ...
```

`Returns`セクションと`Examples`セクションをdocstringに手動で記述し、自動生成されたバージョンを上書きします。

```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)を参照）。

- デコレーターは、関数のシグネチャから型を自動的に抽出します。パラメーターに型アノテーションがある場合、docstring のフォーマット文字列で型を繰り返す必要はありません。両方が存在する場合、シグネチャの型が優先されます。docstring の型は、アノテーションのないパラメーターのフォールバックとして機能します。

## ドキュメント文字列の確認

プルリクエストを開くと、ユーティリティスクリプトがドキュメント文字列を検証します。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
```

## クイックリファレンスチェックリスト

| Do | しない |
|---|---|
| モデル、設定、プロセッサのクラスおよびそれらの主要なメソッド（`forward`、`__call__`、`preprocess`）に`@auto_docstring`を適用します。 | モジュールファイル内の継承モデルには`@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/main/ja/main_classes/configuration#transformers.PreTrainedConfig)の手前で停止し、ベースクラスのフィールドを除外します。

    `self`、`kwargs`、`args`、`deprecated_arguments`、および`_`プレフィックス付きの名前などのパラメータは自動的に除外されます。一部のプライベートパラメータは、パブリックな対応する名称にリネームされます（バックボーンモデルでは`_out_features` → `out_features`）。

2. 一般的な引数の説明は`auto_docstring.py`から取得されます: `ModelArgs`（モデルの入力）、`ModelOutputArgs`（`hidden_states`などの出力フィールド）、`ImageProcessorArgs`（画像の前処理）、`ProcessorArgs`（マルチモーダルプロセッサのコンポーネント）、および`ConfigArgs`（設定のハイパーパラメータ）。

3. 各パラメータの説明は、以下の優先度チェーンに従います。

    - 手動で定義された docstring（`r""" """` ブロックまたは `custom_args`）が優先されます。
    - 事前定義されたソースの辞書(`ModelArgs`、`ModelForArgs`、`ConfigArgs`、`ImageProcessorArgs`、`ProcessorArgs`、`ModelOutputArgs`)がフォールバックとして使用されます。
    - ソースのいずれにも説明がない場合、ビルド出力でそのパラメータは`[ERROR]`としてフラグが立てられます。

4. `ModelForCausalLM` のような標準的な名前を持つモデルクラス、またはパイプラインにマッピングされるクラスの場合、`@auto_docstring` がイントロを生成します。マルチモーダルプロセッサの場合、イントロには、そのクラスがラップしているコンポーネント（トークナイザー、画像プロセッサなど）がリストされます。完全なリストについては、[ClassDocstring](https://github.com/huggingface/transformers/blob/main/src/transformers/utils/auto_docstring.py#L2437) を参照してください。

    `ClassDocstring` にクラス名がない場合は、`custom_intro` を設定してください。

5. 事前定義済みの docstring では、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/main/ja/main_classes/output#transformers.utils.ModelOutput) のサブクラスの場合、`@auto_docstring` はそのクラスのドキュメント文字列からフィールドの説明を取得します。関数のドキュメント文字列にカスタムの `Returns` ブロックがある場合は、そちらが優先されます。

8. `UNROLL_KWARGS_METHODS` のメソッドと `UNROLL_KWARGS_CLASSES` のクラスでは、このデコレーターは `Unpack[KwargsTypedDict]` で型付けされた `**kwargs` を展開します。`TypedDict` の各キーが、ドキュメント化されたパラメータになります。

    同じ展開は、[BaseImageProcessor](/docs/transformers/main/ja/main_classes/image_processor#transformers.BaseImageProcessor)および[ProcessorMixin](/docs/transformers/main/ja/main_classes/processors#transformers.ProcessorMixin)のサブクラスにおける`__call__`メソッドと`preprocess`メソッドにも適用されます。汎用的なベース型（`TextKwargs`、`ImagesKwargs`、`VideosKwargs`、`AudioKwargs`）はスキップされます。展開されるのは、モデル固有のサブクラスのみです。

