CPU上での処理とInferentia上での処理との比較

章4.1、章4.2で実行した推論用スクリプトに変更を加え、CPU上で推論処理を実行する場合と、Neuronコア上に推論処理をオフロードする場合との性能比較を行います。

Step 1. 推論スクリプトの変更

以下の内容でinfer_resnet50_perf.py というファイル名の推論実行 Python スクリプトを作成します。

章4.1、章4.2で使用したCPU向けモデル、Inferentia推論チップ向けにコンパイル済みモデルをそれぞれ再利用しますので、同じディレクトリ内で作業を行ってください。

import os
import time
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions

# added for utilizing 4 neuron cores
os.environ['NEURON_RT_VISIBLE_CORES'] = '0-3'

# Load models
model_dir = 'resnet50'
predictor_cpu = tf.contrib.predictor.from_saved_model(model_dir)
compiled_model_dir = 'resnet50_neuron'
predictor_inferentia = tf.contrib.predictor.from_saved_model(compiled_model_dir)

# Create input from image
img_sgl = image.load_img('kitten_small.jpg', target_size=(224, 224))
img_arr = image.img_to_array(img_sgl)
img_arr2 = np.expand_dims(img_arr, axis=0)
img_arr3 = preprocess_input(img_arr2)

model_feed_dict={'input': img_arr3}

# warmup
infa_rslts = predictor_cpu(model_feed_dict) 
infa_rslts = predictor_inferentia(model_feed_dict) 

num_inferences = 1000

# Run inference on CPUs, Display results
start = time.time()
for _ in range(num_inferences):
    infa_rslts = predictor_cpu(model_feed_dict)
elapsed_time = time.time() - start

print('By CPU         - num_inferences:{:>6}[images], elapsed_time:{:6.2f}[sec], Throughput:{:8.2f}[images/sec]'.format(num_inferences, elapsed_time, num_inferences / elapsed_time))

# Run inference on Neuron Cores, Display results
start = time.time()
for _ in range(num_inferences):
    infa_rslts = predictor_inferentia(model_feed_dict)
elapsed_time = time.time() - start

print('By Neuron Core - num_inferences:{:>6}[images], elapsed_time:{:6.2f}[sec], Throughput:{:8.2f}[images/sec]'.format(num_inferences, elapsed_time, num_inferences / elapsed_time))

Step 2. 推論スクリプトを実行

推論実行スクリプトinfer_resnet50_perf.pyを実行し、CPU上での処理とNeuronコア上での処理との比較を行います。

python infer_resnet50_perf.py

次の結果が取得されます。CPU上で推論処理を実行した場合と比較し、Neuronコアによる推論処理の高速化を確認できます。

By CPU         - num_inferences:  1000[images], elapsed_time: 50.66[sec], Throughput:   19.74[images/sec]
By Neuron Core - num_inferences:  1000[images], elapsed_time:  3.71[sec], Throughput:  269.62[images/sec]