Bird
Raised Fist0
PyTorchml~20 mins

TorchServe setup in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - TorchServe setup
Problem:You want to deploy a PyTorch model so it can serve predictions through a web API using TorchServe.
Current Metrics:No deployment yet, so no serving or prediction metrics available.
Issue:Model is trained but not yet deployed for real-time inference. You need to package and serve it properly.
Your Task
Set up TorchServe to deploy a PyTorch model and test that it returns correct predictions via API.
Use a simple pretrained model (e.g., a small CNN or a pretrained ResNet).
Create a model archive (.mar) file using TorchServe tools.
Serve the model locally using TorchServe.
Test the API with sample input and get prediction output.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
PyTorch
import torch
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
import requests
import json
import os

# Step 1: Save a pretrained model
model = models.resnet18(pretrained=True)
model.eval()

model_path = 'resnet18.pth'
torch.save(model.state_dict(), model_path)

# Step 2: Create a model archive using torch-model-archiver (run in shell):
# torch-model-archiver --model-name resnet18 --version 1.0 --serialized-file resnet18.pth --handler image_classifier --export-path model_store --extra-files index_to_name.json

# Note: You need to provide index_to_name.json mapping file for the image_classifier handler.

# Step 3: Start TorchServe (run in shell):
# torchserve --start --model-store model_store --models resnet18=resnet18.mar

# Step 4: Prepare an image for prediction
image_url = 'https://pytorch.org/assets/images/deeplab1.png'
image_path = 'test_image.png'

if not os.path.exists(image_path):
    img_data = requests.get(image_url).content
    with open(image_path, 'wb') as f:
        f.write(img_data)

# Step 5: Send image to TorchServe API
with open(image_path, 'rb') as f:
    image_bytes = f.read()

response = requests.post('http://127.0.0.1:8080/predictions/resnet18', data=image_bytes)

print('Prediction response:', response.text)

# Step 6: Stop TorchServe (run in shell):
# torchserve --stop
Saved pretrained ResNet18 model state_dict instead of TorchScript for compatibility with default image_classifier handler.
Added note about providing index_to_name.json mapping file required by image_classifier handler.
Kept other steps unchanged.
Results Interpretation

Before: Model trained but no deployment or serving.

After: Model deployed with TorchServe, serving predictions via REST API successfully.

TorchServe simplifies deploying PyTorch models for real-time inference by packaging models and providing a REST API for predictions.
Bonus Experiment
Try creating a custom handler to preprocess input images differently or postprocess outputs before returning predictions.
💡 Hint
Write a Python handler class inheriting from BaseHandler and specify it during model archiving.

Practice

(1/5)
1. What is the main purpose of TorchServe in PyTorch model deployment?
easy
A. To convert PyTorch models into TensorFlow format
B. To train PyTorch models faster on GPUs
C. To visualize PyTorch model architectures
D. To package and serve PyTorch models for easy deployment

Solution

  1. Step 1: Understand TorchServe's role

    TorchServe is designed to help deploy PyTorch models by packaging them and serving predictions.
  2. Step 2: Compare options

    Options B, C, and D describe unrelated tasks like training speed, visualization, or conversion, which TorchServe does not do.
  3. Final Answer:

    To package and serve PyTorch models for easy deployment -> Option D
  4. Quick Check:

    TorchServe = model packaging and serving [OK]
Hint: TorchServe is for deployment, not training or conversion [OK]
Common Mistakes:
  • Confusing TorchServe with training tools
  • Thinking TorchServe converts model formats
  • Assuming TorchServe visualizes models
2. Which command is used to create a model archive (.mar) file for TorchServe?
easy
A. torchserve --start
B. torch-model-archiver
C. python setup.py build
D. torch.save(model, 'model.pth')

