GithubHelp home page GithubHelp logo

ddps-lab / edge-inference Goto Github PK

View Code? Open in Web Editor NEW
2.0 2.0 3.0 287.17 MB

Evaluation of inference model performance on edge devices

License: Apache License 2.0

Python 93.36% Dockerfile 0.83% Shell 5.81%

edge-inference's People

Contributors

jungae-park avatar kmu-leeky avatar leehanjeong avatar unhochoi avatar workdd avatar

Stargazers

 avatar  avatar

Forkers

workdd mh3ong

edge-inference's Issues

Dockerfile 재구성

tpu 환경에 필요한 라이브러리를 포함하여 재구성 및 docker hub에 이미지 업로드

CNN 모델 edge TPU (tflite) convert 에러

image

  • TF cnn model tflite convert 과정
import tensorflow as tf
from tensorflow.keras.applications import ( 
        mobilenet,
        mobilenet_v2,
        inception_v3
        )

mobilnet_model = tf.keras.applications.MobileNet(weights='imagenet')
mobilnetv2_model = tf.keras.applications.MobileNetV2(weights='imagenet')
Inceptionv3_model = tf.keras.applications.InceptionV3(weights='imagenet')

converter = tf.lite.TFLiteConverter.from_keras_model(mobilnet_model)
tflite_model = converter.convert()

with open('mobilenet_v1.tflite', 'wb') as f:
  f.write(tflite_model)

converter = tf.lite.TFLiteConverter.from_keras_model(mobilnetv2_model)
tflite_model = converter.convert()

with open('mobilenet_v2.tflite', 'wb') as f:
  f.write(tflite_model)

converter = tf.lite.TFLiteConverter.from_keras_model(Inceptionv3_model)
tflite_model = converter.convert()

with open('inception_v3.tflite', 'wb') as f:
  f.write(tflite_model)
  • tflite 모델 edge tpu model convert 과정
# curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
# echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list
# sudo apt-get update
# sudo apt-get install edgetpu-compiler	

edgetpu_compiler 명령문을 사용하여 변환

# edgetpu_compiler mobilenet_v1.tflite
# edgetpu_compiler mobilenet_v2.tflite
# edgetpu_compiler inception_v3.tflite
  • edge tpu convert 성공시 메시지
Edge TPU Compiler version 16.0.384591198
Started a compilation timeout timer of 180 seconds.

Model compiled successfully in 554 ms.

Input model: inception_v3.tflite
Input size: 90.91MiB
Output model: inception_v3_edgetpu.tflite
Output size: 90.90MiB
On-chip memory used for caching model parameters: 0.00B
On-chip memory remaining for caching model parameters: 0.00B
Off-chip memory used for streaming uncached model parameters: 0.00B
Number of Edge TPU subgraphs: 0
Total number of operations: 125
Operation log: inception_v3_edgetpu.log

Model successfully compiled but not all operations are supported by the Edge TPU. A percentage of the model will instead run on the CPU, which is slower. If possible, consider updating your model to use only operations supported by the Edge TPU. For details, visit g.co/coral/model-reqs.
Number of operations that will run on Edge TPU: 0
Number of operations that will run on CPU: 125
See the operation log file for individual operation details.
Compilation child process completed within timeout period.
Compilation succeeded! 
  • edge tpu convert 실패시 메시지
Edge TPU Compiler version 16.0.384591198
Started a compilation timeout timer of 180 seconds.
ERROR: Attempting to use a delegate that only supports static-sized tensors with a graph that has dynamic-sized tensors.
Compilation failed: Model failed in Tflite interpreter. Please ensure model can be loaded/run in Tflite interpreter.
Compilation child process completed within timeout period.
Compilation failed! 

convert 실패시 메시지를 아래와 같이 확인 하였을 때 모델 사이즈를 정적으로 지정하지 못해서 생기는 이슈로 판단되어 확인중 (FP32 or FP16)

ERROR: Attempting to use a delegate that only supports static-sized tensors with a graph that has dynamic-sized tensors.

edge 장비 백업 및 버전선정 후 재설치

현재 edge 장비들이 ubuntu 18.04를 사용하고 disk의 용량의 대부분을 사용하고 있는데 파악이 안되고 있습니다.
새롭게 tf serving 이미지를 빌드할겸 실험환경 재구성할겸 ubuntu를 업그레이드하는 등 cuda, tf, python 등의 LTS 최신으로 시스템부터 docker 이미지까지 버전을 통일해서 시스템 구성을 하겠습니다.
백업이 필요할까요?

