目錄
環境:
系統:ubuntu 18.04
cuda: 10.0
cudnn: 7.4
Tensorflow: 2.0.0
TensorRt: 6.1
1. 安裝TensorRt
1. 下載TensorRt 安裝包:https://developer.nvidia.com/tensorrt
點擊Download Now即可選擇不同的版本下載,選擇版本時需要根據你的系統版本與cuda版本。如果是第一次下載,需要註冊一個賬戶,然後填一個調查問卷,挺簡單的。儘量下載.tar壓縮文件,和GA版本,GA表示穩定版,RC表示發行測試版。下載的速度可能會比較慢,請科學上網,方能玩轉深度學習。
2. 安裝
儘量選擇一個python虛擬環境(使用conda創建)來安裝,而且該環境已經安裝了tensorflow-gpu版本,這是前置條件。
2.1 系統路徑設置
將lib加入系統路徑中:
sudo gedit ~/.bashrc
將下面的語句複製到文件的最後面
export LD_LIBRARY_PATH=/home/snow/TensorRT-6.0.1.5/lib:$LD_LIBRARY_PATH
更新一哈
source ~/.bashrc
2.2 安裝tensorrt
打開終端,cd進TensorRT/python文件夾下:
根據你的python版本來選擇不同的安裝文件
note: 如果環境中有pip, pip2, pip3, 安裝python2包使用pip2, 安裝python3的包使用pip3; 如果只有一個pip, 就無所謂拉,直接使用pip。
tensorrt導入沒有錯誤,則安裝成功
在Pycharm中如果導入失敗,在終端導入成功,可以將lib下的庫全部複製到 /usr/lib下,基本就可以拉。
2.3 安裝uff, graphsurgeon:
不知道是不是我的tensorflow版本過高的問題,uff可以安裝成功,導入就是不能成功,有點鬱悶,也沒事,本文暫時用不到uff模塊,如果哪位小夥伴知道爲什麼導入失敗,請在下方評論,謝謝。
uff 測試方法與tensorrt一樣,
>>>import uff
不出錯就沒有問題啦,我的Import失敗,不知道你們能不能成功,我在另一臺電腦,ubuntu16.04, tf1.x,是可以導入成功的。
graphsurgeon不用測試,提示安裝成功就可以啦。
2. 模型保存
以mnist數據集爲例:
# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow.keras import datasets, optimizers
# from tensorflow.python.compiler.tensorrt import trt_convert
def preprocess(x, y):
"""
x is a simple image, not a batch
"""
x = tf.expand_dims(x, axis=-1)
x = tf.cast(x, dtype=tf.float32) / 255.
# x = tf.reshape(x, [28 * 28])
y = tf.cast(y, dtype=tf.int32)
y = tf.one_hot(y, depth=10)
return x, y
batchsz = 128
def train():
# 可以直接使用datasets.mnist.load_data(),如果網絡好,可以連接外網,
# 如果下載不了,可以自己先下載文件
(x, y), (x_val, y_val) = datasets.mnist.load_data('/home/snow/picture/mnist.npz')
print('datasets:', x.shape, y.shape, x.min(), x.max())
db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(10000).batch(batchsz)
ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz)
# sample = next(iter(db))
# print(sample[0].shape, sample[1].shape)
inputs = tf.keras.Input(shape=(28,28,1), name='input')
# [28, 28, 1] => [28, 28, 64]
input = tf.keras.layers.Flatten(name="flatten")(inputs)
fc_1 = tf.keras.layers.Dense(512, activation='relu', name='fc_1')(input)
fc_2 = tf.keras.layers.Dense(256, activation='relu', name='fc_2')(fc_1)
pred = tf.keras.layers.Dense(10, activation='softmax', name='output')(fc_2)
model = tf.keras.Model(inputs=inputs, outputs=pred, name='mnist')
model.summary()
Loss = []
Acc = []
optimizer = optimizers.Adam(0.001)
# epoches = 5
for epoch in range(1):
# 創建用於測試精度的參數
total_num = 0
total_correct = 0
for step, (x,y) in enumerate(db):
with tf.GradientTape() as tape:
pred = model(x)
loss = tf.keras.losses.categorical_crossentropy(y_pred=pred,
y_true=y,
from_logits=False)
loss = tf.reduce_mean(loss)
grades = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grades, model.trainable_variables))
# 輸出loss值
if step % 10 == 0:
print("epoch: ", epoch, "step: ", step, "loss: ", loss.numpy())
Loss.append(loss)
# 計算精度,將全連接層的輸出轉化爲概率值輸出
for step, (x_val, y_val) in enumerate(ds_val):
# 預測測試集的輸出
pred = model(x_val)
# pred = tf.nn.softmax(pred, axis=1)
pred = tf.argmax(pred, axis=1)
pred = tf.cast(pred, tf.int32)
y_val = tf.argmax(y_val, axis=1)
y_val = tf.cast(y_val, tf.int32)
correct = tf.equal(pred, y_val)
correct = tf.cast(correct, tf.int32)
correct = tf.reduce_sum(correct)
total_correct += int(correct)
total_num += x_val.shape[0]
if step % 20 == 0:
acc_step = total_correct / total_num
print("第" + str(step) + "步的階段精度是:", acc_step)
Acc.append(float(acc_step))
acc = total_correct / total_num
print("epoch %d test acc: " % epoch, acc)
# 方式1:
model.save('./model/tf_savedmodel', save_format='tf')
# 方式2:
# tf.saved_model.save(obj=model, export_dir="./model/")
if __name__ == "__main__":
train()
所有代碼中,應該注意的是model.save() ,它前面的代碼是訓練代碼,可以根據自己的網絡修改,最後的保存方式是重點:
model.save('./model/tf_savedmodel', save_format='tf'),第一個參數是保存路徑,第二個參數是保存格式,不能修改。
2.1 顯存分配
在ubuntu系統下,非常容易出現顯存不足的情況,可以加上下面指令,可以有效分配顯存,當然,如果顯存很大,可以略過。
方式1:
import os
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
方式2:
# 寫在頭文件下面
# physical_devices = tf.config.experimental.list_physical_devices('GPU')
# assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
# tf.config.experimental.set_memory_growth(physical_devices[0], True)
3. 模型轉換
# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from tensorflow.python.compiler.tensorrt import trt_convert as trt
params = trt.DEFAULT_TRT_CONVERSION_PARAMS
params._replace(precision_mode=trt.TrtPrecisionMode.FP32)
converter = trt.TrtGraphConverterV2(input_saved_model_dir="./model/yolo_tf_model", conversion_params=params)
# 完成轉換,但是此時沒有進行優化,優化在執行推理時完成
converter.convert()
converter.save('./model/trt_savedmodel')
這一步也會生成一個.pb文件,這個文件則是tensorrt文件
4. 模型推理測試
# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
import tensorflow as tf
from tensorflow.python.compiler.tensorrt import trt_convert as trt
from tensorflow.keras.datasets import mnist
import time
import cv2
import numpy as np
# physical_devices = tf.config.experimental.list_physical_devices('GPU')
# assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
# tf.config.experimental.set_memory_growth(physical_devices[0], True)
(x_train, y_train), (x_test, y_test) = mnist.load_data('/home/snow/picture/mnist.npz')
x_test = x_test.astype('float32')
x_test = x_test.reshape(10000, 784)
x_test /= 255
# 讀取模型
saved_model_loaded = tf.saved_model.load("./model/trt_savedmodel", tags=[trt.tag_constants.SERVING])
# 獲取推理函數,也可以使用saved_model_loaded.signatures['serving_default']
graph_func = saved_model_loaded.signatures[trt.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]
# 將模型中的變量變成常量,這一步可以省略,直接調用graph_func也行
frozen_func = trt.convert_to_constants.convert_variables_to_constants_v2(graph_func)
count = 20
for x,y in zip(x_test, y_test):
x = tf.cast(x, tf.float32)
start = time.time()
# frozen_func(x)返回值是個列表
# 列表中含有一個元素,就是輸出tensor,使用.numpy()將其轉化爲numpy格式
output = frozen_func(x)[0].numpy()
end = time.time()
times = (end - start) * 1000.0
print("tensorrt times: ", times, " ms")
result = np.argmax(output, 1)
print("prediction result: ", result, " | ", "true result: ", y)
if count == 0:
break
count -= 1
輸出結果展示:
總共循環了20次,第一次較慢,後面就開始趨於正常,一張圖片預測只花費了0.4ms左右,超過2000fps/s,簡直恐怖,而且我的顯卡也不好,MX150。當然網絡小是主要原因。
現在用YOLOV2來測試一波,YOLOV2有23層網絡,4000多萬的參數量:
來看看它的速度:
平均172ms,速度還是極爲快的,而且,在未轉化爲tensorRt模型之前的原模型,在我電腦上都跑不動,顯存不足。