用于通过http json api公开tensorflow模型的服务器
tfweb的Python项目详细描述
tfweb
用于python中tensorflow模型推断的web服务器。
快速启动
$ pip install tensorflow
$ pip install tfweb
$ tfweb --model s3://tfweb-models/hotdog --batch_transpose
$ curl -d '{"image": {"url": "https://i.imgur.com/H37kxPH.jpg"}}' localhost:8080/predict
{
"class": ["no hotdog"],
"prediction": [0.7314095497131348]
}
可能需要一些时间从s3://tfweb-models
下载模型。
$ tfweb -h
usage: tfweb [-h] [--model MODEL] [--tags TAGS] [--batch_size BATCH_SIZE]
[--static_path STATIC_PATH] [--batch_transpose] [--no_cors]
[--request_size REQUEST_SIZE] [--grpc_port GRPC_PORT]
tfweb
optional arguments:
-h, --help show this help message and exit
--model MODEL path to saved_model directory (can also be S3, GCS or hdfs)
--tags TAGS Comma separated SavedModel tags. Defaults to `serve`
--batch_size BATCH_SIZE
Maximum batch size for batchable methods
--static_path STATIC_PATH
Path to static content, eg. html files served on GET
--batch_transpose Provide and return each example in batches separately
--no_cors Accept HTTP requests from all domains
--request_size REQUEST_SIZE
Max size per request
--grpc_port GRPC_PORT
Port accepting grpc requests
为什么?
tfweb的目标是比tf服务更易于设置、修补和集成。由于用纯Python 3编写,它可以与TySoFr流交互,尽管它是灵活的Python绑定。
用法
tensorflow有一种标准格式,用于持久化名为savedModel的模型。任何以这种格式保存的模型,如果指定了它的签名,则可以自动公开为具有tfweb的web服务。
创建一个包含签名def的savedModel(查看examples
文件夹),然后启动一个服务器,用$ tfweb --model s3://tfweb-models/openimages --batch_transpose
在json上公开模型
要查看模型公开的api类型,可以查询它以获取其类型信息:
$ curl localhost:8080 | python -m json.tool
[
{
"name": "features",
"inputs": {
"image": {
"type": "string",
"shape": [
-1
]
}
},
"outputs": {
"features": {
"type": "float32",
"shape": [
-1,
2048
]
}
}
},
{
"name": "names",
"inputs": {
"image": {
"type": "string",
"shape": [
-1
]
}
},
"outputs": {
"names": {
"type": "string",
"shape": [
-1,
5
]
}
}
}
]
这里我们看到模型公开了两个方法,features
和names
,这两个方法接受成批的字符串。该模型实际上是在openimages上训练的inception v3,这意味着这些字符串是jpeg图像的批。我们不能将jpeg数据编码为json,所以我们可以让服务器从url获取数据,也可以在发送之前对图像数据进行base64编码。
因此我们可以像这样查询方法names
:
curl -d '{"image": {"url": "https://i.imgur.com/ekNNNjN.jpg"}}' localhost:8080/names | python -m json.tool
{
"names": [
"mammal",
"animal",
"pet",
"cat",
"vertebrate"
]
}
我们收到了5个对应于最佳初始匹配的字符串。
配料
默认情况下,tfweb不做任何批处理,但是如果一个方法(签名定义)对于所有输入和输出都有一个可变的外部维度(即shape是[-1,..)然后假设该方法是可批处理的,并且tfweb将在tensorflow会话忙于执行其他任务(如运行前一批)时,对批处理请求进行优化排队。
如果方法接受批处理,我们还可以在同一请求中发送多个查询:
curl -d '[{"image": {"url": "https://i.imgur.com/ekNNNjN.jpg"}}, {"image": {"url": "https://i.imgur.com/JNo5tHj.jpg"}}]' localhost:8080/names | python -m json.tool
[
{
"names": [
"mammal",
"animal",
"pet",
"cat",
"vertebrate"
]
},
{
"names": [
"mammal",
"animal",
"pet",
"vertebrate",
"dog"
]
}
]
功能性
- 纯python-与最成熟的tensorflow api相同!
- 读取tensorflow saved_model并根据签名定义中的类型信息公开http api
- 跨多个GPU使用请求批处理,无延迟
- 可以通过json读取封装在
{"b64": "..."}
或{"url": "..."}
中的二进制数据 - base64还对无效utf-8的json结果进行编码
- 也接受predict grpc签名。查看
test.py
以获取示例。
待办事项
- 更多的测试(包括编码和真实世界!)
- 当
- 公开自动缩放的指标
- 下载URL时,请跟踪内容大小