blob: 5c2ddabb3163b00414c42a261bbc0986909e4d2c [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
40from .shared_buffer_allocation import find_block_configs_suitable_for_pass_and_shared_buffer
41from .shared_buffer_allocation import shared_buffer_allocation_for_pass_and_block_config
42from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020043from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010044from .tensor import TensorFormat
45from .tensor import TensorPurpose
46from .tensor import TensorSubPurpose
Jacob Bohlin1a666972020-09-11 10:04:15 +020047
Tim Hall79d07d22020-04-27 18:20:16 +010048
49class ParetoMetric(enum.Enum):
50 BwCycMem = 1
51 BwCycMemBlkH = 2
52
53 def __str__(self):
54 return self.name
55
56
57class SchedulerOptions:
58 def __init__(
59 self,
60 use_cascading=True,
61 use_ifm_ofm_overlap=True,
62 verbose_schedule=False,
63 verbose_pareto_frontier_schedules=False,
64 use_ifm_streaming=True,
65 pareto_metric=ParetoMetric.BwCycMem,
Charles Xu7b8823f2020-05-29 13:53:10 +020066 use_nhcwb16_between_cascaded_passes=True,
Tim Hall79d07d22020-04-27 18:20:16 +010067 ):
68 self.use_cascading = use_cascading
69 self.use_ifm_ofm_overlap = use_ifm_ofm_overlap
70 self.verbose_schedule = verbose_schedule
71 self.verbose_pareto_frontier_schedules = verbose_pareto_frontier_schedules
72 self.use_ifm_streaming = use_ifm_streaming
73 self.pareto_metric = pareto_metric
Charles Xu7b8823f2020-05-29 13:53:10 +020074 self.use_nhcwb16_between_cascaded_passes = use_nhcwb16_between_cascaded_passes
Tim Hall79d07d22020-04-27 18:20:16 +010075
76 def __str__(self):
77 return type(self).__name__ + ": " + str(self.__dict__)
78
79 __repr__ = __str__
80
81
82class Strategy:
83 __slots__ = "strat", "param", "passes", "block_configs", "rewrite_list", "bws", "macs", "cycles", "sram_used"
84
85 def __init__(self, strat, param, passes, block_configs, rewrite_list, bws, macs, cycles, sram_used):
86 self.strat = strat
87 self.param = param
88 self.passes = passes
89 self.block_configs = block_configs
90 self.rewrite_list = (
91 rewrite_list # list of (SchedulerRewrite, Tensor, new sub purpose, purpose param a, purpose param b, pass)
92 )
93 self.bws = bws
94 self.macs = macs
95 self.cycles = cycles
96 self.sram_used = sram_used
97
98 def __eq__(self, other):
99 if self.strat != other.strat:
100 return False
101 if self.param != other.param:
102 return False
103 if self.block_configs != other.block_configs:
104 return False
105 if self.passes != other.passes:
106 return False
107 if (self.bws != other.bws).any():
108 return False
109 if (self.macs != other.macs).any():
110 return False
111 if (self.cycles != other.cycles).any():
112 return False
113 if self.sram_used != other.sram_used:
114 return False
115 return True
116
117 def empty(self):
118 return not self.passes
119
120 def key(self):
121 return self.passes[-1]
122
123 def clone(self):
124 return Strategy(
125 self.strat,
126 self.param,
127 self.passes,
128 self.block_configs,
129 self.rewrite_list,
130 self.bws,
131 self.macs,
132 self.cycles,
133 self.sram_used,
134 )
135
136 def __str__(self):
137 return "<scheduler.Strategy: %s %s %s %s %s %s %s>" % (
138 self.strat,
139 self.passes,
140 self.rewrite_list,
141 self.bws,
142 self.macs,
143 self.cycles,
144 self.sram_used,
145 )
146
147 __repr__ = __str__
148
149
150class StrategySet:
151 __slots__ = "strats", "bws", "macs", "cycles", "max_sram_used", "total_sram_used"
152
153 def __init__(self, strats=None):
154 if strats is None:
155 strats = dict()
156 self.strats = strats # final pass in packed pass -> Strategy
157 self.bws, self.macs, self.cycles = make_metrics_arrays()
158 self.max_sram_used = 0
159 self.total_sram_used = 0
160
161 def update_statistics(self):
162 self.bws = make_bandwidth_array()
163 self.max_sram_used = 0
164 for ps, strat in self.strats.items():
165 self.bws += strat.bws
166 self.macs += strat.macs
167 self.cycles += strat.cycles
168 self.max_sram_used = max(self.max_sram_used, strat.sram_used)
169 self.total_sram_used += strat.sram_used
170
171 def clone_add_strategy(self, new_strat):
172 key = new_strat.key()
173 if key in self.strats:
174 assert new_strat == self.strats[key]
175 return self
176 else:
177 new_strats = dict(self.strats)
178 new_strats[key] = new_strat
179 new_set = StrategySet(new_strats)
180 new_set.bws = self.bws + new_strat.bws
181 new_set.macs = self.macs + new_strat.macs
182 new_set.cycles = self.cycles + new_strat.cycles
183 new_set.max_sram_used = max(self.max_sram_used, new_strat.sram_used)
184 new_set.total_sram_used = self.total_sram_used + new_strat.sram_used
185 return new_set
186
187 def __eq__(self, other):
188 if (self.bws != other.bws).any():
189 return False
190 if (self.macs != other.macs).any():
191 return False
192 if (self.cycles != other.cycles).any():
193 return False
194 if self.max_sram_used != other.max_sram_used:
195 return False
196 if self.total_sram_used != other.total_sram_used:
197 return False
198 if self.strats != other.strats:
199 return False
200 return True
201
202 def __str__(self):
203 return "<scheduler.StrategySet: max_sram_used=%s passes_covered=%s>" % (
204 self.max_sram_used,
205 list(ps.name for ps in self.strats),
206 )
207
208 __repr__ = __str__
209
210
211empty_strategy = Strategy(
212 SchedulingStrategy.Unknown, None, [], [], [], make_bandwidth_array(), make_macs_array(), make_cycles_array(), 0
213)
214INFINITY = 1e30
215
216ABORT_SEARCH = []
217
218
219def flatten_list_of_lists(lstlst):
220 lst = []
221 for v in lstlst:
222 lst.extend(v)
223 return lst
224
225
226class DynamicProgrammingScheduler:
227 def __init__(self, nng, sg, arch, sram_limit, options: SchedulerOptions):
228 self.nng = nng
229 self.sg = sg
230 self.arch = arch
231 self.sram_limit = sram_limit
232 self.options = copy.copy(options)
233 self.use_cascading = options.use_cascading
234
235 if self.arch.feature_map_storage_mem_area != MemArea.Sram:
236 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 +0200237 else:
238 self.use_ifm_ofm_overlap = options.use_ifm_ofm_overlap
Tim Hall79d07d22020-04-27 18:20:16 +0100239
240 self.verbose_schedule = options.verbose_schedule
241 self.verbose_pareto_frontier_schedules = options.verbose_pareto_frontier_schedules
242 self.mem_area = MemArea.Sram
243
244 self.bandwidth_weights = arch.bandwidth_weights
245 self.cycles_weight = arch.cycles_weight
246 self.max_sram_used_weight = arch.max_sram_used_weight
247
248 self.n_combinations_searched = 0
249
250 self.feature_maps_not_in_fast_storage = (
251 arch.tensor_storage_mem_area[TensorPurpose.FeatureMap] != arch.fast_storage_mem_area
252 )
253
254 self.pareto_max_candidates = 16
255
256 self.ifm_stream_npu_blocks = set(
Diqing Zhong504d6b62020-09-17 12:21:10 +0200257 (
258 NpuBlockType.ConvolutionMxN,
259 NpuBlockType.ConvolutionDepthWise,
260 NpuBlockType.Pooling,
261 )
Tim Hall79d07d22020-04-27 18:20:16 +0100262 )
263
264 num_pareto_metrics = 4
265 view_values = ",".join(["d"] * num_pareto_metrics)
266 order_values = ["f%d" % (idx,) for idx in range(num_pareto_metrics)]
267
268 def pareto_metric(self, candidate):
269 strat, strat_set = candidate
270 total_cycles = strat.cycles[PassCycles.Total] + strat_set.cycles[PassCycles.Total]
271 bws = strat.bws + strat_set.bws
272 last_block_height = 0
273 if self.options.pareto_metric == ParetoMetric.BwCycMemBlkH and len(strat.block_configs) > 0:
274 last_block_height = strat.block_configs[-1][0]
275
276 return (
277 np.tensordot(bws, self.bandwidth_weights, axes=3) + total_cycles * self.cycles_weight,
278 strat_set.max_sram_used,
279 strat.sram_used,
280 last_block_height,
281 )
282
283 def filter_pareto_frontier(self, candidates, remove_equally_good_candidates):
284
285 candidates = [cand for cand in candidates if max(cand[0].sram_used, cand[1].max_sram_used) <= self.sram_limit]
286
287 if len(candidates) <= 1:
288 return candidates
289 assert remove_equally_good_candidates
Tim Hall79d07d22020-04-27 18:20:16 +0100290 pareto_vals = np.zeros((len(candidates), DynamicProgrammingScheduler.num_pareto_metrics))
291 ids = np.arange(len(candidates), dtype=np.int32)
292 for idx, cand in enumerate(candidates):
293 pareto_vals[idx] = self.pareto_metric(cand)
294
295 sort_order = np.argsort(
296 pareto_vals.view(DynamicProgrammingScheduler.view_values),
297 order=DynamicProgrammingScheduler.order_values,
298 axis=0,
299 kind="stable",
300 ).flatten()
301 pareto_vals = pareto_vals[sort_order]
302 ids = ids[sort_order]
303
304 pareto_frontier = []
305 while len(ids) > 0:
306 pareto_frontier.append(candidates[ids[0]])
307 not_dominated_by_first = (pareto_vals < pareto_vals[0]).any(axis=1)
308 ids = ids[not_dominated_by_first]
309 pareto_vals = pareto_vals[not_dominated_by_first]
310
311 if len(pareto_frontier) > self.pareto_max_candidates:
312 pareto_frontier = self.sort_by_candidate_metric(pareto_frontier)
313 pareto_frontier = pareto_frontier[: self.pareto_max_candidates]
314
315 return pareto_frontier
316
317 def candidate_metric(self, candidate):
318 strat, strat_set = candidate
319 max_sram_used = max(strat_set.max_sram_used, strat.sram_used)
320 bws = strat.bws + strat_set.bws
321 total_cycles = strat.cycles[PassCycles.Total] + strat_set.cycles[PassCycles.Total]
322
323 return (
324 max_sram_used * self.max_sram_used_weight
325 + np.tensordot(bws, self.bandwidth_weights, axes=3)
326 + total_cycles * self.cycles_weight
327 )
328
329 def sort_by_candidate_metric(self, candidate_list):
330 sorted_list = list(sorted(candidate_list, key=self.candidate_metric))
331 return sorted_list
332
333 def best_candidate(self, candidate_list):
334 if len(candidate_list) == 0:
335 return ABORT_SEARCH
336 if len(candidate_list) == 1:
337 return candidate_list[0]
338 sorted_list = self.sort_by_candidate_metric(candidate_list)
339 return sorted_list[0]
340
341 def graduate_strat(self, strat_type, sram_used, old_strat_data):
342 res = []
343 for old_strat, old_strat_set in old_strat_data:
344 if old_strat.sram_used + sram_used > self.sram_limit:
345 continue # This strategy is bad, drop it
346 if old_strat_set.max_sram_used > self.sram_limit:
347 continue # This strategy is bad, drop it
348 assert old_strat.strat == SchedulingStrategy.Unknown
349
350 new_strat = old_strat.clone()
351 new_strat.strat = strat_type
352 new_strat.sram_used = old_strat.sram_used + sram_used
353
354 if self.use_ifm_ofm_overlap:
355 overlap = calc_allowed_ofm_ifm_overlap_for_pass_list(
356 new_strat.strat, new_strat.passes, new_strat.block_configs
357 )
358 new_strat.sram_used -= overlap
359
360 new_strat_set = old_strat_set.clone_add_strategy(new_strat)
361 res.append((empty_strategy, new_strat_set))
362 return self.filter_pareto_frontier(res, remove_equally_good_candidates=True)
363
364 def append_sram(self, sram_used, old_strat_data):
365 res = []
366 for old_strat, strat_set in old_strat_data:
367 assert old_strat.strat == SchedulingStrategy.Unknown
368 assert old_strat.sram_used == 0
369 new_strat = old_strat.clone()
370 new_strat.sram_used = old_strat.sram_used + sram_used
371
372 res.append((new_strat, strat_set))
373 return res
374
375 def append_sram_block_config_performance_metrics(self, sram_used, block_config, metrics, old_strat_data):
376 res = []
377 for old_strat, strat_set in old_strat_data:
378 assert old_strat.strat == SchedulingStrategy.Unknown
379 new_strat = old_strat.clone()
380 bws, macs, cycles = metrics[:3]
381
382 new_strat.sram_used = old_strat.sram_used + sram_used
383 new_strat.block_configs = old_strat.block_configs + [block_config]
384 new_strat.bws = old_strat.bws + bws
385 new_strat.macs = old_strat.macs + macs
386 new_strat.cycles = old_strat.cycles + cycles
387 new_strat.bws, new_strat.macs, new_strat.cycles = npu_performance.collate_stats_for_cascaded_pass(
388 self.arch, new_strat.bws, new_strat.macs, new_strat.cycles
389 )
390
391 res.append((new_strat, strat_set))
392 return res
393
394 def append_sram_pass_block_config_performance_metrics_rewrite_list(
395 self, sram_used, new_pass, block_config, metrics, rewrite_list, old_strat_data
396 ):
397 res = []
398 for old_strat, strat_set in old_strat_data:
399 assert old_strat.strat == SchedulingStrategy.Unknown
400 new_strat = old_strat.clone()
401 bws, macs, cycles = metrics[:3]
402 new_strat.sram_used = old_strat.sram_used + sram_used
403 new_strat.block_configs = old_strat.block_configs + [block_config]
404 new_strat.bws = old_strat.bws + bws
405 new_strat.macs = old_strat.macs + macs
406 new_strat.cycles = old_strat.cycles + cycles
407 new_strat.passes = old_strat.passes + [new_pass]
408 new_strat.bws, new_strat.macs, new_strat.cycles = npu_performance.collate_stats_for_cascaded_pass(
409 self.arch, new_strat.bws, new_strat.macs, new_strat.cycles
410 )
411 new_strat.rewrite_list = old_strat.rewrite_list + rewrite_list
412 res.append((new_strat, strat_set))
413 return res
414
415 def append_sram_rewrite_list(self, sram_used, rewrite_list, old_strat_data):
416 res = []
417 for old_strat, strat_set in old_strat_data:
418 assert old_strat.strat == SchedulingStrategy.Unknown
419 new_strat = old_strat.clone()
420 new_strat.sram_used = old_strat.sram_used + sram_used
421 new_strat.rewrite_list = old_strat.rewrite_list + rewrite_list
422 res.append((new_strat, strat_set))
423 return res
424
425 def pass_to_strat(self, strat_data):
426 res = {}
427 for strat in strat_data[1].strats.values():
428 for ps in strat.passes:
429 res[ps] = strat
430 return res
431
432 def compatible_strats(self, a, b):
433 intersection = a.keys() & b.keys()
434 for k in intersection:
435 if a[k] != b[k]:
436 return False
437 return True
438
439 def collate_strats_for_passes(self, all_passes):
440 if len(all_passes) == 0:
441 return [(empty_strategy, StrategySet(dict()))]
442 if len(all_passes) == 1:
443 return all_passes[0] # save some space in the common case
444 all_strands = [[self.pass_to_strat(strat_data) for strat_data in strand] for strand in all_passes]
445 prev_combos = [dict()]
446 for j, strand in enumerate(all_strands):
447 new_combos = []
448 for i, alt in enumerate(strand):
449 for prev in prev_combos:
450 if self.compatible_strats(prev, alt):
451 cmb = dict(prev)
452 cmb.update(all_passes[j][i][1].strats)
453 new_combos.append(cmb)
454 prev_combos = new_combos
455
456 res = []
457 for d in prev_combos:
458 s = StrategySet(d)
459 s.update_statistics()
460 res.append((empty_strategy, s))
461 return res
462
463 def search_all_but_one_predecessor(self, ps, pred_pass, pred_pass_data):
464 # get the rest of the predecessors
465 other_predecessors = [pred for pred in ps.dag_predecessors if pred != pred_pass]
466 other_predecessor_data = self.search_pass_list(other_predecessors)
467
468 # pred strat data has an incomplete strategy, which we need
469 # to continue on, whereas the other ones have completed strategies.
470 # we need to merge these, but keep the incomplete strategy too.
471
472 res = []
473 for pred_pass_strat, pred_pass_strat_set in pred_pass_data:
474 all_strats = [
475 [(empty_strategy, pred_pass_strat_set)], # pred strat data but with a dummy empty strategy
476 other_predecessor_data, # this one is fine to use as-is
477 ]
478 collated_strat_data = self.collate_strats_for_passes(all_strats)
479 strat_data = [(pred_pass_strat, strat_set) for _, strat_set in collated_strat_data]
480 res.extend(strat_data)
481 return res
482
483 def calc_non_local_mem_usage(self):
484 ignore_subgraph_input_output_tensors = self.sg.placement == PassPlacement.Cpu
485 range_set = live_range.extract_live_ranges_from_passes(
486 self.sg,
487 self.mem_area,
488 mark_output_tensors_overlapping_with_input_tensors=True,
489 ignore_subgraph_input_output_tensors=ignore_subgraph_input_output_tensors,
490 )
491 range_dict = range_set.ranges
492
493 # find which ranges overlap passes but aren't input/outputs of the passes.
494 # these won't be counted by the dynamic programming search and must be counted in manually.
495 end_pos = max(ps.time for ps in self.sg.passes) + 2
496 mem_usage = np.zeros(end_pos) + self.sg.base_sram_used
497 non_local_mem_usage = np.zeros(end_pos, dtype=np.int64)
498
499 for tens, rng in range_dict.items():
500 storage_size = tens.storage_size()
501 assert tens.mem_area == self.mem_area
502 mem_usage[rng.start_time : rng.end_time] += storage_size
503
504 for ps in self.sg.passes:
505 local_mem_usage = 0
506 for tens in ps.inputs + ps.outputs + ps.intermediates:
507 if tens.mem_area != self.mem_area:
508 continue
509
510 local_mem_usage += tens.storage_size()
511
512 non_local_mem_usage[ps.time] = mem_usage[ps.time] - local_mem_usage
513
514 self.non_local_mem_usage = non_local_mem_usage
515
516 def search(self):
517 self.calc_non_local_mem_usage()
518 starting_passes = [ps for ps in self.sg.passes if not ps.successors]
519 strat_data = self.search_pass_list(starting_passes)
520
521 _, best_set = self.best_candidate(strat_data)
522
523 if self.verbose_pareto_frontier_schedules:
524 print(
525 "Scheduler searched %d combinations and found %d candidate schedules along the pareto frontier"
Diqing Zhong504d6b62020-09-17 12:21:10 +0200526 % (self.n_combinations_searched, len(strat_data))
Tim Hall79d07d22020-04-27 18:20:16 +0100527 )
528 for idx, (_, strat_set) in enumerate(strat_data):
529 extra = ""
530 if strat_set == best_set:
531 extra = "(Best candidate)"
532 print("Candidate", idx, extra)
533 memory_used = {MemArea.Sram: strat_set.max_sram_used}
534 stats_writer.print_performance_metrics_for_strat(
535 self.arch,
536 "",
537 strat_set.cycles,
538 strat_set.macs,
539 strat_set.bws,
540 self.nng.batch_size,
541 memory_used,
542 len(self.sg.passes),
543 len(strat_set.strats),
544 )
545
546 return best_set
547
548 def search_pass_list(self, pass_list):
549 all_strats = []
550 for ps in pass_list:
551 strat = self.search_output(ps)
552 all_strats.append(strat)
553 strat_data = self.collate_strats_for_passes(all_strats)
554 for strd in strat_data:
555 for ps in pass_list:
556 assert ps in strd[1].strats # should have strategies for everything we asked to search
557 return strat_data
558
559 def search_predecessors(self, ps):
560
561 # protect against graphs with loops. collate_strats_for_passes will sort this out later so that
562 # we have strats for all passes
563
564 pass_list = ps.dag_predecessors
565 strat_data = self.search_pass_list(pass_list)
566
567 return strat_data
568
569 @lru_cache(maxsize=None)
570 def search_output(self, ps):
571
572 assert ps in self.sg.passes
573 candidate_list = []
574
575 candidate_list.extend(self.search_weight_streaming_output(ps))
576
577 if self.options.use_ifm_streaming:
578 candidate_list.extend(self.search_ifm_streaming_output(ps))
579
580 best = self.filter_pareto_frontier(candidate_list, remove_equally_good_candidates=True)
581
582 if not best:
583 print(
584 "Warning: Dynamic search programming algorithm failed for pass %s, invoking fallback strategy"
585 % (ps.name,)
586 )
587 return self.search_predecessors(ps)
588
589 return best
590
591 def search_ifm_streaming_output(self, ps):
592 if ps.placement != PassPlacement.Npu:
593 return ABORT_SEARCH
594 if ps.npu_block_type not in self.ifm_stream_npu_blocks:
595 return ABORT_SEARCH
596 strat_data = self.search_ifm_streaming_body(ps, False)
597
598 sram_used = self.non_local_mem_usage[ps.time]
599 for tens in ps.outputs:
600 if tens.mem_area == self.mem_area:
601 sram_used += tens.storage_size()
602
603 return self.graduate_strat(SchedulingStrategy.IfmStream, sram_used, strat_data)
604
605 @lru_cache(maxsize=None)
606 def search_ifm_streaming_body(self, ps, force_outputs_to_fast_storage):
607 if ps.placement != PassPlacement.Npu:
608 return ABORT_SEARCH
609 if ps.npu_block_type not in self.ifm_stream_npu_blocks:
610 return ABORT_SEARCH
611 ifm_input_search_resuls = self.search_ifm_streaming_input(ps)
612 res = []
613
614 base_sram_used = 0
615 for tens in ps.intermediates:
616 if tens.mem_area == self.mem_area:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200617 if tens.purpose == TensorPurpose.Weights:
618 base_sram_used = tens.storage_size(self.arch.weight_estimation_scaling)
619 else:
620 base_sram_used += tens.storage_size()
Tim Hall79d07d22020-04-27 18:20:16 +0100621
622 all_block_configs = self.get_block_configs(ps)
623 for block_config in all_block_configs:
624 all_strats = []
625
626 if self.use_cascading:
627 all_strats.extend(self.search_ifm_streaming_partial(ps, block_config))
628
629 all_strats.extend(ifm_input_search_resuls)
630
631 rewrite_list = []
632 sram_used = base_sram_used
633
634 metrics = npu_performance.performance_metrics_for_pass(
635 self.arch,
636 ps,
637 block_config,
638 rewrite_list=rewrite_list,
639 force_outputs_to_fast_storage=force_outputs_to_fast_storage,
640 )
641
642 res.extend(
643 self.append_sram_pass_block_config_performance_metrics_rewrite_list(
644 sram_used, ps, block_config, metrics, rewrite_list, all_strats
645 )
646 )
647
648 self.n_combinations_searched += len(res)
649 res = self.filter_pareto_frontier(res, remove_equally_good_candidates=True)
650 return res
651
Diqing Zhong504d6b62020-09-17 12:21:10 +0200652 def avoid_for_cascading(self, pred_candidate):
Patrik Gustavssonc0bb8992020-08-11 16:45:35 +0200653 for op in pred_candidate.ops:
Diqing Zhong504d6b62020-09-17 12:21:10 +0200654 if (
655 op.type == "ConcatSliceWrite"
656 and self.arch.feature_map_storage_mem_area != self.arch.fast_storage_mem_area
657 ):
658 # For SRAM spilling, concat op is avoided as predecessor
Patrik Gustavssonc0bb8992020-08-11 16:45:35 +0200659 return True
Jacob Bohlin1a666972020-09-11 10:04:15 +0200660 if len(op.outputs) > 1 or len(op.outputs[0].consumer_list) > 1:
661 # The op has consumers in other subgraphs
662 return True
Patrik Gustavssonc0bb8992020-08-11 16:45:35 +0200663 return False
664
Tim Hall79d07d22020-04-27 18:20:16 +0100665 def search_ifm_streaming_partial(self, ps, block_config):
666 if ps.placement != PassPlacement.Npu:
667 return ABORT_SEARCH
668
669 if len(ps.inputs) < 1:
670 return ABORT_SEARCH
671
672 ifm_tensor = ps.ifm_tensor
673
674 if ifm_tensor is None:
675 return ABORT_SEARCH
676 if ifm_tensor.purpose != TensorPurpose.FeatureMap:
677 return ABORT_SEARCH
678 if not ifm_tensor.storage_shape or len(ifm_tensor.storage_shape) != 4:
679 return ABORT_SEARCH
680
681 pred_pass_list = []
682 for pred_candidate in ps.dag_predecessors:
683 if len(pred_candidate.outputs) == 1 and pred_candidate.outputs[0] == ifm_tensor:
684 # we found a predecessor that produces this IFM tensor
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200685 if not ifm_tensor.avoid_NHCWB16:
686 # and NHCWB16 format is not to be avoided
687 if len(pred_candidate.successors) == 1 and pred_candidate.successors[0] == ps:
688 # and it only has one successor, namely us
689 if pred_candidate.placement == PassPlacement.Npu:
690 if pred_candidate.npu_block_type in self.ifm_stream_npu_blocks:
691 # and it is on the Npu
Diqing Zhong504d6b62020-09-17 12:21:10 +0200692 if not self.avoid_for_cascading(pred_candidate):
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200693 # and fusable - it's a candidate
694 pred_pass_list.append(pred_candidate)
Tim Hall79d07d22020-04-27 18:20:16 +0100695
696 if not pred_pass_list:
697 return ABORT_SEARCH
698
699 all_candidates = []
700 for pred_pass in pred_pass_list:
701 # recurse into the next pass
702 ifm_strat_data = self.search_ifm_streaming_body(pred_pass, self.feature_maps_not_in_fast_storage)
703
704 strat_data = self.search_all_but_one_predecessor(ps, pred_pass, ifm_strat_data)
705 for strat_opt in strat_data:
706
707 pred_pass_block_config = strat_opt[0].block_configs[-1]
708 rolling_buffer_dims = npu_performance.rolling_buffer_dims_from_passes(
709 self.arch, pred_pass, pred_pass_block_config, ps, block_config
710 )
711 if rolling_buffer_dims is None:
712 continue # this does not pack properly, skip it.
713
714 sram_used = 0
715 for tens in ps.inputs:
716 if tens != ifm_tensor:
717 if tens.mem_area == self.mem_area:
718 sram_used += tens.storage_size()
719
720 rolling_buffer_y, rolling_buffer_x = rolling_buffer_dims
721
722 rewrite_list = [
723 (
724 SchedulerRewrite.ChangeTensorSubPurpose,
725 ifm_tensor,
726 TensorSubPurpose.RollingBufferY,
727 rolling_buffer_y,
728 None,
729 ps,
730 )
731 ]
732 sram_used += ifm_tensor.storage_size_for_sub_purpose(
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200733 self.arch, TensorSubPurpose.RollingBufferY, rolling_buffer_y, None
Tim Hall79d07d22020-04-27 18:20:16 +0100734 )
735
736 all_candidates.extend(self.append_sram_rewrite_list(sram_used, rewrite_list, [strat_opt]))
737
738 self.n_combinations_searched += len(all_candidates)
739 return all_candidates
740
741 def get_block_configs(self, ps):
742 if ps.placement != PassPlacement.Npu:
Diego Russoea6111a2020-04-14 18:41:58 +0100743 return [(1, 1, 1, 1)] # default
Tim Hall79d07d22020-04-27 18:20:16 +0100744
745 block_configs = find_block_configs_suitable_for_pass_and_shared_buffer(self.arch, ps)
746
747 # Take a limited number of the largest blocks
748 if self.arch.block_config_limit > 0:
749 # Sort by block area, followed by depth
750 block_configs.sort(key=lambda cfg: (cfg[0] * cfg[1]) << 8 | cfg[3], reverse=True)
751 bound = min(len(block_configs), self.arch.block_config_limit)
752 # We take 'n' from the fat end of the list, and 'n' from the thin end of the list.
753 tmp = block_configs[:bound]
754 tmp.extend(block_configs[max(bound, len(block_configs) - bound) :])
755 block_configs = tmp
756
757 return block_configs
758
759 def search_ifm_streaming_input(self, ps):
760 sram_used = 0
761 for tens in ps.inputs:
762 if tens.mem_area == self.mem_area:
763 sram_used += tens.storage_size()
764
765 return self.append_sram(sram_used, self.search_predecessors(ps))
766
767 def search_weight_streaming_output(self, ps):
768 strat_data = self.search_weight_streaming_body(ps)
769
770 sram_used = self.non_local_mem_usage[ps.time]
771 for tens in ps.outputs:
772 if tens.mem_area == self.mem_area:
773 sram_used += tens.storage_size()
774
775 return self.graduate_strat(SchedulingStrategy.WeightStream, sram_used, strat_data)
776
777 @lru_cache(maxsize=None)
778 def search_weight_streaming_body(self, ps):
779
780 strat_data = self.search_weight_streaming_input(ps)
781
782 res = []
783
784 all_block_configs = self.get_block_configs(ps)
785
786 for block_config in all_block_configs:
787
788 sram_used = 0
789 rewrite_list = []
790
791 for tens in ps.intermediates:
792 if tens.mem_area == self.mem_area:
793 if tens.purpose == TensorPurpose.Weights:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200794 sram_used += tens.storage_size_for_sub_purpose(
795 self.arch, TensorSubPurpose.DoubleBuffer, block_config[3]
796 )
Tim Hall79d07d22020-04-27 18:20:16 +0100797 rewrite_list.append(
798 (
799 SchedulerRewrite.ChangeTensorSubPurpose,
800 tens,
801 TensorSubPurpose.DoubleBuffer,
802 block_config[3],
803 None,
804 ps,
805 )
806 )
807 else:
808 sram_used += tens.storage_size()
809
810 metrics = npu_performance.performance_metrics_for_pass(
811 self.arch, ps, block_config, rewrite_list=rewrite_list
812 )
813
814 res.extend(
815 self.append_sram_pass_block_config_performance_metrics_rewrite_list(
816 sram_used, ps, block_config, metrics, rewrite_list, strat_data
817 )
818 )
819
820 self.n_combinations_searched += len(res)
821 res = self.filter_pareto_frontier(res, remove_equally_good_candidates=True)
822 return res
823
824 def search_weight_streaming_input(self, ps):
825 sram_used = 0
826 for tens in ps.inputs:
827 if tens.mem_area == self.mem_area:
828 sram_used += tens.storage_size()
829
830 return self.append_sram(sram_used, self.search_predecessors(ps))
831
832 def apply_result(self, strat_set, arch):
833 pass_to_cascaded_pass = dict()
834 for _, strat in strat_set.strats.items():
835 # rewrite the tensors that need this first. e.g. make rolling buffers
836 inputs = []
837 intermediates = []
838 outputs = []
839
840 for ps in strat.passes:
841 inputs += ps.inputs
842 intermediates += ps.intermediates
843 outputs += ps.outputs
844
845 for tens in set(inputs) & set(outputs):
846 # tensors that are in both sets are intermediates
847
848 # find pass with input/output tensor, and check if they are both placed on NPU
849 input_placement = None
850 output_placement = None
851 for ps in strat.passes:
852 if tens in ps.inputs:
853 input_placement = ps.placement
854 if tens in ps.outputs:
855 output_placement = ps.placement
856 if input_placement == output_placement == PassPlacement.Npu:
857 tens.set_format(TensorFormat.NHCWB16, arch)
858
859 intermediates.append(tens)
860 inputs.remove(tens)
861 outputs.remove(tens)
862
863 for rewrite_op, tens, sub_purpose, param_a, param_b, ps in strat.rewrite_list:
864 if rewrite_op == SchedulerRewrite.ChangeTensorSubPurpose:
865 tens.mem_area = self.arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200866 tens.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100867 tens.set_new_sub_purpose(sub_purpose, param_a, param_b)
868 else:
869 assert 0, "unknown rewrite_op " + str(rewrite_op)
870
871 is_element_wise = True
872 for ps in strat.passes:
873 assert ps.placement == strat.passes[0].placement
874 if not ps.is_element_wise:
875 is_element_wise = False
876 break
877
878 cascaded_pass = CascadedPass(
879 strat.passes[0].name,
880 strat.strat,
881 inputs,
882 intermediates,
883 outputs,
884 strat.passes,
885 strat.passes[0].placement,
886 is_element_wise,
887 )
888 assert strat.sram_used >= 0
889 cascaded_pass.sram_used = strat.sram_used
890
891 for idx, ps in enumerate(strat.passes):
892 assert ps not in pass_to_cascaded_pass
893 pass_to_cascaded_pass[ps] = cascaded_pass
894 ps.cascade = cascaded_pass
895 ps.block_config = strat.block_configs[idx]
896
897 if ps.placement == PassPlacement.Npu:
898 ps.shared_buffer = shared_buffer_allocation_for_pass_and_block_config(
899 self.arch, ps, ps.block_config
900 )
901 assert ps.shared_buffer is not None
902
Diqing Zhong504d6b62020-09-17 12:21:10 +0200903 sram_used = max(self.non_local_mem_usage[ps.time], 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100904 for op in ps.ops:
905 subgraph = op.attrs.get("subgraph")
906 if subgraph:
Diqing Zhong504d6b62020-09-17 12:21:10 +0200907 subgraph.base_sram_used = sram_used
Tim Hall79d07d22020-04-27 18:20:16 +0100908
909 # all passes should have a cascaded pass now
910 if len(pass_to_cascaded_pass) != len(self.sg.passes):
911 print(
912 "mismatch: we have %d passes, but only %d have cascaded passes associated"
913 % (len(self.sg.passes), len(pass_to_cascaded_pass))
914 )
915 for ps in self.sg.passes:
Diego Russoea6111a2020-04-14 18:41:58 +0100916 if ps not in pass_to_cascaded_pass:
Tim Hall79d07d22020-04-27 18:20:16 +0100917 print("%3d pass missing cascaded pass %s" % (ps.time, ps))
918
919 assert len(pass_to_cascaded_pass) == len(self.sg.passes)
Tim Hall79d07d22020-04-27 18:20:16 +0100920
Tim Hall79d07d22020-04-27 18:20:16 +0100921 cascaded_passes = []
Charles Xu19515e82020-06-10 10:48:33 +0200922 if self.sg.placement == PassPlacement.Cpu:
923 # Retain the pass order for CPU subgraph
924 cascaded_passes = [ps.cascade for ps in self.sg.passes]
925 else:
926 # we have all the passes, but we need to put them in order and build predecessor/successor links.
927 visit_pass_set = set()
Tim Hall79d07d22020-04-27 18:20:16 +0100928
Charles Xu19515e82020-06-10 10:48:33 +0200929 def visit_pass(ps):
930 if ps in visit_pass_set:
931 return
932 visit_pass_set.add(ps)
Tim Hall79d07d22020-04-27 18:20:16 +0100933
Charles Xu19515e82020-06-10 10:48:33 +0200934 cps = ps.cascade
935 dont_traverse = set(cps.passes)
Tim Hall79d07d22020-04-27 18:20:16 +0100936
Charles Xu19515e82020-06-10 10:48:33 +0200937 for ps in cps.passes:
938 for pred in ps.predecessors:
939 if pred in dont_traverse:
940 continue
941 visit_pass(pred)
Tim Hall79d07d22020-04-27 18:20:16 +0100942
Charles Xu19515e82020-06-10 10:48:33 +0200943 cascaded_passes.append(cps)
Tim Hall79d07d22020-04-27 18:20:16 +0100944
Charles Xu19515e82020-06-10 10:48:33 +0200945 starting_passes = [ps for ps in self.sg.passes if not ps.successors]
946 for ps in starting_passes:
947 visit_pass(ps)
Tim Hall79d07d22020-04-27 18:20:16 +0100948
949 # reorder so startup init cascaded passes come first
950 def is_startup_cascaded_pass(cps):
951 if not cps.passes:
952 return False
953 return cps.placement == PassPlacement.StartupInit
954
955 cascaded_passes = [cps for cps in cascaded_passes if is_startup_cascaded_pass(cps)] + [
956 cps for cps in cascaded_passes if not is_startup_cascaded_pass(cps)
957 ]
958
959 self.sg.cascaded_passes = cascaded_passes
960 self.sg.build_cascaded_pass_links()
961
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200962 # Check if NHCWB16 and/or fast storage can be used in between cascaded passes
963 # (NHCWB16 within cascaded passes has been handled earlier in this function)
964 if self.sg.placement == PassPlacement.Npu:
965 # Dictionary tensor -> list of ops, containing feature maps that can be attempted
966 # to be moved to fast storage
967 fast_storage_tensor_rewrites = {}
968 last_op_in_subgraph = self.sg.cascaded_passes[-1].passes[-1].primary_op
969 for ps in self.sg.cascaded_passes:
970 if ps.placement != PassPlacement.Npu:
971 continue
972 for output in ps.outputs:
973 if output.purpose != TensorPurpose.FeatureMap or output.avoid_NHCWB16:
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +0200974 continue
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200975
976 use_NHCWB16 = True
977 use_fast_storage = True
978 rewrites = []
979 for op in output.consumer_list:
980 if op is None:
981 use_NHCWB16 = False
982 use_fast_storage = False
Charles Xu7b8823f2020-05-29 13:53:10 +0200983 continue
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200984 if op.type == "ReduceSum" and output.dtype == DataType.int32:
985 use_NHCWB16 = False
986 elif op.type == "Reshape":
987 # Detect no-op reshapes by comparing their full input and output tensor shapes.
988 inshape = full_shape(4, op.inputs[0].shape, 1)
989 outshape = full_shape(4, op.outputs[0].shape, 1)
990 # Using NHCWB16 format for a no-op reshape is only an option if subsequent
991 # consumers do not also need to perform a reshape or if the OFM is going to
992 # be processed by CPU operations. No-op reshape consumers with empty lists
993 # (those that have no consumers, or null-consumers used as list terminators)
994 # must use normal NHWC output.
995 incompatible_consumers = [
996 (
997 not consumer.run_on_npu
998 or consumer.type == "Reshape"
999 or (consumer is last_op_in_subgraph)
1000 )
1001 for consumer in op.outputs[0].consumer_list
1002 if consumer is not None
1003 ]
1004 if (outshape == inshape) and incompatible_consumers and not any(incompatible_consumers):
1005 rewrites.append(op)
Tim Hallba695182020-08-26 17:27:19 +01001006 else:
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001007 use_NHCWB16 = False
1008 use_fast_storage = False
1009 use_NHCWB16 &= op.run_on_npu
1010 use_fast_storage &= op.run_on_npu
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +02001011
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001012 if use_fast_storage:
1013 fast_storage_tensor_rewrites[output] = rewrites
1014 if use_NHCWB16 and self.options.use_nhcwb16_between_cascaded_passes:
1015 output.set_format(TensorFormat.NHCWB16, arch)
1016 for rewrite_op in rewrites:
1017 rewrite_op.outputs[0].set_format(TensorFormat.NHCWB16, arch)
1018 if self.feature_maps_not_in_fast_storage:
1019 # Remember feature maps that can be moved to fast storage for later use
1020 # in use_fast_storage_for_feature_maps
1021 self.sg.scheduling_info["feature_map_rewrites"] = fast_storage_tensor_rewrites
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +02001022
Tim Hall79d07d22020-04-27 18:20:16 +01001023
1024def schedule_passes(nng, arch, options: SchedulerOptions):
1025
1026 for sg in nng.subgraphs:
1027 sg.base_sram_used = 0
1028
1029 for sg in nng.subgraphs:
1030 # re-entering the same nodes from different contexts requires us to
1031 # build a simplified directed acyclic (DAG) version of the graph to
1032 # use for traversal, rather than using a visit dictionary. this avoids
1033 # recursing infinitely due to loops.
1034 sg.build_pass_dag_predecessors()
1035
1036 dps = DynamicProgrammingScheduler(nng, sg, arch, arch.sram_size, options)
1037
1038 strat_set = dps.search()
1039
1040 dps.apply_result(strat_set, arch)
1041
1042 if options.verbose_schedule:
1043 sg.print_cascaded_passes()
Louis Verhaard0b9c9a32020-09-15 14:05:38 +02001044
1045
1046def _calc_tens_to_cps(sg, tensor_rewrites):
1047 # Determines for each tensor the list of affected cascaded passes, in terms of SRAM consumption.
1048 # Returns dictionary tensor -> list of cascaded passes
1049 # Note: if cascaded passes are A, B, C, D, and a tensor is output
1050 # of A and input to D, then it also consumes SRAM in passes B and C.
1051 if "tens_to_cps" in sg.scheduling_info:
1052 return sg.scheduling_info["tens_to_cps"]
1053 # Determine life-time of tensors
1054 min_index = {}
1055 max_index = {}
1056 index = 0
1057 cps_list = [cps for cps in sg.cascaded_passes if cps.placement == PassPlacement.Npu]
1058 for cps in cps_list:
1059 for tens in cps.inputs + cps.outputs:
1060 if tens in tensor_rewrites:
1061 min_index[tens] = min(index, min_index.get(tens, len(cps_list)))
1062 max_index[tens] = index
1063 index += 1
1064 # Convert to affected cps-es
1065 tens_to_cps = {}
1066 for tens in min_index:
1067 tens_to_cps[tens] = cps_list[min_index[tens] : max_index[tens] + 1]
1068 sg.scheduling_info["tens_to_cps"] = tens_to_cps
1069 return tens_to_cps
1070
1071
1072def use_fast_storage_for_feature_maps(sg, sram_limit, arch):
1073 # Attempts to use as much fast storage as possible for feature maps shared between cascaded passes.
1074 tensor_rewrites = sg.scheduling_info.get("feature_map_rewrites", {})
1075 tens_to_cps = _calc_tens_to_cps(sg, tensor_rewrites)
1076 # Sort tensors first on life-time (smallest first), then on size (biggest first)
1077 tens_list = sorted([(len(tens_to_cps[tens]), -tens.storage_size(), tens.name, tens) for tens in tens_to_cps])
1078 for _, _, _, tens in tens_list:
1079 cps_list = tens_to_cps[tens]
1080 if len(cps_list) <= 1:
1081 continue
1082 sz = tens.storage_size()
1083 fits_in_fast_storage = all([cps.sram_used + sz <= sram_limit for cps in cps_list])
1084 if fits_in_fast_storage:
1085 tens.mem_area = arch.fast_storage_mem_area
1086 tens.mem_type = MemType.Scratch_fast
1087 tens.set_new_sub_purpose(TensorSubPurpose.Standard, None, None)
1088 assert tens in tensor_rewrites
1089 # Also rewrite reshapes
1090 for rewrite_op in tensor_rewrites[tens]:
1091 tens2 = rewrite_op.outputs[0]
1092 tens2.mem_area = arch.fast_storage_mem_area
1093 tens2.mem_type = MemType.Scratch_fast
1094 tens2.set_new_sub_purpose(TensorSubPurpose.Standard, None, None)
1095 for cps in cps_list:
1096 cps.sram_used += sz
1097
1098
1099def undo_use_fast_storage(sg, arch):
1100 # Undoes the effects of a previous call to use_fast_storage_for_feature_maps
1101 tensor_rewrites = sg.scheduling_info.get("feature_map_rewrites", {})
1102 tens_to_cps = _calc_tens_to_cps(sg, tensor_rewrites)
1103 mem_area = arch.tensor_storage_mem_area[TensorPurpose.FeatureMap]
1104 for tens, cps_list in tens_to_cps.items():
1105 if tens.mem_type == MemType.Scratch_fast:
1106 sz = tens.storage_size()
1107 tens.mem_area = mem_area
1108 tens.mem_type = MemType.Scratch
1109 # Also undo reshapes
1110 for rewrite_op in tensor_rewrites[tens]:
1111 tens2 = rewrite_op.outputs[0]
1112 tens2.mem_area = mem_area
1113 tens2.mem_type = MemType.Scratch
1114 for cps in cps_list:
1115 cps.sram_used -= sz