自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

用TFserving部署深度學(xué)習(xí)模型

開發(fā) 架構(gòu) 深度學(xué)習(xí)
本文介紹了TFserving部署線上推理服務(wù),從模型的轉(zhuǎn)換,部署啟動(dòng)和調(diào)用推理,歡迎交流,希望對(duì)你有幫助。

1.什么是TFserving

當(dāng)你訓(xùn)好你的模型,需要提供給外部使用的時(shí)候,你就需要把模型部署到線上,并提供合適的接口給外部調(diào)用。你可能會(huì)考慮一些問(wèn)題:

  •  用什么來(lái)部署
  •  怎么提供api接口
  •  多個(gè)模型GPU資源如何分配
  •  線上模型如何更新而服務(wù)不中斷

目前流行的深度學(xué)習(xí)框架Tensorflow和Pytorch, Pytorch官方并沒(méi)有提供合適的線上部署方案;Tensorflow則提供了TFserving方案來(lái)部署線上模型推理。另外,Model Server for Apache MXNet 為MXNet模型提供推理服務(wù)。

本文為TFServing的使用指南。如果你是pytorch或者M(jìn)XNet模型,也可以通過(guò)ONNX轉(zhuǎn)成TFserving的模型,部署在TFServing上。

那什么是TFserving?

TFserving是Google 2017推出的線上推理服務(wù);采用C/S架構(gòu),客戶端可通過(guò)gRPC和RESTfull API與模型服務(wù)進(jìn)行通信。

TFServing的特點(diǎn):

  •  支持模型版本控制和回滾:Manager會(huì)進(jìn)行模型的版本的管理
  •  支持并發(fā),實(shí)現(xiàn)高吞吐量
  •  開箱即用,并且可定制化
  •  支持多模型服務(wù)
  •  支持批處理
  •  支持熱更新:Source加載本地模型,通知Manager有新的模型需要加載,Manager檢查模型的版本,通知Source創(chuàng)建的Loader進(jìn)行加載模型
  •  支持分布式模型

2.TFserving安裝

強(qiáng)烈建議采用docker方式安裝TFserving,安裝依賴docker和nvidia-docker(TFserving的gpu需要)

  •  docker 安裝 
  1. #安裝yum-utils工具和device-mapper相關(guān)依賴包  
  2. yum install -y yum-utils \  
  3. device-mapper-persistent-data \  
  4. lvm2  
  5. #添加docker-ce stable版本的倉(cāng)庫(kù)  
  6. yum-config-manager \  
  7. --add-repo \  
  8. https://download.docker.com/linux/centos/docker-ce.repo  
  9. #更新yum緩存文件  
  10. yum makecache fast  
  11. #查看所有可安裝的docker-ce版本  
  12. yum list docker-ce --showduplicates | sort -r  
  13. # 安裝docker-ce  
  14. yum install docker-ce-17.12.1.ce-1.el7.centos  
  15. #允許開機(jī)啟動(dòng)docker-ce服務(wù)  
  16. systemctl enable docker.service  
  17. #啟動(dòng)Docker-ce服務(wù)  
  18. systemctl start docker  
  19. #運(yùn)行測(cè)試容器hello-world  
  20. docker run --rm hello-world 
  •  nvidia-docker 安裝 
  1. # 安裝nvidia-docker2  
  2. yum install -y nvidia-docker2-2.0.3-1.docker17.12.1.ce  
  3. # 重啟docker服務(wù)  
  4. service docker restart 
  •  安裝TFserving 
  1. docker pull tensorflow/serving:latest-gpu  
  2. # 可以選擇其他版本如 docker pull tensorflow/serving:1.14.0-rc0-gpu 

注意:docker版本和nvidia-docker要匹配

  •  目前最新的nvidia-docker需要Docker為19.03 可參考官方https://github.com/NVIDIA/nvidia-docker
  •  nvidia-docker2 支持Docker版本低于19.03的其他版本(需>=1.12),現(xiàn)有服務(wù)器有18.09,1.17,1.13  https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(version-2.0)

3.TFserving使用說(shuō)明

3.1 模型轉(zhuǎn)換

TFserving的模型需要轉(zhuǎn)換成TFserving的格式, 不支持通常的checkpoint和pb格式。

