快捷方式

⚠️ 注意:有限維護

本專案不再積極維護。現有版本仍然可用,但沒有計劃中的更新、錯誤修復、新功能或安全補丁。使用者應注意漏洞可能不會得到解決。

管理 API

TorchServe 提供了以下 API,允許您在執行時管理模型

  1. 註冊模型

  2. 增加/減少特定模型的 worker 數量

  3. 描述模型的狀態

  4. 登出模型

  5. 列出已註冊的模型

  6. 設定模型的預設版本

  7. 重新整理 token 以進行 token 授權

管理 API 預設監聽 8081 埠,並且只能從 localhost 訪問。要更改預設設定,請參閱 TorchServe 配置

用於註冊和刪除模型的管理 API 預設處於停用狀態。在執行 TorchServe 時,向命令列新增 --enable-model-api 以啟用這些 API 的使用。有關更多詳細資訊和啟用方法,請參閱 模型 API 控制

對於所有管理 API 請求,TorchServe 要求包含正確的管理 token,否則必須停用 token 授權。有關更多詳細資訊,請參閱 token 授權文件

推理 API 類似,管理 API 提供 API 描述,用於使用 OpenAPI 3.0 規範描述管理 API。

或者,如果您想使用 KServe,TorchServe 同時支援 v1 和 v2 API。有關更多詳細資訊,請參閱此 kserve 文件

註冊模型

此 API 遵循 ManagementAPIsService.RegisterModel gRPC API。

TorchServe 啟動後要使用此 API,必須啟用模型 API 控制。在啟動 TorchServe 時,向命令列新增 --enable-model-api 以啟用此 API 的使用。有關更多詳細資訊,請參閱 模型 API 控制

POST /models

  • url - 模型歸檔檔案下載 URL。支援以下位置:

    • 本地模型歸檔檔案 (.mar);檔案必須位於 model_store 資料夾中(不能在子資料夾中)。

    • 使用 HTTP(s) 協議的 URI。TorchServe 可以從網際網路下載 .mar 檔案。

  • model_name - 模型名稱;此名稱將在其他 API 中用作路徑的一部分 {model_name}。如果此引數不存在,將使用 MANIFEST.json 中的 modelName

  • handler - 推理處理器的入口點。如果存在,此值將覆蓋 MANIFEST.json 中的 handler注意:請確保給定的 handler 位於 PYTHONPATH 中。handler 的格式為 module_name:method_name

  • runtime - 模型自定義服務程式碼的執行時。如果存在,此值將覆蓋 runtime 在 MANIFEST.json。預設值為 PYTHON

  • batch_size - 推理批次大小。預設值為 1

  • max_batch_delay - 批次聚合的最大延遲。預設值為 100 毫秒。

  • initial_workers - 建立的初始 worker 數量。預設值為 0。TorchServe 在至少分配一個 worker 之前不會執行推理。

  • synchronous - worker 的建立是否是同步的。預設值為 false。TorchServe 將建立新的 worker,而無需等待確認上一個 worker 已線上。

  • response_timeout - 如果模型的後端 worker 在此超時期間內未響應推理響應,則該 worker 將被視為無響應並重新啟動。單位為秒。預設值為 120 秒。

  • startup_timeout - 如果模型的後端 worker 在此超時期間內未載入模型,則該 worker 將被視為無響應並重新啟動。單位為秒。預設值為 120 秒。

curl -X POST  "https://: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 URL 是 https://torchserve.pytorch.org/sse-test/squeezenet1_1.mar

  • 如果 torchserve 將在 EC2 例項上執行(例如 作業系統:ubuntu)

  1. 為 EC2 例項新增 IAM 角色 (AWSS3ReadOnlyAccess)

  2. 執行 ts_scripts/get_aws_credential.sh 匯出 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY

  3. 匯出 AWS_DEFAULT_REGION=您的_s3_桶區域

  4. 啟動 torchserve

  5. 在 curl 命令中設定 s3_sse_kms=true 註冊加密模型 squeezenet1_1。

curl -X POST  "https://: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."
}
  • 如果 torchserve 將在本地執行(例如 作業系統:macOS)

  1. 找到您的 AWS 訪問金鑰和秘密金鑰。如果您忘記了金鑰,可以重置它們

  2. 匯出 AWS_ACCESS_KEY_ID=您的_aws_訪問金鑰

  3. 匯出 AWS_SECRET_ACCESS_KEY=您的_aws_秘密金鑰

  4. 匯出 AWS_DEFAULT_REGION=您的_s3_桶區域

  5. 啟動 torchserve

  6. 在 curl 命令中設定 s3_sse_kms=true 註冊加密模型 squeezenet1_1(與 EC2 示例步驟 5 相同)。

