blob: 2a599aaac45f37087bbaf7a993b93208d65ed84a [file] [log] [blame]
Tim Hall3b1578e2023-01-13 17:57:25 +00001# SPDX-FileCopyrightText: Copyright 2021-2023 Arm Limited and/or its affiliates <open-source-office@arm.com>
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +02002#
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.
Rickard Bolinbc6ee582022-11-04 08:24:29 +000016#
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020017# Description:
18# Early optimisation of the TOSA based network graph, using the rewrite_graph module to do the traversal of the graph.
Patrik Gustavssonf366fb12021-09-07 13:30:29 +020019import numpy as np
20
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020021from . import rewrite_graph
22from .api import NpuRoundingMode
23from .data_type import DataType
24from .debug_database import DebugDatabase
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020025from .graph_optimiser_util import bypass_memory_only_ops
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020026from .graph_optimiser_util import calc_explicit_padding
Patrik Gustavssondf995102021-08-23 15:33:59 +020027from .graph_optimiser_util import convert_depthwise_to_conv
Patrik Gustavssonf436ada2021-09-14 14:56:48 +020028from .graph_optimiser_util import convert_to_lut
Patrik Gustavssonf1580f02021-09-01 12:43:02 +020029from .graph_optimiser_util import move_splitsliceread_to_consumer
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020030from .graph_optimiser_util import needed_total_padding
31from .graph_optimiser_util import set_ifm_ofm_op_shapes
32from .graph_optimiser_util import set_tensor_equivalence
33from .operation import ExplicitScaling
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020034from .operation import Op
Patrik Gustavssonf1580f02021-09-01 12:43:02 +020035from .operation_util import create_add_nop
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020036from .operation_util import create_avgpool_nop
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +020037from .operation_util import create_pad_nop
Patrik Gustavssonf1580f02021-09-01 12:43:02 +020038from .shape4d import Shape4D
39from .tensor import create_const_tensor
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +020040from .tensor import create_equivalence_id
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +020041from .tensor import shape_num_elements
42from .tensor import Tensor
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020043
44
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020045def replace_rescale_with_avg_pool(rescale_op):
46 assert rescale_op.type == Op.Rescale
47
48 avgpool_op = create_avgpool_nop(rescale_op.name + "_avgpool")
49 rescale_op_clone = rescale_op.clone()
50 op = rescale_op
51 op.attrs = avgpool_op.attrs.copy()
52 op.type = Op.AvgPool
53 DebugDatabase.add_optimised(rescale_op_clone, op)
54
55 return op
56
57
58def calc_skirt(kernel, input_shape, explicit_padding):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020059 k_w, k_h = kernel.dilated_wh()
60 s_x, s_y = kernel.stride
61 ypad = needed_total_padding(int(input_shape.height), int(s_y), int(k_h))
62 xpad = needed_total_padding(int(input_shape.width), int(s_x), int(k_w))
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020063
64 top, left, bottom, right = explicit_padding
65 top_pad, bottom_pad = calc_explicit_padding(int(input_shape.height), int(s_y), int(k_h), int(top), int(bottom))
66 left_pad, right_pad = calc_explicit_padding(int(input_shape.width), int(s_x), int(k_w), int(left), int(right))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020067
68 padding = (top_pad, left_pad, bottom_pad, right_pad)
69 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
70 return padding, skirt
71
72
73def add_padding_fields(op, arch, nng):
74 if op.run_on_npu:
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020075 if "explicit_padding" in op.attrs:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020076 input_shape = op.ifm_shapes[0]
77
78 if op.type == Op.Conv2DBackpropInputSwitchedBias:
79 # TODO not yet supported, but there will be need for separate handling
80 assert False
81 else:
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020082 padding, skirt = calc_skirt(op.kernel, input_shape, op.attrs.get("explicit_padding"))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020083
84 op.attrs["explicit_padding"] = padding
85 op.attrs["skirt"] = skirt
86
87 return op
88
89
Patrik Gustavssonf366fb12021-09-07 13:30:29 +020090# Counts leading zeroes for a (int32)
91def count_leading_zeros(a):
92 lz = int(32)
93 if a != 0:
94 mask = 1 << (32 - 1)
95 lz = 0
96 while (mask & a) == 0:
97 mask = mask >> 1
98 lz = lz + 1
99 return lz
100
101
102def calc_scaling_avgpool(op, arch, nng):
103 if op.type == Op.AvgPool:
104 top, left, _, _ = op.attrs["explicit_padding"]
105 # TODO Only support for when global scaling can be used.
106 # That is when there is no padding
107 assert top == 0 and left == 0
108 assert op.explicit_scaling is None
109 multiplier = []
110 shift = []
111
112 kernel_wh = op.kernel.elements_wh()
113 k = 32 - count_leading_zeros(kernel_wh - 1)
114 numerator = np.int64(((1 << 30) + 1) << k)
115 multiplier.append(numerator // kernel_wh)
116 shift.append(30 + k)
117
118 op.rounding_mode = NpuRoundingMode.NATURAL
119 op.explicit_scaling = ExplicitScaling(False, shift, multiplier)
120 return op
121
122
Patrik Gustavssondf995102021-08-23 15:33:59 +0200123def remove_const_transpose(op, arch, nng):
124 if op.type == Op.Transpose:
125 removed = False
126 if len(op.ifm.ops) == 1:
127 prev_op = op.ifm.ops[0]
128 if prev_op.type == Op.Const:
129 # Transpose the Tensor and data and remove Transpose
130 # TODO move to Tensor?
131 reorder = op.attrs["perms"]
132 shape = op.ifm.shape.copy()
133 tens = op.ifm
134
135 tens.shape = [shape[idx] for idx in reorder]
136 tens.bandwidth_shape = tens.shape
137 tens.storage_shape = tens.shape
138
139 if tens.values is not None:
140 tens.values = tens.values.transpose(reorder)
141
142 op.ofm.values = tens.values
143 # Bypass the Transpose op
144 prev_op.set_output_tensor(op.ofm)
145 DebugDatabase.add_optimised(op, prev_op)
146 removed = True
147
148 if not removed:
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200149 print("Warning: Cannot remove Transpose, and handling of Transpose is not supported")
Patrik Gustavssondf995102021-08-23 15:33:59 +0200150 assert False
151
152 return op
153
154
Patrik Gustavsson1bf0f192021-10-06 14:46:46 +0200155def insert_add_copy_for_const(op, ifm_ofm_shape):
156 assert op.type == Op.Const
157 ofm = op.ofm
158 copy_tens = ofm.clone()
159 op.set_output_tensor(copy_tens)
160
161 name = ofm.name + "_add"
162 ifm2 = create_const_tensor(
163 name + "_zero_scalar",
164 [1],
165 copy_tens.dtype,
166 [0],
Patrik Gustavsson1bf0f192021-10-06 14:46:46 +0200167 quantization=copy_tens.quantization,
168 )
169 copy_op = create_add_nop(name)
170 copy_op.add_input_tensor(copy_tens)
171 copy_op.add_input_tensor(ifm2)
172 copy_op.set_output_tensor(ofm)
173 copy_op.ifm_shapes.append(ifm_ofm_shape)
174 copy_op.ifm_shapes.append(Shape4D(ifm2.shape))
175 copy_op.ofm_shapes.append(ifm_ofm_shape)
176 copy_op.run_on_npu = True
177
178 DebugDatabase.add_optimised(op, copy_op)
179
180
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200181# TODO can we change to add for both TFLite and TOSA?
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200182def insert_add_copy_op_after_tens(tens, ifm_ofm_shape):
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200183 tens_cons_list_copy = tens.consumer_list.copy()
184 copy_tens = tens.clone()
185
186 name = tens.name + "_add"
187 ifm2 = create_const_tensor(
188 name + "_zero_scalar",
189 [1],
190 copy_tens.dtype,
191 [0],
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200192 quantization=copy_tens.quantization,
193 )
194 copy_op = create_add_nop(name)
195 copy_op.add_input_tensor(tens)
196 copy_op.add_input_tensor(ifm2)
197 copy_op.set_output_tensor(copy_tens)
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200198 copy_op.ifm_shapes.append(ifm_ofm_shape)
199 copy_op.ifm_shapes.append(Shape4D(ifm2.shape))
200 copy_op.ofm_shapes.append(ifm_ofm_shape)
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200201 copy_op.run_on_npu = True
202
203 # Set copy_ifm consumers
204 for tens_cons in tens_cons_list_copy:
205 if tens_cons is not None:
206 for ifm_idx, cons_inp in enumerate(tens_cons.inputs):
207 if cons_inp == tens:
208 tens_cons.set_input_tensor(copy_tens, ifm_idx)
209
210 DebugDatabase.add_optimised(tens.ops[0], copy_op)
211
212
Patrik Gustavsson1bf0f192021-10-06 14:46:46 +0200213def get_shape_for_copy_op(shape):
214 # remove dimensions that are set to 1
215 new_shape = []
216 for dim in shape:
217 if dim != 1:
218 new_shape.append(dim)
219 if not new_shape:
220 new_shape = [1]
221
222 rank = len(new_shape)
223 if rank > 3:
224 # Reshape so that batch becomes 1, by moving elements to H dimension
225 n = rank - 2
226 h = 1
227 for i in range(n):
228 h *= shape[i]
229 new_shape = Shape4D(new_shape[n:]).with_height(h)
230 else:
231 new_shape = Shape4D(new_shape)
232 return new_shape
233
234
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200235def fix_sg_input_output_tosa(op, arch, nng):
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200236
Patrik Gustavsson1bf0f192021-10-06 14:46:46 +0200237 if op.type == Op.Const and any(ofm_cons is None for ofm_cons in op.ofm.consumer_list):
238 # Const operator with sg output, insert copy op before the ofm
239 new_shape = get_shape_for_copy_op(op.ofm.shape.copy())
240 insert_add_copy_for_const(op, new_shape)
241 elif op.run_on_npu and op.type in (Op.Reshape, Op.Identity):
242 # For the Reshape operators we want to remove, tensors are removed.
243 # But in order to to do this, they cannot be outputs of the sg,
244 # this need to be fixed prior to the removal.
245 # Solution is to add a copy op, to maintain the original tensor.
246 # This is also valid when reshape ifm/ofm is produced respectively
247 # consumed by CPU
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200248
Patrik Gustavsson1bf0f192021-10-06 14:46:46 +0200249 # Check if operator ifm/ofm are sg ifm/ofm
250 ifm_is_sg_ifm = op.ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
251 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in op.ifm.consumer_list)
252 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in op.ofm.consumer_list)
253 # Check if ifm/ofm is produced repectivly consumed by CPU
254 ifm_is_cpu_produced = any(ifm_prod is not None and not ifm_prod.run_on_npu for ifm_prod in op.ifm.ops)
255 ofm_is_cpu_consumed = any(ofm_cons is not None and not ofm_cons.run_on_npu for ofm_cons in op.ofm.consumer_list)
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200256
Patrik Gustavsson1bf0f192021-10-06 14:46:46 +0200257 if (ifm_is_sg_ofm or ifm_is_sg_ifm or ifm_is_cpu_produced) and (ofm_is_sg_ofm or ofm_is_cpu_consumed):
258 # Both ifm and ofm need to persist, but only ifm need a copy, in order to remove the Operator
259 # Decide on ifm/ofm shapes for the copy op based on ifm
260 new_shape = get_shape_for_copy_op(op.ifm.shape.copy())
261 insert_add_copy_op_after_tens(op.ifm, new_shape)
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200262 return op
263
264
265def create_add_for_concat(concat_op, name, ifm, ifm_shape: Shape4D, write_offset: Shape4D):
266 """Creates an add op for the given concat op/input feature map"""
267 ofm = concat_op.ofm
Tim Hall3b1578e2023-01-13 17:57:25 +0000268 ifm2 = create_const_tensor(name + "_zero_scalar", [1], ofm.dtype, [0], quantization=ofm.quantization)
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200269 add_op = create_add_nop(name)
270
271 add_op.inputs = [ifm, ifm2]
272 add_op.outputs = [ofm]
273 add_op.write_offset = write_offset
274 add_op.write_shape = ifm_shape
275 ofm.ops.append(add_op)
276 DebugDatabase.add_optimised(concat_op, add_op)
277 add_op.ifm_shapes.append(ifm_shape)
278 add_op.ifm_shapes.append(Shape4D(ifm2.shape))
279 add_op.ofm_shapes.append(concat_op.ofm_shapes[0])
280 add_op.memory_function = Op.ConcatSliceWrite
281 return add_op
282
283
284# TODO Could be further optimized checking the type of the consumer,
285# rather than just mimic the TFLite behaviour depending on type.
286# TOSA bool_t not considered yet
287def remove_splitsliceread(op, arch):
288
289 if op.type == Op.SplitSliceRead:
290 # Check if it is possible to put the SplitSliceRead on the tensor consumer, or if an avgpool need to be inserted
291 if (
292 len(op.ofm.consumer_list) == 1
293 and op.ofm.consumer_list[0] is not None
294 and op.ofm.consumer_list[0].run_on_npu
295 and op.ofm.consumer_list[0].type != Op.Reshape
296 and op.ofm_shapes[0] == Shape4D.from_list(op.ofm.shape)
297 and op.ofm.dtype in (DataType.uint8, DataType.int8, DataType.int16)
298 ):
299 # SplitSliceRead can be performed by tensor consumer
300 cons_op = op.ofm.consumer_list[0]
301 move_splitsliceread_to_consumer(op, cons_op)
302 else:
303 name = op.name + "_add"
304 ofm = op.ofm
Tim Hall3b1578e2023-01-13 17:57:25 +0000305 ifm2 = create_const_tensor(name + "_zero_scalar", [1], ofm.dtype, [0], quantization=ofm.quantization)
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200306 add_op = create_add_nop(name)
307 add_op.inputs = [op.ifm, ifm2]
308 add_op.outputs = [ofm]
309 op.ofm.ops.remove(op)
310 op.ofm.ops.append(add_op)
311 add_op.ifm_shapes.append(op.ifm_shapes[0])
312 add_op.ifm_shapes.append(Shape4D(ifm2.shape))
313 add_op.ofm_shapes.append(op.ofm_shapes[0])
314 add_op.read_offsets[0] = op.read_offsets[0]
315 add_op.read_shapes[0] = op.read_shapes[0]
316
317 op.ifm.consumer_list.remove(op)
318 DebugDatabase.add_optimised(op, add_op)
319
320
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200321def rewrite_concat(op):
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200322 if not op.run_on_npu or not op.type == Op.Concat:
323 return
324
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200325 offset = 0
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200326 inputs = op.inputs
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200327 axis_4D = op.attrs["axis4D"]
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200328
329 for idx, inp in enumerate(inputs):
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200330 write_offset = [0, 0, 0, 0]
331 write_offset[axis_4D] = offset
332 concat_end = offset + op.ifm_shapes[idx][axis_4D]
333 create_add_for_concat(op, op.name + str(idx) + "_add", inp, op.ifm_shapes[idx], Shape4D.from_list(write_offset))
334 offset = concat_end
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200335 assert op.ofm_shapes[0][axis_4D] == offset
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200336
337
Patrik Gustavssonef3ebdd2021-10-01 11:10:25 +0200338def remove_memory_ops(op, arch):
339 if op.run_on_npu and op.type in (Op.Reshape, Op.Identity):
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200340 bypass_memory_only_ops(op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200341
342
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200343def rewrite_activation(op, arch, nng):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200344 if op.type not in (Op.ReluN, Op.Clamp):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200345 return op
346
347 ifm = op.ifm
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200348 zp = ifm.quantization.zero_point if ifm.quantization.zero_point else 0
349 if op.ofm.quantization.zero_point is None:
350 op.ofm.quantization.zero_point = zp
351
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200352 if op.type == Op.Clamp:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200353 op.attrs["min"] = op.attrs["min_int"] - zp
354 op.attrs["max"] = op.attrs["max_int"] - zp
355 elif op.type == Op.ReluN:
356 op.attrs["max"] = op.attrs["max_int"] - zp
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200357
358 return op
359
360
361def rewrite_rescale(op, arch, nng):
362 if op.type == Op.Rescale:
363 ifm = op.ifm
364 ofm = op.ofm
365
366 # some error checking
367 assert len(ifm.ops) == 1
368 prev_op = ifm.ops[0]
369
370 # TODO currently not supported
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200371 assert len(ifm.consumer_list) == 1
372
373 input_zp = op.attrs["input_zp"]
374 output_zp = op.attrs["output_zp"]
375 multiplier = op.attrs["multiplier"]
376 shift = op.attrs["shift"]
377 scale32 = op.attrs["scale32"]
378 double_round = op.attrs["double_round"]
379 per_channel = op.attrs["per_channel"]
380
381 assert ifm.dtype in (DataType.uint8, DataType.int8, DataType.int32)
382 assert ifm.dtype in (DataType.uint8, DataType.int8) or input_zp == 0
383 assert ofm.dtype in (DataType.uint8, DataType.int8) or output_zp == 0
384 assert (scale32 and ifm.dtype != DataType.int48) or (not scale32 and not double_round)
385
386 # Check that input tensor has the same zp or no zp
387 ifm_zp = ifm.quantization.zero_point
388 if ifm_zp is not None and ifm_zp != input_zp:
389 print("Error (fuse_rescale): zp of tensors producer/consumer differs unexpectedidly ")
390 assert False
391 ifm.quantization.zero_point = input_zp
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200392 ofm.quantization.zero_point = output_zp
393 for s, m in zip(shift, multiplier):
394 # TODO these are the TOSA limitations
395 assert m >= 0
396 assert 2 <= s <= 62
397 # TODO these are the HW limitations
398 assert 0 <= s < (1 << 6)
399 explicit_scaling = ExplicitScaling(per_channel, shift, multiplier)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200400
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200401 if double_round and scale32:
402 rounding_mode = NpuRoundingMode.TFL
403 else:
404 rounding_mode = NpuRoundingMode.NATURAL
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200405
406 if prev_op.type.is_depthwise_conv2d_op() or prev_op.type.is_conv2d_op() or prev_op.type == Op.FullyConnected:
407 assert len(multiplier) == len(shift) == len(prev_op.bias.values)
408
409 if ifm.dtype == DataType.int32 and per_channel:
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200410 prev_op.explicit_scaling = explicit_scaling
411 prev_op.rounding_mode = rounding_mode
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200412
413 # Bypass op
414 prev_op.set_output_tensor(ofm)
415 DebugDatabase.add_optimised(op, prev_op)
416 return op
417 else:
418 print("Warning, unsupported fusing of TOSA Rescale previous operator is of type:", prev_op.type)
419 assert False
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200420 # TODO which are the cases we need to and can do standalone Rescale?
421 # TODO should we try to identify a conversion uint8<->int8 accomplished by 2 RESCALE ops?
422 # origin might be TFLite op QUANTIZE, should we look to see if they can be translated to QUANTIZE?
423 # limited to these at the moment:
424 elif (
425 (ifm.dtype == DataType.int8 and ofm.dtype == DataType.int8)
426 or (ifm.dtype == DataType.uint8 and ofm.dtype == DataType.int8)
427 or (ifm.dtype == DataType.int8 and ofm.dtype == DataType.uint8)
428 ):
429 # Create NOP performing the RESCALE
430 avgpool_op = replace_rescale_with_avg_pool(op)
431 avgpool_op.rounding_mode = rounding_mode
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200432
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200433 if per_channel:
434 # TODO
435 avgpool_op.explicit_scaling = explicit_scaling
436 print("Warning, unsupported TOSA Rescale")
437 assert False
438 else:
439 avgpool_op.explicit_scaling = explicit_scaling
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200440 else:
441 print("Warning, unsupported fusing of TOSA Rescale previous operator is of type:", prev_op.type)
442 assert False
443 return op
444
445
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200446def convert_pad_in_width(op):
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200447 """
448 Rewrites PAD operator to an add that copies the IFM to the OFM
449 + up to 4 add operators that fill the OFM with zeros at the borders.
450 """
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200451 assert op.type == Op.Pad
452 assert op.ifm_shapes[0] is not None and op.ofm_shapes[0] is not None
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200453 ifm = op.ifm
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200454 ofm = op.ofm
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200455 ifm_shape = op.ifm_shapes[0]
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200456 ofm.ops = []
457 ofm_shape = op.ofm_shapes[0]
458
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200459 padding = op.inputs[1].values
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200460 left, right = padding[-2]
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200461
462 # Add op that copies IFM to the right place inside the OFM
463 shp0 = Shape4D(0, 0, 0, 0)
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200464 add_op = create_add_for_concat(op, op.name + "_main", ifm, ifm_shape, shp0.with_width(left))
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200465 add_op.activation = op.activation
466
467 quant = ofm.quantization
468 pad_value = ifm.quantization.zero_point
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200469 ifm.quantization.zero_point = 0
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200470 if left > 0:
471 shape = Shape4D(1, ifm_shape.height, left, ofm_shape.depth)
472 zero_tens = create_const_tensor(
Tim Hall3b1578e2023-01-13 17:57:25 +0000473 op.name + "_left", shape.as_list(), ofm.dtype, shape.elements() * [pad_value], quantization=quant
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200474 )
475 zero_tens.equivalence_id = create_equivalence_id(tuple(zero_tens.values))
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200476 create_add_for_concat(op, op.name + "_left", zero_tens, shape, shp0)
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200477 if right > 0:
478 shape = Shape4D(1, ifm_shape.height, right, ofm_shape.depth)
479 zero_tens = create_const_tensor(
Tim Hall3b1578e2023-01-13 17:57:25 +0000480 op.name + "_right", shape.as_list(), ofm.dtype, shape.elements() * [pad_value], quantization=quant
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200481 )
482 zero_tens.equivalence_id = create_equivalence_id(tuple(zero_tens.values))
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200483 create_add_for_concat(op, op.name + "_right", zero_tens, shape, shp0.with_width(ofm_shape.width - right))
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200484
485 op.type = Op.ConcatTFLite
486 return add_op
487
488
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200489def convert_table_to_lut(op, arch, nng):
490 # Converts table op to a no-op + LUT
491 if op.type is not Op.Table:
492 return op
493
494 table = op.inputs[1]
495 op.inputs.remove(table)
496 op.set_ifm_ofm_shapes()
497
498 return convert_to_lut(op, table.values, "table")
499
500
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200501def decompose_elem_tensors_hwc(op):
502 """
503 Decomposes elementwise op if any of the ifm(s)/ofm are to large in any dimension to be handled by the NPU
504 """
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200505 max_t_size = 65535
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200506 ofm_shape = op.write_shape if op.write_shape is not None else op.ofm_shapes[0]
507 ifm_shape = op.read_shapes[0] if op.read_shapes[0] is not None else op.ifm_shapes[0]
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200508 ifm2_shape = op.ifm_shapes[1] if op.ifm_shapes[1] else None
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200509 ifm2_shape = op.read_shapes[1] if op.read_shapes[1] is not None else ifm2_shape
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200510 limit_shape = Shape4D(1, max_t_size, max_t_size, max_t_size)
511
512 if any(dim_size > max_t_size for dim_size in ofm_shape.as_list()):
513 ofm_split = ofm_shape.floordiv_const(max_t_size).add(1, 1, 1, 1)
514
515 for height in range(ofm_split.height):
516 for width in range(ofm_split.width):
517 for depth in range(ofm_split.depth):
518 ofm_offset = Shape4D(0, height * max_t_size, width * max_t_size, depth * max_t_size)
519 ofm_part_shape = ofm_shape.clip(ofm_offset, limit_shape)
520 ofm_cut = (ofm_offset, ofm_part_shape)
521
522 ifm_d = depth * max_t_size if ifm_shape.depth == ofm_shape.depth else 0
523 ifm_w = width * max_t_size if ifm_shape.width == ofm_shape.width else 0
524 ifm_h = height * max_t_size if ifm_shape.height == ofm_shape.height else 0
525 ifm_offset = Shape4D(0, ifm_h, ifm_w, ifm_d)
526 ifm_part_shape = ifm_shape.clip(ifm_offset, limit_shape)
527 ifm_cut = (ifm_offset, ifm_part_shape)
528
529 if ifm2_shape is not None:
530 ifm2_d = depth * max_t_size if ifm2_shape.depth == ofm_shape.depth else 0
531 ifm2_w = width * max_t_size if ifm2_shape.width == ofm_shape.width else 0
532 ifm2_h = height * max_t_size if ifm2_shape.height == ofm_shape.height else 0
533 ifm2_offset = Shape4D(0, ifm2_h, ifm2_w, ifm2_d)
534 ifm2_part_shape = ifm2_shape.clip(ifm2_offset, limit_shape)
535 ifm2_cut = (ifm2_offset, ifm2_part_shape)
536 else:
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200537 ifm2_cut = (None, None)
538
539 create_elem_part_op(op, ifm_cut, ifm2_cut, ofm_cut)
540 op.ofm.ops.remove(op)
541 op.ifm.consumer_list.remove(op)
542 if op.ifm2 is not None:
543 op.ifm2.consumer_list.remove(op)
544 return
545
546
547def create_elem_part_op(op, ifm_cut, ifm2_cut, ofm_cut):
548 part_op = op.clone()
549 ifm_read_offset = op.read_offsets[0] if op.read_offsets[0] is not None else Shape4D(0, 0, 0, 0)
550 ofm_write_offset = op.write_offset if op.write_offset is not None else Shape4D(0, 0, 0, 0)
551 ifm_offset, ifm_shape = ifm_cut
552 ofm_offset, ofm_shape = ofm_cut
553
554 part_op.read_offsets[0] = ifm_read_offset + ifm_offset
555 part_op.read_shapes[0] = ifm_shape
556 part_op.write_offset = ofm_write_offset + ofm_offset
557 part_op.write_shape = ofm_shape
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200558 part_op.ifm_shapes = op.ifm_shapes.copy()
559 part_op.ofm_shapes = op.ofm_shapes.copy()
560 part_op.ifm.consumer_list.append(part_op)
561 op.ofm.ops.append(part_op)
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200562
563 ifm2_offset, ifm2_shape = ifm2_cut
564 if ifm2_offset:
565 ifm2_read_offset = op.read_offsets[1] if op.read_offsets[1] is not None else Shape4D(0, 0, 0, 0)
566 part_op.read_offsets[1] = ifm2_read_offset + ifm2_offset
567 part_op.read_shapes[1] = ifm2_shape
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200568 part_op.ifm2.consumer_list.append(part_op)
569
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200570 return part_op
571
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200572
573def get_nhwc_stride(shape):
574 stride_x = shape.depth
575 stride_y = shape.width * stride_x
576 stride_n = shape.height * stride_y
577 return Shape4D(stride_n, stride_y, stride_x, 1)
578
579
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200580def pad_to_rank(shape, rank):
581 """
582 Pads a shape to the given rank
583 """
584 while len(shape) < rank:
585 shape = [1] + shape
586
587 return shape
588
589
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200590def get_elem_shapes_removed_singles(op):
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200591 """
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200592 Returns the shapes of ifm(s)/ofms after removing all the dimensions that are 1 for all ifm(s)/ofm
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200593 """
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200594 binary = op.ifm2 is not None
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200595 ofm_shape = op.ofm_shapes[0].as_list() if len(op.ofm_shapes) > 0 else op.ofm.shape
596 ifm_shape = op.ifm_shapes[0].as_list() if len(op.ifm_shapes) > 0 else op.ifm.shape
597 if binary:
598 ifm2_shape = op.ifm_shapes[1].as_list() if len(op.ofm_shapes) else op.ifm2.shape
599
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200600 rank = max(len(ofm_shape), len(ifm_shape), len(ifm2_shape) if binary else 0)
601 ofm_shape = pad_to_rank(ofm_shape, rank)
602 ifm_shape = pad_to_rank(ifm_shape, rank)
603 if binary:
604 ifm2_shape = pad_to_rank(ifm2_shape, rank)
605
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200606 new_ofm_shape = []
607 new_ifm_shape = []
608 new_ifm2_shape = []
609 for idx in range(rank):
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200610 if ofm_shape[idx] != 1:
611 new_ofm_shape.append(ofm_shape[idx])
612 new_ifm_shape.append(ifm_shape[idx])
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200613 if binary:
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200614 new_ifm2_shape.append(ifm2_shape[idx])
615
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200616 if new_ofm_shape == []:
617 new_ofm_shape = [1]
618 new_ifm_shape = [1]
619 new_ifm2_shape = [1] if binary else None
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200620
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200621 return new_ofm_shape, new_ifm_shape, new_ifm2_shape
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200622
623
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200624def decomp_dims_elementwise(op):
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200625 """
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200626 Decompose elementwise ops with Rank > 3 (H,W,D).
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200627 If Rank > 3, all the dimensions above H are viewed as the N dimension.
628 the elementwise operation will be decomposed to N (of ofm) elementwise operations.
629 By reading and writing with offsets from/to the ifm(s)/ofm.
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200630 Note: Broadcast need to be handled for binary elementwise ops, and TOSA allowes for broadcast by both ifm and ifm2
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200631 """
632
633 ifm = op.ifm
634 ifm2 = op.ifm2
635 ofm = op.ofm
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200636 binary = op.ifm2 is not None
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200637
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200638 # Remove dimensions that are all 1
639 new_ofm_shape, new_ifm_shape, new_ifm2_shape = get_elem_shapes_removed_singles(op)
640 rank = len(new_ofm_shape)
641
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200642 if rank > 3:
643 n = rank - 3
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200644 ofm_decomp_shape = Shape4D(new_ofm_shape[0:n])
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200645 ofm_decomp_stride = get_nhwc_stride(ofm_decomp_shape)
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200646 ofm_part_shape = Shape4D(new_ofm_shape[n:])
647 op.ofm_shapes.append(Shape4D([ofm_decomp_shape.elements()] + new_ofm_shape[n:]))
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200648
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200649 if binary:
650 ifm_decomp_shape = Shape4D(new_ifm_shape[0:n])
651 ifm2_decomp_shape = Shape4D(new_ifm2_shape[0:n])
652 ifm_decomp_stride = get_nhwc_stride(ifm_decomp_shape)
653 ifm2_decomp_stride = get_nhwc_stride(ifm2_decomp_shape)
654 ifm_part_shape = Shape4D(new_ifm_shape[n:])
655 ifm2_part_shape = Shape4D(new_ifm2_shape[n:])
656 op.ifm_shapes.append(Shape4D([ifm_decomp_shape.elements()] + new_ifm_shape[n:]))
657 op.ifm_shapes.append(Shape4D([ifm2_decomp_shape.elements()] + new_ifm2_shape[n:]))
658 else:
659 op.ifm_shapes.append(Shape4D([ofm_decomp_shape.elements()] + new_ofm_shape[n:]))
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200660
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200661 op_list = []
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200662 for height in range(ofm_decomp_shape.height):
663 for width in range(ofm_decomp_shape.width):
664 for depth in range(ofm_decomp_shape.depth):
665 ofm_offset = Shape4D(0, height, width, depth)
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200666 ofm_offset = Shape4D(ofm_offset.dot_prod(ofm_decomp_stride), 0, 0, 0)
667 ofm_cut = (ofm_offset, ofm_part_shape)
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200668
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200669 if binary:
670 ifm_d = depth if ifm_decomp_shape.depth == ofm_decomp_shape.depth else 0
671 ifm_w = width if ifm_decomp_shape.width == ofm_decomp_shape.width else 0
672 ifm_h = height if ifm_decomp_shape.height == ofm_decomp_shape.height else 0
673 ifm_offset = Shape4D(0, ifm_h, ifm_w, ifm_d)
674 ifm_offset = Shape4D(ifm_offset.dot_prod(ifm_decomp_stride), 0, 0, 0)
675 ifm_cut = (ifm_offset, ifm_part_shape)
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200676
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200677 ifm2_d = depth if ifm2_decomp_shape.depth == ofm_decomp_shape.depth else 0
678 ifm2_w = width if ifm2_decomp_shape.width == ofm_decomp_shape.width else 0
679 ifm2_h = height if ifm2_decomp_shape.height == ofm_decomp_shape.height else 0
680 ifm2_offset = Shape4D(0, ifm2_h, ifm2_w, ifm2_d)
681 ifm2_offset = Shape4D(ifm2_offset.dot_prod(ifm2_decomp_stride), 0, 0, 0)
682 ifm2_cut = (ifm2_offset, ifm2_part_shape)
683 op_list.append(create_elem_part_op(op, ifm_cut, ifm2_cut, ofm_cut))
684 else:
685 op_list.append(create_elem_part_op(op, ofm_cut, None, ofm_cut))
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200686
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200687 ofm.ops.remove(op)
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200688 ifm.consumer_list.remove(op)
689 if binary:
690 ifm2.consumer_list.remove(op)
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200691
692 return op_list
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200693 else:
694 op.ofm_shapes.append(Shape4D(new_ofm_shape))
695 op.ifm_shapes.append(Shape4D(new_ifm_shape))
696 op.ifm_shapes.append(Shape4D(new_ifm2_shape))
697
698 return [op]
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200699
700
701def decomp_elementwise(tens, arch, nng):
702 """
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200703 Decompose elementwise ops with Rank > 3 (H,W,C).
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200704 Decompose size of tensors exceeding NPU max size
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200705 """
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200706 tens_ops = tens.ops.copy()
707 for op in tens_ops:
708 if op.type.is_elementwise_op():
709 decomp_list = decomp_dims_elementwise(op)
710 for part_op in decomp_list:
711 decompose_elem_tensors_hwc(part_op)
712 return tens
713
714
715def reshape_concat_shape(shape, rank, axis):
716 new_h = 1
717 for i in range(axis):
718 new_h *= shape[i]
719 new_c = 1
720 for i in range(axis + 1, rank):
721 new_c *= shape[i]
722 if axis == (rank - 1):
723 new_shape = [new_h, shape[axis], 1]
724 else:
725 new_shape = [new_h, shape[axis], new_c]
726 return new_shape
727
728
729def reshape_concat(op):
730 """
731 Reshapes concat ops with Rank > 3 (H,W,C).
732 """
733 ofm = op.ofm
734 rank = len(ofm.shape)
735 axis = op.attrs["axis"]
736 if axis < 0:
737 axis += rank
738
739 if rank > 3:
740 # Reshape so that axis in to be concatenated is the W dimension
741 # Reshape inputs
742 for inp in op.inputs:
743 new_shape = reshape_concat_shape(inp.shape, rank, axis)
744 op.ifm_shapes.append(Shape4D(new_shape))
745 # Reshape output
746 new_shape = reshape_concat_shape(ofm.shape, rank, axis)
747 op.ofm_shapes.append(Shape4D(new_shape))
748 op.attrs["axis4D"] = 2
749 else:
750 for inp in op.inputs:
751 op.ifm_shapes.append(Shape4D(inp.shape))
752 op.ofm_shapes.append(Shape4D(ofm.shape))
753 op.attrs["axis4D"] = axis + (4 - rank)
754
755
756def decomp_rewrite_concat(tens, arch, nng):
757 """
758 Decompose concat ops with Rank > 3 (H,W,C).
759 Rewrite of concat to elementwise operations
760 """
761 if len(tens.ops) == 1 and tens.ops[0].type == Op.Concat:
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200762 op = tens.ops[0]
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200763
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200764 reshape_concat(op)
765 rewrite_concat(op)
Patrik Gustavsson3f22ec22021-09-21 14:18:44 +0200766
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200767 op.ofm.ops.remove(op)
768 for inp in op.inputs:
769 inp.consumer_list.remove(op)
770
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200771 return tens
772
773
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200774def decomp_rewrite_pad(op, arch):
775 """
776 Decomposition of pad to elementwise operations:
777 For each dimension that needs padding:
778 -Create a new PAD operator for each dimension to be added
779 Ifm/ofm are reshape so this is the width dimension is to be padded
780 (rank for each is 3)
781 -Rewrite the the new PAD operator so there is:
782 -1 Add operator for copying the data
783 -1 Add operator for each left/right to be padded
784 """
785 # TODO several things would be possible to optimize
786 # For instance there are cases when it should be possible to pad 2
787 # dimensions at the same time.
788 if op.type == Op.Pad:
789 ofm_elements = shape_num_elements(op.ofm.shape)
790 padding = op.inputs[1].values
791
792 rank = len(op.ifm.shape)
793 next_ifm = op.ifm
794 next_ifm_shape = next_ifm.shape.copy()
795
796 first_pad_rewrite_op = None
797 ifm_quant = op.ifm.quantization.clone()
798
799 for dim in range(padding.shape[0]):
800 # Check if padding is to be applied in this dimension
801 dim_pad = padding[dim]
802 if not (dim_pad == 0).all():
803 # Reshape so that width dimension is to be padded
804 new_ifm_shape = reshape_concat_shape(next_ifm_shape, rank, dim)
805 new_pad_input = np.zeros((4, 2), dtype=np.int32)
806 new_pad_input[2] = dim_pad
807
808 pad_op = create_pad_nop(f"{op.name}_dim_{dim}")
809 pad_op.add_input_tensor(next_ifm)
810 new_pad_tens = op.inputs[1].clone("_dim_{dim}")
811
812 name = op.inputs[1].name + f"_dim_{dim}"
Tim Hall3b1578e2023-01-13 17:57:25 +0000813 new_pad_tens = create_const_tensor(name, list(new_pad_input.shape), DataType.int32, new_pad_input)
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200814 pad_op.add_input_tensor(new_pad_tens)
815
816 new_ofm_shape = new_ifm_shape.copy()
817 new_ofm_shape[-2] = new_ofm_shape[-2] + dim_pad.sum()
818 next_ifm_shape[dim] = next_ifm_shape[dim] + dim_pad.sum()
819
820 if Shape4D(new_ofm_shape).elements() == ofm_elements:
821 # Last one, use op.ofm
822 ofm = op.ofm
823 else:
824 # add a new ofm Tensor
825 ofm = Tensor(new_ofm_shape, op.ofm.dtype, f"{pad_op.name}_tens")
826 ofm.quantization = ifm_quant.clone()
827
828 pad_op.set_output_tensor(ofm)
829 pad_op.ifm_shapes.append(Shape4D(new_ifm_shape))
830 pad_op.ofm_shapes.append(Shape4D(new_ofm_shape))
831 DebugDatabase.add_optimised(op, pad_op)
832 next_ifm = ofm
833
834 # Rewrite the pad op
835 converted_pad_op = convert_pad_in_width(pad_op)
836 first_pad_rewrite_op = converted_pad_op
837 else:
838 # Change to Identity operation (will be removed)
839 op.type = Op.Identity
840
841 if first_pad_rewrite_op:
842 assert op.ofm.shape == next_ifm_shape
843 for inp in op.inputs:
844 inp.consumer_list.remove(op)
845 return first_pad_rewrite_op
846
847 return op
848
849
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200850def fixup_quantization(op, arch, nng):
851 if op.ifm and op.ifm.quantization.zero_point is None:
852 op.ifm.quantization.zero_point = 0
853 if op.ifm2 and op.ifm2.quantization.zero_point is None:
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200854 op.ifm2.quantization.zero_point = 0
855 if not op.forced_output_quantization:
856 if op.ofm and op.ofm.quantization and op.ofm.quantization.zero_point is None:
857 op.ofm.quantization.zero_point = 0
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200858 return op
859
860
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200861def supported_operator_check(op, arch, nng):
862 op.run_on_npu = arch.tosa_supported_operators.is_operator_supported(op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200863 assert op.run_on_npu or op.type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200864 return op
865
866
867def tosa_optimise_graph(nng, arch):
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200868
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200869 # TODO the supported operator checking need to be split in semantic and HW checks
870 for idx, sg in enumerate(nng.subgraphs):
871 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200872 nng,
873 sg,
874 arch,
875 [],
876 [supported_operator_check],
877 rewrite_unsupported=False,
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200878 )
879
880 # Decomposing and rewrite of concat
881 for idx, sg in enumerate(nng.subgraphs):
882 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
883 nng, sg, arch, [decomp_rewrite_concat], [], rewrite_unsupported=False
884 )
885
Patrik Gustavssonb4936ad2021-10-05 13:53:34 +0200886 # Decomposing of pad
887 for idx, sg in enumerate(nng.subgraphs):
888 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [decomp_rewrite_pad])
889 sg.refresh_after_modification()
890
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200891 # Handle sg input output
892 for idx, sg in enumerate(nng.subgraphs):
893 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200894 nng,
895 sg,
896 arch,
897 [],
898 [fix_sg_input_output_tosa],
899 rewrite_unsupported=True,
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200900 )
901
902 # Removal of reshapes
903 for sg in nng.subgraphs:
Patrik Gustavssonef3ebdd2021-10-01 11:10:25 +0200904 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_memory_ops])
Patrik Gustavsson008cd102021-09-24 13:46:42 +0200905 sg.refresh_after_modification()
906
Patrik Gustavssonc2b129d2021-09-23 13:52:34 +0200907 # Decomposing of elementwise
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200908 for idx, sg in enumerate(nng.subgraphs):
909 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
910 nng, sg, arch, [decomp_elementwise], [], rewrite_unsupported=False
911 )
912
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200913 for idx, sg in enumerate(nng.subgraphs):
914 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200915 nng,
916 sg,
917 arch,
918 [],
919 [set_ifm_ofm_op_shapes],
920 rewrite_unsupported=False,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200921 )
922
Patrik Gustavssondf995102021-08-23 15:33:59 +0200923 # Removal of Transpose
924 for idx, sg in enumerate(nng.subgraphs):
925 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200926 nng,
927 sg,
928 arch,
929 [],
930 [remove_const_transpose],
931 rewrite_unsupported=False,
Patrik Gustavssondf995102021-08-23 15:33:59 +0200932 )
933
Patrik Gustavssonf366fb12021-09-07 13:30:29 +0200934 # TODO, when and where to best handle calc_scaling_avgpool
935 for idx, sg in enumerate(nng.subgraphs):
936 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200937 nng,
938 sg,
939 arch,
940 [],
941 [calc_scaling_avgpool],
942 rewrite_unsupported=False,
Patrik Gustavssonf366fb12021-09-07 13:30:29 +0200943 )
944
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200945 # Rewite Operators step
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200946 op_rewrite_list = [set_tensor_equivalence, rewrite_rescale, convert_depthwise_to_conv, convert_table_to_lut]
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200947
948 for idx, sg in enumerate(nng.subgraphs):
949 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200950 nng,
951 sg,
952 arch,
953 [],
954 op_rewrite_list,
955 rewrite_unsupported=False,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200956 )
957
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200958 # Post-processing step 1
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200959 for idx, sg in enumerate(nng.subgraphs):
960 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200961 nng,
962 sg,
963 arch,
964 [],
965 [rewrite_activation, add_padding_fields],
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200966 )
967
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200968 # Removal of Slice, need to be done after optimisation has been performed,
969 # since ifm/ofm_shapes are of importance to this function
970 for sg in nng.subgraphs:
971 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_splitsliceread])
972 sg.refresh_after_modification()
973
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200974 # Post-processing step 2
975 for idx, sg in enumerate(nng.subgraphs):
Jonas Ohlssond8575072022-03-30 10:30:25 +0200976 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
977 nng,
978 sg,
979 arch,
980 [],
981 [fixup_quantization],
982 )
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200983
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200984 return nng