Buckets:

hf-doc-build/doc / transformers /main /vi /auto_docstring.md
mishig's picture
|
download
raw
23.6 kB
# Tự động tạo docstring
Trình trang trí `@auto_docstring` tạo ra các docstring nhất quán cho các lớp và phương thức của model. Nó tự động lấy các mô tả tham số chuẩn, vì vậy bạn chỉ cần viết tài liệu cho các tham số mới hoặc tùy chỉnh. Khi [thêm một model mới](./modular_transformers), hãy bỏ qua các phần lặp lại và tập trung vào những gì mới.
## @auto_docstring
Nhập decorator trong tệp `modular_model.py` của bạn (hoặc `modeling_model.py` đối với các model cũ hơn).
```python
from ...utils import auto_docstring
```
Nếu model của bạn kế thừa từ một model của thư viện khác trong một file modular, `@auto_docstring` đã được áp dụng trong class cha. `make fix-repo` sẽ sao chép nó vào file `modeling_model.py` được tạo ra cho bạn. Chỉ cần áp dụng decorator một cách tường minh để tùy chỉnh hành vi của nó (các model độc lập, custom intros, hoặc các argument bị ghi đè).
> [!WARNING]
> Khi ghi đè bất kỳ decorator nào trong một file modular, hãy bao gồm **tất cả** các decorator từ hàm hoặc lớp cha. Nếu bạn chỉ ghi đè một số, phần còn lại sẽ không xuất hiện trong file modeling được tạo ra.
Trình trang trí chấp nhận các đối số tùy chọn sau:
| tham số | mô tả |
|---|---|
| `custom_intro` | Mô tả lớp hoặc phương thức, được chèn vào trước phần Args. Bắt buộc đối với các lớp không kết thúc bằng [hậu tố được công nhận](#how-it-works) như `ForCausalLM` hoặc `ForTokenClassification`. |
| `custom_args` | Văn bản docstring cho các tham số cụ thể. Hữu ích khi cùng một tập hợp các đối số tùy chỉnh xuất hiện ở nhiều vị trí khác nhau trong tệp modeling. |
| `checkpoint` | Một định danh checkpoint mô hình (`"org/my-model"`) được sử dụng để tạo các ví dụ sử dụng. Ghi đè checkpoint được suy luận tự động từ lớp cấu hình. Thường được đặt trên các lớp cấu hình. |
## Cách sử dụng
Cách `@auto_docstring` hoạt động phụ thuộc vào đối tượng bạn đang trang trí. Các lớp Model lấy tài liệu tham số từ `__init__`, các lớp config lấy từ các chú thích ở cấp lớp, các lớp processor tự động tạo mô tả từ các thành phần của chúng, và các phương thức như `forward` sẽ nhận được kiểu trả về cùng các ví dụ sử dụng.
### Các lớp mô hình
Đặt `@auto_docstring` ngay phía trên định nghĩa lớp. Bộ trang trí này suy ra mô tả tham số từ chữ ký và docstring của phương thức `__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
```
Truyền `custom_intro` và `custom_args` để có thêm quyền kiểm soát. Các đối số tùy chỉnh có thể đặt trong `custom_args` hoặc trong docstring của `__init__`. Sử dụng `custom_args` khi cùng một tập hợp đối số lặp lại ở nhiều phương thức khác nhau.
```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):
# ...
```
Cũng áp dụng `@auto_docstring` cho các lớp kế thừa từ [ModelOutput](/docs/transformers/main/vi/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
```
### Các lớp cấu hình
Đặt `@auto_docstring` ngay phía trên một lớp con của [PreTrainedConfig](/docs/transformers/main/vi/main_classes/configuration#transformers.PreTrainedConfig), cùng với decorator `@strict`. `@strict` thêm vào việc kiểm tra kiểu dữ liệu lúc runtime và biến lớp thành một dataclass đã được kiểm chứng. Các tham số cấu hình là *ghi chú kiểu ở cấp lớp* (không phải các đối số của `__init__`), và `@auto_docstring` đọc chúng từ thân lớp để tạo tài liệu.
`ConfigArgs` cung cấp các tham số chuẩn như `vocab_size`, `hidden_size` và `num_hidden_layers`, do đó chúng không cần mô tả trừ khi hành vi khác đi. Các tham số cơ sở của [PreTrainedConfig](/docs/transformers/main/vi/main_classes/configuration#transformers.PreTrainedConfig) được loại bỏ tự động. Đối số `checkpoint` tạo ra ví dụ sử dụng.
```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"
# Các tham số chuẩn (vocab_size, hidden_size, v.v.) được tự động tài liệu hóa từ ConfigArgs. vocab_size: int = 32000 hidden_size: int = 768 num_hidden_layers: int = 12 # Các tham số cụ thể của mô hình phải được tài liệu hóa trong docstring của lớp ở trên. custom_param: int = 64 another_param: str = "gelu"
```
### Processor classes
Multimodal processors ([ProcessorMixin](/docs/transformers/main/vi/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/vi/main_classes/feature_extractor#transformers.BatchFeature): A [BatchFeature](/docs/transformers/main/vi/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.
"""
# ...
```
#### Bộ xử lý hình ảnh và video
Bộ xử lý hình ảnh và video (các lớp con của `BaseImageProcessor`, `image_processing_*.py`) tuân theo một trong hai mẫu.
Nếu bộ xử lý có các tham số cụ thể cho mô hình, hãy định nghĩa một TypedDict `XxxImageProcessorKwargs(ImagesKwargs, total=False)` với docstring cho các tham số đó, đặt `valid_kwargs` trên lớp và sử dụng `@auto_docstring` trần. `__init__` không có 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)
```
Nếu lớp chỉ đặt các thuộc tính cấp lớp chuẩn (`size`, `resample`, `image_mean`, v.v.) mà không có kwargs tùy chỉnh nào, hãy dùng `@auto_docstring(custom_intro="Constructs a MyModel image processor.")` thay thế.
```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}
```
Khi ghi đè `preprocess`, hãy trang trí nó bằng `@auto_docstring` và chỉ tài liệu hóa các đối số không có trong `ImageProcessorArgs`. Các đối số chuẩn và `return_tensors` sẽ được bao gồm tự động.
### Hàm
Đặt `@auto_docstring` ngay phía trên định nghĩa hàm. Bộ trang trí này suy ra mô tả tham số từ chữ ký của hàm.
Trình trang trí tạo ra văn bản giá trị trả về từ docstring của lớp `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.
"""
# ...
```
Truyền `custom_intro` và `custom_args` để có thêm quyền kiểm soát. Sử dụng `custom_args` để định nghĩa tài liệu cho các tham số dùng chung một lần khi cùng một tập tham số xuất hiện trong nhiều phương thức.
```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"""
# ...
```
Viết các phần `Returns` và `Examples` thủ công trong docstring để ghi đè các phiên bản được tạo tự động.
```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.
```
* Bao gồm `type` trong dấu backtick.
* Thêm *optional* nếu đối số không bắt buộc hoặc có giá trị mặc định.
* Thêm "mặc định là X" nếu nó có giá trị mặc định. Bạn không cần thêm "mặc định là `None`" nếu giá trị mặc định là `None`.
* Truyền cùng một khối vào `custom_args` khi cùng các đối số lặp lại qua nhiều phương thức (xem [ví dụ về Functions ở trên](#functions)).
- Trình trang trí (decorator) tự động trích xuất các kiểu dữ liệu từ chữ ký của hàm. Nếu một tham số có chú thích kiểu dữ liệu, bạn không cần lặp lại kiểu đó trong chuỗi định dạng của docstring. Khi cả hai đều có mặt, kiểu dữ liệu trong chữ ký sẽ được ưu tiên. Kiểu dữ liệu trong docstring đóng vai trò là phương án dự phòng cho các tham số không có chú thích.
## Kiểm tra các docstring
Một script tiện ích xác thực docstring khi bạn mở một pull request. CI chạy script và kiểm tra các mục sau.
> [!TIP]
> Nếu bạn thấy `[ERROR]` trong đầu ra, hãy thêm mô tả của tham số vào docstring hoặc lớp Args phù hợp trong `auto_docstring.py`.
* Kiểm tra xem `@auto_docstring` có được áp dụng cho các lớp model và phương thức công khai liên quan hay không.
* Kiểm tra tính đầy đủ và nhất quán của các đối số: các đối số được tài liệu hóa phải tồn tại trong chữ ký, và kiểu dữ liệu cùng giá trị mặc định phải khớp. Các đối số không xác định mà không có mô tả cục bộ sẽ được đánh dấu.
* Đánh dấu các placeholder chưa hoàn chỉnh như `<fill_type>` và `<fill_docstring>`.
* Kiểm tra xem các docstring có tuân theo phong cách định dạng mong đợi hay không.
Chạy kiểm tra cục bộ trước khi cam kết.
```bash
make fix-repo
```
`make fix-repo` cũng chạy một số kiểm tra khác. Để chỉ chạy các kiểm tra docstring và auto-docstring, hãy sử dụng lệnh bên dưới.
```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
```
## Danh sách kiểm tra tham khảo nhanh
| Làm | Không |
|---|---|
| Áp dụng `@auto_docstring` cho các lớp model, config và processor cùng các phương thức chính của chúng (`forward`, `__call__`, `preprocess`). | Thêm `@auto_docstring` vào các model kế thừa trong các file modular vì nó được kế thừa tự động. |
| Chỉ tài liệu hóa các đối số mới hoặc các đối số cụ thể cho mô hình. | Định nghĩa lại các đối số chuẩn (`input_ids`, `attention_mask`, `vocab_size`, v.v.) có hành vi giống như mô tả mặc định của chúng. |
| Đặt các tham số cấu hình trong docstring của thân lớp dưới dạng chú thích cấp lớp. | Đặt các tham số cấu hình trong `__init__`. |
| Đặt các tham số bộ xử lý ảnh vào một TypedDict `XxxImageProcessorKwargs`. | Đặt các tham số bộ xử lý ảnh trong `__init__`. |
| Chạy `python utils/check_docstrings.py --fix_and_overwrite` trước khi commit. | Bỏ qua đầu ra `[ERROR]` vì nó có nghĩa là một tham số chưa được tài liệu hóa. |
## Cách hoạt động
Trình trang trí `@auto_docstring` tạo ra các docstring thông qua các bước sau.
1. Trình trang trí kiểm tra chữ ký để đọc các đối số, kiểu dữ liệu và giá trị mặc định từ `__init__` của lớp được trang trí hoặc từ hàm được trang trí. Đối với các lớp cấu hình, nó duyệt qua các chú thích ở cấp độ lớp dọc theo chuỗi kế thừa và dừng lại trước [PreTrainedConfig](/docs/transformers/main/vi/main_classes/configuration#transformers.PreTrainedConfig), loại trừ các trường của lớp cơ sở.
Nó tự động lọc ra các tham số như `self`, `kwargs`, `args`, `deprecated_arguments` và các tên có tiền tố `_`. Một số tham số riêng tư được đổi tên thành tương đương công khai của chúng (`_out_features` → `out_features` đối với các mô hình backbone).
2. Mô tả các đối số phổ biến được lấy từ `auto_docstring.py`: `ModelArgs` (đầu vào của model), `ModelOutputArgs` (các trường đầu ra như `hidden_states`), `ImageProcessorArgs` (tiền xử lý ảnh), `ProcessorArgs` (các thành phần của processor đa phương tiện) và `ConfigArgs` (các siêu tham số cấu hình).
3. Mô tả của từng tham số tuân theo chuỗi ưu tiên sau:
- Docstring thủ công (`r""" """` block hoặc `custom_args`) có độ ưu tiên cao hơn.
- Từ điển nguồn được định nghĩa trước (`ModelArgs`, `ModelForArgs`, `ConfigArgs`, `ImageProcessorArgs`, `ProcessorArgs`, `ModelOutputArgs`) là phương án dự phòng.
- Nếu cả hai nguồn đều không có mô tả, tham số sẽ được đánh dấu bằng `[ERROR]` trong kết quả build.
4. Đối với các lớp mô hình có tên chuẩn như `ModelForCausalLM`, hoặc các lớp được ánh xạ tới một pipeline, `@auto_docstring` sẽ tạo phần giới thiệu. Đối với các bộ xử lý đa phương thức, phần giới thiệu sẽ liệt kê các thành phần (tokenizer, image processor, v.v.) mà lớp đó bao bọc. Xem [ClassDocstring](https://github.com/huggingface/transformers/blob/main/src/transformers/utils/auto_docstring.py#L2437) để biết danh sách đầy đủ.
Nếu tên lớp không có trong `ClassDocstring`, hãy đặt `custom_intro`.
5. Docstring được định nghĩa sẵn có thể tham chiếu các giá trị động từ [auto_modules](https://github.com/huggingface/transformers/tree/main/src/transformers/models/auto) của Transformers, chẳng hạn như `{processor_class}`, `{image_processor_class}` và `{config_class}`. Các placeholder sẽ được tự động phân giải.
6. Trình trang trí (decorator) chọn các ví dụ sử dụng dựa trên tác vụ hoặc khả năng tương thích pipeline của mô hình. Nó đọc metadata checkpoint từ lớp cấu hình để các ví dụ sử dụng các ID mô hình thực. Đối số `checkpoint` ghi đè lên checkpoint được suy ra từ docstring của lớp cấu hình. Đặt `checkpoint` trên các lớp cấu hình, hoặc khi việc suy luận checkpoint thất bại. Nếu bạn thấy lỗi như `"Config not found for <model_name>"`, hãy thêm một mục vào `HARDCODED_CONFIG_FOR_MODELS` trong `auto_docstring.py`.
7. Đối với các phương thức như `forward`, decorator sẽ viết phần `Returns` từ kiểu trả về của phương thức. Khi kiểu trả về là một lớp con của [ModelOutput](/docs/transformers/main/vi/main_classes/output#transformers.utils.ModelOutput), `@auto_docstring` sẽ lấy mô tả các trường từ docstring của lớp đó. Khối `Returns` tùy chỉnh trong docstring của hàm sẽ có quyền ưu tiên cao hơn.
8. Đối với các phương thức trong `UNROLL_KWARGS_METHODS` và các lớp trong `UNROLL_KWARGS_CLASSES`, bộ trang trí sẽ mở rộng `**kwargs` được đánh kiểu bằng `Unpack[KwargsTypedDict]`. Mỗi khóa từ `TypedDict` sẽ trở thành một tham số được tài liệu hóa.
Cùng sự mở rộng này được áp dụng cho các phương thức `__call__` và `preprocess` trên các lớp con của [BaseImageProcessor](/docs/transformers/main/vi/main_classes/image_processor#transformers.BaseImageProcessor) và [ProcessorMixin](/docs/transformers/main/vi/main_classes/processors#transformers.ProcessorMixin). Các kiểu cơ sở chung (`TextKwargs`, `ImagesKwargs`, `VideosKwargs`, `AudioKwargs`) bị bỏ qua. Chỉ các lớp con cụ thể cho từng model mới được mở rộng.

Xet Storage Details

Size:
23.6 kB
·
Xet hash:
1a39263f513ffd0ce761dd63830a30cd36936b7f0ceda11cdba79398ae557312

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.