blob: 3f979e48ee300b8f219b610f5606061bda7e1ca2 [file] [log] [blame]
Georgios Pinitasd8734b52017-12-22 15:27:52 +00001/*
SiCongLibc912972021-05-25 14:29:21 +01002 * Copyright (c) 2018-2021 Arm Limited.
Georgios Pinitasd8734b52017-12-22 15:27:52 +00003 *
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 */
Georgios Pinitasd9eb2752018-04-03 13:44:29 +010024#include "arm_compute/graph/mutators/NodeFusionMutator.h"
Georgios Pinitasd8734b52017-12-22 15:27:52 +000025
giuros01acce5042019-02-21 17:32:34 +000026#include "arm_compute/graph/GraphBuilder.h"
Georgios Pinitasd9eb2752018-04-03 13:44:29 +010027#include "arm_compute/graph/Logger.h"
Georgios Pinitas2a2db592018-08-15 12:14:46 +010028#include "arm_compute/graph/Utils.h"
giuros01acce5042019-02-21 17:32:34 +000029#include "arm_compute/graph/backends/BackendRegistry.h"
30#include "arm_compute/graph/nodes/FusedConvolutionBatchNormalizationNode.h"
Sheri Zhangfb228032021-11-02 10:45:07 +000031#include "arm_compute/graph/nodes/FusedConvolutionWithPostOpNode.h"
Georgios Pinitasd9eb2752018-04-03 13:44:29 +010032#include "arm_compute/graph/nodes/Nodes.h"
Georgios Pinitasd8734b52017-12-22 15:27:52 +000033
Gunes Bayircc171f92021-09-13 13:38:29 +010034#include "src/graph/mutators/MutatorUtils.h"
35
Sang-Hoon Park68dd25f2020-10-19 16:00:11 +010036#include "support/Cast.h"
Georgios Pinitasd8734b52017-12-22 15:27:52 +000037
Sheri Zhangfb228032021-11-02 10:45:07 +000038#include <list>
Georgios Pinitas6f109bd2018-07-16 12:57:42 +010039#include <set>
40
Georgios Pinitasd8734b52017-12-22 15:27:52 +000041namespace arm_compute
42{
Georgios Pinitasd9eb2752018-04-03 13:44:29 +010043namespace graph
Georgios Pinitasd8734b52017-12-22 15:27:52 +000044{
45namespace detail
46{
Sheri Zhangc65023e2021-11-03 21:24:00 +000047void transfer_driving_nodes_and_remove_old_node(Graph &g, INode *new_node, INode *old_node, bool add_output_tensor)
48{
49 if(new_node == nullptr || old_node == nullptr)
50 {
51 return;
52 }
53
54 // Get driving nodes of last fusable node
55 std::vector<NodeIdxPair> last_driving_nodes = get_driving_nodes(*old_node);
56
57 // Extract last fusable node accessor if any
58 if(old_node->output(0) == nullptr)
59 {
60 return;
61 }
62 auto old_node_accessor = old_node->output(0)->extract_accessor();
63
64 // Remove node
65 g.remove_node(old_node->id());
66
67 // Update fused node outputs
68 for(auto &driving_node : last_driving_nodes)
69 {
70 g.add_connection(new_node->id(), 0, driving_node.node_id, driving_node.index);
71 if(add_output_tensor)
72 {
73 configure_tensor(new_node->output(0));
74 }
75 }
76
77 // Update accessor to fused node
78 new_node->output(0)->set_accessor(std::move(old_node_accessor));
79}
80
giuros01acce5042019-02-21 17:32:34 +000081void fuse_convolution_with_batch_normalization(Graph &g, const Edge *output_edge)
82{
83 ARM_COMPUTE_ERROR_ON(output_edge == nullptr);
84
85 auto *conv_node = arm_compute::utils::cast::polymorphic_downcast<ConvolutionLayerNode *>(output_edge->producer());
86 auto *bn_node = arm_compute::utils::cast::polymorphic_downcast<BatchNormalizationLayerNode *>(output_edge->consumer());
87
88 // Not fusing if number of groups is greater than 1
89 if(conv_node->num_groups() > 1)
90 {
91 return;
92 }
93
94 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Fusing convolution node with ID : " << output_edge->producer_id()
95 << " with BatchNormalization Layer node with ID : " << output_edge->consumer_id() << std::endl);
96
97 // Prevent fusion if fused node has an output accessor
98 if(conv_node->output(0)->accessor() == nullptr)
99 {
100 const Target assigned_target = conv_node->assigned_target();
101
102 // Extract conv inputs
103 const auto conv_input_id = conv_node->input_edge(0)->producer_id();
104 const auto conv_weights_id = conv_node->input_edge(1)->producer_id();
giuros01acce5042019-02-21 17:32:34 +0000105 const auto conv_info = conv_node->convolution_info();
106 const auto conv_method = conv_node->convolution_method();
107 const auto num_groups = conv_node->num_groups();
108 const auto act_info = bn_node->fused_activation();
109 FastMathHint fast_math_hint = conv_node->fast_math_hint();
110
111 // Extract bn inputs
giuros01351bd132019-08-23 14:27:30 +0100112 const auto bn_mean_id = bn_node->input_edge(1)->producer_id();
113 const auto bn_var_id = bn_node->input_edge(2)->producer_id();
114
115 const auto epsilon = bn_node->epsilon();
giuros01acce5042019-02-21 17:32:34 +0000116
117 // Create the fused node
Manuel Bottinibffb41e2019-06-20 16:00:27 +0100118 const NodeID fused_id = g.add_node<FusedConvolutionBatchNormalizationNode>(epsilon, conv_info, num_groups, conv_method, fast_math_hint, act_info);
giuros01acce5042019-02-21 17:32:34 +0000119
120 if(conv_node->input_edge(2) != nullptr)
121 {
122 auto conv_bias_id = conv_node->input_edge(2)->producer_id();
123 g.add_connection(conv_bias_id, 0, fused_id, 2);
124 }
125
126 // Add connections from the conv/batch_norm inputs to the fused node
127 g.add_connection(conv_input_id, 0, fused_id, 0);
128 g.add_connection(conv_weights_id, 0, fused_id, 1);
129 g.add_connection(bn_mean_id, 0, fused_id, 3);
130 g.add_connection(bn_var_id, 0, fused_id, 4);
giuros01351bd132019-08-23 14:27:30 +0100131
132 if(bn_node->input_edge(3) != nullptr)
133 {
134 const auto bn_beta_id = bn_node->input_edge(3)->producer_id();
135 g.add_connection(bn_beta_id, 0, fused_id, 5);
136 }
137
138 if(bn_node->input_edge(4) != nullptr)
139 {
140 const auto bn_gamma_id = bn_node->input_edge(4)->producer_id();
141 g.add_connection(bn_gamma_id, 0, fused_id, 6);
142 }
giuros01acce5042019-02-21 17:32:34 +0000143
Sheri Zhangc65023e2021-11-03 21:24:00 +0000144 auto fused_node = g.node(fused_id);
145 auto bn_node_name = bn_node->name();
giuros01acce5042019-02-21 17:32:34 +0000146
Sheri Zhangc65023e2021-11-03 21:24:00 +0000147 transfer_driving_nodes_and_remove_old_node(g, fused_node, bn_node, true);
giuros01acce5042019-02-21 17:32:34 +0000148
giuros01acce5042019-02-21 17:32:34 +0000149 fused_node->set_assigned_target(assigned_target);
150 fused_node->set_common_node_parameters(NodeParams{ conv_node->name() + "+" + bn_node_name, assigned_target });
151
152 // Remove convolution node
153 g.remove_node(conv_node->id());
154 }
155 else
156 {
157 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of convolution with batch normalization due to the presence of an output accessor\n");
158 }
159}
160
Manuel Bottinibffb41e2019-06-20 16:00:27 +0100161void fuse_depthwise_convolution_with_batch_normalization(Graph &g, const Edge *output_edge)
162{
163 ARM_COMPUTE_ERROR_ON(output_edge == nullptr);
164
165 auto *depth_conv_node = arm_compute::utils::cast::polymorphic_downcast<DepthwiseConvolutionLayerNode *>(output_edge->producer());
166 auto *bn_node = arm_compute::utils::cast::polymorphic_downcast<BatchNormalizationLayerNode *>(output_edge->consumer());
167
168 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Fusing depthwise convolution node with ID : " << output_edge->producer_id()
169 << " with BatchNormalization Layer node with ID : " << output_edge->consumer_id() << std::endl);
170
171 // Prevent fusion if fused node has an output accessor
172 if(depth_conv_node->output(0)->accessor() == nullptr)
173 {
174 const Target assigned_target = depth_conv_node->assigned_target();
175
176 // Extract conv inputs
177 const auto depth_conv_input_id = depth_conv_node->input_edge(0)->producer_id();
178 const auto conv_weights_id = depth_conv_node->input_edge(1)->producer_id();
179 const auto conv_info = depth_conv_node->convolution_info();
180 const auto depth_conv_method = depth_conv_node->depthwise_convolution_method();
181 const auto depth_multiplier = depth_conv_node->depth_multiplier();
182 const auto act_info = bn_node->fused_activation();
183
184 // Extract bn inputs
185 const auto bn_mean_id = bn_node->input_edge(1)->producer_id();
186 const auto bn_var_id = bn_node->input_edge(2)->producer_id();
187 const auto bn_beta_id = bn_node->input_edge(3)->producer_id();
188 const auto bn_gamma_id = bn_node->input_edge(4)->producer_id();
189 const auto epsilon = bn_node->epsilon();
190
191 // Create the fused node
192 const NodeID fused_id = g.add_node<FusedDepthwiseConvolutionBatchNormalizationNode>(epsilon, conv_info, depth_multiplier, depth_conv_method, act_info);
193
194 if(depth_conv_node->input_edge(2) != nullptr)
195 {
196 const auto conv_bias_id = depth_conv_node->input_edge(2)->producer_id();
197 g.add_connection(conv_bias_id, 0, fused_id, 2);
198 }
199
200 // Add connections from the conv/batch_norm inputs to the fused node
201 g.add_connection(depth_conv_input_id, 0, fused_id, 0);
202 g.add_connection(conv_weights_id, 0, fused_id, 1);
203 g.add_connection(bn_mean_id, 0, fused_id, 3);
204 g.add_connection(bn_var_id, 0, fused_id, 4);
205 g.add_connection(bn_beta_id, 0, fused_id, 5);
206 g.add_connection(bn_gamma_id, 0, fused_id, 6);
207
Sheri Zhangc65023e2021-11-03 21:24:00 +0000208 auto fused_node = g.node(fused_id);
209 auto bn_node_name = bn_node->name();
Manuel Bottinibffb41e2019-06-20 16:00:27 +0100210
Sheri Zhangc65023e2021-11-03 21:24:00 +0000211 transfer_driving_nodes_and_remove_old_node(g, fused_node, bn_node, true);
Manuel Bottinibffb41e2019-06-20 16:00:27 +0100212
Manuel Bottinibffb41e2019-06-20 16:00:27 +0100213 fused_node->set_assigned_target(assigned_target);
214 fused_node->set_common_node_parameters(NodeParams{ depth_conv_node->name() + "+" + bn_node_name, assigned_target });
215
216 // Remove convolution node
217 g.remove_node(depth_conv_node->id());
218 }
219 else
220 {
221 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of depthwise convolution with batch normalization due to the presence of an output accessor\n");
222 }
223}
224
Georgios Pinitas08346e92018-10-16 19:10:46 +0100225template <typename N>
giuros01acce5042019-02-21 17:32:34 +0000226void fuse_node_with_activation(Graph &g, const Edge *output_edge, const std::set<Activation> &supported_fused_activations)
227{
228 ARM_COMPUTE_ERROR_ON(output_edge == nullptr);
229
230 auto *n_node = arm_compute::utils::cast::polymorphic_downcast<N *>(output_edge->producer());
231 auto *act_node = arm_compute::utils::cast::polymorphic_downcast<ActivationLayerNode *>(output_edge->consumer());
232
233 ARM_COMPUTE_ERROR_ON(act_node->output(0) == nullptr || n_node->output(0) == nullptr);
234
235 // Check if activation is supported for fusion
236 if(supported_fused_activations.count(act_node->activation_info().activation()) == 0)
237 {
238 return;
239 }
240
Sheri Zhang16dddd22020-05-27 15:03:48 +0100241 // EltwiseLayerNode can only be fused when dataype is float
242 if(n_node->type() == NodeType::EltwiseLayer && !is_data_type_float(n_node->output(0)->desc().data_type))
243 {
244 return;
245 }
246
giuros01acce5042019-02-21 17:32:34 +0000247 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Fusing node with ID : " << output_edge->producer_id()
248 << " with Activation Layer node with ID : " << output_edge->consumer_id() << std::endl);
249
250 // Prevent fusion if fused node has an output accessor
251 if(n_node->output(0)->accessor() == nullptr)
252 {
giuros01acce5042019-02-21 17:32:34 +0000253 // Set activation info to fused node
254 n_node->set_fused_activation(act_node->activation_info());
255
Sheri Zhangc65023e2021-11-03 21:24:00 +0000256 transfer_driving_nodes_and_remove_old_node(g, n_node, act_node, false);
giuros01acce5042019-02-21 17:32:34 +0000257 }
258 else
259 {
260 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of node with activation due to the presence of an output accessor\n");
261 }
262}
263
Gunes Bayir814bddf2021-09-01 16:20:54 +0100264template <typename N>
265void fuse_pad_with_convolution(Graph &g, const Edge *output_edge)
266{
267 auto *pad_node = arm_compute::utils::cast::polymorphic_downcast<PadLayerNode *>(output_edge->producer());
268 auto *conv_node = arm_compute::utils::cast::polymorphic_downcast<N *>(output_edge->consumer());
269
270 const Edge *input_edge = pad_node->input_edge(0);
271 if(input_edge != nullptr && input_edge->tensor() != nullptr && pad_node->output(0)->accessor() == nullptr
272 && pad_node->pad_value().get<float>() == 0.0)
273 {
274 const DataLayout layout = input_edge->tensor()->desc().layout;
275 const PaddingList padding_list = pad_node->padding();
Gunes Bayir814bddf2021-09-01 16:20:54 +0100276
Gunes Bayircc171f92021-09-13 13:38:29 +0100277 const unsigned int height_index = get_dimension_idx(layout, DataLayoutDimension::HEIGHT);
278 const unsigned int width_index = get_dimension_idx(layout, DataLayoutDimension::WIDTH);
279
280 const PaddingInfo pad_w = width_index < padding_list.size() ? padding_list[width_index] : PaddingInfo(0, 0);
281 const PaddingInfo pad_h = height_index < padding_list.size() ? padding_list[height_index] : PaddingInfo(0, 0);
282
283 if(is_padding_in_height_or_width(layout, padding_list))
Gunes Bayir814bddf2021-09-01 16:20:54 +0100284 {
285 // Add paddings to the convolution node
286 const PadStrideInfo conv_info = conv_node->convolution_info();
287 const PadStrideInfo new_conv_info(
288 conv_info.stride().first,
289 conv_info.stride().second,
290 conv_info.pad_left() + pad_w.first,
291 conv_info.pad_right() + pad_w.second,
292 conv_info.pad_top() + pad_h.first,
293 conv_info.pad_bottom() + pad_h.second,
294 conv_info.round());
295 conv_node->set_convolution_info(new_conv_info);
296
297 // Update drivers of the convolution node
298 std::vector<NodeIdxPair> pad_driver_nodes = get_driver_nodes(*pad_node);
299 g.remove_node(pad_node->id());
300
301 // Update fused node inputs
302 for(auto &driver_node : pad_driver_nodes)
303 {
304 g.add_connection(driver_node.node_id, driver_node.index, conv_node->id(), 0);
305 }
306 }
307 }
308}
309
giuros01acce5042019-02-21 17:32:34 +0000310template <typename N1, typename N2, typename F, typename... Args>
311void fuse_layer(Graph &g, std::function<bool(INode &)> const &prec, const F fuse_fcn, Args &&... optional_arguments)
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000312{
SiCongLibc912972021-05-25 14:29:21 +0100313 // Note that fused nodes may be added to the end of the node list.
314 // Instead of only looping over the original list of nodes, we loop over the current node list which could be growing.
315 // This is intentional as it probes the newly added fused nodes for further fusing opportunities.
316 for(unsigned int i = 0; i < g.nodes().size(); ++i)
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000317 {
SiCongLibc912972021-05-25 14:29:21 +0100318 auto node = g.node(i);
Sheri Zhangfb228032021-11-02 10:45:07 +0000319 // Check if the node is of type N1 and not a branching node
giuros01acce5042019-02-21 17:32:34 +0000320 if(node && node->type() == N1::node_type && node->output_edges().size() == 1)
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000321 {
giuros01acce5042019-02-21 17:32:34 +0000322 const auto output_edge_id = *node->output_edges().begin();
323 const auto output_edge = g.edge(output_edge_id);
324
Sheri Zhangfb228032021-11-02 10:45:07 +0000325 // Check if following node is a type N2 node
giuros01acce5042019-02-21 17:32:34 +0000326 if((output_edge != nullptr) && (output_edge->consumer() != nullptr) && (output_edge->consumer()->type() == N2::node_type) && prec(*output_edge->producer()))
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000327 {
giuros01acce5042019-02-21 17:32:34 +0000328 fuse_fcn(g, output_edge, optional_arguments...);
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000329 }
330 }
331 }
332}
Sheri Zhangfb228032021-11-02 10:45:07 +0000333
Sheri Zhangc65023e2021-11-03 21:24:00 +0000334/** Check valid combinations:
335 *
336 * | Main operator | Post operators |
337 * |:--------------|:---------------------------|
338 * |conv | add |
339 * |conv | act + add |
340 * |conv | add + act |
341 * |conv | act + add + act |
342 *
343*/
344#define MAX_VALIDE_COMBINATION 4
345#define MAX_POST_OP_NUM 3
346NodeType valide_post_op_type[MAX_VALIDE_COMBINATION][MAX_POST_OP_NUM] = { { EltwiseLayerNode::node_type },
347 { EltwiseLayerNode::node_type, ActivationLayerNode::node_type },
348 { ActivationLayerNode::node_type, EltwiseLayerNode::node_type },
349 { ActivationLayerNode::node_type, EltwiseLayerNode::node_type, ActivationLayerNode::node_type }
350};
351
352bool check_post_op_type(NodeType *post_op_type, int len)
353{
354 if(len > MAX_POST_OP_NUM || len <= 0)
355 {
356 return false;
357 }
358
359 bool found = false;
360 for(int i = 0; i < MAX_VALIDE_COMBINATION; ++i)
361 {
362 for(int j = 0; j < len; ++j)
363 {
364 if(post_op_type[j] != valide_post_op_type[i][j])
365 {
366 found = false;
367 break;
368 }
369 found = true;
370 }
371 if(found)
372 break;
373 }
374
375 return found;
376}
377
378void fuse_convolution_with_post_op(Graph &g, INode *fused_node, std::list<INode *> post_op_node_list, int prev_op_dst_pos)
379{
380 unsigned int op_idx = 0;
381 // Fuse post operators with conv
382 for(const auto &post_op : post_op_node_list)
383 {
384 switch(post_op->type())
385 {
386 case EltwiseLayerNode::node_type:
387 {
388 auto *eltwise_node = arm_compute::utils::cast::polymorphic_downcast<EltwiseLayerNode *>(post_op);
389 ARM_COMPUTE_ERROR_ON(eltwise_node->output(0) == nullptr);
390
391 fused_node->post_op_info_list().push_back(std::make_unique<ConvPostOpInfoEltwiseAdd>(prev_op_dst_pos, eltwise_node->convert_policy()));
392 ARM_COMPUTE_LOG_GRAPH_VERBOSE(" with Elementwise Layer node with ID : " << post_op->id());
393 break;
394 }
395 case ActivationLayerNode::node_type:
396 {
397 auto *act_node = arm_compute::utils::cast::polymorphic_downcast<ActivationLayerNode *>(post_op);
398 ARM_COMPUTE_ERROR_ON(act_node->output(0) == nullptr);
399
400 fused_node->post_op_info_list().push_back(std::make_unique<ConvPostOpInfoActivation>(act_node->activation_info()));
401 ARM_COMPUTE_LOG_GRAPH_VERBOSE(" with Activation Layer node with ID : " << post_op->id());
402 break;
403 }
404 default:
405 {
406 break;
407 }
408 }
409
410 if(op_idx == post_op_node_list.size() - 1) // last fusable node
411 {
412 transfer_driving_nodes_and_remove_old_node(g, fused_node, post_op, true);
413 }
414 else
415 {
416 // Remove node
417 g.remove_node(post_op->id());
418 }
419 op_idx++;
420 }
421}
422
423std::list<INode *> get_post_op_list(Graph &g, int &eltwise_operand_id, int &prev_op_dst_pos, int conv_node_id, const std::set<Activation> &supported_fused_activations)
424{
425 std::list<INode *> post_op_node_list = {};
426 NodeID prev_op_dst_id = conv_node_id;
427 NodeType post_op_type_list[3] = { NodeType::Dummy, NodeType::Dummy, NodeType::Dummy };
428 int post_op_idx = 0;
429 for(unsigned int i = conv_node_id + 1; i < g.nodes().size(); ++i)
430 {
431 auto post_op_node = g.node(i);
432 bool fusable_post_op = false;
433 if(post_op_node != nullptr && post_op_node->output_edges().size() > 0)
434 {
435 const auto post_op_output_edge_id = *post_op_node->output_edges().begin();
436 const auto post_op_output_edge = g.edge(post_op_output_edge_id);
437
438 if(post_op_output_edge != nullptr)
439 {
440 switch(post_op_output_edge->producer()->type())
441 {
442 case EltwiseLayerNode::node_type:
443 {
444 auto *eltwise_node = arm_compute::utils::cast::polymorphic_downcast<EltwiseLayerNode *>(post_op_output_edge->producer());
445 ARM_COMPUTE_ERROR_ON(eltwise_node->output(0) == nullptr);
446 if(eltwise_node->output(0)->accessor() == nullptr)
447 {
448 post_op_node_list.push_back(post_op_output_edge->producer());
449 fusable_post_op = true;
450 post_op_type_list[post_op_idx++] = eltwise_node->type();
451
452 // Extract elementwise inputs
453 const auto eltwise_input_id_0 = eltwise_node->input_edge(0)->producer_id();
454 const auto eltwise_input_id_1 = eltwise_node->input_edge(1)->producer_id();
455 if(eltwise_input_id_0 == prev_op_dst_id)
456 {
457 eltwise_operand_id = eltwise_input_id_1;
458 prev_op_dst_pos = 0;
459 }
460 else if(eltwise_input_id_1 == prev_op_dst_id)
461 {
462 eltwise_operand_id = eltwise_input_id_0;
463 prev_op_dst_pos = 1;
464 }
465 }
466 else
467 {
468 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of convolution node with elementwise due to the presence of an output accessor\n");
469 }
470 break;
471 }
472 case ActivationLayerNode::node_type:
473 {
474 auto *act_node = arm_compute::utils::cast::polymorphic_downcast<ActivationLayerNode *>(post_op_output_edge->producer());
475 ARM_COMPUTE_ERROR_ON(act_node->output(0) == nullptr);
476 // Check if activation is supported for fusion
477 if(supported_fused_activations.count(act_node->activation_info().activation()) == 0)
478 {
479 break;
480 }
481 if(act_node->output(0)->accessor() == nullptr)
482 {
483 post_op_node_list.push_back(post_op_output_edge->producer());
484 fusable_post_op = true;
485 post_op_type_list[post_op_idx++] = act_node->type();
486 prev_op_dst_id = act_node->id();
487 }
488 else
489 {
490 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of convolution node with activation due to the presence of an output accessor\n");
491 }
492 break;
493 }
494 default:
495 {
496 break;
497 }
498 }
499 }
500
501 // Check if the node is not a branching node and current node is fusable
502 if(post_op_node->output_edges().size() == 1 && fusable_post_op == true && post_op_node_list.size() < 3)
503 {
504 continue;
505 }
506 else
507 {
508 break;
509 }
510 }
511 }
512
513 // Check whether it's valid post op list
514 if(post_op_node_list.size() > 0)
515 {
516 bool fuse_with_post_op = check_post_op_type(post_op_type_list, post_op_node_list.size());
517 if(!fuse_with_post_op)
518 {
519 post_op_node_list.clear();
520 }
521 }
522
523 return post_op_node_list;
524}
525
Sheri Zhangfb228032021-11-02 10:45:07 +0000526/** Fuse below operators:
527 *
528 * | Main operator | Post operators |
529 * |:--------------|:---------------------------|
530 * |conv | add |
531 * |conv | act + add |
532 * |conv | add + act |
533 * |conv | act + add + act |
534 *
535 * Notes: currently, only GEMM supports fusion with post operator
536*/
537template <typename N>
538void fuse_convolution(Graph &g, const Edge *output_edge, int conv_node_id, const std::set<Activation> &supported_fused_activations)
539{
540 ARM_COMPUTE_ERROR_ON(output_edge == nullptr);
541
542 auto *conv_node = arm_compute::utils::cast::polymorphic_downcast<N *>(output_edge->producer());
543 ARM_COMPUTE_ERROR_ON(conv_node->output(0) == nullptr);
Sheri Zhangc65023e2021-11-03 21:24:00 +0000544
545 const ConvolutionMethod conv_algorithm = conv_node->convolution_method();
546 if(conv_algorithm != ConvolutionMethod::GEMM)
547 {
548 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of convolution node with post ops due to non GEMM convolution\n");
549 return;
550 }
551
Sheri Zhangfb228032021-11-02 10:45:07 +0000552 // Prevent fusion if fused node has an output accessor
553 if(conv_node->output(0)->accessor() == nullptr)
554 {
555 // If data type is FP32/FP16, data layout is NHWC, and filter size if 1x1, fuse convolution with post op, as Conv1x1 always leads to GEMM.
556 const Edge *input_edge = conv_node->input_edge(1);
557 if(input_edge != nullptr && input_edge->tensor() != nullptr)
558 {
559 const DataLayout data_layout = input_edge->tensor()->desc().layout;
560 const DataType data_type = input_edge->tensor()->desc().data_type;
561 const TensorShape tensor_shape = input_edge->tensor()->desc().shape;
562 if(data_layout != DataLayout::NHWC || is_data_type_float(data_type) == false || tensor_shape.y() != 1 || tensor_shape.z() != 1)
563 {
564 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of convolution node with post ops due to non GEMM convolution\n");
565 return;
566 }
567 }
568 else
569 {
570 return;
571 }
572
Sheri Zhangc65023e2021-11-03 21:24:00 +0000573 // Get post op list
574 int eltwise_operand_id = 0;
575 int prev_op_dst_pos = 0; // Previous operator dst's postion in current operator
576 std::list<INode *> post_op_node_list = get_post_op_list(g, eltwise_operand_id, prev_op_dst_pos, conv_node_id, supported_fused_activations);
Sheri Zhangfb228032021-11-02 10:45:07 +0000577
578 if(post_op_node_list.size() == 0)
579 {
580 return;
581 }
Sheri Zhangc65023e2021-11-03 21:24:00 +0000582 else // Do convolution fusion with post op if there're one(elementwise), two or more operators
Sheri Zhangfb228032021-11-02 10:45:07 +0000583 {
584 const Target assigned_target = conv_node->assigned_target();
585
586 // Extract conv inputs
587 const auto conv_input_id = conv_node->input_edge(0)->producer_id();
588 const auto conv_weights_id = conv_node->input_edge(1)->producer_id();
589 const auto conv_info = conv_node->convolution_info();
590 const auto conv_method = conv_node->convolution_method();
591 const auto num_groups = conv_node->num_groups();
592 FastMathHint fast_math_hint = conv_node->fast_math_hint();
593
594 // Create the fused node
595 const NodeID fused_id = g.add_node<FusedConvolutionWithPostOpNode>(conv_info, num_groups, conv_method, fast_math_hint);
596 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Fusing convolution node with ID : " << conv_node->id());
597
598 // Add connections from the conv inputs to the fused node
599 g.add_connection(conv_input_id, 0, fused_id, 0);
600 g.add_connection(conv_weights_id, 0, fused_id, 1);
601 if(conv_node->input_edge(2) != nullptr)
602 {
603 auto conv_bias_id = conv_node->input_edge(2)->producer_id();
604 g.add_connection(conv_bias_id, 0, fused_id, 2);
605 }
Sheri Zhangc65023e2021-11-03 21:24:00 +0000606 g.add_connection(eltwise_operand_id, 0, fused_id, 3);
Sheri Zhangfb228032021-11-02 10:45:07 +0000607 g.remove_node(conv_node->id());
608
609 // Update fused node outputs
Sheri Zhangc65023e2021-11-03 21:24:00 +0000610 auto fused_node = g.node(fused_id);
Sheri Zhangfb228032021-11-02 10:45:07 +0000611 fused_node->set_assigned_target(assigned_target);
612
Sheri Zhangc65023e2021-11-03 21:24:00 +0000613 // Fuse convolution with post op
614 fuse_convolution_with_post_op(g, fused_node, post_op_node_list, prev_op_dst_pos);
Sheri Zhangfb228032021-11-02 10:45:07 +0000615
Sheri Zhangfb228032021-11-02 10:45:07 +0000616 post_op_node_list.clear();
617 ARM_COMPUTE_LOG_GRAPH_VERBOSE(std::endl);
618 }
619 }
620 else
621 {
622 ARM_COMPUTE_LOG_GRAPH_VERBOSE("Prevented fusion of convolution node with post ops due to the presence of an output accessor\n");
623 }
624}
625
626template <typename N1, typename F, typename... Args>
627void fuse_layer(Graph &g, std::function<bool(INode &)> const &prec, const F fuse_fcn, Args &&... optional_arguments)
628{
629 // Note that fused nodes may be added to the end of the node list.
630 // Instead of only looping over the original list of nodes, we loop over the current node list which could be growing.
631 // This is intentional as it probes the newly added fused nodes for further fusing opportunities.
632 for(unsigned int i = 0; i < g.nodes().size(); ++i)
633 {
634 auto node = g.node(i);
635 // Check if the node is of type N1 and not a branching node
636 if(node && node->type() == N1::node_type && node->output_edges().size() == 1)
637 {
638 const auto output_edge_id = *node->output_edges().begin();
639 const auto output_edge = g.edge(output_edge_id);
640
641 // Check if it's the correct target
642 if((output_edge != nullptr) && (output_edge->consumer() != nullptr) && prec(*output_edge->producer()))
643 {
644 fuse_fcn(g, output_edge, i, optional_arguments...);
645 }
646 }
647 }
648}
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000649} // namespace detail
650
651const char *NodeFusionMutator::name()
652{
653 return "NodeFusionMutator";
654}
655
Georgios Pinitasf4261ad2019-12-02 11:58:19 +0000656IGraphMutator::MutationType NodeFusionMutator::type() const
657{
658 return IGraphMutator::MutationType::Backend;
659}
660
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000661void NodeFusionMutator::mutate(Graph &g)
662{
Georgios Pinitas08346e92018-10-16 19:10:46 +0100663 // Supported activations when fusing
Sang-Hoon Park68dd25f2020-10-19 16:00:11 +0100664 const std::set<Activation> supported_fused_activations = { Activation::ABS, Activation::BOUNDED_RELU, Activation::ELU,
665 Activation::HARD_SWISH, Activation::IDENTITY, Activation::LEAKY_RELU,
666 Activation::LINEAR, Activation::LOGISTIC, Activation::LU_BOUNDED_RELU,
667 Activation::RELU, Activation::SOFT_RELU, Activation::SQRT,
668 Activation::SQUARE, Activation::TANH
669 };
Georgios Pinitas08346e92018-10-16 19:10:46 +0100670
Georgios Pinitas60e98252018-10-22 16:17:20 +0100671 // Preconditions
Michalis Spyrou299fdd32019-05-01 13:03:59 +0100672 auto empty_prec = [](INode &)
Georgios Pinitas60e98252018-10-22 16:17:20 +0100673 {
674 return true;
675 };
Giorgio Arena8b2a7d32020-02-11 17:21:31 +0000676 auto cl_target_prec = [](INode & n)
677 {
678 return n.assigned_target() == Target::CL;
679 };
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000680 auto qs8_prec = [&g](INode & n)
Georgios Pinitas60e98252018-10-22 16:17:20 +0100681 {
682 ARM_COMPUTE_ERROR_ON(n.output(0) == nullptr);
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000683
684 const auto output_edge_id = *n.output_edges().begin();
685 const auto output_edge = g.edge(output_edge_id);
686 // To perform fusion the two nodes must have same output quantization information
687 const bool same_qinfo = n.output(0)->desc().quant_info == output_edge->producer()->output(0)->desc().quant_info;
688 const bool output_qasymm8 = n.output(0)->desc().data_type == DataType::QASYMM8;
689
Georgios Pinitascadb3682019-03-29 10:54:36 +0000690 return (output_qasymm8 && same_qinfo) || !output_qasymm8;
Georgios Pinitas60e98252018-10-22 16:17:20 +0100691 };
692
693 // Fusion mutations
Sheri Zhangfb228032021-11-02 10:45:07 +0000694
695 detail::fuse_layer<ConvolutionLayerNode>(g, cl_target_prec, detail::fuse_convolution<ConvolutionLayerNode>, supported_fused_activations);
696 detail::fuse_layer<ConvolutionLayerNode, ActivationLayerNode>(g, empty_prec, detail::fuse_node_with_activation<ConvolutionLayerNode>, supported_fused_activations);
697 detail::fuse_layer<ConvolutionLayerNode, BatchNormalizationLayerNode>(g, empty_prec, detail::fuse_convolution_with_batch_normalization);
Gunes Bayir814bddf2021-09-01 16:20:54 +0100698 detail::fuse_layer<PadLayerNode, ConvolutionLayerNode>(g, empty_prec, detail::fuse_pad_with_convolution<ConvolutionLayerNode>);
699 detail::fuse_layer<PadLayerNode, DepthwiseConvolutionLayerNode>(g, empty_prec, detail::fuse_pad_with_convolution<DepthwiseConvolutionLayerNode>);
Gian Marco Iodice047c6fc2020-09-21 14:22:25 +0100700 detail::fuse_layer<BatchNormalizationLayerNode, ActivationLayerNode>(g, empty_prec, detail::fuse_node_with_activation<BatchNormalizationLayerNode>, supported_fused_activations);
Gian Marco Iodice047c6fc2020-09-21 14:22:25 +0100701 detail::fuse_layer<DepthwiseConvolutionLayerNode, ActivationLayerNode>(g, qs8_prec, detail::fuse_node_with_activation<DepthwiseConvolutionLayerNode>, supported_fused_activations);
Sheri Zhangfb228032021-11-02 10:45:07 +0000702 detail::fuse_layer<DepthwiseConvolutionLayerNode, BatchNormalizationLayerNode>(g, empty_prec, detail::fuse_depthwise_convolution_with_batch_normalization);
Gian Marco Iodice047c6fc2020-09-21 14:22:25 +0100703 detail::fuse_layer<FullyConnectedLayerNode, ActivationLayerNode>(g, empty_prec, detail::fuse_node_with_activation<FullyConnectedLayerNode>, supported_fused_activations);
704 detail::fuse_layer<EltwiseLayerNode, ActivationLayerNode>(g, cl_target_prec, detail::fuse_node_with_activation<EltwiseLayerNode>, supported_fused_activations);
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000705}
Georgios Pinitasd9eb2752018-04-03 13:44:29 +0100706} // namespace graph
Georgios Pinitasd8734b52017-12-22 15:27:52 +0000707} // namespace arm_compute