timm documentation

모델

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

모델

이 페이지에는 timm 모델 생성 및 탐색, 사전 학습된 구성 및 체크포인트 / Hub 헬퍼에 대한 API 참조 문서와 timm 모델이 공유하는 인터페이스 개요가 포함되어 있습니다. 개별 아키텍처는 모델 요약 및 모델별 페이지에서 다룹니다.

사용

모델은 create_model을(를) 통해 이름으로 생성됩니다. 이름은 timm에 등록된 아키텍처를 선택하며, . 뒤에 사전 학습 태그를 선택적으로 포함할 수 있습니다(resnet50.a1_in1k). 또는 소스 접두사를 사용하여 Hugging Face Hub의 모델이나 로컬 폴더의 모델을 지정할 수 있습니다. create_model이 자체적으로 사용하지 않는 키워드 인수는 모델의 엔트리포인트 함수를 통해 모델 클래스 생성자로 전달되므로, 모델에 특화된 인수를 모두 설정할 수 있습니다.

import torch
import timm

# Random init (pretrained=False is the default). The tag selects the pretrained cfg, and the weights loaded with
# pretrained=True. Without a tag the architecture's default tag is used.
model = timm.create_model('vit_tiny_patch16_224.augreg_in21k_ft_in1k')
print(model.pretrained_cfg['mean'], model.pretrained_cfg['crop_pct'])  # (0.5, 0.5, 0.5) 0.9

# Model arguments pass through to the model class, a 10 class head, single channel input and regularization.
model = timm.create_model('resnet50', num_classes=10, in_chans=1, drop_rate=0.2, drop_path_rate=0.05)

# Discover models, filters are fnmatch wildcards.
timm.list_models('convnext*')  # architecture names
timm.list_pretrained('resnet50.*')  # architecture.tag names w/ pretrained weights
timm.list_models(module='vision_transformer', pretrained=True)

# Image preprocessing to match the model's pretrained cfg (input size, interpolation, crop, mean / std).
model = timm.create_model('vit_tiny_patch16_224.augreg_in21k_ft_in1k')
data_config = timm.data.resolve_model_data_config(model)
transform = timm.data.create_transform(**data_config, is_training=False)

x = torch.randn(2, 3, 224, 224)
features = model.forward_features(x)  # unpooled features, (2, 197, 192)
pre_logits = model.forward_head(features, pre_logits=True)  # pooled features, (2, 192)
logits = model.forward_head(features)  # same as model(x), (2, 1000)

model.reset_classifier(5)  # replace the classifier w/ a new 5 class one
model.set_input_size(img_size=(384, 384))  # resample the position embedding for a new resolution
logits = model(torch.randn(2, 3, 384, 384))  # (2, 5)

학습 스크립트(train.py)는 이러한 플래그를 통해 일반적인 인수를 노출합니다:

  • --model은 모델을 선택합니다.
  • --pretrained는 사전 학습된 가중치를 로드합니다.
  • --num-classes는 분류기 크기(num_classes)를 설정합니다.
  • --in-chans는 입력 채널(in_chans)을 설정합니다.
  • --gp는 전역 풀링 유형(global_pool)을 설정합니다.
  • --drop은 분류기 dropout(drop_rate)을 설정합니다.
  • --drop-path는 stochastic depth(drop_path_rate)를 설정합니다.
  • --pretrained-path는 분류기/입력 컨볼루션 적응을 사용하여 로컬 파일에서 사전 학습된 가중치를 로드합니다(pretrained_cfg_overlay=dict(file=...)).
  • --initial-checkpoint는 모델 생성 후 적응 없이 체크포인트를 로드합니다(checkpoint_path).
  • --model-kwargs key=value ...는 기타 모델 인수를 전달합니다.

소개는 빠른 시작을 참고하세요.

모델 이름

