# Membuat docstring secara otomatis

Dekorator `@auto_docstring` menghasilkan docstring yang konsisten untuk kelas dan metode model. Dekorator ini menarik deskripsi argumen standar secara otomatis, sehingga Anda hanya perlu menulis dokumentasi untuk argumen baru atau kustom. Saat [menambahkan model baru](./modular_transformers), lewati bagian boilerplate dan fokus pada hal-hal yang baru.

## @auto_docstring

Impor dekorator di file `modular_model.py` Anda (atau `modeling_model.py` untuk model yang lebih lama).

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

Jika model Anda mewarisi model dari pustaka lain dalam file modular, `@auto_docstring` sudah diterapkan di induknya. `make fix-repo` menyalinnya ke file `modeling_model.py` yang dihasilkan untuk Anda. Terapkan dekorator secara eksplisit hanya untuk menyesuaikan perilakunya (model mandiri, intro kustom, atau argumen yang ditimpa).

> [!WARNING]
> Saat menimpa dekorator apa pun dalam file modular, sertakan **semua** dekorator dari fungsi atau kelas induk. Jika Anda hanya menimpa sebagian, sisanya tidak akan muncul dalam file modeling yang dihasilkan.

Decorator menerima argumen opsional berikut:

| argument | deskripsi |
|---|---|
| `custom_intro` | Deskripsi kelas atau metode, disisipkan sebelum bagian Args. Wajib untuk kelas yang tidak diakhiri dengan [awalan yang dikenali](#how-it-works) seperti `ForCausalLM` atau `ForTokenClassification`. |
| `custom_args` | Teks docstring untuk parameter tertentu. Berguna ketika argumen kustom yang sama muncul di beberapa tempat dalam file pemodelan. |
| `checkpoint` | Identifikasi checkpoint model (`"org/my-model"`) yang digunakan untuk menghasilkan contoh penggunaan. Menimpa checkpoint yang disimpulkan secara otomatis dari kelas konfigurasi. Biasanya diset pada kelas konfigurasi. |

## Penggunaan

Cara kerja `@auto_docstring` bergantung pada apa yang Anda dekorasi. Kelas model mengambil dokumentasi parameter dari `__init__`, kelas config mengambilnya dari anotasi tingkat kelas, kelas processor menghasilkan intros secara otomatis dari komponen-komponennya, dan metode seperti `forward` mendapatkan tipe pengembalian serta contoh penggunaan.

### Kelas model

Letakkan `@auto_docstring` tepat di atas definisi kelas. Dekorator ini menurunkan deskripsi parameter dari tanda tangan dan docstring metode `__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
```

Lewati `custom_intro` dan `custom_args` untuk kontrol lebih lanjut. Argumen kustom dapat diletakkan di `custom_args` atau di docstring `__init__`. Gunakan `custom_args` ketika argumen yang sama berulang di beberapa metode.

```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):
        # ...
```

Terapkan juga `@auto_docstring` pada kelas yang mewarisi dari [ModelOutput](/docs/transformers/main/id/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
```

### Kelas konfigurasi

Letakkan `@auto_docstring` tepat di atas subclass [PreTrainedConfig](/docs/transformers/main/id/main_classes/configuration#transformers.PreTrainedConfig), berdampingan dengan dekorator `@strict`. `@strict` menambahkan validasi tipe pada runtime dan mengubah kelas menjadi dataclass yang tervalidasi. Parameter config adalah *annotasi tingkat kelas* (bukan argumen `__init__`), dan `@auto_docstring` membacanya dari badan kelas untuk menghasilkan dokumentasi.

`ConfigArgs` menyediakan parameter standar seperti `vocab_size`, `hidden_size`, dan `num_hidden_layers`, sehingga tidak memerlukan deskripsi kecuali perilakunya berbeda. Parameter dasar [PreTrainedConfig](/docs/transformers/main/id/main_classes/configuration#transformers.PreTrainedConfig) dikecualikan secara otomatis. Argumen `checkpoint` menghasilkan contoh penggunaan.

```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"

    # Parameter standar (vocab_size, hidden_size, dll.) didokumentasikan secara otomatis dari ConfigArgs. vocab_size: int = 32000 hidden_size: int = 768 num_hidden_layers: int = 12 # Parameter spesifik model harus didokumentasikan dalam docstring kelas di atas. custom_param: int = 64 another_param: str = "gelu"
```

### Processor classes

Multimodal processors ([ProcessorMixin](/docs/transformers/main/id/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/main/id/main_classes/feature_extractor#transformers.BatchFeature): A [BatchFeature](/docs/transformers/main/id/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.
        """
        # ...
```

#### Pemroses gambar dan video

Pemroses gambar dan video (subkelas `BaseImageProcessor`, `image_processing_*.py`) mengikuti salah satu dari dua pola.

Jika prosesor memiliki parameter yang spesifik untuk model, definisikan TypedDict `XxxImageProcessorKwargs(ImagesKwargs, total=False)` dengan docstring untuk parameter tersebut, atur `valid_kwargs` pada kelas, dan gunakan `@auto_docstring` polos. `__init__` tidak memiliki docstring.

```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)
```

Jika kelas hanya mengatur atribut tingkat kelas standar (`size`, `resample`, `image_mean`, dll.) tanpa kwargs kustom, gunakan `@auto_docstring(custom_intro="Constructs a MyModel image processor.")` sebagai gantinya.

```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}
```

Saat menimpa `preprocess`, hiasi dengan `@auto_docstring` dan dokumentasikan hanya argumen yang tidak ada di `ImageProcessorArgs`. Argumen standar dan `return_tensors` disertakan secara otomatis.

### Fungsi

Letakkan `@auto_docstring` tepat di atas definisi fungsi. Dekorator ini menurunkan deskripsi parameter dari tanda tangan fungsi.

Decorator menghasilkan teks nilai pengembalian dari docstring kelas `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.
        """
        # ...
```

Lewati `custom_intro` dan `custom_args` untuk kontrol lebih lanjut. Gunakan `custom_args` untuk mendokumentasikan argumen bersama sekali ketika parameter yang sama muncul di beberapa metode.

```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"""
        # ...
```

Tulis bagian `Returns` dan `Examples` secara manual di docstring untuk menimpa versi yang dibuat otomatis.

```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.
    ```

  * Sertakan `type` dalam backticks.
  * Tambahkan *opsional* jika argumen tidak wajib atau memiliki nilai default.
  * Tambahkan "defaultnya X" jika memiliki nilai default. Anda tidak perlu menambahkan "defaultnya `None`" jika nilai defaultnya adalah `None`.
  * Lewatkan blok yang sama ke `custom_args` ketika argumen yang sama berulang di beberapa metode (lihat [contoh Fungsi di atas](#functions)).

- Decorator mengekstrak tipe dari tanda tangan fungsi secara otomatis. Jika sebuah parameter memiliki anotasi tipe, Anda tidak perlu mengulang tipe tersebut dalam string format docstring. Ketika keduanya hadir, tipe dari tanda tangan memiliki prioritas. Tipe dalam docstring berfungsi sebagai cadangan untuk parameter yang tidak dianotasi.

## Mengecek docstring

Skrip utilitas memvalidasi docstring saat Anda membuka pull request. CI menjalankan skrip tersebut dan memeriksa hal-hal berikut.

> [!TIP]
> Jika Anda melihat `[ERROR]` dalam output, tambahkan deskripsi parameter ke docstring atau kelas Args yang sesuai di `auto_docstring.py`.

* Memeriksa bahwa `@auto_docstring` diterapkan pada kelas model dan metode publik yang relevan.
* Memvalidasi kelengkapan dan konsistensi argumen: argumen yang terdokumentasi harus ada dalam tanda tangan, dan tipe serta nilai default harus cocok. Argumen yang tidak dikenal tanpa deskripsi lokal ditandai.
* Menandai placeholder yang tidak lengkap seperti `<fill_type>` dan `<fill_docstring>`.
* Memverifikasi bahwa docstring mengikuti gaya format yang diharapkan.

Jalankan pemeriksaan secara lokal sebelum melakukan commit.

```bash
make fix-repo
```

`make fix-repo` juga menjalankan beberapa pemeriksaan lain. Untuk hanya menjalankan pemeriksaan docstring dan auto-docstring, gunakan perintah di bawah ini.

```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
```

## Daftar periksa referensi cepat

| Lakukan | Jangan |
|---|---|
| Terapkan `@auto_docstring` pada kelas model, config, dan processor serta metode utama mereka (`forward`, `__call__`, `preprocess`). | Tambahkan `@auto_docstring` ke model yang diwarisi dalam file modular karena atribut ini diturunkan secara otomatis. |
| Dokumentasikan hanya argumen baru atau argumen yang spesifik untuk model. | Definisikan ulang argumen standar (`input_ids`, `attention_mask`, `vocab_size`, dll.) yang berperilaku sama dengan deskripsi default-nya. |
| Letakkan parameter config dalam docstring badan kelas sebagai anotasi tingkat kelas. | Letakkan parameter config di `__init__`. |
| Letakkan parameter pemroses gambar dalam TypedDict `XxxImageProcessorKwargs`. | Letakkan parameter image processor di `__init__`. |
| Jalankan `python utils/check_docstrings.py --fix_and_overwrite` sebelum melakukan commit. | Abaikan output `[ERROR]` karena itu berarti sebuah parameter tidak terdokumentasi. |

## Cara kerjanya

Dekorator `@auto_docstring` menghasilkan docstring melalui langkah-langkah berikut.

1. Decorator memeriksa signature untuk membaca argumen, tipe, dan nilai default dari `__init__` kelas yang didekorasi atau dari fungsi yang didekorasi. Untuk kelas konfigurasi, decorator menelusuri anotasi tingkat kelas di sepanjang rantai warisan dan berhenti sebelum [PreTrainedConfig](/docs/transformers/main/id/main_classes/configuration#transformers.PreTrainedConfig), sehingga mengecualikan field dari kelas dasar.

    Secara otomatis, parameter seperti `self`, `kwargs`, `args`, `deprecated_arguments`, dan nama dengan awalan `_` akan disaring. Beberapa parameter privat diganti namanya menjadi padanan publiknya (`_out_features` → `out_features` untuk model backbone).

2. Deskripsi argumen umum berasal dari `auto_docstring.py`: `ModelArgs` (input model), `ModelOutputArgs` (field output seperti `hidden_states`), `ImageProcessorArgs` (pra-pemrosesan gambar), `ProcessorArgs` (komponen pemroses multimodal), dan `ConfigArgs` (hiperparameter konfigurasi).

3. Deskripsi setiap parameter mengikuti rantai prioritas berikut:

    - Docstring manual (`r""" """` blok atau `custom_args`) memiliki prioritas lebih tinggi.
    - Dict sumber yang predefined (`ModelArgs`, `ModelForArgs`, `ConfigArgs`, `ImageProcessorArgs`, `ProcessorArgs`, `ModelOutputArgs`) adalah fallback.
    - Jika kedua sumber tidak memiliki deskripsi, parameter ditandai dengan `[ERROR]` dalam output build.

4. Untuk kelas model dengan nama standar seperti `ModelForCausalLM`, atau kelas yang dipetakan ke sebuah pipeline, `@auto_docstring` menghasilkan bagian pengantar. Untuk pemroses multimodal, bagian pengantar mencantumkan komponen mana (tokenizer, image processor, dan sebagainya) yang dibungkus oleh kelas tersebut. Lihat [ClassDocstring](https://github.com/huggingface/transformers/blob/main/src/transformers/utils/auto_docstring.py#L2437) untuk daftar lengkapnya.

    Jika nama kelas tidak ada di `ClassDocstring`, atur `custom_intro`.

5. Docstring yang sudah didefinisikan dapat merujuk ke nilai dinamis dari [auto_modules](https://github.com/huggingface/transformers/tree/main/src/transformers/models/auto) Transformers, seperti `{processor_class}`, `{image_processor_class}`, dan `{config_class}`. Placeholder akan diselesaikan secara otomatis.

6. Decorator memilih contoh penggunaan berdasarkan tugas atau kompatibilitas pipeline model. Ia membaca metadata checkpoint dari kelas konfigurasi sehingga contoh menggunakan ID model yang sebenarnya. Argumen `checkpoint` menimpa checkpoint yang disimpulkan dari docstring kelas konfigurasi. Tetapkan `checkpoint` pada kelas konfigurasi, atau ketika penarikan kesimpulan checkpoint gagal. Jika Anda melihat error seperti `"Config not found for <model_name>"`, tambahkan entri ke `HARDCODED_CONFIG_FOR_MODELS` di `auto_docstring.py`.

7. Untuk metode seperti `forward`, dekorator menulis bagian `Returns` dari tipe pengembalian metode tersebut. Ketika tipe pengembaliannya adalah subkelas [ModelOutput](/docs/transformers/main/id/main_classes/output#transformers.utils.ModelOutput), `@auto_docstring` mengambil deskripsi field dari docstring kelas tersebut. Blok `Returns` kustom dalam docstring fungsi memiliki prioritas lebih tinggi.

8. Untuk metode dalam `UNROLL_KWARGS_METHODS` dan kelas dalam `UNROLL_KWARGS_CLASSES`, dekorator mengembang `**kwargs` yang bertipe `Unpack[KwargsTypedDict]`. Setiap kunci dari `TypedDict` menjadi parameter yang terdokumentasi.

    Ekspansi yang sama berlaku untuk metode `__call__` dan `preprocess` pada subclass [BaseImageProcessor](/docs/transformers/main/id/main_classes/image_processor#transformers.BaseImageProcessor) dan [ProcessorMixin](/docs/transformers/main/id/main_classes/processors#transformers.ProcessorMixin). Tipe basis generik (`TextKwargs`, `ImagesKwargs`, `VideosKwargs`, `AudioKwargs`) dilewati. Hanya subclass yang spesifik untuk model yang diurai.

