blob: 9c6e1f5b37ea6fb949d745dd1a3924723352234d [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Early optimisation of the network graph, using the rewrite_graph module to do the traversal of the graph. These are
18# split into two parts optimise_graph_a and optimise_graph_b.
Tim Hall79d07d22020-04-27 18:20:16 +010019import math
Diego Russoea6111a2020-04-14 18:41:58 +010020
21import numpy as np
22
23from . import rewrite_graph
Diego Russoea6111a2020-04-14 18:41:58 +010024from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020025from .errors import UnsupportedFeatureError
Dwight Lidman42fed942020-05-29 09:37:03 +020026from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaarde0ef2732020-06-03 08:56:44 +020027from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010028from .operation import NpuBlockType
29from .operation import Operation
Fredrik Svedberga0c36242020-06-03 15:43:31 +020030from .softmax import SoftMax
Charles Xu9a03fdf2020-07-02 15:12:40 +020031from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010032from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010033
34passthrough_nodes = set(("Identity",))
35
36
37def remove_passthrough_tensor(tens, arch):
38 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
39 assert len(tens.ops[0].inputs) == 1
40 tens = tens.ops[0].inputs[0]
41 return tens
42
43
44def rewrite_concat(tens, arch):
45 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
46 concat_op = tens.ops[0]
47 if tens != concat_op.outputs[0]:
48 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
49
50 # Not supported so leave it and run on CPU
51 if not concat_op.run_on_npu:
52 return tens
53
54 inputs, axis = concat_op.get_concat_inputs_axis()
55
56 tens.ops = []
57 offset = 0
58 for idx, inp in enumerate(inputs):
59 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
60 new_op.inputs = [inp]
61 new_op.outputs = [tens]
62 new_op.attrs["concat_axis"] = axis
63 new_op.attrs["concat_start"] = offset
64 offset += inp.shape[axis]
65 new_op.attrs["concat_end"] = offset
66 new_op.run_on_npu = True
67 tens.ops.append(new_op)
68 assert tens.shape[axis] == offset
69
70 return tens
71
72
73def rewrite_split(tens, arch):
74
75 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
76 split_op = tens.ops[0]
77
78 # Not supported so leave it and run on CPU
79 if not split_op.run_on_npu:
80 return tens
81
82 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
83
84 tens.ops = []
85 new_op = Operation("SplitSliceRead", split_op.name)
86 new_op.inputs = [inp]
87 new_op.outputs = [tens]
88
89 # For Split the offset cannot be extracted from the tensor so it has to
90 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +010091 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +010092 # Get the start and end of the split
93 offset_start = [0] * len(tens.shape)
94 offset_end = [0] * len(tens.shape)
95 for out in outputs:
96 if out == tens:
97 break
98 offset_start[axis] += out.shape[axis]
99
100 offset_end[axis] = offset_start[axis] + tens.shape[axis]
101
102 new_op.attrs["split_start"] = offset_start
103 new_op.attrs["split_end"] = offset_end
104 new_op.run_on_npu = True
105 tens.ops.append(new_op)
106
107 return tens
108
109
110def needed_total_padding(input_size, stride, filter_size):
111 out_size = (input_size + stride - 1) // stride
112 needed_input = (out_size - 1) * stride + filter_size
113 total_padding = max(0, needed_input - input_size)
114 return total_padding
115
116
117def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
118 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
119 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
120 if padding_type == b"SAME":
121 left_pad = (xpad + 0) // 2
122 right_pad = (xpad + 1) // 2
123 top_pad = (ypad + 0) // 2
124 bottom_pad = (ypad + 1) // 2
125 elif padding_type == b"VALID":
126 left_pad = 0
127 right_pad = 0
128 top_pad = 0
129 bottom_pad = 0
130 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200131 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100132 padding = (top_pad, left_pad, bottom_pad, right_pad)
133 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
134 return padding, skirt
135
Tim Hallc30f4952020-06-15 20:47:35 +0100136
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200137def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
138 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200139 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200140 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
141 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
142
143 right_pad = ((xpad + 1) // upscaling_factor) - 1
144 bottom_pad = ((ypad + 1) // upscaling_factor) - 1
145 left_pad = max(kernel_width - 1 - right_pad, 0)
146 top_pad = max(kernel_height - 1 - bottom_pad, 0)
147
Jacob Bohlincf7da102020-05-20 09:03:40 +0200148 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200149 right_pad = max(kernel_width - 2, 0)
150 bottom_pad = max(kernel_height - 2, 0)
151 left_pad = kernel_width - 1
152 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200153 else:
154 assert 0, "Unknown padding"
155
156 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200157 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200158 return padding, skirt
159
Tim Hall79d07d22020-04-27 18:20:16 +0100160
161def fixup_conv2d_backprop(op, arch):
162 if op.type == "Conv2DBackpropInput":
163 # flip the inputs
164 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200165 op.type = "Conv2DBackpropInputSwitchedBias"
166 weight_shape = op.inputs[1].shape
167 weight_sets = weight_shape[3]
168
169 if len(op.inputs) < 4:
170 # Add bias/scale tensor filled with zeros
171 scale_op = Operation("Const", op.name + "_bias")
172 scale_tens = Tensor([weight_sets], DataType.int32, op.name + "_bias_tens")
173 scale_tens.values = [0] * weight_sets
174 scale_tens.quant_values = [0] * weight_sets
175 scale_tens.ops = [scale_op]
176 scale_op.outputs = [scale_tens]
177 scale_tens.consumer_list = [op]
178 op.inputs.append(scale_tens)
179
180 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100181 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100182
183 return op
184
185
Charles Xu9a03fdf2020-07-02 15:12:40 +0200186# Convert the op to an elementwise add
187def convert_resizebilinear_1x1_to_add(op):
188 op.type = "AddAct"
189 op.name = op.name + "_add"
190 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
191 op.attrs["resizebilinear"] = True
192 # Create an input tensor filled with zeros
193 shape = op.outputs[0].shape
194 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
195 tens.values = np.zeros(shape)
196 tens.quant_values = np.zeros(shape, np.uint8)
197 tens.quantization = QuantizationParameters(0.0, 255.0)
198 tens.quantization.scale_f32 = 1.0
199 tens.quantization.zero_point = 0
200 tens.consumer_list = [op]
201 tens_op = op.inputs[1].ops[0]
202 tens_op.outputs = [tens]
203 tens.ops = [tens_op]
204 # Set the add inputs
205 op.inputs[1] = op.inputs[0]
206 op.inputs[0] = tens
207
208 return op
209
210
211def fixup_resizebilinear(op, arch):
212 if op.type == "ResizeBilinear":
213 if op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
214 convert_resizebilinear_1x1_to_add(op)
215
216 return op
217
218
Tim Hall79d07d22020-04-27 18:20:16 +0100219def fixup_fully_connected_input(op, arch):
220 if op.type == "FullyConnectedAct":
221 inp = op.inputs[0]
222 weights = op.inputs[1]
223
224 n_in_elems = weights.shape[-2]
225 elms = inp.elements()
226 batch_size = elms // n_in_elems
227 assert batch_size * n_in_elems == elms
228
229 desired_shape = [batch_size, n_in_elems]
230 if inp.shape != desired_shape:
231 # mismatch, insert a reshape to fix this.
232 reshape_name = op.name + "_reshape"
233 new_shape_tens = Tensor([1], DataType.int32, reshape_name + "_shape")
234 new_shape_tens.values = np.array(desired_shape)
235 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
236 new_shape_tens.ops = [new_shape_tens_const]
237 new_shape_tens_const.outputs = [new_shape_tens]
238
239 reshape_op = Operation("Reshape", reshape_name)
240 reshape_op.inputs = [inp, new_shape_tens]
241 reshape_op.attrs["new_shape"] = desired_shape
242 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100243 reshape_out.set_all_shapes(desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100244 reshape_out.ops = [reshape_op]
245 reshape_op.outputs = [reshape_out]
246
247 op.inputs[0] = reshape_out
248
249 return op
250
251
252def fixup_pack_input(op, arch):
253 if op.type == "Pack":
254 # Pack is also referred to as Stack
255 # Requires the rewrite_concat function to be called on the op afterwards
256 axis = int(op.attrs["axis"])
257 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
258
259 # Construct 1 shape tensor to be used by all inserted reshape ops
260 new_shape_name = op.name + "_reshape_shape"
261 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
262 new_shape_tens.values = np.array(desired_shape)
263 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
264 new_shape_tens.ops = [new_shape_tens_const]
265 new_shape_tens_const.outputs = [new_shape_tens]
266
267 for idx, inp in enumerate(op.inputs):
268 reshape_name = op.name + str(idx) + "_reshape"
269 reshape_op = Operation("Reshape", reshape_name)
270 reshape_op.inputs = [inp, new_shape_tens]
271 reshape_op.attrs["new_shape"] = desired_shape
272 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100273 reshape_out.set_all_shapes(desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100274 reshape_out.ops = [reshape_op]
275 reshape_op.outputs = [reshape_out]
276
277 op.inputs[idx] = reshape_out
278
279 op.type = "PackReshaped"
280
281 return op
282
283
284def fixup_unpack_output(tens, arch):
285 op = tens.ops[0]
286 if op.type in set(("Unpack", "StridedSlice")):
287 # Unpack is also referred to as Unstack
288 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200289
290 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100291 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200292 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100293 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200294 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200295
296 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
297 # Not supported, will be put on CPU
298 return tens
299 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100300 # Equal Rank StridedSlice, no need to insert reshape
301 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200302 elif shrink_axis_mask != 0:
303 n = 0
304 axis = 0
305 while shrink_axis_mask:
306 prev_mask = shrink_axis_mask
307 n += 1
308 shrink_axis_mask &= shrink_axis_mask - 1
309 axis = int(math.log2(prev_mask - shrink_axis_mask))
310 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100311
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200312 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
313 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100314
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200315 elif new_axis_mask != 0:
316 n = 0
317 axis = 0
318 while new_axis_mask:
319 prev_mask = new_axis_mask
320 n += 1
321 new_axis_mask &= new_axis_mask - 1
322 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200323 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200324 new_axis_mask >>= 1
325
326 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
327 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100328 else:
329 axis = int(op.attrs["axis"])
330 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200331 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100332
333 # Construct 1 shape tensor to be used by all inserted reshape ops
334 new_shape_name = op.name + "_reshape_shape"
335 new_shape_tens = Tensor([1], DataType.int32, new_shape_name)
336 new_shape_tens.values = np.array(tens.shape)
337 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
338 new_shape_tens.ops = [new_shape_tens_const]
339 new_shape_tens_const.outputs = [new_shape_tens]
340
341 for idx, out_tens in enumerate(op.outputs):
342 reshape_name = op.name + str(idx) + "_reshape"
343 reshape_op = Operation("Reshape", reshape_name)
344 reshape_op.outputs = [out_tens]
345 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100346 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100347 reshape_in.ops = [op]
348 out_tens.ops = [reshape_op]
349 reshape_op.inputs = [reshape_in, new_shape_tens]
350
351 op.outputs[idx] = reshape_in
352
353 return tens
354
355
356def add_padding_fields(op, arch):
357 if "padding" in op.attrs:
358 if "Conv" in op.type:
359 kernel_size = op.inputs[1].shape[:2]
360 input_shape = op.inputs[0].shape
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200361 elif "Pool" in op.type or op.type in ("ResizeBilinear", "ReduceSum"):
Tim Hall79d07d22020-04-27 18:20:16 +0100362 kernel_size = op.attrs["ksize"][1:3]
363 input_shape = op.inputs[0].shape
364 elif op.type == "ExtractImagePatches":
365 kernel_size = op.attrs["ksizes"][1:3]
366 input_shape = op.inputs[0].shape
367 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200368 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100369
Jacob Bohlincf7da102020-05-20 09:03:40 +0200370 if op.type == "Conv2DBackpropInputSwitchedBias":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200371 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
Tim Hallc30f4952020-06-15 20:47:35 +0100372 padding, skirt = calc_upscaled_padding_and_skirt(
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200373 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
Tim Hallc30f4952020-06-15 20:47:35 +0100374 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200375 else:
376 dilation_h, dilation_w = op.get_dilation_h_w()
377 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
Tim Hallc30f4952020-06-15 20:47:35 +0100378 padding, skirt = calc_padding_and_skirt(
379 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
380 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200381
Tim Hall79d07d22020-04-27 18:20:16 +0100382 op.attrs["explicit_padding"] = padding
383 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200384
Tim Hall79d07d22020-04-27 18:20:16 +0100385 return op
386
387
Jacob Bohlincf7da102020-05-20 09:03:40 +0200388conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
Tim Hall79d07d22020-04-27 18:20:16 +0100389fc_op = set(
390 (
391 "MatMul",
392 "QuantizedMatMul",
393 "BlockLSTM",
394 "RnnAct",
395 "UnidirectionalSequenceRnnAct",
396 "BidirectionalSequenceRnnAct",
397 "LstmAct",
398 "UnidirectionalSequenceLstmAct",
399 "BidirectionalSequenceLstmAct",
400 "FullyConnectedAct",
401 )
402)
403depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200404pool_op = set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200405 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
Louis Verhaard7db78962020-05-25 15:05:26 +0200406)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200407reduce_sum_ops = set(("ReduceSum",))
408elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs", "CLZ", "SHL", "SHR"))
Charles Xu78792222020-05-13 10:15:26 +0200409binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100410activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
411memory_only_ops = set(("Reshape",))
412
Diego Russoea6111a2020-04-14 18:41:58 +0100413
Tim Hall79d07d22020-04-27 18:20:16 +0100414# Check if the op can be reordered
415def get_prepend_op(op):
416 inp = op.inputs[0]
417 # The op should be reordered between prev_op and prep_op
418 prev_op = inp.ops[-1]
419 prep_op = None
420 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
421 prep_op = prev_op
422 inp = prev_op.inputs[0]
423 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100424 if prev_op is not None and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100425 return prep_op
426
427 return None
428
429
430def mark_npu_block_type(op, arch):
431 npu_block_type = NpuBlockType.Default
432 if op.type in conv_op:
433 npu_block_type = NpuBlockType.ConvolutionMxN
434 elif op.type in fc_op:
435 npu_block_type = NpuBlockType.VectorProduct
436 elif op.type in depthwise_op:
437 npu_block_type = NpuBlockType.ConvolutionDepthWise
438 elif op.type in pool_op:
439 npu_block_type = NpuBlockType.Pooling
440 elif op.type in elementwise_op:
441 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200442 elif op.type in reduce_sum_ops:
443 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100444
445 op.attrs["npu_block_type"] = npu_block_type
446 return op
447
448
449def convert_depthwise_to_conv(op, arch):
450 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
451 # the ofm depth equals the depth multipler.
452 # If those conditions are true, then we can perform a simple
453 # switch of the operator type (and weight order)
454
455 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
456 ifm_tensor = op.inputs[0]
457 weight_tensor = op.inputs[1]
458 ofm_tensor = op.outputs[0]
459 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
460 # Change op type to Conv2d
461 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
462 del op.attrs["channel_multiplier"]
463 del op.attrs["depth_multiplier"]
464
465 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100466 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100467 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200468 raise UnsupportedFeatureError(
469 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100470 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
471 )
472 )
Tim Hall79d07d22020-04-27 18:20:16 +0100473 return op
474
475
Jacob Bohline843d332020-06-23 12:12:56 +0200476def reorder_depthwise_weights(op, arch):
477 if "DepthwiseConv2d" in op.type:
478 weight_tensor = op.inputs[1]
479 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100480 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200481 weight_tensor.weight_transpose_depthwise = True
482
483 return op
484
485
Michael McGeagh8d939c02020-07-29 13:11:43 +0100486def convert_conv_to_fc(op, arch):
487 # Conv 1x1 can be equivalent to Fully Connected.
488 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
489 # caching/double buffering for the weights.
490 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
491 if op.type == "Conv2DBiasAct":
492 _, h, w, _ = op.inputs[0].shape
493 kh, kw, _, _ = op.inputs[1].shape
494 if h == 1 and w == 1 and kh == 1 and kw == 1:
495 # Overwrite this op as a Fully Connected Op
496 op.name += "_fc"
497 op.type = "FullyConnectedAct"
498 faf = op.attrs.get("fused_activation_function", None)
499 op.attrs = {
500 "fused_activation_function": faf,
501 "weights_format": 0,
502 "npu_block_type": NpuBlockType.VectorProduct,
503 }
504 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
505 weight_tensor = op.inputs[1]
506 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
507 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
508 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
509 # back to 4D afterwards as the next layer is expecting that shape
510 orig_ofm_tensor = op.outputs[0]
511 # Reshape this ops output to be 2D: {(N*H*W), C} (We know N H and W are all 1 so this becomes {1, C})
512 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
513 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
514 fc_ofm_tensor.ops = [op]
515 # Add a reshape after the new OFM to convert it back to the original 4D shape
516 reshape_name = op.name + "_reshape_post"
517 new_shape_tens = Tensor([1], DataType.int32, reshape_name + "_shape")
518 new_shape_tens.values = np.array(orig_ofm_tensor.shape)
519 new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const")
520 new_shape_tens.ops = [new_shape_tens_const]
521 new_shape_tens_const.outputs = [new_shape_tens]
522 reshape_op = Operation("Reshape", reshape_name)
523 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
524 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
525 orig_ofm_tensor.ops = [reshape_op]
526 reshape_op.outputs = [orig_ofm_tensor]
527 # Replace this ops OFM to point to the 2D tensor
528 op.outputs[0] = fc_ofm_tensor
529 return op
530
531
Tim Hall79d07d22020-04-27 18:20:16 +0100532# Reorder activation op if it's after the memory only operations
533def fixup_act_reorder(op, arch):
534 if op.type in activation_ops:
535 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100536 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100537 act_op = op.clone("_reordered")
538 act_op.inputs = [prep_op.inputs[0]]
539 act_op_out = act_op.inputs[0].clone("_acted")
540 act_op_out.quantization = op.outputs[0].quantization.clone()
541 act_op_out.ops = [act_op]
542 act_op.outputs = [act_op_out]
543 prep_op.inputs[0] = act_op_out
544 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
545
546 # Mark the op so that it will be removed as passthrough later on
547 op.type = "Identity"
548 return op
549
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200550
Charles Xu78792222020-05-13 10:15:26 +0200551def fixup_elementwise_with_scalars(op, arch):
552 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200553 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200554 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
555 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
556 if diff > 0:
557 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
558 elif diff < 0:
559 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200560 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
561 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
562 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
563 ifm_tensor.storage_shape = ifm_tensor.shape
564 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
565 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
566 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
567 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200568 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100569
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200570
Tim Hall4e127762020-05-15 16:05:49 +0100571# Set input/output tensor equivalence to the same id for memory operations
572def set_tensor_equivalence(op, arch):
573 if op.type == "Reshape":
574 eid = op.outputs[0].equivalence_id
575 for inp in op.inputs:
576 inp.equivalence_id = eid
577 return op
578
579
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200580def convert_softmax(op, arch):
581 if op.type == "Softmax" and op.run_on_npu:
582 softmax = SoftMax(op)
583 op = softmax.get_graph()
584 return op
585
586
Tim Hall79d07d22020-04-27 18:20:16 +0100587def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100588 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100589
590 Input X For X = -1 or X > 0
591 | \ / This subgraph can be replaced with either
592 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
593 | /
594 Max
595 """
596
597 if op.type == "Maximum":
598 # finds the Mul input(s) to the Max
599 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
600 if len(muls) == 1:
601 mul = muls[0].ops[0]
602 elif len(muls) == 2:
603 # In the case both inputs are Muls, find the one with the same input as the Max
604 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
605 else:
606 # No Mul inputs
607 return op
608
609 # make sure the Mul doesn't have any other consumers
610 if len(mul.outputs[0].consumers()) != 1:
611 return op
612 # make sure the Mul doesn't have a faf
613 if mul.attrs["fused_activation_function"]:
614 return op
615
616 # finds the branched input that goes to both the Max and the Mul
617 shared = set(op.inputs) & set(mul.inputs)
618 if len(shared) == 1:
619 shared_in = shared.pop()
620 # find the constant scalar input to the Mul
621 const_tens = (set(mul.inputs) - {shared_in}).pop()
622 # check that it is a scalar
623 if const_tens.shape != []:
624 return op
625 const = const_tens.ops[0]
626 # check that it is a constant
627 if const.type != "Const":
628 return op
629 else:
630 return op
631
632 val = const.outputs[0].values
633 if val >= 0:
634 new_op = "LeakyRelu"
635 op.attrs["alpha"] = val
636 elif val == -1:
637 new_op = "Abs"
638 else:
639 return op
640
641 op.type = op.type.replace("Maximum", new_op)
642 op.name = op.name.replace("Maximum", new_op)
643 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
644 op.inputs = [shared_in]
645 return op
646
647
Dwight Lidman42fed942020-05-29 09:37:03 +0200648def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100649 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200650 input_tensor = op.inputs[0]
651 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
652 out_shape = op.outputs[0].shape[1:3]
653 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
654 # this means the output is supposed to be a x2 upscale,
655 # so we need to do SAME padding
656 op.attrs["padding"] = b"SAME"
657 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
658 # here we can just run the avg pool without padding and
659 # produce a (M * 2 - 1, N * 2 - 1) sized output
660 op.attrs["padding"] = b"VALID"
661 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +0200662 return op
Dwight Lidman42fed942020-05-29 09:37:03 +0200663 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100664 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200665 return op
666
667
Tim Hall79d07d22020-04-27 18:20:16 +0100668def supported_operator_check(op, arch):
669 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
670 return op
671
672
673def optimise_graph_a(nng, arch, verbose_graph=False):
674 if verbose_graph:
675 nng.print_graph()
676
677 op_rewrite_list = [
678 # mark block type and check if the operations are supported
679 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100680 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100681 supported_operator_check,
682 # then do any rewrites of supported operators
683 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100684 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200685 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +0100686 fixup_fully_connected_input,
687 fixup_pack_input,
688 fixup_conv2d_backprop,
689 fixup_act_reorder,
Dwight Lidman42fed942020-05-29 09:37:03 +0200690 add_attrs_to_resizebilinear,
Tim Hall79d07d22020-04-27 18:20:16 +0100691 add_padding_fields,
692 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200693 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200694 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +0200695 fixup_resizebilinear,
Tim Hall79d07d22020-04-27 18:20:16 +0100696 # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved
697 ]
698
699 for idx, sg in enumerate(nng.subgraphs):
700 # rewrite graph pass
701 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100702 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100703 )
704
705 for idx, sg in enumerate(nng.subgraphs):
706 # remove passthrough tensors
Diego Russoea6111a2020-04-14 18:41:58 +0100707 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100708
709 if verbose_graph:
710 nng.print_graph()
711 return nng
712
Diego Russoea6111a2020-04-14 18:41:58 +0100713
Tim Hall79d07d22020-04-27 18:20:16 +0100714def optimise_graph_b(nng, arch, verbose_graph=False):
715 if verbose_graph:
716 nng.print_graph()
717
718 for idx, sg in enumerate(nng.subgraphs):
719 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100720 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100721
722 if verbose_graph:
723 nng.print_graph()
724 return nng