이름소스
resnet50timm 레지스트리의 아키텍처, 기본 사전 학습 설정(여기서는 a1_in1k)
resnet50.a1_in1kArchitecture + pretrained 태그, 알려지지 않은 태그는 오류를 발생시킵니다
hf-hub:timm/resnet50.a1_in1kHugging Face Hub 저장소에서 아키텍처, 사전 학습된 cfg 및 모델 인수는 config.json에서 가져오며, @revision은 리비전을 선택합니다
local-dir:/path/to/foldersave_for_hf로 작성된 config.json과 가중치가 포함된 로컬 폴더

Hub 및 로컬 소스는 pretrained=False인 경우에도 config를 읽지만, 가중치는 pretrained=True인 경우에만 로드됩니다. 소스 접두사가 없으면서 /, \ 또는 :를 포함하는 이름은 동일한 이름의 레지스트리 모델로 폴백하는 대신 ValueError를 발생시킵니다. hf_hub:는 hf-hub:의 비권장 별칭입니다.

공통 인자

  • pretrained는 state_dict 또는 file이 설정된 경우 해당 위치에서, 그렇지 않은 경우 huggingface_hub가 설치되어 있으면 Hub(hf_hub_id)에서, 아니면 url에서 사전 학습된 cfg의 가중치를 로드합니다. 아래에 설명된 분류기/입력 컨볼루션 적응을 사용하면 사전 학습된 모델을 한 번의 호출로 미세 조정용으로 생성할 수 있습니다.
  • num_classes은 분류기의 크기를 설정하며, 0은 분류기를 제거합니다. 기본값은 사전 학습된 cfg에서 가져옵니다. 사전 학습된 가중치를 로드할 때, 클래스 수가 다르면 분류기 가중치가 폐기됩니다(무작위 초기화 상태로 유지됨).
  • global_pool은 풀링 유형을 설정하며, 옵션은 모델에 따라 다릅니다(예: 대부분의 convnet의 경우 avg, max, avgmax, catavgmax, ViT의 경우 token, avg, map). ''은 풀링을 비활성화합니다.
  • in_chans은 입력 채널을 설정합니다. 기본값은 사전 학습된 cfg에서 가져옵니다. 사전 학습된 가중치를 로드할 때, 이 값이 소스 체크포인트의 채널 수(input_size[0], 사전 학습된 cfg 기준)와 다르면 지원되는 경우 첫 번째 conv 가중치가 조정됩니다.
  • drop_rate은 대부분의 모델에서 지원하는 분류기 dropout을 설정합니다.
  • drop_path_rate는 대부분의 모델에서 지원하는 stochastic depth를 설정합니다.
  • img_size은 고정된 입력 크기를 가진 ViT 스타일 및 기타 모델의 인수로, 설정되지 않는 한 사전 학습된 cfg의 input_size를 기반으로 구성됩니다.
  • ViT 및 EVA 계열에서 dynamic_img_size=True는 모든 forward pass마다 위치 임베딩을 입력 크기에 맞게 다시 샘플링합니다.
  • features_only (out_indices, output_stride, feature_cls 포함)는 모델을 feature backbone으로 래핑하여 feature map을 반환합니다. feature extraction을 참조하세요.
  • pretrained_cfg는 사전 학습된 cfg(태그, dict 또는 PretrainedCfg)를 대체합니다.
  • pretrained_cfg_overlay는 일부 필드를 오버라이드하며, 예를 들어 pretrained_cfg_overlay=dict(file='weights.pth')는 pretrained=True 가중치를 로컬 파일에서 로드하고, 위의 분류기 / 입력 컨볼루션 적응을 적용합니다(train.py에서 --pretrained-path가 수행하는 것과 동일).
  • 모델이 생성된 후 checkpoint_path는 load_checkpoint를 사용하여 체크포인트를 로드합니다. 이는 적응 없이 엄격하게 로드되며, 체크포인트에 EMA 가중치가 포함된 경우 해당 가중치가 사용됩니다.
  • cache_dir은 사전 학습된 가중치와 Hub 구성 파일의 다운로드 캐시를 재정의합니다.
  • device는 모델 클래스에 전달되며, 파라미터는 해당 디바이스에서 직접 생성됩니다. device='meta'는 가중치를 위한 메모리를 할당하지 않고 모델을 생성합니다.
  • dtype는 모델 클래스에 전달되며, 파라미터는 해당 dtype로 직접 생성됩니다.
  • scriptable는 TorchScript 스크립팅을 위한 레이어 구성 플래그를 설정합니다.
  • exportable는 export/tracing을 위한 레이어 설정 플래그를 설정합니다.
  • no_jit은 jit 스크립트된 레이어를 비활성화하도록 레이어 구성 플래그를 설정합니다.

