blob: d69d2cd7d04f2f50039398f7f2400f06beb17cb7 [file] [log] [blame]
Georgios Pinitas2a2db592018-08-15 12:14:46 +01001/*
2 * Copyright (c) 2018 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/mutators/GroupedConvolutionMutator.h"
25
26#include "arm_compute/graph/Graph.h"
27#include "arm_compute/graph/GraphBuilder.h"
28#include "arm_compute/graph/Logger.h"
29#include "arm_compute/graph/Utils.h"
30#include "arm_compute/graph/backends/BackendRegistry.h"
31#include "arm_compute/graph/nodes/Nodes.h"
32
33#include "arm_compute/core/utils/misc/Cast.h"
34
35#include <set>
36
37namespace arm_compute
38{
39namespace graph
40{
41namespace
42{
43NodeID create_grouped_convolution(Graph &g, const NodeParams &params, NodeIdxPair input, NodeID weights, NodeID bias,
Georgios Pinitas1c32bf3962018-11-12 18:36:19 +000044 PadStrideInfo conv_info, ConvolutionMethod method, ActivationLayerInfo fused_act, FastMathHint fast_math_hint, unsigned int num_groups)
Georgios Pinitas2a2db592018-08-15 12:14:46 +010045{
46 bool has_bias = (bias != EmptyNodeID);
47
48 // Split input
49 const TensorDescriptor input_tensor_desc = get_tensor_descriptor(g, g.node(input.node_id)->outputs()[0]);
50 const unsigned int input_idx = get_dimension_idx(input_tensor_desc, DataLayoutDimension::CHANNEL);
51 NodeID input_split = GraphBuilder::add_split_node(g, params, input, num_groups, input_idx);
52
53 // Split weights
54 const TensorDescriptor weights_tensor_desc = get_tensor_descriptor(g, g.node(weights)->outputs()[0]);
55 const unsigned int batch_idx = get_dimension_idx(weights_tensor_desc, DataLayoutDimension::BATCHES);
56 NodeID weights_split = GraphBuilder::add_split_node(g, params, { weights, 0 }, num_groups, batch_idx);
57
58 // Split bias
59 NodeID bias_split = EmptyNodeID;
60 if(has_bias)
61 {
62 // Split bias
63 bias_split = GraphBuilder::add_split_node(g, params, { bias, 0 }, num_groups, 0);
64 }
65
66 std::vector<NodeIdxPair> convolution_outputs;
67 for(unsigned int i = 0; i < num_groups; ++i)
68 {
69 NodeParams group_params = params;
70 NodeID conv_nid = g.add_node<ConvolutionLayerNode>(conv_info, 1, method, fast_math_hint);
71 g.add_connection(input_split, i, conv_nid, 0);
72 g.add_connection(weights_split, i, conv_nid, 1);
73 if(has_bias)
74 {
75 g.add_connection(bias_split, i, conv_nid, 2);
76 }
77
78 // Add group name
79 if(!group_params.name.empty())
80 {
81 group_params.name.append("_g" + arm_compute::support::cpp11::to_string(i));
82 }
83
84 // Set node parameters
85 INode *node = g.node(conv_nid);
86 ARM_COMPUTE_ERROR_ON(node == nullptr);
87 node->set_common_node_parameters(group_params);
88
Georgios Pinitas1c32bf3962018-11-12 18:36:19 +000089 // Down-cast node
90 auto *conv_node = arm_compute::utils::cast::polymorphic_downcast<ConvolutionLayerNode *>(node);
91 conv_node->set_fused_activation(fused_act);
92
Georgios Pinitas2a2db592018-08-15 12:14:46 +010093 convolution_outputs.push_back({ conv_nid, 0 });
94 }
95
96 // Depth concatenate output
97 return GraphBuilder::add_concatenate_node(g, params, convolution_outputs, DataLayoutDimension::CHANNEL);
98}
99} // namespace
100
101const char *GroupedConvolutionMutator::name()
102{
103 return "GroupedConvolutionMutator";
104}
105
106void GroupedConvolutionMutator::mutate(Graph &g)
107{
108 // Early exit if no Convolution layers exist in graph
109 if(g.nodes(NodeType::ConvolutionLayer).empty())
110 {
111 return;
112 }
113
114 // Total nodes
115 size_t total_nodes = g.nodes().size();
116
117 // Iterate over convolution nodes
118 for(unsigned int i = 0; i < total_nodes; ++i)
119 {
120 INode *node = g.node(i);
121 if(node != nullptr && node->type() == NodeType::ConvolutionLayer && arm_compute::utils::cast::polymorphic_downcast<ConvolutionLayerNode *>(node)->num_groups() != 1)
122 {
123 // Validate node
Anthony Barbier890ad1b2018-08-22 13:44:36 +0100124 backends::IDeviceBackend &backend = backends::BackendRegistry::get().get_backend(node->assigned_target());
125 Status status = backend.validate_node(*node);
Georgios Pinitas2a2db592018-08-15 12:14:46 +0100126
127 // If grouped convolution is not supported
128 if(!bool(status))
129 {
130 // Down-cast node
131 auto *conv_node = arm_compute::utils::cast::polymorphic_downcast<ConvolutionLayerNode *>(node);
132
133 // Get internal convolution info
Georgios Pinitas1c32bf3962018-11-12 18:36:19 +0000134 // TODO (geopin01) : Create a descriptor or a clone interface
135 const PadStrideInfo conv_info = conv_node->convolution_info();
136 const ConvolutionMethod conv_method = conv_node->convolution_method();
137 const ActivationLayerInfo fused_act_info = conv_node->fused_activation();
138 const FastMathHint fast_math_hint = conv_node->fast_math_hint();
139 const unsigned int num_groups = conv_node->num_groups();
140 const NodeParams params = conv_node->common_node_params();
141 const Target assigned_target = conv_node->assigned_target();
Georgios Pinitas2a2db592018-08-15 12:14:46 +0100142
143 // Extract node ids
Georgios Pinitas1c32bf3962018-11-12 18:36:19 +0000144 ARM_COMPUTE_ERROR_ON(conv_node->input_edge(0) == nullptr || conv_node->input_edge(1) == nullptr);
145 const NodeID input_id = conv_node->input_edge(0)->producer()->id();
146 const NodeID weights_id = conv_node->input_edge(1)->producer()->id();
147 const NodeID bias_id = (conv_node->input_edge(2) != nullptr) ? conv_node->input_edge(2)->producer()->id() : EmptyNodeID;
Georgios Pinitas2a2db592018-08-15 12:14:46 +0100148
149 // Get driving nodes
150 std::vector<NodeIdxPair> driving_nodes = get_driving_nodes(*node);
151
152 // Extract activation node accessor if any
153 auto node_accessor = conv_node->output(0)->extract_accessor();
154
155 // Current max tensor and node id
156 TensorID latest_tid = g.tensors().size();
157 NodeID latest_nid = g.nodes().size();
158
159 // Create grouped convolution node
160 NodeID grouped_conv_id = create_grouped_convolution(g, params, { input_id, 0 }, weights_id, bias_id,
Georgios Pinitas1c32bf3962018-11-12 18:36:19 +0000161 conv_info, conv_method, fused_act_info, fast_math_hint, num_groups);
Georgios Pinitas2a2db592018-08-15 12:14:46 +0100162
163 // Remove convolution node
164 g.remove_node(node->id());
165
166 // Update batch normalization node outputs
167 for(auto &driving_node : driving_nodes)
168 {
169 g.add_connection(grouped_conv_id, 0, driving_node.node_id, driving_node.index);
170 }
171
172 // Update accessor to batch normalization node
173 g.node(grouped_conv_id)->output(0)->set_accessor(std::move(node_accessor));
174
175 // Configure new tensors and nodes
176 std::for_each(g.tensors().begin() + latest_tid, g.tensors().end(), [](std::unique_ptr<Tensor> &t)
177 {
178 configure_tensor(t.get());
179 });
180 std::for_each(g.nodes().begin() + latest_nid, g.nodes().end(), [&assigned_target](std::unique_ptr<INode> &n)
181 {
182 if(n != nullptr)
183 {
184 n->set_assigned_target(assigned_target);
185 }
186 });
187 }
188 }
189 }
190}
191} // namespace graph
192} // namespace arm_compute