본문 바로가기
AI Coding/ONNX

[ONNX] ONNX Runtime에서 실행하기

by ga.0_0.ga 2023. 3. 31.
728x90
반응형

이번 포스팅에서는 ONNX로 변환된 모델을 이용해 ONNX Runtime에서 실행하는 방법에 대해 설명하겠습니다!

 

모델을 ONNX Runtime에서 실행하려면 미리 설정된 파라미터로 모델을 위한 inference session을 생성해야합니다.

그 다음 모델의 run() 함수를 이용해 모델을 실행합니다. run() 함수를 통해 리턴 받은 결과 값들은 ONNX Runtime에서 연산된 모든 결과를 포함한 리스트 형태입니다.

 

먼저 필요한 라이브러리들을 import 해줍니다.

import onnxruntime

 

그 다음은 run()함수를 통해 결과값을 도출합니다.

ort_session = onnxruntime.InferenceSession('fd_live_512x512_multiftnet_best381_230321.onnx')

def to_numpy(tensor):
    return  tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

# ONNX Runtime에서 계산된 결과값
ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(img)}
ort_outs = ort_session.run(None, ort_inputs)

 

ONNX Runtime에서 연산된 결과값과 PyTorch 모델에서 연산된 결과값을 비교해보겠습니다.

torch_out = to_numpy(torch_model(img))
np.testing.assert_allclose(torch_out, ort_outs[0], rtol = 1e-03, atol = 1e-05)
print("Exported model has been tested with ONNXRuntime, and the result looks good!")

np.testing.assert_allclose 함수는 오차범위 내에서 두 값이 일치하는지 확인할 수 있는 함수입니다. 위 코드에서는 오차범위 1e-03 ~ 1e-05 이내에서 확인합니다. 

오차범위 내에서 동일하다면 맞게 변환된 것입니다!

728x90
반응형

댓글