blob: 7ab009f044a67e20c4203f6fdcca1a1fe81e7811 [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):
395 if "padding" in op.attrs:
396 if "Conv" in op.type:
397 kernel_size = op.inputs[1].shape[:2]
398 input_shape = op.inputs[0].shape
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200399 elif "Pool" in op.type or op.type in ("ResizeBilinear", "ReduceSum"):
Tim Hall79d07d22020-04-27 18:20:16 +0100400 kernel_size = op.attrs["ksize"][1:3]
401 input_shape = op.inputs[0].shape
402 elif op.type == "ExtractImagePatches":
403 kernel_size = op.attrs["ksizes"][1:3]
404 input_shape = op.inputs[0].shape
405 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200406 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100407
Jacob Bohlincf7da102020-05-20 09:03:40 +0200408 if op.type == "Conv2DBackpropInputSwitchedBias":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200409 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
Tim Hallc30f4952020-06-15 20:47:35 +0100410 padding, skirt = calc_upscaled_padding_and_skirt(
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200411 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
Tim Hallc30f4952020-06-15 20:47:35 +0100412 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200413 else:
414 dilation_h, dilation_w = op.get_dilation_h_w()
415 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
Tim Hallc30f4952020-06-15 20:47:35 +0100416 padding, skirt = calc_padding_and_skirt(
417 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
418 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200419
Tim Hall79d07d22020-04-27 18:20:16 +0100420 op.attrs["explicit_padding"] = padding
421 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200422
Tim Hall79d07d22020-04-27 18:20:16 +0100423 return op
424
425
Jacob Bohlincf7da102020-05-20 09:03:40 +0200426conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
Tim Hall79d07d22020-04-27 18:20:16 +0100427fc_op = set(
428 (
429 "MatMul",
430 "QuantizedMatMul",
431 "BlockLSTM",
432 "RnnAct",
433 "UnidirectionalSequenceRnnAct",
434 "BidirectionalSequenceRnnAct",
435 "LstmAct",
436 "UnidirectionalSequenceLstmAct",
437 "BidirectionalSequenceLstmAct",
438 "FullyConnectedAct",
439 )
440)
441depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
Louis Verhaard7db78962020-05-25 15:05:26 +0200442pool_op = set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200443 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
Louis Verhaard7db78962020-05-25 15:05:26 +0200444)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200445reduce_sum_ops = set(("ReduceSum",))
446elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs", "CLZ", "SHL", "SHR"))
Charles Xu78792222020-05-13 10:15:26 +0200447binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
Tim Hall79d07d22020-04-27 18:20:16 +0100448activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh"))
449memory_only_ops = set(("Reshape",))
450
Diego Russoea6111a2020-04-14 18:41:58 +0100451
Tim Hall79d07d22020-04-27 18:20:16 +0100452# Check if the op can be reordered
453def get_prepend_op(op):
454 inp = op.inputs[0]
455 # The op should be reordered between prev_op and prep_op
456 prev_op = inp.ops[-1]
457 prep_op = None
458 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
459 prep_op = prev_op
460 inp = prev_op.inputs[0]
461 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100462 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 +0100463 return prep_op
464
465 return None
466
467
468def mark_npu_block_type(op, arch):
469 npu_block_type = NpuBlockType.Default
470 if op.type in conv_op:
471 npu_block_type = NpuBlockType.ConvolutionMxN
472 elif op.type in fc_op:
473 npu_block_type = NpuBlockType.VectorProduct
474 elif op.type in depthwise_op:
475 npu_block_type = NpuBlockType.ConvolutionDepthWise
476 elif op.type in pool_op:
477 npu_block_type = NpuBlockType.Pooling
478 elif op.type in elementwise_op:
479 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200480 elif op.type in reduce_sum_ops:
481 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100482
483 op.attrs["npu_block_type"] = npu_block_type
484 return op
485
486
487def convert_depthwise_to_conv(op, arch):
488 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
489 # the ofm depth equals the depth multipler.
490 # If those conditions are true, then we can perform a simple
491 # switch of the operator type (and weight order)
492
493 if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1):
494 ifm_tensor = op.inputs[0]
495 weight_tensor = op.inputs[1]
496 ofm_tensor = op.outputs[0]
497 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
498 # Change op type to Conv2d
499 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
500 del op.attrs["channel_multiplier"]
501 del op.attrs["depth_multiplier"]
502
503 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100504 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100505 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200506 raise UnsupportedFeatureError(
507 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100508 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
509 )
510 )
Tim Hall79d07d22020-04-27 18:20:16 +0100511 return op
512
513
Jacob Bohline843d332020-06-23 12:12:56 +0200514def reorder_depthwise_weights(op, arch):
515 if "DepthwiseConv2d" in op.type:
516 weight_tensor = op.inputs[1]
517 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100518 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200519 weight_tensor.weight_transpose_depthwise = True
520
521 return op
522
523
Michael McGeagh8d939c02020-07-29 13:11:43 +0100524def convert_conv_to_fc(op, arch):
525 # Conv 1x1 can be equivalent to Fully Connected.
526 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
527 # caching/double buffering for the weights.
528 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
529 if op.type == "Conv2DBiasAct":
530 _, h, w, _ = op.inputs[0].shape
531 kh, kw, _, _ = op.inputs[1].shape
532 if h == 1 and w == 1 and kh == 1 and kw == 1:
533 # Overwrite this op as a Fully Connected Op
534 op.name += "_fc"
535 op.type = "FullyConnectedAct"
536 faf = op.attrs.get("fused_activation_function", None)
537 op.attrs = {
538 "fused_activation_function": faf,
539 "weights_format": 0,
540 "npu_block_type": NpuBlockType.VectorProduct,
541 }
542 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
543 weight_tensor = op.inputs[1]
544 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
545 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
546 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
547 # back to 4D afterwards as the next layer is expecting that shape
548 orig_ofm_tensor = op.outputs[0]
549 # 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})
550 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
551 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
552 fc_ofm_tensor.ops = [op]
553 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100554 reshape_name = op.name + "_reshape"
555 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100556 reshape_op = Operation("Reshape", reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100557 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100558 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
559 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100560 # Replace this ops OFM to point to the 2D tensor
561 op.outputs[0] = fc_ofm_tensor
562 return op
563
564
Tim Hall79d07d22020-04-27 18:20:16 +0100565# Reorder activation op if it's after the memory only operations
566def fixup_act_reorder(op, arch):
567 if op.type in activation_ops:
568 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100569 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100570 act_op = op.clone("_reordered")
571 act_op.inputs = [prep_op.inputs[0]]
572 act_op_out = act_op.inputs[0].clone("_acted")
573 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100574 act_op.set_output_tensor(act_op_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100575 prep_op.inputs[0] = act_op_out
576 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
577
578 # Mark the op so that it will be removed as passthrough later on
579 op.type = "Identity"
580 return op
581
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200582
Charles Xu78792222020-05-13 10:15:26 +0200583def fixup_elementwise_with_scalars(op, arch):
584 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200585 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200586 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
587 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
588 if diff > 0:
589 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
590 elif diff < 0:
591 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200592 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
593 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
594 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
595 ifm_tensor.storage_shape = ifm_tensor.shape
596 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
597 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
598 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
599 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200600 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100601
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200602
Tim Hall4e127762020-05-15 16:05:49 +0100603# Set input/output tensor equivalence to the same id for memory operations
604def set_tensor_equivalence(op, arch):
605 if op.type == "Reshape":
606 eid = op.outputs[0].equivalence_id
607 for inp in op.inputs:
608 inp.equivalence_id = eid
609 return op
610
611
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200612def convert_softmax(op, arch):
613 if op.type == "Softmax" and op.run_on_npu:
614 softmax = SoftMax(op)
615 op = softmax.get_graph()
616 return op
617
618
Tim Hall79d07d22020-04-27 18:20:16 +0100619def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100620 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100621
622 Input X For X = -1 or X > 0
623 | \ / This subgraph can be replaced with either
624 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
625 | /
626 Max
627 """
628
629 if op.type == "Maximum":
630 # finds the Mul input(s) to the Max
631 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
632 if len(muls) == 1:
633 mul = muls[0].ops[0]
634 elif len(muls) == 2:
635 # In the case both inputs are Muls, find the one with the same input as the Max
636 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
637 else:
638 # No Mul inputs
639 return op
640
641 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200642 mul_ofm = mul.outputs[0]
643 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100644 return op
645 # make sure the Mul doesn't have a faf
646 if mul.attrs["fused_activation_function"]:
647 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200648 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
649 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
650 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200651 if not ifm.is_scaling_equal(ofm) or not ifm.is_scaling_equal(mul_ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200652 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
653 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100654
655 # finds the branched input that goes to both the Max and the Mul
656 shared = set(op.inputs) & set(mul.inputs)
657 if len(shared) == 1:
658 shared_in = shared.pop()
659 # find the constant scalar input to the Mul
660 const_tens = (set(mul.inputs) - {shared_in}).pop()
661 # check that it is a scalar
662 if const_tens.shape != []:
663 return op
664 const = const_tens.ops[0]
665 # check that it is a constant
666 if const.type != "Const":
667 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200668 # Remove the Mul from the shared input's consumers
669 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100670 else:
671 return op
672
673 val = const.outputs[0].values
674 if val >= 0:
675 new_op = "LeakyRelu"
676 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200677 # to produce bit exact results, the alpha is not enough;
678 # save additional scaling info in attr "alpha_scale", to be used as input
679 # to the LUT construction
680 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
681 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
682 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
683 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
684 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
685 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100686 elif val == -1:
687 new_op = "Abs"
688 else:
689 return op
690
691 op.type = op.type.replace("Maximum", new_op)
692 op.name = op.name.replace("Maximum", new_op)
693 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
694 op.inputs = [shared_in]
695 return op
696
697
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200698def convert_lrelu_to_mul_max(op, arch):
699 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
700 # (the opposite of convert_mul_max_to_abs_or_lrelu)
701 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
702
703 # Add multiplication with alpha
704 mul_alpha = Operation("MulAct", op.name + "_mul_alpha")
705 mul_alpha.add_input_tensor(ifm)
706 # Create const tensor containing alpha as scalar
707 alpha = op.attrs["alpha"]
708 quantization = ifm.quantization.clone()
709 quantization.min = 0
710 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
711 quantization.scale_f32 = alpha
712 quantization.zero_point = 0
713 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
714 mul_alpha.add_input_tensor(alpha_tens)
715 fm_alpha = ofm.clone(op.name + "_alpha")
716 mul_alpha.set_output_tensor(fm_alpha)
717
718 if ifm.is_scaling_equal(ofm):
719 # No identity multiplication is needed
720 fm_id = ifm
721 else:
722 # Add multiplication with identity
723 mul_identity = Operation("MulAct", op.name + "_mul_identity")
724 mul_identity.add_input_tensor(ifm)
725 # Create const tensor containing identity as scalar
726 quantization = ifm.quantization.clone()
727 quantization.min = 0
728 quantization.max = quantization.quant_max - quantization.quant_min
729 quantization.scale_f32 = 1
730 quantization.zero_point = 0
731 identity_tens = create_const_tensor(
732 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
733 )
734 mul_identity.add_input_tensor(identity_tens)
735 fm_id = ofm.clone(op.name + "_id")
736 mul_identity.set_output_tensor(fm_id)
737
738 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
739 op.type = "Maximum"
740 op.name = op.name.replace("LeakyRelu", "Maximum")
741 op.inputs = []
742 ifm.consumer_list.remove(op)
743 op.add_input_tensor(fm_alpha)
744 op.add_input_tensor(fm_id)
745 return op
746
747
748def convert_lrelu_to_lut(op, arch):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200749 # Rewrite LeakyRelu by Add with scalar 0 + LUT activation
Louis Verhaard58520b92020-08-24 16:45:38 +0200750 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
751 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200752 op.type = "AddAct"
753 op.name = op.name + "_add"
754 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
755 # Mark as no-op to enable potential fusing optimizations
756 op.attrs["is_nop"] = True
757 # Create an input tensor containing scalar zero
758 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200759 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200760 quantization.zero_point = 0
761 tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization)
762 op.add_input_tensor(tens)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200763 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200764 alpha = op.attrs["alpha"]
765 ifm_scale = np.double(ifm.quantization.scale_f32)
766 ofm_scale = np.double(ofm.quantization.scale_f32)
767 zp_in = ifm.quantization.zero_point
768 zp_out = ofm.quantization.zero_point
769 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
770 alpha_scalar = 1
771 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
772 if "alpha_scaling" in op.attrs:
773 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
774 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
775 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200776 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200777 quantized_min = min(ix)
778 quantized_max = max(ix)
779 for x in ix:
780 if x < zp_in:
781 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
782 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
783 )
784 else:
785 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
786 lut_result = min(quantized_max, max(quantized_min, lut_result))
787 values.append(lut_result)
788 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
789 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
790 # should be the same as the IFM
791 op.attrs["forced_output_quantization"] = ifm.quantization
Louis Verhaard58520b92020-08-24 16:45:38 +0200792 lut_tensor = lut.create_lut_tensor(op.name + "_lut", values, DataType.int8)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200793 op.set_activation_lut(lut_tensor)
794 return op
795
796
797def convert_lrelu(op, arch):
798 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
799 if op.type != "LeakyRelu":
800 return op
801 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
Louis Verhaardd7911c42020-08-25 13:36:41 +0200802 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
803 # use LUT for int8/uint8
804 return convert_lrelu_to_lut(op, arch)
805 if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype and ifm.dtype == DataType.int16:
806 # use LeakyRelu unmodified for int16 with equal input/output scaling
807 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200808 return convert_lrelu_to_mul_max(op, arch)
809
810
811def fuse_activation_function_with_prev(op, arch):
812 # if op is a no-op: attempts to move the activation function to the preceding op
813 if not op.attrs.get("is_nop", False) or op.attrs.get("fused_activation_function", None) is None:
814 return op
815 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
816 # finds the input(s) to the operation
817 prev_op = ifm.ops[0]
818 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
819 fuse = (
820 prev_op.run_on_npu
821 and prev_op.attrs["npu_block_type"] != NpuBlockType.Default
822 and len(ifm.ops) == 1
823 and len(prev_op.outputs[0].consumers()) == 1
824 and prev_op.attrs.get("fused_activation_function", None) is None
825 and ifm.is_scaling_equal(ofm)
826 )
827 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
828 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
829 # LUT currently only works correctly for elementwise ops
830 fuse = False
831 if fuse and op.activation_lut is not None:
832 # Check if LUT can be used with prev_op
833 prev_ifm, prev_ifm2, _, _ = prev_op.get_ifm_ifm2_weights_ofm()
834 fuse = prev_ifm is not None and prev_ifm.quantization is not None and prev_ifm.is_scaling_equal(ifm)
835 if prev_ifm2 is not None:
836 fuse = fuse and prev_ifm2.quantization is not None and prev_ifm2.is_scaling_equal(ifm)
837 if not fuse:
838 return op
839 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200840 for attr in ("fused_activation_function", "alpha", "forced_output_quantization"):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200841 if attr in op.attrs:
842 prev_op.attrs[attr] = op.attrs[attr]
843 if op.activation_lut is not None:
844 prev_op.set_activation_lut(op.activation_lut)
845 # Bypass op
846 prev_op.set_output_tensor(op.outputs[0])
847 return op
848
849
Dwight Lidman42fed942020-05-29 09:37:03 +0200850def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100851 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200852 input_tensor = op.inputs[0]
853 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
854 out_shape = op.outputs[0].shape[1:3]
855 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
856 # this means the output is supposed to be a x2 upscale,
857 # so we need to do SAME padding
858 op.attrs["padding"] = b"SAME"
859 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
860 # here we can just run the avg pool without padding and
861 # produce a (M * 2 - 1, N * 2 - 1) sized output
862 op.attrs["padding"] = b"VALID"
863 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +0200864 return op
Dwight Lidman42fed942020-05-29 09:37:03 +0200865 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100866 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200867 return op
868
869
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200870def fixup_bias_tensors(op, arch):
871 if op.needs_bias() and not op.inputs[-1]:
872 # Op has no bias, add bias tensor filled with zeros
873 nr_biases = op.inputs[1].shape[-1]
874 bias_values = [0] * nr_biases
875 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
876 bias_tensor.quant_values = bias_tensor.values
877 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200878
879 return op
880
881
Tim Hall79d07d22020-04-27 18:20:16 +0100882def supported_operator_check(op, arch):
883 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
884 return op
885
886
887def optimise_graph_a(nng, arch, verbose_graph=False):
888 if verbose_graph:
889 nng.print_graph()
890
891 op_rewrite_list = [
892 # mark block type and check if the operations are supported
893 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100894 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100895 supported_operator_check,
896 # then do any rewrites of supported operators
897 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100898 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200899 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +0100900 fixup_fully_connected_input,
901 fixup_pack_input,
902 fixup_conv2d_backprop,
903 fixup_act_reorder,
Tim Hall79d07d22020-04-27 18:20:16 +0100904 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200905 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200906 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +0200907 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200908 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200909 convert_mul_max_to_abs_or_lrelu,
910 convert_lrelu,
Tim Hall79d07d22020-04-27 18:20:16 +0100911 ]
912
913 for idx, sg in enumerate(nng.subgraphs):
914 # rewrite graph pass
915 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100916 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100917 )
918
919 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200920 # remove passthrough tensors and attempt further optimizations
921 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Charles Xu87c13502020-08-06 12:17:26 +0200922 sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields]
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200923 )
Tim Hall79d07d22020-04-27 18:20:16 +0100924
925 if verbose_graph:
926 nng.print_graph()
927 return nng
928
Diego Russoea6111a2020-04-14 18:41:58 +0100929
Tim Hall79d07d22020-04-27 18:20:16 +0100930def optimise_graph_b(nng, arch, verbose_graph=False):
931 if verbose_graph:
932 nng.print_graph()
933
934 for idx, sg in enumerate(nng.subgraphs):
935 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100936 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100937
938 if verbose_graph:
939 nng.print_graph()
940 return nng