tensorflowtfserving部署多个模型、使⽤不同版本的模型
本篇主要介绍使⽤tfserving和docker同时部署多个模型,使⽤不同版本的模型,基本的流程与部署单个模型的过程类似,(关于运⾏tfserving容器使⽤单个模型进⾏预测的相关步骤可以参见 )不同之处在于需要⽤到⼀个多模型的配置⽂件。⾸先得到多个可以⽤于tfserving预测的模型⽂件,相关步骤可以参考。本例中⽤中的相关代码⽣成三个模型,分别建⽴三个⽂件夹,将得到的模型分别放⼊,最后的⽂件结构如下图。其中100001⽂件夹表⽰模型的版本,可以在model1下放置不同版本的模型,默认情况下会加载具有较⼤版本号数字的模型。
1. 多模型部署
在multiModel⽂件夹下新建⼀个配置⽂件fig,⽂件内容为:
model_config_list:{
config:{
name:"model1",
base_path:"/models/multiModel/model1",
model_platform:"tensorflow"
},
config:{
name:"model2",
base_path:"/models/multiModel/model2",
model_platform:"tensorflow"
},
config:{
name:"model3",
base_path:"/models/multiModel/model3",
model_platform:"tensorflow"
}
}
配置⽂件定义了模型的名称和模型在容器内的路径,现在运⾏tfserving容器 :
docker run -p 8501:8501 --mount type=bind,source=/home/jerry/tmp/multiModel/,target=/models/multiModel \
-t tensorflow/serving --model_config_file=/models/fig
请求预测:
import requests
import numpy as np
SERVER_URL = 'localhost:8501/v1/models/model3:predict'
#注意SERVER_URL中的‘model3’是config⽂件中定义的模型name,不是⽂件夹名称
def prediction():
predict_request='{"instances":%s}' % str([[[10]*7]*7])
print(predict_request)
response = requests.post(SERVER_URL, data=predict_request)
print(response)
prediction = response.json()['predictions'][0]
print(prediction)
if __name__ == "__main__":
prediction()
2.指定模型版本
如果⼀个模型有多个版本,并在预测的时候希望指定模型的版本,可以通过以下⽅式实现。
修改fig⽂件,增加model_version_policy:
model_config_list:{
config:{
name:"model1",
base_path:"/models/multiModel/model1",
model_platform:"tensorflow",
tensorflow版本选择model_version_policy:{
all:{}
}
},
config:{
name:"model2",
base_path:"/models/multiModel/model2",
model_platform:"tensorflow"
},
config:{
name:"model3",
base_path:"/models/multiModel/model3",
model_platform:"tensorflow"
}
}
请求预测的时候,如果要使⽤版本为100001的模型,只要修改SERVER_URL为:
SERVER_URL = 'localhost:8501/v1/models/model1/versions/100001:predict'
tfserving⽀持模型的Hot Plug,上述容器运⾏起来之后,如果在宿主机的 /home/jerry/tmp/multiModel/model1/ ⽂件夹下新增模型⽂件如100003/,tfserving会⾃动加载新模型;同样如果移除现有模型,tfserving也会⾃动卸载模型。