您可能希望在註冊期間建立 worker。因為建立初始 worker 可能需要一些時間,您可以選擇同步或非同步呼叫以確保初始 worker 正確建立。

非同步呼叫在嘗試建立 worker 之前返回 HTTP 程式碼 202。

curl -v -X POST "https://: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..."
}

同步呼叫在所有 worker 已調整後返回 HTTP 程式碼 200。

curl -v -X POST "https://: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"
}

擴縮 worker

此 API 遵循 ManagementAPIsService.ScaleWorker gRPC API。它返回 ModelServer 中模型的狀態。

PUT /models/{model_name}

  • min_worker - (可選)worker 程序的最小數量。TorchServe 將嘗試為指定模型維持此最小值。預設值為 1

  • max_worker - (可選)worker 程序的最大數量。TorchServe 為指定模型建立的 worker 數量不會超過此值。預設值與 min_worker 的設定相同。

  • synchronous - 呼叫是否是同步的。預設值為 false

  • timeout - 為 worker 完成所有待處理請求指定的等待時間。如果超出,worker 程序將被終止。使用 0 可立即終止後端 worker 程序。使用 -1 可無限等待。預設值為 -1

使用擴縮 Worker API 動態調整模型任意版本的 worker 數量,以更好地服務不同的推理請求負載。

此 API 有兩種不同型別:同步和非同步。

非同步呼叫將立即返回 HTTP 程式碼 202

curl -v -X PUT "https://: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..."
}

同步呼叫在所有 worker 已調整後返回 HTTP 程式碼 200。

curl -v -X PUT "https://: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"
}

要擴縮模型的特定版本的 worker,請使用 URI : /models/{model_name}/{version} PUT /models/{model_name}/{version}

以下同步呼叫將在模型“noop”的版本“2.0”的所有 worker 都調整完畢後返回 HTTP 程式碼 200。

curl -v -X PUT "https://: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}

使用描述模型 API 獲取模型的預設版本的詳細執行時狀態

curl https://: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}

使用描述模型 API 獲取模型的特定版本的詳細執行時狀態

curl https://: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

使用描述模型 API 獲取模型所有版本的詳細執行時狀態

curl https://: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=trueGET /models/{model_name}?customized=true

使用描述模型 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
  • 如果 handler 沒有繼承自 BaseHandler,則實現函式 _is_describe。然後,在 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
  • 在 handle 中呼叫函式 _is_describe 和 describe_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 https://: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}"
     }
]
  • 在客戶端解碼 customizedMetadata。例如:

import requests
import json

response = requests.get('https://:8081/models/noop-customized/?customized=true').json()
customizedMetadata = response[0]['customizedMetadata']
print(customizedMetadata)

登出模型

此 API 遵循 ManagementAPIsService.UnregisterModel gRPC API。它返回 ModelServer 中模型的狀態。

TorchServe 啟動後要使用此 API,必須啟用模型 API 控制。在啟動 TorchServe 時,向命令列新增 --enable-model-api 以啟用此 API 的使用。有關更多詳細資訊,請參閱 模型 API 控制

DELETE /models/{model_name}/{version}

使用登出模型 API 透過從 TorchServe 登出模型的特定版本來釋放系統資源

curl -X DELETE https://:8081/models/noop/1.0

{
  "status": "Model \"noop\" unregistered"
}

列出模型

此 API 遵循 ManagementAPIsService.ListModels gRPC API。它返回 ModelServer 中模型的狀態。

GET /models

  • limit - (可選)返回的最大專案數。它作為查詢引數傳遞。預設值為 100

  • next_page_token - (可選)查詢下一頁。它作為查詢引數傳遞。此值由先前的 API 呼叫返回。

使用 Models API 查詢當前註冊模型的預設版本

curl "https://:8081/models"

此 API 支援分頁

curl "https://: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 https://:8080

# To view all management APIs:
curl -X OPTIONS https://: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 https://:8081/models/noop/2.0/set-default

輸出是 OpenAPI 3.0.1 json 格式。您可以使用它來生成客戶端程式碼,詳細資訊請參閱 swagger codegen

Token 授權 API

TorchServe 現在預設強制執行 token 授權。檢視以下文件瞭解更多資訊:Token 授權

此 API 用於生成新金鑰以替換管理或推理金鑰。

管理示例

curl localhost:8081/token?type=management -H "Authorization: Bearer {API Token}"

將用新金鑰替換 key_file 中的當前管理金鑰,並更新過期時間。

推理示例

curl localhost:8081/token?type=inference -H "Authorization: Bearer {API Token}"

將用新金鑰替換 key_file 中的當前推理金鑰,並更新過期時間。

文件

查閱 PyTorch 的全面開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深度教程

檢視教程

資源

查詢開發資源並獲取問題解答

檢視資源