Solution

  1. Step 1: Identify the command for packaging models

    The torch-model-archiver command creates the .mar file needed by TorchServe.
  2. Step 2: Eliminate other commands

    torchserve --start starts the server, python setup.py build is unrelated, and torch.save saves a model but not as a .mar archive.
  3. Final Answer:

    torch-model-archiver -> Option B
  4. Quick Check:

    Model archive = torch-model-archiver [OK]
Hint: Use torch-model-archiver to package models [OK]
Common Mistakes:
  • Using torchserve to create archives
  • Confusing torch.save with archiving
  • Running unrelated Python build commands
3. Given the following commands, what will be the output after starting TorchServe?
!torch-model-archiver --model-name mymodel --version 1.0 --serialized-file model.pth --handler handler.py --export-path model_store
!torchserve --start --model-store model_store --models mymodel=mymodel-1.0.mar
What happens when you send a prediction request to the server?
medium
A. The server returns predictions from the loaded model
B. The server throws an error because model_store is missing
C. The server starts but does not load any model
D. The server converts the model to ONNX format

Solution

  1. Step 1: Understand the archiving and serving commands

    The first command creates a .mar file in model_store. The second starts TorchServe loading that model.
  2. Step 2: Predict server behavior on request

    Since the model is loaded, the server will respond with predictions when given input data.
  3. Final Answer:

    The server returns predictions from the loaded model -> Option A
  4. Quick Check:

    Model archived and loaded = predictions served [OK]
Hint: Archive then start server to serve predictions [OK]
Common Mistakes:
  • Assuming model_store folder is missing
  • Thinking server starts without loading models
  • Believing TorchServe converts model formats
4. You run torchserve --start --model-store model_store --models mymodel=mymodel.mar but get an error: ModelNotFoundError. What is the most likely cause?
medium
A. The handler.py file is missing
B. TorchServe is not installed
C. The .mar file is not in the model_store directory
D. The model name is misspelled in the command

Solution

  1. Step 1: Analyze the error message

    ModelNotFoundError means TorchServe cannot find the specified .mar file in the model_store directory.
  2. Step 2: Check command and files

    If the .mar file is missing or not placed in model_store, the server cannot load it. Misspelling or missing handler causes different errors.
  3. Final Answer:

    The .mar file is not in the model_store directory -> Option C
  4. Quick Check:

    ModelNotFoundError = missing .mar file [OK]
Hint: Ensure .mar file is inside model_store folder [OK]
Common Mistakes:
  • Ignoring file location for .mar archive
  • Assuming TorchServe installation issue
  • Confusing model name typo with missing file
5. You want to deploy two different PyTorch models simultaneously using TorchServe. Which setup correctly achieves this?
hard
A. Create two .mar files and start TorchServe with --models model1=model1.mar model2=model2.mar
B. Combine both models into one .mar file and start TorchServe with a single model
C. Start two TorchServe servers on the same port, each serving one model
D. Use torch-model-archiver to merge models into a single .pth file

Solution

  1. Step 1: Understand multi-model serving in TorchServe

    TorchServe supports serving multiple models by specifying multiple .mar files with aliases in the --models option.
  2. Step 2: Evaluate options

    Create two .mar files and start TorchServe with --models model1=model1.mar model2=model2.mar correctly uses two .mar files with aliases. Combine both models into one .mar file and start TorchServe with a single model is invalid because .mar files cannot combine models. Start two TorchServe servers on the same port, each serving one model fails because two servers cannot share the same port. Use torch-model-archiver to merge models into a single .pth file is incorrect; torch-model-archiver does not merge models.
  3. Final Answer:

    Create two .mar files and start TorchServe with --models model1=model1.mar model2=model2.mar -> Option A
  4. Quick Check:

    Multiple models = multiple .mar files with aliases [OK]
Hint: Use space-separated model aliases in --models option [OK]
Common Mistakes:
  • Trying to merge models into one .mar file
  • Running multiple servers on same port
  • Misusing torch-model-archiver to combine models
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard