• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2017-2020 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"
25 #include "support/ToolchainSupport.h"
26 #include "utils/CommonGraphOptions.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 ResNetV1_50 network using the Compute Library's graph API */
35 class GraphResNetV1_50Example : public Example
36 {
37 public:
GraphResNetV1_50Example()38     GraphResNetV1_50Example()
39         : cmd_parser(), common_opts(cmd_parser), common_params(), graph(0, "ResNetV1_50")
40     {
41     }
do_setup(int argc,char ** argv)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         // Print parameter values
59         std::cout << common_params << std::endl;
60 
61         // Get trainable parameters data path
62         std::string data_path = common_params.data_path;
63 
64         // Create a preprocessor object
65         const std::array<float, 3> mean_rgb{ { 122.68f, 116.67f, 104.01f } };
66         std::unique_ptr<IPreprocessor> preprocessor = arm_compute::support::cpp14::make_unique<CaffePreproccessor>(mean_rgb,
67                                                                                                                    false /* Do not convert to BGR */);
68 
69         // Create input descriptor
70         const auto        operation_layout = common_params.data_layout;
71         const TensorShape tensor_shape     = permute_shape(TensorShape(224U, 224U, 3U, 1U), DataLayout::NCHW, operation_layout);
72         TensorDescriptor  input_descriptor = TensorDescriptor(tensor_shape, common_params.data_type).set_layout(operation_layout);
73 
74         // Set weights trained layout
75         const DataLayout weights_layout = DataLayout::NCHW;
76 
77         graph << common_params.target
78               << common_params.fast_math_hint
79               << InputLayer(input_descriptor, get_input_accessor(common_params, std::move(preprocessor), false /* Do not convert to BGR */))
80               << ConvolutionLayer(
81                   7U, 7U, 64U,
82                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_weights.npy", weights_layout),
83                   std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
84                   PadStrideInfo(2, 2, 3, 3))
85               .set_name("conv1/convolution")
86               << BatchNormalizationLayer(
87                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_moving_mean.npy"),
88                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_moving_variance.npy"),
89                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_gamma.npy"),
90                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_beta.npy"),
91                   0.0000100099996416f)
92               .set_name("conv1/BatchNorm")
93               << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name("conv1/Relu")
94               << PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, operation_layout, PadStrideInfo(2, 2, 0, 1, 0, 1, DimensionRoundingType::FLOOR))).set_name("pool1/MaxPool");
95 
96         add_residual_block(data_path, "block1", weights_layout, 64, 3, 2);
97         add_residual_block(data_path, "block2", weights_layout, 128, 4, 2);
98         add_residual_block(data_path, "block3", weights_layout, 256, 6, 2);
99         add_residual_block(data_path, "block4", weights_layout, 512, 3, 1);
100 
101         graph << PoolingLayer(PoolingLayerInfo(PoolingType::AVG, operation_layout)).set_name("pool5")
102               << ConvolutionLayer(
103                   1U, 1U, 1000U,
104                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/logits_weights.npy", weights_layout),
105                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/logits_biases.npy"),
106                   PadStrideInfo(1, 1, 0, 0))
107               .set_name("logits/convolution")
108               << FlattenLayer().set_name("predictions/Reshape")
109               << SoftmaxLayer().set_name("predictions/Softmax")
110               << OutputLayer(get_output_accessor(common_params, 5));
111 
112         // Finalize graph
113         GraphConfig config;
114         config.num_threads      = common_params.threads;
115         config.use_tuner        = common_params.enable_tuner;
116         config.tuner_mode       = common_params.tuner_mode;
117         config.tuner_file       = common_params.tuner_file;
118         config.convert_to_uint8 = (common_params.data_type == DataType::QASYMM8);
119 
120         graph.finalize(common_params.target, config);
121 
122         return true;
123     }
124 
do_run()125     void do_run() override
126     {
127         // Run graph
128         graph.run();
129     }
130 
131 private:
132     CommandLineParser  cmd_parser;
133     CommonGraphOptions common_opts;
134     CommonGraphParams  common_params;
135     Stream             graph;
136 
add_residual_block(const std::string & data_path,const std::string & name,DataLayout weights_layout,unsigned int base_depth,unsigned int num_units,unsigned int stride)137     void add_residual_block(const std::string &data_path, const std::string &name, DataLayout weights_layout,
138                             unsigned int base_depth, unsigned int num_units, unsigned int stride)
139     {
140         for(unsigned int i = 0; i < num_units; ++i)
141         {
142             std::stringstream unit_path_ss;
143             unit_path_ss << "/cnn_data/resnet50_model/" << name << "_unit_" << (i + 1) << "_bottleneck_v1_";
144             std::stringstream unit_name_ss;
145             unit_name_ss << name << "/unit" << (i + 1) << "/bottleneck_v1/";
146 
147             std::string unit_path = unit_path_ss.str();
148             std::string unit_name = unit_name_ss.str();
149 
150             unsigned int middle_stride = 1;
151 
152             if(i == (num_units - 1))
153             {
154                 middle_stride = stride;
155             }
156 
157             SubStream right(graph);
158             right << ConvolutionLayer(
159                       1U, 1U, base_depth,
160                       get_weights_accessor(data_path, unit_path + "conv1_weights.npy", weights_layout),
161                       std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
162                       PadStrideInfo(1, 1, 0, 0))
163                   .set_name(unit_name + "conv1/convolution")
164                   << BatchNormalizationLayer(
165                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_moving_mean.npy"),
166                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_moving_variance.npy"),
167                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_gamma.npy"),
168                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_beta.npy"),
169                       0.0000100099996416f)
170                   .set_name(unit_name + "conv1/BatchNorm")
171                   << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "conv1/Relu")
172 
173                   << ConvolutionLayer(
174                       3U, 3U, base_depth,
175                       get_weights_accessor(data_path, unit_path + "conv2_weights.npy", weights_layout),
176                       std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
177                       PadStrideInfo(middle_stride, middle_stride, 1, 1))
178                   .set_name(unit_name + "conv2/convolution")
179                   << BatchNormalizationLayer(
180                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_moving_mean.npy"),
181                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_moving_variance.npy"),
182                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_gamma.npy"),
183                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_beta.npy"),
184                       0.0000100099996416f)
185                   .set_name(unit_name + "conv2/BatchNorm")
186                   << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "conv1/Relu")
187 
188                   << ConvolutionLayer(
189                       1U, 1U, base_depth * 4,
190                       get_weights_accessor(data_path, unit_path + "conv3_weights.npy", weights_layout),
191                       std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
192                       PadStrideInfo(1, 1, 0, 0))
193                   .set_name(unit_name + "conv3/convolution")
194                   << BatchNormalizationLayer(
195                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_moving_mean.npy"),
196                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_moving_variance.npy"),
197                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_gamma.npy"),
198                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_beta.npy"),
199                       0.0000100099996416f)
200                   .set_name(unit_name + "conv2/BatchNorm");
201 
202             if(i == 0)
203             {
204                 SubStream left(graph);
205                 left << ConvolutionLayer(
206                          1U, 1U, base_depth * 4,
207                          get_weights_accessor(data_path, unit_path + "shortcut_weights.npy", weights_layout),
208                          std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
209                          PadStrideInfo(1, 1, 0, 0))
210                      .set_name(unit_name + "shortcut/convolution")
211                      << BatchNormalizationLayer(
212                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_moving_mean.npy"),
213                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_moving_variance.npy"),
214                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_gamma.npy"),
215                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_beta.npy"),
216                          0.0000100099996416f)
217                      .set_name(unit_name + "shortcut/BatchNorm");
218 
219                 graph << EltwiseLayer(std::move(left), std::move(right), EltwiseOperation::Add).set_name(unit_name + "add");
220             }
221             else if(middle_stride > 1)
222             {
223                 SubStream left(graph);
224                 left << PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 1, common_params.data_layout, PadStrideInfo(middle_stride, middle_stride, 0, 0), true)).set_name(unit_name + "shortcut/MaxPool");
225 
226                 graph << EltwiseLayer(std::move(left), std::move(right), EltwiseOperation::Add).set_name(unit_name + "add");
227             }
228             else
229             {
230                 SubStream left(graph);
231                 graph << EltwiseLayer(std::move(left), std::move(right), EltwiseOperation::Add).set_name(unit_name + "add");
232             }
233 
234             graph << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "Relu");
235         }
236     }
237 };
238 
239 /** Main program for ResNetV1_50
240  *
241  * Model is based on:
242  *      https://arxiv.org/abs/1512.03385
243  *      "Deep Residual Learning for Image Recognition"
244  *      Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
245  *
246  * Provenance: download.tensorflow.org/models/resnet_v1_50_2016_08_28.tar.gz
247  *
248  * @note To list all the possible arguments execute the binary appended with the --help option
249  *
250  * @param[in] argc Number of arguments
251  * @param[in] argv Arguments
252  */
main(int argc,char ** argv)253 int main(int argc, char **argv)
254 {
255     return arm_compute::utils::run_example<GraphResNetV1_50Example>(argc, argv);
256 }
257