管理API¶
TorchServe 提供以下 API,允许您在运行时管理模型:
管理API在端口8081上监听,默认情况下仅可从localhost访问。要更改默认设置,请参阅TorchServe配置。
管理API用于注册和删除模型,默认情况下是禁用的。在运行TorchServe时,添加--enable-model-api到命令行以启用这些API的使用。更多详情和启用方法请参见模型API控制
对于所有管理API请求,TorchServe要求包含正确的管理令牌或禁用令牌授权。有关详细信息,请参阅令牌授权文档
类似于 推理API, 管理API提供了 API描述,以OpenAPI 3.0规范描述管理API。
或者,如果您想使用KServe,TorchServe支持v1和v2 API。有关更多详细信息,请参阅此kserve文档
注册模型¶
此 API 遵循 ManagementAPIsService.RegisterModel gRPC API。
要使用此API,在TorchServe启动后,必须启用模型API控制。在启动TorchServe时,向命令行添加--enable-model-api以启用此API的使用。有关更多详细信息,请参阅模型API控制
POST /models
url- 模型档案下载URL。支持以下位置:a本地模型档案 (.mar); 文件必须在
model_store文件夹中(且不在子文件夹中)。使用HTTP(s)协议的URI。TorchServe可以从互联网上下载.marl文件。
model_name- 模型的名称;这个名称将在其他API中作为{model_name}部分路径的一部分使用。如果此参数不存在,则将使用MANIFEST.json中的modelName。handler- 推理处理程序入口点。如果存在,则此值将覆盖handler在 MANIFEST.json 中。注意:确保给定的handler在PYTHONPATH中。处理程序的格式为module_name:method_name。runtime- 模型自定义服务代码的运行时。如果存在,则此值将覆盖 MANIFEST.json 中的运行时。默认值为PYTHON。batch_size- 推理批次大小。默认值为1。max_batch_delay- 批处理聚合的最大延迟。默认值为100毫秒。initial_workers- 初始工人数量。默认值为0。TorchServe在至少有一个工作分配后才会运行推理。synchronous- 是否创建工作者是异步的。默认值为false。TorchServe将创建新的工作者,而无需等待确认前一个工作者在线。response_timeout- 如果模型的后端工作者在这个超时期内没有响应推理响应,该工作者将被视为无响应并重启。单位是秒。默认值为120秒。startup_timeout- 如果模型的后端工作者在这个超时期内没有加载模型,该工作者将被视为无响应并重启。单位是秒。默认值为120秒。
curl -X POST "http://localhost:8081/models?url=https://torchserve.pytorch.org/mar_files/squeezenet1_1.mar"
{
"status": "Model \"squeezenet_v1.1\" Version: 1.0 registered with 0 initial workers. Use scale workers API to add workers for the model."
}
加密模型服务¶
如果您想要提供加密模型服务,您需要设置具有以下环境变量的 S3 SSE-KMS:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_DEFAULT_REGION
并且在HTTP请求中设置“s3_sse_kms=true”。
例如:模型 squeezenet1_1 已在您自己的私有账户下 在 S3 上加密。S3 上的模型 http 地址是 https://torchserve.pytorch.org/sse-test/squeezenet1_1.mar。
如果 PyTorch Serve 将在 EC2 实例上运行(例如操作系统:Ubuntu)
为EC2实例添加IAM角色(AWSS3ReadOnlyAccess)
运行 ts_scripts/get_aws_credential.sh 来导出 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY
将 AWS_DEFAULT_REGION 设置为您的 S3 存储桶区域。
开始 PyTorch Serve
在 curl 命令中设置 s3_sse_kms=true 来注册加密模型 squeezenet1_1。
curl -X POST "http://localhost:8081/models?url=https://torchserve.pytorch.org/sse-test/squeezenet1_1.mar&s3_sse_kms=true"
{
"status": "Model \"squeezenet_v1.1\" Version: 1.0 registered with 0 initial workers. Use scale workers API to add workers for the model."
}
如果 PyTorch Serve 将在本地运行(例如,操作系统:macOS)
找到您的 AWS 访问密钥和秘密密钥。如果您忘记了密钥,可以重置它们。
将 AWS 访问密钥 ID 导出
将 AWS 秘钥密钥导出为你的 AWS 秘钥
将 AWS_DEFAULT_REGION 设置为您的 S3 存储桶区域。
开始 PyTorch Serve
在 curl 命令中设置 s3_sse_kms=true 来注册加密模型 squeezenet1_1(与 EC2 示例步骤 5 相同)。
你可能需要在注册时创建工作者。因为创建初始工作者可能需要一些时间,你可以选择同步或异步调用来确保初始工作者被正确创建。
异步调用在尝试创建工作者之前返回HTTP状态码202。
curl -v -X POST "http://localhost:8081/models?initial_workers=1&synchronous=false&url=https://torchserve.pytorch.org/mar_files/squeezenet1_1.mar"
< HTTP/1.1 202 Accepted
< content-type: application/json
< x-request-id: 4dc54158-c6de-42aa-b5dd-ebcb5f721043
< content-length: 47
< connection: keep-alive
<
{
"status": "Processing worker updates..."
}
同步调用在所有工作器都被调整后返回HTTP状态码200。
curl -v -X POST "http://localhost:8081/models?initial_workers=1&synchronous=true&url=https://torchserve.pytorch.org/mar_files/squeezenet1_1.mar"
< HTTP/1.1 200 OK
< content-type: application/json
< x-request-id: ecd2e502-382f-4c3b-b425-519fbf6d3b85
< content-length: 89
< connection: keep-alive
<
{
"status": "Model \"squeezenet1_1\" Version: 1.0 registered with 1 initial workers"
}
缩放工人¶
此 API 遵循 ManagementAPIsService.ScaleWorker gRPC API。它返回 ModelServer 中模型的状态。
PUT /models/{model_name}
min_worker- (可选) 模型所需的最小工作进程数。TorchServe 将尝试维持此最小值以指定模型。默认值为1。max_worker- (可选) 指定模型的最大工作进程数。TorchServe 将不会为指定的模型创建超过此数量的工作进程。默认值与min_worker的设置相同。synchronous- 是否为同步调用。默认值为false。timeout- 指定的工人完成所有待办请求所需的时间。如果超过该时间,工作进程将被终止。使用0立即终止后端工人进程。使用-1无限等待。默认值为-1。
使用Scale Worker API 动态调整模型的worker数量,以更好地满足不同推理请求负载。
这个API有两种不同的风味,同步和异步。
异步调用将以HTTP状态码202立即返回。
curl -v -X PUT "http://localhost:8081/models/noop?min_worker=3"
< HTTP/1.1 202 Accepted
< content-type: application/json
< x-request-id: 42adc58e-6956-4198-ad07-db6c620c4c1e
< content-length: 47
< connection: keep-alive
<
{
"status": "Processing worker updates..."
}
同步调用在所有工作器都被调整后返回HTTP状态码200。
curl -v -X PUT "http://localhost:8081/models/noop?min_worker=3&synchronous=true"
< HTTP/1.1 200 OK
< content-type: application/json
< x-request-id: b72b1ea0-81c6-4cce-92c4-530d3cfe5d4a
< content-length: 63
< connection: keep-alive
<
{
"status": "Workers scaled to 3 for model: noop"
}
要使用特定版本的模型的工作者,请使用URI:/models/{model_name}/{version}
PUT /models/{model_name}/{version}
以下同步调用将在所有版本“2.0”模型“noop”的工作器被调整为HTTP状态码200后返回。
curl -v -X PUT "http://localhost:8081/models/noop/2.0?min_worker=3&synchronous=true"
< HTTP/1.1 200 OK
< content-type: application/json
< x-request-id: 3997ccd4-ae44-4570-b249-e361b08d3d47
< content-length: 77
< connection: keep-alive
<
{
"status": "Workers scaled to 3 for model: noop, version: 2.0"
}
描述模型¶
此 API 遵循 ManagementAPIsService.DescribeModel gRPC API。它返回 ModelServer 中模型的状态。
GET /models/{model_name}
使用Describe Model API 获取模型默认版本的详细运行时状态:
curl http://localhost:8081/models/noop
[
{
"modelName": "noop",
"modelVersion": "1.0",
"modelUrl": "noop.mar",
"engine": "Torch",
"runtime": "python",
"minWorkers": 1,
"maxWorkers": 1,
"batchSize": 1,
"maxBatchDelay": 100,
"workers": [
{
"id": "9000",
"startTime": "2018-10-02T13:44:53.034Z",
"status": "READY",
"gpu": false,
"memoryUsage": 89247744
}
],
"jobQueueStatus": {
"remainingCapacity": 100,
"pendingRequests": 0
}
}
]
GET /models/{model_name}/{version}
使用Describe Model API 获取特定版本模型的详细运行时状态:
curl http://localhost:8081/models/noop/2.0
[
{
"modelName": "noop",
"modelVersion": "2.0",
"modelUrl": "noop_2.mar",
"engine": "Torch",
"runtime": "python",
"minWorkers": 1,
"maxWorkers": 1,
"batchSize": 1,
"maxBatchDelay": 100,
"workers": [
{
"id": "9000",
"startTime": "2018-10-02T13:44:53.034Z",
"status": "READY",
"gpu": false,
"memoryUsage": 89247744
}
],
"jobQueueStatus": {
"remainingCapacity": 100,
"pendingRequests": 0
}
}
]
GET /models/{model_name}/all
使用Describe Model API 获取模型所有版本的详细运行时状态:
curl http://localhost:8081/models/noop/all
[
{
"modelName": "noop",
"modelVersion": "1.0",
"modelUrl": "noop.mar",
"engine": "Torch",
"runtime": "python",
"minWorkers": 1,
"maxWorkers": 1,
"batchSize": 1,
"maxBatchDelay": 100,
"workers": [
{
"id": "9000",
"startTime": "2018-10-02T13:44:53.034Z",
"status": "READY",
"gpu": false,
"memoryUsage": 89247744
}
],
"jobQueueStatus": {
"remainingCapacity": 100,
"pendingRequests": 0
}
},
{
"modelName": "noop",
"modelVersion": "2.0",
"modelUrl": "noop_2.mar",
"engine": "Torch",
"runtime": "python",
"minWorkers": 1,
"maxWorkers": 1,
"batchSize": 1,
"maxBatchDelay": 100,
"workers": [
{
"id": "9000",
"startTime": "2018-10-02T13:44:53.034Z",
"status": "READY",
"gpu": false,
"memoryUsage": 89247744
}
],
"jobQueueStatus": {
"remainingCapacity": 100,
"pendingRequests": 0
}
}
]
GET /models/{model_name}/{model_version}?customized=true
or
GET /models/{model_name}?customized=true
使用Describe Model API 获取模型版本的详细运行时状态和自定义元数据:
实现函数describe_handle。例如
def describe_handle(self):
"""Customized describe handler
Returns:
dict : A dictionary response.
"""
output_describe = None
logger.info("Collect customized metadata")
return output_describe
实现函数_is_describe,如果handler不是继承自BaseHandler。然后,在handle中调用_is_describe和describe_handle。
def _is_describe(self):
if self.context and self.context.get_request_header(0, "describe"):
if self.context.get_request_header(0, "describe") == "True":
return True
return False
def handle(self, data, context):
if self._is_describe():
output = [self.describe_handle()]
else:
data_preprocess = self.preprocess(data)
if not self._is_explain():
output = self.inference(data_preprocess)
output = self.postprocess(output)
else:
output = self.explain_handle(data_preprocess, data)
return output
调用函数_is_describe 和 describe_handle 在 handle 中。例如
def handle(self, data, context):
"""Entry point for default handler. It takes the data from the input request and returns
the predicted outcome for the input.
Args:
data (list): The input data that needs to be made a prediction request on.
context (Context): It is a JSON Object containing information pertaining to
the model artifacts parameters.
Returns:
list : Returns a list of dictionary with the predicted response.
"""
# It can be used for pre or post processing if needed as additional request
# information is available in context
start_time = time.time()
self.context = context
metrics = self.context.metrics
is_profiler_enabled = os.environ.get("ENABLE_TORCH_PROFILER", None)
if is_profiler_enabled:
output, _ = self._infer_with_profiler(data=data)
else:
if self._is_describe():
output = [self.describe_handle()]
else:
data_preprocess = self.preprocess(data)
if not self._is_explain():
output = self.inference(data_preprocess)
output = self.postprocess(output)
else:
output = self.explain_handle(data_preprocess, data)
stop_time = time.time()
metrics.add_time('HandlerTime', round(
(stop_time - start_time) * 1000, 2), None, 'ms')
return output
这是一个例子。“customizedMetadata”显示用户模型的元数据。这些元数据可以解码成字典。
curl http://localhost:8081/models/noop-customized/1.0?customized=true
[
{
"modelName": "noop-customized",
"modelVersion": "1.0",
"modelUrl": "noop-customized.mar",
"runtime": "python",
"minWorkers": 1,
"maxWorkers": 1,
"batchSize": 1,
"maxBatchDelay": 100,
"loadedAtStartup": false,
"workers": [
{
"id": "9010",
"startTime": "2022-02-08T11:03:20.974Z",
"status": "READY",
"memoryUsage": 0,
"pid": 98972,
"gpu": false,
"gpuUsage": "N/A"
}
],
"jobQueueStatus": {
"remainingCapacity": 100,
"pendingRequests": 0
},
"customizedMetadata": "{\n \"data1\": \"1\",\n \"data2\": \"2\"\n}"
}
]
在客户端解码自定义元数据。例如:
import requests
import json
response = requests.get('http://localhost:8081/models/noop-customized/?customized=true').json()
customizedMetadata = response[0]['customizedMetadata']
print(customizedMetadata)
注销模型¶
此 API 遵循 ManagementAPIsService.UnregisterModel gRPC API。它返回 ModelServer 中模型的状态。
要使用此API,在TorchServe启动后,必须启用模型API控制。在启动TorchServe时,向命令行添加--enable-model-api以启用此API的使用。有关更多详细信息,请参阅模型API控制
DELETE /models/{model_name}/{version}
使用Unregister Model API通过注销特定版本的模型从TorchServe释放系统资源。
curl -X DELETE http://localhost:8081/models/noop/1.0
{
"status": "Model \"noop\" unregistered"
}
列表模型¶
此 API 遵循 ManagementAPIsService.ListModels gRPC API。它返回 ModelServer 中模型的状态。
GET /models
limit- (可选) 返回的最大项目数。作为查询参数传递。默认值为100。next_page_token- (可选) 下一页查询。作为查询参数传递。此值由先前的API调用返回。
使用模型API查询当前注册模型的默认版本:
curl "http://localhost:8081/models"
这个API支持分页:
curl "http://localhost:8081/models?limit=2&next_page_token=2"
{
"nextPageToken": "4",
"models": [
{
"modelName": "noop",
"modelUrl": "noop-v1.0"
},
{
"modelName": "noop_v0.1",
"modelUrl": "noop-v0.1"
}
]
}
API 描述¶
OPTIONS /
要查看完整的推理和管理API列表,请使用以下命令:
# To view all inference APIs:
curl -X OPTIONS http://localhost:8080
# To view all management APIs:
curl -X OPTIONS http://localhost:8081
输出是OpenAPI 3.0.1 JSON格式。您可以使用它生成客户端代码,详情请参见swagger codegen。
示例输出的推理和管理API:
设置默认版本¶
此 API 遵循 ManagementAPIsService.SetDefault gRPC API。它返回 ModelServer 中模型的状态。
PUT /models/{model_name}/{version}/set-default
要将任何注册的模型版本设置为默认版本,请使用:
curl -v -X PUT http://localhost:8081/models/noop/2.0/set-default
输出是OpenAPI 3.0.1 JSON格式。您可以使用它生成客户端代码,详情请参见swagger codegen。