태그 보관물: tensorflow

OpenVINO python을 이용한 inference 예제

OpenVINO를 이용해서 TensorFlow(Keras)로 training한 모델로 추론(inference)을 수행하는 간단한 예제를 작성해 보았다.

TensorFlow model을 freeze하기

Training된 모델을 model optimizer에 넣기 전에 freeze시켜야 하는데, output_node_names를 입력하라는 오류 메세지가 계속 뜬다면 제대로 freezing을 수행했는지 확인해 보는게 좋다. 알아보기 쉽게 하기 위해 입출력 layer에 ‘name=’ parameter로 다음과 같이 이름을 지정해 주었다.

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28), name='input'),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax', name='output')
])

그러면 layer의 이름들을 출력할 때 다음과 같이 나온다. 전체 MINST model training과 freezing 과정은 이 CoLab에 적어 두었으니 참조.

------------------------------------------------------------
Frozen model layers:
x
sequential/input/Const
sequential/input/Reshape
sequential/dense/MatMul/ReadVariableOp/resource
sequential/dense/MatMul/ReadVariableOp
sequential/dense/MatMul
sequential/dense/BiasAdd/ReadVariableOp/resource
sequential/dense/BiasAdd/ReadVariableOp
sequential/dense/BiasAdd
sequential/dense/Relu
sequential/dropout/Identity
sequential/output/MatMul/ReadVariableOp/resource
sequential/output/MatMul/ReadVariableOp
sequential/output/MatMul
sequential/output/BiasAdd/ReadVariableOp/resource
sequential/output/BiasAdd/ReadVariableOp
sequential/output/BiasAdd
sequential/output/Softmax
Identity
------------------------------------------------------------

모델 옵티마이저(mo-tf.py)

Freeze된 모델을 다운로드 받은 후에 TensorFlow용 model optimizer인 mo-tf.py를 실행 시키면 model을 나타내는 xml file과 weight값을 저장하는 bin file이 생성된다. 이 때 training된 모델은 입력 shape을 [-1, 28, 28]로 알고 있기 때문에 음수가 아닌 값을 넣어 달라는 에러가 생긴다. –input_shape parameter를 다음과 같이 적어준다.

/opt/intel/openvino_2021/deployment_tools/model_optimizer/mo_tf.py --input_model ./model/mnist_model/frozen_graph.pb  --input_shape [28,28]

OpenVINO를 이용한 inference

Model optimizer가 수행되었다면 이제 xml file을 이용해 model을 load하고 inference를 수행하면 된다. 다음은 Training 후 freezing과 model optimization이 수행된 XML file을 이용해서 inference를 수행하는 간단한 코드이다.

출력결과

$ python3 ./infer_mnist.py ./model/mnist_model/frozen/frozen_graph.xml

        Model path= ./model/mnist_model/frozen/frozen_graph.xml 
        Device= CPU
Accuracy: 0.9789 (hit: 9789/ miss: 211)

TensorFlow에서 CUBLAS_STATUS_NOT_INITIALIZED 오류 문제

failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED

이 문제는 TensorFlow의 GPU memory growth 설정과 관련이 있다. 이 경우 GPU의 allow_grouth option을 True로 설정하면 문제를 해결할 수 있는데, Use a GPU 페이지에 따르면 tf.config.experimental.set_memory_growth()를 통해 True로 설정하거나 혹은 환경변수 TF_FORCE_GPU_ALLOW_GROWTH를 설정해서 해결 할 수 있다.

코드에 다음과 같이 환경 변수를 설정해 줄 수도 있지만,

# Fix CUBLAS_STATUS_NOT_INITIALIZED error.
#  - failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
os.environ [ "TF_FORCE_GPU_ALLOW_GROWTH" ] = "true"

실행 환경에 따라 문제가 발생하지 않을 수도 있어서, 나는 주로 command line에서 다음과 같이 script를 실행할 때 이 값을 함께 설정한다.

# Command terminal
TF_FORCE_CPU_ALLOW_GROWTH=true flask run --host=0.0.0.9