콘텐츠로 이동

PyTorch ResNet50

Overview

이 튜토리얼에서는 TorchVision의 사전 학습된 ResNet50 모델을 RBLN Python API와 PyTorch의 torch.compile() API를 사용하여 컴파일하고 추론을 실행하는 방법을 보여줍니다.

Setup & Installation

시작하기 전에 시스템 환경이 올바르게 구성되어 있으며, 필요한 모든 필수 패키지가 설치되어 있는지 확인하십시오. 다음 항목이 포함됩니다:

Note

RBLN SDK는 .whl 패키지로 배포됩니다. rebel-compilerrbln_driver를 사용하려면 RBLN Portal 계정이 필요합니다.

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 Runtime으로 컴파일된 모델을 로드하여 추론을 실행하고 최상위 예측 클래스를 출력합니다.

import urllib.request  
from torchvision.io.image import read_image  
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)  

결과는 다음과 같이 표시됩니다:

Top1 category:  tabby

torch.compile() API 사용

모델 및 입력 준비

ResNet50 모델과 입력 이미지를 준비합니다.

import torch  
from torchvision.models import resnet50, ResNet50_Weights  
import urllib.request  
from torchvision.io.image import read_image  

if torch.__version__ >= '2.5.0':  
    torch._dynamo.config.inline_inbuilt_nn_modules = False  

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이 필요합니다.

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)  

결과는 다음과 같이 표시됩니다:

Top1 category:  tabby

Summary and References

이 튜토리얼에서는 TorchVision ResNet50 모델을 RBLN Python API와 PyTorch의 torch.compile() API로 컴파일하고 추론하는 방법을 보여주었습니다.
이제 컴파일된 모델을 RBLN NPU에서 효율적으로 사용할 수 있습니다.

References: