blob: 73fbf6c7a1698b9666a02fd63e6877601217ddb6 [file] [log] [blame]
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +02001# Copyright (C) 2021 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.
16# Description:
17# Common functions and definitions used during the graph optimization.
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020018from typing import Tuple
19
Patrik Gustavssondf995102021-08-23 15:33:59 +020020import numpy as np
21
Patrik Gustavssonf436ada2021-09-14 14:56:48 +020022from . import lut
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020023from .data_type import DataType
24from .debug_database import DebugDatabase
Patrik Gustavssondf995102021-08-23 15:33:59 +020025from .errors import UnsupportedFeatureError
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020026from .errors import VelaError
27from .operation import Op
Patrik Gustavssondf995102021-08-23 15:33:59 +020028from .operation_util import create_avgpool_nop
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020029from .shape4d import Shape4D
Patrik Gustavssonf436ada2021-09-14 14:56:48 +020030from .tensor import create_const_tensor
31from .tensor import QuantizationParameters
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020032
Jonas Ohlsson81942e92021-08-20 09:33:28 +020033memory_only_ops = (
34 Op.Reshape,
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020035 Op.QuantizedReshape,
Jonas Ohlsson81942e92021-08-20 09:33:28 +020036 Op.Squeeze,
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020037 Op.ExpandDims,
Patrik Gustavssonef3ebdd2021-10-01 11:10:25 +020038 Op.Identity,
Jonas Ohlsson81942e92021-08-20 09:33:28 +020039)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020040
41
42def _avoid_nhcwb16_for_concat(tens):
43 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
44 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
45 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
46 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
47 return any(op.write_offset.depth % 16 != 0 for op in tens.ops if op.write_offset is not None)
48
49
50def _avoid_nhcwb16_for_split(tens):
51 # If read offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
52 for cons_op in tens.consumer_list:
53 if cons_op.ifm == tens:
54 read_offset = cons_op.read_offsets[0]
55 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == tens:
56 read_offset = cons_op.read_offsets[1]
57 else:
58 assert False
59 if read_offset is not None and (read_offset[-1] % 16) != 0:
60 return True
61 return False
62
63
64def _avoid_nhcwb16_for_shapes(tens):
65 # check all producers/consumers to see if any op shape is preventing NHCWB16
66 for cons_op in tens.consumer_list:
67 if cons_op.ifm == tens:
68 cons_op_shape = cons_op.ifm_shapes[0]
69 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == tens:
70 cons_op_shape = cons_op.ifm_shapes[1]
71 else:
72 assert False
73 if Shape4D(tens.shape) != cons_op_shape:
74 return True
75
76 for prod_op in tens.ops:
77 if Shape4D(tens.shape) != prod_op.ofm_shapes[0]:
78 return True
79
80 return False
81
82
83# Check if non linear format can be used
84def check_format_restrictions(tens, arch):
85 if len(tens.ops) < 1:
86 return
87 if tens.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const) or any(
88 cons is None for cons in tens.consumer_list
89 ):
90 return
91
92 # Check if any of the producers/consumers is run on CPU
93 if not all(cons.run_on_npu for cons in tens.consumer_list):
94 return
95 if not all(prod.run_on_npu for prod in tens.ops):
96 return
97
98 # "Concat" ofm exception:
99 if _avoid_nhcwb16_for_concat(tens):
100 return
101
102 # "Split" ifm exception:
103 if _avoid_nhcwb16_for_split(tens):
104 return
105
106 # Shapes checking: check all producers/consumers are NHCWB16 compatible with tens.shape
107 if _avoid_nhcwb16_for_shapes(tens):
108 return
109
110 for op in tens.consumer_list:
111 if op.type == Op.ReduceSum and tens.dtype == DataType.int32:
112 return
113 if op.type == Op.Reshape:
114 # Using NHCWB16 format for a no-op reshape is only an option if subsequent
115 # consumers do not also need to perform a reshape or if the OFM is going to
116 # be processed by CPU operations. No-op reshape consumers with empty lists
117 # (those that have no consumers, or null-consumers used as list terminators)
118 # must use normal NHWC output.
119
120 def incompatible_consumers(oper):
121 if oper and oper.type == Op.Reshape:
122 for consumer in oper.outputs[0].consumer_list:
123 yield from incompatible_consumers(consumer)
124 yield not oper or not oper.run_on_npu
125
126 if not any(incompatible_consumers(op)):
127
128 def get_rewrites(oper):
129 if oper and oper.type == Op.Reshape:
130 for consumer in oper.outputs[0].consumer_list:
131 yield from get_rewrites(consumer)
132 yield oper
133
134 # Detect no-op reshapes by comparing their full input and output tensor shapes.
135 inshape = op.ifm_shapes[0]
136 compatible_shape = [(inshape == oper.ofm_shapes[0]) for oper in get_rewrites(op)]
137 if not (compatible_shape and all(compatible_shape)):
138 return
139 else:
140 return
141
142 tens.needs_linear_format = False
143
144
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200145def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]:
146 """
147 Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding
148 that provides equivalent results.
149 """
150 total_padding = needed_total_padding(input_size, stride, filter_size)
151
152 # The bottom/right padding might need downward adjustment depending on stride/input size
153 total_minus_before = total_padding - pad_before
154 output_pad_after = pad_after
155 while output_pad_after > 0 and output_pad_after % stride != total_minus_before % stride:
156 output_pad_after -= 1
157 return pad_before, output_pad_after
158
159
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200160def needed_total_padding(input_size, stride, filter_size):
161 out_size = (input_size + stride - 1) // stride
162 needed_input = (out_size - 1) * stride + filter_size
163 total_padding = max(0, needed_input - input_size)
164 return total_padding
165
166
167# Set input/output tensor equivalence to the same id for memory operations
168def set_tensor_equivalence(op, arch, nng):
169 if op.type in memory_only_ops:
170 eid = op.outputs[0].equivalence_id
171 for inp in op.inputs:
172 inp.equivalence_id = eid
173 return op
174
175
176def set_ifm_ofm_op_shapes(op, arch, nng):
177 if op.run_on_npu and op.type.needs_shapes():
178 if op.ifm_shapes or op.ofm_shapes:
179 # Shapes already set
180 return op
181 op.set_ifm_ofm_shapes()
182 return op
183
184
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200185def bypass_memory_only_ops(op):
186 assert op.type in memory_only_ops
Patrik Gustavssondf995102021-08-23 15:33:59 +0200187 ofm = op.ofm
188 ifm = op.ifm
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200189
Patrik Gustavssondf995102021-08-23 15:33:59 +0200190 # Check if ifm/ofm are network ifm/ofm
191 ifm_is_sg_ifm = ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
192 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list)
193 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list)
194 # Check if ifm/ofm is produced respectively consumed by CPU
195 ifm_is_cpu_produced = any(ifm_prod is not None and not ifm_prod.run_on_npu for ifm_prod in op.ifm.ops)
196 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)
197
198 # This case should be handled prior to this function
199 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))
200
201 if ofm_is_sg_ofm or ofm_is_cpu_consumed:
202 # Bypassed by replacing ifm with ofm
203 ofm.ops = []
204 for prev_op in ifm.ops:
205 prev_op.outputs = [ofm]
206 ofm.ops.append(prev_op)
207
208 # All ifm consumers need to use ofm as input
209 for ifm_cons in ifm.consumer_list:
210 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
211 if cons_ifm == ifm:
212 ifm_cons.set_input_tensor(ofm, ifm_idx)
213 else:
214 # Bypassed by replacing ofm with ifm
215 for cons in ofm.consumer_list:
216 for ifm_idx, cons_ifm in enumerate(cons.inputs):
217 if cons_ifm == ofm:
218 cons.set_input_tensor(ifm, ifm_idx)
219
220
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200221def move_splitsliceread_to_consumer(op, cons_op):
222 assert op.type == Op.SplitSliceRead
223
224 if cons_op.ifm == op.ofm:
225 cons_op.read_offsets[0] = op.read_offsets[0]
226 cons_op.read_shapes[0] = op.read_shapes[0]
227 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[0])
228 cons_op.ifm_shapes[0] = op.ifm_shapes[0]
229 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == op.ofm:
230 cons_op.read_offsets[1] = op.read_offsets[0]
231 cons_op.read_shapes[1] = op.read_shapes[0]
232 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[1])
233 cons_op.ifm_shapes[1] = op.ifm_shapes[0]
234
235 if "skirt" in cons_op.attrs:
236 assert cons_op.attrs["explicit_padding"] == cons_op.attrs["skirt"]
237 cons_op.attrs["skirt"] = None
238 cons_op.attrs["force_padding"] = True
239 op.ofm.consumer_list.remove(cons_op)
240 op.ofm.ops = []
241 op.ifm.consumer_list.remove(op)
242
243
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200244def check_memory_only_removed(op, arch):
245 if op.run_on_npu and op.type in memory_only_ops:
246 # Memory only operators should have been removed
247 raise VelaError(f"Memory only {op.type} op {op} expected to have been removed, still remains")
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200248
249
250def record_optimised(op, arch):
251 if op.type != Op.Const:
252 DebugDatabase.add_optimised(op, op)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200253
254
255def insert_copy_op_after_tens(tens):
256 tens_cons_list_copy = tens.consumer_list.copy()
257
258 # Create a avg_pool nop op with ifm as input
259 copy_tens = tens.clone()
260 copy_op = create_avgpool_nop(tens.name + "_avgpool")
261 copy_op.add_input_tensor(tens)
262 copy_op.set_output_tensor(copy_tens)
263 copy_op.set_ifm_ofm_shapes()
264 copy_op.run_on_npu = True
265
266 # Set copy_ifm consumers
267 for tens_cons in tens_cons_list_copy:
268 if tens_cons is not None:
269 for ifm_idx, cons_inp in enumerate(tens_cons.inputs):
270 if cons_inp == tens:
271 tens_cons.set_input_tensor(copy_tens, ifm_idx)
272
273 DebugDatabase.add_optimised(tens.ops[0], copy_op)
274
275
276def fix_sg_input_output(op, arch, nng):
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200277 if not op.run_on_npu or op.type not in memory_only_ops:
Patrik Gustavssondf995102021-08-23 15:33:59 +0200278 return op
279
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200280 # For the memory only operators we want to remove, tensors are removed.
Patrik Gustavssondf995102021-08-23 15:33:59 +0200281 # But in order to to do this, they cannot be outputs of the sg,
282 # this need to be fixed prior to the removal.
283 # Solution is to add a avgpool NOP, to maintain the original tensor.
284 # This is also valid when reshape ifm/ofm is produced respectively
285 # consumed by CPU
286
287 # Check if operator ifm/ofm are sg ifm/ofm
288 ifm_is_sg_ifm = op.ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
289 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in op.ifm.consumer_list)
290 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in op.ofm.consumer_list)
291 # Check if ifm/ofm is produced respectively consumed by CPU
292 ifm_is_cpu_produced = any(ifm_prod is not None and not ifm_prod.run_on_npu for ifm_prod in op.ifm.ops)
293 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)
294
295 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):
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200296 # Both ifm and ofm need to persist, but only ifm need a copy, in order to remove the memory only operator.
Patrik Gustavssondf995102021-08-23 15:33:59 +0200297 insert_copy_op_after_tens(op.ifm)
298
299 return op
300
301
302def convert_depthwise_to_conv(op, arch, nng):
303 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
304 # the ofm depth equals the depth multipler.
305 # If those conditions are true, then we can perform a simple
306 # switch of the operator type (and weight order)
307
308 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
309 ifm_shape = op.ifm_shapes[0]
310 weight_tensor = op.inputs[1]
311 ofm_shape = op.ofm_shapes[0]
312 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
313 # Change op type to Conv2d
314 op.type = Op.Conv2DBias
315 del op.attrs["channel_multiplier"]
316 del op.attrs["depth_multiplier"]
317
318 weight_tensor.values = np.transpose(weight_tensor.values, (0, 1, 3, 2))
319 weight_tensor.set_all_shapes(list(weight_tensor.values.shape))
320 else:
321 raise UnsupportedFeatureError(
322 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
323 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
324 )
325 DebugDatabase.add_optimised(op, op)
326 return op
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200327
328
329def convert_to_lut(op, lut_values, lut_name):
330 # Rewrite the operation by Add with scalar 0 + LUT activation
331 ifm = op.inputs[0]
332 if ifm is None:
333 return op
334 assert ifm.dtype.size_in_bytes() == 1
335 op.type = Op.Add
336 op.name = op.name + "_lut_" + lut_name
337 # Mark as no-op to enable potential fusing optimizations
338 op.attrs["is_nop"] = True
339 # Create an input tensor containing scalar zero
340 quantization = QuantizationParameters(0.0, 255.0)
341 quantization.scale_f32 = ifm.quantization.scale_f32
342 quantization.zero_point = 0
343 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
344 op.add_input_tensor(tens)
345 op.ifm_shapes.append(Shape4D(tens.shape)) # TODO no shape?
346
347 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
348 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
349 # should be the same as the IFM
350 op.forced_output_quantization = ifm.quantization
351 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
352 op.set_activation_lut(lut_tensor)
353 op.set_ifm_ofm_shapes()
354 return op