None으로 설정된 인수는 모델에 도달하기 전에 제거되므로 모델의 기본값이 적용됩니다. 모델 클래스가 지원하지 않는 인수를 전달하면 대부분의 모델에서 TypeError가 발생하며, 일부 모델은 알 수 없는 인수를 무시합니다.

사전 학습된 구성

Architectures에는 모델에 등록되는 태그별 하나 이상의 사전 학습된 cfg가 있습니다. cfg는 가중치(위치, 라이선스, 출처)와 모델이 어떻게 학습되었는지, 그리고 해당 가중치로 어떻게 평가해야 하는지를 설명합니다. create_model으로 생성된 모델의 cfg는 model.pretrained_cfg에 dict로 저장되어 있으며(model.default_cfg는 별칭입니다), 레지스트리 버전은 get_pretrained_cfg에 의해 PretrainedCfg 인스턴스로 반환됩니다.

필드설명
architecture, tag모델 아키텍처 및 사전 학습 태그
hf_hub_id, url, file, state_dict가중치 소스(위 pretrained 참조)
input_size, test_input_size, fixed_input_sizeTrain(및 기본 eval) 입력 크기, use_test_size=True 사용 시 eval 크기(다른 경우), 모델이 고정된 입력 크기(img_size 인자)를 가지는지 여부
interpolation, crop_pct, test_crop_pct, crop_modeEval 리사이즈 보간, 크롭 비율(기본 center 크롭 모드에서는 이미지가 input_size / crop_pct로 리사이즈된 후 중앙 크롭됩니다) 및 크롭 모드
mean, std입력 정규화
num_classes, label_names, label_descriptionsClassifier의 크기와 라벨(알려진 경우)
classifier, first_conv가중치를 로드할 때 적응하기 위해 사용되는 분류기와 첫 번째 conv의 모듈 이름
license, origin_url, paper_ids, paper_name, notes가중치 메타데이터

입력 필드는 resolve_data_config / resolve_model_data_config가 데이터셋의 transforms와 loader에 대해 데이터 config로 해석하는 대상입니다. cfg는 소스 체크포인트를 설명하며, 모델이 생성되거나 다르게 수정될 때(num_classes, in_chans, img_size, set_input_size()) 업데이트되지 않습니다. 모델의 현재 입력 채널, 크기 및 고정 크기 제약은 별도로 추적됩니다: get_model_input_config가 이를 반환하고, resolve_input_data_config가 이를 기준으로 데이터 config를 해석합니다(학습, 검증 및 추론 스크립트가 수행하는 방식과 동일). get_model_args는 현재 모델 상태를 재구성하기 위한 인수를 반환하며, save_for_hf가 이를 내보낸 config에 기록합니다. 자세한 내용은 모델 적응 및 내보내기를 참조하세요.

모델 인터페이스

timm 모델은 forward() 외에도 공통 인터페이스를 공유합니다. 여기에는 forward_features() / forward_head() 분리, 분류기 초기화, 중간 특징, 입력 크기 조정, 그리고 그래디언트 체크포인트링 및 매개변수 그룹화와 같은 학습 훅이 포함됩니다. 이는 timm Model API에 설명되어 있으며, 어떤 모델 계열이 어떤 부분을 지원하는지도 포함되어 있습니다.

체크포인트와 허브

  • load_checkpoint는 체크포인트 파일(PyTorch 또는 .safetensors)을 모델에 로드합니다.
  • load_state_dict는 체크포인트 파일을 읽고 해당 상태 딕셔너리를 반환합니다.
  • resume_checkpoint은 train.py 체크포인트의 모델, 옵티마이저 및 손스케일러 상태를 복원하고, 재개할 에포크를 반환합니다.

