blob: 677a385ac6b70d2a90c3b8cf992de49b17610c97 [file] [log] [blame]
erik.andersson@arm.comad45f792021-02-03 10:20:16 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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# Neural network graph classes and enums.
18# Pass - A packed pass containing one or more Operations.
19# CascadedPass - A scheduled pass containing one or more Passes, as well as a scheduling strategy and block
20# configurations.
21# Subgraph - Holds a neural network subgraph, pointing at Tensors, Operations, Passes, and CascadedPasses.
22# Graph - A full neural network graph with one or more Subgraphs.
Tim Hall79d07d22020-04-27 18:20:16 +010023import enum
patrik.gustavssoneeb85152020-12-21 17:10:40 +000024from typing import List
Tim Hall79d07d22020-04-27 18:20:16 +010025
Louis Verhaardaee5d752020-09-30 09:01:52 +020026from .operation import Op
patrik.gustavssoneeb85152020-12-21 17:10:40 +000027from .shape4d import Shape4D
Louis Verhaardaee5d752020-09-30 09:01:52 +020028
Tim Hall79d07d22020-04-27 18:20:16 +010029
30class PassPlacement(enum.Enum):
31 Unknown = 0
32 Cpu = 1
33 Npu = 2
34 MemoryOnly = 3
35 StartupInit = 4
36
37
38class TensorAllocator(enum.Enum):
39 LinearAlloc = 1
40 Greedy = 2
Louis Verhaardd7002522021-01-20 17:23:54 +010041 HillClimb = 3
Tim Hall79d07d22020-04-27 18:20:16 +010042
43 def __str__(self):
44 return self.name
45
46
47class Pass:
48 def __init__(self, name, placement, is_element_wise, npu_block_type):
49 self.inputs = []
50 self.intermediates = []
51 self.outputs = []
52 self.ops = []
53 self.primary_op = None
54 self.ifm_tensor = None
55 self.ifm2_tensor = None
56 self.ofm_tensor = None
57 self.weight_tensor = None
58 self.scale_tensor = None
Fredrik Svedberga0c36242020-06-03 15:43:31 +020059 self.lut_tensor = None
Tim Hall79d07d22020-04-27 18:20:16 +010060 self.name = name
61 self.cascade = None
62 self.placement = placement
patrik.gustavssoneeb85152020-12-21 17:10:40 +000063 self.ifm_shapes: List[Shape4D] = []
64 self.ofm_shapes: List[Shape4D] = []
Tim Hall79d07d22020-04-27 18:20:16 +010065
66 # TODO: rename is_element_wise because it is not the same as an ElementWise operator. It is used by the tensor
67 # allocation and requires that the OFM and IFM has the exact same address. Essentially complete overlap.
68 self.is_element_wise = is_element_wise
69 self.npu_block_type = npu_block_type
70 self.block_config = None # will be filled in by scheduler
71 self.shared_buffer = None # will be filled in by scheduler
72
73 self.predecessors = []
74 self.successors = []
75
76 def __str__(self):
77 return "<nng.Pass '%s', %s, ops=%s>" % (self.name, self.placement, [op.type for op in self.ops])
78
79 __repr__ = __str__
80
81 def get_primary_op_ifm_weights(self):
82 if not self.primary_op:
83 return None, None
84 return self.primary_op.get_ifm_ifm2_weights_ofm()[::2]
85
86 def get_primary_op_ifm_ifm2_weights_ofm(self):
87 if not self.primary_op:
88 return None, None, None, None
89 return self.primary_op.get_ifm_ifm2_weights_ofm()
90
91 def get_primary_op_ifm_weights_biases_ofm(self):
92 if not self.primary_op:
93 return None, None, None, None
94 return self.primary_op.get_ifm_weights_biases_ofm()
95
Fredrik Svedberga0c36242020-06-03 15:43:31 +020096 def get_primary_op_lut(self):
97 if not self.primary_op:
98 return None
99 return self.primary_op.activation_lut
100
Tim Hall79d07d22020-04-27 18:20:16 +0100101
102class SchedulingStrategy(enum.Enum):
103 Unknown = -1
104 IfmStream = 0
105 WeightStream = 1
106
107
108class SchedulerRewrite(enum.Enum):
109 Nop = 0
110 ChangeTensorSubPurpose = 1
111
112
113class CascadedPass:
114 def __init__(self, name, strat, inputs, intermediates, outputs, passes, placement, is_element_wise):
115 self.name = name
116 self.strategy = strat
117 self.inputs = inputs
118 self.intermediates = intermediates
119 self.outputs = outputs
120 self.passes = passes
121 self.placement = placement
122 self.is_element_wise = is_element_wise
123
124 self.predecessors = []
125 self.successors = []
126
127 def __str__(self):
128 return "<nng.CascadedPass strategy=%s x %s '%s', passes=%s, block_configs=%s>" % (
129 self.strategy,
130 len(self.passes),
131 self.name,
132 [ps.name for ps in self.passes],
133 [ps.block_config for ps in self.passes],
134 )
135
136 __repr__ = __str__
137
138
139class Subgraph:
140 def __init__(self, name="<unnamed>", placement=PassPlacement.Cpu):
141 self.output_tensors = []
142 self.input_tensors = []
143 self.original_inputs = [] # Preserve the original input order
144 self.passes = []
145 self.cascaded_passes = []
146 self.name = name
147 self.high_level_command_stream = []
148 self.placement = placement
149 self.command_stream_tensor = None
150 self.flash_tensor = None
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200151 # Scratch information locally used in the scheduler
152 self.scheduling_info = {}
erik.andersson@arm.comad45f792021-02-03 10:20:16 +0100153 self.generated_stream_id = None
Tim Hall79d07d22020-04-27 18:20:16 +0100154
155 self.memory_used = {}
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200156 self.memory_used_per_type = {}
erik.andersson@arm.com3438c922021-03-24 10:32:09 +0100157 self.min_mem_usage = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100158
159 def __str__(self):
160 return "<nng.Subgraph '%s', n_passes=%d, n_cascaded_passes=%d>" % (
161 self.name,
162 len(self.passes),
163 len(self.cascaded_passes),
164 )
165
166 __repr__ = __str__
167
168 def update_consumers(self):
169 visit_op_set = set()
170 visit_tensor_set = set()
171 self.input_tensors = []
172
173 print_visit = False
174
175 def visit_op(op):
176 if op in visit_op_set:
177 return
178
179 visit_op_set.add(op)
180 for inp in op.inputs:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200181 if not inp:
182 continue
Tim Hall79d07d22020-04-27 18:20:16 +0100183 if print_visit:
184 print(inp, "adding consumer", op)
185 visit_tensor(inp)
186 inp.consumer_list.append(op)
187
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000188 if op.type in (Op.Placeholder, Op.SubgraphInput):
Tim Hall79d07d22020-04-27 18:20:16 +0100189 assert len(op.outputs) == 1
190 self.input_tensors.append(op.outputs[0])
191
192 for out in op.outputs:
193 if out not in visit_tensor_set:
194 out.consumer_list = [] # reset unvisited output, just in case
195
196 def visit_tensor(tens):
197 if tens in visit_tensor_set:
198 return
199 visit_tensor_set.add(tens)
200 tens.consumer_list = []
201 for op in tens.ops:
202 visit_op(op)
203
204 for ps in self.passes:
205 for tens in ps.outputs + ps.inputs:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200206 if not tens:
207 continue
Tim Hall79d07d22020-04-27 18:20:16 +0100208 tens.consumer_list = [] # reset unvisited tensors to start with
209
210 for tens in self.output_tensors:
211 visit_tensor(tens)
212 tens.consumer_list.append(None) # special op to indicate that the graph consumes the result
213
214 print_visit = True
215 for ps in self.passes:
216 for op in ps.ops:
217 visit_op(op)
218 for tens in ps.inputs:
219 visit_tensor(tens)
220
221 def build_pass_links(self):
222 for idx, ps in enumerate(self.passes):
223 ps.time = 2 * idx
224 ps.predecessors = []
225 ps.successors = []
226
227 for ps in self.passes:
228 for tens in ps.inputs:
229 for op in tens.ops:
230 pred_pass = op.scheduled_pass
231 assert pred_pass.time < ps.time
232 if ps not in pred_pass.successors:
233 pred_pass.successors.append(ps)
234
235 if pred_pass not in ps.predecessors:
236 ps.predecessors.append(pred_pass)
237
238 assert tens in pred_pass.outputs
239
240 def build_pass_dag_predecessors(self):
241 for ps in self.passes:
242 ps.dag_predecessors = []
243
244 class State(enum.Enum):
245 NotVisited = 0
246 BeingVisited = 1
247 Visited = 2
248
249 pass_visit_dict = {}
250
251 def visit_pass(ps):
252 state = pass_visit_dict.get(ps, State.NotVisited)
253 if state == State.Visited:
254 return True
255 elif state == State.BeingVisited:
256 return False # this is a loop, need to remove this link
257 elif state == State.NotVisited:
258 pass_visit_dict[ps] = State.BeingVisited
259
260 ps.dag_predecessors = []
261 for pred in ps.predecessors:
262 if visit_pass(pred):
263 ps.dag_predecessors.append(pred)
264
265 pass_visit_dict[ps] = State.Visited
266 return True
267
268 for ps in self.passes:
269 if not ps.successors:
270 visit_pass(ps)
271
272 def build_cascaded_pass_links(self):
273 for cps in self.cascaded_passes:
274 cps.predecessors = []
275 cps.successors = []
276
277 for cps in self.cascaded_passes:
278 for tens in cps.inputs:
279 for op in tens.ops:
280 pred_cpass = op.scheduled_pass.cascade
281 if cps not in pred_cpass.successors:
282 pred_cpass.successors.append(cps)
283
284 if pred_cpass not in cps.predecessors:
285 cps.predecessors.append(pred_cpass)
286
287 assert tens in pred_cpass.outputs
288
289 def refresh_after_modification(self):
290 self.update_consumers()
291
292 def prune_startup_init_pass(self):
293 assert len(self.passes) >= 1
294 ps = self.passes[0]
295 assert ps.placement == PassPlacement.StartupInit
296
297 ps.outputs = [out_tens for out_tens in ps.outputs if len(out_tens.consumers()) > 0]
298 ps.ops = [op for op in ps.ops if op.outputs[0] in ps.outputs]
299
300 def get_all_ops(self):
301 all_ops = []
302 visit_op_set = set()
303 visit_tensor_set = set()
304
305 def visit_op(op):
306 if op in visit_op_set:
307 return
308 visit_op_set.add(op)
309 for inp in op.inputs:
310 visit_tensor(inp)
311
312 all_ops.append(op)
313
314 def visit_tensor(tens):
Andreas Nevalainene1cc3de2020-09-08 15:31:02 +0200315 if tens is None or tens in visit_tensor_set:
Tim Hall79d07d22020-04-27 18:20:16 +0100316 return
317 visit_tensor_set.add(tens)
318 for op in tens.ops:
319 visit_op(op)
320
321 for tens in self.output_tensors:
322 visit_tensor(tens)
323
324 return all_ops
325
326 def print_operators(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100327 print("print_operators()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100328 all_ops = self.get_all_ops()
329 unique_ops = []
Tim Hall79d07d22020-04-27 18:20:16 +0100330 for op in all_ops:
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000331 if op.type in (Op.Const, Op.Identity, Op.Placeholder):
Tim Hall79d07d22020-04-27 18:20:16 +0100332 continue
333
Louis Verhaardaee5d752020-09-30 09:01:52 +0200334 attrs = op.attrs.copy()
335 if op.type in (Op.Conv2D, Op.Conv2DBias, Op.DepthwiseConv2DBias):
Tim Hall79d07d22020-04-27 18:20:16 +0100336 kshape = op.inputs[1].shape
337 attrs["kshape"] = [kshape[0], kshape[1]]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200338 attrs["type"] = op.type.name
Tim Hall79d07d22020-04-27 18:20:16 +0100339 attrs.pop("use_cudnn_on_gpu", None)
Fredrik Svedberg16343052021-04-16 14:36:22 +0200340 custom_options = attrs.pop("custom_options", None)
Tim Hall79d07d22020-04-27 18:20:16 +0100341 if attrs not in unique_ops:
342 unique_ops.append(attrs)
343 # print attributes in human readable format
344 a = attrs.copy()
Fredrik Svedberg16343052021-04-16 14:36:22 +0200345 if custom_options is not None:
346 a["custom_options"] = custom_options
Tim Hall79d07d22020-04-27 18:20:16 +0100347 s = a.pop("type")
348 data_format = a.pop("data_format", None)
349 if data_format and data_format != b"NHWC":
350 s += " " + str(data_format)
351 t = a.pop("T", None)
352 if t:
353 s += " " + str(t)[9:-2]
354 srct = a.pop("SrcT", None)
355 if srct:
356 s += " " + str(srct)[9:-2]
357 dstt = a.pop("DstT", None)
358 if dstt:
359 s += "->" + str(dstt)[9:-2]
360 print(s + " " + str(a))
361
362 def print_graph(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100363 print("print_graph()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100364 all_ops = self.get_all_ops()
365 for idx, op in enumerate(all_ops):
366 print(idx, op.type, op.name)
367
368 def print_graph_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100369 print("print_graph_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100370 all_ops = self.get_all_ops()
371 for idx, op in enumerate(all_ops):
372 print(idx, op.type, op.name)
373 for idx, tens in enumerate(op.inputs):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200374 print(
375 " Input %02d %20s %20s %20s %s"
376 % (idx, tens.purpose.name, tens.mem_area.name, tens.mem_type.name, tens)
377 )
Tim Hall79d07d22020-04-27 18:20:16 +0100378 for idx, tens in enumerate(op.outputs):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200379 print(
380 " Output %02d %20s %20s %20s %s"
381 % (idx, tens.purpose.name, tens.mem_area.name, tens.mem_type.name, tens)
382 )
Tim Hall79d07d22020-04-27 18:20:16 +0100383 print()
384
385 def print_graph_with_tensor_quantization(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100386 print("print_graph_with_tensor_quantization()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100387 all_ops = self.get_all_ops()
388 for idx, op in enumerate(all_ops):
389 print(idx, op.type, op.name)
390 for idx, tens in enumerate(op.inputs):
391 q = tens.quantization
392 if q is None:
393 print(" Input %02d %10s NO QUANTIZATION INFO %s" % (idx, tens.dtype, tens.name))
394 else:
395 print(
396 " Input %02d %10s min=%s max=%s scale=%s zero_point=%s %s"
397 % (idx, tens.dtype, q.min, q.max, q.scale_f32, q.zero_point, tens.name)
398 )
399 for idx, tens in enumerate(op.outputs):
400 q = tens.quantization
401 if q is None:
402 print(" Output %02d %10s NO QUANTIZATION INFO %s" % (idx, tens.dtype, tens.name))
403 else:
404 print(
405 " Output %02d %10s min=%s max=%s scale=%s zero_point=%s %s"
406 % (idx, tens.dtype, q.min, q.max, q.scale_f32, q.zero_point, tens.name)
407 )
408 print()
409
410 def print_passes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100411 print("print_passes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100412 for idx, ps in enumerate(self.passes):
413 print("%03d %s" % (idx * 2, ps))
414
415 def print_passes_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100416 print("print_passes_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100417 for idx, ps in enumerate(self.passes):
418 print("%3d %s" % (idx * 2, ps))
419 for idx, tens in enumerate(ps.inputs):
420 print(
421 " Input %2d %-15s %-15s %-15s %s"
422 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
423 )
424 for idx, tens in enumerate(ps.intermediates):
425 print(
426 " Intermediate %2d %-15s %-15s %-15s %s"
427 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
428 )
429 for idx, tens in enumerate(ps.outputs):
430 print(
431 " Output %2d %-15s %-15s %-15s %s"
432 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
433 )
434 print()
435
436 def print_cascaded_passes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100437 print("print_cascaded_passes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100438 for idx, ps in enumerate(self.cascaded_passes):
439 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
440
441 def print_cascaded_passes_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100442 print("print_cascaded_passes_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100443 for idx, ps in enumerate(self.cascaded_passes):
444 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
445 for idx, tens in enumerate(ps.inputs):
446 print(
447 " Input %2d %-15s %-15s %-15s %s"
448 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
449 )
450 for idx, tens in enumerate(ps.intermediates):
451 print(
452 " Intermediate %2d %-15s %-15s %-15s %s"
453 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
454 )
455 for idx, tens in enumerate(ps.outputs):
456 print(
457 " Output %2d %-15s %-15s %-15s %s"
458 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
459 )
460 print()
461
462 def print_cascaded_passes_with_tensor_sizes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100463 print("print_cascaded_passes_with_tensor_sizes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100464 for idx, ps in enumerate(self.cascaded_passes):
465 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
466 for idx, tens in enumerate(ps.inputs):
467 print(
468 " Input %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
469 % (
470 idx,
471 tens.storage_size() / 1024,
472 tens.storage_shape,
473 tens.mem_area.name,
474 tens.purpose.name,
475 tens.format.name,
476 tens.name,
477 )
478 )
479 for idx, tens in enumerate(ps.intermediates):
480 print(
481 " Intermediate %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
482 % (
483 idx,
484 tens.storage_size() / 1024,
485 tens.storage_shape,
486 tens.mem_area.name,
487 tens.purpose.name,
488 tens.format.name,
489 tens.name,
490 )
491 )
492 for idx, tens in enumerate(ps.outputs):
493 print(
494 " Output %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
495 % (
496 idx,
497 tens.storage_size() / 1024,
498 tens.storage_shape,
499 tens.mem_area.name,
500 tens.purpose.name,
501 tens.format.name,
502 tens.name,
503 )
504 )
505 print()
506
507 def print_high_level_command_stream(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100508 print("print_high_level_command_stream()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100509 for idx, cmd in enumerate(self.high_level_command_stream):
510 print("%3d %s" % (idx, cmd))
511
512
513class Graph:
514 def __init__(self, name="<unnamed>", batch_size=1):
515 self.name = name
516 self.batch_size = batch_size
517 self.subgraphs = []
Michael McGeagh22f74e12020-08-07 16:21:03 +0100518 self.metadata = []
Tim Hall79d07d22020-04-27 18:20:16 +0100519 self.memory_used = {}
Diqing Zhongdb5124c2021-01-11 12:52:48 +0100520 self.total_original_weights = 0
Fredrik Svedbergf5c07c42021-04-23 14:36:42 +0200521 self.total_npu_weights = 0
522 self.total_npu_encoded_weights = 0
Louis Verhaard3c07c972020-05-07 08:12:58 +0200523 self.weight_cache = None # See CompressedWeightCache
Tim Hall79d07d22020-04-27 18:20:16 +0100524
525 def get_root_subgraph(self):
526 return self.subgraphs[0]
527
528 def prune_startup_init_pass(self):
529 for sg in self.subgraphs:
530 sg.prune_startup_init_pass()
531
532 def update_consumers(self):
533 for sg in self.subgraphs:
534 sg.update_consumers()
535
536 def refresh_after_modification(self):
537 for sg in self.subgraphs:
538 sg.refresh_after_modification()
539
540 def print_operators(self):
541 for sg in self.subgraphs:
542 sg.print_operators()
543
544 def print_graph(self):
545 for sg in self.subgraphs:
546 sg.print_graph()
547
548 def print_graph_with_tensors(self):
549 for sg in self.subgraphs:
550 sg.print_graph_with_tensors()
551
552 def print_graph_with_tensor_quantization(self):
553 for sg in self.subgraphs:
554 sg.print_graph_with_tensor_quantization()
555
556 def print_passes(self):
557 for sg in self.subgraphs:
558 sg.print_passes()
559
560 def print_passes_with_tensors(self):
561 for sg in self.subgraphs:
562 sg.print_passes_with_tensors()
563
564 def print_cascaded_passes(self):
565 for sg in self.subgraphs:
566 sg.print_cascaded_passes()
567
568 def print_cascaded_passes_with_tensors(self):
569 for sg in self.subgraphs:
570 sg.print_cascaded_passes_with_tensors()
571
572 def print_cascaded_passes_with_tensor_sizes(self):
573 for sg in self.subgraphs:
574 sg.print_cascaded_passes_with_tensor_sizes()
575
576 def print_high_level_command_stream(self):
577 for sg in self.subgraphs:
578 sg.print_high_level_command_stream()