blob: a89f8e63839a9ac99b24853bcb84b3d0f48efc16 [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
Louis Verhaardd7911c42020-08-25 13:36:41 +020023from . import fp_math
Louis Verhaardb9fc33c2020-08-13 11:47:36 +020024from . import lut
Diego Russoea6111a2020-04-14 18:41:58 +010025from . import rewrite_graph
Louis Verhaardd7911c42020-08-25 13:36:41 +020026from . import scaling
Diego Russoea6111a2020-04-14 18:41:58 +010027from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020028from .errors import UnsupportedFeatureError
Dwight Lidman42fed942020-05-29 09:37:03 +020029from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaarde0ef2732020-06-03 08:56:44 +020030from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010031from .operation import NpuBlockType
32from .operation import Operation
Fredrik Svedberga0c36242020-06-03 15:43:31 +020033from .softmax import SoftMax
Michael McGeaghc5b549b2020-08-07 11:54:28 +010034from .tensor import create_const_tensor
35from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020036from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010037from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010038
39passthrough_nodes = set(("Identity",))
40
41
42def remove_passthrough_tensor(tens, arch):
43 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
44 assert len(tens.ops[0].inputs) == 1
45 tens = tens.ops[0].inputs[0]
46 return tens
47
48
49def rewrite_concat(tens, arch):
50 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
51 concat_op = tens.ops[0]
52 if tens != concat_op.outputs[0]:
53 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
54
55 # Not supported so leave it and run on CPU
56 if not concat_op.run_on_npu:
57 return tens
58
59 inputs, axis = concat_op.get_concat_inputs_axis()
60
61 tens.ops = []
62 offset = 0
63 for idx, inp in enumerate(inputs):
64 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
65 new_op.inputs = [inp]
66 new_op.outputs = [tens]
67 new_op.attrs["concat_axis"] = axis
68 new_op.attrs["concat_start"] = offset
69 offset += inp.shape[axis]
70 new_op.attrs["concat_end"] = offset
71 new_op.run_on_npu = True
72 tens.ops.append(new_op)
73 assert tens.shape[axis] == offset
74
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020075 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
76 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
77 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
Patrik Gustavsson458a2082020-08-13 13:41:05 +020078 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020079 if axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +020080 for op in tens.ops:
81 if op.attrs["concat_start"] % 16 != 0:
82 tens.avoid_NHCWB16 = True
83 break
84
Tim Hall79d07d22020-04-27 18:20:16 +010085 return tens
86
87
88def rewrite_split(tens, arch):
89
90 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
91 split_op = tens.ops[0]
92
93 # Not supported so leave it and run on CPU
94 if not split_op.run_on_npu:
95 return tens
96
97 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
98
99 tens.ops = []
100 new_op = Operation("SplitSliceRead", split_op.name)
101 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100102
103 # For Split the offset cannot be extracted from the tensor so it has to
104 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100105 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100106 # Get the start and end of the split
107 offset_start = [0] * len(tens.shape)
108 offset_end = [0] * len(tens.shape)
109 for out in outputs:
110 if out == tens:
111 break
112 offset_start[axis] += out.shape[axis]
113
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200114 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
115 if (offset_start[-1] % 16) != 0:
116 inp.avoid_NHCWB16 = True
117
Tim Hall79d07d22020-04-27 18:20:16 +0100118 offset_end[axis] = offset_start[axis] + tens.shape[axis]
119
120 new_op.attrs["split_start"] = offset_start
121 new_op.attrs["split_end"] = offset_end
122 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100123 new_op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100124
125 return tens
126
127
128def needed_total_padding(input_size, stride, filter_size):
129 out_size = (input_size + stride - 1) // stride
130 needed_input = (out_size - 1) * stride + filter_size
131 total_padding = max(0, needed_input - input_size)
132 return total_padding
133
134
135def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
136 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
137 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
138 if padding_type == b"SAME":
139 left_pad = (xpad + 0) // 2
140 right_pad = (xpad + 1) // 2
141 top_pad = (ypad + 0) // 2
142 bottom_pad = (ypad + 1) // 2
143 elif padding_type == b"VALID":
144 left_pad = 0
145 right_pad = 0
146 top_pad = 0
147 bottom_pad = 0
148 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200149 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100150 padding = (top_pad, left_pad, bottom_pad, right_pad)
151 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
152 return padding, skirt
153
Tim Hallc30f4952020-06-15 20:47:35 +0100154
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200155def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
156 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200157 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200158 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
159 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
160
Jacob Bohlind47cc272020-08-24 11:42:14 +0200161 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
162 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200163 left_pad = max(kernel_width - 1 - right_pad, 0)
164 top_pad = max(kernel_height - 1 - bottom_pad, 0)
165
Jacob Bohlincf7da102020-05-20 09:03:40 +0200166 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200167 right_pad = max(kernel_width - 2, 0)
168 bottom_pad = max(kernel_height - 2, 0)
169 left_pad = kernel_width - 1
170 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200171 else:
172 assert 0, "Unknown padding"
173
174 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200175 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200176 return padding, skirt
177
Tim Hall79d07d22020-04-27 18:20:16 +0100178
179def fixup_conv2d_backprop(op, arch):
180 if op.type == "Conv2DBackpropInput":
181 # flip the inputs
182 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200183 op.type = "Conv2DBackpropInputSwitchedBias"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200184
185 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100186 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100187
188 return op
189
190
Charles Xu9a03fdf2020-07-02 15:12:40 +0200191# Convert the op to an elementwise add
192def convert_resizebilinear_1x1_to_add(op):
193 op.type = "AddAct"
194 op.name = op.name + "_add"
195 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
196 op.attrs["resizebilinear"] = True
197 # Create an input tensor filled with zeros
198 shape = op.outputs[0].shape
199 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
200 tens.values = np.zeros(shape)
201 tens.quant_values = np.zeros(shape, np.uint8)
202 tens.quantization = QuantizationParameters(0.0, 255.0)
203 tens.quantization.scale_f32 = 1.0
204 tens.quantization.zero_point = 0
205 tens.consumer_list = [op]
206 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100207 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200208 # Set the add inputs
209 op.inputs[1] = op.inputs[0]
210 op.inputs[0] = tens
211
212 return op
213
214
Charles Xu87c13502020-08-06 12:17:26 +0200215# Convert ResizeBilinear to a number of 2x2 pool ops
216def convert_resizebilinear_to_2x2_pool(op):
217 count = 0
218 pre_op = op
219 outputs = op.outputs
220
221 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
222 if op.attrs["align_corners"]:
223 shape_modifier = 1
224 op.attrs["padding"] = b"VALID"
225 else:
226 shape_modifier = 0
227 op.attrs["padding"] = b"SAME"
228 op.inputs[0].resampling_mode = resampling_mode.NEAREST
229
230 upscaled_shape = np.array(op.inputs[0].shape[1:3])
231 out_shape = np.array(op.outputs[0].shape[1:3])
232 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
233 return op
234
235 while (upscaled_shape < out_shape).all():
236 if count == 0:
237 scaled_op = pre_op
238 else:
239 scaled_op = op.clone("_{}".format(count))
240 scaled_op.inputs[0] = pre_op.outputs[0]
241
242 upscaled_shape = upscaled_shape * 2 - shape_modifier
243
244 if (upscaled_shape == out_shape).all():
245 scaled_op.outputs = outputs
246 scaled_op.outputs[0].ops = [scaled_op]
247 else:
248 shape = outputs[0].shape.copy()
249 shape[1:3] = upscaled_shape[0:2]
250 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
251 out_tens.quantization = op.outputs[0].quantization.clone()
252 out_tens.quantization.quant_min = np.iinfo(np.int16).min
253 out_tens.quantization.quant_max = np.iinfo(np.int16).max
254 scaled_op.set_output_tensor(out_tens)
255 pre_op = scaled_op
256 count += 1
257
258 # Setup the scale value
259 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
260 scaled_op.attrs["rescale"] = 128
261 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
262 scaled_op.attrs["rescale"] = 1 / 128
263 elif "rescale" in scaled_op.attrs:
264 del scaled_op.attrs["rescale"]
265
266 return op
267
268
Charles Xu9a03fdf2020-07-02 15:12:40 +0200269def fixup_resizebilinear(op, arch):
Charles Xu87c13502020-08-06 12:17:26 +0200270 if op.type == "ResizeBilinear" and op.run_on_npu:
271 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200272 # Bypass nop resizebilinear
273 op.inputs = op.inputs[:1]
274 op.type = "Identity"
Charles Xu87c13502020-08-06 12:17:26 +0200275 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
276 convert_resizebilinear_1x1_to_add(op)
277 else:
278 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200279
280 return op
281
282
Tim Hall79d07d22020-04-27 18:20:16 +0100283def fixup_fully_connected_input(op, arch):
284 if op.type == "FullyConnectedAct":
285 inp = op.inputs[0]
286 weights = op.inputs[1]
287
288 n_in_elems = weights.shape[-2]
289 elms = inp.elements()
290 batch_size = elms // n_in_elems
291 assert batch_size * n_in_elems == elms
292
293 desired_shape = [batch_size, n_in_elems]
294 if inp.shape != desired_shape:
295 # mismatch, insert a reshape to fix this.
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100296 op.inputs[0] = create_reshape_tensor(inp, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100297
298 return op
299
300
301def fixup_pack_input(op, arch):
302 if op.type == "Pack":
303 # Pack is also referred to as Stack
304 # Requires the rewrite_concat function to be called on the op afterwards
305 axis = int(op.attrs["axis"])
306 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
307
308 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100309 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100310
311 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100312 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100313 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100314
315 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
316 reshape_op.attrs["new_shape"] = desired_shape
317 reshape_op.inputs = [inp, new_shape_tens]
318 reshape_op.set_output_tensor(reshape_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100319
320 op.inputs[idx] = reshape_out
321
322 op.type = "PackReshaped"
323
324 return op
325
326
327def fixup_unpack_output(tens, arch):
328 op = tens.ops[0]
329 if op.type in set(("Unpack", "StridedSlice")):
330 # Unpack is also referred to as Unstack
331 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200332
333 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100334 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200335 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100336 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200337 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200338
339 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
340 # Not supported, will be put on CPU
341 return tens
342 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100343 # Equal Rank StridedSlice, no need to insert reshape
344 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200345 elif shrink_axis_mask != 0:
346 n = 0
347 axis = 0
348 while shrink_axis_mask:
349 prev_mask = shrink_axis_mask
350 n += 1
351 shrink_axis_mask &= shrink_axis_mask - 1
352 axis = int(math.log2(prev_mask - shrink_axis_mask))
353 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100354
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200355 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
356 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100357
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200358 elif new_axis_mask != 0:
359 n = 0
360 axis = 0
361 while new_axis_mask:
362 prev_mask = new_axis_mask
363 n += 1
364 new_axis_mask &= new_axis_mask - 1
365 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200366 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200367 new_axis_mask >>= 1
368
369 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
370 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100371 else:
372 axis = int(op.attrs["axis"])
373 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200374 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100375
376 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100377 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100378
379 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100380 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100381 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100382 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100383
384 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
385 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100386 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100387 reshape_op.set_output_tensor(out_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100388
389 op.outputs[idx] = reshape_in
390
391 return tens
392
393
394def add_padding_fields(op, arch):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200395 if op.run_on_npu:
396 if "padding" in op.attrs:
397 if "Conv" in op.type:
398 kernel_size = op.inputs[1].shape[:2]
399 input_shape = op.inputs[0].shape
400 elif "Pool" in op.type or op.type in ("ResizeBilinear", "ReduceSum"):
401 kernel_size = op.attrs["ksize"][1:3]
402 input_shape = op.inputs[0].shape
403 elif op.type == "ExtractImagePatches":
404 kernel_size = op.attrs["ksizes"][1:3]
405 input_shape = op.inputs[0].shape
406 else:
407 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100408
Jacob Bohlin90033f32020-08-28 15:45:44 +0200409 if op.type == "Conv2DBackpropInputSwitchedBias":
410 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
411 padding, skirt = calc_upscaled_padding_and_skirt(
412 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
413 )
414 else:
415 dilation_h, dilation_w = op.get_dilation_h_w()
416 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
417 padding, skirt = calc_padding_and_skirt(
418 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
419 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200420
Jacob Bohlin90033f32020-08-28 15:45:44 +0200421 op.attrs["explicit_padding"] = padding
422 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200423
Tim Hall79d07d22020-04-27 18:20:16 +0100424 return op
425
426
Jacob Bohlincf7da102020-05-20 09:03:40 +0200427conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
Tim Hall79d07d22020-04-27 18:20:16 +0100428fc_op = set(
429 (
430 "MatMul",
431 "QuantizedMatMul",
432 "BlockLSTM",
433 "RnnAct",
434 "UnidirectionalSequenceRnnAct",
435 "BidirectionalSequenceRnnAct",
436 "LstmAct",
437 "UnidirectionalSequenceLstmAct",
438 "BidirectionalSequenceLstmAct",
439 "FullyConnectedAct",
440 )
441)
442depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200443pool_op = set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200444 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
Louis Verhaard7db78962020-05-25 15:05:26 +0200445)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200446reduce_sum_ops = set(("ReduceSum",))
447elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs", "CLZ", "SHL", "SHR"))
Charles Xu78792222020-05-13 10:15:26 +0200448binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100449activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
450memory_only_ops = set(("Reshape",))
451
Diego Russoea6111a2020-04-14 18:41:58 +0100452
Tim Hall79d07d22020-04-27 18:20:16 +0100453# Check if the op can be reordered
454def get_prepend_op(op):
455 inp = op.inputs[0]
456 # The op should be reordered between prev_op and prep_op
457 prev_op = inp.ops[-1]
458 prep_op = None
459 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
460 prep_op = prev_op
461 inp = prev_op.inputs[0]
462 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100463 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 +0100464 return prep_op
465
466 return None
467
468
469def mark_npu_block_type(op, arch):
470 npu_block_type = NpuBlockType.Default
471 if op.type in conv_op:
472 npu_block_type = NpuBlockType.ConvolutionMxN
473 elif op.type in fc_op:
474 npu_block_type = NpuBlockType.VectorProduct
475 elif op.type in depthwise_op:
476 npu_block_type = NpuBlockType.ConvolutionDepthWise
477 elif op.type in pool_op:
478 npu_block_type = NpuBlockType.Pooling
479 elif op.type in elementwise_op:
480 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200481 elif op.type in reduce_sum_ops:
482 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100483
484 op.attrs["npu_block_type"] = npu_block_type
485 return op
486
487
488def convert_depthwise_to_conv(op, arch):
489 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
490 # the ofm depth equals the depth multipler.
491 # If those conditions are true, then we can perform a simple
492 # switch of the operator type (and weight order)
493
494 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
495 ifm_tensor = op.inputs[0]
496 weight_tensor = op.inputs[1]
497 ofm_tensor = op.outputs[0]
498 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
499 # Change op type to Conv2d
500 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
501 del op.attrs["channel_multiplier"]
502 del op.attrs["depth_multiplier"]
503
504 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100505 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100506 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200507 raise UnsupportedFeatureError(
508 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100509 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
510 )
511 )
Tim Hall79d07d22020-04-27 18:20:16 +0100512 return op
513
514
Jacob Bohline843d332020-06-23 12:12:56 +0200515def reorder_depthwise_weights(op, arch):
516 if "DepthwiseConv2d" in op.type:
517 weight_tensor = op.inputs[1]
518 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100519 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200520 weight_tensor.weight_transpose_depthwise = True
521
522 return op
523
524
Michael McGeagh8d939c02020-07-29 13:11:43 +0100525def convert_conv_to_fc(op, arch):
526 # Conv 1x1 can be equivalent to Fully Connected.
527 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
528 # caching/double buffering for the weights.
529 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
530 if op.type == "Conv2DBiasAct":
531 _, h, w, _ = op.inputs[0].shape
532 kh, kw, _, _ = op.inputs[1].shape
533 if h == 1 and w == 1 and kh == 1 and kw == 1:
534 # Overwrite this op as a Fully Connected Op
535 op.name += "_fc"
536 op.type = "FullyConnectedAct"
537 faf = op.attrs.get("fused_activation_function", None)
538 op.attrs = {
539 "fused_activation_function": faf,
540 "weights_format": 0,
541 "npu_block_type": NpuBlockType.VectorProduct,
542 }
543 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
544 weight_tensor = op.inputs[1]
545 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
546 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
547 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
548 # back to 4D afterwards as the next layer is expecting that shape
549 orig_ofm_tensor = op.outputs[0]
550 # 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})
551 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
552 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
553 fc_ofm_tensor.ops = [op]
554 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100555 reshape_name = op.name + "_reshape"
556 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100557 reshape_op = Operation("Reshape", reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100558 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100559 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
560 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100561 # Replace this ops OFM to point to the 2D tensor
562 op.outputs[0] = fc_ofm_tensor
563 return op
564
565
Tim Hall79d07d22020-04-27 18:20:16 +0100566# Reorder activation op if it's after the memory only operations
567def fixup_act_reorder(op, arch):
568 if op.type in activation_ops:
569 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100570 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100571 act_op = op.clone("_reordered")
572 act_op.inputs = [prep_op.inputs[0]]
573 act_op_out = act_op.inputs[0].clone("_acted")
574 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100575 act_op.set_output_tensor(act_op_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100576 prep_op.inputs[0] = act_op_out
577 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
578
579 # Mark the op so that it will be removed as passthrough later on
580 op.type = "Identity"
581 return op
582
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200583
Charles Xu78792222020-05-13 10:15:26 +0200584def fixup_elementwise_with_scalars(op, arch):
585 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200586 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200587 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
588 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
589 if diff > 0:
590 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
591 elif diff < 0:
592 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200593 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
594 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
595 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
596 ifm_tensor.storage_shape = ifm_tensor.shape
597 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
598 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
599 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
600 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200601 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100602
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200603
Tim Hall4e127762020-05-15 16:05:49 +0100604# Set input/output tensor equivalence to the same id for memory operations
605def set_tensor_equivalence(op, arch):
606 if op.type == "Reshape":
607 eid = op.outputs[0].equivalence_id
608 for inp in op.inputs:
609 inp.equivalence_id = eid
610 return op
611
612
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200613def convert_softmax(op, arch):
614 if op.type == "Softmax" and op.run_on_npu:
615 softmax = SoftMax(op)
616 op = softmax.get_graph()
617 return op
618
619
Tim Hall79d07d22020-04-27 18:20:16 +0100620def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100621 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100622
623 Input X For X = -1 or X > 0
624 | \ / This subgraph can be replaced with either
625 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
626 | /
627 Max
628 """
629
630 if op.type == "Maximum":
631 # finds the Mul input(s) to the Max
632 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
633 if len(muls) == 1:
634 mul = muls[0].ops[0]
635 elif len(muls) == 2:
636 # In the case both inputs are Muls, find the one with the same input as the Max
637 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
638 else:
639 # No Mul inputs
640 return op
641
642 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200643 mul_ofm = mul.outputs[0]
644 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100645 return op
646 # make sure the Mul doesn't have a faf
647 if mul.attrs["fused_activation_function"]:
648 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200649 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
650 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
651 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200652 if not ifm.is_scaling_equal(ofm) or not ifm.is_scaling_equal(mul_ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200653 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
654 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100655
656 # finds the branched input that goes to both the Max and the Mul
657 shared = set(op.inputs) & set(mul.inputs)
658 if len(shared) == 1:
659 shared_in = shared.pop()
660 # find the constant scalar input to the Mul
661 const_tens = (set(mul.inputs) - {shared_in}).pop()
662 # check that it is a scalar
663 if const_tens.shape != []:
664 return op
665 const = const_tens.ops[0]
666 # check that it is a constant
667 if const.type != "Const":
668 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200669 # Remove the Mul from the shared input's consumers
670 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100671 else:
672 return op
673
674 val = const.outputs[0].values
675 if val >= 0:
676 new_op = "LeakyRelu"
677 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200678 # to produce bit exact results, the alpha is not enough;
679 # save additional scaling info in attr "alpha_scale", to be used as input
680 # to the LUT construction
681 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
682 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
683 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
684 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
685 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
686 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100687 elif val == -1:
688 new_op = "Abs"
689 else:
690 return op
691
692 op.type = op.type.replace("Maximum", new_op)
693 op.name = op.name.replace("Maximum", new_op)
694 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
695 op.inputs = [shared_in]
696 return op
697
698
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200699def convert_lrelu_to_mul_max(op, arch):
700 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
701 # (the opposite of convert_mul_max_to_abs_or_lrelu)
702 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
703
704 # Add multiplication with alpha
705 mul_alpha = Operation("MulAct", op.name + "_mul_alpha")
706 mul_alpha.add_input_tensor(ifm)
707 # Create const tensor containing alpha as scalar
708 alpha = op.attrs["alpha"]
709 quantization = ifm.quantization.clone()
710 quantization.min = 0
711 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
712 quantization.scale_f32 = alpha
713 quantization.zero_point = 0
714 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
715 mul_alpha.add_input_tensor(alpha_tens)
716 fm_alpha = ofm.clone(op.name + "_alpha")
717 mul_alpha.set_output_tensor(fm_alpha)
718
719 if ifm.is_scaling_equal(ofm):
720 # No identity multiplication is needed
721 fm_id = ifm
722 else:
723 # Add multiplication with identity
724 mul_identity = Operation("MulAct", op.name + "_mul_identity")
725 mul_identity.add_input_tensor(ifm)
726 # Create const tensor containing identity as scalar
727 quantization = ifm.quantization.clone()
728 quantization.min = 0
729 quantization.max = quantization.quant_max - quantization.quant_min
730 quantization.scale_f32 = 1
731 quantization.zero_point = 0
732 identity_tens = create_const_tensor(
733 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
734 )
735 mul_identity.add_input_tensor(identity_tens)
736 fm_id = ofm.clone(op.name + "_id")
737 mul_identity.set_output_tensor(fm_id)
738
739 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
740 op.type = "Maximum"
741 op.name = op.name.replace("LeakyRelu", "Maximum")
742 op.inputs = []
743 ifm.consumer_list.remove(op)
744 op.add_input_tensor(fm_alpha)
745 op.add_input_tensor(fm_id)
746 return op
747
748
749def convert_lrelu_to_lut(op, arch):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200750 # Rewrite LeakyRelu by Add with scalar 0 + LUT activation
Louis Verhaard58520b92020-08-24 16:45:38 +0200751 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
752 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200753 op.type = "AddAct"
754 op.name = op.name + "_add"
755 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
756 # Mark as no-op to enable potential fusing optimizations
757 op.attrs["is_nop"] = True
758 # Create an input tensor containing scalar zero
759 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200760 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200761 quantization.zero_point = 0
762 tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization)
763 op.add_input_tensor(tens)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200764 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200765 alpha = op.attrs["alpha"]
766 ifm_scale = np.double(ifm.quantization.scale_f32)
767 ofm_scale = np.double(ofm.quantization.scale_f32)
768 zp_in = ifm.quantization.zero_point
769 zp_out = ofm.quantization.zero_point
770 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
771 alpha_scalar = 1
772 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
773 if "alpha_scaling" in op.attrs:
774 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
775 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
776 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200777 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200778 quantized_min = min(ix)
779 quantized_max = max(ix)
780 for x in ix:
781 if x < zp_in:
782 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
783 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
784 )
785 else:
786 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
787 lut_result = min(quantized_max, max(quantized_min, lut_result))
788 values.append(lut_result)
789 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
790 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
791 # should be the same as the IFM
792 op.attrs["forced_output_quantization"] = ifm.quantization
Louis Verhaard58520b92020-08-24 16:45:38 +0200793 lut_tensor = lut.create_lut_tensor(op.name + "_lut", values, DataType.int8)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200794 op.set_activation_lut(lut_tensor)
795 return op
796
797
798def convert_lrelu(op, arch):
799 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
800 if op.type != "LeakyRelu":
801 return op
802 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
Louis Verhaardd7911c42020-08-25 13:36:41 +0200803 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
804 # use LUT for int8/uint8
805 return convert_lrelu_to_lut(op, arch)
806 if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype and ifm.dtype == DataType.int16:
807 # use LeakyRelu unmodified for int16 with equal input/output scaling
808 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200809 return convert_lrelu_to_mul_max(op, arch)
810
811
812def fuse_activation_function_with_prev(op, arch):
813 # if op is a no-op: attempts to move the activation function to the preceding op
814 if not op.attrs.get("is_nop", False) or op.attrs.get("fused_activation_function", None) is None:
815 return op
816 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
817 # finds the input(s) to the operation
818 prev_op = ifm.ops[0]
819 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
820 fuse = (
821 prev_op.run_on_npu
822 and prev_op.attrs["npu_block_type"] != NpuBlockType.Default
823 and len(ifm.ops) == 1
824 and len(prev_op.outputs[0].consumers()) == 1
825 and prev_op.attrs.get("fused_activation_function", None) is None
826 and ifm.is_scaling_equal(ofm)
827 )
828 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
829 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
830 # LUT currently only works correctly for elementwise ops
831 fuse = False
832 if fuse and op.activation_lut is not None:
833 # Check if LUT can be used with prev_op
834 prev_ifm, prev_ifm2, _, _ = prev_op.get_ifm_ifm2_weights_ofm()
835 fuse = prev_ifm is not None and prev_ifm.quantization is not None and prev_ifm.is_scaling_equal(ifm)
836 if prev_ifm2 is not None:
837 fuse = fuse and prev_ifm2.quantization is not None and prev_ifm2.is_scaling_equal(ifm)
838 if not fuse:
839 return op
840 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200841 for attr in ("fused_activation_function", "alpha", "forced_output_quantization"):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200842 if attr in op.attrs:
843 prev_op.attrs[attr] = op.attrs[attr]
844 if op.activation_lut is not None:
845 prev_op.set_activation_lut(op.activation_lut)
846 # Bypass op
847 prev_op.set_output_tensor(op.outputs[0])
848 return op
849
850
Dwight Lidman42fed942020-05-29 09:37:03 +0200851def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100852 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200853 input_tensor = op.inputs[0]
854 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
855 out_shape = op.outputs[0].shape[1:3]
856 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
857 # this means the output is supposed to be a x2 upscale,
858 # so we need to do SAME padding
859 op.attrs["padding"] = b"SAME"
860 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
861 # here we can just run the avg pool without padding and
862 # produce a (M * 2 - 1, N * 2 - 1) sized output
863 op.attrs["padding"] = b"VALID"
864 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +0200865 return op
Dwight Lidman42fed942020-05-29 09:37:03 +0200866 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100867 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200868 return op
869
870
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200871def fixup_bias_tensors(op, arch):
872 if op.needs_bias() and not op.inputs[-1]:
873 # Op has no bias, add bias tensor filled with zeros
874 nr_biases = op.inputs[1].shape[-1]
875 bias_values = [0] * nr_biases
876 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
877 bias_tensor.quant_values = bias_tensor.values
878 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200879
880 return op
881
882
Tim Hall79d07d22020-04-27 18:20:16 +0100883def supported_operator_check(op, arch):
884 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
885 return op
886
887
888def optimise_graph_a(nng, arch, verbose_graph=False):
889 if verbose_graph:
890 nng.print_graph()
891
892 op_rewrite_list = [
893 # mark block type and check if the operations are supported
894 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100895 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100896 supported_operator_check,
897 # then do any rewrites of supported operators
898 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100899 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200900 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +0100901 fixup_fully_connected_input,
902 fixup_pack_input,
903 fixup_conv2d_backprop,
904 fixup_act_reorder,
Tim Hall79d07d22020-04-27 18:20:16 +0100905 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200906 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200907 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +0200908 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200909 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200910 convert_mul_max_to_abs_or_lrelu,
911 convert_lrelu,
Tim Hall79d07d22020-04-27 18:20:16 +0100912 ]
913
914 for idx, sg in enumerate(nng.subgraphs):
915 # rewrite graph pass
916 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100917 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100918 )
919
920 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200921 # remove passthrough tensors and attempt further optimizations
922 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Charles Xu87c13502020-08-06 12:17:26 +0200923 sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields]
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200924 )
Tim Hall79d07d22020-04-27 18:20:16 +0100925
926 if verbose_graph:
927 nng.print_graph()
928 return nng
929
Diego Russoea6111a2020-04-14 18:41:58 +0100930
Tim Hall79d07d22020-04-27 18:20:16 +0100931def optimise_graph_b(nng, arch, verbose_graph=False):
932 if verbose_graph:
933 nng.print_graph()
934
935 for idx, sg in enumerate(nng.subgraphs):
936 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100937 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100938
939 if verbose_graph:
940 nng.print_graph()
941 return nng