blob: a57ac82e1ff35c8f7422dda2c961fa9db5f1c6b4 [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
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +010031from .operation import create_avgpool_nop
Diego Russoe8a10452020-04-21 17:39:10 +010032from .operation import NpuBlockType
33from .operation import Operation
Fredrik Svedberga0c36242020-06-03 15:43:31 +020034from .softmax import SoftMax
Michael McGeaghc5b549b2020-08-07 11:54:28 +010035from .tensor import create_const_tensor
36from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020037from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010038from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010039
40passthrough_nodes = set(("Identity",))
41
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010042conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct"))
43fc_op = set(
44 (
45 "MatMul",
46 "QuantizedMatMul",
47 "BlockLSTM",
48 "RnnAct",
49 "UnidirectionalSequenceRnnAct",
50 "BidirectionalSequenceRnnAct",
51 "LstmAct",
52 "UnidirectionalSequenceLstmAct",
53 "BidirectionalSequenceLstmAct",
54 "FullyConnectedAct",
55 )
56)
57depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",))
58pool_op = set(
59 ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear")
60)
61reduce_sum_ops = set(("ReduceSum",))
62binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum"))
63elementwise_op = set(("LeakyRelu", "Abs", "CLZ", "SHL", "SHR")) | binary_elementwise_op
64relu_ops = set(("Relu", "Relu6", "ReluN1To1"))
65activation_ops = set(("Sigmoid", "Tanh")) | relu_ops
66memory_only_ops = set(("Reshape",))
67
Tim Hall79d07d22020-04-27 18:20:16 +010068
69def remove_passthrough_tensor(tens, arch):
70 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
71 assert len(tens.ops[0].inputs) == 1
72 tens = tens.ops[0].inputs[0]
73 return tens
74
75
76def rewrite_concat(tens, arch):
77 if len(tens.ops) == 1 and tens.ops[0].is_concat_op():
78 concat_op = tens.ops[0]
79 if tens != concat_op.outputs[0]:
80 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
81
82 # Not supported so leave it and run on CPU
83 if not concat_op.run_on_npu:
84 return tens
85
86 inputs, axis = concat_op.get_concat_inputs_axis()
87
88 tens.ops = []
89 offset = 0
90 for idx, inp in enumerate(inputs):
91 new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx))
92 new_op.inputs = [inp]
93 new_op.outputs = [tens]
94 new_op.attrs["concat_axis"] = axis
95 new_op.attrs["concat_start"] = offset
96 offset += inp.shape[axis]
97 new_op.attrs["concat_end"] = offset
98 new_op.run_on_npu = True
99 tens.ops.append(new_op)
100 assert tens.shape[axis] == offset
101
Patrik Gustavsson29d568e2020-08-18 10:11:21 +0200102 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
103 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
104 # 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 +0200105 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson29d568e2020-08-18 10:11:21 +0200106 if axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200107 for op in tens.ops:
108 if op.attrs["concat_start"] % 16 != 0:
109 tens.avoid_NHCWB16 = True
110 break
111
Tim Hall79d07d22020-04-27 18:20:16 +0100112 return tens
113
114
115def rewrite_split(tens, arch):
116
117 if len(tens.ops) == 1 and tens.ops[0].is_split_op():
118 split_op = tens.ops[0]
119
120 # Not supported so leave it and run on CPU
121 if not split_op.run_on_npu:
122 return tens
123
124 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
125
126 tens.ops = []
127 new_op = Operation("SplitSliceRead", split_op.name)
128 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100129
130 # For Split the offset cannot be extracted from the tensor so it has to
131 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100132 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100133 # Get the start and end of the split
134 offset_start = [0] * len(tens.shape)
135 offset_end = [0] * len(tens.shape)
136 for out in outputs:
137 if out == tens:
138 break
139 offset_start[axis] += out.shape[axis]
140
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200141 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
142 if (offset_start[-1] % 16) != 0:
143 inp.avoid_NHCWB16 = True
144
Tim Hall79d07d22020-04-27 18:20:16 +0100145 offset_end[axis] = offset_start[axis] + tens.shape[axis]
146
147 new_op.attrs["split_start"] = offset_start
148 new_op.attrs["split_end"] = offset_end
149 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100150 new_op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100151
152 return tens
153
154
155def needed_total_padding(input_size, stride, filter_size):
156 out_size = (input_size + stride - 1) // stride
157 needed_input = (out_size - 1) * stride + filter_size
158 total_padding = max(0, needed_input - input_size)
159 return total_padding
160
161
162def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
163 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
164 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
165 if padding_type == b"SAME":
166 left_pad = (xpad + 0) // 2
167 right_pad = (xpad + 1) // 2
168 top_pad = (ypad + 0) // 2
169 bottom_pad = (ypad + 1) // 2
170 elif padding_type == b"VALID":
171 left_pad = 0
172 right_pad = 0
173 top_pad = 0
174 bottom_pad = 0
175 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200176 raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type)))
Tim Hall79d07d22020-04-27 18:20:16 +0100177 padding = (top_pad, left_pad, bottom_pad, right_pad)
178 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
179 return padding, skirt
180
Tim Hallc30f4952020-06-15 20:47:35 +0100181
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200182def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
183 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200184 if padding_type == b"SAME":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200185 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
186 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
187
Jacob Bohlind47cc272020-08-24 11:42:14 +0200188 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
189 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200190 left_pad = max(kernel_width - 1 - right_pad, 0)
191 top_pad = max(kernel_height - 1 - bottom_pad, 0)
192
Jacob Bohlincf7da102020-05-20 09:03:40 +0200193 elif padding_type == b"VALID":
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200194 right_pad = max(kernel_width - 2, 0)
195 bottom_pad = max(kernel_height - 2, 0)
196 left_pad = kernel_width - 1
197 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200198 else:
199 assert 0, "Unknown padding"
200
201 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200202 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200203 return padding, skirt
204
Tim Hall79d07d22020-04-27 18:20:16 +0100205
206def fixup_conv2d_backprop(op, arch):
207 if op.type == "Conv2DBackpropInput":
208 # flip the inputs
209 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Jacob Bohlincf7da102020-05-20 09:03:40 +0200210 op.type = "Conv2DBackpropInputSwitchedBias"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200211
212 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100213 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100214
215 return op
216
217
Charles Xu9a03fdf2020-07-02 15:12:40 +0200218# Convert the op to an elementwise add
219def convert_resizebilinear_1x1_to_add(op):
220 op.type = "AddAct"
221 op.name = op.name + "_add"
222 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
223 op.attrs["resizebilinear"] = True
224 # Create an input tensor filled with zeros
225 shape = op.outputs[0].shape
226 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
227 tens.values = np.zeros(shape)
228 tens.quant_values = np.zeros(shape, np.uint8)
229 tens.quantization = QuantizationParameters(0.0, 255.0)
230 tens.quantization.scale_f32 = 1.0
231 tens.quantization.zero_point = 0
232 tens.consumer_list = [op]
233 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100234 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200235 # Set the add inputs
236 op.inputs[1] = op.inputs[0]
237 op.inputs[0] = tens
238
239 return op
240
241
Charles Xu87c13502020-08-06 12:17:26 +0200242# Convert ResizeBilinear to a number of 2x2 pool ops
243def convert_resizebilinear_to_2x2_pool(op):
244 count = 0
245 pre_op = op
246 outputs = op.outputs
247
248 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
249 if op.attrs["align_corners"]:
250 shape_modifier = 1
251 op.attrs["padding"] = b"VALID"
252 else:
253 shape_modifier = 0
254 op.attrs["padding"] = b"SAME"
255 op.inputs[0].resampling_mode = resampling_mode.NEAREST
256
257 upscaled_shape = np.array(op.inputs[0].shape[1:3])
258 out_shape = np.array(op.outputs[0].shape[1:3])
259 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
260 return op
261
262 while (upscaled_shape < out_shape).all():
263 if count == 0:
264 scaled_op = pre_op
265 else:
266 scaled_op = op.clone("_{}".format(count))
267 scaled_op.inputs[0] = pre_op.outputs[0]
268
269 upscaled_shape = upscaled_shape * 2 - shape_modifier
270
271 if (upscaled_shape == out_shape).all():
272 scaled_op.outputs = outputs
273 scaled_op.outputs[0].ops = [scaled_op]
274 else:
275 shape = outputs[0].shape.copy()
276 shape[1:3] = upscaled_shape[0:2]
277 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
278 out_tens.quantization = op.outputs[0].quantization.clone()
279 out_tens.quantization.quant_min = np.iinfo(np.int16).min
280 out_tens.quantization.quant_max = np.iinfo(np.int16).max
281 scaled_op.set_output_tensor(out_tens)
282 pre_op = scaled_op
283 count += 1
284
285 # Setup the scale value
286 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
287 scaled_op.attrs["rescale"] = 128
288 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
289 scaled_op.attrs["rescale"] = 1 / 128
290 elif "rescale" in scaled_op.attrs:
291 del scaled_op.attrs["rescale"]
292
293 return op
294
295
Charles Xu9a03fdf2020-07-02 15:12:40 +0200296def fixup_resizebilinear(op, arch):
Charles Xu87c13502020-08-06 12:17:26 +0200297 if op.type == "ResizeBilinear" and op.run_on_npu:
298 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200299 # Bypass nop resizebilinear
300 op.inputs = op.inputs[:1]
301 op.type = "Identity"
Charles Xu87c13502020-08-06 12:17:26 +0200302 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
303 convert_resizebilinear_1x1_to_add(op)
304 else:
305 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200306
307 return op
308
309
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200310def convert_nop_split_to_identity(op, arch):
311 if op.type == "Split" and op.attrs.get("num_splits") == 1:
312 # the list comprehension should return a list with a single tensor
313 # if it shouldn't, remove_passthrough_tensor will fail appropriately
314 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
315 op.type = "Identity"
316 return op
317
318
Tim Hall79d07d22020-04-27 18:20:16 +0100319def fixup_fully_connected_input(op, arch):
320 if op.type == "FullyConnectedAct":
321 inp = op.inputs[0]
322 weights = op.inputs[1]
323
324 n_in_elems = weights.shape[-2]
325 elms = inp.elements()
326 batch_size = elms // n_in_elems
327 assert batch_size * n_in_elems == elms
328
329 desired_shape = [batch_size, n_in_elems]
330 if inp.shape != desired_shape:
331 # mismatch, insert a reshape to fix this.
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100332 op.inputs[0] = create_reshape_tensor(inp, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100333
334 return op
335
336
337def fixup_pack_input(op, arch):
338 if op.type == "Pack":
339 # Pack is also referred to as Stack
340 # Requires the rewrite_concat function to be called on the op afterwards
341 axis = int(op.attrs["axis"])
342 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
343
344 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100345 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100346
347 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100348 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100349 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100350
351 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
352 reshape_op.attrs["new_shape"] = desired_shape
353 reshape_op.inputs = [inp, new_shape_tens]
354 reshape_op.set_output_tensor(reshape_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100355
356 op.inputs[idx] = reshape_out
357
358 op.type = "PackReshaped"
359
360 return op
361
362
363def fixup_unpack_output(tens, arch):
364 op = tens.ops[0]
365 if op.type in set(("Unpack", "StridedSlice")):
366 # Unpack is also referred to as Unstack
367 # Requires the rewrite_split function to be called on the op afterwards
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200368
369 reshape_input_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +0100370 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200371 new_axis_mask = op.attrs["new_axis_mask"]
Tim Hall79d07d22020-04-27 18:20:16 +0100372 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Louis Verhaard7db78962020-05-25 15:05:26 +0200373 ellipsis_mask = op.attrs["ellipsis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200374
375 if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0:
376 # Not supported, will be put on CPU
377 return tens
378 if shrink_axis_mask == 0 and new_axis_mask == 0:
Tim Hall79d07d22020-04-27 18:20:16 +0100379 # Equal Rank StridedSlice, no need to insert reshape
380 return tens
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200381 elif shrink_axis_mask != 0:
382 n = 0
383 axis = 0
384 while shrink_axis_mask:
385 prev_mask = shrink_axis_mask
386 n += 1
387 shrink_axis_mask &= shrink_axis_mask - 1
388 axis = int(math.log2(prev_mask - shrink_axis_mask))
389 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100390
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200391 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
392 op.attrs["shrink_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100393
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200394 elif new_axis_mask != 0:
395 n = 0
396 axis = 0
397 while new_axis_mask:
398 prev_mask = new_axis_mask
399 n += 1
400 new_axis_mask &= new_axis_mask - 1
401 axis = int(math.log2(prev_mask - new_axis_mask))
Louis Verhaard7db78962020-05-25 15:05:26 +0200402 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200403 new_axis_mask >>= 1
404
405 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
406 op.attrs["new_axis_mask"] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100407 else:
408 axis = int(op.attrs["axis"])
409 op.type = "UnpackReshaped"
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200410 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100411
412 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100413 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100414
415 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100416 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100417 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100418 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100419
420 reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx))
421 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100422 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100423 reshape_op.set_output_tensor(out_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100424
425 op.outputs[idx] = reshape_in
426
427 return tens
428
429
430def add_padding_fields(op, arch):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200431 if op.run_on_npu:
432 if "padding" in op.attrs:
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100433 if op.type in conv_op | depthwise_op:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200434 kernel_size = op.inputs[1].shape[:2]
435 input_shape = op.inputs[0].shape
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100436 elif op.type in pool_op | reduce_sum_ops:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200437 kernel_size = op.attrs["ksize"][1:3]
438 input_shape = op.inputs[0].shape
439 elif op.type == "ExtractImagePatches":
440 kernel_size = op.attrs["ksizes"][1:3]
441 input_shape = op.inputs[0].shape
442 else:
443 raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type))
Tim Hall79d07d22020-04-27 18:20:16 +0100444
Jacob Bohlin90033f32020-08-28 15:45:44 +0200445 if op.type == "Conv2DBackpropInputSwitchedBias":
446 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
447 padding, skirt = calc_upscaled_padding_and_skirt(
448 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
449 )
450 else:
451 dilation_h, dilation_w = op.get_dilation_h_w()
452 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
453 padding, skirt = calc_padding_and_skirt(
454 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
455 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200456
Jacob Bohlin90033f32020-08-28 15:45:44 +0200457 op.attrs["explicit_padding"] = padding
458 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200459
Tim Hall79d07d22020-04-27 18:20:16 +0100460 return op
461
462
Tim Hall79d07d22020-04-27 18:20:16 +0100463# Check if the op can be reordered
464def get_prepend_op(op):
465 inp = op.inputs[0]
466 # The op should be reordered between prev_op and prep_op
467 prev_op = inp.ops[-1]
468 prep_op = None
469 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
470 prep_op = prev_op
471 inp = prev_op.inputs[0]
472 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100473 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 +0100474 return prep_op
475
476 return None
477
478
479def mark_npu_block_type(op, arch):
480 npu_block_type = NpuBlockType.Default
481 if op.type in conv_op:
482 npu_block_type = NpuBlockType.ConvolutionMxN
483 elif op.type in fc_op:
484 npu_block_type = NpuBlockType.VectorProduct
485 elif op.type in depthwise_op:
486 npu_block_type = NpuBlockType.ConvolutionDepthWise
487 elif op.type in pool_op:
488 npu_block_type = NpuBlockType.Pooling
489 elif op.type in elementwise_op:
490 npu_block_type = NpuBlockType.ElementWise
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200491 elif op.type in reduce_sum_ops:
492 npu_block_type = NpuBlockType.ReduceSum
Tim Hall79d07d22020-04-27 18:20:16 +0100493
494 op.attrs["npu_block_type"] = npu_block_type
495 return op
496
497
498def convert_depthwise_to_conv(op, arch):
499 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
500 # the ofm depth equals the depth multipler.
501 # If those conditions are true, then we can perform a simple
502 # switch of the operator type (and weight order)
503
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100504 if (op.type in depthwise_op) and (op.attrs["depth_multiplier"] != 1):
Tim Hall79d07d22020-04-27 18:20:16 +0100505 ifm_tensor = op.inputs[0]
506 weight_tensor = op.inputs[1]
507 ofm_tensor = op.outputs[0]
508 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
509 # Change op type to Conv2d
510 op.type = op.type.replace("DepthwiseConv2d", "Conv2D")
511 del op.attrs["channel_multiplier"]
512 del op.attrs["depth_multiplier"]
513
514 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100515 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100516 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200517 raise UnsupportedFeatureError(
518 "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format(
Tim Hall79d07d22020-04-27 18:20:16 +0100519 op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3]
520 )
521 )
Tim Hall79d07d22020-04-27 18:20:16 +0100522 return op
523
524
Jacob Bohline843d332020-06-23 12:12:56 +0200525def reorder_depthwise_weights(op, arch):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100526 if op.type in depthwise_op:
Jacob Bohline843d332020-06-23 12:12:56 +0200527 weight_tensor = op.inputs[1]
528 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100529 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200530 weight_tensor.weight_transpose_depthwise = True
531
532 return op
533
534
Michael McGeagh8d939c02020-07-29 13:11:43 +0100535def convert_conv_to_fc(op, arch):
536 # Conv 1x1 can be equivalent to Fully Connected.
537 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
538 # caching/double buffering for the weights.
539 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
540 if op.type == "Conv2DBiasAct":
541 _, h, w, _ = op.inputs[0].shape
542 kh, kw, _, _ = op.inputs[1].shape
543 if h == 1 and w == 1 and kh == 1 and kw == 1:
544 # Overwrite this op as a Fully Connected Op
545 op.name += "_fc"
546 op.type = "FullyConnectedAct"
547 faf = op.attrs.get("fused_activation_function", None)
548 op.attrs = {
549 "fused_activation_function": faf,
550 "weights_format": 0,
551 "npu_block_type": NpuBlockType.VectorProduct,
552 }
553 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
554 weight_tensor = op.inputs[1]
555 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
556 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
557 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
558 # back to 4D afterwards as the next layer is expecting that shape
559 orig_ofm_tensor = op.outputs[0]
560 # 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})
561 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
562 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
563 fc_ofm_tensor.ops = [op]
564 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100565 reshape_name = op.name + "_reshape"
566 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100567 reshape_op = Operation("Reshape", reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100568 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100569 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
570 reshape_op.set_output_tensor(orig_ofm_tensor)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100571 # Replace this ops OFM to point to the 2D tensor
572 op.outputs[0] = fc_ofm_tensor
573 return op
574
575
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100576def fixup_relus_with_differing_ifm_ofm_scaling(op, arch):
577 if op.run_on_npu and op.type in relu_ops:
578 ifm = op.inputs[0]
579 ofm = op.outputs[0]
580 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
581 # and requires its own to be inserted
582 if not ifm.is_scaling_equal(ofm):
583 # Override this op with its own primary op (avgpool)
584 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
585 # And fuse the original activation function to it
586 relu_fused_op.attrs["fused_activation_function"] = op.type
587 # Tidy up and assign the ifm and ofm to the new op
588 ifm.consumer_list.remove(op)
589 relu_fused_op.add_input_tensor(ifm)
590 relu_fused_op.set_output_tensor(ofm)
591 op = relu_fused_op
592 return op
593
594
Tim Hall79d07d22020-04-27 18:20:16 +0100595# Reorder activation op if it's after the memory only operations
596def fixup_act_reorder(op, arch):
597 if op.type in activation_ops:
598 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100599 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100600 act_op = op.clone("_reordered")
601 act_op.inputs = [prep_op.inputs[0]]
602 act_op_out = act_op.inputs[0].clone("_acted")
603 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100604 act_op.set_output_tensor(act_op_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100605 prep_op.inputs[0] = act_op_out
606 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
607
608 # Mark the op so that it will be removed as passthrough later on
609 op.type = "Identity"
610 return op
611
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200612
Charles Xu78792222020-05-13 10:15:26 +0200613def fixup_elementwise_with_scalars(op, arch):
614 if op.type in binary_elementwise_op:
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200615 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200616 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
617 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
618 if diff > 0:
619 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
620 elif diff < 0:
621 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200622 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
623 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
624 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
625 ifm_tensor.storage_shape = ifm_tensor.shape
626 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
627 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
628 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
629 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200630 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100631
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200632
Tim Hall4e127762020-05-15 16:05:49 +0100633# Set input/output tensor equivalence to the same id for memory operations
634def set_tensor_equivalence(op, arch):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100635 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100636 eid = op.outputs[0].equivalence_id
637 for inp in op.inputs:
638 inp.equivalence_id = eid
639 return op
640
641
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200642def convert_softmax(op, arch):
643 if op.type == "Softmax" and op.run_on_npu:
644 softmax = SoftMax(op)
645 op = softmax.get_graph()
646 return op
647
648
Tim Hall79d07d22020-04-27 18:20:16 +0100649def convert_mul_max_to_abs_or_lrelu(op, arch):
Diego Russoea6111a2020-04-14 18:41:58 +0100650 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100651
652 Input X For X = -1 or X > 0
653 | \ / This subgraph can be replaced with either
654 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
655 | /
656 Max
657 """
658
659 if op.type == "Maximum":
660 # finds the Mul input(s) to the Max
661 muls = [i for i in op.inputs if i.ops[0].type == "MulAct"]
662 if len(muls) == 1:
663 mul = muls[0].ops[0]
664 elif len(muls) == 2:
665 # In the case both inputs are Muls, find the one with the same input as the Max
666 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
667 else:
668 # No Mul inputs
669 return op
670
671 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200672 mul_ofm = mul.outputs[0]
673 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100674 return op
675 # make sure the Mul doesn't have a faf
676 if mul.attrs["fused_activation_function"]:
677 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200678 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
679 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
680 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200681 if not ifm.is_scaling_equal(ofm) or not ifm.is_scaling_equal(mul_ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200682 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
683 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100684
685 # finds the branched input that goes to both the Max and the Mul
686 shared = set(op.inputs) & set(mul.inputs)
687 if len(shared) == 1:
688 shared_in = shared.pop()
689 # find the constant scalar input to the Mul
690 const_tens = (set(mul.inputs) - {shared_in}).pop()
691 # check that it is a scalar
692 if const_tens.shape != []:
693 return op
694 const = const_tens.ops[0]
695 # check that it is a constant
696 if const.type != "Const":
697 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200698 # Remove the Mul from the shared input's consumers
699 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100700 else:
701 return op
702
703 val = const.outputs[0].values
704 if val >= 0:
705 new_op = "LeakyRelu"
706 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200707 # to produce bit exact results, the alpha is not enough;
708 # save additional scaling info in attr "alpha_scale", to be used as input
709 # to the LUT construction
710 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
711 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
712 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
713 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
714 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
715 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100716 elif val == -1:
717 new_op = "Abs"
718 else:
719 return op
720
721 op.type = op.type.replace("Maximum", new_op)
722 op.name = op.name.replace("Maximum", new_op)
723 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op)
724 op.inputs = [shared_in]
725 return op
726
727
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200728def convert_lrelu_to_mul_max(op, arch):
729 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
730 # (the opposite of convert_mul_max_to_abs_or_lrelu)
731 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
732
733 # Add multiplication with alpha
734 mul_alpha = Operation("MulAct", op.name + "_mul_alpha")
735 mul_alpha.add_input_tensor(ifm)
736 # Create const tensor containing alpha as scalar
737 alpha = op.attrs["alpha"]
738 quantization = ifm.quantization.clone()
739 quantization.min = 0
740 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
741 quantization.scale_f32 = alpha
742 quantization.zero_point = 0
743 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
744 mul_alpha.add_input_tensor(alpha_tens)
745 fm_alpha = ofm.clone(op.name + "_alpha")
746 mul_alpha.set_output_tensor(fm_alpha)
747
748 if ifm.is_scaling_equal(ofm):
749 # No identity multiplication is needed
750 fm_id = ifm
751 else:
752 # Add multiplication with identity
753 mul_identity = Operation("MulAct", op.name + "_mul_identity")
754 mul_identity.add_input_tensor(ifm)
755 # Create const tensor containing identity as scalar
756 quantization = ifm.quantization.clone()
757 quantization.min = 0
758 quantization.max = quantization.quant_max - quantization.quant_min
759 quantization.scale_f32 = 1
760 quantization.zero_point = 0
761 identity_tens = create_const_tensor(
762 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
763 )
764 mul_identity.add_input_tensor(identity_tens)
765 fm_id = ofm.clone(op.name + "_id")
766 mul_identity.set_output_tensor(fm_id)
767
768 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
769 op.type = "Maximum"
770 op.name = op.name.replace("LeakyRelu", "Maximum")
771 op.inputs = []
772 ifm.consumer_list.remove(op)
773 op.add_input_tensor(fm_alpha)
774 op.add_input_tensor(fm_id)
775 return op
776
777
778def convert_lrelu_to_lut(op, arch):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200779 # Rewrite LeakyRelu by Add with scalar 0 + LUT activation
Louis Verhaard58520b92020-08-24 16:45:38 +0200780 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
781 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200782 op.type = "AddAct"
783 op.name = op.name + "_add"
784 op.attrs.update({"npu_block_type": NpuBlockType.ElementWise})
785 # Mark as no-op to enable potential fusing optimizations
786 op.attrs["is_nop"] = True
787 # Create an input tensor containing scalar zero
788 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200789 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200790 quantization.zero_point = 0
791 tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization)
792 op.add_input_tensor(tens)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200793 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200794 alpha = op.attrs["alpha"]
795 ifm_scale = np.double(ifm.quantization.scale_f32)
796 ofm_scale = np.double(ofm.quantization.scale_f32)
797 zp_in = ifm.quantization.zero_point
798 zp_out = ofm.quantization.zero_point
799 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
800 alpha_scalar = 1
801 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
802 if "alpha_scaling" in op.attrs:
803 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
804 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
805 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200806 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200807 quantized_min = min(ix)
808 quantized_max = max(ix)
809 for x in ix:
810 if x < zp_in:
811 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
812 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
813 )
814 else:
815 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
816 lut_result = min(quantized_max, max(quantized_min, lut_result))
817 values.append(lut_result)
818 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
819 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
820 # should be the same as the IFM
821 op.attrs["forced_output_quantization"] = ifm.quantization
Louis Verhaard58520b92020-08-24 16:45:38 +0200822 lut_tensor = lut.create_lut_tensor(op.name + "_lut", values, DataType.int8)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200823 op.set_activation_lut(lut_tensor)
824 return op
825
826
827def convert_lrelu(op, arch):
828 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
829 if op.type != "LeakyRelu":
830 return op
831 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
Louis Verhaardd7911c42020-08-25 13:36:41 +0200832 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
833 # use LUT for int8/uint8
834 return convert_lrelu_to_lut(op, arch)
835 if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype and ifm.dtype == DataType.int16:
836 # use LeakyRelu unmodified for int16 with equal input/output scaling
837 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200838 return convert_lrelu_to_mul_max(op, arch)
839
840
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200841def remove_unwanted_reshapes(op, arch):
842 # Try to remove reshapes enclosing ElementWise operator with only one non-constant input
843 if not op.run_on_npu or op.attrs["npu_block_type"] != NpuBlockType.ElementWise:
844 return op
845
846 # Check if the ElementWise operator only have one non-constant input
847 non_const_tens = [x for x in op.inputs if x.ops[0].type != "Const"]
848 if len(non_const_tens) != 1:
849 return op
850 ifm = non_const_tens[0]
851
852 # Check if operation is enclosed by Reshapes that can be removed
853 ofm = op.outputs[0]
854 prev_op = ifm.ops[0]
855 if (
856 len(ifm.consumer_list) == 1
857 and prev_op.type == "Reshape"
858 and len(ofm.consumer_list) == 1
859 and ofm.consumer_list[0].type == "Reshape"
860 ):
861 # Operation is enclosed by reshapes, check if they can be removed
862 prev_op_ifm, _, _, prev_op_ofm = prev_op.get_ifm_weights_biases_ofm()
863 cons_op = ofm.consumer_list[0]
864 cons_op_ifm = ofm
865 cons_op_ofm = cons_op.outputs[0]
866 if len(prev_op_ifm.shape) == len(cons_op_ofm.shape):
867 # Check if quantization is the same in the input and output for the reshape ops
868 if prev_op_ifm.quantization.is_scaling_equal(
869 prev_op_ofm.quantization
870 ) and cons_op_ifm.quantization.is_scaling_equal(cons_op_ofm.quantization):
871 op.inputs[0] = prev_op_ifm
872 op.outputs[0] = cons_op_ofm
873 return op
874
875
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200876def fuse_activation_function_with_prev(op, arch):
877 # if op is a no-op: attempts to move the activation function to the preceding op
878 if not op.attrs.get("is_nop", False) or op.attrs.get("fused_activation_function", None) is None:
879 return op
880 ifm, _, _, ofm = op.get_ifm_weights_biases_ofm()
881 # finds the input(s) to the operation
882 prev_op = ifm.ops[0]
883 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
884 fuse = (
885 prev_op.run_on_npu
886 and prev_op.attrs["npu_block_type"] != NpuBlockType.Default
887 and len(ifm.ops) == 1
888 and len(prev_op.outputs[0].consumers()) == 1
889 and prev_op.attrs.get("fused_activation_function", None) is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200890 )
891 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
892 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
893 # LUT currently only works correctly for elementwise ops
894 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200895 if not fuse:
896 return op
897 # Move the fused activation function + corresponding info to prev_op
Louis Verhaard98a34992020-09-01 10:39:04 +0200898 for attr in ("fused_activation_function", "forced_output_quantization"):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200899 if attr in op.attrs:
900 prev_op.attrs[attr] = op.attrs[attr]
901 if op.activation_lut is not None:
902 prev_op.set_activation_lut(op.activation_lut)
903 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +0200904 prev_op.set_output_tensor(ofm)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200905 return op
906
907
Dwight Lidman42fed942020-05-29 09:37:03 +0200908def add_attrs_to_resizebilinear(op, arch):
Tim Hallc30f4952020-06-15 20:47:35 +0100909 if op.type == "ResizeBilinear" and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +0200910 input_tensor = op.inputs[0]
911 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
912 out_shape = op.outputs[0].shape[1:3]
913 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
914 # this means the output is supposed to be a x2 upscale,
915 # so we need to do SAME padding
916 op.attrs["padding"] = b"SAME"
917 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
918 # here we can just run the avg pool without padding and
919 # produce a (M * 2 - 1, N * 2 - 1) sized output
920 op.attrs["padding"] = b"VALID"
921 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +0200922 return op
Dwight Lidman42fed942020-05-29 09:37:03 +0200923 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +0100924 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +0200925 return op
926
927
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200928def fixup_bias_tensors(op, arch):
929 if op.needs_bias() and not op.inputs[-1]:
930 # Op has no bias, add bias tensor filled with zeros
931 nr_biases = op.inputs[1].shape[-1]
932 bias_values = [0] * nr_biases
933 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
934 bias_tensor.quant_values = bias_tensor.values
935 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200936
937 return op
938
939
Tim Hall79d07d22020-04-27 18:20:16 +0100940def supported_operator_check(op, arch):
941 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
942 return op
943
944
945def optimise_graph_a(nng, arch, verbose_graph=False):
946 if verbose_graph:
947 nng.print_graph()
948
949 op_rewrite_list = [
950 # mark block type and check if the operations are supported
951 mark_npu_block_type,
Tim Hall4e127762020-05-15 16:05:49 +0100952 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +0100953 supported_operator_check,
954 # then do any rewrites of supported operators
955 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100956 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200957 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +0100958 fixup_fully_connected_input,
959 fixup_pack_input,
960 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100961 fixup_relus_with_differing_ifm_ofm_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100962 fixup_act_reorder,
Tim Hall79d07d22020-04-27 18:20:16 +0100963 mark_npu_block_type,
Charles Xu78792222020-05-13 10:15:26 +0200964 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +0200965 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +0200966 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200967 fixup_bias_tensors,
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200968 convert_nop_split_to_identity,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200969 convert_mul_max_to_abs_or_lrelu,
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200970 remove_unwanted_reshapes,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200971 convert_lrelu,
Tim Hall79d07d22020-04-27 18:20:16 +0100972 ]
973
974 for idx, sg in enumerate(nng.subgraphs):
975 # rewrite graph pass
976 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Diego Russoea6111a2020-04-14 18:41:58 +0100977 sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False
Tim Hall79d07d22020-04-27 18:20:16 +0100978 )
979
980 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200981 # remove passthrough tensors and attempt further optimizations
982 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Charles Xu87c13502020-08-06 12:17:26 +0200983 sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields]
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200984 )
Tim Hall79d07d22020-04-27 18:20:16 +0100985
986 if verbose_graph:
987 nng.print_graph()
988 return nng
989
Diego Russoea6111a2020-04-14 18:41:58 +0100990
Tim Hall79d07d22020-04-27 18:20:16 +0100991def optimise_graph_b(nng, arch, verbose_graph=False):
992 if verbose_graph:
993 nng.print_graph()
994
995 for idx, sg in enumerate(nng.subgraphs):
996 # combined rewrite graph pass
Diego Russoea6111a2020-04-14 18:41:58 +0100997 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], [])
Tim Hall79d07d22020-04-27 18:20:16 +0100998
999 if verbose_graph:
1000 nng.print_graph()
1001 return nng