0
0
PyTorchml~20 mins

REST API inference in PyTorch - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
REST API Inference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Flask REST API inference code?
Consider this simple Flask app that loads a PyTorch model and returns predictions for input data sent as JSON. What will be the JSON response when sending {"input": [1.0, 2.0, 3.0]}?
PyTorch
from flask import Flask, request, jsonify
import torch
import torch.nn as nn

app = Flask(__name__)

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(3, 1)
    def forward(self, x):
        return self.linear(x)

model = SimpleModel()
model.linear.weight.data.fill_(1.0)
model.linear.bias.data.fill_(0.0)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    x = torch.tensor(data['input'], dtype=torch.float32)
    with torch.no_grad():
        output = model(x).item()
    return jsonify({'prediction': output})
A{"prediction": 1.0}
B{"prediction": 3.0}
C{"prediction": 0.0}
D{"prediction": 6.0}
Attempts:
2 left
💡 Hint
Remember the linear layer sums weighted inputs plus bias. Weights are all 1, bias is 0.
Model Choice
intermediate
1:30remaining
Which PyTorch model is best suited for REST API inference on image classification?
You want to deploy a REST API that receives images and returns predicted labels. Which model architecture below is most appropriate for this task?
AA linear regression model
BA recurrent neural network (RNN) like LSTM
CA convolutional neural network (CNN) like ResNet
DA k-means clustering model
Attempts:
2 left
💡 Hint
Think about which model type handles image data well.
Hyperparameter
advanced
1:30remaining
Which batch size is best for fast REST API inference with PyTorch?
You deploy a REST API for inference. To optimize latency and throughput, which batch size should you choose?
ABatch size of 1 for lowest latency per request
BBatch size of 128 to maximize GPU utilization
CBatch size of 0 to disable batching
DBatch size of 1000 to process many requests at once
Attempts:
2 left
💡 Hint
Consider that REST API requests usually come one at a time and latency matters.
🔧 Debug
advanced
2:00remaining
Why does this PyTorch REST API inference code raise a RuntimeError?
Given this code snippet, why does the server raise a RuntimeError: "Trying to backward through the graph during inference"?
PyTorch
from flask import Flask, request, jsonify
import torch
import torch.nn as nn

app = Flask(__name__)

model = nn.Linear(2, 1)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    x = torch.tensor(data['input'], dtype=torch.float32)
    with torch.no_grad():
        output = model(x)
    return jsonify({'prediction': output.item()})
AFlask cannot handle POST requests without JSON schema validation
BThe code is missing torch.no_grad() context, so autograd tries to track operations
CThe input tensor x has wrong dtype causing runtime error
DThe model is not in eval() mode causing training behavior
Attempts:
2 left
💡 Hint
Inference should not track gradients to save memory and avoid errors.
Metrics
expert
2:00remaining
Which metric is best to monitor REST API inference quality for a multi-class classification model?
You deploy a REST API serving a multi-class classifier. Which metric below best measures the model's prediction quality on live data?
AAccuracy - percentage of correct predictions
BMean Squared Error (MSE)
CSilhouette Score
DBLEU Score
Attempts:
2 left
💡 Hint
Think about classification metrics that reflect correct label predictions.