TFserving的模型包含一個(gè).pb文件和variables目錄(可以為空),導(dǎo)出格式如下:. 

  1. ├── 1  
  2. │   ├── saved_model.pb  
  3. │   └── variables  
  4. ├── 2  
  5. │   ├── saved_model.pb  
  6. │   └── variables 

不同的深度學(xué)習(xí)框架的轉(zhuǎn)換路徑: 

  1. (1) pytorch(.pth)--> onnx(.onnx)--> tensorflow(.pb) --> TFserving  
  2. (2) keras(.h5)--> tensorflow(.pb) --> TFserving  
  3. (3) tensorflow(.pb) --> TFserving 

這里詳細(xì)介紹下pb轉(zhuǎn)換成TFserving模型 

  1. import tensorflow as tf  
  2. def create_graph(pb_file):  
  3.     """Creates a graph from saved GraphDef file and returns a saver."""  
  4.     # Creates graph from saved graph_def.pb.  
  5.     with tf.gfile.FastGFile(pb_file, 'rb') as f:  
  6.         graph_def = tf.GraphDef()  
  7.         graph_def.ParseFromString(f.read())  
  8.         _ = tf.import_graph_def(graph_def, name='' 
  9. def pb_to_tfserving(pb_file, export_path, pb_io_name=[], input_node_name='input'output_node_name='output'signature_name='default_tfserving'):  
  10.     # pb_io_name 為 pb模型輸入和輸出的節(jié)點(diǎn)名稱,  
  11.     # input_node_name為轉(zhuǎn)化后輸入名  
  12.     # output_node_name為轉(zhuǎn)化后輸出名  
  13.     # signature_name 為簽名  
  14.     create_graph(pb_file) 
  15.      # tensor_name_list = [tensor.name for tensor in tf.get_default_graph().as_graph_def().node]  
  16.     input_name = '%s:0' % pb_io_name[0]  
  17.     output_name = '%s:0' % pb_io_name[1]  
  18.     with tf.Session() as sess:  
  19.         in_tensor = sess.graph.get_tensor_by_name(input_name)  
  20.         out_tensor = sess.graph.get_tensor_by_name(output_name)  
  21.         builder = tf.saved_model.builder.SavedModelBuilder(export_path)  ## export_path導(dǎo)出路徑  
  22.         inputs = {input_node_name: tf.saved_model.utils.build_tensor_info(in_tensor)}    
  23.         outputs = {output_node_name: tf.saved_model.utils.build_tensor_info(out_tensor)}  
  24.         signature = tf.saved_model.signature_def_utils.build_signature_def(  
  25.             inputs, outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)  
  26.         builder.add_meta_graph_and_variables(  
  27.             sesssess=sess, tags=[tf.saved_model.tag_constants.SERVING],  
  28.             signature_def_map={signature_name: signature}, clear_devices=True)  ## signature_name為簽名,可自定義  
  29.         builder.save()  
  30. pb_model_path = 'test.pb'  
  31. pb_to_tfserving(pb_model_path, './1', pb_io_name=['input_1_1','output_1'],signature_name='your_model'

3.2 TFserving配置和啟動(dòng)

模型導(dǎo)出后,同一個(gè)模型可以導(dǎo)出不同的版本(版本后數(shù)字),可以TFserving配置中指定模型和指定版本。TFserving的模型是通過(guò)模型名稱和簽名來(lái)唯一定位。TFserving 可以配置多個(gè)模型,充分利用GPU資源。

  •  模型配置 
  1. # models.config  
  2. model_config_list {  
  3.   config {  
  4.     name: 'your_model'  
  5.     base_path: '/models/your_model/'  
  6.     model_platform: 'tensorflow'  
  7. #     model_version_policy {  
  8. #       specific {  
  9. #         versions: 42  
  10. #         versions: 43  
  11. #       }  
  12. #     }  
  13. #     version_labels {  
  14. #       key: 'stable'  
  15. #       value: 43  
  16. #     }  
  17. #     version_labels {  
  18. #       key: 'canary'  
  19. #       value: 43  
  20. #     }  
  21.   }  
  22.   config {  
  23.     name: "mnist",  
  24.     base_path: "/models/mnist",  
  25.     model_platform: "tensorflow",  
  26.     model_version_policy: {  
  27.        specific: {  
  28.         versions: 1,  
  29.         versions: 2  
  30.        }  
  31.   }  
  32.  
  33. # 可以通過(guò)model_version_policy 進(jìn)行版本的控制 
  •  啟動(dòng)服務(wù) 
  1. # 建議把模型和配置文件放在docker外的本地路徑,如/home/tfserving/models, 通過(guò)-v 掛載到docker內(nèi)部  
  2. # --model_config_file: 指定模型配置文件  
  3. # -e NVIDIA_VISIBLE_DEVICES=0: 指定GPU  
  4. # -p 指定端口映射 8500為gRpc 8501為restful api端口  
  5. # -t 為docker鏡像  
  6. nvidia-docker run  -it --privileged  -d -e NVIDIA_VISIBLE_DEVICES=0  -v /home/tfserving/models:/models  -p 8500:8500 -p 8501:8501 \  
  7.  -t tensorflow/serving:latest-gpu \  
  8. --model_config_file=/models/models.config  
  9. # /home/tfserving/models 結(jié)構(gòu)  
  10. ├── models.config  
  11. └── your_model  
  12.     ├── 1  
  13.     │   ├── saved_model.pb  
  14.     │   └── variables  
  15.     └── 2  
  16.         ├── saved_model.pb  
  17.         └── variables  
  18. # test  
  19. curl http://192.168.0.3:8501/v1/models/your_model  
  20.  
  21.     "model_version_status": [  
  22.         {  
  23.             "version": "2",  
  24.             "state": "AVAILABLE",  
  25.             "status": {  
  26.             "error_code": "OK",  
  27.             "error_message": ""  
  28.             }  
  29.         }  
  30.     ]        
  31.  
  32. # 其他啟動(dòng)方式  
  33. # 如果多個(gè)模型在不同的目錄,可以通過(guò)-mount 單獨(dú)加載  
  34. nvidia-docker run  -it --privileged  -d -e NVIDIA_VISIBLE_DEVICES=0 \  
  35. --mount type=bind,source=/home/tfserving/models/your_model,target=/models/your_model \  
  36. --mount type=bind,source=/home/tfserving/models/your_model/models.config,target=/models/models.config \  
  37. -p 8510:8500 -p 8501:8501 \  
  38. -t tensorflow/serving:latest-gpu \  
  39. --model_config_file=/models/models.config 

3.3 TFserving服務(wù)調(diào)用

客戶端可以通過(guò)gRpc和http方式調(diào)用TFserving服務(wù)模型,支持多種客戶端語(yǔ)言,這里提供python的調(diào)用方式; 調(diào)用都是通過(guò)模型名稱和簽名來(lái)唯一對(duì)應(yīng)一個(gè)模型

  •  gRpc調(diào)用, gRpc的端口是8500 
  1.  
  2. # -*-coding:utf-8 -*-  
  3. import tensorflow as tf  
  4. from tensorflow_serving.apis import predict_pb2  
  5. from tensorflow_serving.apis import prediction_service_pb2_grpc  
  6. import grpc  
  7. import time  
  8. import numpy as np  
  9. import cv2 
  10. class YourModel(object):  
  11.     def __init__(self, socket):  
  12.         """ 
  13.         Args:  
  14.             socket: host and port of the tfserving, like 192.168.0.3:8500  
  15.         """  
  16.         self.socket = socket  
  17.         start = time.time()  
  18.         self.request, selfself.stub = self.__get_request()  
  19.         end = time.time()  
  20.         print('initialize cost time: ' + str(end - start) + ' s')  
  21.     def __get_request(self):  
  22.         channel = grpc.insecure_channel(self.socket, options=[('grpc.max_send_message_length', 1024 * 1024 * 1024),  
  23.                                                               ('grpc.max_receive_message_length', 1024 * 1024 * 1024)]) # 可設(shè)置大小  
  24.         stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)  
  25.         request = predict_pb2.PredictRequest()  
  26.         request.model_spec.name = "your_model"  # model name  
  27.         request.model_spec.signature_name = "your_model"  # model signature name  
  28.         return request, stub  
  29.     def run(self, image):  
  30.         """  
  31.         Args:  
  32.             image: the input image(rgb format)  
  33.         Returns: embedding is output of model  
  34.         """  
  35.         img = image[..., ::-1]   
  36.         self.request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(img))  # images is input of model  
  37.         result = self.stub.Predict(self.request, 30.0)  
  38.         return tf.make_ndarray(result.outputs['output'])  
  39.     def run_file(self, image_file):  
  40.         """  
  41.         Args:  
  42.             image_file: the input image file  
  43.         Returns:  
  44.         """  
  45.         image = cv2.imread(image_file)  
  46.         image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  
  47.         return self.run(image)  
  48. if __name__ == '__main__': 
  49.      model = YourModel('192.168.0.3:8500')  
  50.     test_file = './test.jpg'  
  51.     result = model.run_file(test_file)  
  52.     print(result)  
  53.     # [8.014745e-05 9.999199e-01] 
  •  restful api調(diào)用: restful端口是8501 
  1. import cv2  
  2. import requests  
  3. class SelfEncoder(json.JSONEncoder):  
  4.     def default(self, obj):  
  5.         if isinstance(obj, np.ndarray):  
  6.             return obj.tolist()  
  7.         elif isinstance(obj, np.floating):  
  8.             return float(obj)  
  9.         elif isinstance(obj, bytes):  
  10.             return str(obj, encoding='utf-8');  
  11.         return json.JSONEncoder.default(self, obj)  
  12. image_file = '/home/tfserving/test.jpg'  
  13. image = cv2.imread(image_file)  
  14. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  
  15. img = image[..., ::-1]  
  16. input_data = {  
  17.     "signature_name": "your_model",  
  18.     "instances": img  
  19.  
  20. data = json.dumps(input_data, cls=SelfEncoderindent=None 
  21. result = requests.post("http://192.168.0.3:8501/v1/models/your_model:predict", datadata=data)  
  22. eval(result .content)  
  23. # {'predictions': [8.01474525e-05, 0.999919891]} 

5.總結(jié)

本文介紹了TFserving部署線上推理服務(wù),從模型的轉(zhuǎn)換,部署啟動(dòng)和調(diào)用推理,歡迎交流,希望對(duì)你有幫助。我們來(lái)回答下開篇提出的問(wèn)題

  •  用什么來(lái)部署:當(dāng)然是TFserving
  •  怎么提供api接口:TFserving有提供restful api接口,現(xiàn)實(shí)部署時(shí)會(huì)在前面再加一層如flask api
  •  多個(gè)模型GPU資源如何分配:TFserving支持部署多模型,通過(guò)配置
  •  線上模型如何更新而服務(wù)不中斷:TFserving支持模型的不同的版本,如your_model中1和2兩個(gè)版本,當(dāng)你新增一個(gè)3模型時(shí),TFserving會(huì)自動(dòng)判斷,自動(dòng)加載模型3為當(dāng)前模型,不需要重啟 

 

責(zé)任編輯:龐桂玉 來(lái)源: Python中文社區(qū)
相關(guān)推薦

2019-08-08 08:00:00

深度學(xué)習(xí)機(jī)器學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)

2022-03-28 18:59:02

DockerFlask深度學(xué)習(xí)

2022-05-10 10:19:04

AI深度學(xué)習(xí)模型

2018-11-07 09:00:00

機(jī)器學(xué)習(xí)模型Amazon Sage

2020-11-02 14:38:56

Java 深度學(xué)習(xí)模型

2021-09-02 08:02:50

深度學(xué)習(xí)Kubernetes集群管理

2019-01-23 11:12:42

機(jī)器學(xué)習(xí)機(jī)器模型預(yù)測(cè)工資

2023-11-19 23:36:50

2020-10-13 14:42:42

深度學(xué)習(xí)Windows人工智能

2017-05-27 14:00:06

深度學(xué)習(xí)人臉建模

2018-02-26 17:10:57

深度學(xué)習(xí)

2024-09-09 11:45:15

ONNX部署模型

2020-09-29 17:00:33

人工智能

2023-01-09 08:00:00

遷移學(xué)習(xí)機(jī)器學(xué)習(xí)數(shù)據(jù)集

2017-08-16 10:57:52

深度學(xué)習(xí)TensorFlowNLP

2017-10-18 09:48:13

深度學(xué)習(xí)TensorFlow入門篇

2021-02-03 13:56:09

KerasAPI深度學(xué)習(xí)

2023-02-23 07:46:48

學(xué)習(xí)模型數(shù)據(jù)倉(cāng)庫(kù)

2017-05-08 14:42:36

2024-04-18 10:39:57

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)