Skip to content

Commit f11a36c

Browse files
committed
[mobile] Mobile Perf Recipe
1 parent f7d7360 commit f11a36c

File tree

3 files changed

+228
-0
lines changed

3 files changed

+228
-0
lines changed

recipes_source/mobile_perf.rst

+217
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
Pytorch Mobile Performance Recipes
2+
==================================
3+
4+
Introduction
5+
------------
6+
Performance (aka latency) is crucial to most, if not all,
7+
applications and use-cases of ML model inference on mobile devices.
8+
9+
Today, PyTorch executes the models on the CPU backend pending availability
10+
of other hardware backends such as GPU, DSP, and NPU.
11+
12+
13+
Model preparation
14+
-----------------
15+
16+
Next recipes you can take (offline) while preparing the model
17+
to have an optimized model that will probably have shorter execution time
18+
(higher performance, lower latency) on the mobile device.
19+
20+
21+
Setup
22+
_____
23+
First we need to installed pytorch using conda or pip with version at least 1.5.0.
24+
25+
::
26+
27+
conda install pytorch torchvision -c pytorch
28+
29+
or
30+
31+
::
32+
33+
pip install torch torchvision
34+
35+
Code your model:
36+
37+
::
38+
39+
import torch
40+
from torch.utils.mobile_optimizer import optimize_for_mobile
41+
42+
class AnnotatedConvBnReLUModel(torch.nn.Module):
43+
def __init__(self):
44+
super(AnnotatedConvBnReLUModel, self).__init__()
45+
self.conv = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float)
46+
self.bn = torch.nn.BatchNorm2d(5).to(dtype=torch.float)
47+
self.relu = torch.nn.ReLU(inplace=True)
48+
self.quant = torch.quantization.QuantStub()
49+
self.dequant = torch.quantization.DeQuantStub()
50+
51+
def forward(self, x):
52+
x = self.quant(x)
53+
x = self.conv(x)
54+
x = self.bn(x)
55+
x = self.relu(x)
56+
x = self.dequant(x)
57+
return x
58+
59+
model = AnnotatedConvBnReLUModel()
60+
61+
62+
``torch.quantization.QuantStub`` and ``torch.quantization.DeQuantStub()`` are no-op stubs, which will be used for quantization step.
63+
64+
65+
1. Fuse operators using ``torch.quantization.fuse_modules``
66+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
67+
68+
Do not be confused that fuse_modules is in the quantization package.
69+
It works for all ``torcn.nn.Module``.
70+
71+
``torch.quantization.fuse_modules`` fuses a list of modules into a single module.
72+
It fuses only the following sequence of modules:
73+
74+
- Convolution, Batch normalization
75+
- Convolution, Batch normalization, Relu
76+
- Convolution, Relu
77+
- Linear, Relu
78+
79+
This script will fuse Convolution, Batch Noarmalization and Relu in previously declared model.
80+
81+
::
82+
83+
torch.quantization.fuse_modules(model, [['conv', 'bn', 'relu']], inplace=True)
84+
85+
86+
2. Quantize your model
87+
~~~~~~~~~~~~~~~~~~~~~~
88+
89+
You can find more about PyTorch quantization in
90+
`the dedicated tutorial <https://pytorch.org/blog/introduction-to-quantization-on-pytorch/>`_.
91+
92+
Quantization of the model not only moves computation to int8,
93+
but also reduces the size of your model on a disk.
94+
That size reduction helps to reduce disk read operations during the first load of the model and decreases the amount of RAM.
95+
Both of those resources can be crucial for the performance of mobile applications.
96+
97+
::
98+
99+
model.qconfig = torch.quantization.get_default_qconfig('qnnpack')
100+
torch.quantization.prepare(model)
101+
torch.quantization.convert(model)
102+
103+
104+
105+
3. Use torch.utils.mobile_optimizer
106+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107+
108+
Torch mobile_optimizer package does several optimizations with the scripted model,
109+
which will help to conv2d and linear operations.
110+
It pre-packs model weights in an optimized format and fuses ops above with relu
111+
if it is the next operation.
112+
113+
First we script the result model from previous step:
114+
115+
::
116+
117+
torchscript_model = torch.jit.script(model)
118+
119+
Next we call ``optimize_for_mobile`` and save model on the disk.
120+
121+
::
122+
123+
torchscript_model_optimized = optimize_for_mobile(torchscript_model)
124+
torch.jit.save(torchscript_model_optimized, "model.pt")
125+
126+
127+
4. Android. Reusing tensors for forward.
128+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
129+
130+
This recipe is Android only.
131+
Memory is a critical resource for android performance, especially on old devices.
132+
Tensors can need a significant amount of memory.
133+
For example, standard computer vision tensor contains 1*3*224*224 elements,
134+
assuming that data type is float and will need 588Kb of memory.
135+
136+
::
137+
138+
FloatBuffer buffer = Tensor.allocateFloatBuffer(1*3*224*224);
139+
Tensor tensor = Tensor.fromBlob(buffer, new long[]{1, 3, 224, 224});
140+
141+
142+
Here we allocate native memory as ``java.nio.FloatBuffer`` and creating ``org.pytorch.Tensor`` which storage will be pointing to the memory of the allocated buffer.
143+
144+
For most of the use cases, we do not do model forward only once, repeating it with some frequency or as fast as possible.
145+
146+
If we are doing new memory allocation for every module forward - that will be suboptimal.
147+
Instead of this, we can reuse the same memory that we allocated on the previous step, fill it with new data, and run module forward again on the same tensor object.
148+
149+
You can check how it looks in code in `pytorch android application example <https://github.com/pytorch/android-demo-app/blob/master/PyTorchDemoApp/app/src/main/java/org/pytorch/demo/vision/ImageClassificationActivity.java#L174>`_.
150+
151+
::
152+
153+
protected AnalysisResult analyzeImage(ImageProxy image, int rotationDegrees) {
154+
if (mModule == null) {
155+
mModule = Module.load(moduleFileAbsoluteFilePath);
156+
mInputTensorBuffer =
157+
Tensor.allocateFloatBuffer(3 * 224 * 224);
158+
mInputTensor = Tensor.fromBlob(mInputTensorBuffer, new long[]{1, 3, 224, 224});
159+
}
160+
161+
TensorImageUtils.imageYUV420CenterCropToFloatBuffer(
162+
image.getImage(), rotationDegrees,
163+
224, 224,
164+
TensorImageUtils.TORCHVISION_NORM_MEAN_RGB,
165+
TensorImageUtils.TORCHVISION_NORM_STD_RGB,
166+
mInputTensorBuffer, 0);
167+
168+
Tensor outputTensor = mModule.forward(IValue.from(mInputTensor)).toTensor();
169+
}
170+
171+
Member fields ``mModule``, ``mInputTensorBuffer`` and ``mInputTensor`` are initialized only once
172+
and buffer is refilled using ``org.pytorch.torchvision.TensorImageUtils.imageYUV420CenterCropToFloatBuffer``.
173+
174+
Benchmarking
175+
------------
176+
177+
The best way to benchmark (to check if optimizations helped your use case) - to measure your particular use case that you want to optimize, as performance behavior can vary in different environments.
178+
179+
PyTorch distribution provides a way to benchmark naked binary that runs the model forward,
180+
this approach can give more stable measurements rather than testing inside the application.
181+
182+
183+
Android
184+
-------
185+
186+
For this you first need to build benchmark binary:
187+
188+
::
189+
190+
<from-your-root-pytorch-dir>
191+
rm -rf build_android
192+
BUILD_PYTORCH_MOBILE=1 ANDROID_ABI=arm64-v8a ./scripts/build_android.sh -DBUILD_BINARY=ON
193+
194+
You should have arm64 binary at: ``build_android/bin/speed_benchmark_torch``.
195+
This binary takes ``--model=<path-to-model>``, ``--input_dim="1,3,224,224"`` as dimension information for the input and ``--input_type="float"`` as the type of the input as arguments.
196+
197+
Once you have your android device connected,
198+
push speedbenchark_torch binary and your model to the phone:
199+
200+
::
201+
202+
adb push <speedbenchmark-torch> /data/local/tmp
203+
adb push <path-to-scripted-model> /data/local/tmp
204+
205+
206+
Now we are ready to benchmark your model:
207+
208+
::
209+
210+
adb shell "/data/local/tmp/speed_benchmark_torch --model="/data/local/tmp/model.pt" --input_dims="1,3,224,224" --input_type="float"
211+
----- output -----
212+
Starting benchmark.
213+
Running warmup runs.
214+
Main runs.
215+
Main run finished. Microseconds per iter: 121318. Iters per second: 8.24281
216+
217+

recipes_source/recipes/README.txt

+4
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,7 @@ PyTorch Recipes
5252
13. zeroing_out_gradients.py
5353
Zeroing out gradients
5454
https://pytorch.org/tutorials/recipes/recipes/zeroing_out_gradients.html
55+
56+
14. mobile_perf.py
57+
PyTorch Mobile Performance Recipes
58+
https://pytorch.org/tutorials/recipes/mobile_perf.html

recipes_source/recipes_index.rst

+7
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,13 @@ Recipes are bite-sized bite-sized, actionable examples of how to use specific Py
146146
:link: ../recipes/deployment_with_flask.html
147147
:tags: Production,TorchScript
148148

149+
.. customcarditem::
150+
:header: PyTorch Mobile Performance Recipes
151+
:card_description: List of recipes for performance optimizations for using PyTorch on Mobile.
152+
:image: ../_static/img/thumbnails/cropped/zeroing-out-gradients.PNG
153+
:link: ../recipes/mobile_perf.html
154+
:tags: Mobile,Model-Optimization
155+
149156

150157
.. End of tutorial card section
151158

0 commit comments

Comments
 (0)