load_checkpoint와 load_state_dict는 기본적으로 train.py 체크포인트의 EMA 가중치를 선택합니다(use_ema). 또한 module.(DDP) 및 _orig_mod.(torch.compile) 키 접두사를 제거합니다.

  • save_for_hf는 가중치와 config.json(아키텍처, 사전 학습 cfg, model_args, label_names)을 폴더에 작성합니다.
  • push_to_hf_hub는 저장소에 모델 카드가 없는 경우 생성된 모델 카드와 함께 가중치 및 구성을 Hub 저장소에 업로드합니다.

모델은 hf-hub: 또는 local-dir:를 사용하여 생성되며, 모델 공유 및 로드를 참조하세요.

import timm
from timm.models import save_for_hf

model = timm.create_model('resnet18', num_classes=4)
# ... fine-tune
save_for_hf(model, 'my_resnet18', model_config=dict(label_names=['a', 'b', 'c', 'd']), safe_serialization=True)
model = timm.create_model('local-dir:my_resnet18', pretrained=True)  # 4 classes, weights and labels restored
print(model.pretrained_cfg['label_names'])

커스텀 모델

register_model으로 장식된 모델 엔트리포인트 함수가 레지스트리에 추가되므로, create_model로 생성하고 list_models로 찾을 수 있습니다. timm의 엔트리포인트는 build_model_with_cfg를 사용하여 모델을 빌드하며, 이 함수는 사전 학습된 cfg, 사전 학습된 가중치 로딩 및 features_only를 처리합니다.

API

모델 생성

timm.create_model

< >

( model_name: strpretrained: bool = Falsepretrained_cfg: typing.Union[str, typing.Dict[str, typing.Any], timm.models._pretrained.PretrainedCfg, NoneType] = Nonepretrained_cfg_overlay: typing.Optional[typing.Dict[str, typing.Any]] = Nonecheckpoint_path: typing.Union[str, pathlib.Path, NoneType] = Nonecache_dir: typing.Union[str, pathlib.Path, NoneType] = Nonescriptable: typing.Optional[bool] = Noneexportable: typing.Optional[bool] = Noneno_jit: typing.Optional[bool] = None**kwargs: typing.Any )

매개변수

  • model_name — 인스턴스화할 모델의 이름.
  • pretrained — True로 설정하면 사전 학습된 ImageNet-1k 가중치를 로드합니다.
  • pretrained_cfg — 모델에 외부 pretrained_cfg를 전달합니다.
  • pretrained_cfg_overlay — 기본 pretrained_cfg의 키-값을 이 값으로 대체합니다.
  • checkpoint_path — 모델이 초기화된 이후 로드할 체크포인트의 경로
  • cache_dir — Hugging Face Hub 및 Torch 체크포인트의 모델 캐시 디렉터리를 재정의합니다.
  • scriptable — 모델이 jit scriptable하도록 레이어 구성을 설정합니다 (아직 모든 모델에서 작동하지 않음).
  • exportable — 모델이 traceable / ONNX exportable하도록 레이어 구성을 설정합니다 (아직 완전히 구현/준수되지 않음).
  • no_jit — 모델이 jit 스크립트된 레이어를 사용하지 않도록 레이어 구성을 설정합니다(현재까지 활성화 함수만 해당).

모델을 생성합니다.

모델의 entrypoint 함수를 조회하고 관련 인수를 전달하여 새 모델을 생성합니다.

Tip: **kwargs는 entrypoint fn을 통해 timm.models.build_model_with_cfg()로 전달된 후 모델 클래스의 init()로 전달됩니다. None으로 설정된 kwargs 값은 전달 전에 제거됩니다.

Keyword Args: drop_rate (float): 학습을 위한 Classifier dropout rate. drop_path_rate (float): 학습을 위한 Stochastic depth drop rate. global_pool (str): Classifier global pooling type.

