A REST API lets you send data to a machine learning model and get predictions back easily over the internet.
REST API inference in PyTorch
from flask import Flask, request, jsonify import torch app = Flask(__name__) # Load your trained PyTorch model model = torch.load('model.pth') model.eval() @app.route('/predict', methods=['POST']) def predict(): data = request.json # Get JSON data from POST request input_tensor = torch.tensor(data['input'], dtype=torch.float32).unsqueeze(0) # Convert input list to tensor with batch dimension with torch.no_grad(): output = model(input_tensor) prediction = output.argmax(dim=1).item() # Get predicted class return jsonify({'prediction': prediction}) if __name__ == '__main__': app.run(debug=True)
This example uses Flask, a simple web framework for Python.
The model is loaded once and used for all requests to save time.
curl -X POST http://localhost:5000/predict -H "Content-Type: application/json" -d '{"input": [0.5, 1.2, 3.3]}'
import requests response = requests.post('http://localhost:5000/predict', json={'input': [0.5, 1.2, 3.3]}) print(response.json())
This program creates a simple PyTorch model, saves it, then loads it in a Flask app. The app listens for POST requests at /predict, runs the model on input data, and returns the predicted class.
from flask import Flask, request, jsonify import torch import torch.nn as nn # Define a simple model for demonstration class SimpleModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(3, 2) # 3 inputs, 2 classes def forward(self, x): return self.linear(x) app = Flask(__name__) # Create and save a dummy model model = SimpleModel() torch.save(model, 'model.pth') # Load the model model = torch.load('model.pth') model.eval() @app.route('/predict', methods=['POST']) def predict(): data = request.json input_tensor = torch.tensor(data['input'], dtype=torch.float32).unsqueeze(0) # batch size 1 with torch.no_grad(): output = model(input_tensor) prediction = output.argmax(dim=1).item() return jsonify({'prediction': prediction}) if __name__ == '__main__': app.run(debug=False)
Always set your model to evaluation mode with model.eval() before inference.
Use torch.no_grad() to avoid tracking gradients during prediction, which saves memory.
For production, use a more robust server than Flask's built-in one.
A REST API lets you send data and get predictions from your ML model over the web.
Flask is a simple way to create such an API in Python.
Remember to load your model once and use model.eval() and torch.no_grad() for efficient inference.
Practice
Solution
Step 1: Understand REST API role
A REST API allows communication over the web by sending requests and receiving responses.Step 2: Connect REST API with model inference
In PyTorch, a REST API is used to send input data and get predictions from the model remotely.Final Answer:
To send data to the model and receive predictions over the web -> Option BQuick Check:
REST API = Web data exchange for predictions [OK]
- Confusing inference with training
- Thinking REST API is for saving models
- Assuming REST API visualizes models
Solution
Step 1: Identify how to disable gradients
PyTorch usestorch.no_grad()context to turn off gradient tracking during inference.Step 2: Check other options
model.train()enables training mode,torch.enable_grad()enables gradients, andmodel.backward()is invalid.Final Answer:
with torch.no_grad(): -> Option AQuick Check:
Disable gradients = torch.no_grad() [OK]
- Using model.train() instead of model.eval()
- Not disabling gradients causing slow inference
- Calling backward() during inference
from flask import Flask, request, jsonify
import torch
app = Flask(__name__)
model = torch.nn.Linear(2, 1)
model.eval()
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
x = torch.tensor(data['input']).unsqueeze(0).float()
with torch.no_grad():
output = model(x)
return jsonify({'prediction': output.item()})Solution
Step 1: Understand input and output processing
The input JSON is converted to a tensor with shape (1, 2). The model outputs a tensor with shape (1, 1).Step 2: Check output conversion
The output tensor's single value is extracted usingoutput.item(), which returns a float, then wrapped in JSON.Final Answer:
{"prediction": 3.0} -> Option DQuick Check:
output.item() returns float for JSON [OK]
- Returning tensor object directly in JSON
- Forgetting to convert input to tensor
- Not using torch.no_grad() causing slow inference
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
x = torch.tensor(data['input'])
with torch.no_grad():
output = model(x)
return jsonify({'prediction': output.item()})Solution
Step 1: Understand the error cause
The model expects float tensors but input tensor is double (default from Python floats).Step 2: Fix input tensor type
Convert input tensor to float type using.float()before passing to the model.Final Answer:
Convert input tensor to float using .float() before passing to model -> Option AQuick Check:
Tensor dtype mismatch fixed by .float() [OK]
- Not converting input data type
- Calling model.train() during inference
- Removing torch.no_grad() causing slow inference
Solution
Step 1: Model loading and mode
Load the model once globally to avoid overhead and set it to evaluation mode withmodel.eval().Step 2: Input preprocessing and inference
Preprocess the input image to a tensor, usetorch.no_grad()to disable gradients, get prediction, and return JSON response.Final Answer:
Load model once globally, set model.eval(), preprocess input image to tensor, use torch.no_grad(), get prediction, return JSON -> Option CQuick Check:
Efficient inference = global load + eval + no_grad + preprocess [OK]
- Loading model on every request causing slow response
- Using model.train() during inference
- Not preprocessing input to tensor
- Calling backward() during inference
Ready to prove it?
Pass the test and this pattern moves unknown
