PyTorch ResNet50
개요
이 튜토리얼에서는 TorchVision의 사전 학습된 ResNet50 모델을 RBLN Python API와 PyTorch의 torch.compile() API를 사용하여 컴파일하고 추론을 실행하는 방법을 보여줍니다.
환경 설정 및 설치 확인
시작하기 전에 시스템 환경이 올바르게 구성되어 있고 필요한 패키지가 모두 설치되어 있는지 확인합니다. 필요한 항목은 다음과 같습니다:
- 시스템 요구 사항:
- 필수 패키지:
- 설치 명령어:
| pip install --extra-index-url https://download.pytorch.org/whl/cpu torch torchvision
pip install \
--extra-index-url https://pypi.rbln.ai/simple \
rebel-compiler==0.12.0
|
Info
rebel-compiler를 사용하려면 RBLN Portal 계정이 필요합니다. - 위 명령은 Debian 계열 Linux(예: Ubuntu)에서 pip로 패키지를 설치하는 일반적인 절차를 전제로 합니다. OS나 환경이 다른 경우에는 설치 가이드에서 지원되는 설치 조합과 적용 가능한 명령을 확인할 수 있습니다.
RBLN Python API 사용
모델 컴파일
TorchVision에서 사전 학습된 ResNet50 모델을 불러와 추론 모드로 설정한 후, RBLN Python API로 컴파일합니다.
| import torch
from torchvision.models import resnet50, ResNet50_Weights
import rebel
weights = ResNet50_Weights.DEFAULT
model = resnet50(weights=weights)
model.eval()
compiled_model = rebel.compile_from_torch(
model,
[('input', [1, 3, 224, 224], torch.float32)],
)
compiled_model.save('resnet50.rbln')
|
모델 추론
예제 이미지를 다운로드하고 전처리한 후, RBLN 런타임으로 컴파일된 모델을 로드하여 추론을 실행하고 최상위 예측 클래스를 출력합니다.
| import urllib.request
from torchvision.io.image import read_image
import torch
from torchvision.models import ResNet50_Weights
from rebel import Runtime
weights = ResNet50_Weights.DEFAULT
urllib.request.urlretrieve('https://rbln-public.s3.ap-northeast-2.amazonaws.com/images/tabby.jpg', 'input.jpg')
img = read_image('input.jpg')
preprocess = weights.transforms()
batch = preprocess(img).unsqueeze(0)
module = Runtime('resnet50.rbln', tensor_type='pt')
output = module(batch)
_, idx = torch.topk(output, 1, dim=1)
pred_class = weights.meta['categories'][idx]
print('Top-1 Predicted Class:', pred_class)
|
예시 출력:
| Top-1 Predicted Class: tabby
|
torch.compile() API 사용
모델 및 입력 준비
ResNet50 모델과 입력 이미지를 준비합니다.
| import torch
from torchvision.models import resnet50, ResNet50_Weights
import urllib.request
from torchvision.io.image import read_image
weights = ResNet50_Weights.DEFAULT
model = resnet50(weights=weights)
model.eval()
img_url = 'https://rbln-public.s3.ap-northeast-2.amazonaws.com/images/tabby.jpg'
img_path = './tabby.jpg'
with urllib.request.urlopen(img_url) as response, open(img_path, 'wb') as f:
f.write(response.read())
img = read_image(img_path)
preprocess = weights.transforms()
batch = preprocess(img).unsqueeze(0)
|
컴파일 및 추론
torch.compile()에 backend='rbln'을 지정하여 RBLN 백엔드로 모델을 컴파일합니다. 첫 번째 포워드 패스로 컴파일을 트리거한 후, 컴파일된 모델로 추론을 실행합니다.
Note
torch.compile()에서 RBLN 백엔드를 사용하려면 backend='rbln'을 지정해야 하며, 컴파일 전에 import rebel이 필요합니다.
Warning
RBLN 백엔드가 그래프 컴파일에 실패하면 torch.compile()은 경고만 남기고 CPU eager 실행으로 폴백합니다. options에 'mode': 'strict'를 추가하면 폴백 대신 오류가 발생합니다.
| import rebel # Need to use torch dynamo's "rbln" backend.
compiled_model = torch.compile(
model,
backend='rbln',
options={'cache_dir': './.cache'},
dynamic=False
)
# Trigger compilation with the first forward pass
compiled_model(batch)
rbln_result = compiled_model(batch)
score, class_id = torch.topk(rbln_result, 1, dim=1)
category_name = weights.meta['categories'][class_id]
print('Top-1 category:', category_name)
|
예시 출력:
참고