Hugging Face에서 timm 사용하기
Hugging Face에서 timm 사용하기
timm은 pytorch-image-models로도 알려져 있으며, 최신(state-of-the-art) PyTorch 이미지 모델, 사전 학습 가중치, 그리고 학습·추론·검증용 유틸리티 스크립트의 오픈소스 모음이에요.
출처: 문서
본문
이 문서는 timm 라이브러리 자체가 아니라 Hugging Face 허브에서의 timm 기능에 초점을 맞춰요. timm 라이브러리에 대한 자세한 정보는 그 문서를 참고하세요.
모델 페이지 왼쪽의 필터를 사용하면 허브에서 많은 timm 모델을 찾을 수 있어요.
허브의 모든 모델에는 여러 유용한 기능이 함께 제공됩니다:
- 모델 작성자가 모델 정보로 채울 수 있는 자동 생성 모델 카드
- 사용자가 관련
timm모델을 찾도록 돕는 메타데이터 태그 - 브라우저에서 직접 모델을 시험해 볼 수 있는 인터랙티브 위젯
- 사용자가 추론 요청을 보낼 수 있게 하는 Inference Providers
허브의 기존 모델 사용하기
timm이 설치되어 있으면 Hugging Face 허브의 어떤 timm 모델도 한 줄의 코드로 로드할 수 있어요! 허브에서 모델을 선택한 뒤, hf-hub: 접두사가 붙은 모델 ID를 timm의 create_model 메서드에 전달하면 모델을 다운로드하고 인스턴스화할 수 있어요.
import timm
# Loading https://huggingface.co/timm/eca_nfnet_l0
model = timm.create_model("hf-hub:timm/eca_nfnet_l0", pretrained=True)
특정 모델 로드 방법을 보고 싶다면 Use in timm을 클릭하면 로드할 수 있는 동작하는 스니펫을 얻을 수 있어요!
추론 (Inference)
아래 스니펫은 허브에서 로드한 timm 모델로 추론을 수행하는 방법을 보여줘요:
import timm
import torch
from PIL import Image
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
# Load from Hub 🔥
model = timm.create_model(
'hf-hub:nateraw/resnet50-oxford-iiit-pet',
pretrained=True
)
# Set model to eval mode for inference
model.eval()
# Create Transform
transform = create_transform(**resolve_data_config(model.pretrained_cfg, model=model))
# Get the labels from the model config
labels = model.pretrained_cfg['label_names']
top_k = min(len(labels), 5)
# Use your own image file here...
image = Image.open('boxer.jpg').convert('RGB')
# Process PIL image with transforms and add a batch dimension
x = transform(image).unsqueeze(0)
# Pass inputs to model forward function to get outputs
out = model(x)
# Apply softmax to get predicted probabilities for each class
probabilities = torch.nn.functional.softmax(out[0], dim=0)
# Grab the values and indices of top 5 predicted classes
values, indices = torch.topk(probabilities, top_k)
# Prepare a nice dict of top k predictions
predictions = [
{"label": labels[i], "score": v.item()}
for i, v in zip(indices, values)
]
print(predictions)
이 코드는 아래와 같은 예측 목록을 반환합니다:
[
{'label': 'american_pit_bull_terrier', 'score': 0.9999998807907104},
{'label': 'staffordshire_bull_terrier', 'score': 1.0000000149011612e-07},
{'label': 'miniature_pinscher', 'score': 1.0000000149011612e-07},
{'label': 'chihuahua', 'score': 1.0000000149011612e-07},
{'label': 'beagle', 'score': 1.0000000149011612e-07}
]
모델 공유하기
timm 모델을 Hugging Face 허브로 직접 공유할 수 있어요. 이렇게 하면 모델의 새 버전이 허브에 게시되고, 없다면 모델 저장소도 자동으로 만들어줘요.
모델을 푸시하기 전에 Hugging Face에 로그인되어 있는지 확인하세요:
python -m pip install huggingface_hub
hf auth login
또는 Jupyter/Colaboratory 노트북에서 작업하는 걸 선호한다면, huggingface_hub을 설치한 후 다음으로 로그인할 수 있어요:
from huggingface_hub import notebook_login
notebook_login()
그런 다음 push_to_hf_hub 메서드로 모델을 푸시하세요:
import timm
# Build or load a model, e.g. timm's pretrained resnet18
model = timm.create_model('resnet18', pretrained=True, num_classes=4)
###########################
# [Fine tune your model...]
###########################
# Push it to the 🤗 Hub
timm.models.hub.push_to_hf_hub(
model,
'resnet18-random-classifier',
model_config={'labels': ['a', 'b', 'c', 'd']}
)
# Load your model from the Hub
model_reloaded = timm.create_model(
'hf-hub:<your-username>/resnet18-random-classifier',
pretrained=True
)
추가 자료
- timm (pytorch-image-models) GitHub 저장소
- timm 문서
- Aman Arora의 timmdocs 추가 문서
- Chris Hughes의 Getting Started with PyTorch Image Models (timm): A Practitioner's Guide