blob: d2c848ad5ecffa3de9100c511f80e9ab8f4ee18d [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# 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 Verhaard9bfe0f82020-12-03 12:26:25 +010041 Search = 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 = {}
Tim Hall79d07d22020-04-27 18:20:16 +0100153
154 self.memory_used = {}
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200155 self.memory_used_per_type = {}
Tim Hall79d07d22020-04-27 18:20:16 +0100156
157 def __str__(self):
158 return "<nng.Subgraph '%s', n_passes=%d, n_cascaded_passes=%d>" % (
159 self.name,
160 len(self.passes),
161 len(self.cascaded_passes),
162 )
163
164 __repr__ = __str__
165
166 def update_consumers(self):
167 visit_op_set = set()
168 visit_tensor_set = set()
169 self.input_tensors = []
170
171 print_visit = False
172
173 def visit_op(op):
174 if op in visit_op_set:
175 return
176
177 visit_op_set.add(op)
178 for inp in op.inputs:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200179 if not inp:
180 continue
Tim Hall79d07d22020-04-27 18:20:16 +0100181 if print_visit:
182 print(inp, "adding consumer", op)
183 visit_tensor(inp)
184 inp.consumer_list.append(op)
185
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000186 if op.type in (Op.Placeholder, Op.SubgraphInput):
Tim Hall79d07d22020-04-27 18:20:16 +0100187 assert len(op.outputs) == 1
188 self.input_tensors.append(op.outputs[0])
189
190 for out in op.outputs:
191 if out not in visit_tensor_set:
192 out.consumer_list = [] # reset unvisited output, just in case
193
194 def visit_tensor(tens):
195 if tens in visit_tensor_set:
196 return
197 visit_tensor_set.add(tens)
198 tens.consumer_list = []
199 for op in tens.ops:
200 visit_op(op)
201
202 for ps in self.passes:
203 for tens in ps.outputs + ps.inputs:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200204 if not tens:
205 continue
Tim Hall79d07d22020-04-27 18:20:16 +0100206 tens.consumer_list = [] # reset unvisited tensors to start with
207
208 for tens in self.output_tensors:
209 visit_tensor(tens)
210 tens.consumer_list.append(None) # special op to indicate that the graph consumes the result
211
212 print_visit = True
213 for ps in self.passes:
214 for op in ps.ops:
215 visit_op(op)
216 for tens in ps.inputs:
217 visit_tensor(tens)
218
219 def build_pass_links(self):
220 for idx, ps in enumerate(self.passes):
221 ps.time = 2 * idx
222 ps.predecessors = []
223 ps.successors = []
224
225 for ps in self.passes:
226 for tens in ps.inputs:
227 for op in tens.ops:
228 pred_pass = op.scheduled_pass
229 assert pred_pass.time < ps.time
230 if ps not in pred_pass.successors:
231 pred_pass.successors.append(ps)
232
233 if pred_pass not in ps.predecessors:
234 ps.predecessors.append(pred_pass)
235
236 assert tens in pred_pass.outputs
237
238 def build_pass_dag_predecessors(self):
239 for ps in self.passes:
240 ps.dag_predecessors = []
241
242 class State(enum.Enum):
243 NotVisited = 0
244 BeingVisited = 1
245 Visited = 2
246
247 pass_visit_dict = {}
248
249 def visit_pass(ps):
250 state = pass_visit_dict.get(ps, State.NotVisited)
251 if state == State.Visited:
252 return True
253 elif state == State.BeingVisited:
254 return False # this is a loop, need to remove this link
255 elif state == State.NotVisited:
256 pass_visit_dict[ps] = State.BeingVisited
257
258 ps.dag_predecessors = []
259 for pred in ps.predecessors:
260 if visit_pass(pred):
261 ps.dag_predecessors.append(pred)
262
263 pass_visit_dict[ps] = State.Visited
264 return True
265
266 for ps in self.passes:
267 if not ps.successors:
268 visit_pass(ps)
269
270 def build_cascaded_pass_links(self):
271 for cps in self.cascaded_passes:
272 cps.predecessors = []
273 cps.successors = []
274
275 for cps in self.cascaded_passes:
276 for tens in cps.inputs:
277 for op in tens.ops:
278 pred_cpass = op.scheduled_pass.cascade
279 if cps not in pred_cpass.successors:
280 pred_cpass.successors.append(cps)
281
282 if pred_cpass not in cps.predecessors:
283 cps.predecessors.append(pred_cpass)
284
285 assert tens in pred_cpass.outputs
286
287 def refresh_after_modification(self):
288 self.update_consumers()
289
290 def prune_startup_init_pass(self):
291 assert len(self.passes) >= 1
292 ps = self.passes[0]
293 assert ps.placement == PassPlacement.StartupInit
294
295 ps.outputs = [out_tens for out_tens in ps.outputs if len(out_tens.consumers()) > 0]
296 ps.ops = [op for op in ps.ops if op.outputs[0] in ps.outputs]
297
298 def get_all_ops(self):
299 all_ops = []
300 visit_op_set = set()
301 visit_tensor_set = set()
302
303 def visit_op(op):
304 if op in visit_op_set:
305 return
306 visit_op_set.add(op)
307 for inp in op.inputs:
308 visit_tensor(inp)
309
310 all_ops.append(op)
311
312 def visit_tensor(tens):
Andreas Nevalainene1cc3de2020-09-08 15:31:02 +0200313 if tens is None or tens in visit_tensor_set:
Tim Hall79d07d22020-04-27 18:20:16 +0100314 return
315 visit_tensor_set.add(tens)
316 for op in tens.ops:
317 visit_op(op)
318
319 for tens in self.output_tensors:
320 visit_tensor(tens)
321
322 return all_ops
323
324 def print_operators(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100325 print("print_operators()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100326 all_ops = self.get_all_ops()
327 unique_ops = []
Tim Hall79d07d22020-04-27 18:20:16 +0100328 for op in all_ops:
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000329 if op.type in (Op.Const, Op.Identity, Op.Placeholder):
Tim Hall79d07d22020-04-27 18:20:16 +0100330 continue
331
Louis Verhaardaee5d752020-09-30 09:01:52 +0200332 attrs = op.attrs.copy()
333 if op.type in (Op.Conv2D, Op.Conv2DBias, Op.DepthwiseConv2DBias):
Tim Hall79d07d22020-04-27 18:20:16 +0100334 kshape = op.inputs[1].shape
335 attrs["kshape"] = [kshape[0], kshape[1]]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200336 attrs["type"] = op.type.name
Tim Hall79d07d22020-04-27 18:20:16 +0100337 attrs.pop("use_cudnn_on_gpu", None)
338 if attrs not in unique_ops:
339 unique_ops.append(attrs)
340 # print attributes in human readable format
341 a = attrs.copy()
342 s = a.pop("type")
343 data_format = a.pop("data_format", None)
344 if data_format and data_format != b"NHWC":
345 s += " " + str(data_format)
346 t = a.pop("T", None)
347 if t:
348 s += " " + str(t)[9:-2]
349 srct = a.pop("SrcT", None)
350 if srct:
351 s += " " + str(srct)[9:-2]
352 dstt = a.pop("DstT", None)
353 if dstt:
354 s += "->" + str(dstt)[9:-2]
355 print(s + " " + str(a))
356
357 def print_graph(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100358 print("print_graph()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100359 all_ops = self.get_all_ops()
360 for idx, op in enumerate(all_ops):
361 print(idx, op.type, op.name)
362
363 def print_graph_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100364 print("print_graph_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100365 all_ops = self.get_all_ops()
366 for idx, op in enumerate(all_ops):
367 print(idx, op.type, op.name)
368 for idx, tens in enumerate(op.inputs):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200369 print(
370 " Input %02d %20s %20s %20s %s"
371 % (idx, tens.purpose.name, tens.mem_area.name, tens.mem_type.name, tens)
372 )
Tim Hall79d07d22020-04-27 18:20:16 +0100373 for idx, tens in enumerate(op.outputs):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200374 print(
375 " Output %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 print()
379
380 def print_graph_with_tensor_quantization(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100381 print("print_graph_with_tensor_quantization()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100382 all_ops = self.get_all_ops()
383 for idx, op in enumerate(all_ops):
384 print(idx, op.type, op.name)
385 for idx, tens in enumerate(op.inputs):
386 q = tens.quantization
387 if q is None:
388 print(" Input %02d %10s NO QUANTIZATION INFO %s" % (idx, tens.dtype, tens.name))
389 else:
390 print(
391 " Input %02d %10s min=%s max=%s scale=%s zero_point=%s %s"
392 % (idx, tens.dtype, q.min, q.max, q.scale_f32, q.zero_point, tens.name)
393 )
394 for idx, tens in enumerate(op.outputs):
395 q = tens.quantization
396 if q is None:
397 print(" Output %02d %10s NO QUANTIZATION INFO %s" % (idx, tens.dtype, tens.name))
398 else:
399 print(
400 " Output %02d %10s min=%s max=%s scale=%s zero_point=%s %s"
401 % (idx, tens.dtype, q.min, q.max, q.scale_f32, q.zero_point, tens.name)
402 )
403 print()
404
405 def print_passes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100406 print("print_passes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100407 for idx, ps in enumerate(self.passes):
408 print("%03d %s" % (idx * 2, ps))
409
410 def print_passes_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100411 print("print_passes_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100412 for idx, ps in enumerate(self.passes):
413 print("%3d %s" % (idx * 2, ps))
414 for idx, tens in enumerate(ps.inputs):
415 print(
416 " Input %2d %-15s %-15s %-15s %s"
417 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
418 )
419 for idx, tens in enumerate(ps.intermediates):
420 print(
421 " Intermediate %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.outputs):
425 print(
426 " Output %2d %-15s %-15s %-15s %s"
427 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
428 )
429 print()
430
431 def print_cascaded_passes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100432 print("print_cascaded_passes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100433 for idx, ps in enumerate(self.cascaded_passes):
434 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
435
436 def print_cascaded_passes_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100437 print("print_cascaded_passes_with_tensors()", 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 for idx, tens in enumerate(ps.inputs):
441 print(
442 " Input %2d %-15s %-15s %-15s %s"
443 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
444 )
445 for idx, tens in enumerate(ps.intermediates):
446 print(
447 " Intermediate %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.outputs):
451 print(
452 " Output %2d %-15s %-15s %-15s %s"
453 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
454 )
455 print()
456
457 def print_cascaded_passes_with_tensor_sizes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100458 print("print_cascaded_passes_with_tensor_sizes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100459 for idx, ps in enumerate(self.cascaded_passes):
460 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
461 for idx, tens in enumerate(ps.inputs):
462 print(
463 " Input %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
464 % (
465 idx,
466 tens.storage_size() / 1024,
467 tens.storage_shape,
468 tens.mem_area.name,
469 tens.purpose.name,
470 tens.format.name,
471 tens.name,
472 )
473 )
474 for idx, tens in enumerate(ps.intermediates):
475 print(
476 " Intermediate %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
477 % (
478 idx,
479 tens.storage_size() / 1024,
480 tens.storage_shape,
481 tens.mem_area.name,
482 tens.purpose.name,
483 tens.format.name,
484 tens.name,
485 )
486 )
487 for idx, tens in enumerate(ps.outputs):
488 print(
489 " Output %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
490 % (
491 idx,
492 tens.storage_size() / 1024,
493 tens.storage_shape,
494 tens.mem_area.name,
495 tens.purpose.name,
496 tens.format.name,
497 tens.name,
498 )
499 )
500 print()
501
502 def print_high_level_command_stream(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100503 print("print_high_level_command_stream()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100504 for idx, cmd in enumerate(self.high_level_command_stream):
505 print("%3d %s" % (idx, cmd))
506
507
508class Graph:
509 def __init__(self, name="<unnamed>", batch_size=1):
510 self.name = name
511 self.batch_size = batch_size
512 self.subgraphs = []
Michael McGeagh22f74e12020-08-07 16:21:03 +0100513 self.metadata = []
Tim Hall79d07d22020-04-27 18:20:16 +0100514 self.memory_used = {}
515 self.bits_per_element = {}
516 self.total_size = {}
517 self.total_elements = {}
Louis Verhaard3c07c972020-05-07 08:12:58 +0200518 self.weight_cache = None # See CompressedWeightCache
Tim Hall79d07d22020-04-27 18:20:16 +0100519
520 def get_root_subgraph(self):
521 return self.subgraphs[0]
522
523 def prune_startup_init_pass(self):
524 for sg in self.subgraphs:
525 sg.prune_startup_init_pass()
526
527 def update_consumers(self):
528 for sg in self.subgraphs:
529 sg.update_consumers()
530
531 def refresh_after_modification(self):
532 for sg in self.subgraphs:
533 sg.refresh_after_modification()
534
535 def print_operators(self):
536 for sg in self.subgraphs:
537 sg.print_operators()
538
539 def print_graph(self):
540 for sg in self.subgraphs:
541 sg.print_graph()
542
543 def print_graph_with_tensors(self):
544 for sg in self.subgraphs:
545 sg.print_graph_with_tensors()
546
547 def print_graph_with_tensor_quantization(self):
548 for sg in self.subgraphs:
549 sg.print_graph_with_tensor_quantization()
550
551 def print_passes(self):
552 for sg in self.subgraphs:
553 sg.print_passes()
554
555 def print_passes_with_tensors(self):
556 for sg in self.subgraphs:
557 sg.print_passes_with_tensors()
558
559 def print_cascaded_passes(self):
560 for sg in self.subgraphs:
561 sg.print_cascaded_passes()
562
563 def print_cascaded_passes_with_tensors(self):
564 for sg in self.subgraphs:
565 sg.print_cascaded_passes_with_tensors()
566
567 def print_cascaded_passes_with_tensor_sizes(self):
568 for sg in self.subgraphs:
569 sg.print_cascaded_passes_with_tensor_sizes()
570
571 def print_high_level_command_stream(self):
572 for sg in self.subgraphs:
573 sg.print_high_level_command_stream()