• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2018-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 ResNeXt50 network using the Compute Library's graph API */
35 class GraphResNeXt50Example : public Example
36 {
37 public:
GraphResNeXt50Example()38     GraphResNeXt50Example()
39         : cmd_parser(), common_opts(cmd_parser), common_params(), graph(0, "ResNeXt50")
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         // Checks
59         ARM_COMPUTE_EXIT_ON_MSG(arm_compute::is_data_type_quantized_asymmetric(common_params.data_type), "QASYMM8 not supported for this graph");
60 
61         // Print parameter values
62         std::cout << common_params << std::endl;
63 
64         // Get trainable parameters data path
65         std::string data_path = common_params.data_path;
66 
67         // Create input descriptor
68         const auto        operation_layout = common_params.data_layout;
69         const TensorShape tensor_shape     = permute_shape(TensorShape(224U, 224U, 3U, 1U), DataLayout::NCHW, operation_layout);
70         TensorDescriptor  input_descriptor = TensorDescriptor(tensor_shape, common_params.data_type).set_layout(operation_layout);
71 
72         // Set weights trained layout
73         const DataLayout weights_layout = DataLayout::NCHW;
74 
75         graph << common_params.target
76               << common_params.fast_math_hint
77               << InputLayer(input_descriptor, get_input_accessor(common_params))
78               << ScaleLayer(get_weights_accessor(data_path, "/cnn_data/resnext50_model/bn_data_mul.npy"),
79                             get_weights_accessor(data_path, "/cnn_data/resnext50_model/bn_data_add.npy"))
80               .set_name("bn_data/Scale")
81               << ConvolutionLayer(
82                   7U, 7U, 64U,
83                   get_weights_accessor(data_path, "/cnn_data/resnext50_model/conv0_weights.npy", weights_layout),
84                   get_weights_accessor(data_path, "/cnn_data/resnext50_model/conv0_biases.npy"),
85                   PadStrideInfo(2, 2, 2, 3, 2, 3, DimensionRoundingType::FLOOR))
86               .set_name("conv0/Convolution")
87               << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name("conv0/Relu")
88               << PoolingLayer(PoolingLayerInfo(PoolingType::MAX, 3, operation_layout, PadStrideInfo(2, 2, 0, 1, 0, 1, DimensionRoundingType::FLOOR))).set_name("pool0");
89 
90         add_residual_block(data_path, weights_layout, /*ofm*/ 256, /*stage*/ 1, /*num_unit*/ 3, /*stride_conv_unit1*/ 1);
91         add_residual_block(data_path, weights_layout, 512, 2, 4, 2);
92         add_residual_block(data_path, weights_layout, 1024, 3, 6, 2);
93         add_residual_block(data_path, weights_layout, 2048, 4, 3, 2);
94 
95         graph << PoolingLayer(PoolingLayerInfo(PoolingType::AVG, operation_layout)).set_name("pool1")
96               << FlattenLayer().set_name("predictions/Reshape")
97               << OutputLayer(get_npy_output_accessor(common_params.labels, TensorShape(2048U), DataType::F32));
98 
99         // Finalize graph
100         GraphConfig config;
101         config.num_threads = common_params.threads;
102         config.use_tuner   = common_params.enable_tuner;
103         config.tuner_mode  = common_params.tuner_mode;
104         config.tuner_file  = common_params.tuner_file;
105 
106         graph.finalize(common_params.target, config);
107 
108         return true;
109     }
110 
do_run()111     void do_run() override
112     {
113         // Run graph
114         graph.run();
115     }
116 
117 private:
118     CommandLineParser  cmd_parser;
119     CommonGraphOptions common_opts;
120     CommonGraphParams  common_params;
121     Stream             graph;
122 
add_residual_block(const std::string & data_path,DataLayout weights_layout,unsigned int base_depth,unsigned int stage,unsigned int num_units,unsigned int stride_conv_unit1)123     void add_residual_block(const std::string &data_path, DataLayout weights_layout,
124                             unsigned int base_depth, unsigned int stage, unsigned int num_units, unsigned int stride_conv_unit1)
125     {
126         for(unsigned int i = 0; i < num_units; ++i)
127         {
128             std::stringstream unit_path_ss;
129             unit_path_ss << "/cnn_data/resnext50_model/stage" << stage << "_unit" << (i + 1) << "_";
130             std::string unit_path = unit_path_ss.str();
131 
132             std::stringstream unit_name_ss;
133             unit_name_ss << "stage" << stage << "/unit" << (i + 1) << "/";
134             std::string unit_name = unit_name_ss.str();
135 
136             PadStrideInfo pad_grouped_conv(1, 1, 1, 1);
137             if(i == 0)
138             {
139                 pad_grouped_conv = (stage == 1) ? PadStrideInfo(stride_conv_unit1, stride_conv_unit1, 1, 1) : PadStrideInfo(stride_conv_unit1, stride_conv_unit1, 0, 1, 0, 1, DimensionRoundingType::FLOOR);
140             }
141 
142             SubStream right(graph);
143             right << ConvolutionLayer(
144                       1U, 1U, base_depth / 2,
145                       get_weights_accessor(data_path, unit_path + "conv1_weights.npy", weights_layout),
146                       get_weights_accessor(data_path, unit_path + "conv1_biases.npy"),
147                       PadStrideInfo(1, 1, 0, 0))
148                   .set_name(unit_name + "conv1/convolution")
149                   << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "conv1/Relu")
150 
151                   << ConvolutionLayer(
152                       3U, 3U, base_depth / 2,
153                       get_weights_accessor(data_path, unit_path + "conv2_weights.npy", weights_layout),
154                       std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
155                       pad_grouped_conv, 32)
156                   .set_name(unit_name + "conv2/convolution")
157                   << ScaleLayer(get_weights_accessor(data_path, unit_path + "bn2_mul.npy"),
158                                 get_weights_accessor(data_path, unit_path + "bn2_add.npy"))
159                   .set_name(unit_name + "conv1/Scale")
160                   << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "conv2/Relu")
161 
162                   << ConvolutionLayer(
163                       1U, 1U, base_depth,
164                       get_weights_accessor(data_path, unit_path + "conv3_weights.npy", weights_layout),
165                       get_weights_accessor(data_path, unit_path + "conv3_biases.npy"),
166                       PadStrideInfo(1, 1, 0, 0))
167                   .set_name(unit_name + "conv3/convolution");
168 
169             SubStream left(graph);
170             if(i == 0)
171             {
172                 left << ConvolutionLayer(
173                          1U, 1U, base_depth,
174                          get_weights_accessor(data_path, unit_path + "sc_weights.npy", weights_layout),
175                          std::unique_ptr<arm_compute::graph::ITensorAccessor>(nullptr),
176                          PadStrideInfo(stride_conv_unit1, stride_conv_unit1, 0, 0))
177                      .set_name(unit_name + "sc/convolution")
178                      << ScaleLayer(get_weights_accessor(data_path, unit_path + "sc_bn_mul.npy"),
179                                    get_weights_accessor(data_path, unit_path + "sc_bn_add.npy"))
180                      .set_name(unit_name + "sc/scale");
181             }
182 
183             graph << EltwiseLayer(std::move(left), std::move(right), EltwiseOperation::Add).set_name(unit_name + "add");
184             graph << ActivationLayer(ActivationLayerInfo(ActivationLayerInfo::ActivationFunction::RELU)).set_name(unit_name + "Relu");
185         }
186     }
187 };
188 
189 /** Main program for ResNeXt50
190  *
191  * Model is based on:
192  *      https://arxiv.org/abs/1611.05431
193  *      "Aggregated Residual Transformations for Deep Neural Networks"
194  *      Saining Xie, Ross Girshick, Piotr Dollar, Zhuowen Tu, Kaiming He
195  *
196  * @note To list all the possible arguments execute the binary appended with the --help option
197  *
198  * @param[in] argc Number of arguments
199  * @param[in] argv Arguments
200  */
main(int argc,char ** argv)201 int main(int argc, char **argv)
202 {
203     return arm_compute::utils::run_example<GraphResNeXt50Example>(argc, argv);
204 }
205