Compute Library
 21.02
graph_shufflenet.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-2021 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include "arm_compute/graph.h"
27 #include "utils/GraphUtils.h"
28 #include "utils/Utils.h"
29 
30 using namespace arm_compute::utils;
31 using namespace arm_compute::graph::frontend;
32 using namespace arm_compute::graph_utils;
33 
34 /** Example demonstrating how to implement ShuffleNet network using the Compute Library's graph API */
35 class ShuffleNetExample : public Example
36 {
37 public:
38  ShuffleNetExample()
39  : cmd_parser(), common_opts(cmd_parser), common_params(), graph(0, "ShuffleNet")
40  {
41  }
42  bool do_setup(int argc, char **argv) override
43  {
44  // Parse arguments
45  cmd_parser.parse(argc, argv);
46  cmd_parser.validate();
47 
48  // Consume common parameters
49  common_params = consume_common_graph_parameters(common_opts);
50 
51  // Return when help menu is requested
52  if(common_params.help)
53  {
54  cmd_parser.print_help(argv[0]);
55  return false;
56  }
57 
58  // Set default layout if needed (Single kernel grouped convolution not yet supported int NHWC)
59  if(!common_opts.data_layout->is_set())
60  {
61  common_params.data_layout = DataLayout::NHWC;
62  }
63 
64  // Checks
65  ARM_COMPUTE_EXIT_ON_MSG(arm_compute::is_data_type_quantized_asymmetric(common_params.data_type), "QASYMM8 not supported for this graph");
66 
67  // Print parameter values
68  std::cout << common_params << std::endl;
69  std::cout << "Model: Shufflenet_1_g4" << std::endl;
70 
71  // Create model path
72  std::string model_path = "/cnn_data/shufflenet_model/";
73 
74  // Get trainable parameters data path
75  std::string data_path = common_params.data_path;
76 
77  // Add model path to data path
78  if(!data_path.empty())
79  {
80  data_path += model_path;
81  }
82 
83  // Create input descriptor
84  const auto operation_layout = common_params.data_layout;
85  const TensorShape tensor_shape = permute_shape(TensorShape(224U, 224U, 3U, 1U), DataLayout::NCHW, operation_layout);
86  TensorDescriptor input_descriptor = TensorDescriptor(tensor_shape, common_params.data_type).set_layout(operation_layout);
87 
88  // Set weights trained layout
89  const DataLayout weights_layout = DataLayout::NCHW;
90 
91  // Create preprocessor
92  std::unique_ptr<IPreprocessor> preprocessor = std::make_unique<TFPreproccessor>(0);
93 
94  graph << common_params.target
95  << common_params.fast_math_hint
96  << InputLayer(input_descriptor, get_input_accessor(common_params, std::move(preprocessor), false /* Do not convert to BGR */))
98  3U, 3U, 24U,
99  get_weights_accessor(data_path, "conv3_0_w_0.npy", weights_layout),
100  get_weights_accessor(data_path, "conv3_0_b_0.npy", weights_layout),
101  PadStrideInfo(2, 2, 1, 1))
102  .set_name("Conv1/convolution")
104  get_weights_accessor(data_path, "conv3_0_bn_rm_0.npy"),
105  get_weights_accessor(data_path, "conv3_0_bn_riv_0.npy"),
106  get_weights_accessor(data_path, "conv3_0_bn_s_0.npy"),
107  get_weights_accessor(data_path, "conv3_0_bn_b_0.npy"),
108  1e-5f)
109  .set_name("Conv1/BatchNorm")
110  << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name("Conv1/Relu")
111  << PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, operation_layout, PadStrideInfo(2, 2, 1, 1))).set_name("pool1/MaxPool");
112 
113  // Stage 2
114  add_residual_block(data_path, DataLayout::NCHW, 0U /* unit */, 112U /* depth */, 2U /* stride */);
115  add_residual_block(data_path, DataLayout::NCHW, 1U /* unit */, 136U /* depth */, 1U /* stride */);
116  add_residual_block(data_path, DataLayout::NCHW, 2U /* unit */, 136U /* depth */, 1U /* stride */);
117  add_residual_block(data_path, DataLayout::NCHW, 3U /* unit */, 136U /* depth */, 1U /* stride */);
118 
119  // Stage 3
120  add_residual_block(data_path, DataLayout::NCHW, 4U /* unit */, 136U /* depth */, 2U /* stride */);
121  add_residual_block(data_path, DataLayout::NCHW, 5U /* unit */, 272U /* depth */, 1U /* stride */);
122  add_residual_block(data_path, DataLayout::NCHW, 6U /* unit */, 272U /* depth */, 1U /* stride */);
123  add_residual_block(data_path, DataLayout::NCHW, 7U /* unit */, 272U /* depth */, 1U /* stride */);
124  add_residual_block(data_path, DataLayout::NCHW, 8U /* unit */, 272U /* depth */, 1U /* stride */);
125  add_residual_block(data_path, DataLayout::NCHW, 9U /* unit */, 272U /* depth */, 1U /* stride */);
126  add_residual_block(data_path, DataLayout::NCHW, 10U /* unit */, 272U /* depth */, 1U /* stride */);
127  add_residual_block(data_path, DataLayout::NCHW, 11U /* unit */, 272U /* depth */, 1U /* stride */);
128 
129  // Stage 4
130  add_residual_block(data_path, DataLayout::NCHW, 12U /* unit */, 272U /* depth */, 2U /* stride */);
131  add_residual_block(data_path, DataLayout::NCHW, 13U /* unit */, 544U /* depth */, 1U /* stride */);
132  add_residual_block(data_path, DataLayout::NCHW, 14U /* unit */, 544U /* depth */, 1U /* stride */);
133  add_residual_block(data_path, DataLayout::NCHW, 15U /* unit */, 544U /* depth */, 1U /* stride */);
134 
135  graph << PoolingLayer(PoolingLayerInfo(PoolingType::AVG, operation_layout)).set_name("predictions/AvgPool")
136  << FlattenLayer().set_name("predictions/Reshape")
138  1000U,
139  get_weights_accessor(data_path, "pred_w_0.npy", weights_layout),
140  get_weights_accessor(data_path, "pred_b_0.npy"))
141  .set_name("predictions/FC")
142  << SoftmaxLayer().set_name("predictions/Softmax")
143  << OutputLayer(get_output_accessor(common_params, 5));
144 
145  // Finalize graph
146  GraphConfig config;
147  config.num_threads = common_params.threads;
148  config.use_tuner = common_params.enable_tuner;
149  config.tuner_mode = common_params.tuner_mode;
150  config.tuner_file = common_params.tuner_file;
151  config.mlgo_file = common_params.mlgo_file;
152 
153  graph.finalize(common_params.target, config);
154 
155  return true;
156  }
157 
158  void do_run() override
159  {
160  // Run graph
161  graph.run();
162  }
163 
164 private:
165  CommandLineParser cmd_parser;
166  CommonGraphOptions common_opts;
167  CommonGraphParams common_params;
168  Stream graph;
169 
170  void add_residual_block(const std::string &data_path, DataLayout weights_layout,
171  unsigned int unit, unsigned int depth, unsigned int stride)
172  {
173  PadStrideInfo dwc_info = PadStrideInfo(1, 1, 1, 1);
174  const unsigned int gconv_id = unit * 2;
175  const unsigned int num_groups = 4;
176  const std::string unit_id_name = arm_compute::support::cpp11::to_string(unit);
177  const std::string gconv_id_name = arm_compute::support::cpp11::to_string(gconv_id);
178  const std::string gconv_id_1_name = arm_compute::support::cpp11::to_string(gconv_id + 1);
179  const std::string unit_name = "unit" + unit_id_name;
180 
181  SubStream left_ss(graph);
182  SubStream right_ss(graph);
183 
184  if(stride == 2)
185  {
186  right_ss << PoolingLayer(PoolingLayerInfo(PoolingType::AVG, 3, common_params.data_layout, PadStrideInfo(2, 2, 1, 1))).set_name(unit_name + "/pool_1/AveragePool");
187  dwc_info = PadStrideInfo(2, 2, 1, 1);
188  }
189 
190  left_ss << ConvolutionLayer(
191  1U, 1U, depth,
192  get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_w_0.npy", weights_layout),
193  std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
194  PadStrideInfo(1, 1, 0, 0), num_groups)
195  .set_name(unit_name + "/gconv1_" + gconv_id_name + "/convolution")
197  get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_rm_0.npy"),
198  get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_riv_0.npy"),
199  get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_s_0.npy"),
200  get_weights_accessor(data_path, "gconv1_" + gconv_id_name + "_bn_b_0.npy"),
201  1e-5f)
202  .set_name(unit_name + "/gconv1_" + gconv_id_name + "/BatchNorm")
203  << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "/gconv1_" + gconv_id_name + "/Relu")
204  << ChannelShuffleLayer(num_groups).set_name(unit_name + "/shuffle_0/ChannelShufle")
206  3U, 3U,
207  get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_w_0.npy", weights_layout),
208  std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
209  dwc_info)
210  .set_name(unit_name + "/gconv3_" + unit_id_name + "/depthwise")
212  get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_rm_0.npy"),
213  get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_riv_0.npy"),
214  get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_s_0.npy"),
215  get_weights_accessor(data_path, "gconv3_" + unit_id_name + "_bn_b_0.npy"),
216  1e-5f)
217  .set_name(unit_name + "/gconv3_" + unit_id_name + "/BatchNorm")
218  << ConvolutionLayer(
219  1U, 1U, depth,
220  get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_w_0.npy", weights_layout),
221  std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
222  PadStrideInfo(1, 1, 0, 0), num_groups)
223  .set_name(unit_name + "/gconv1_" + gconv_id_1_name + "/convolution")
225  get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_rm_0.npy"),
226  get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_riv_0.npy"),
227  get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_s_0.npy"),
228  get_weights_accessor(data_path, "gconv1_" + gconv_id_1_name + "_bn_b_0.npy"),
229  1e-5f)
230  .set_name(unit_name + "/gconv1_" + gconv_id_1_name + "/BatchNorm");
231 
232  if(stride == 2)
233  {
234  graph << ConcatLayer(std::move(left_ss), std::move(right_ss)).set_name(unit_name + "/Concat");
235  }
236  else
237  {
238  graph << EltwiseLayer(std::move(left_ss), std::move(right_ss), EltwiseOperation::Add).set_name(unit_name + "/Add");
239  }
240  graph << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "/Relu");
241  }
242 };
243 
244 /** Main program for ShuffleNet
245  *
246  * Model is based on:
247  * https://arxiv.org/abs/1707.01083
248  * "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices"
249  * Xiangyu Zhang, Xinyu Zhou, Mengxiao Lin, Jian Sun
250  *
251  * Provenance: https://s3.amazonaws.com/download.onnx/models/opset_9/shufflenet.tar.gz
252  *
253  * @note To list all the possible arguments execute the binary appended with the --help option
254  *
255  * @param[in] argc Number of arguments
256  * @param[in] argv Arguments
257  */
258 int main(int argc, char **argv)
259 {
260  return arm_compute::utils::run_example<ShuffleNetExample>(argc, argv);
261 }
Graph configuration structure Device target types.
Definition: Types.h:80
CLTunerMode tuner_mode
Tuner mode to be used by the CL tuner.
Definition: Types.h:87
std::unique_ptr< graph::ITensorAccessor > get_input_accessor(const arm_compute::utils::CommonGraphParams &graph_parameters, std::unique_ptr< IPreprocessor > preprocessor=nullptr, bool bgr=true)
Generates appropriate input accessor according to the specified graph parameters. ...
Definition: GraphUtils.h:497
std::string to_string(T &&value)
Convert integer and float values to string.
void consume_common_graph_parameters(CommonGraphValidateOptions &options, CommonParams &common_params)
Consumes the consume_common_graph_parameters graph options and creates a structure containing any inf...
Includes all the Graph headers at once.
Common command line options used to configure the graph examples.
Class to parse command line arguments.
std::string mlgo_file
Filename to load MLGO heuristics from.
Definition: Types.h:90
std::string tuner_file
File to load/store tuning values from.
Definition: Types.h:89
#define ARM_COMPUTE_EXIT_ON_MSG(cond, msg)
If the condition is true, the given message is printed and program exits.
Definition: Error.h:379
int main(int argc, char **argv)
Main program for ShuffleNet.
const unsigned int num_groups
Definition: Im2Col.cpp:153
Abstract Example class.
Definition: Utils.h:78
Num samples, channels, height, width.
TensorShape permute_shape(TensorShape tensor_shape, DataLayout in_data_layout, DataLayout out_data_layout)
Permutes a given tensor shape given the input and output data layout.
Definition: GraphUtils.h:664
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1190
TensorDescriptor & set_layout(DataLayout data_layout)
Sets tensor descriptor data layout.
Structure holding all the common graph parameters.
Num samples, height, width, channels.
std::unique_ptr< graph::ITensorAccessor > get_output_accessor(const arm_compute::utils::CommonGraphParams &graph_parameters, size_t top_n=5, bool is_validation=false, std::ostream &output_stream=std::cout)
Generates appropriate output accessor according to the specified graph parameters.
Definition: GraphUtils.h:543
bool use_tuner
Use a tuner in tunable backends.
Definition: Types.h:85
std::unique_ptr< graph::ITensorAccessor > get_weights_accessor(const std::string &path, const std::string &data_file, DataLayout file_layout=DataLayout::NCHW)
Generates appropriate weights accessor according to the specified path.
Definition: GraphUtils.h:475
int num_threads
Number of threads to use (thread capable backends), if 0 the backend will auto-initialize, if -1 the backend will stay as it is.
Definition: Types.h:88
Stream frontend class to construct simple graphs in a stream fashion.
Definition: Stream.h:45
DataLayout
[DataLayout enum definition]
Definition: Types.h:120
ILayer & set_name(std::string name)
Sets the name of the layer.
Definition: ILayer.h:55