Docstring 자동 생성하기
Docstring 자동 생성하기 (Auto-generating docstrings)
@auto_docstring 데코레이터는 모델 클래스와 메서드에 일관된 docstring을 생성해줘요. 표준 인자 설명을 자동으로 가져오기 때문에, 여러분은 새로 추가한 인자나 커스텀 인자에 대한 문서만 작성하면 돼요. 새 모델을 추가할 때 boilerplate는 건너뛰고 새로운 부분에만 집중할 수 있지요.
출처: 문서
본문
@auto_docstring
modular_model.py 파일(오래된 모델이라면 modeling_model.py)에서 데코레이터를 import 해요.
from ...utils import auto_docstring
모델이 modular 파일에서 다른 라이브러리 모델을 상속받는다면 @auto_docstring은 이미 부모에 적용되어 있어요. make fix-repo가 이를 생성된 modeling_model.py 파일로 복사해 줘요. 데코레이터는 그 동작을 커스터마이즈할 때만 명시적으로 적용하면 돼요(독립형 모델, 커스텀 intro, 오버라이드된 인자 등).
[!WARNING] modular 파일에서 데코레이터를 오버라이드할 때는 부모 함수나 클래스의 모든 데코레이터를 포함해야 해요. 일부만 오버라이드하면 나머지는 생성된 modeling 파일에 나타나지 않아요.
데코레이터는 다음의 선택적 인자를 받아요:
| 인자 | 설명 |
|---|---|
custom_intro |
Args 섹션 앞에 삽입되는 클래스나 메서드의 설명. ForCausalLM이나 ForTokenClassification 같은 인식되는 접미사로 끝나지 않는 클래스에는 필수예요. |
custom_args |
특정 파라미터에 대한 docstring 텍스트. 같은 커스텀 인자가 modeling 파일의 여러 곳에 나타날 때 유용해요. |
checkpoint |
사용 예시 생성에 사용되는 모델 checkpoint 식별자("org/my-model"). config 클래스에서 자동 추론된 checkpoint를 오버라이드해요. 보통 config 클래스에 설정해요. |
사용법 (Usage)
@auto_docstring이 어떻게 동작하는지는 무엇을 데코레이트하느냐에 따라 달라요. 모델 클래스는 __init__에서 파라미터 문서를 가져오고, config 클래스는 클래스 레벨 어노테이션에서 가져오며, processor 클래스는 컴포넌트에서 intro를 자동 생성하고, forward 같은 메서드는 반환 타입과 사용 예시를 얻어요.
모델 클래스 (Model classes)
클래스 정의 바로 위에 @auto_docstring을 배치해요. 데코레이터는 __init__ 메서드의 시그니처와 docstring에서 파라미터 설명을 유도해요.
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):
# ...
ModelOutput을 상속받는 클래스에도 @auto_docstring을 적용해요.
@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
Config 클래스 (Config classes)
PreTrainedConfig 서브클래스 바로 위에 @strict 데코레이터와 함께 @auto_docstring을 배치해요. @strict는 런타임 타입 검증을 추가하고 클래스를 검증된 dataclass로 만들어요. Config 파라미터는 클래스 레벨 어노테이션입니다(__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"
Processor 클래스 (Processor classes)
멀티모달 processor(ProcessorMixin 서브클래스, processing_*.py)는 항상 있는 그대로의(bare) @auto_docstring을 사용해요. 클래스 intro는 자동 생성돼요. ProcessorArgs(image_processor, tokenizer, chat_template 등)에 이미 포함되지 않은 __init__ 파라미터만 문서화해요.
모든 파라미터가 표준이면 docstring을 생략해요. __call__도 @auto_docstring으로 데코레이트해요. 그 본문 docstring에는 Returns: 섹션과 추가 모델별 호출 인자만 담아요. 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/v5.17.0/en/main_classes/image_processor#transformers.BatchFeature): A [BatchFeature](/docs/transformers/v5.17.0/en/main_classes/image_processor#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.
"""
# ...
이미지/비디오 processor (Image and video processors)
이미지·비디오 processor(BaseImageProcessor 서브클래스, image_processing_*.py)는 두 패턴 중 하나를 따라요.
processor에 모델별 파라미터가 있다면, 그 파라미터에 대한 docstring을 가진 XxxImageProcessorKwargs(ImagesKwargs, total=False) TypedDict를 정의하고, 클래스에 valid_kwargs를 설정하며, 있는 그대로의 @auto_docstring을 사용해요. __init__에는 docstring이 없어요.
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)
클래스가 커스텀 kwargs 없이 표준 클래스 레벨 속성(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는 자동으로 포함돼요.
함수 (Functions)
함수 정의 바로 위에 @auto_docstring을 배치해요. 데코레이터는 함수 시그니처에서 파라미터 설명을 유도해요.
데코레이터는 ModelOutput 클래스 docstring에서 반환값 텍스트를 생성해요.
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)
```
"""
# ...
인자 문서화하기 (Documenting arguments)
서로 다른 인자 타입을 문서화할 때는 다음 규칙을 따라요.
-
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""" """블록에서 문서화해요. 함수는 시그니처 뒤에, 모델·processor 클래스는__init__docstring에, config 클래스는 클래스 본문 docstring에, 이미지 processor는XxxImageProcessorKwargsTypedDict 본문에 배치해요.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 toNone"을 추가할 필요는 없어요. - 같은 인자가 여러 메서드에 반복되면 같은 블록을
custom_args에 전달해요(위의 Functions 예시 참고).
-
데코레이터는 함수 시그니처에서 타입을 자동으로 추출해요. 파라미터에 타입 어노테이션이 있으면 docstring 형식 문자열에 타입을 반복할 필요가 없어요. 둘 다 있으면 시그니처 타입이 우선해요. docstring 타입은 어노테이션 없는 파라미터의 폴백 역할을 해요.
Docstring 확인하기 (Checking the docstrings)
유틸리티 스크립트가 pull request를 열 때 docstring을 검증해요. CI가 스크립트를 실행하고 다음을 확인해요.
[!TIP] 출력에서
[ERROR]가 보이면 파라미터 설명을 docstring이나auto_docstring.py의 적절한 Args 클래스에 추가해 주세요.
- 관련 모델 클래스와 공개 메서드에
@auto_docstring이 적용되었는지 확인해요. - 인자 완전성과 일관성을 검증해요: 문서화된 인자가 시그니처에 존재해야 하고, 타입과 기본값이 일치해야 해요. 로컬 설명이 없는 알 수 없는 인자는 플래그 처리돼요.
<fill_type>과<fill_docstring>같은 불완전한 placeholder를 플래그 처리해요.- 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
빠른 참조 체크리스트 (Quick-reference checklist)
| Do | Don't |
|---|---|
모델, config, processor 클래스와 그 주요 메서드(forward, __call__, preprocess)에 @auto_docstring을 적용해요. |
modular 파일의 상속 모델에 @auto_docstring을 추가하지 마세요. 자동으로 이어지기 때문이에요. |
| 새 인자나 모델별 인자만 문서화해요. | 기본 설명과 동일하게 동작하는 표준 인자(input_ids, attention_mask, vocab_size 등)를 재정의하지 마세요. |
| config 파라미터는 클래스 본문 docstring에 클래스 레벨 어노테이션으로 넣어요. | config 파라미터를 __init__에 넣지 마세요. |
이미지 processor 파라미터는 XxxImageProcessorKwargs TypedDict에 넣어요. |
이미지 processor 파라미터를 __init__에 넣지 마세요. |
커밋 전에 python utils/check_docstrings.py --fix_and_overwrite를 실행해요. |
[ERROR] 출력을 무시하지 마세요. 파라미터가 문서화되지 않았다는 뜻이니까요. |
동작 원리 (How it works)
@auto_docstring 데코레이터는 다음 단계로 docstring을 생성해요.
-
데코레이터는 시그니처를 검사해서 데코레이트된 클래스의
__init__이나 함수에서 인자, 타입, 기본값을 읽어요. config 클래스의 경우 상속 체인을 따라 클래스 레벨 어노테이션을 탐색하고 PreTrainedConfig 앞에서 멈추며, 기본 클래스 필드를 제외해요.self,kwargs,args,deprecated_arguments,_접두사 이름 같은 파라미터는 자동으로 걸러져요. 몇몇 private 파라미터는 공개 동등물로 이름이 바뀌어요(백본 모델의_out_features→out_features). -
공통 인자 설명은
auto_docstring.py에서 와요:ModelArgs(모델 입력),ModelOutputArgs(출력 필드, 예:hidden_states),ImageProcessorArgs(이미지 전처리),ProcessorArgs(멀티모달 processor 컴포넌트),ConfigArgs(config 하이퍼파라미터)가 있어요. -
각 파라미터의 설명은 다음 우선순위 체인을 따라요:
- 수동 docstring(
r""" """블록 또는custom_args)이 우선해요. - 미리 정의된 source dict(
ModelArgs,ConfigArgs,ImageProcessorArgs,ProcessorArgs,ModelOutputArgs)가 폴백이에요. - 두 소스 모두에 설명이 없으면 파라미터는 빌드 출력에
[ERROR]로 플래그 처리돼요.
- 수동 docstring(
-
ModelForCausalLM같은 표준 이름의 모델 클래스나 pipeline에 매핑되는 클래스의 경우@auto_docstring이 intro를 생성해요. 멀티모달 processor의 경우 intro가 클래스가 감싸는 컴포넌트(tokenizer, image processor 등)를 나열해요. 전체 목록은 ClassDocstring을 참고해 주세요.클래스 이름이
ClassDocstring에 없으면custom_intro를 설정해요. -
사전 정의된 docstring은 Transformers의 auto_modules의 동적 값, 예를 들어
{processor_class},{image_processor_class},{config_class}를 참조할 수 있어요. placeholder는 자동으로 해석돼요. -
데코레이터는 모델의 태스크나 pipeline 호환성에 따라 사용 예시를 선택해요. config 클래스에서 checkpoint 메타데이터를 읽어 예시가 실제 모델 ID를 사용하게 해요.
checkpoint인자는 config 클래스 docstring에서 추론된 checkpoint를 오버라이드해요. config 클래스에checkpoint를 설정하거나 checkpoint 추론이 실패할 때 설정해요."Config not found for <model_name>"같은 오류가 보이면auto_docstring.py의HARDCODED_CONFIG_FOR_MODELS에 항목을 추가해요. -
forward같은 메서드의 경우 데코레이터는 메서드 반환 타입에서Returns섹션을 작성해요. 반환 타입이 ModelOutput 서브클래스이면@auto_docstring은 그 클래스 docstring에서 필드 설명을 가져와요. 함수 docstring의 커스텀Returns블록이 우선해요. -
UNROLL_KWARGS_METHODS의 메서드와UNROLL_KWARGS_CLASSES의 클래스에 대해 데코레이터는Unpack[KwargsTypedDict]로 타입된**kwargs를 펼쳐요.TypedDict의 각 키가 문서화된 파라미터가 돼요.같은 확장이 BaseImageProcessor와 ProcessorMixin 서브클래스의
__call__과preprocess메서드에도 적용돼요. 일반 기본 타입(TextKwargs,ImagesKwargs,VideosKwargs,AudioKwargs)은 건너뛰어요. 모델별 서브클래스만 펼쳐져요.