Skip to content

Commit f60da86

Browse files
committed
[mobile_perf][recipe] Add ChannelsLast recommendation
1 parent 6285b8f commit f60da86

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

recipes_source/mobile_perf.rst

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ Code your model:
4949
self.dequant = torch.quantization.DeQuantStub()
5050

5151
def forward(self, x):
52+
x.contiguous(memory_format=torch.channels_last)
5253
x = self.quant(x)
5354
x = self.conv(x)
5455
x = self.bn(x)
@@ -129,9 +130,24 @@ Next we call ``optimize_for_mobile`` and save model on the disk.
129130
torchscript_model_optimized = optimize_for_mobile(torchscript_model)
130131
torch.jit.save(torchscript_model_optimized, "model.pt")
131132

133+
4. Prefer Using Channels Last Tensor memory format
134+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
132135

133-
4. Android. Reusing tensors for forward.
134-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136+
Channels Last(NHWC) memory format was introduced in PyTorch 1.4.0. It is supported only for four-dimensional tensors. This memory format gives a better memory locality for most operators, especially convolution. Our measurements showed a 3x speedup of MobileNetV2 model compared with the default Channels First(NCHW) format.
137+
138+
At the moment of writing this recipe, PyTorch Android java API does not support using inputs in Channels Last memory format. But it can be used on the TorchScript model level, by adding the conversion to it for model inputs.
139+
140+
.. code-block:: python
141+
142+
def forward(self, x):
143+
x.contiguous(memory_format=torch.channels_last)
144+
...
145+
146+
147+
This conversion is zero cost if your input is already in Chanels Last memory format. After it, all operators will work preserving ChannelsLast memory format.
148+
149+
5. Android. Reusing tensors for forward
150+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
135151

136152
This recipe is Android only.
137153
Memory is a critical resource for android performance, especially on old devices.

0 commit comments

Comments
 (0)