PyTorch Model Deployment
Model deployment is the process of putting a trained machine learning model into practical use. PyTorch provides a variety of tools and methods to achieve this.
Why Model Deployment Is Needed
- Application Integration: integrate AI capabilities into Web, mobile, or embedded systems
- Performance optimization: optimize model inference speed for production environments
- Resource management: effectively utilize computing resources for high-concurrency services
Deployment Process Overview

Model Preparation and Optimization
Model Export Formats
PyTorch mainly supports the following export formats:
| Format | Feature | Applicable scenarios |
|---|---|---|
| TorchScript | PyTorch native format, preserves dynamic graph characteristics | Used internally within the PyTorch ecosystem |
| ONNX | Open standard, cross-framework compatible | Multi-framework collaboration environments |
| Torch-TensorRT | NVIDIA optimized format | GPU inference acceleration |
Export to TorchScript
Example
import
torch
import
torchvision
Load a pre-trained model
model
=
torchvision.
models
.
resnet18
(
pretrained
=
True
)
model.
eval
(
)
Example input
example_input
=
torch.
rand
(
1
,
3
,
224
,
224
)
Method 1: export via tracing
traced_script
=
torch.
jit
.
trace
(
model
,
example_input
)
traced_script.
save
(
"resnet18_traced.pt"
)
Method 2: export via scripting
scripted_model
=
torch.
jit
.
script
(
model
)
scripted_model.
save
(
"resnet18_scripted.pt"
)
Notes:
torch.jit.traceMore suitable for models without control flowtorch.jit.scriptCan handle models with complex logic such as conditional branches- Must call before exporting
model.eval()
Deployment Option Selection
Local Deployment Options
LibTorch (C++ API)
Example
#include
int
main
(
)
{
// load model
torch
::
jit
::
script
::
Module
module
;
module
=
torch
::
jit
::
load
(
"resnet18.pt"
)
;
// prepare input
std
::
vector
<
torch
::
jit
::
IValue
inputs
;
inputs.
push_back
(
torch
::
ones
(
{
1
,
3
,
224
,
224
}
)
)
;
// run inference
auto
output
=
module.
forward
(
inputs
)
.
toTensor
(
)
;
std
::
cout
<<
output.
slice
(
/dim=/
1
,
/start=/
0
,
/end=/
5
)
<<
'\n'
;
}
ONNX Runtime
Example
import
onnxruntime
as
ort
Create inference session
sess
=
ort.
InferenceSession
(
"model.onnx"
)
Prepare the input
input_name
=
sess.
get_inputs
(
)
[
0
]
.
name
input_data
=
np.
random
.
rand
(
1
,
3
,
224
,
224
)
.
astype
(
np.
float32
)
Run inference
outputs
=
sess.
run
(
None
,
{
input_name: input_data
}
)
Cloud Deployment Options
TorchServe (official serving framework)
Example
Installation
pip
install
torchserve torch-model-archiver
Package the model
torch-model-archiver
--model-name
resnet18 \
--version
1.0
\
--serialized-file
model.pth \
--extra-files
index_to_name.json \
--handler
image_classifier \
--export-path
model_store
Start the service
torchserve
--start
--model-store
model_store
--models
resnet18
=resnet18.mar
Build a REST API with FastAPI
Example
from
fastapi
import
FastAPI
from
PIL
import
Image
import
io
import
torch
app
=
FastAPI
(
)
model
=
torch.
jit
.
load
(
"model.pt"
)
@
app.
post
(
"/predict"
)
async
def
predict
(
image: UploadFile
=
File
(
...
)
)
:
img_data
=
await image.
read
(
)
img
=
Image.
open
(
io.
BytesIO
(
img_data
)
)
Preprocessing...
with
torch.
no_grad
(
)
:
output
=
model
(
img_tensor
)
return
{
"prediction"
: output.
argmax
(
)
.
item
(
)
}
Performance optimization tips
Quantization Acceleration
Example
Dynamic quantization
quantized_model
=
torch.
quantization
.
quantize_dynamic
(
model
,
{
torch.
nn
.
Linear
}
,
dtype
=
torch.
qint8
)
Static quantization
model.
qconfig
=
torch.
quantization
.
get_default_qconfig
(
'fbgemm'
)
torch.
quantization
.
prepare
(
model
,
inplace
=
True
)
Calibration...
torch.
quantization
.
convert
(
model
,
inplace
=
True
)
Acceleration with TensorRT
Example
import
torch_tensorrt
Compilation optimization
trt_model
=
torch_tensorrt.
compile
(
model
,
inputs
=
[
torch_tensorrt.
Input
(
(
1
,
3
,
224
,
224
)
)
]
,
enabled_precisions
=
{
torch.
float32
}
or {torch.float16}
)
Save the optimized model
torch.
jit
.
save
(
trt_model
,
"model_trt.pt"
)
Frequently Asked Questions
Q1: What should I do about version compatibility issues during deployment? A: It is recommended to use Docker containers to pin environment versions, or use conda to create a dedicated environment.
Q2: How to monitor the performance of deployed models? A: You can integrate monitoring tools such as Prometheus to track latency, throughput, and resource usage.
Q3: How to achieve hot updates after model deployment? A: TorchServe supports model version management and A/B testing, allowing dynamic switching of model versions via API.