blob: 8b24eaf91a9d13445f8fe4fff8d6c7a7c58ec1b2 [file] [log] [blame]
Johan Alfvén78fc9bc2023-01-05 15:09:27 +01001# 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# 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
30from .shape4d import Shape4D
Patrik Gustavssonf436ada2021-09-14 14:56:48 +020031from .tensor import create_const_tensor
32from .tensor import QuantizationParameters
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020033
Jonas Ohlsson81942e92021-08-20 09:33:28 +020034memory_only_ops = (
35 Op.Reshape,
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020036 Op.QuantizedReshape,
Jonas Ohlsson81942e92021-08-20 09:33:28 +020037 Op.Squeeze,
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020038 Op.ExpandDims,
Patrik Gustavssonef3ebdd2021-10-01 11:10:25 +020039 Op.Identity,
Jonas Ohlsson81942e92021-08-20 09:33:28 +020040)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020041
42
43def _avoid_nhcwb16_for_concat(tens):
44 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
45 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
46 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
47 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
48 return any(op.write_offset.depth % 16 != 0 for op in tens.ops if op.write_offset is not None)
49
50
51def _avoid_nhcwb16_for_split(tens):
52 # 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 +010053
54 # Return True if NHCWB16 needs to be avoided
55 def offset_not_aligned(read_offset):
56 return read_offset is not None and (read_offset.depth % 16) != 0
57
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020058 for cons_op in tens.consumer_list:
59 if cons_op.ifm == tens:
James Ward6bf16132021-09-08 11:14:20 +010060 if offset_not_aligned(cons_op.read_offsets[0]):
61 return True
62 if cons_op.ifm2 is not None and cons_op.ifm2 == tens:
63 if offset_not_aligned(cons_op.read_offsets[1]):
64 return True
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020065 return False
66
67
68def _avoid_nhcwb16_for_shapes(tens):
69 # check all producers/consumers to see if any op shape is preventing NHCWB16
70 for cons_op in tens.consumer_list:
71 if cons_op.ifm == tens:
72 cons_op_shape = cons_op.ifm_shapes[0]
73 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == tens:
74 cons_op_shape = cons_op.ifm_shapes[1]
75 else:
76 assert False
77 if Shape4D(tens.shape) != cons_op_shape:
78 return True
79
80 for prod_op in tens.ops:
81 if Shape4D(tens.shape) != prod_op.ofm_shapes[0]:
82 return True
83
84 return False
85
86
Johan Alfven90724962023-02-02 09:07:48 +010087def _avoid_nhcwb16_for_memory_only(tens):
88 # check all producers/consumers to see if any op is preventing NHCWB16
89 return any(op.type == Op.Memcpy for op in (tens.consumer_list + tens.ops))
90
91
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020092# 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
Johan Alfven90724962023-02-02 09:07:48 +0100119 # Memory only ifm/ofm exception: DMA ops must use NHCW
120 if _avoid_nhcwb16_for_memory_only(tens):
121 return
122
Rickard Bolinfea15162022-07-04 16:19:16 +0000123 # Resize bilinear half pixel center implementation requires OFM with linear format to
124 # allow stride modification in H/W dimensions.
125 for op in tens.ops:
126 if op.original_type == Op.ResizeBilinear and op.type == Op.DepthwiseConv2DBias:
127 return
128
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200129 for op in tens.consumer_list:
Tim Halld6efcd32022-09-02 15:01:01 +0100130 if op.type == Op.ReduceSum and (
131 tens.dtype == DataType.int32 or arch.accelerator_config == Accelerator.Ethos_U65_512
132 ):
133 # ReduceSum requires NHWC input
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200134 return
135 if op.type == Op.Reshape:
136 # Using NHCWB16 format for a no-op reshape is only an option if subsequent
137 # consumers do not also need to perform a reshape or if the OFM is going to
138 # be processed by CPU operations. No-op reshape consumers with empty lists
139 # (those that have no consumers, or null-consumers used as list terminators)
140 # must use normal NHWC output.
141
142 def incompatible_consumers(oper):
143 if oper and oper.type == Op.Reshape:
144 for consumer in oper.outputs[0].consumer_list:
145 yield from incompatible_consumers(consumer)
146 yield not oper or not oper.run_on_npu
147
148 if not any(incompatible_consumers(op)):
149
150 def get_rewrites(oper):
151 if oper and oper.type == Op.Reshape:
152 for consumer in oper.outputs[0].consumer_list:
153 yield from get_rewrites(consumer)
154 yield oper
155
156 # Detect no-op reshapes by comparing their full input and output tensor shapes.
157 inshape = op.ifm_shapes[0]
158 compatible_shape = [(inshape == oper.ofm_shapes[0]) for oper in get_rewrites(op)]
159 if not (compatible_shape and all(compatible_shape)):
160 return
161 else:
162 return
163
164 tens.needs_linear_format = False
165
166
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200167def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]:
168 """
169 Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding
170 that provides equivalent results.
171 """
172 total_padding = needed_total_padding(input_size, stride, filter_size)
173
174 # The bottom/right padding might need downward adjustment depending on stride/input size
175 total_minus_before = total_padding - pad_before
176 output_pad_after = pad_after
177 while output_pad_after > 0 and output_pad_after % stride != total_minus_before % stride:
178 output_pad_after -= 1
179 return pad_before, output_pad_after
180
181
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200182def needed_total_padding(input_size, stride, filter_size):
183 out_size = (input_size + stride - 1) // stride
184 needed_input = (out_size - 1) * stride + filter_size
185 total_padding = max(0, needed_input - input_size)
186 return total_padding
187
188
189# Set input/output tensor equivalence to the same id for memory operations
190def set_tensor_equivalence(op, arch, nng):
191 if op.type in memory_only_ops:
192 eid = op.outputs[0].equivalence_id
193 for inp in op.inputs:
194 inp.equivalence_id = eid
195 return op
196
197
198def set_ifm_ofm_op_shapes(op, arch, nng):
199 if op.run_on_npu and op.type.needs_shapes():
200 if op.ifm_shapes or op.ofm_shapes:
201 # Shapes already set
202 return op
203 op.set_ifm_ofm_shapes()
204 return op
205
206
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200207def move_splitsliceread_to_consumer(op, cons_op):
208 assert op.type == Op.SplitSliceRead
209
210 if cons_op.ifm == op.ofm:
211 cons_op.read_offsets[0] = op.read_offsets[0]
212 cons_op.read_shapes[0] = op.read_shapes[0]
213 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[0])
214 cons_op.ifm_shapes[0] = op.ifm_shapes[0]
215 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == op.ofm:
216 cons_op.read_offsets[1] = op.read_offsets[0]
217 cons_op.read_shapes[1] = op.read_shapes[0]
218 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[1])
219 cons_op.ifm_shapes[1] = op.ifm_shapes[0]
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200220 op.ofm.consumer_list.remove(cons_op)
221 op.ofm.ops = []
222 op.ifm.consumer_list.remove(op)
223
224
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200225def check_memory_only_removed(op, arch):
226 if op.run_on_npu and op.type in memory_only_ops:
227 # Memory only operators should have been removed
228 raise VelaError(f"Memory only {op.type} op {op} expected to have been removed, still remains")
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200229
230
231def record_optimised(op, arch):
wilisa0179a89042022-11-02 17:18:43 +0000232 if op.type not in (Op.Const, Op.Placeholder):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200233 DebugDatabase.add_optimised(op, op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200234
235
Johan Alfvena5e1b622023-02-02 14:59:03 +0100236def bypass_memory_only_ops(op, arch, nng):
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200237 if not op.run_on_npu or op.type not in memory_only_ops:
Patrik Gustavssondf995102021-08-23 15:33:59 +0200238 return op
239
Johan Alfvena5e1b622023-02-02 14:59:03 +0100240 # Memory only operators can be completely removed if there is a one to one
241 # connection. The reshape OFM can be connected to the previous op.
Johan Alfvén48e51592022-09-28 20:06:25 +0200242 #
Johan Alfvena5e1b622023-02-02 14:59:03 +0100243 # Bypassed to
244 # --->
245 # 1x6x6x10 1x6x6x10
246 # ADD ADD
247 # | -------> |
248 # 1x6x6x10 | 1x20x3x6
249 # RESHAPE | MEAN
250 # | ---------|
251 # 1x20x3x10
252 # MEAN
Johan Alfvén48e51592022-09-28 20:06:25 +0200253 #
Johan Alfvena5e1b622023-02-02 14:59:03 +0100254 # In the above the ADD OFM = RESHAPE IFM is removed and replaced by
255 # the RESHAPE OFM.
256 #
257 # Then there are two cases when bypassing is not possible. One is when
258 # the IFM is produced by the CPU. This tensor must be preserved. It
259 # cannot be removed from the graph. The other case is when the IFM has
260 # multiple consumers, then it is not possible to just bypass the op and
261 # there is a need for a DMA (nop).
262 #
263 # Converts to
264 # --->
265 # 1x6x6x10 1x6x6x10
266 # -----ADD----- -----ADD-----
267 # | | | |
268 # 1x6x6x10 1x6x6x10 1x6x6x10 1x6x6x10
269 # RESHAPE MEAN DMA OP MEAN
270 # | |
271 # 1x20x3x6 1x20x3x6
272 # MEAN MEAN
273 #
274 # If the DMA IFM and DMA OFM ends up in the same memory area
275 # the DMA op will be removed when the cmd stream is generated.
276
Johan Alfvén48e51592022-09-28 20:06:25 +0200277 ifm_has_multiple_cons = len(op.ifm.consumer_list) > 1
Johan Alfvén5060ff52022-09-15 15:50:30 +0200278 ifm_is_cpu_produced = any(ifm_prod is not None and not ifm_prod.run_on_npu for ifm_prod in op.ifm.ops)
279
Johan Alfvena5e1b622023-02-02 14:59:03 +0100280 if ifm_has_multiple_cons or ifm_is_cpu_produced:
281 # Convert to a memcpy op
282 op.type = Op.Memcpy
283 DebugDatabase.add_optimised(op, op)
284 else:
285 # Bypass op
286 ofm = op.ofm
287 ifm = op.ifm
288 ofm.ops = []
289 for prev_op in ifm.ops:
290 prev_op.outputs = [ofm]
291 ofm.ops.append(prev_op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200292
293 return op
294
295
296def convert_depthwise_to_conv(op, arch, nng):
297 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
298 # the ofm depth equals the depth multipler.
299 # If those conditions are true, then we can perform a simple
300 # switch of the operator type (and weight order)
301
302 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
303 ifm_shape = op.ifm_shapes[0]
304 weight_tensor = op.inputs[1]
305 ofm_shape = op.ofm_shapes[0]
306 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
307 # Change op type to Conv2d
308 op.type = Op.Conv2DBias
309 del op.attrs["channel_multiplier"]
310 del op.attrs["depth_multiplier"]
311
312 weight_tensor.values = np.transpose(weight_tensor.values, (0, 1, 3, 2))
313 weight_tensor.set_all_shapes(list(weight_tensor.values.shape))
wilisa0179a89042022-11-02 17:18:43 +0000314 DebugDatabase.add_optimised(op, op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200315 else:
316 raise UnsupportedFeatureError(
317 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
318 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
319 )
Patrik Gustavssondf995102021-08-23 15:33:59 +0200320 return op
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200321
322
323def convert_to_lut(op, lut_values, lut_name):
324 # Rewrite the operation by Add with scalar 0 + LUT activation
Tim Hall1c590482023-01-26 17:27:00 +0000325 ifm = op.ifm
326 ofm = op.ofm
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200327 if ifm is None:
328 return op
329 assert ifm.dtype.size_in_bytes() == 1
330 op.type = Op.Add
331 op.name = op.name + "_lut_" + lut_name
332 # Mark as no-op to enable potential fusing optimizations
333 op.attrs["is_nop"] = True
334 # Create an input tensor containing scalar zero
335 quantization = QuantizationParameters(0.0, 255.0)
336 quantization.scale_f32 = ifm.quantization.scale_f32
337 quantization.zero_point = 0
Tim Hall1c590482023-01-26 17:27:00 +0000338 tens = create_const_tensor(ifm.name + "_scalar0", [], ifm.dtype, [0], quantization=quantization)
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200339 op.add_input_tensor(tens)
340 op.ifm_shapes.append(Shape4D(tens.shape)) # TODO no shape?
341
342 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
343 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
344 # should be the same as the IFM
345 op.forced_output_quantization = ifm.quantization
Tim Hall1c590482023-01-26 17:27:00 +0000346
347 # the lut tensor datatype needs to match both; the ofm datatype, because these are the values output; and the
348 # datatype used to generate the lut values (which is probably the ifm datatype), because we want to avoid any
349 # potential overflow errors in create_lut_tensor() caused by converting Python int (which could represent a uint)
350 # to NumPy int. this can be guaranteed by checking that the ifm and ofm datatypes are the same
351 assert ifm.dtype == ofm.dtype
352 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, ofm.dtype)
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200353 op.set_activation_lut(lut_tensor)
354 op.set_ifm_ofm_shapes()
wilisa0179a89042022-11-02 17:18:43 +0000355 DebugDatabase.add_optimised(op, op)
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200356 return op