xref: /aosp_15_r20/external/ComputeLibrary/examples/graph_resnet50.cpp (revision c217d954acce2dbc11938adb493fc0abd69584f3)
1*c217d954SCole Faust /*
2*c217d954SCole Faust  * Copyright (c) 2017-2021 Arm Limited.
3*c217d954SCole Faust  *
4*c217d954SCole Faust  * SPDX-License-Identifier: MIT
5*c217d954SCole Faust  *
6*c217d954SCole Faust  * Permission is hereby granted, free of charge, to any person obtaining a copy
7*c217d954SCole Faust  * of this software and associated documentation files (the "Software"), to
8*c217d954SCole Faust  * deal in the Software without restriction, including without limitation the
9*c217d954SCole Faust  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10*c217d954SCole Faust  * sell copies of the Software, and to permit persons to whom the Software is
11*c217d954SCole Faust  * furnished to do so, subject to the following conditions:
12*c217d954SCole Faust  *
13*c217d954SCole Faust  * The above copyright notice and this permission notice shall be included in all
14*c217d954SCole Faust  * copies or substantial portions of the Software.
15*c217d954SCole Faust  *
16*c217d954SCole Faust  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17*c217d954SCole Faust  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18*c217d954SCole Faust  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19*c217d954SCole Faust  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20*c217d954SCole Faust  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21*c217d954SCole Faust  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22*c217d954SCole Faust  * SOFTWARE.
23*c217d954SCole Faust  */
24*c217d954SCole Faust #include "arm_compute/graph.h"
25*c217d954SCole Faust #include "support/ToolchainSupport.h"
26*c217d954SCole Faust #include "utils/CommonGraphOptions.h"
27*c217d954SCole Faust #include "utils/GraphUtils.h"
28*c217d954SCole Faust #include "utils/Utils.h"
29*c217d954SCole Faust 
30*c217d954SCole Faust using namespace arm_compute::utils;
31*c217d954SCole Faust using namespace arm_compute::graph::frontend;
32*c217d954SCole Faust using namespace arm_compute::graph_utils;
33*c217d954SCole Faust 
34*c217d954SCole Faust /** Example demonstrating how to implement ResNetV1_50 network using the Compute Library's graph API */
35*c217d954SCole Faust class GraphResNetV1_50Example : public Example
36*c217d954SCole Faust {
37*c217d954SCole Faust public:
GraphResNetV1_50Example()38*c217d954SCole Faust     GraphResNetV1_50Example()
39*c217d954SCole Faust         : cmd_parser(), common_opts(cmd_parser), common_params(), graph(0, "ResNetV1_50")
40*c217d954SCole Faust     {
41*c217d954SCole Faust     }
do_setup(int argc,char ** argv)42*c217d954SCole Faust     bool do_setup(int argc, char **argv) override
43*c217d954SCole Faust     {
44*c217d954SCole Faust         // Parse arguments
45*c217d954SCole Faust         cmd_parser.parse(argc, argv);
46*c217d954SCole Faust         cmd_parser.validate();
47*c217d954SCole Faust 
48*c217d954SCole Faust         // Consume common parameters
49*c217d954SCole Faust         common_params = consume_common_graph_parameters(common_opts);
50*c217d954SCole Faust 
51*c217d954SCole Faust         // Return when help menu is requested
52*c217d954SCole Faust         if(common_params.help)
53*c217d954SCole Faust         {
54*c217d954SCole Faust             cmd_parser.print_help(argv[0]);
55*c217d954SCole Faust             return false;
56*c217d954SCole Faust         }
57*c217d954SCole Faust 
58*c217d954SCole Faust         // Print parameter values
59*c217d954SCole Faust         std::cout << common_params << std::endl;
60*c217d954SCole Faust 
61*c217d954SCole Faust         // Get trainable parameters data path
62*c217d954SCole Faust         std::string data_path = common_params.data_path;
63*c217d954SCole Faust 
64*c217d954SCole Faust         // Create a preprocessor object
65*c217d954SCole Faust         const std::array<float, 3> mean_rgb{ { 122.68f, 116.67f, 104.01f } };
66*c217d954SCole Faust         std::unique_ptr<IPreprocessor> preprocessor = std::make_unique<CaffePreproccessor>(mean_rgb,
67*c217d954SCole Faust                                                                                            false /* Do not convert to BGR */);
68*c217d954SCole Faust 
69*c217d954SCole Faust         // Create input descriptor
70*c217d954SCole Faust         const auto        operation_layout = common_params.data_layout;
71*c217d954SCole Faust         const TensorShape tensor_shape     = permute_shape(TensorShape(224U, 224U, 3U, common_params.batches), DataLayout::NCHW, operation_layout);
72*c217d954SCole Faust         TensorDescriptor  input_descriptor = TensorDescriptor(tensor_shape, common_params.data_type).set_layout(operation_layout);
73*c217d954SCole Faust 
74*c217d954SCole Faust         // Set weights trained layout
75*c217d954SCole Faust         const DataLayout weights_layout = DataLayout::NCHW;
76*c217d954SCole Faust 
77*c217d954SCole Faust         graph << common_params.target
78*c217d954SCole Faust               << common_params.fast_math_hint
79*c217d954SCole Faust               << InputLayer(input_descriptor, get_input_accessor(common_params, std::move(preprocessor), false /* Do not convert to BGR */))
80*c217d954SCole Faust               << ConvolutionLayer(
81*c217d954SCole Faust                   7U, 7U, 64U,
82*c217d954SCole Faust                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_weights.npy", weights_layout),
83*c217d954SCole Faust                   std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
84*c217d954SCole Faust                   PadStrideInfo(2, 2, 3, 3))
85*c217d954SCole Faust               .set_name("conv1/convolution")
86*c217d954SCole Faust               << BatchNormalizationLayer(
87*c217d954SCole Faust                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_moving_mean.npy"),
88*c217d954SCole Faust                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_moving_variance.npy"),
89*c217d954SCole Faust                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_gamma.npy"),
90*c217d954SCole Faust                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/conv1_BatchNorm_beta.npy"),
91*c217d954SCole Faust                   0.0000100099996416f)
92*c217d954SCole Faust               .set_name("conv1/BatchNorm")
93*c217d954SCole Faust               << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name("conv1/Relu")
94*c217d954SCole Faust               << PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, operation_layout, PadStrideInfo(2, 2, 0, 1, 0, 1, DimensionRoundingType::FLOOR))).set_name("pool1/MaxPool");
95*c217d954SCole Faust 
96*c217d954SCole Faust         add_residual_block(data_path, "block1", weights_layout, 64, 3, 2);
97*c217d954SCole Faust         add_residual_block(data_path, "block2", weights_layout, 128, 4, 2);
98*c217d954SCole Faust         add_residual_block(data_path, "block3", weights_layout, 256, 6, 2);
99*c217d954SCole Faust         add_residual_block(data_path, "block4", weights_layout, 512, 3, 1);
100*c217d954SCole Faust 
101*c217d954SCole Faust         graph << PoolingLayer(PoolingLayerInfo(PoolingType::AVG, operation_layout)).set_name("pool5")
102*c217d954SCole Faust               << ConvolutionLayer(
103*c217d954SCole Faust                   1U, 1U, 1000U,
104*c217d954SCole Faust                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/logits_weights.npy", weights_layout),
105*c217d954SCole Faust                   get_weights_accessor(data_path, "/cnn_data/resnet50_model/logits_biases.npy"),
106*c217d954SCole Faust                   PadStrideInfo(1, 1, 0, 0))
107*c217d954SCole Faust               .set_name("logits/convolution")
108*c217d954SCole Faust               << FlattenLayer().set_name("predictions/Reshape")
109*c217d954SCole Faust               << SoftmaxLayer().set_name("predictions/Softmax")
110*c217d954SCole Faust               << OutputLayer(get_output_accessor(common_params, 5));
111*c217d954SCole Faust 
112*c217d954SCole Faust         // Finalize graph
113*c217d954SCole Faust         GraphConfig config;
114*c217d954SCole Faust         config.num_threads        = common_params.threads;
115*c217d954SCole Faust         config.use_tuner          = common_params.enable_tuner;
116*c217d954SCole Faust         config.tuner_mode         = common_params.tuner_mode;
117*c217d954SCole Faust         config.tuner_file         = common_params.tuner_file;
118*c217d954SCole Faust         config.mlgo_file          = common_params.mlgo_file;
119*c217d954SCole Faust         config.use_synthetic_type = arm_compute::is_data_type_quantized(common_params.data_type);
120*c217d954SCole Faust         config.synthetic_type     = common_params.data_type;
121*c217d954SCole Faust 
122*c217d954SCole Faust         graph.finalize(common_params.target, config);
123*c217d954SCole Faust 
124*c217d954SCole Faust         return true;
125*c217d954SCole Faust     }
126*c217d954SCole Faust 
do_run()127*c217d954SCole Faust     void do_run() override
128*c217d954SCole Faust     {
129*c217d954SCole Faust         // Run graph
130*c217d954SCole Faust         graph.run();
131*c217d954SCole Faust     }
132*c217d954SCole Faust 
133*c217d954SCole Faust private:
134*c217d954SCole Faust     CommandLineParser  cmd_parser;
135*c217d954SCole Faust     CommonGraphOptions common_opts;
136*c217d954SCole Faust     CommonGraphParams  common_params;
137*c217d954SCole Faust     Stream             graph;
138*c217d954SCole Faust 
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)139*c217d954SCole Faust     void add_residual_block(const std::string &data_path, const std::string &name, DataLayout weights_layout,
140*c217d954SCole Faust                             unsigned int base_depth, unsigned int num_units, unsigned int stride)
141*c217d954SCole Faust     {
142*c217d954SCole Faust         for(unsigned int i = 0; i < num_units; ++i)
143*c217d954SCole Faust         {
144*c217d954SCole Faust             std::stringstream unit_path_ss;
145*c217d954SCole Faust             unit_path_ss << "/cnn_data/resnet50_model/" << name << "_unit_" << (i + 1) << "_bottleneck_v1_";
146*c217d954SCole Faust             std::stringstream unit_name_ss;
147*c217d954SCole Faust             unit_name_ss << name << "/unit" << (i + 1) << "/bottleneck_v1/";
148*c217d954SCole Faust 
149*c217d954SCole Faust             std::string unit_path = unit_path_ss.str();
150*c217d954SCole Faust             std::string unit_name = unit_name_ss.str();
151*c217d954SCole Faust 
152*c217d954SCole Faust             unsigned int middle_stride = 1;
153*c217d954SCole Faust 
154*c217d954SCole Faust             if(i == (num_units - 1))
155*c217d954SCole Faust             {
156*c217d954SCole Faust                 middle_stride = stride;
157*c217d954SCole Faust             }
158*c217d954SCole Faust 
159*c217d954SCole Faust             SubStream right(graph);
160*c217d954SCole Faust             right << ConvolutionLayer(
161*c217d954SCole Faust                       1U, 1U, base_depth,
162*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv1_weights.npy", weights_layout),
163*c217d954SCole Faust                       std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
164*c217d954SCole Faust                       PadStrideInfo(1, 1, 0, 0))
165*c217d954SCole Faust                   .set_name(unit_name + "conv1/convolution")
166*c217d954SCole Faust                   << BatchNormalizationLayer(
167*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_moving_mean.npy"),
168*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_moving_variance.npy"),
169*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_gamma.npy"),
170*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv1_BatchNorm_beta.npy"),
171*c217d954SCole Faust                       0.0000100099996416f)
172*c217d954SCole Faust                   .set_name(unit_name + "conv1/BatchNorm")
173*c217d954SCole Faust                   << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "conv1/Relu")
174*c217d954SCole Faust 
175*c217d954SCole Faust                   << ConvolutionLayer(
176*c217d954SCole Faust                       3U, 3U, base_depth,
177*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv2_weights.npy", weights_layout),
178*c217d954SCole Faust                       std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
179*c217d954SCole Faust                       PadStrideInfo(middle_stride, middle_stride, 1, 1))
180*c217d954SCole Faust                   .set_name(unit_name + "conv2/convolution")
181*c217d954SCole Faust                   << BatchNormalizationLayer(
182*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_moving_mean.npy"),
183*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_moving_variance.npy"),
184*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_gamma.npy"),
185*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv2_BatchNorm_beta.npy"),
186*c217d954SCole Faust                       0.0000100099996416f)
187*c217d954SCole Faust                   .set_name(unit_name + "conv2/BatchNorm")
188*c217d954SCole Faust                   << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "conv1/Relu")
189*c217d954SCole Faust 
190*c217d954SCole Faust                   << ConvolutionLayer(
191*c217d954SCole Faust                       1U, 1U, base_depth * 4,
192*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv3_weights.npy", weights_layout),
193*c217d954SCole Faust                       std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
194*c217d954SCole Faust                       PadStrideInfo(1, 1, 0, 0))
195*c217d954SCole Faust                   .set_name(unit_name + "conv3/convolution")
196*c217d954SCole Faust                   << BatchNormalizationLayer(
197*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_moving_mean.npy"),
198*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_moving_variance.npy"),
199*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_gamma.npy"),
200*c217d954SCole Faust                       get_weights_accessor(data_path, unit_path + "conv3_BatchNorm_beta.npy"),
201*c217d954SCole Faust                       0.0000100099996416f)
202*c217d954SCole Faust                   .set_name(unit_name + "conv2/BatchNorm");
203*c217d954SCole Faust 
204*c217d954SCole Faust             if(i == 0)
205*c217d954SCole Faust             {
206*c217d954SCole Faust                 SubStream left(graph);
207*c217d954SCole Faust                 left << ConvolutionLayer(
208*c217d954SCole Faust                          1U, 1U, base_depth * 4,
209*c217d954SCole Faust                          get_weights_accessor(data_path, unit_path + "shortcut_weights.npy", weights_layout),
210*c217d954SCole Faust                          std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
211*c217d954SCole Faust                          PadStrideInfo(1, 1, 0, 0))
212*c217d954SCole Faust                      .set_name(unit_name + "shortcut/convolution")
213*c217d954SCole Faust                      << BatchNormalizationLayer(
214*c217d954SCole Faust                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_moving_mean.npy"),
215*c217d954SCole Faust                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_moving_variance.npy"),
216*c217d954SCole Faust                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_gamma.npy"),
217*c217d954SCole Faust                          get_weights_accessor(data_path, unit_path + "shortcut_BatchNorm_beta.npy"),
218*c217d954SCole Faust                          0.0000100099996416f)
219*c217d954SCole Faust                      .set_name(unit_name + "shortcut/BatchNorm");
220*c217d954SCole Faust 
221*c217d954SCole Faust                 graph << EltwiseLayer(std::move(left), std::move(right), EltwiseOperation::Add).set_name(unit_name + "add");
222*c217d954SCole Faust             }
223*c217d954SCole Faust             else if(middle_stride > 1)
224*c217d954SCole Faust             {
225*c217d954SCole Faust                 SubStream left(graph);
226*c217d954SCole Faust                 left << PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 1, common_params.data_layout, PadStrideInfo(middle_stride, middle_stride, 0, 0), true)).set_name(unit_name + "shortcut/MaxPool");
227*c217d954SCole Faust 
228*c217d954SCole Faust                 graph << EltwiseLayer(std::move(left), std::move(right), EltwiseOperation::Add).set_name(unit_name + "add");
229*c217d954SCole Faust             }
230*c217d954SCole Faust             else
231*c217d954SCole Faust             {
232*c217d954SCole Faust                 SubStream left(graph);
233*c217d954SCole Faust                 graph << EltwiseLayer(std::move(left), std::move(right), EltwiseOperation::Add).set_name(unit_name + "add");
234*c217d954SCole Faust             }
235*c217d954SCole Faust 
236*c217d954SCole Faust             graph << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "Relu");
237*c217d954SCole Faust         }
238*c217d954SCole Faust     }
239*c217d954SCole Faust };
240*c217d954SCole Faust 
241*c217d954SCole Faust /** Main program for ResNetV1_50
242*c217d954SCole Faust  *
243*c217d954SCole Faust  * Model is based on:
244*c217d954SCole Faust  *      https://arxiv.org/abs/1512.03385
245*c217d954SCole Faust  *      "Deep Residual Learning for Image Recognition"
246*c217d954SCole Faust  *      Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
247*c217d954SCole Faust  *
248*c217d954SCole Faust  * Provenance: download.tensorflow.org/models/resnet_v1_50_2016_08_28.tar.gz
249*c217d954SCole Faust  *
250*c217d954SCole Faust  * @note To list all the possible arguments execute the binary appended with the --help option
251*c217d954SCole Faust  *
252*c217d954SCole Faust  * @param[in] argc Number of arguments
253*c217d954SCole Faust  * @param[in] argv Arguments
254*c217d954SCole Faust  */
main(int argc,char ** argv)255*c217d954SCole Faust int main(int argc, char **argv)
256*c217d954SCole Faust {
257*c217d954SCole Faust     return arm_compute::utils::run_example<GraphResNetV1_50Example>(argc, argv);
258*c217d954SCole Faust }
259