blob: f810df0fa61fb3fafb0eb770177496e2fec5ed30 [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 = {}
Tim Hall79d07d22020-04-27 18:20:16 +0100157
158 def __str__(self):
159 return "<nng.Subgraph '%s', n_passes=%d, n_cascaded_passes=%d>" % (
160 self.name,
161 len(self.passes),
162 len(self.cascaded_passes),
163 )
164
165 __repr__ = __str__
166
167 def update_consumers(self):
168 visit_op_set = set()
169 visit_tensor_set = set()
170 self.input_tensors = []
171
172 print_visit = False
173
174 def visit_op(op):
175 if op in visit_op_set:
176 return
177
178 visit_op_set.add(op)
179 for inp in op.inputs:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200180 if not inp:
181 continue
Tim Hall79d07d22020-04-27 18:20:16 +0100182 if print_visit:
183 print(inp, "adding consumer", op)
184 visit_tensor(inp)
185 inp.consumer_list.append(op)
186
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000187 if op.type in (Op.Placeholder, Op.SubgraphInput):
Tim Hall79d07d22020-04-27 18:20:16 +0100188 assert len(op.outputs) == 1
189 self.input_tensors.append(op.outputs[0])
190
191 for out in op.outputs:
192 if out not in visit_tensor_set:
193 out.consumer_list = [] # reset unvisited output, just in case
194
195 def visit_tensor(tens):
196 if tens in visit_tensor_set:
197 return
198 visit_tensor_set.add(tens)
199 tens.consumer_list = []
200 for op in tens.ops:
201 visit_op(op)
202
203 for ps in self.passes:
204 for tens in ps.outputs + ps.inputs:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200205 if not tens:
206 continue
Tim Hall79d07d22020-04-27 18:20:16 +0100207 tens.consumer_list = [] # reset unvisited tensors to start with
208
209 for tens in self.output_tensors:
210 visit_tensor(tens)
211 tens.consumer_list.append(None) # special op to indicate that the graph consumes the result
212
213 print_visit = True
214 for ps in self.passes:
215 for op in ps.ops:
216 visit_op(op)
217 for tens in ps.inputs:
218 visit_tensor(tens)
219
220 def build_pass_links(self):
221 for idx, ps in enumerate(self.passes):
222 ps.time = 2 * idx
223 ps.predecessors = []
224 ps.successors = []
225
226 for ps in self.passes:
227 for tens in ps.inputs:
228 for op in tens.ops:
229 pred_pass = op.scheduled_pass
230 assert pred_pass.time < ps.time
231 if ps not in pred_pass.successors:
232 pred_pass.successors.append(ps)
233
234 if pred_pass not in ps.predecessors:
235 ps.predecessors.append(pred_pass)
236
237 assert tens in pred_pass.outputs
238
239 def build_pass_dag_predecessors(self):
240 for ps in self.passes:
241 ps.dag_predecessors = []
242
243 class State(enum.Enum):
244 NotVisited = 0
245 BeingVisited = 1
246 Visited = 2
247
248 pass_visit_dict = {}
249
250 def visit_pass(ps):
251 state = pass_visit_dict.get(ps, State.NotVisited)
252 if state == State.Visited:
253 return True
254 elif state == State.BeingVisited:
255 return False # this is a loop, need to remove this link
256 elif state == State.NotVisited:
257 pass_visit_dict[ps] = State.BeingVisited
258
259 ps.dag_predecessors = []
260 for pred in ps.predecessors:
261 if visit_pass(pred):
262 ps.dag_predecessors.append(pred)
263
264 pass_visit_dict[ps] = State.Visited
265 return True
266
267 for ps in self.passes:
268 if not ps.successors:
269 visit_pass(ps)
270
271 def build_cascaded_pass_links(self):
272 for cps in self.cascaded_passes:
273 cps.predecessors = []
274 cps.successors = []
275
276 for cps in self.cascaded_passes:
277 for tens in cps.inputs:
278 for op in tens.ops:
279 pred_cpass = op.scheduled_pass.cascade
280 if cps not in pred_cpass.successors:
281 pred_cpass.successors.append(cps)
282
283 if pred_cpass not in cps.predecessors:
284 cps.predecessors.append(pred_cpass)
285
286 assert tens in pred_cpass.outputs
287
288 def refresh_after_modification(self):
289 self.update_consumers()
290
291 def prune_startup_init_pass(self):
292 assert len(self.passes) >= 1
293 ps = self.passes[0]
294 assert ps.placement == PassPlacement.StartupInit
295
296 ps.outputs = [out_tens for out_tens in ps.outputs if len(out_tens.consumers()) > 0]
297 ps.ops = [op for op in ps.ops if op.outputs[0] in ps.outputs]
298
299 def get_all_ops(self):
300 all_ops = []
301 visit_op_set = set()
302 visit_tensor_set = set()
303
304 def visit_op(op):
305 if op in visit_op_set:
306 return
307 visit_op_set.add(op)
308 for inp in op.inputs:
309 visit_tensor(inp)
310
311 all_ops.append(op)
312
313 def visit_tensor(tens):
Andreas Nevalainene1cc3de2020-09-08 15:31:02 +0200314 if tens is None or tens in visit_tensor_set:
Tim Hall79d07d22020-04-27 18:20:16 +0100315 return
316 visit_tensor_set.add(tens)
317 for op in tens.ops:
318 visit_op(op)
319
320 for tens in self.output_tensors:
321 visit_tensor(tens)
322
323 return all_ops
324
325 def print_operators(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100326 print("print_operators()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100327 all_ops = self.get_all_ops()
328 unique_ops = []
Tim Hall79d07d22020-04-27 18:20:16 +0100329 for op in all_ops:
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000330 if op.type in (Op.Const, Op.Identity, Op.Placeholder):
Tim Hall79d07d22020-04-27 18:20:16 +0100331 continue
332
Louis Verhaardaee5d752020-09-30 09:01:52 +0200333 attrs = op.attrs.copy()
334 if op.type in (Op.Conv2D, Op.Conv2DBias, Op.DepthwiseConv2DBias):
Tim Hall79d07d22020-04-27 18:20:16 +0100335 kshape = op.inputs[1].shape
336 attrs["kshape"] = [kshape[0], kshape[1]]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200337 attrs["type"] = op.type.name
Tim Hall79d07d22020-04-27 18:20:16 +0100338 attrs.pop("use_cudnn_on_gpu", None)
Fredrik Svedberg16343052021-04-16 14:36:22 +0200339 custom_options = attrs.pop("custom_options", None)
Tim Hall79d07d22020-04-27 18:20:16 +0100340 if attrs not in unique_ops:
341 unique_ops.append(attrs)
342 # print attributes in human readable format
343 a = attrs.copy()
Fredrik Svedberg16343052021-04-16 14:36:22 +0200344 if custom_options is not None:
345 a["custom_options"] = custom_options
Tim Hall79d07d22020-04-27 18:20:16 +0100346 s = a.pop("type")
347 data_format = a.pop("data_format", None)
348 if data_format and data_format != b"NHWC":
349 s += " " + str(data_format)
350 t = a.pop("T", None)
351 if t:
352 s += " " + str(t)[9:-2]
353 srct = a.pop("SrcT", None)
354 if srct:
355 s += " " + str(srct)[9:-2]
356 dstt = a.pop("DstT", None)
357 if dstt:
358 s += "->" + str(dstt)[9:-2]
359 print(s + " " + str(a))
360
Fredrik Svedbergc875aa62021-05-06 09:53:31 +0200361 def print_graph(self, label=None):
362 if label:
363 print(f"\n[ {label} ]")
Michael McGeagh775e3962020-07-28 11:44:22 +0100364 print("print_graph()", 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
369 def print_graph_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100370 print("print_graph_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100371 all_ops = self.get_all_ops()
372 for idx, op in enumerate(all_ops):
373 print(idx, op.type, op.name)
374 for idx, tens in enumerate(op.inputs):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200375 print(
376 " Input %02d %20s %20s %20s %s"
377 % (idx, tens.purpose.name, tens.mem_area.name, tens.mem_type.name, tens)
378 )
Tim Hall79d07d22020-04-27 18:20:16 +0100379 for idx, tens in enumerate(op.outputs):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200380 print(
381 " Output %02d %20s %20s %20s %s"
382 % (idx, tens.purpose.name, tens.mem_area.name, tens.mem_type.name, tens)
383 )
Tim Hall79d07d22020-04-27 18:20:16 +0100384 print()
385
386 def print_graph_with_tensor_quantization(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100387 print("print_graph_with_tensor_quantization()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100388 all_ops = self.get_all_ops()
389 for idx, op in enumerate(all_ops):
390 print(idx, op.type, op.name)
391 for idx, tens in enumerate(op.inputs):
392 q = tens.quantization
393 if q is None:
394 print(" Input %02d %10s NO QUANTIZATION INFO %s" % (idx, tens.dtype, tens.name))
395 else:
396 print(
397 " Input %02d %10s min=%s max=%s scale=%s zero_point=%s %s"
398 % (idx, tens.dtype, q.min, q.max, q.scale_f32, q.zero_point, tens.name)
399 )
400 for idx, tens in enumerate(op.outputs):
401 q = tens.quantization
402 if q is None:
403 print(" Output %02d %10s NO QUANTIZATION INFO %s" % (idx, tens.dtype, tens.name))
404 else:
405 print(
406 " Output %02d %10s min=%s max=%s scale=%s zero_point=%s %s"
407 % (idx, tens.dtype, q.min, q.max, q.scale_f32, q.zero_point, tens.name)
408 )
409 print()
410
411 def print_passes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100412 print("print_passes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100413 for idx, ps in enumerate(self.passes):
414 print("%03d %s" % (idx * 2, ps))
415
416 def print_passes_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100417 print("print_passes_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100418 for idx, ps in enumerate(self.passes):
419 print("%3d %s" % (idx * 2, ps))
420 for idx, tens in enumerate(ps.inputs):
421 print(
422 " Input %2d %-15s %-15s %-15s %s"
423 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
424 )
425 for idx, tens in enumerate(ps.intermediates):
426 print(
427 " Intermediate %2d %-15s %-15s %-15s %s"
428 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
429 )
430 for idx, tens in enumerate(ps.outputs):
431 print(
432 " Output %2d %-15s %-15s %-15s %s"
433 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
434 )
435 print()
436
437 def print_cascaded_passes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100438 print("print_cascaded_passes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100439 for idx, ps in enumerate(self.cascaded_passes):
440 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
441
442 def print_cascaded_passes_with_tensors(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100443 print("print_cascaded_passes_with_tensors()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100444 for idx, ps in enumerate(self.cascaded_passes):
445 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
446 for idx, tens in enumerate(ps.inputs):
447 print(
448 " Input %2d %-15s %-15s %-15s %s"
449 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
450 )
451 for idx, tens in enumerate(ps.intermediates):
452 print(
453 " Intermediate %2d %-15s %-15s %-15s %s"
454 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
455 )
456 for idx, tens in enumerate(ps.outputs):
457 print(
458 " Output %2d %-15s %-15s %-15s %s"
459 % (idx, tens.purpose.name, tens.mem_area.name, tens.format.name, tens.name)
460 )
461 print()
462
463 def print_cascaded_passes_with_tensor_sizes(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100464 print("print_cascaded_passes_with_tensor_sizes()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100465 for idx, ps in enumerate(self.cascaded_passes):
466 print("%3d %s SRAM used %.1f KB" % (idx * 2, ps, ps.sram_used / 1024))
467 for idx, tens in enumerate(ps.inputs):
468 print(
469 " Input %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
470 % (
471 idx,
472 tens.storage_size() / 1024,
473 tens.storage_shape,
474 tens.mem_area.name,
475 tens.purpose.name,
476 tens.format.name,
477 tens.name,
478 )
479 )
480 for idx, tens in enumerate(ps.intermediates):
481 print(
482 " Intermediate %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
483 % (
484 idx,
485 tens.storage_size() / 1024,
486 tens.storage_shape,
487 tens.mem_area.name,
488 tens.purpose.name,
489 tens.format.name,
490 tens.name,
491 )
492 )
493 for idx, tens in enumerate(ps.outputs):
494 print(
495 " Output %2d %7.1f KB %-24s %-15s %-15s %-20s %s"
496 % (
497 idx,
498 tens.storage_size() / 1024,
499 tens.storage_shape,
500 tens.mem_area.name,
501 tens.purpose.name,
502 tens.format.name,
503 tens.name,
504 )
505 )
506 print()
507
508 def print_high_level_command_stream(self):
Michael McGeagh775e3962020-07-28 11:44:22 +0100509 print("print_high_level_command_stream()", self.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100510 for idx, cmd in enumerate(self.high_level_command_stream):
511 print("%3d %s" % (idx, cmd))
512
513
514class Graph:
515 def __init__(self, name="<unnamed>", batch_size=1):
516 self.name = name
517 self.batch_size = batch_size
518 self.subgraphs = []
Michael McGeagh22f74e12020-08-07 16:21:03 +0100519 self.metadata = []
Tim Hall79d07d22020-04-27 18:20:16 +0100520 self.memory_used = {}
Diqing Zhongdb5124c2021-01-11 12:52:48 +0100521 self.total_original_weights = 0
Fredrik Svedbergf5c07c42021-04-23 14:36:42 +0200522 self.total_npu_weights = 0
523 self.total_npu_encoded_weights = 0
Louis Verhaard3c07c972020-05-07 08:12:58 +0200524 self.weight_cache = None # See CompressedWeightCache
Tim Hall79d07d22020-04-27 18:20:16 +0100525
526 def get_root_subgraph(self):
527 return self.subgraphs[0]
528
529 def prune_startup_init_pass(self):
530 for sg in self.subgraphs:
531 sg.prune_startup_init_pass()
532
533 def update_consumers(self):
534 for sg in self.subgraphs:
535 sg.update_consumers()
536
537 def refresh_after_modification(self):
538 for sg in self.subgraphs:
539 sg.refresh_after_modification()
540
541 def print_operators(self):
542 for sg in self.subgraphs:
543 sg.print_operators()
544
Fredrik Svedbergc875aa62021-05-06 09:53:31 +0200545 def print_graph(self, label=None):
Tim Hall79d07d22020-04-27 18:20:16 +0100546 for sg in self.subgraphs:
Fredrik Svedbergc875aa62021-05-06 09:53:31 +0200547 sg.print_graph(label)
Tim Hall79d07d22020-04-27 18:20:16 +0100548
549 def print_graph_with_tensors(self):
550 for sg in self.subgraphs:
551 sg.print_graph_with_tensors()
552
553 def print_graph_with_tensor_quantization(self):
554 for sg in self.subgraphs:
555 sg.print_graph_with_tensor_quantization()
556
557 def print_passes(self):
558 for sg in self.subgraphs:
559 sg.print_passes()
560
561 def print_passes_with_tensors(self):
562 for sg in self.subgraphs:
563 sg.print_passes_with_tensors()
564
565 def print_cascaded_passes(self):
566 for sg in self.subgraphs:
567 sg.print_cascaded_passes()
568
569 def print_cascaded_passes_with_tensors(self):
570 for sg in self.subgraphs:
571 sg.print_cascaded_passes_with_tensors()
572
573 def print_cascaded_passes_with_tensor_sizes(self):
574 for sg in self.subgraphs:
575 sg.print_cascaded_passes_with_tensor_sizes()
576
577 def print_high_level_command_stream(self):
578 for sg in self.subgraphs:
579 sg.print_high_level_command_stream()