

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# TorchServe
<a name="tutorial-torchserve"></a>

TorchServe 是一種靈活的工具，用於提供已從 PyTorch 匯出的深度學習模型。TorchServe 已預先安裝具有 Conda 的深度學習 AMI。

如需使用 TorchServe 的詳細資訊，請參閱 [Model Server for PyTorch 文件](https://github.com/pytorch/serve/blob/master/docs/README.md)。

 **主題** 

## 在 TorchServe 上提供影像分類模型
<a name="tutorial-torchserve-serving"></a>

本教學課程說明如何使用 TorchServe 提供影像分類模型。它使用 PyTorch 提供的 DenseNet-161 模型。 一旦伺服器執行，它會監聽預測請求。當您上傳映像時，在此案例中是小貓的映像，伺服器會從訓練模型的類別中傳回前 5 個相符類別的預測。

**在 TorchServe 上提供範例影像分類模型**

1. 使用 Conda v34 或更新版本的深度學習 AMI 連線至 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。

1. 啟用環境 `pytorch_p310`。

   ```
   source activate pytorch_p310
   ```

1. 複製 TorchServe 儲存庫，然後建立目錄來存放模型。  

   ```
   git clone https://github.com/pytorch/serve.git
   mkdir model_store
   ```

1. 使用模型封存程式封存模型。`extra-files` 此參數使用來自`TorchServe`儲存庫的檔案，因此請視需要更新路徑。 如需模型封存器的詳細資訊，請參閱[適用於 TorchServe 的 Torch 模型封存器。](https://github.com/pytorch/serve/blob/master/model-archiver/README.md)

   ```
   wget https://download.pytorch.org/models/densenet161-8d451a50.pth
   torch-model-archiver --model-name densenet161 --version 1.0 --model-file ./serve/examples/image_classifier/densenet_161/model.py --serialized-file densenet161-8d451a50.pth --export-path model_store --extra-files ./serve/examples/image_classifier/index_to_name.json --handler image_classifier
   ```

1. 執行 TorchServe 以啟動端點。新增 `> /dev/null` 可靜音日誌輸出。

   ```
   torchserve --start --ncs --model-store model_store --models densenet161.mar > /dev/null
   ```

1. 下載小貓的影像並將其傳送至 TorchServe 預測端點：

   ```
   curl -O https://s3.amazonaws.com/model-server/inputs/kitten.jpg
   curl http://127.0.0.1:8080/predictions/densenet161 -T kitten.jpg
   ```

   預測端點會以類似下列前五大預測的 JSON 傳回預測，其中映像包含埃及貓的機率為 47%，接著有 46% 的機率具有 Tabby 貓。

   ```
   {
    "tiger_cat": 0.46933576464653015,
    "tabby": 0.463387668132782,
    "Egyptian_cat": 0.0645613968372345,
    "lynx": 0.0012828196631744504,
    "plastic_bag": 0.00023323058849200606
   }
   ```

1. 完成測試後，請停止伺服器：

   ```
   torchserve --stop
   ```

 **其他範例** 

TorchServe 有各種範例，您可以在 DLAMI 執行個體上執行。您可以在 [ TorchServe 專案儲存庫範例頁面上](https://github.com/pytorch/serve/tree/master/examples)檢視它們。

 **詳細資訊** 

 如需更多 TorchServe 文件，包括如何使用 Docker 設定 TorchServe 和最新的 TorchServe 功能，請參閱 GitHub 上的 [ TorchServe 專案頁面](https://github.com/pytorch/serve)。