今天筆者想記錄一下深度學(xué)習(xí)模型的部署浑测,不知道大家研究過(guò)沒(méi)有募壕,tensorflow模型有三種保存方式:
- 訓(xùn)練時(shí)我們會(huì)一般會(huì)將模型保存成:checkpoint文件
- 為了方便python麦轰,C++或者其他語(yǔ)言部署你的模型坦报,你可以將模型保存成一個(gè)既包含網(wǎng)絡(luò)結(jié)構(gòu)又包含權(quán)重參數(shù)的:PB文件
- 為了方便使用TensorFlow Serving 部署你的模型盟步,你可以將模型保存成:Saved_model文件
筆者是keras(tensorflow )的深度用戶,經(jīng)常把模型保存成HDF5格式他匪。那么問(wèn)題來(lái)了菇存,如何把keras的模型轉(zhuǎn)化成PB文件 或者 Saved_model文件供生成部署使用。今天筆者就是來(lái)介紹一下如何將Keras的模型保存成PB文件 或者 Saved_model文件邦蜜。
定義BERT二分類模型
下方函數(shù)定義的是一個(gè)標(biāo)準(zhǔn)的BERT做文本二分類的圖結(jié)構(gòu)依鸥。
from keras.models import Model
from keras.layers import *
from keras import backend as K
import tensorflow as tf
from keras_bert import get_model,compile_model
def load_bert_model_weight(bert_model_path):
b_model = get_model(token_num=21128,)
compile_model(b_model)
bert_model = Model(
inputs = b_model.input[:2],
outputs = b_model.get_layer('Encoder-12-FeedForward-Norm').output
)
x1_in = Input(shape=(None,))
x2_in = Input(shape=(None,))
x = bert_model([x1_in, x2_in])
x = Lambda(lambda x: x[:, 0])(x)## 取[CLS]向量
p = Dense(2, activation='softmax')(x)
model = Model([x1_in, x2_in], p)
# model.compile(
# loss='binary_crossentropy',
# optimizer=Adam(1e-5), # 用足夠小的學(xué)習(xí)率
# metrics=['accuracy']
# )
model.load_weights(bert_model_path)
return model
model_path = "/opt/developer/wp/wzcq/model/bert1014v1_weights.hf"
model = load_bert_model_weight(model_path)
具體結(jié)構(gòu)如下圖所示其中
- model_2 就是含12層的transformer的bert模型,
- 之后接一個(gè)keras中經(jīng)常使用的Lambda層用于抽取 bert最后一層出來(lái)的[CLS]位置對(duì)應(yīng)特征向量悼沈,
- 將[CLS]的特征向量輸入給一個(gè)全連接層做而分類贱迟。
由于筆者之前已經(jīng)訓(xùn)練好了一個(gè)人模型,這里我直接使用load_bert_model_weight函數(shù)將模型以及模型參數(shù)加載進(jìn)內(nèi)存絮供。
將keras模型轉(zhuǎn)化為PB文件
接下來(lái)可以使用這個(gè)函數(shù)將上市的model連模型圖結(jié)構(gòu)代參數(shù)一起保存下來(lái)衣吠,然后通過(guò)tensoflow 為python,java壤靶,c++語(yǔ)言等提供的模型調(diào)用接口使用起來(lái)了蒸播。
def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
"""
Freezes the state of a session into a pruned computation graph.
Creates a new computation graph where variable nodes are replaced by
constants taking their current value in the session. The new graph will be
pruned so subgraphs that are not necessary to compute the requested
outputs are removed.
@param session The TensorFlow session to be frozen.
@param keep_var_names A list of variable names that should not be frozen,
or None to freeze all the variables in the graph.
@param output_names Names of the relevant graph outputs.
@param clear_devices Remove the device directives from the graph for better portability.
@return The frozen graph definition.
"""
graph = session.graph
with graph.as_default():
freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
output_names = output_names or []
output_names += [v.op.name for v in tf.global_variables()]
input_graph_def = graph.as_graph_def()
if clear_devices:
for node in input_graph_def.node:
node.device = ""
frozen_graph = tf.graph_util.convert_variables_to_constants(
session, input_graph_def, output_names, freeze_var_names)
return frozen_graph
def save_keras_model_to_pb(keras_model , dic_pb=None, file_pb=None):
"""
save keras model to tf *.pb file
"""
frozen_graph = freeze_session(K.get_session(),output_names=[out.op.name for out in keras_model.outputs])
tf.train.write_graph(frozen_graph, dic_pb, file_pb, as_text=False)
return
save_keras_model_to_pb(model,"py","bert_model.pb")
將keras模型轉(zhuǎn)化為Saved_model文件
而接下來(lái)的部分是如何將model制作成Saved_model文件,這樣你就可以使用TensorFlow Serving 部署你的模型萍肆。這里筆者介紹一下使用TensorFlow Serving 部署你的模型的一些優(yōu)勢(shì)。
- 支持模型版本控制和回滾
- 支持并發(fā)胀屿,實(shí)現(xiàn)高吞吐量
- 開(kāi)箱即用塘揣,并且可定制化
- 支持多模型服務(wù)
- 支持批處理
- 支持熱更新
- 支持分布式模型
- 易于使用的inference api:為gRPC expose port 8500,為REST API expose port 8501
import tensorflow as tf
import os
from tensorflow.keras.losses import categorical_crossentropy
from tensorflow.keras.optimizers import Adadelta
def export_model(model,
export_model_dir,
model_version
):
"""
:param export_model_dir: type string, save dir for exported model url
:param model_version: type int best
:return:no return
"""
with tf.get_default_graph().as_default():
# prediction_signature
tensor_info_input_0 = tf.saved_model.utils.build_tensor_info(model.input[0])
tensor_info_input_1 = tf.saved_model.utils.build_tensor_info(model.input[1])
tensor_info_output = tf.saved_model.utils.build_tensor_info(model.output)
print(model.input)
print(model.output.shape, '**', tensor_info_output)
prediction_signature = (
tf.saved_model.signature_def_utils.build_signature_def(
inputs ={'input_0': tensor_info_input_0,'input_1': tensor_info_input_1}, # Tensorflow.TensorInfo
outputs={'result': tensor_info_output},
#method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)
method_name= "tensorflow/serving/predict")
)
print('step1 => prediction_signature created successfully')
# set-up a builder
os.mkdir(export_model_dir)
export_path_base = export_model_dir
export_path = os.path.join(
tf.compat.as_bytes(export_path_base),
tf.compat.as_bytes(str(model_version)))
builder = tf.saved_model.builder.SavedModelBuilder(export_path)
builder.add_meta_graph_and_variables(
# tags:SERVING,TRAINING,EVAL,GPU,TPU
sess=K.get_session(),
tags=[tf.saved_model.tag_constants.SERVING],
signature_def_map={
'predict':prediction_signature,
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: prediction_signature,
},
)
print('step2 => Export path(%s) ready to export trained model' % export_path, '\n starting to export model...')
#builder.save(as_text=True)
builder.save()
print('Done exporting!')
export_model(model,"bert",1)
上述過(guò)程需要注意的一個(gè)人地方是模型API輸入和輸出的定義:
這個(gè)部分要按照模型的輸入輸出定義好宿崭。由于我的bert模型
定義如下:
- 輸入token_id和segment_id兩部分輸入亲铡,
- 輸出是dense層的輸出
所以我的API定義過(guò)程如下
###輸入tensor
tensor_info_input_0 = tf.saved_model.utils.build_tensor_info(model.input[0])
tensor_info_input_1 = tf.saved_model.utils.build_tensor_info(model.input[1])
###輸出tensor
tensor_info_output = tf.saved_model.utils.build_tensor_info(model.output)
### 定義api
prediction_signature = (
tf.saved_model.signature_def_utils.build_signature_def(
inputs ={'input_0': tensor_info_input_0,'input_1': tensor_info_input_1}, # Tensorflow.TensorInfo
outputs={'result': tensor_info_output},
#method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)
method_name= "tensorflow/serving/predict")
)
下圖是腳本執(zhí)行輸出:
采用上述代碼將model 保持成Saved_model 格式后,模型文件結(jié)構(gòu)如下圖所示:包含版本,模型pd文件奖蔓,參數(shù)的文件夾赞草。
TensorFlow Serving 之使用Docker 部署Saved_model
使用docker部署模型的好處在于,避免了與繁瑣的環(huán)境配置打交道吆鹤。使用docker厨疙,不需要手動(dòng)安裝Python,更不需要安裝numpy疑务、tensorflow各種包沾凄。google 已經(jīng)幫你制作好了tensorflow/serving 鏡像,GPU版和CPU版都有知允,你只要要使用docker pull 命令將鏡像拉取到本地就可以了
run -p 8501:8501 --mount type=bind,source=/opt/developer/wp/learn/bert,target=/models/bert -e MODEL_NAME=bert --name bert -t tensorflow/serving
使用上面的docker命令啟動(dòng)TF Server :
(1)-p 8501:8501是端口映射撒蟀,是將容器的8501端口映射到宿主機(jī)的8501端口,后面預(yù)測(cè)的時(shí)候使用該端口温鸽;
(2)-e MODEL_NAME=bert 設(shè)置模型名稱保屯;
(3)--mount type=bind,source=/opt/developer/wp/learn/bert, target=/models/bert 是將宿主機(jī)的路徑/opt/developer/wp/learn/bert 掛載到容器的/models/bert 下。
/opt/developer/wp/learn/bert是通過(guò)上述py腳本生成的Saved_model的路徑涤垫。容器內(nèi)部會(huì)根據(jù)綁定的路徑讀取模型文件姑尺;
使用下方命令行查看服務(wù)狀態(tài)
curl http://localhost:8501/v1/models/bert
請(qǐng)求服務(wù)
加下來(lái)使用request庫(kù)嘗試請(qǐng)求一下我們的bert服務(wù)。
這里需要注意的是數(shù)據(jù)預(yù)處理的方式要和你做訓(xùn)練時(shí)的方式一樣雹姊。
sent = "來(lái)玩英雄聯(lián)盟"
tokenid_train = tokenizer.encode(sent,max_len=200)[0]
sen_id_train = tokenizer.encode(sent,max_len=200)[1]
import requests
SERVER_URL = "http://192.168.77.40:8501/v1/models/bert:predict"
predict_request='{"signature_name": "predict", "instances":[{"input_0":%s,"input_1":%s}] }' %(tokenid_train,sen_id_train)
response = requests.post(SERVER_URL, data=predict_request)
response.content
返回結(jié)果:{ "predictions": [[8.70507502e-05, 0.999913]]}
當(dāng)然你也可以使用gRPC 的API在8500端口訪問(wèn)你的服務(wù)股缸。
結(jié)語(yǔ)
今天筆者只是簡(jiǎn)單介紹了一下,如何將模型轉(zhuǎn)換為生產(chǎn)環(huán)境能用與部署的格式吱雏,以及使用docker部署模型的方式敦姻,其實(shí)模型訓(xùn)練出來(lái)了,達(dá)到了很好的效果歧杏,接下來(lái)讓更多的人能夠方便的使用到它們也是我們算法工程師所期望的事情镰惦,所以,模型的部署還是很有意義的一件事情犬绒。