예:

>>> from timm import create_model

>>> # Create a MobileNetV3-Large model with no pretrained weights.
>>> model = create_model('mobilenetv3_large_100')

>>> # Create a MobileNetV3-Large model with pretrained weights.
>>> model = create_model('mobilenetv3_large_100', pretrained=True)
>>> model.num_classes
1000

>>> # Create a MobileNetV3-Large model with pretrained weights and a new head with 10 classes.
>>> model = create_model('mobilenetv3_large_100', pretrained=True, num_classes=10)
>>> model.num_classes
10

>>> # Create a Dinov2 small model with pretrained weights and save weights in a custom directory.
>>> model = create_model('vit_small_patch14_dinov2.lvd142m', pretrained=True, cache_dir="/data/my-models")
>>> # Data will be stored at */data/my-models/models--timm--vit_small_patch14_dinov2.lvd142m/*

모델 탐색

timm.list_models

< >

( filter: typing.Union[str, typing.Iterable[str]] = ''module: typing.Union[str, typing.Iterable[str]] = ''pretrained: bool = Falseexclude_filters: typing.Union[str, typing.Iterable[str]] = ''name_matches_cfg: bool = Falseinclude_tags: typing.Optional[bool] = None )

매개변수

  • filter — fnmatch와 함께 작동하는 와일드카드 필터입니다.
  • module — 모델 선택을 특정 서브모듈(예: ‘vision_transformer’)로 제한합니다.
  • pretrained — True인 경우, 유효한 사전학습 가중치를 가진 모델만 포함합니다.
  • exclude_filters — filter로 모델을 포함시킨 후 제외할 와일드카드 필터입니다.
  • name_matches_cfg — Include only models w/ model_name matching default_cfg name (excludes some aliases).
  • include_tags — 모델 이름에 사전 학습 태그(model.tag)를 포함합니다. None인 경우 pretrained의 값으로 설정됩니다.

자연 순서대로 정렬된 사용 가능한 모델 이름 목록을 반환합니다.

예: list_models(‘gluon_resnet’) — ‘gluon_resnet’로 시작하는 모든 모델을 반환합니다 list_models(’resnext*’, ‘resnet’) — ‘resnet’ 모듈에 ‘resnext’가 포함된 모든 모델을 반환합니다

timm.list_pretrained

< >

( filter: typing.Union[str, typing.Iterable[str]] = ''exclude_filters: typing.Union[str, typing.Iterable[str]] = '' )

매개변수

  • filter — fnmatch와 함께 작동하는 와일드카드 필터입니다.
  • exclude_filters — filter로 모델을 포함시킨 후 제외할 와일드카드 필터입니다.

태그가 포함된 사전 학습 모델 이름 목록을 자연스러운 순서로 정렬하여 반환합니다.

timm.list_modules

< >

( )

모델 엔트리포인트를 포함하는 모듈 이름의 정렬된 목록을 반환합니다.

timm.is_model

< >

( model_name: str )

pretrained 태그를 무시하고 모델 아키텍처가 등록되어 있는지 확인합니다.

timm.is_model_pretrained

< >

( model_name: str )

모델 이름(태그 포함 또는 미포함)에 사전 학습된 가중치가 등록되어 있는지 확인합니다.

timm.model_entrypoint

< >

( model_name: strmodule_filter: typing.Optional[str] = None )

매개변수

  • model_name — 사전 학습 태그가 있거나 없는 모델 이름
  • module_filter — 설정된 경우, 모델이 해당 서브모듈에 없으면 예외를 발생시킵니다.

pretrained 태그를 무시하고 모델 이름에 해당하는 모델 엔트리포인트 함수를 가져옵니다.

사전 학습된 구성

timm.get_pretrained_cfg

< >

( model_name: strallow_unregistered: bool = True )

매개변수

  • model_name — 사전 학습 태그가 있거나 없는 모델 이름
  • allow_unregistered — 아키텍처에 사전 학습된 cfgs가 없는 경우 예외를 발생시키지 않고 None을 반환합니다.