CNN 모델 edge TPU (tflite) inference 에러

  • 라즈베리파이 + coral tpu 환경에서 추론을 위해 필요한 라이브러리 설치 및 확인
# Install Edge TPU Libraries
echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | tee /etc/apt/sources.list.d/coral-edgetpu.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -
apt-get update

# Libraries required for Mini PCIe Coral Chip
apt-get install -y gasket-dkms libedgetpu1-std

# tflite runtime install(arm 64)
# https://www.tensorflow.org/lite/guide/python?hl=ko (tflite_runtime 설치)
pip3 install https://dl.google.com/coral/python/tflite_runtime-2.1.0.post1-cp36-cp36m-linux_aarch64.whl
# package, library check
dpkg -l | grep edgetpu 
dpkg -L libedgetpu1-std

#lsusb install (tpu device check)
apt install usbutils
lsusb
  • 추론을 위해 tpu 라이브러리를 사용하도록 기존 모델 코드에 추가
import tflite_runtime.interpreter as tflite

model = tflite.Interpreter(
    "./model_edgetpu.tflite", 
    experimental_delegates=[tflite.load_delegate('libedgetpu.so.1')])
model.allocate_tensors()
  • 추론 작업시 error 발생
ValueError: Failed to load delegate from libedgetpu.so.1

