Tensorflow Lite (TFLite) 로 효율적으로 배포/추론하기
우리 회사는 클라우드 기반 서비스를 제공하지만, 비용 등의 문제로 CPU만 사용하고 있으며, 빠른 추론 속도가 핵심이다. 그래서 Tensorflow Lite (TFLite)를 택해서 모델을 배포하고 있다.
1. TFLite 소개
TFLite는 모바일 기기, 임베디드 시스템, IoT 기기 등 리소스가 제한된 기기에서 효과적으로 추론할 수 있도록 모델을 최적화하고 배포하기 위한 프레임워크이다. 즉 Tensorflow model을 경량화하기 위한 도구이다. 빠른 응답속도, 작은 사이즈가 특징이다.
TFLite는 FlatBuffer(.tflite 파일 확장자로 식별됨)라는 특수 형식을 사용하여 작고 이동 가능한 좋은 포맷을 구현했다. 반면 tensorflow 는 Protocol Buffers 라는 것을 사용하는데, 이에 비해 FlatBuffer는 축소된 크기, 추론 속도 개선 등의 이점이 있다.
짧은 응답 속도, 작은 사이즈 외에도 공식 문서에 소개된 장점으로,
- 개인 정보 보호: 기기에 개인 정보를 남기지 않는다.
- 연결성: 인터넷 연결이 필요하지 않다.
- 여러 플랫폼 지원: Android 및 iOS 기기, 내장형 Linux 및 마이크로 컨트롤러 등
- 다양한 언어 지원: 자바, Swift, Objective-C, C++, Python 등
- 모델 최적화 지원: 양자화, 잘라내기, 클러스터링 등
등이 있다.
2. TFLite 전체 개발 플로우
현재 TFLite에서는 학습을 지원하지 않는다. 통상적으로는 tensorflow/pytorch로 모델을 구축하고 학습한 후, TFLite로 변환하여 사용할 수 있다. 이 과정에서 모델을 변환하는 Converter, 변환된 모델을 동작시키는 Interpreter가 사용된다. Converter는 파이썬 개발환경에서 사용되고, Interpreter는 사용하려는 기기와 동일한 환경(자바, Swift, Objective-C, C++, Python 등)에서 사용된다.
- 모델 준비: 사전 학습된 TensorFlow 모델이나 직접 학습한 모델을 준비한다(pb 형태, h5 형태 등)
- TFLite 모델로 변환: 준비한 모델 파일을 TFLite 포맷인 .tflite 파일로 변환(convert)한다 [Converter 사용]
- 배포(deploy): 실제 구동할 디바이스에 tflite를 이식하여 배포한다.
- 모델 최적화: 양자화(Quantization), 잘라내기, 클러스터링 등을 통해 사이즈와 메모리 사용량, 반응
- 추론: Interpreter를 이용하여 추론
3. TFLite 변환/추론 코드 (Python)
현재 회사에서는 추론 역시 파이썬 환경에서 하므로, 이것만 소개하려 한다.
우선 변환 코드는 아래와 같다.
import tensorflow as tf
# 모델 변환 Convert the model
model_dir = PATH_OF_THE_MODEL_DIRECTORY # pb 형태로 저장된 모델 directory
converter = tf.lite.TFLiteConverter.from_saved_model(model_dir)
tflite_model = converter.convert()
# tflite 모델 저장 Save the model
save_path = PATH_TO_SAVE_TFLITE_MODEL
with open(f"{save_path}.tflite", 'wb') as f:
f.write(tflite_model)
1. pb 형태도 저장된 모델 directory가 필요하다. h5로 저장되어 있으면 pb로 변환까지 해주어야 함.
2. converter 로 변환해주고, 저장하면 된다. 아주 간단함.
추론 코드는 아래와 같다.
import numpy as np
import tensorflow as tf
# Load the TFLite model and allocate tensors.
# TFLite 모델을 interpreter로 load한다
interpreter = tf.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
# input, output detail을 얻는다.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Test the model on random input data.
# test를 위해 random data 만들기
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
# Inference
# 추론!
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
# get_tensor를 이용해 추론 결과를 얻는다!
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)
이상!
참고자료
https://www.tensorflow.org/lite/guide?hl=ko