Raises

RuntimeError

  • RuntimeError — 태그가 아키텍처에 대해 유효하지 않거나, cfgs가 없고 allow_unregistered가 False인 경우.

모델 이름에 대해 사전 학습된 cfg의 사본을 가져옵니다. 태그가 지정되지 않은 경우 기본 태그가 사용됩니다.

timm.get_pretrained_cfg_value

< >

( model_name: strcfg_key: str )

Raises

RuntimeError

  • RuntimeError — 모델에 사전 학습된 cfg가 등록되어 있지 않거나 태그가 잘못된 경우.

모델 이름에 대해 특정 사전 학습된 cfg 값을 키로 가져오며, 해당 키가 존재하지 않으면 None을 반환합니다.

timm.models.get_arch_pretrained_cfgs

< >

( model_name: str )

매개변수

  • model_name — 모델 이름. 사전 학습 태그는 무시됩니다.

모델 아키텍처의 모든 사전 학습된 cfg 사본을 가져옵니다.

class timm.models.PretrainedCfg

< >

( url: typing.Union[str, typing.Tuple[str, str], NoneType] = Nonefile: typing.Optional[str] = Nonestate_dict: typing.Optional[typing.Dict[str, typing.Any]] = Nonehf_hub_id: typing.Optional[str] = Nonehf_hub_filename: typing.Optional[str] = Nonesource: typing.Optional[str] = Nonearchitecture: typing.Optional[str] = Nonetag: typing.Optional[str] = Nonecustom_load: bool = Falseinput_size: typing.Tuple[int, int, int] = (3, 224, 224)test_input_size: typing.Optional[typing.Tuple[int, int, int]] = Nonemin_input_size: typing.Optional[typing.Tuple[int, int, int]] = Nonefixed_input_size: bool = Falseinterpolation: str = 'bicubic'crop_pct: float = 0.875test_crop_pct: typing.Optional[float] = Nonecrop_mode: str = 'center'mean: typing.Tuple[float, ...] = (0.485, 0.456, 0.406)std: typing.Tuple[float, ...] = (0.229, 0.224, 0.225)num_classes: int = 1000label_offset: typing.Optional[int] = Nonelabel_names: typing.Optional[typing.Tuple[str]] = Nonelabel_descriptions: typing.Optional[typing.Dict[str, str]] = Nonepool_size: typing.Optional[typing.Tuple[int, ...]] = Nonetest_pool_size: typing.Optional[typing.Tuple[int, ...]] = Nonefirst_conv: typing.Optional[str] = Noneclassifier: typing.Optional[str] = Nonelicense: typing.Optional[str] = Nonedescription: typing.Optional[str] = Noneorigin_url: typing.Optional[str] = Nonepaper_name: typing.Optional[str] = Nonepaper_ids: typing.Union[str, typing.Tuple[str], NoneType] = Nonenotes: typing.Optional[typing.Tuple[str]] = None )

현재 모델 입력 및 내보내기

timm.models.get_model_input_config

< >

( model: Module )

현재 이미지 채널, 명목상 크기, 고정 크기 제약을 반환합니다.

명목 크기는 유연한 모델에 대한 권장 사항입니다. 소스 체크포인트 메타데이터는 model.pretrained_cfg에 그대로 유지되며 여기서는 절대 수정되지 않습니다.

timm.models.get_model_traits

< >

( model: Module )

현재 채널 및 클래스 수로 보완된 모델의 특성(trait) 사본을 반환합니다.

기존의 in_chans 및 num_classes 속성이 여전히 기준이 됩니다. 이 속성은 저장된 traits에 중복되지 않도록 여기에서 읽힙니다. feature wrapper에 없는 속성은 생략됩니다.

timm.models.get_model_args

< >

( model: Moduleoverrides: typing.Optional[typing.Dict[str, typing.Any]] = None )

생성 이후에 적용된 지원되는 변경 사항을 포함하여 재구성 인수를 반환합니다.