해당 에러는 라이브러리를 설치하였지만, 라이브러리를 못찾고 있는 에러로 확인되며
환경에 맞는 버전으로 잘 설치 되어 있는지 확인하고 있으며, 다른 부분에서 빠진 설정이 있는지 공식 coral-tpu 문서를 보고 전체적인 설정 확인중
(https://coral.ai/docs/notes/build-coral/#required-components)

tpu 환경에서 image classification 추론시 accuarcy 수치 이슈

https://github.com/ddps-lab/research-issues/issues/45

입력 형식을 해결하여 tpu 환경에서 dtype이 모두 int8인 tfrecord imagenet dataset, edgetpu 모델을 사용한 추론 결과를 아래와 같이 확인하였습니다.

***** TF-lite matric *****
user_batch_size = 1
accuracy = 0.001
model_load_time = 3.132760524749756
dataset_load_time = 3.074784755706787
inference_time = 41.50337839126587
inference_time(avg) = 0.017514058351516724
IPS = 20.959311305960835
IPS(inf) = 57.09698916889812

정확도 수치가 이상하여 디버깅을 진행하고 있습니다.

tpu(edgetpu-tflite)와 rpi-cpu(tflite)의 성능 비교 실험

inception v3 모델에 대해 tpu(edgetpu-tflite)와 rpi-cpu(tflite)의 성능 비교 실험을 통해 더 나은 성능을 살펴보고,
tpu 장치에 대한 이해를 하기 위해 작업을 진행합니다.

  • inception v3 model
  • imagenet dataset
  • batch size 1 기준 (추후 배치 추론 성능도 비교 예정)

Flask Process 초기화 여부 테스트

목적 : 요청을 처리할 때 tensorflow load가 발생하지 않도록 구현해야함

Flask에서 요청 route를 받을 때 새로운 process를 사용한다면 load가 될 것이고, 그렇지 않는다면 테스트에 활용가능하여 해당 경우를 테스트 코드 작성하여 확인해볼 예정입니다.

CNN 모델 TensorRT convert 및 inference

  1. model : Mobilenet V1, Mobilenet V2, Inception V3, Yolo V5
  2. dataset : tfrecord imagenet (1000장)
  3. GPU device : Nvidia Jetson TX1, TX2, Xavier, Nano
  4. TPU device : rpi-4 + Coral TPU

CNN 추론 메모리 부족 에러

[추가 실험 필요 대상]

  • TX1 장비
  1. inception v3 (batch size 64,128)
  • Nano 장비
  1. mobilenet v1 (batch size 64,128)
  2. mobilenet v2 (batch size 32,64,128)
  3. inception v3 (모든 batch size)

[기존 실험]

  1. 1000장의 이미지를 batch size 만큼 추론 진행
    (batch size가 32일 경우, 각기 다른 32장의 이미지를 약 30번 추론 진행)

[추가 실험]

  1. 1000장의 이미지 중 batch size 만큼의 같은 이미지 (32장 or 64장)를 batch size 만큼 추론 진행

기존 실험 metric 결과와 차이점 확인 및 추가 실험을 통한 metric 결과 값 수정

각 edge 장비 재설치 후 gpu에 접근을 하며 추론하는지 확인을 하던 중에 중요한 사실을 놓치고 있어 보고드립니다.

xavier,nano는 재설치를 진행하면 jetpack을 같이 설치해주어 cuda, cudnn이 설치되고 별다른 조치 없이 gpu에 접근이 가능하였고, 추론 하여 결과 metric을 정리하였었습니다.
그러나 다른 장비들과 달리 tx1, tx2 장비는 재설치 후 jetpack이 자동으로 설치되지 않아 gpu에 접근하지 못하고 있었던 사실을 확인하였습니다.

그래서 tx1 장비에 추가로 jetpack을 수동으로 설치 후, gpu에 접근 가능한 것을 확인하여 추론을 해보았는데 결과가 이전과 많이 달랐습니다.

[이전 실험 결과]

***** TF-FP32 matric *****
user_batch_size = 1
accuracy = 0.93	
model_load_time = 58.66154599	
dataset_load_time = 1.593460083	
inference_time = 208.2208807	
inference_time(avg) = 0.2068657527	
IPS = 3.724726716	
IPS(inf) = 4.83405294

[현재 재설치 및 jetpack 추가 설치 후 실험 결과]

***** TF-FP32 matric *****
user_batch_size = 1
accuracy = 0.93
model_load_time = 59.926010608673096
dataset_load_time = 1.6062180995941162
inference_time = 99.50904369354248
inference_time(avg) = 0.09781955647468567
IPS = 6.209582934647488
IPS(inf) = 10.222904662819504

성능 차이가 확실히 달라졌으며, 기존 실험 결과를 분석하는 과정에서 세 번째 라인의 의미처럼
tx1,tx2 장비보다 nano 장비의 flops가 낮지만 IPS 값이 높은 이유가 설명이 되지 않았고 이상하였는데 tx1,tx2 장비가 gpu에 제대로 접근을 하지 못해 생긴 것으로 판단됩니다.
image

다시 mobilenet v1 모델 추론 결과를 살펴보니 nano 장비보다 tx2의 아키텍처와 장비 스펙의 Flops이 더 좋은 만큼 성능 결과도 그에 맞게 달라진 것을 확인하여 다른 모델들도 배치 추론을 다시하여 metric 결과 값을 수정하려고 합니다.

한 가지 문제점은 tx1 장비의 경우도 jetpack을 수동으로 설치해주어 cuda,cudnn을 통해 gpu에 접근 및 추론이 가능하도록 해야하는데, tx1 장비는 이미 내장되어 있는 disk 용량이 16GB로 jetpack을 추가로 설치하기에 용량이 부족합니다.
그래서 외장 sd card (128GB)를 붙여 root에 설치되는 라이브러리를 외장 sd card에 설치하고 라이브러리 PATH를 변경시켜 사용하도록 시도해보고 있습니다.

그래서 아래와 같이 작업을 해보려고 합니다.

  1. tx2 장비의 모델별 배치 추론 결과 다시 정리
  2. tx1 장비 + 외장 sd-card 추가 및 jetpack 설치 후 배치 추론 결과 다시 정리
    (xavier, nano 장비에서의 모델별 배치 추론은 gpu를 사용하며 배치 추론한 것이 확실하여 다시 결과값을 정리하지 않아도 됩니다.)

edge 장비에서 cnn, nlp 모델 추론 가능성 test

edge 장비에서 여러 모델 추론 가능성을 확인합니다.

  1. image classification (mobilenetv1, mobilenetv2, inceptionv3 - raw image 1장 추론)
  2. coral-tpu 장비에서 mage classification (edgetpu-tflite 모델 {mobilenetv1, mobilenetv2, inceptionv3} - raw image 1장 추론)
  3. object detection (yolov5 - raw image 1장 추론)
  4. nlp (rnn, lstm, bert, distilbert - test data 하나만 추론)

Coral TPU 의 성능이 일관적이지 않은 이유에 대한 분석 필요

이전 실험 결과 분석에 의하면
Coral TPU 가 Mobilnet V1, MobileNet V2 의 경우 Xavier 보다 높은 처리 성능을 보였지만, InceptionV3 에서의 성능은 좋지않음.
당시에 분석했던 이유중 하나가 InceptionV3 의 경우 Coral 공식 홈페이지에서 모델을 제공해주지 않았다고 했는데, 지금 확인해보면 제공을 해주고 있음.
당시에 해당 내용에 대한 분석이 부족한것 같아서 시간을 내서 조금 더 분석을 해봤으면 함.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.