blob: fde01cfec5cbc04a4c5178d7d002b1676d715f18 [file] [log] [blame]
Rickard Bolinbc6ee582022-11-04 08:24:29 +00001# SPDX-FileCopyrightText: Copyright 2021-2022 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# Common functions and definitions used during the graph optimization.
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020019from typing import Tuple
20
Patrik Gustavssondf995102021-08-23 15:33:59 +020021import numpy as np
22
Patrik Gustavssonf436ada2021-09-14 14:56:48 +020023from . import lut
Tim Halld6efcd32022-09-02 15:01:01 +010024from .architecture_features import Accelerator
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020025from .data_type import DataType
26from .debug_database import DebugDatabase
Patrik Gustavssondf995102021-08-23 15:33:59 +020027from .errors import UnsupportedFeatureError
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020028from .errors import VelaError
29from .operation import Op
Patrik Gustavssondf995102021-08-23 15:33:59 +020030from .operation_util import create_avgpool_nop
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020031from .shape4d import Shape4D
Patrik Gustavssonf436ada2021-09-14 14:56:48 +020032from .tensor import create_const_tensor
33from .tensor import QuantizationParameters
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020034
Jonas Ohlsson81942e92021-08-20 09:33:28 +020035memory_only_ops = (
36 Op.Reshape,
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020037 Op.QuantizedReshape,
Jonas Ohlsson81942e92021-08-20 09:33:28 +020038 Op.Squeeze,
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020039 Op.ExpandDims,
Patrik Gustavssonef3ebdd2021-10-01 11:10:25 +020040 Op.Identity,
Jonas Ohlsson81942e92021-08-20 09:33:28 +020041)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020042
Johan Alfvén48e51592022-09-28 20:06:25 +020043# Ops that are dependent that the original ifm tensor shape is not changed
44# by the bypass memory op function
45original_ifm_shape_ops = (Op.Mean,)
46
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020047
48def _avoid_nhcwb16_for_concat(tens):
49 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
50 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
51 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
52 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
53 return any(op.write_offset.depth % 16 != 0 for op in tens.ops if op.write_offset is not None)
54
55
56def _avoid_nhcwb16_for_split(tens):
57 # If read offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
James Ward6bf16132021-09-08 11:14:20 +010058
59 # Return True if NHCWB16 needs to be avoided
60 def offset_not_aligned(read_offset):
61 return read_offset is not None and (read_offset.depth % 16) != 0
62
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020063 for cons_op in tens.consumer_list:
64 if cons_op.ifm == tens:
James Ward6bf16132021-09-08 11:14:20 +010065 if offset_not_aligned(cons_op.read_offsets[0]):
66 return True
67 if cons_op.ifm2 is not None and cons_op.ifm2 == tens:
68 if offset_not_aligned(cons_op.read_offsets[1]):
69 return True
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020070 return False
71
72
73def _avoid_nhcwb16_for_shapes(tens):
74 # check all producers/consumers to see if any op shape is preventing NHCWB16
75 for cons_op in tens.consumer_list:
76 if cons_op.ifm == tens:
77 cons_op_shape = cons_op.ifm_shapes[0]
78 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == tens:
79 cons_op_shape = cons_op.ifm_shapes[1]
80 else:
81 assert False
82 if Shape4D(tens.shape) != cons_op_shape:
83 return True
84
85 for prod_op in tens.ops:
86 if Shape4D(tens.shape) != prod_op.ofm_shapes[0]:
87 return True
88
89 return False
90
91
92# Check if non linear format can be used
93def check_format_restrictions(tens, arch):
94 if len(tens.ops) < 1:
95 return
96 if tens.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const) or any(
97 cons is None for cons in tens.consumer_list
98 ):
99 return
100
101 # Check if any of the producers/consumers is run on CPU
102 if not all(cons.run_on_npu for cons in tens.consumer_list):
103 return
104 if not all(prod.run_on_npu for prod in tens.ops):
105 return
106
107 # "Concat" ofm exception:
108 if _avoid_nhcwb16_for_concat(tens):
109 return
110
111 # "Split" ifm exception:
112 if _avoid_nhcwb16_for_split(tens):
113 return
114
115 # Shapes checking: check all producers/consumers are NHCWB16 compatible with tens.shape
116 if _avoid_nhcwb16_for_shapes(tens):
117 return
118
Rickard Bolinfea15162022-07-04 16:19:16 +0000119 # Resize bilinear half pixel center implementation requires OFM with linear format to
120 # allow stride modification in H/W dimensions.
121 for op in tens.ops:
122 if op.original_type == Op.ResizeBilinear and op.type == Op.DepthwiseConv2DBias:
123 return
124
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200125 for op in tens.consumer_list:
Tim Halld6efcd32022-09-02 15:01:01 +0100126 if op.type == Op.ReduceSum and (
127 tens.dtype == DataType.int32 or arch.accelerator_config == Accelerator.Ethos_U65_512
128 ):
129 # ReduceSum requires NHWC input
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200130 return
131 if op.type == Op.Reshape:
132 # Using NHCWB16 format for a no-op reshape is only an option if subsequent
133 # consumers do not also need to perform a reshape or if the OFM is going to
134 # be processed by CPU operations. No-op reshape consumers with empty lists
135 # (those that have no consumers, or null-consumers used as list terminators)
136 # must use normal NHWC output.
137
138 def incompatible_consumers(oper):
139 if oper and oper.type == Op.Reshape:
140 for consumer in oper.outputs[0].consumer_list:
141 yield from incompatible_consumers(consumer)
142 yield not oper or not oper.run_on_npu
143
144 if not any(incompatible_consumers(op)):
145
146 def get_rewrites(oper):
147 if oper and oper.type == Op.Reshape:
148 for consumer in oper.outputs[0].consumer_list:
149 yield from get_rewrites(consumer)
150 yield oper
151
152 # Detect no-op reshapes by comparing their full input and output tensor shapes.
153 inshape = op.ifm_shapes[0]
154 compatible_shape = [(inshape == oper.ofm_shapes[0]) for oper in get_rewrites(op)]
155 if not (compatible_shape and all(compatible_shape)):
156 return
157 else:
158 return
159
160 tens.needs_linear_format = False
161
162
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200163def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]:
164 """
165 Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding
166 that provides equivalent results.
167 """
168 total_padding = needed_total_padding(input_size, stride, filter_size)
169
170 # The bottom/right padding might need downward adjustment depending on stride/input size
171 total_minus_before = total_padding - pad_before
172 output_pad_after = pad_after
173 while output_pad_after > 0 and output_pad_after % stride != total_minus_before % stride:
174 output_pad_after -= 1
175 return pad_before, output_pad_after
176
177
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200178def needed_total_padding(input_size, stride, filter_size):
179 out_size = (input_size + stride - 1) // stride
180 needed_input = (out_size - 1) * stride + filter_size
181 total_padding = max(0, needed_input - input_size)
182 return total_padding
183
184
185# Set input/output tensor equivalence to the same id for memory operations
186def set_tensor_equivalence(op, arch, nng):
187 if op.type in memory_only_ops:
188 eid = op.outputs[0].equivalence_id
189 for inp in op.inputs:
190 inp.equivalence_id = eid
191 return op
192
193
194def set_ifm_ofm_op_shapes(op, arch, nng):
195 if op.run_on_npu and op.type.needs_shapes():
196 if op.ifm_shapes or op.ofm_shapes:
197 # Shapes already set
198 return op
199 op.set_ifm_ofm_shapes()
200 return op
201
202
Johan Alfvén48e51592022-09-28 20:06:25 +0200203def bypass_need_to_keep_ofm_shape(op):
204 # Check if ifm must be replaced by ofm (rank is changed or the op that follow must have original ifm shape)
205 ifm_replaced_by_ofm = any(
206 ofm_cons is not None and ofm_cons.type in original_ifm_shape_ops for ofm_cons in op.ofm.consumer_list
207 ) or len(op.ifm.shape) != len(op.ofm.shape)
208 return ifm_replaced_by_ofm
209
210
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200211def bypass_memory_only_ops(op):
212 assert op.type in memory_only_ops
Patrik Gustavssondf995102021-08-23 15:33:59 +0200213 ofm = op.ofm
214 ifm = op.ifm
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200215
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200216 # Check if ifm/ofm are network ifm/ofm
Patrik Gustavssondf995102021-08-23 15:33:59 +0200217 ifm_is_sg_ifm = ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200218 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list)
219 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list)
220 # Check if ifm/ofm is produced respectively consumed by CPU
Patrik Gustavssondf995102021-08-23 15:33:59 +0200221 ifm_is_cpu_produced = any(ifm_prod is not None and not ifm_prod.run_on_npu for ifm_prod in op.ifm.ops)
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200222 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 Gustavssondf995102021-08-23 15:33:59 +0200223
224 # This case should be handled prior to this function
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200225 assert not ((ifm_is_sg_ifm or ifm_is_sg_ofm or ifm_is_cpu_produced) and (ofm_is_sg_ofm or ofm_is_cpu_consumed))
Patrik Gustavssondf995102021-08-23 15:33:59 +0200226
Johan Alfvén48e51592022-09-28 20:06:25 +0200227 if (ifm.shape != ofm.shape) and (ofm_is_sg_ofm or ofm_is_cpu_consumed or bypass_need_to_keep_ofm_shape(op)):
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200228 # Bypassed by replacing ifm with ofm
229 ofm.ops = []
230 for prev_op in ifm.ops:
231 prev_op.outputs = [ofm]
232 ofm.ops.append(prev_op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200233
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200234 # All ifm consumers need to use ofm as input
235 for ifm_cons in ifm.consumer_list:
236 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
237 if cons_ifm == ifm:
238 ifm_cons.set_input_tensor(ofm, ifm_idx)
239 else:
240 # Bypassed by replacing ofm with ifm
241 for cons in ofm.consumer_list:
242 for ifm_idx, cons_ifm in enumerate(cons.inputs):
243 if cons_ifm == ofm:
244 cons.set_input_tensor(ifm, ifm_idx)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200245
246
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200247def move_splitsliceread_to_consumer(op, cons_op):
248 assert op.type == Op.SplitSliceRead
249
250 if cons_op.ifm == op.ofm:
251 cons_op.read_offsets[0] = op.read_offsets[0]
252 cons_op.read_shapes[0] = op.read_shapes[0]
253 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[0])
254 cons_op.ifm_shapes[0] = op.ifm_shapes[0]
255 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == op.ofm:
256 cons_op.read_offsets[1] = op.read_offsets[0]
257 cons_op.read_shapes[1] = op.read_shapes[0]
258 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[1])
259 cons_op.ifm_shapes[1] = op.ifm_shapes[0]
260
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200261 op.ofm.consumer_list.remove(cons_op)
262 op.ofm.ops = []
263 op.ifm.consumer_list.remove(op)
264
265
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200266def check_memory_only_removed(op, arch):
267 if op.run_on_npu and op.type in memory_only_ops:
268 # Memory only operators should have been removed
269 raise VelaError(f"Memory only {op.type} op {op} expected to have been removed, still remains")
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200270
271
272def record_optimised(op, arch):
273 if op.type != Op.Const:
274 DebugDatabase.add_optimised(op, op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200275
276
Johan Alfvén48e51592022-09-28 20:06:25 +0200277def insert_copy_op_before_op(op):
278 # Create a avg_pool nop op with ifm as input
279 tens = op.ifm
280 copy_tens = tens.clone()
281 copy_op = create_avgpool_nop(f"{tens.name}_avgpool")
282 copy_op.add_input_tensor(tens)
283 copy_op.set_output_tensor(copy_tens)
284 copy_op.set_ifm_ofm_shapes()
285
286 op.set_input_tensor(copy_tens, 0)
287
288 DebugDatabase.add_optimised(op, copy_op)
289
290
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200291def insert_copy_op_after_tens(tens):
292 tens_cons_list_copy = tens.consumer_list.copy()
Patrik Gustavssondf995102021-08-23 15:33:59 +0200293
294 # Create a avg_pool nop op with ifm as input
295 copy_tens = tens.clone()
296 copy_op = create_avgpool_nop(tens.name + "_avgpool")
297 copy_op.add_input_tensor(tens)
298 copy_op.set_output_tensor(copy_tens)
299 copy_op.set_ifm_ofm_shapes()
300 copy_op.run_on_npu = True
301
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200302 # Set copy_ifm consumers
303 for tens_cons in tens_cons_list_copy:
304 if tens_cons is not None:
305 for ifm_idx, cons_inp in enumerate(tens_cons.inputs):
306 if cons_inp == tens:
307 tens_cons.set_input_tensor(copy_tens, ifm_idx)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200308
309 DebugDatabase.add_optimised(tens.ops[0], copy_op)
310
311
312def fix_sg_input_output(op, arch, nng):
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200313 if not op.run_on_npu or op.type not in memory_only_ops:
Patrik Gustavssondf995102021-08-23 15:33:59 +0200314 return op
315
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200316 # For the memory only operators we want to remove, tensors are removed.
317 # But in order to to do this, they cannot be outputs of the sg,
318 # this need to be fixed prior to the removal.
Patrik Gustavssondf995102021-08-23 15:33:59 +0200319 # Solution is to add a avgpool NOP, to maintain the original tensor.
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200320 # This is also valid when reshape ifm/ofm is produced respectively
321 # consumed by CPU
Patrik Gustavssondf995102021-08-23 15:33:59 +0200322
Johan Alfvén48e51592022-09-28 20:06:25 +0200323 # Rare case: original_ifm_shape_ops contain ops that are dependent
324 # that the original ifm tensor shape is not changed by the bypass memory
325 # function. If the memory only op ifm is subgraph ifm/ifm is cpu produced
326 # or the ifm is consumed by many, then there is a need to insert an avgpool
327 # NOP before the original_ifm_shape_ops. Also note that the NOP is only inserted
328 # before original_ifm_shape_ops. The above is also true when the memory only
329 # op change the rank between the IFM and OFM.
330 #
331 # Below is an example showing the case when there is a need for an AVG NOP
332 # when RESHAPE is bypassed by replacing IFM with OFM.
333 #
334 # Converts to And in bypass_memory
335 # ---> --->
336 # -----ADD----- -----ADD----- -----ADD-----
337 # | | | | | |
338 # 1x6x6x10 1x6x6x10 1x6x6x10 1x6x6x10 1x6x6x10 1x6x6x10
339 # RESHAPE MEAN AVG POOL MEAN AVG POOL MEAN
340 # | | | |
341 # 1x20x3x6 1x6x6x10 1x20x3x6
342 # MEAN RESHAPE MEAN
343 # |
344 # 1x20x3x6
345 # MEAN
346 ifm_has_multiple_cons = len(op.ifm.consumer_list) > 1
347
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200348 # Check if operator ifm/ofm are sg ifm/ofm
Patrik Gustavssondf995102021-08-23 15:33:59 +0200349 ifm_is_sg_ifm = op.ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200350 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in op.ifm.consumer_list)
351 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in op.ofm.consumer_list)
352 # Check if ifm/ofm is produced respectively consumed by CPU
Johan Alfvén5060ff52022-09-15 15:50:30 +0200353 ifm_is_cpu_produced = any(ifm_prod is not None and not ifm_prod.run_on_npu for ifm_prod in op.ifm.ops)
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200354 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)
Johan Alfvén5060ff52022-09-15 15:50:30 +0200355
Johan Alfvén48e51592022-09-28 20:06:25 +0200356 if bypass_need_to_keep_ofm_shape(op):
357 # Bypass need to keep OFM shape
358 if ifm_has_multiple_cons:
359 # Rare case:
360 # IFM need to persist due to multiple consumers and copy op is needed
361 # OFM will replace IFM for the memory only op
362 insert_copy_op_before_op(op)
363 elif not (ofm_is_sg_ofm or ofm_is_cpu_consumed):
364 # Only one consumer and OFM is not subgraph output or cpu consumed,
365 # safe to replace ifm.shape by ofm.shape
366 # IFM can then replace OFM for the memory only op and no copy op is needed
367 op.ifm.shape = op.ofm.shape
368
369 # Special case when when OFM is sg_ofm or cpu_consumed
Johan Alfvén8484d6e2022-09-28 14:22:54 +0200370 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):
371 # Both ifm and ofm need to persist, but only ifm need a copy, in order to remove the memory only operator.
372 insert_copy_op_after_tens(op.ifm)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200373
374 return op
375
376
377def convert_depthwise_to_conv(op, arch, nng):
378 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
379 # the ofm depth equals the depth multipler.
380 # If those conditions are true, then we can perform a simple
381 # switch of the operator type (and weight order)
382
383 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
384 ifm_shape = op.ifm_shapes[0]
385 weight_tensor = op.inputs[1]
386 ofm_shape = op.ofm_shapes[0]
387 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
388 # Change op type to Conv2d
389 op.type = Op.Conv2DBias
390 del op.attrs["channel_multiplier"]
391 del op.attrs["depth_multiplier"]
392
393 weight_tensor.values = np.transpose(weight_tensor.values, (0, 1, 3, 2))
394 weight_tensor.set_all_shapes(list(weight_tensor.values.shape))
395 else:
396 raise UnsupportedFeatureError(
397 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
398 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
399 )
400 DebugDatabase.add_optimised(op, op)
401 return op
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200402
403
404def convert_to_lut(op, lut_values, lut_name):
405 # Rewrite the operation by Add with scalar 0 + LUT activation
406 ifm = op.inputs[0]
407 if ifm is None:
408 return op
409 assert ifm.dtype.size_in_bytes() == 1
410 op.type = Op.Add
411 op.name = op.name + "_lut_" + lut_name
412 # Mark as no-op to enable potential fusing optimizations
413 op.attrs["is_nop"] = True
414 # Create an input tensor containing scalar zero
415 quantization = QuantizationParameters(0.0, 255.0)
416 quantization.scale_f32 = ifm.quantization.scale_f32
417 quantization.zero_point = 0
418 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
419 op.add_input_tensor(tens)
420 op.ifm_shapes.append(Shape4D(tens.shape)) # TODO no shape?
421
422 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
423 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
424 # should be the same as the IFM
425 op.forced_output_quantization = ifm.quantization
426 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
427 op.set_activation_lut(lut_tensor)
428 op.set_ifm_ofm_shapes()
429 return op