Runtime arguments는 팩토리에 의해 제외됩니다. Drop rates는 overrides에 명시적으로 제공되지 않는 한 생략됩니다. 직렬화할 수 없는 아키텍처 arguments는 내보내기 시 명시적으로 직렬화 가능한 대체 항목이 필요합니다.

timm.models.resolve_model_input_args

< >

( model_name: strargs: typing.Optional[typing.Dict[str, typing.Any]] = None**model_kwargs )

create_model의 인수로 스크립트 입력 요청을 해석합니다.

저장된 모델 인수는 기본값입니다. 명시적인 채널/크기 요청은 소스 체크포인트를 설명하는 메타데이터를 덮어쓰지 않고 대상만 선택합니다.

timm.models.adapt_input_conv

< >

( in_chans: intconv_weight: Tensorbase_chans: int = 3 )

매개변수

  • in_chans — 대상 모델의 입력 채널 수.
  • conv_weight — OIHW 레이아웃의 사전 학습된 Conv2d 가중치.
  • base_chans — 사전 학습에 사용되는 물리적 입력 채널의 수입니다. space-to-depth 스템의 경우 가중치의 입력 차원과 다를 수 있습니다.

Raises

ValueError 또는 NotImplementedError

  • ValueError — 채널 수가 양수가 아닌 경우.
  • NotImplementedError — 가중치 형식을 적응할 수 없는 경우.

Adapt pretrained input convolution weights to a different channel count.

체크포인트와 허브

timm.models.load_checkpoint

< >

( model: Modulecheckpoint_path: struse_ema: bool = Truedevice: typing.Union[str, torch.device] = 'cpu'strict: bool = Trueremap: bool = Falsefilter_fn: typing.Optional[typing.Callable] = Noneweights_only: bool = True )

매개변수

  • model — 체크포인트를 로드할 모델.
  • checkpoint_path — 체크포인트 파일 경로.
  • use_ema — 사용 가능한 경우 EMA 가중치를 사용할지 여부.
  • device — 체크포인트를 로드할 장치.
  • strict — state_dict 키가 정확히 일치하는지 엄격하게 강제할지 여부
  • remap — 상태 딕트 키를 순서대로 재매핑할지 여부.
  • filter_fn — state dict를 필터링할 선택적 함수.
  • weights_only — 가중치만 로드할지 여부 (torch.load 파라미터).

모델에 체크포인트를 로드합니다.

.npz/.npy` checkpoints are foreign, model-specific formats and are delegated to the model's `load_pretrained helper.

timm.models.load_state_dict

< >

( checkpoint_path: struse_ema: bool = Truedevice: typing.Union[str, torch.device] = 'cpu'weights_only: bool = True )

매개변수

  • checkpoint_path — 체크포인트 파일 경로.
  • use_ema — 사용 가능한 경우 EMA 가중치를 사용할지 여부.
  • device — 체크포인트를 로드할 장치.
  • weights_only — 가중치만 로드할지 여부 (torch.load 파라미터).

checkpoint 파일에서 상태 사전(state dictionary)을 로드합니다.

timm.models.resume_checkpoint

< >

( model: Modulecheckpoint_path: stroptimizer: typing.Optional[torch.optim.Optimizer] = Noneloss_scaler: typing.Optional[typing.Any] = Nonelog_info: bool = Trueweights_only: bool = True )

매개변수

  • model — 체크포인트를 로드할 모델.
  • checkpoint_path — 체크포인트 파일 경로.
  • optimizer — 상태를 복원할 선택적 옵티마이저.
  • loss_scaler — 상태를 복원하기 위한 선택적 AMP loss scaler입니다.
  • log_info — 로딩 정보를 기록할지 여부.
  • weights_only — torch.load를 통해 가중치만 로드할지 여부.

checkpoint에서 학습을 재개합니다.

timm.models.save_for_hf

< >

( model: Modulesave_directory: strmodel_config: typing.Optional[dict] = Nonemodel_args: typing.Optional[dict] = Nonesafe_serialization: typing.Union[bool, typing.Literal['both']] = Falsedata_config: typing.Optional[dict] = None )

