Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch Model Deployment

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

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:

  1. torch.jit.trace More suitable for models without control flow
  2. torch.jit.script Can handle models with complex logic such as conditional branches
  3. 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.