keras 模型部署——TensorFlow Serving/Docker

今天筆者想記錄一下深度學習模型的部署,不知道大家研究過沒有,tensorflow模型有三種保存方式:

  • 訓練時我們會一般會將模型保存成:checkpoint文件
  • 為了方便python,C++或者其他語言部署你的模型,你可以將模型保存成一個既包含網(wǎng)絡結(jié)構(gòu)又包含權(quán)重參數(shù)的:PB文件
  • 為了方便使用TensorFlow Serving 部署你的模型,你可以將模型保存成:Saved_model文件

筆者是keras(tensorflow )的深度用戶,經(jīng)常把模型保存成HDF5格式。那么問題來了,如何把keras的模型轉(zhuǎn)化成PB文件 或者 Saved_model文件供生成部署使用。今天筆者就是來介紹一下如何將Keras的模型保存成PB文件 或者 Saved_model文件。

定義BERT二分類模型

下方函數(shù)定義的是一個標準的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), # 用足夠小的學習率
#         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模型,
  • 之后接一個keras中經(jīng)常使用的Lambda層用于抽取 bert最后一層出來的[CLS]位置對應特征向量,
  • 將[CLS]的特征向量輸入給一個全連接層做而分類。

由于筆者之前已經(jīng)訓練好了一個人模型,這里我直接使用load_bert_model_weight函數(shù)將模型以及模型參數(shù)加載進內(nèi)存。


BERT二分類

將keras模型轉(zhuǎn)化為PB文件

接下來可以使用這個函數(shù)將上市的model連模型圖結(jié)構(gòu)代參數(shù)一起保存下來,然后通過tensoflow 為python,java,c++語言等提供的模型調(diào)用接口使用起來了。

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文件

而接下來的部分是如何將model制作成Saved_model文件,這樣你就可以使用TensorFlow Serving 部署你的模型。這里筆者介紹一下使用TensorFlow Serving 部署你的模型的一些優(yōu)勢。

  • 支持模型版本控制和回滾
  • 支持并發(fā),實現(xiàn)高吞吐量
  • 開箱即用,并且可定制化
  • 支持多模型服務
  • 支持批處理
  • 支持熱更新
  • 支持分布式模型
  • 易于使用的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)

上述過程需要注意的一個人地方是模型API輸入和輸出的定義:
這個部分要按照模型的輸入輸出定義好。由于我的bert模型
定義如下:

  • 輸入token_id和segment_id兩部分輸入,
  • 輸出是dense層的輸出
    所以我的API定義過程如下
###輸入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í)行輸出:


res

采用上述代碼將model 保持成Saved_model 格式后,模型文件結(jié)構(gòu)如下圖所示:包含版本,模型pd文件,參數(shù)的文件夾。


Saved_model

TensorFlow Serving 之使用Docker 部署Saved_model

使用docker部署模型的好處在于,避免了與繁瑣的環(huán)境配置打交道。使用docker,不需要手動安裝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命令啟動TF Server :
(1)-p 8501:8501是端口映射,是將容器的8501端口映射到宿主機的8501端口,后面預測的時候使用該端口;
(2)-e MODEL_NAME=bert 設置模型名稱;
(3)--mount type=bind,source=/opt/developer/wp/learn/bert, target=/models/bert 是將宿主機的路徑/opt/developer/wp/learn/bert 掛載到容器的/models/bert 下。
/opt/developer/wp/learn/bert是通過上述py腳本生成的Saved_model的路徑。容器內(nèi)部會根據(jù)綁定的路徑讀取模型文件;

使用下方命令行查看服務狀態(tài)

 curl http://localhost:8501/v1/models/bert 
image.png

請求服務

加下來使用request庫嘗試請求一下我們的bert服務。
這里需要注意的是數(shù)據(jù)預處理的方式要和你做訓練時的方式一樣。

sent = "來玩英雄聯(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]]}
當然你也可以使用gRPC 的API在8500端口訪問你的服務。

結(jié)語

今天筆者只是簡單介紹了一下,如何將模型轉(zhuǎn)換為生產(chǎn)環(huán)境能用與部署的格式,以及使用docker部署模型的方式,其實模型訓練出來了,達到了很好的效果,接下來讓更多的人能夠方便的使用到它們也是我們算法工程師所期望的事情,所以,模型的部署還是很有意義的一件事情。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容