Transformers documentation
ドキュメント文字列の自動生成
ドキュメント文字列の自動生成
@auto_docstring デコレーターは、モデルクラスおよびメソッドに対して一貫性のあるドキュメント文字列を生成します。標準的な引数の説明を自動的に取り込むため、新規またはカスタムの引数のドキュメントのみを記述すれば構いません。新しいモデルを追加する際には、定型の記述を省略し、新規の機能に集中できます。
@auto_docstring
modular_model.py ファイル(旧モデルの場合は modeling_model.py)にデコレーターをインポートします。
from ...utils import auto_docstringモデルがモジュラーファイル内の別のライブラリのモデルを継承している場合、@auto_docstring は親クラスにすでに適用されています。make fix-repo が生成された modeling_model.py ファイルにコピーします。動作をカスタマイズする(スタンドアロンモデル、カスタムのイントロ、またはオーバーライドされた引数)場合のみ、デコレーターを明示的に適用してください。
モジュール化ファイルでデコレータをオーバーライドする場合は、親関数または親クラスからすべてのデコレータを含める必要があります。一部のデコレータのみをオーバーライドすると、残りは生成されるモデリングファイルに反映されません。
このデコレーターは、以下の任意の引数を受け取ります:
| 引数 | 説明 |
|---|---|
custom_intro | Args セクションの前に挿入されるクラスまたはメソッドの説明です。ForCausalLM や ForTokenClassification のような 認識されるサフィックス で終わらないクラスには必須です。 |
custom_args | 特定の引数に関するDocstringのテキストです。モデリングファイル内で同じカスタム引数が複数の箇所に出現する場合に便利です。 |
checkpoint | 使用例を生成するために使用するモデルチェックポイント識別子("org/my-model")。設定クラスから自動推論されるチェックポイントをオーバーライドします。通常、設定クラスに設定されます。 |
使用方法
@auto_docstring の動作は、装飾する対象によって異なります。モデルクラスは __init__ からパラメータのドキュメントを取得し、設定クラスはクラスレベルのアノテーションから取得します。プロセッサークラスはコンポーネントからイントロを自動生成し、forward のようなメソッドには戻り値の型と使用例が付与されます。
モデルクラス
@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より詳細な制御を行うには、custom_intro と custom_args を渡します。カスタム引数は custom_args に、または __init__ の docstring に記述できます。複数のメソッドで同じ引数が繰り返し使用される場合は、custom_args を使用してください。
@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を継承するクラスにも適用します。
@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 のサブクラスに、@strict デコレータの隣に直接配置します。@strict はランタイムでの型検証を追加し、クラスを検証済みのデータクラスに変換します。設定パラメータは__init__ の引数ではなく、クラスレベルのアノテーションであり、@auto_docstring はクラス本体からそれを読み取ってドキュメントを生成します。
ConfigArgs は、vocab_size、hidden_size、num_hidden_layers などの標準的なパラメータを提供します。そのため、動作が異なる場合を除き、説明は不要です。PreTrainedConfig のベースパラメータは自動的に除外されます。checkpoint 引数は、使用例を生成します。
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"
# Standard params (vocab_size, hidden_size, etc.) are auto-documented from ConfigArgs.
vocab_size: int = 32000
hidden_size: int = 768
num_hidden_layers: int = 12
# Model-specific params must be documented in the class docstring above.
custom_param: int = 64
another_param: str = "gelu"プロセッサクラス
マルチモーダルプロセッサ(ProcessorMixin のサブクラス、processing_*.py)は、常にプレーンな@auto_docstringを使用します。クラスの紹介文は自動生成されます。ProcessorArgs(image_processor、tokenizer、chat_template など)で既にカバーされていない__init__のパラメータのみをドキュメント化してください。
すべてのパラメータが標準的な場合は、docstringを省略してください。__call__にも@auto_docstringを付与してください。その本体のdocstringには、Returns:セクションと、モデル固有の追加のcall引数のみを記述します。return_tensorsは自動的に追加されます。
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/en/main_classes/feature_extractor#transformers.BatchFeature): A [BatchFeature](/docs/transformers/main/en/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__にはドキュメント文字列がありません。
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.")を使用してください。
@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クラスのドキュメント文字列から、戻り値のテキストを生成します。
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 を使用して共有される引数のドキュメントを一度だけ定義できます。
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に手動で記述し、自動生成されたバージョンを上書きします。
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)
```
"""
# ...引数のドキュメント化
異なる引数の型をドキュメント化する際は、以下のルールに従ってください。
auto_docstring.pyは標準的な引数(input_ids、attention_mask、pixel_valuesなど)を定義し、自動的にそれらを含みます。モデル内で引数の挙動が異なる場合を除き、ローカルで再定義しないでください。モデル内で標準的な引数の動作が異なる場合は、
r""" """ブロック内でローカルにオーバーライドしてください。ローカル定義が優先されます。例えば、labels引数はモデルごとにカスタマイズされることが多く、オーバーライドが必要なケースが一般的です。標準の config 引数(
vocab_size、hidden_size、num_hidden_layersなど)は同じ原則に従いますが、ConfigArgsから提供されます。標準の processor 引数(image_processor、tokenizer、do_resize、return_tensorsなど)はProcessorArgsとImageProcessorArgsから提供されます。パラメータは、モデル固有である場合、または標準の説明と動作が異なる場合にのみドキュメント化してください。r""" """ブロックで、新規またはカスタムの引数をドキュメント化します。関数の場合はシグネチャの後に、モデルやプロセッサクラスの場合は__init__のドキュメント文字列に、設定クラスの場合はクラス本体のドキュメント文字列に、画像プロセッサの場合はXxxImageProcessorKwargsのTypedDict本体に配置します。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に渡します(上記の関数の例を参照)。
デコレーターは、関数のシグネチャから型を自動的に抽出します。パラメーターに型アノテーションがある場合、docstringのフォーマット文字列で型を繰り返す必要はありません。両方が存在する場合、シグネチャの型が優先されます。docstringの型は、アノテーションのないパラメーターのフォールバックとして機能します。
ドキュメント文字列の確認
プルリクエストを開くと、ユーティリティスクリプトがドキュメント文字列を検証します。CIはこのスクリプトを実行し、以下の項目を確認します。
出力に
[ERROR]が表示された場合は、auto_docstring.py内のドキュメント文字列または適切なArgsクラスに、そのパラメータの説明を追加してください。
@auto_docstringが関連するモデルクラスおよび公開メソッドに適用されていることを確認します。- 引数の完全性と一貫性を検証します。ドキュメントに記載されている引数はシグネチャに存在する必要があり、型とデフォルト値が一致している必要があります。ローカルな説明のない不明な引数はフラグが立てられます。
<fill_type>や<fill_docstring>のような不完全なプレースホルダーをフラグ付けします。- ドキュメント文字列が期待されるフォーマットスタイルに従っていることを検証します。
コミットする前に、ローカルでチェックを実行してください。
make fix-repo
make fix-repo は、他のいくつかのチェックも実行します。docstring と auto-docstring のチェックのみを実行するには、以下のコマンドを使用してください。
# 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 デコレーターは、以下の手順でドキュメント文字列を生成します。
デコレーターは、デコレートされたクラスの
__init__またはデコレートされた関数のシグネチャを解析し、引数、型、デフォルト値を読み取ります。設定クラスの場合、クラスレベルのアノテーションを継承チェーンに沿って上方向にたどり、PreTrainedConfigの手前で停止し、ベースクラスのフィールドを除外します。self、kwargs、args、deprecated_arguments、および_プレフィックス付きの名前などのパラメータは自動的に除外されます。一部のプライベートパラメータは、パブリックな対応する名称にリネームされます(バックボーンモデルでは_out_features→out_features)。一般的な引数の説明は
auto_docstring.pyから取得されます:ModelArgs(モデルの入力)、ModelOutputArgs(hidden_statesなどの出力フィールド)、ImageProcessorArgs(画像の前処理)、ProcessorArgs(マルチモーダルプロセッサのコンポーネント)、およびConfigArgs(設定のハイパーパラメータ)。各パラメータの説明は、以下の優先順位に従います。
- 手動で定義された docstring(
r""" """ブロックまたはcustom_args)が優先されます。 - 事前定義されたソースの辞書(
ModelArgs、ModelForArgs、ConfigArgs、ImageProcessorArgs、ProcessorArgs、ModelOutputArgs)がフォールバックとして使用されます。 - ソースのいずれにも説明がない場合、ビルド出力でそのパラメータは
[ERROR]としてフラグが立てられます。
- 手動で定義された docstring(
ModelForCausalLMのような標準的な名前を持つモデルクラス、またはパイプラインにマッピングされるクラスの場合、@auto_docstringがイントロを生成します。マルチモーダルプロセッサの場合、イントロには、そのクラスがラップしているコンポーネント(トークナイザー、画像プロセッサなど)がリストされます。完全なリストについては、ClassDocstring を参照してください。ClassDocstringにクラス名がない場合は、custom_introを設定してください。事前定義された docstring は、auto_modules 内の動的な値、例えば
{processor_class}、{image_processor_class}、{config_class}を参照できます。プレースホルダーは自動的に解決されます。デコレーターは、モデルのタスクまたはパイプラインとの互換性に基づいて使用例を選択します。設定クラスからチェックポイントのメタデータを読み取り、使用例に実際のモデル ID が使用されるようにします。
checkpoint引数は、設定クラスのドキュメントストリングから推測されるチェックポイントをオーバーライドします。設定クラスにcheckpointを設定するか、チェックポイントの推測に失敗した場合に設定してください。"Config not found for <model_name>"のようなエラーが表示された場合は、auto_docstring.pyのHARDCODED_CONFIG_FOR_MODELSにエントリを追加してください。forwardのようなメソッドの場合、デコレーターはメソッドの戻り値の型からReturnsセクションを生成します。戻り値の型が ModelOutput のサブクラスである場合、@auto_docstringはそのクラスのドキュメント文字列からフィールドの説明を取得します。関数のドキュメント文字列にカスタムのReturnsブロックがある場合は、そちらが優先されます。UNROLL_KWARGS_METHODSのメソッドとUNROLL_KWARGS_CLASSESのクラスでは、このデコレーターはUnpack[KwargsTypedDict]で型付けされた**kwargsを展開します。TypedDictの各キーが、ドキュメント化されたパラメータになります。同じ展開は、BaseImageProcessorおよびProcessorMixinのサブクラスにおける
__call__メソッドとpreprocessメソッドにも適用されます。汎用的なベース型(TextKwargs、ImagesKwargs、VideosKwargs、AudioKwargs)はスキップされます。展開されるのは、モデル固有のサブクラスのみです。