네이티브 가중치와 현재 모델 및 전처리 구성을 저장합니다.

timm.models.push_to_hf_hub

< >

( model: Modulerepo_id: strcommit_message: str = 'Add model'token: typing.Optional[str] = Nonerevision: typing.Optional[str] = Noneprivate: bool = Falsecreate_pr: bool = Falsemodel_config: typing.Optional[dict] = Nonemodel_card: typing.Optional[dict] = Nonemodel_args: typing.Optional[dict] = Nonetask_name: str = 'image-classification'safe_serialization: typing.Union[bool, typing.Literal['both']] = 'both'data_config: typing.Optional[dict] = None )

매개변수

  • (…) —
  • model_args — 팩토리가 기록한 인수를 보완하는 명시적인 재구성 인수입니다.
  • data_config — 내보낸 체크포인트와 함께 사용되는 전처리, 입력 크기 및 정규화를 포함합니다.
  • safe_serialization (bool 또는 "both", 선택 사항, 기본값 False) — safetensors를 사용하여 모델을 저장할지, 아니면 전통적인 PyTorch 방식(pickle 사용)을 사용할지 여부를 지정합니다. "both"로 설정하면 안전하고 안전한 두 가지 가중치를 모두 push할 수 있습니다.

커스텀 모델

timm.models.register_model

< >

( fn: typing.Callable[..., typing.Any] )

매개변수

  • fn — name 아래에 등록된 모델 엔트리포인트 fn입니다.

모델 엔트리포인트 fn과 해당 모듈의 default_cfgs에 있는 사전 학습된 cfgs를 등록하는 데코레이터입니다.

이미 존재하는 이름을 등록하면 이전 등록 정보와 사전 학습된 cfgs가 덮어쓰기됩니다.

timm.models.build_model_with_cfg

< >

( model_cls: typing.Union[typing.Type[~ModelT], typing.Callable[..., ~ModelT]]variant: strpretrained: boolpretrained_cfg: typing.Optional[typing.Dict] = Nonepretrained_cfg_overlay: typing.Optional[typing.Dict] = Nonemodel_cfg: typing.Optional[typing.Any] = Nonefeature_cfg: typing.Optional[typing.Dict] = Nonepretrained_strict: bool = Truepretrained_filter_fn: typing.Optional[typing.Callable] = Nonecache_dir: typing.Union[str, pathlib.Path, NoneType] = Nonekwargs_filter: typing.Optional[typing.Tuple[str]] = Nonepretrained_model_args: typing.Optional[typing.Dict] = None**kwargs )

매개변수

  • model_cls — 모델 클래스
  • variant — 모델 변형 이름
  • pretrained — 사전 학습된 가중치를 로드합니다
  • pretrained_cfg — 모델의 사전 학습된 가중치/작업 설정
  • pretrained_cfg_overlay — pretrained_cfg의 항목을 덮어쓸 항목
  • model_cfg — 모델의 아키텍처 설정
  • feature_cfg — Feature 추출 어댑터 설정
  • pretrained_strict — 사전 학습된 가중치를 엄격하게 로드
  • pretrained_filter_fn — 사전 학습된 가중치를 위한 필터 콜러블
  • cache_dir — Hugging Face Hub 및 Torch 체크포인트의 모델 캐시 디렉터리를 재정의합니다
  • kwargs_filter — 모델에 전달하기 전에 필터링(제거)할 Kwargs 키
  • pretrained_model_args — 소스 체크포인트를 설명하는 재구성 인자
  • **kwargs — 모델 init에 전달되는 모델 인자

지정된 default_cfg와 선택적 model_cfg를 사용하여 모델을 빌드합니다

이 헬퍼 함수는 다음을 포함하여 모델 구성을 지원합니다:

  • 기본 설정(default_cfg) 및 관련 사전 학습된 가중치 로딩 처리
  • config 기반 아키텍처 사양을 가진 모델에 대해 선택적 model_cfg를 전달
  • features_only 모델 적응
  • pruning config / model adaptation
Update on GitHub