blob: 59376a85e40165ed94ecfc29368424c9537bd877 [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Packs a subgraph with Neural Network Operations into Passes. Each Pass has one or more Operations.
Diego Russoea6111a2020-04-14 18:41:58 +010018import collections
Diego Russoe8a10452020-04-21 17:39:10 +010019import enum
Diego Russoea6111a2020-04-14 18:41:58 +010020
Tim Halle6ccd872020-11-09 16:46:37 +000021from .debug_database import DebugDatabase
Diego Russoe8a10452020-04-21 17:39:10 +010022from .nn_graph import Pass
23from .nn_graph import PassPlacement
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +010024from .operation import create_avgpool_nop
Diego Russoe8a10452020-04-21 17:39:10 +010025from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020026from .operation import Op
Diego Russoea6111a2020-04-14 18:41:58 +010027from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010028
29
30class PassFlags(enum.Flag):
31 Empty = 0
32 Pre = 1
33 Main = 2
34 Post = 4
35 Mac = 8
36 Dma = 32
37 ElementWise = 256
38 Npu = 512
39 Cpu = 1024
40 StartupInit = 2048
41 MemoryOnly = 4096
42 PostFusingLimited = 8192
43
44
Louis Verhaardaee5d752020-09-30 09:01:52 +020045npu_pre_ops = set((Op.SplitSliceRead,))
Tim Hall79d07d22020-04-27 18:20:16 +010046
47mac_main_ops = set(
48 (
49 # convolutions
Louis Verhaardaee5d752020-09-30 09:01:52 +020050 Op.Conv2DBias,
51 Op.Conv2D,
52 Op.QuantizedConv2D,
53 Op.Conv2DBackpropInputSwitchedBias,
Tim Hall79d07d22020-04-27 18:20:16 +010054 # depth-wise convolutions
Louis Verhaardaee5d752020-09-30 09:01:52 +020055 Op.DepthwiseConv2DBias,
Tim Hall79d07d22020-04-27 18:20:16 +010056 # FC layers
Louis Verhaardaee5d752020-09-30 09:01:52 +020057 Op.QuantizedMatMul,
58 Op.MatMul,
59 Op.FullyConnected,
Tim Hall79d07d22020-04-27 18:20:16 +010060 # RNN/LSTM/GRU
Louis Verhaardaee5d752020-09-30 09:01:52 +020061 Op.BlockLSTM,
Tim Hall79d07d22020-04-27 18:20:16 +010062 # pooling
Louis Verhaardaee5d752020-09-30 09:01:52 +020063 Op.QuantizedMaxPool,
64 Op.QuantizedAvgPool,
65 Op.AvgPool,
66 Op.MaxPool,
67 Op.ReduceSum,
Dwight Lidman3ec04ac2020-04-30 11:54:48 +020068 # deconvolution
Louis Verhaardaee5d752020-09-30 09:01:52 +020069 Op.ResizeBilinear,
Tim Hall79d07d22020-04-27 18:20:16 +010070 )
71)
72
Louis Verhaardaee5d752020-09-30 09:01:52 +020073binary_elem_wise_main_ops = Op.op_set(Op.is_binary_elementwise_op)
Tim Hall79d07d22020-04-27 18:20:16 +010074
Louis Verhaardaee5d752020-09-30 09:01:52 +020075unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op) # Unary element-wise operations
Tim Hall79d07d22020-04-27 18:20:16 +010076
77elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
78
Louis Verhaardaee5d752020-09-30 09:01:52 +020079activation_ops = Op.op_set(Op.is_relu_op)
80npu_post_ops = activation_ops
Tim Hall79d07d22020-04-27 18:20:16 +010081
82npu_post_fuse_limited_ops = set(
83 # Set of post operators that should not be fused with main/elementwise ops
Louis Verhaardaee5d752020-09-30 09:01:52 +020084 (Op.ConcatSliceWrite, Op.Sigmoid, Op.Tanh, Op.Quantize)
Tim Hall79d07d22020-04-27 18:20:16 +010085)
86
Louis Verhaardaee5d752020-09-30 09:01:52 +020087elem_wise_ops = elem_wise_main_ops | activation_ops | set((Op.Sigmoid, Op.Tanh))
Tim Hall79d07d22020-04-27 18:20:16 +010088
89
Louis Verhaardaee5d752020-09-30 09:01:52 +020090quantization_ops = set((Op.Dequantize, Op.Max, Op.Min))
91cpu_ops = set((Op.Softmax, Op.LRN, Op.Shape, Op.Pad, Op.AddN)) | quantization_ops
Tim Hall79d07d22020-04-27 18:20:16 +010092
Louis Verhaardaee5d752020-09-30 09:01:52 +020093npu_dma_ops = set((Op.DMA,))
patrik.gustavsson10683622020-10-14 10:57:46 +000094startup_init_ops = set((Op.Const, Op.Placeholder, Op.SubgraphInput))
Louis Verhaardaee5d752020-09-30 09:01:52 +020095memory_only_ops = set((Op.Squeeze, Op.Reshape, Op.QuantizedReshape, Op.ExpandDims,))
Tim Hall79d07d22020-04-27 18:20:16 +010096
97
98test_sequence = [
99 (
100 # ops_set
101 npu_post_ops,
102 # incompatible_pack_flags
103 PassFlags.Cpu | PassFlags.MemoryOnly | PassFlags.Pre | PassFlags.Main,
104 # flags_to_set
105 PassFlags.Npu | PassFlags.Post,
106 # flags_to_clear
107 PassFlags.Empty,
108 ),
109 (
110 # ops_set
111 npu_post_fuse_limited_ops,
112 # incompatible_pack_flags
113 PassFlags.Cpu | PassFlags.MemoryOnly | PassFlags.Pre | PassFlags.Main,
114 # flags_to_set
115 PassFlags.Npu | PassFlags.PostFusingLimited,
116 # flags_to_clear
117 PassFlags.Empty,
118 ),
119 (
120 # ops_set
121 mac_main_ops,
122 # incompatible_pack_flags
123 PassFlags.Cpu
124 | PassFlags.MemoryOnly
125 | PassFlags.ElementWise
126 | PassFlags.Pre
127 | PassFlags.Main
128 | PassFlags.PostFusingLimited,
129 # flags_to_set
130 PassFlags.Npu | PassFlags.Mac | PassFlags.Main,
131 # flags_to_clear
132 PassFlags.Empty,
133 ),
134 (
135 # ops_set
136 elem_wise_main_ops,
137 # incompatible_pack_flags
138 PassFlags.Cpu
139 | PassFlags.MemoryOnly
140 | PassFlags.Mac
141 | PassFlags.Pre
142 | PassFlags.Main
143 | PassFlags.PostFusingLimited,
144 # flags_to_set
145 PassFlags.Npu | PassFlags.ElementWise | PassFlags.Main,
146 # flags_to_clear
147 PassFlags.Empty,
148 ),
149 (
150 # ops_set
151 npu_pre_ops,
152 # incompatible_pack_flags
153 PassFlags.Cpu | PassFlags.MemoryOnly,
154 # flags_to_set
155 PassFlags.Npu | PassFlags.Mac | PassFlags.Pre | PassFlags.ElementWise,
156 # flags_to_clear
157 PassFlags.Empty,
158 ),
159 (
160 # ops_set
161 npu_dma_ops,
162 # incompatible_pack_flags
163 PassFlags.Cpu | PassFlags.MemoryOnly,
164 # flags_to_set
165 PassFlags.Npu | PassFlags.Dma,
166 # flags_to_clear
Diego Russoea6111a2020-04-14 18:41:58 +0100167 PassFlags.Empty,
Tim Hall79d07d22020-04-27 18:20:16 +0100168 ),
169 (
170 # ops_set
171 startup_init_ops,
172 # incompatible_pack_flags
173 PassFlags.Npu | PassFlags.Cpu | PassFlags.MemoryOnly,
174 # flags_to_set
175 PassFlags.StartupInit | PassFlags.Main,
176 # flags_to_clear
177 PassFlags.Empty,
178 ),
179 (
180 # ops_set
181 memory_only_ops,
182 # incompatible_pack_flags
183 PassFlags.Npu | PassFlags.Cpu,
184 # flags_to_set
185 PassFlags.MemoryOnly | PassFlags.Main,
186 # flags_to_clear
Diego Russoea6111a2020-04-14 18:41:58 +0100187 PassFlags.Empty,
Tim Hall79d07d22020-04-27 18:20:16 +0100188 ),
189 (
190 # ops_set
191 cpu_ops,
192 # incompatible_pack_flags
193 PassFlags.Npu | PassFlags.MemoryOnly | PassFlags.Main,
194 # flags_to_set
195 PassFlags.Cpu | PassFlags.Main,
196 # flags_to_clear
Diego Russoea6111a2020-04-14 18:41:58 +0100197 PassFlags.Empty,
Tim Hall79d07d22020-04-27 18:20:16 +0100198 ),
Diego Russoea6111a2020-04-14 18:41:58 +0100199 ( # This last one is a fallback for unrecognised operations
Tim Hall79d07d22020-04-27 18:20:16 +0100200 # ops_set
201 None,
202 # incompatible_pack_flags
203 PassFlags.Npu | PassFlags.MemoryOnly | PassFlags.Main,
204 # flags_to_set
205 PassFlags.Cpu | PassFlags.Main,
206 # flags_to_clear
Diego Russoea6111a2020-04-14 18:41:58 +0100207 PassFlags.Empty,
Tim Hall79d07d22020-04-27 18:20:16 +0100208 ),
209]
210
211# Some sanity checking
212for (operation_set, incompatible_pack_flags, flags_to_set, flags_to_clear) in test_sequence:
213 assert not flags_to_clear & flags_to_set
214
Tim Hall79d07d22020-04-27 18:20:16 +0100215
216def pack_into_passes(nng, arch, verbose_packing=False):
217 def visit_op(op, ignored):
218 visit_op_refcount[op] += 1
219
220 if visit_op_refcount[op] == 1: # First-time visit, go and fix up unused output tensors
221 for tens in op.outputs:
222 if len(tens.consumers()) == 0:
223 visit_op_refcount[op] += 1
224
225 assert visit_op_refcount[op] <= len(op.outputs)
226 if visit_op_refcount[op] == len(op.outputs):
227
228 if op.type in startup_init_ops:
229 startup_list.append(op)
230 else:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200231 ofm_tensor = op.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100232 if ofm_tensor is None:
233 ofm_tensor = op.outputs[0]
234 build_pass((op,), ofm_tensor)
235
236 def build_pass(start_ops_to_process, ofm_tensor=None):
237 reverse_ops_list = []
238 curr_flags = PassFlags.Empty
239 npu_block_type = NpuBlockType.Default
240
241 reverse_intermediates = []
242 input_set = set()
243 ifm_tensor = None
244 primary_op = None
245
246 to_process = collections.deque()
247 for start_op in start_ops_to_process:
248 to_process.append((start_op, None))
249
250 while to_process:
251 curr_op, tens = to_process.popleft()
252
253 if curr_op in reverse_ops_list:
254 continue
255
256 for operation_set, incompatible_pack_flags, flags_to_set, flags_to_clear in test_sequence:
257 if operation_set is None or curr_op.type in operation_set:
258 if not (curr_flags & incompatible_pack_flags):
259 if flags_to_set & PassFlags.Npu:
260 if not curr_op.run_on_npu:
261 continue
262
263 reverse_ops_list.append(curr_op)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200264 new_block_type = curr_op.type.npu_block_type
Tim Hall79d07d22020-04-27 18:20:16 +0100265 if new_block_type != NpuBlockType.Default:
266 assert npu_block_type == NpuBlockType.Default
267 npu_block_type = new_block_type # Only one major block type per pass
268 assert primary_op is None
269 primary_op = curr_op
270
271 curr_flags &= ~flags_to_clear
272 curr_flags |= flags_to_set
273
274 if flags_to_set & PassFlags.Npu:
275 if flags_to_set & (
276 PassFlags.Mac | PassFlags.ElementWise | PassFlags.Post | PassFlags.PostFusingLimited
277 ):
278 assert len(curr_op.inputs) >= 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200279 ifm_tensor = curr_op.ifm
Louis Verhaard04f8c002020-10-09 11:40:21 +0200280 assert ifm_tensor is not None, "IFM missing in {}".format(curr_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100281 assert ifm_tensor.purpose == TensorPurpose.FeatureMap
282
283 if flags_to_set & PassFlags.Dma:
284 # DMAs are special - Output buffers need to be preserved as intermediates,
285 # if the pass consumes the results
286 if tens is not None:
287 reverse_intermediates.append(tens)
288
289 if operation_set is None:
290 print("Warning:", curr_op.type, "operation is unknown or unsupported, placing on CPU")
291
Charles Xu600351a2020-05-18 08:54:47 +0200292 for inp in reversed(curr_op.inputs):
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200293 if inp is None:
294 continue
Tim Hall79d07d22020-04-27 18:20:16 +0100295 can_pack = True
296 if len(inp.ops) == 1:
297 next_op = inp.ops[0]
298 for outp in next_op.outputs:
299 consumers = outp.consumers()
300 if len(consumers) > 1 or (len(consumers) == 1 and consumers[0] != curr_op):
301 can_pack = False
302 break
303 else:
304 can_pack = False
305
306 if can_pack:
307 to_process.append((next_op, inp))
308 else:
309 assert inp is not None
310 input_set.add(inp)
311
312 break
313
314 else:
315 # This operation is not compatible with already packed operations, just register the tensor as an input
316 assert tens is not None
317 input_set.add(tens)
318
319 if curr_flags & PassFlags.Npu and not curr_flags & (PassFlags.ElementWise | PassFlags.Mac):
320 # Make the choice that if we don't have a mac operation, the ambidextrous operations go on the
321 # element wise unit
322 curr_flags |= PassFlags.ElementWise
323
324 is_element_wise = True
325 for op in reverse_ops_list:
Diego Russoea6111a2020-04-14 18:41:58 +0100326 if op.type not in elem_wise_ops and op.type not in npu_dma_ops:
Tim Hall79d07d22020-04-27 18:20:16 +0100327 is_element_wise = False
328 break
329
330 placement = PassPlacement.Unknown
331 if curr_flags & PassFlags.Npu:
332 assert placement == PassPlacement.Unknown
333 placement = PassPlacement.Npu
334 if curr_flags & PassFlags.Cpu:
335 assert placement == PassPlacement.Unknown
336 placement = PassPlacement.Cpu
337 if curr_flags & PassFlags.MemoryOnly:
338 assert placement == PassPlacement.Unknown
339 placement = PassPlacement.MemoryOnly
340 if curr_flags & PassFlags.StartupInit:
341 assert placement == PassPlacement.Unknown
342 placement = PassPlacement.StartupInit
343 assert placement != PassPlacement.Unknown
344
345 ops_list = list(reversed(reverse_ops_list))
346 intermediates = list(reversed(reverse_intermediates))
347
Diego Russoea6111a2020-04-14 18:41:58 +0100348 if primary_op is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100349 primary_op = create_primary_op(ops_list)
Diego Russoea6111a2020-04-14 18:41:58 +0100350 if primary_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100351 visit_tensor_refcount[primary_op.inputs[0]] += 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200352 npu_block_type = primary_op.type.npu_block_type
Tim Hall79d07d22020-04-27 18:20:16 +0100353 for input_tens in primary_op.inputs:
354 if input_tens not in input_set:
355 input_set.add(input_tens)
356
357 ordered_input_list = []
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200358 # Keep LUT-s in a separate list and add as inputs at the end
359 # to avoid that they would accidentally be assigned as ifm or ifm2
360 lut_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100361 input_refcounts = collections.defaultdict(int)
Diqing Zhong2abd3dd2020-08-25 10:40:36 +0200362 input_ops_list = ops_list.copy()
363
364 # Check primary_op first
365 if primary_op is not None:
366 for inp in primary_op.inputs:
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200367 if inp is None:
368 continue
Louis Verhaardaee5d752020-09-30 09:01:52 +0200369 if len(inp.ops) == 1 and inp.ops[0].type == Op.DMA and inp.purpose == TensorPurpose.FeatureMap:
Diqing Zhong2abd3dd2020-08-25 10:40:36 +0200370 src_op = inp.ops[0]
371 if src_op in input_ops_list:
372 inp = src_op.inputs[0]
373 input_ops_list.remove(src_op)
374 add_input_list(inp, input_set, input_refcounts, lut_list, ordered_input_list)
375 input_ops_list.remove(primary_op)
376
377 # Check rest of the list
378 for op in input_ops_list:
Tim Hall79d07d22020-04-27 18:20:16 +0100379 for inp in op.inputs:
Diqing Zhong2abd3dd2020-08-25 10:40:36 +0200380 add_input_list(inp, input_set, input_refcounts, lut_list, ordered_input_list)
Tim Hall79d07d22020-04-27 18:20:16 +0100381
382 name = ops_list[0].name
Louis Verhaardaee5d752020-09-30 09:01:52 +0200383 non_dma_ops = [op for op in ops_list if op.type != Op.DMA]
Tim Hall79d07d22020-04-27 18:20:16 +0100384 if non_dma_ops:
385 name = non_dma_ops[0].name
386 ps = Pass(name, placement, is_element_wise, npu_block_type)
387 ps.ops = ops_list
388 ps.primary_op = primary_op
389 ps.inputs = ordered_input_list
390 ps.intermediates = intermediates
391 ps.outputs = list(ops_list[-1].outputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100392
393 # ElementWise operation, 2 IFMs
394 if ps.primary_op and ps.primary_op.type in binary_elem_wise_main_ops:
Tim Hall79d07d22020-04-27 18:20:16 +0100395 ps.ifm_tensor = ps.inputs[0]
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200396 ps.ifm2_tensor = ps.inputs[-1]
Tim Hall79d07d22020-04-27 18:20:16 +0100397
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200398 if len(ps.inputs) > 2:
399 ps.ifm_tensor = ps.inputs[-2]
Tim Hall79d07d22020-04-27 18:20:16 +0100400 else:
401 ps.ifm_tensor = ifm_tensor
402 ps.ifm2_tensor = None
403
404 ps.ofm_tensor = ofm_tensor
405 assert ps.placement != PassPlacement.Npu or ps.ofm_tensor is not None
406 ps.weight_tensor = ps.get_primary_op_ifm_weights()[1]
407 ps.scale_tensor = ps.get_primary_op_ifm_weights_biases_ofm()[2]
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200408 ps.lut_tensor = ps.get_primary_op_lut()
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200409 ps.inputs.extend(lut_list)
Tim Hall79d07d22020-04-27 18:20:16 +0100410
411 for op in ps.ops:
412 op.scheduled_pass = ps
413
414 reverse_pass_list.append(ps)
415
416 for inp, refcount in input_refcounts.items():
417 for _ in range(refcount):
418 visit_tensor(inp)
419
420 return ps
421
422 def visit_tensor(tens):
423 visit_tensor_refcount[tens] += 1
424 assert visit_tensor_refcount[tens] <= len(tens.consumers())
425 if visit_tensor_refcount[tens] == len(tens.consumers()):
426 for op in reversed(tens.ops):
427 visit_op(op, tens)
428
Jacob Bohlinfb858732020-08-17 09:42:35 +0200429 def create_primary_op(op_list):
430 if any(op.type in (npu_pre_ops | npu_post_ops | npu_post_fuse_limited_ops) and op.run_on_npu for op in op_list):
Tim Hall79d07d22020-04-27 18:20:16 +0100431 # Configure a 1x1 AvgPool and attach the op onto it
Jacob Bohlinfb858732020-08-17 09:42:35 +0200432 op = op_list[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100433 inp = op.inputs[0]
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100434 avgpool_op = create_avgpool_nop(op.name + "_avgpool")
435 avgpool_op.add_input_tensor(inp)
Tim Hall79d07d22020-04-27 18:20:16 +0100436 avgpool_out = inp.clone("_avgpooled")
437 avgpool_out.consumer_list.append(op)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100438 avgpool_op.set_output_tensor(avgpool_out)
Tim Hall79d07d22020-04-27 18:20:16 +0100439
440 op.inputs[0] = avgpool_out
Jacob Bohlinfb858732020-08-17 09:42:35 +0200441 op_list.insert(0, avgpool_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100442
Tim Halle6ccd872020-11-09 16:46:37 +0000443 DebugDatabase.add_optimised(op, avgpool_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100444 return avgpool_op
445
446 return None
447
Diqing Zhong2abd3dd2020-08-25 10:40:36 +0200448 def add_input_list(inp_to_add, inp_set, inp_refcnts, lut_list, ordered_inp_list):
449 if inp_to_add in inp_set:
450 if inp_refcnts[inp_to_add] == 0:
451 if inp_to_add.purpose == TensorPurpose.LUT:
452 lut_list.append(inp_to_add)
453 else:
454 ordered_inp_list.append(inp_to_add)
455 inp_refcnts[inp_to_add] += 1
456
Tim Hall79d07d22020-04-27 18:20:16 +0100457 for sg in nng.subgraphs:
458 reverse_pass_list = []
459 visit_op_refcount = collections.defaultdict(int)
460 visit_tensor_refcount = collections.defaultdict(int)
461
462 startup_list = []
463
464 for tens in sg.output_tensors:
465 visit_tensor(tens)
466
467 if startup_list:
468 startup_ps = build_pass(startup_list)
469 startup_ps.outputs = [op.outputs[0] for op in startup_list] # Need to fixup the outputs
470 startup_ps.name = "startup_weight_initialisation"
471
472 sg.passes = list(reversed(reverse_pass_list))
473 sg.build_pass_links()
474
475 if verbose_packing:
476 nng.print_passes()
477
478 return nng