blob: 977eb58e16cf22a1d8edd254c4f9fe2336e6dd7d [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# The scheduler costs various strategies for scheduling the network in order to select the block configuration.
Diego Russoea6111a2020-04-14 18:41:58 +010018import copy
Diego Russoe8a10452020-04-21 17:39:10 +010019import enum
20from functools import lru_cache
Diego Russoea6111a2020-04-14 18:41:58 +010021
Tim Hall79d07d22020-04-27 18:20:16 +010022import numpy as np
Diego Russoea6111a2020-04-14 18:41:58 +010023
24from . import live_range
Tim Hall79d07d22020-04-27 18:20:16 +010025from . import npu_performance
26from . import stats_writer
Fredrik Svedberg880e7352020-08-25 11:31:47 +020027from .data_type import DataType
Tim Hall79d07d22020-04-27 18:20:16 +010028from .high_level_command_stream_generator import calc_allowed_ofm_ifm_overlap_for_pass_list
Diego Russoe8a10452020-04-21 17:39:10 +010029from .nn_graph import CascadedPass
30from .nn_graph import PassPlacement
31from .nn_graph import SchedulerRewrite
32from .nn_graph import SchedulingStrategy
33from .npu_performance import make_bandwidth_array
34from .npu_performance import make_cycles_array
35from .npu_performance import make_macs_array
36from .npu_performance import make_metrics_arrays
37from .npu_performance import PassCycles
Jacob Bohlin1a666972020-09-11 10:04:15 +020038from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010039from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020040from .operation import Op
Andreas Nevalainen897cc142020-10-28 15:42:08 +010041from .operation import Operation
Diego Russoe8a10452020-04-21 17:39:10 +010042from .shared_buffer_allocation import find_block_configs_suitable_for_pass_and_shared_buffer
43from .shared_buffer_allocation import shared_buffer_allocation_for_pass_and_block_config
44from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020045from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010046from .tensor import TensorFormat
47from .tensor import TensorPurpose
48from .tensor import TensorSubPurpose
Jacob Bohlin1a666972020-09-11 10:04:15 +020049
Tim Hall79d07d22020-04-27 18:20:16 +010050
51class ParetoMetric(enum.Enum):
52 BwCycMem = 1
53 BwCycMemBlkH = 2
54
55 def __str__(self):
56 return self.name
57
58
59class SchedulerOptions:
60 def __init__(
61 self,
62 use_cascading=True,
Tim Hall79d07d22020-04-27 18:20:16 +010063 verbose_schedule=False,
64 verbose_pareto_frontier_schedules=False,
65 use_ifm_streaming=True,
66 pareto_metric=ParetoMetric.BwCycMem,
Charles Xu7b8823f2020-05-29 13:53:10 +020067 use_nhcwb16_between_cascaded_passes=True,
Tim Hall14e8a202020-11-27 12:23:42 +000068 cache_bias_scale_tensor=True,
Tim Hall79d07d22020-04-27 18:20:16 +010069 ):
70 self.use_cascading = use_cascading
Tim Hall79d07d22020-04-27 18:20:16 +010071 self.verbose_schedule = verbose_schedule
72 self.verbose_pareto_frontier_schedules = verbose_pareto_frontier_schedules
73 self.use_ifm_streaming = use_ifm_streaming
74 self.pareto_metric = pareto_metric
Charles Xu7b8823f2020-05-29 13:53:10 +020075 self.use_nhcwb16_between_cascaded_passes = use_nhcwb16_between_cascaded_passes
Tim Hall14e8a202020-11-27 12:23:42 +000076 self.cache_bias_scale_tensor = cache_bias_scale_tensor
Tim Hall79d07d22020-04-27 18:20:16 +010077
78 def __str__(self):
79 return type(self).__name__ + ": " + str(self.__dict__)
80
81 __repr__ = __str__
82
83
84class Strategy:
85 __slots__ = "strat", "param", "passes", "block_configs", "rewrite_list", "bws", "macs", "cycles", "sram_used"
86
87 def __init__(self, strat, param, passes, block_configs, rewrite_list, bws, macs, cycles, sram_used):
88 self.strat = strat
89 self.param = param
90 self.passes = passes
91 self.block_configs = block_configs
92 self.rewrite_list = (
93 rewrite_list # list of (SchedulerRewrite, Tensor, new sub purpose, purpose param a, purpose param b, pass)
94 )
95 self.bws = bws
96 self.macs = macs
97 self.cycles = cycles
98 self.sram_used = sram_used
99
100 def __eq__(self, other):
101 if self.strat != other.strat:
102 return False
103 if self.param != other.param:
104 return False
105 if self.block_configs != other.block_configs:
106 return False
107 if self.passes != other.passes:
108 return False
109 if (self.bws != other.bws).any():
110 return False
111 if (self.macs != other.macs).any():
112 return False
113 if (self.cycles != other.cycles).any():
114 return False
115 if self.sram_used != other.sram_used:
116 return False
117 return True
118
119 def empty(self):
120 return not self.passes
121
122 def key(self):
123 return self.passes[-1]
124
125 def clone(self):
126 return Strategy(
127 self.strat,
128 self.param,
129 self.passes,
130 self.block_configs,
131 self.rewrite_list,
132 self.bws,
133 self.macs,
134 self.cycles,
135 self.sram_used,
136 )
137
138 def __str__(self):
139 return "<scheduler.Strategy: %s %s %s %s %s %s %s>" % (
140 self.strat,
141 self.passes,
142 self.rewrite_list,
143 self.bws,
144 self.macs,
145 self.cycles,
146 self.sram_used,
147 )
148
149 __repr__ = __str__
150
151
152class StrategySet:
153 __slots__ = "strats", "bws", "macs", "cycles", "max_sram_used", "total_sram_used"
154
155 def __init__(self, strats=None):
156 if strats is None:
157 strats = dict()
158 self.strats = strats # final pass in packed pass -> Strategy
159 self.bws, self.macs, self.cycles = make_metrics_arrays()
160 self.max_sram_used = 0
161 self.total_sram_used = 0
162
163 def update_statistics(self):
164 self.bws = make_bandwidth_array()
165 self.max_sram_used = 0
166 for ps, strat in self.strats.items():
167 self.bws += strat.bws
168 self.macs += strat.macs
169 self.cycles += strat.cycles
170 self.max_sram_used = max(self.max_sram_used, strat.sram_used)
171 self.total_sram_used += strat.sram_used
172
173 def clone_add_strategy(self, new_strat):
174 key = new_strat.key()
175 if key in self.strats:
176 assert new_strat == self.strats[key]
177 return self
178 else:
179 new_strats = dict(self.strats)
180 new_strats[key] = new_strat
181 new_set = StrategySet(new_strats)
182 new_set.bws = self.bws + new_strat.bws
183 new_set.macs = self.macs + new_strat.macs
184 new_set.cycles = self.cycles + new_strat.cycles
185 new_set.max_sram_used = max(self.max_sram_used, new_strat.sram_used)
186 new_set.total_sram_used = self.total_sram_used + new_strat.sram_used
187 return new_set
188
189 def __eq__(self, other):
190 if (self.bws != other.bws).any():
191 return False
192 if (self.macs != other.macs).any():
193 return False
194 if (self.cycles != other.cycles).any():
195 return False
196 if self.max_sram_used != other.max_sram_used:
197 return False
198 if self.total_sram_used != other.total_sram_used:
199 return False
200 if self.strats != other.strats:
201 return False
202 return True
203
204 def __str__(self):
205 return "<scheduler.StrategySet: max_sram_used=%s passes_covered=%s>" % (
206 self.max_sram_used,
207 list(ps.name for ps in self.strats),
208 )
209
210 __repr__ = __str__
211
212
213empty_strategy = Strategy(
214 SchedulingStrategy.Unknown, None, [], [], [], make_bandwidth_array(), make_macs_array(), make_cycles_array(), 0
215)
216INFINITY = 1e30
217
218ABORT_SEARCH = []
219
220
221def flatten_list_of_lists(lstlst):
222 lst = []
223 for v in lstlst:
224 lst.extend(v)
225 return lst
226
227
228class DynamicProgrammingScheduler:
229 def __init__(self, nng, sg, arch, sram_limit, options: SchedulerOptions):
230 self.nng = nng
231 self.sg = sg
232 self.arch = arch
233 self.sram_limit = sram_limit
234 self.options = copy.copy(options)
235 self.use_cascading = options.use_cascading
236
237 if self.arch.feature_map_storage_mem_area != MemArea.Sram:
238 self.use_ifm_ofm_overlap = False # force off IFM/OFM overlap if IFMs and OFMs are not in the SRAM
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200239 else:
Patrik Gustavssonfad90c22020-11-03 13:07:40 +0100240 self.use_ifm_ofm_overlap = True
Tim Hall79d07d22020-04-27 18:20:16 +0100241
242 self.verbose_schedule = options.verbose_schedule
243 self.verbose_pareto_frontier_schedules = options.verbose_pareto_frontier_schedules
244 self.mem_area = MemArea.Sram
245
246 self.bandwidth_weights = arch.bandwidth_weights
247 self.cycles_weight = arch.cycles_weight
248 self.max_sram_used_weight = arch.max_sram_used_weight
249
250 self.n_combinations_searched = 0
251
Tim Hall79d07d22020-04-27 18:20:16 +0100252 self.pareto_max_candidates = 16
253
254 self.ifm_stream_npu_blocks = set(
Louis Verhaardaee5d752020-09-30 09:01:52 +0200255 (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling,)
Tim Hall79d07d22020-04-27 18:20:16 +0100256 )
257
258 num_pareto_metrics = 4
259 view_values = ",".join(["d"] * num_pareto_metrics)
260 order_values = ["f%d" % (idx,) for idx in range(num_pareto_metrics)]
261
262 def pareto_metric(self, candidate):
263 strat, strat_set = candidate
264 total_cycles = strat.cycles[PassCycles.Total] + strat_set.cycles[PassCycles.Total]
265 bws = strat.bws + strat_set.bws
266 last_block_height = 0
267 if self.options.pareto_metric == ParetoMetric.BwCycMemBlkH and len(strat.block_configs) > 0:
268 last_block_height = strat.block_configs[-1][0]
269
270 return (
271 np.tensordot(bws, self.bandwidth_weights, axes=3) + total_cycles * self.cycles_weight,
272 strat_set.max_sram_used,
273 strat.sram_used,
274 last_block_height,
275 )
276
277 def filter_pareto_frontier(self, candidates, remove_equally_good_candidates):
278
279 candidates = [cand for cand in candidates if max(cand[0].sram_used, cand[1].max_sram_used) <= self.sram_limit]
280
281 if len(candidates) <= 1:
282 return candidates
283 assert remove_equally_good_candidates
Tim Hall79d07d22020-04-27 18:20:16 +0100284 pareto_vals = np.zeros((len(candidates), DynamicProgrammingScheduler.num_pareto_metrics))
285 ids = np.arange(len(candidates), dtype=np.int32)
286 for idx, cand in enumerate(candidates):
287 pareto_vals[idx] = self.pareto_metric(cand)
288
289 sort_order = np.argsort(
290 pareto_vals.view(DynamicProgrammingScheduler.view_values),
291 order=DynamicProgrammingScheduler.order_values,
292 axis=0,
293 kind="stable",
294 ).flatten()
295 pareto_vals = pareto_vals[sort_order]
296 ids = ids[sort_order]
297
298 pareto_frontier = []
299 while len(ids) > 0:
300 pareto_frontier.append(candidates[ids[0]])
301 not_dominated_by_first = (pareto_vals < pareto_vals[0]).any(axis=1)
302 ids = ids[not_dominated_by_first]
303 pareto_vals = pareto_vals[not_dominated_by_first]
304
305 if len(pareto_frontier) > self.pareto_max_candidates:
306 pareto_frontier = self.sort_by_candidate_metric(pareto_frontier)
307 pareto_frontier = pareto_frontier[: self.pareto_max_candidates]
308
309 return pareto_frontier
310
311 def candidate_metric(self, candidate):
312 strat, strat_set = candidate
313 max_sram_used = max(strat_set.max_sram_used, strat.sram_used)
314 bws = strat.bws + strat_set.bws
315 total_cycles = strat.cycles[PassCycles.Total] + strat_set.cycles[PassCycles.Total]
316
317 return (
318 max_sram_used * self.max_sram_used_weight
319 + np.tensordot(bws, self.bandwidth_weights, axes=3)
320 + total_cycles * self.cycles_weight
321 )
322
323 def sort_by_candidate_metric(self, candidate_list):
324 sorted_list = list(sorted(candidate_list, key=self.candidate_metric))
325 return sorted_list
326
327 def best_candidate(self, candidate_list):
328 if len(candidate_list) == 0:
329 return ABORT_SEARCH
330 if len(candidate_list) == 1:
331 return candidate_list[0]
332 sorted_list = self.sort_by_candidate_metric(candidate_list)
333 return sorted_list[0]
334
335 def graduate_strat(self, strat_type, sram_used, old_strat_data):
336 res = []
337 for old_strat, old_strat_set in old_strat_data:
338 if old_strat.sram_used + sram_used > self.sram_limit:
339 continue # This strategy is bad, drop it
340 if old_strat_set.max_sram_used > self.sram_limit:
341 continue # This strategy is bad, drop it
342 assert old_strat.strat == SchedulingStrategy.Unknown
343
344 new_strat = old_strat.clone()
345 new_strat.strat = strat_type
346 new_strat.sram_used = old_strat.sram_used + sram_used
347
348 if self.use_ifm_ofm_overlap:
349 overlap = calc_allowed_ofm_ifm_overlap_for_pass_list(
350 new_strat.strat, new_strat.passes, new_strat.block_configs
351 )
352 new_strat.sram_used -= overlap
353
354 new_strat_set = old_strat_set.clone_add_strategy(new_strat)
355 res.append((empty_strategy, new_strat_set))
356 return self.filter_pareto_frontier(res, remove_equally_good_candidates=True)
357
358 def append_sram(self, sram_used, old_strat_data):
359 res = []
360 for old_strat, strat_set in old_strat_data:
361 assert old_strat.strat == SchedulingStrategy.Unknown
362 assert old_strat.sram_used == 0
363 new_strat = old_strat.clone()
364 new_strat.sram_used = old_strat.sram_used + sram_used
365
366 res.append((new_strat, strat_set))
367 return res
368
369 def append_sram_block_config_performance_metrics(self, sram_used, block_config, metrics, old_strat_data):
370 res = []
371 for old_strat, strat_set in old_strat_data:
372 assert old_strat.strat == SchedulingStrategy.Unknown
373 new_strat = old_strat.clone()
374 bws, macs, cycles = metrics[:3]
375
376 new_strat.sram_used = old_strat.sram_used + sram_used
377 new_strat.block_configs = old_strat.block_configs + [block_config]
378 new_strat.bws = old_strat.bws + bws
379 new_strat.macs = old_strat.macs + macs
380 new_strat.cycles = old_strat.cycles + cycles
381 new_strat.bws, new_strat.macs, new_strat.cycles = npu_performance.collate_stats_for_cascaded_pass(
382 self.arch, new_strat.bws, new_strat.macs, new_strat.cycles
383 )
384
385 res.append((new_strat, strat_set))
386 return res
387
388 def append_sram_pass_block_config_performance_metrics_rewrite_list(
389 self, sram_used, new_pass, block_config, metrics, rewrite_list, old_strat_data
390 ):
391 res = []
392 for old_strat, strat_set in old_strat_data:
393 assert old_strat.strat == SchedulingStrategy.Unknown
394 new_strat = old_strat.clone()
395 bws, macs, cycles = metrics[:3]
396 new_strat.sram_used = old_strat.sram_used + sram_used
397 new_strat.block_configs = old_strat.block_configs + [block_config]
398 new_strat.bws = old_strat.bws + bws
399 new_strat.macs = old_strat.macs + macs
400 new_strat.cycles = old_strat.cycles + cycles
401 new_strat.passes = old_strat.passes + [new_pass]
402 new_strat.bws, new_strat.macs, new_strat.cycles = npu_performance.collate_stats_for_cascaded_pass(
403 self.arch, new_strat.bws, new_strat.macs, new_strat.cycles
404 )
405 new_strat.rewrite_list = old_strat.rewrite_list + rewrite_list
406 res.append((new_strat, strat_set))
407 return res
408
409 def append_sram_rewrite_list(self, sram_used, rewrite_list, old_strat_data):
410 res = []
411 for old_strat, strat_set in old_strat_data:
412 assert old_strat.strat == SchedulingStrategy.Unknown
413 new_strat = old_strat.clone()
414 new_strat.sram_used = old_strat.sram_used + sram_used
415 new_strat.rewrite_list = old_strat.rewrite_list + rewrite_list
416 res.append((new_strat, strat_set))
417 return res
418
419 def pass_to_strat(self, strat_data):
420 res = {}
421 for strat in strat_data[1].strats.values():
422 for ps in strat.passes:
423 res[ps] = strat
424 return res
425
426 def compatible_strats(self, a, b):
427 intersection = a.keys() & b.keys()
428 for k in intersection:
429 if a[k] != b[k]:
430 return False
431 return True
432
433 def collate_strats_for_passes(self, all_passes):
434 if len(all_passes) == 0:
435 return [(empty_strategy, StrategySet(dict()))]
436 if len(all_passes) == 1:
437 return all_passes[0] # save some space in the common case
438 all_strands = [[self.pass_to_strat(strat_data) for strat_data in strand] for strand in all_passes]
439 prev_combos = [dict()]
440 for j, strand in enumerate(all_strands):
441 new_combos = []
442 for i, alt in enumerate(strand):
443 for prev in prev_combos:
444 if self.compatible_strats(prev, alt):
445 cmb = dict(prev)
446 cmb.update(all_passes[j][i][1].strats)
447 new_combos.append(cmb)
448 prev_combos = new_combos
449
450 res = []
451 for d in prev_combos:
452 s = StrategySet(d)
453 s.update_statistics()
454 res.append((empty_strategy, s))
455 return res
456
457 def search_all_but_one_predecessor(self, ps, pred_pass, pred_pass_data):
458 # get the rest of the predecessors
459 other_predecessors = [pred for pred in ps.dag_predecessors if pred != pred_pass]
460 other_predecessor_data = self.search_pass_list(other_predecessors)
461
462 # pred strat data has an incomplete strategy, which we need
463 # to continue on, whereas the other ones have completed strategies.
464 # we need to merge these, but keep the incomplete strategy too.
465
466 res = []
467 for pred_pass_strat, pred_pass_strat_set in pred_pass_data:
468 all_strats = [
469 [(empty_strategy, pred_pass_strat_set)], # pred strat data but with a dummy empty strategy
470 other_predecessor_data, # this one is fine to use as-is
471 ]
472 collated_strat_data = self.collate_strats_for_passes(all_strats)
473 strat_data = [(pred_pass_strat, strat_set) for _, strat_set in collated_strat_data]
474 res.extend(strat_data)
475 return res
476
477 def calc_non_local_mem_usage(self):
478 ignore_subgraph_input_output_tensors = self.sg.placement == PassPlacement.Cpu
479 range_set = live_range.extract_live_ranges_from_passes(
Patrik Gustavssona151f592020-10-16 13:59:52 +0200480 self.sg, self.mem_area, ignore_subgraph_input_output_tensors=ignore_subgraph_input_output_tensors,
Tim Hall79d07d22020-04-27 18:20:16 +0100481 )
482 range_dict = range_set.ranges
483
484 # find which ranges overlap passes but aren't input/outputs of the passes.
485 # these won't be counted by the dynamic programming search and must be counted in manually.
486 end_pos = max(ps.time for ps in self.sg.passes) + 2
487 mem_usage = np.zeros(end_pos) + self.sg.base_sram_used
488 non_local_mem_usage = np.zeros(end_pos, dtype=np.int64)
489
490 for tens, rng in range_dict.items():
491 storage_size = tens.storage_size()
492 assert tens.mem_area == self.mem_area
493 mem_usage[rng.start_time : rng.end_time] += storage_size
494
495 for ps in self.sg.passes:
496 local_mem_usage = 0
497 for tens in ps.inputs + ps.outputs + ps.intermediates:
498 if tens.mem_area != self.mem_area:
499 continue
500
501 local_mem_usage += tens.storage_size()
502
503 non_local_mem_usage[ps.time] = mem_usage[ps.time] - local_mem_usage
504
505 self.non_local_mem_usage = non_local_mem_usage
506
507 def search(self):
508 self.calc_non_local_mem_usage()
509 starting_passes = [ps for ps in self.sg.passes if not ps.successors]
510 strat_data = self.search_pass_list(starting_passes)
511
512 _, best_set = self.best_candidate(strat_data)
513
514 if self.verbose_pareto_frontier_schedules:
515 print(
516 "Scheduler searched %d combinations and found %d candidate schedules along the pareto frontier"
Diqing Zhong504d6b62020-09-17 12:21:10 +0200517 % (self.n_combinations_searched, len(strat_data))
Tim Hall79d07d22020-04-27 18:20:16 +0100518 )
519 for idx, (_, strat_set) in enumerate(strat_data):
520 extra = ""
521 if strat_set == best_set:
522 extra = "(Best candidate)"
523 print("Candidate", idx, extra)
524 memory_used = {MemArea.Sram: strat_set.max_sram_used}
525 stats_writer.print_performance_metrics_for_strat(
526 self.arch,
527 "",
528 strat_set.cycles,
529 strat_set.macs,
530 strat_set.bws,
531 self.nng.batch_size,
532 memory_used,
533 len(self.sg.passes),
534 len(strat_set.strats),
535 )
536
537 return best_set
538
539 def search_pass_list(self, pass_list):
540 all_strats = []
541 for ps in pass_list:
542 strat = self.search_output(ps)
543 all_strats.append(strat)
544 strat_data = self.collate_strats_for_passes(all_strats)
545 for strd in strat_data:
546 for ps in pass_list:
547 assert ps in strd[1].strats # should have strategies for everything we asked to search
548 return strat_data
549
550 def search_predecessors(self, ps):
551
552 # protect against graphs with loops. collate_strats_for_passes will sort this out later so that
553 # we have strats for all passes
554
555 pass_list = ps.dag_predecessors
556 strat_data = self.search_pass_list(pass_list)
557
558 return strat_data
559
560 @lru_cache(maxsize=None)
561 def search_output(self, ps):
562
563 assert ps in self.sg.passes
564 candidate_list = []
565
566 candidate_list.extend(self.search_weight_streaming_output(ps))
567
Patrik Gustavsson34b9dc12020-11-25 13:41:22 +0100568 if self.options.use_ifm_streaming:
Tim Hall79d07d22020-04-27 18:20:16 +0100569 candidate_list.extend(self.search_ifm_streaming_output(ps))
570
571 best = self.filter_pareto_frontier(candidate_list, remove_equally_good_candidates=True)
572
573 if not best:
574 print(
575 "Warning: Dynamic search programming algorithm failed for pass %s, invoking fallback strategy"
576 % (ps.name,)
577 )
578 return self.search_predecessors(ps)
579
580 return best
581
582 def search_ifm_streaming_output(self, ps):
583 if ps.placement != PassPlacement.Npu:
584 return ABORT_SEARCH
585 if ps.npu_block_type not in self.ifm_stream_npu_blocks:
586 return ABORT_SEARCH
587 strat_data = self.search_ifm_streaming_body(ps, False)
588
589 sram_used = self.non_local_mem_usage[ps.time]
590 for tens in ps.outputs:
591 if tens.mem_area == self.mem_area:
592 sram_used += tens.storage_size()
593
594 return self.graduate_strat(SchedulingStrategy.IfmStream, sram_used, strat_data)
595
596 @lru_cache(maxsize=None)
597 def search_ifm_streaming_body(self, ps, force_outputs_to_fast_storage):
598 if ps.placement != PassPlacement.Npu:
599 return ABORT_SEARCH
600 if ps.npu_block_type not in self.ifm_stream_npu_blocks:
601 return ABORT_SEARCH
602 ifm_input_search_resuls = self.search_ifm_streaming_input(ps)
603 res = []
604
605 base_sram_used = 0
606 for tens in ps.intermediates:
607 if tens.mem_area == self.mem_area:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200608 if tens.purpose == TensorPurpose.Weights:
609 base_sram_used = tens.storage_size(self.arch.weight_estimation_scaling)
610 else:
611 base_sram_used += tens.storage_size()
Tim Hall79d07d22020-04-27 18:20:16 +0100612
613 all_block_configs = self.get_block_configs(ps)
614 for block_config in all_block_configs:
615 all_strats = []
616
617 if self.use_cascading:
618 all_strats.extend(self.search_ifm_streaming_partial(ps, block_config))
619
620 all_strats.extend(ifm_input_search_resuls)
621
622 rewrite_list = []
623 sram_used = base_sram_used
624
625 metrics = npu_performance.performance_metrics_for_pass(
626 self.arch,
627 ps,
628 block_config,
629 rewrite_list=rewrite_list,
630 force_outputs_to_fast_storage=force_outputs_to_fast_storage,
631 )
632
633 res.extend(
634 self.append_sram_pass_block_config_performance_metrics_rewrite_list(
635 sram_used, ps, block_config, metrics, rewrite_list, all_strats
636 )
637 )
638
639 self.n_combinations_searched += len(res)
640 res = self.filter_pareto_frontier(res, remove_equally_good_candidates=True)
641 return res
642
Diqing Zhong504d6b62020-09-17 12:21:10 +0200643 def avoid_for_cascading(self, pred_candidate):
Patrik Gustavssonc0bb8992020-08-11 16:45:35 +0200644 for op in pred_candidate.ops:
Diqing Zhong504d6b62020-09-17 12:21:10 +0200645 if (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200646 op.type == Op.ConcatSliceWrite
Diqing Zhong504d6b62020-09-17 12:21:10 +0200647 and self.arch.feature_map_storage_mem_area != self.arch.fast_storage_mem_area
648 ):
649 # For SRAM spilling, concat op is avoided as predecessor
Patrik Gustavssonc0bb8992020-08-11 16:45:35 +0200650 return True
Jacob Bohlin1a666972020-09-11 10:04:15 +0200651 if len(op.outputs) > 1 or len(op.outputs[0].consumer_list) > 1:
652 # The op has consumers in other subgraphs
653 return True
Patrik Gustavsson34b9dc12020-11-25 13:41:22 +0100654 if op.type == Op.ResizeBilinear:
655 return True
Patrik Gustavssonc0bb8992020-08-11 16:45:35 +0200656 return False
657
Tim Hall79d07d22020-04-27 18:20:16 +0100658 def search_ifm_streaming_partial(self, ps, block_config):
659 if ps.placement != PassPlacement.Npu:
660 return ABORT_SEARCH
661
662 if len(ps.inputs) < 1:
663 return ABORT_SEARCH
664
665 ifm_tensor = ps.ifm_tensor
666
667 if ifm_tensor is None:
668 return ABORT_SEARCH
669 if ifm_tensor.purpose != TensorPurpose.FeatureMap:
670 return ABORT_SEARCH
671 if not ifm_tensor.storage_shape or len(ifm_tensor.storage_shape) != 4:
672 return ABORT_SEARCH
673
674 pred_pass_list = []
675 for pred_candidate in ps.dag_predecessors:
676 if len(pred_candidate.outputs) == 1 and pred_candidate.outputs[0] == ifm_tensor:
677 # we found a predecessor that produces this IFM tensor
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200678 if not ifm_tensor.avoid_NHCWB16:
679 # and NHCWB16 format is not to be avoided
680 if len(pred_candidate.successors) == 1 and pred_candidate.successors[0] == ps:
681 # and it only has one successor, namely us
682 if pred_candidate.placement == PassPlacement.Npu:
683 if pred_candidate.npu_block_type in self.ifm_stream_npu_blocks:
684 # and it is on the Npu
Diqing Zhong504d6b62020-09-17 12:21:10 +0200685 if not self.avoid_for_cascading(pred_candidate):
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200686 # and fusable - it's a candidate
687 pred_pass_list.append(pred_candidate)
Tim Hall79d07d22020-04-27 18:20:16 +0100688
689 if not pred_pass_list:
690 return ABORT_SEARCH
691
692 all_candidates = []
693 for pred_pass in pred_pass_list:
694 # recurse into the next pass
Tim Hall1bd531d2020-11-01 20:59:36 +0000695 ifm_strat_data = self.search_ifm_streaming_body(pred_pass, self.arch.is_spilling_enabled())
Tim Hall79d07d22020-04-27 18:20:16 +0100696
697 strat_data = self.search_all_but_one_predecessor(ps, pred_pass, ifm_strat_data)
698 for strat_opt in strat_data:
699
700 pred_pass_block_config = strat_opt[0].block_configs[-1]
701 rolling_buffer_dims = npu_performance.rolling_buffer_dims_from_passes(
702 self.arch, pred_pass, pred_pass_block_config, ps, block_config
703 )
704 if rolling_buffer_dims is None:
705 continue # this does not pack properly, skip it.
706
707 sram_used = 0
708 for tens in ps.inputs:
709 if tens != ifm_tensor:
710 if tens.mem_area == self.mem_area:
711 sram_used += tens.storage_size()
712
713 rolling_buffer_y, rolling_buffer_x = rolling_buffer_dims
714
715 rewrite_list = [
716 (
717 SchedulerRewrite.ChangeTensorSubPurpose,
718 ifm_tensor,
719 TensorSubPurpose.RollingBufferY,
720 rolling_buffer_y,
721 None,
722 ps,
723 )
724 ]
725 sram_used += ifm_tensor.storage_size_for_sub_purpose(
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200726 self.arch, TensorSubPurpose.RollingBufferY, rolling_buffer_y, None
Tim Hall79d07d22020-04-27 18:20:16 +0100727 )
728
729 all_candidates.extend(self.append_sram_rewrite_list(sram_used, rewrite_list, [strat_opt]))
730
731 self.n_combinations_searched += len(all_candidates)
732 return all_candidates
733
734 def get_block_configs(self, ps):
735 if ps.placement != PassPlacement.Npu:
Diego Russoea6111a2020-04-14 18:41:58 +0100736 return [(1, 1, 1, 1)] # default
Tim Hall79d07d22020-04-27 18:20:16 +0100737
738 block_configs = find_block_configs_suitable_for_pass_and_shared_buffer(self.arch, ps)
739
740 # Take a limited number of the largest blocks
741 if self.arch.block_config_limit > 0:
742 # Sort by block area, followed by depth
743 block_configs.sort(key=lambda cfg: (cfg[0] * cfg[1]) << 8 | cfg[3], reverse=True)
744 bound = min(len(block_configs), self.arch.block_config_limit)
745 # We take 'n' from the fat end of the list, and 'n' from the thin end of the list.
746 tmp = block_configs[:bound]
747 tmp.extend(block_configs[max(bound, len(block_configs) - bound) :])
748 block_configs = tmp
749
750 return block_configs
751
752 def search_ifm_streaming_input(self, ps):
753 sram_used = 0
754 for tens in ps.inputs:
755 if tens.mem_area == self.mem_area:
756 sram_used += tens.storage_size()
757
758 return self.append_sram(sram_used, self.search_predecessors(ps))
759
760 def search_weight_streaming_output(self, ps):
761 strat_data = self.search_weight_streaming_body(ps)
762
763 sram_used = self.non_local_mem_usage[ps.time]
764 for tens in ps.outputs:
765 if tens.mem_area == self.mem_area:
766 sram_used += tens.storage_size()
767
768 return self.graduate_strat(SchedulingStrategy.WeightStream, sram_used, strat_data)
769
770 @lru_cache(maxsize=None)
771 def search_weight_streaming_body(self, ps):
772
773 strat_data = self.search_weight_streaming_input(ps)
774
775 res = []
776
777 all_block_configs = self.get_block_configs(ps)
778
779 for block_config in all_block_configs:
780
781 sram_used = 0
782 rewrite_list = []
783
784 for tens in ps.intermediates:
785 if tens.mem_area == self.mem_area:
786 if tens.purpose == TensorPurpose.Weights:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200787 sram_used += tens.storage_size_for_sub_purpose(
788 self.arch, TensorSubPurpose.DoubleBuffer, block_config[3]
789 )
Tim Hall79d07d22020-04-27 18:20:16 +0100790 rewrite_list.append(
791 (
792 SchedulerRewrite.ChangeTensorSubPurpose,
793 tens,
794 TensorSubPurpose.DoubleBuffer,
795 block_config[3],
796 None,
797 ps,
798 )
799 )
800 else:
801 sram_used += tens.storage_size()
802
803 metrics = npu_performance.performance_metrics_for_pass(
804 self.arch, ps, block_config, rewrite_list=rewrite_list
805 )
806
807 res.extend(
808 self.append_sram_pass_block_config_performance_metrics_rewrite_list(
809 sram_used, ps, block_config, metrics, rewrite_list, strat_data
810 )
811 )
812
813 self.n_combinations_searched += len(res)
814 res = self.filter_pareto_frontier(res, remove_equally_good_candidates=True)
815 return res
816
817 def search_weight_streaming_input(self, ps):
818 sram_used = 0
819 for tens in ps.inputs:
820 if tens.mem_area == self.mem_area:
821 sram_used += tens.storage_size()
822
823 return self.append_sram(sram_used, self.search_predecessors(ps))
824
825 def apply_result(self, strat_set, arch):
826 pass_to_cascaded_pass = dict()
827 for _, strat in strat_set.strats.items():
828 # rewrite the tensors that need this first. e.g. make rolling buffers
829 inputs = []
830 intermediates = []
831 outputs = []
832
833 for ps in strat.passes:
834 inputs += ps.inputs
835 intermediates += ps.intermediates
836 outputs += ps.outputs
837
838 for tens in set(inputs) & set(outputs):
839 # tensors that are in both sets are intermediates
840
841 # find pass with input/output tensor, and check if they are both placed on NPU
842 input_placement = None
843 output_placement = None
844 for ps in strat.passes:
845 if tens in ps.inputs:
846 input_placement = ps.placement
847 if tens in ps.outputs:
848 output_placement = ps.placement
849 if input_placement == output_placement == PassPlacement.Npu:
850 tens.set_format(TensorFormat.NHCWB16, arch)
851
852 intermediates.append(tens)
853 inputs.remove(tens)
854 outputs.remove(tens)
855
856 for rewrite_op, tens, sub_purpose, param_a, param_b, ps in strat.rewrite_list:
857 if rewrite_op == SchedulerRewrite.ChangeTensorSubPurpose:
858 tens.mem_area = self.arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200859 tens.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100860 tens.set_new_sub_purpose(sub_purpose, param_a, param_b)
861 else:
862 assert 0, "unknown rewrite_op " + str(rewrite_op)
863
864 is_element_wise = True
865 for ps in strat.passes:
866 assert ps.placement == strat.passes[0].placement
867 if not ps.is_element_wise:
868 is_element_wise = False
869 break
870
871 cascaded_pass = CascadedPass(
872 strat.passes[0].name,
873 strat.strat,
874 inputs,
875 intermediates,
876 outputs,
877 strat.passes,
878 strat.passes[0].placement,
879 is_element_wise,
880 )
881 assert strat.sram_used >= 0
882 cascaded_pass.sram_used = strat.sram_used
883
884 for idx, ps in enumerate(strat.passes):
885 assert ps not in pass_to_cascaded_pass
886 pass_to_cascaded_pass[ps] = cascaded_pass
887 ps.cascade = cascaded_pass
888 ps.block_config = strat.block_configs[idx]
889
890 if ps.placement == PassPlacement.Npu:
891 ps.shared_buffer = shared_buffer_allocation_for_pass_and_block_config(
892 self.arch, ps, ps.block_config
893 )
894 assert ps.shared_buffer is not None
895
Diqing Zhong504d6b62020-09-17 12:21:10 +0200896 sram_used = max(self.non_local_mem_usage[ps.time], 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100897 for op in ps.ops:
898 subgraph = op.attrs.get("subgraph")
899 if subgraph:
Diqing Zhong504d6b62020-09-17 12:21:10 +0200900 subgraph.base_sram_used = sram_used
Tim Hall79d07d22020-04-27 18:20:16 +0100901
902 # all passes should have a cascaded pass now
903 if len(pass_to_cascaded_pass) != len(self.sg.passes):
904 print(
905 "mismatch: we have %d passes, but only %d have cascaded passes associated"
906 % (len(self.sg.passes), len(pass_to_cascaded_pass))
907 )
908 for ps in self.sg.passes:
Diego Russoea6111a2020-04-14 18:41:58 +0100909 if ps not in pass_to_cascaded_pass:
Tim Hall79d07d22020-04-27 18:20:16 +0100910 print("%3d pass missing cascaded pass %s" % (ps.time, ps))
911
912 assert len(pass_to_cascaded_pass) == len(self.sg.passes)
Tim Hall79d07d22020-04-27 18:20:16 +0100913
Tim Hall79d07d22020-04-27 18:20:16 +0100914 cascaded_passes = []
Charles Xu19515e82020-06-10 10:48:33 +0200915 if self.sg.placement == PassPlacement.Cpu:
916 # Retain the pass order for CPU subgraph
917 cascaded_passes = [ps.cascade for ps in self.sg.passes]
918 else:
919 # we have all the passes, but we need to put them in order and build predecessor/successor links.
920 visit_pass_set = set()
Tim Hall79d07d22020-04-27 18:20:16 +0100921
Charles Xu19515e82020-06-10 10:48:33 +0200922 def visit_pass(ps):
923 if ps in visit_pass_set:
924 return
925 visit_pass_set.add(ps)
Tim Hall79d07d22020-04-27 18:20:16 +0100926
Charles Xu19515e82020-06-10 10:48:33 +0200927 cps = ps.cascade
928 dont_traverse = set(cps.passes)
Tim Hall79d07d22020-04-27 18:20:16 +0100929
Charles Xu19515e82020-06-10 10:48:33 +0200930 for ps in cps.passes:
931 for pred in ps.predecessors:
932 if pred in dont_traverse:
933 continue
934 visit_pass(pred)
Tim Hall79d07d22020-04-27 18:20:16 +0100935
Charles Xu19515e82020-06-10 10:48:33 +0200936 cascaded_passes.append(cps)
Tim Hall79d07d22020-04-27 18:20:16 +0100937
Charles Xu19515e82020-06-10 10:48:33 +0200938 starting_passes = [ps for ps in self.sg.passes if not ps.successors]
939 for ps in starting_passes:
940 visit_pass(ps)
Tim Hall79d07d22020-04-27 18:20:16 +0100941
942 # reorder so startup init cascaded passes come first
943 def is_startup_cascaded_pass(cps):
944 if not cps.passes:
945 return False
946 return cps.placement == PassPlacement.StartupInit
947
948 cascaded_passes = [cps for cps in cascaded_passes if is_startup_cascaded_pass(cps)] + [
949 cps for cps in cascaded_passes if not is_startup_cascaded_pass(cps)
950 ]
951
952 self.sg.cascaded_passes = cascaded_passes
953 self.sg.build_cascaded_pass_links()
954
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200955 # Check if NHCWB16 and/or fast storage can be used in between cascaded passes
956 # (NHCWB16 within cascaded passes has been handled earlier in this function)
957 if self.sg.placement == PassPlacement.Npu:
958 # Dictionary tensor -> list of ops, containing feature maps that can be attempted
959 # to be moved to fast storage
960 fast_storage_tensor_rewrites = {}
961 last_op_in_subgraph = self.sg.cascaded_passes[-1].passes[-1].primary_op
Fredrik Svedbergfd314282020-11-06 13:48:15 +0100962 # Memory only passes have no primary_op, so use the last op in ops
963 if last_op_in_subgraph is None:
964 last_op_in_subgraph = self.sg.cascaded_passes[-1].passes[-1].ops[-1]
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200965 for ps in self.sg.cascaded_passes:
966 if ps.placement != PassPlacement.Npu:
967 continue
968 for output in ps.outputs:
969 if output.purpose != TensorPurpose.FeatureMap or output.avoid_NHCWB16:
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +0200970 continue
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200971
972 use_NHCWB16 = True
973 use_fast_storage = True
974 rewrites = []
975 for op in output.consumer_list:
976 if op is None:
977 use_NHCWB16 = False
978 use_fast_storage = False
Charles Xu7b8823f2020-05-29 13:53:10 +0200979 continue
Louis Verhaardaee5d752020-09-30 09:01:52 +0200980 if op.type == Op.ReduceSum and output.dtype == DataType.int32:
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200981 use_NHCWB16 = False
Louis Verhaardaee5d752020-09-30 09:01:52 +0200982 elif op.type == Op.Reshape:
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200983 # Using NHCWB16 format for a no-op reshape is only an option if subsequent
984 # consumers do not also need to perform a reshape or if the OFM is going to
985 # be processed by CPU operations. No-op reshape consumers with empty lists
986 # (those that have no consumers, or null-consumers used as list terminators)
987 # must use normal NHWC output.
Fredrik Svedbergfd314282020-11-06 13:48:15 +0100988 def incompatible_consumers(oper):
989 if oper and oper.type == Op.Reshape:
990 for consumer in oper.outputs[0].consumer_list:
991 yield from incompatible_consumers(consumer)
992 yield not oper or not oper.run_on_npu or oper is last_op_in_subgraph
993
994 if not any(incompatible_consumers(op)):
995
996 def get_rewrites(oper):
997 if oper and oper.type == Op.Reshape:
998 for consumer in oper.outputs[0].consumer_list:
999 yield from get_rewrites(consumer)
1000 yield oper
1001
1002 rewrites.extend(get_rewrites(op))
1003 # Detect no-op reshapes by comparing their full input and output tensor shapes.
1004 inshape = full_shape(4, op.inputs[0].shape, 1)
1005 compatible_shape = [
1006 (inshape == full_shape(4, oper.outputs[0].shape, 1)) for oper in get_rewrites(op)
1007 ]
1008 use_NHCWB16 = compatible_shape and all(compatible_shape)
Tim Hallba695182020-08-26 17:27:19 +01001009 else:
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001010 use_NHCWB16 = False
1011 use_fast_storage = False
1012 use_NHCWB16 &= op.run_on_npu
1013 use_fast_storage &= op.run_on_npu
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +02001014
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001015 if use_fast_storage:
1016 fast_storage_tensor_rewrites[output] = rewrites
1017 if use_NHCWB16 and self.options.use_nhcwb16_between_cascaded_passes:
1018 output.set_format(TensorFormat.NHCWB16, arch)
1019 for rewrite_op in rewrites:
1020 rewrite_op.outputs[0].set_format(TensorFormat.NHCWB16, arch)
Tim Hall1bd531d2020-11-01 20:59:36 +00001021 if arch.is_spilling_enabled():
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001022 # Remember feature maps that can be moved to fast storage for later use
1023 # in use_fast_storage_for_feature_maps
1024 self.sg.scheduling_info["feature_map_rewrites"] = fast_storage_tensor_rewrites
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +02001025
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001026
1027def move_scales_to_fast_storage(nng, arch):
1028 for sg in nng.subgraphs:
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001029 # IFM streamed ops reads bias tensors several times, move these to fast storage
1030 for cp in sg.cascaded_passes:
1031 if cp.strategy == SchedulingStrategy.IfmStream:
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001032 # Calculate SRAM usage
1033 new_size = 0
1034 all_tens = []
1035 for ps in cp.passes:
1036 pass_tens = np.array([ps.ifm_tensor, ps.ifm2_tensor, ps.ofm_tensor, ps.weight_tensor])
1037 pass_tens = np.append(pass_tens, ps.intermediates)
1038 for tens in pass_tens:
1039 if tens and tens.mem_area == MemArea.Sram and tens not in all_tens:
1040 all_tens.append(tens)
1041 new_size += tens.storage_size()
1042
1043 cp.sram_used = new_size
1044
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001045 for ps in cp.passes:
Andreas Nevalainened67b882020-11-17 09:16:11 +01001046 if ps.scale_tensor:
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001047 tens = ps.scale_tensor
1048
1049 # Find op using scale tensor
1050 op = next((op for op in ps.ops if tens in op.inputs), None)
1051 assert op
1052
1053 # Create fast storage tensor
1054 new_tens = tens.clone_into_fast_storage(arch)
1055 new_tens.consumer_list = tens.consumer_list.copy()
1056 new_tens.purpose = TensorPurpose.FSBias
Andreas Nevalainened67b882020-11-17 09:16:11 +01001057 new_tens_size = new_tens.storage_size()
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001058
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001059 if (cp.sram_used + new_tens_size) <= arch.sram_size:
Andreas Nevalainened67b882020-11-17 09:16:11 +01001060 # Create DMA cmd
1061 dma_cmd = Operation(Op.DMA, tens.ops[0].name + "_dma")
1062 dma_cmd.inputs = [tens]
1063 dma_cmd.set_output_tensor(new_tens)
1064 dma_cmd.attrs["source"] = tens.mem_area
1065 dma_cmd.attrs["destination"] = new_tens.mem_area
1066 dma_cmd.run_on_npu = True
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001067
Andreas Nevalainened67b882020-11-17 09:16:11 +01001068 tens.consumer_list.clear()
1069 tens.consumer_list.append(dma_cmd)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001070
Andreas Nevalainened67b882020-11-17 09:16:11 +01001071 # Replace tensor and op
1072 idx = op.inputs.index(tens)
1073 op.inputs[idx] = new_tens
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001074
Andreas Nevalainened67b882020-11-17 09:16:11 +01001075 ps.ops.insert(0, dma_cmd)
1076 ps.scale_tensor = new_tens
1077 ps.intermediates.append(new_tens)
1078 ps.cascade.intermediates.append(new_tens)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001079
Andreas Nevalainened67b882020-11-17 09:16:11 +01001080 cp.sram_used += new_tens_size
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001081
Tim Hall79d07d22020-04-27 18:20:16 +01001082
1083def schedule_passes(nng, arch, options: SchedulerOptions):
1084
1085 for sg in nng.subgraphs:
1086 sg.base_sram_used = 0
1087
1088 for sg in nng.subgraphs:
1089 # re-entering the same nodes from different contexts requires us to
1090 # build a simplified directed acyclic (DAG) version of the graph to
1091 # use for traversal, rather than using a visit dictionary. this avoids
1092 # recursing infinitely due to loops.
1093 sg.build_pass_dag_predecessors()
1094
1095 dps = DynamicProgrammingScheduler(nng, sg, arch, arch.sram_size, options)
1096
1097 strat_set = dps.search()
1098
1099 dps.apply_result(strat_set, arch)
1100
1101 if options.verbose_schedule:
1102 sg.print_cascaded_passes()
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001103
1104
1105def _calc_tens_to_cps(sg, tensor_rewrites):
1106 # Determines for each tensor the list of affected cascaded passes, in terms of SRAM consumption.
1107 # Returns dictionary tensor -> list of cascaded passes
1108 # Note: if cascaded passes are A, B, C, D, and a tensor is output
1109 # of A and input to D, then it also consumes SRAM in passes B and C.
1110 if "tens_to_cps" in sg.scheduling_info:
1111 return sg.scheduling_info["tens_to_cps"]
1112 # Determine life-time of tensors
1113 min_index = {}
1114 max_index = {}
1115 index = 0
1116 cps_list = [cps for cps in sg.cascaded_passes if cps.placement == PassPlacement.Npu]
1117 for cps in cps_list:
1118 for tens in cps.inputs + cps.outputs:
1119 if tens in tensor_rewrites:
1120 min_index[tens] = min(index, min_index.get(tens, len(cps_list)))
1121 max_index[tens] = index
1122 index += 1
1123 # Convert to affected cps-es
1124 tens_to_cps = {}
1125 for tens in min_index:
1126 tens_to_cps[tens] = cps_list[min_index[tens] : max_index[tens] + 1]
1127 sg.scheduling_info["tens_to_cps"] = tens_to_cps
1128 return tens_to_cps
1129
1130
1131def use_fast_storage_for_feature_maps(sg, sram_limit, arch):
1132 # Attempts to use as much fast storage as possible for feature maps shared between cascaded passes.
1133 tensor_rewrites = sg.scheduling_info.get("feature_map_rewrites", {})
1134 tens_to_cps = _calc_tens_to_cps(sg, tensor_rewrites)
1135 # Sort tensors first on life-time (smallest first), then on size (biggest first)
1136 tens_list = sorted([(len(tens_to_cps[tens]), -tens.storage_size(), tens.name, tens) for tens in tens_to_cps])
1137 for _, _, _, tens in tens_list:
1138 cps_list = tens_to_cps[tens]
Fredrik Svedbergfd314282020-11-06 13:48:15 +01001139 if len(cps_list) < 1:
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001140 continue
1141 sz = tens.storage_size()
1142 fits_in_fast_storage = all([cps.sram_used + sz <= sram_limit for cps in cps_list])
1143 if fits_in_fast_storage:
1144 tens.mem_area = arch.fast_storage_mem_area
1145 tens.mem_type = MemType.Scratch_fast
1146 tens.set_new_sub_purpose(TensorSubPurpose.Standard, None, None)
1147 assert tens in tensor_rewrites
1148 # Also rewrite reshapes
1149 for rewrite_op in tensor_rewrites[tens]:
1150 tens2 = rewrite_op.outputs[0]
1151 tens2.mem_area = arch.fast_storage_mem_area
1152 tens2.mem_type = MemType.Scratch_fast
1153 tens2.set_new_sub_purpose(TensorSubPurpose.Standard, None, None)
1154 for cps in cps_list:
1155 cps.sram_used += sz
1156
1157
1158def undo_use_fast_storage(sg, arch):
1159 # Undoes the effects of a previous call to use_fast_storage_for_feature_maps
1160 tensor_rewrites = sg.scheduling_info.get("feature_map_rewrites", {})
1161 tens_to_cps = _calc_tens_to_cps(sg, tensor_rewrites)
1162 mem_area = arch.tensor_storage_mem_area[TensorPurpose.FeatureMap]
1163 for tens, cps_list in tens_to_cps.items():
1164 if tens.mem_type == MemType.Scratch_fast:
1165 sz = tens.storage_size()
1166 tens.mem_area = mem_area
1167 tens.mem_type = MemType.Scratch
1168 # Also undo reshapes
1169 for rewrite_op in tensor_rewrites[tens]:
1170 tens2 = rewrite_op.outputs[0]
1171 tens2.mem_area = mem_area
1172 tens2.mem_type = MemType.Scratch
1173 for cps in cps_list:
1174 cps.sram_used -= sz