Patrik Gustavsson | 2446e59 | 2021-02-11 08:36:12 +0100 | [diff] [blame] | 1 | # Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved. |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 16 | # Description: |
| 17 | # The scheduler costs various strategies for scheduling the network in order to select the block configuration. |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 18 | import copy |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 19 | import enum |
| 20 | from functools import lru_cache |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 21 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 22 | import numpy as np |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 23 | |
| 24 | from . import live_range |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 25 | from . import npu_performance |
| 26 | from . import stats_writer |
Fredrik Svedberg | 880e735 | 2020-08-25 11:31:47 +0200 | [diff] [blame] | 27 | from .data_type import DataType |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 28 | from .high_level_command_stream_generator import calc_allowed_ofm_ifm_overlap_for_pass_list |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 29 | from .nn_graph import CascadedPass |
| 30 | from .nn_graph import PassPlacement |
| 31 | from .nn_graph import SchedulerRewrite |
| 32 | from .nn_graph import SchedulingStrategy |
| 33 | from .npu_performance import make_bandwidth_array |
| 34 | from .npu_performance import make_cycles_array |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 35 | from .npu_performance import make_metrics_arrays |
| 36 | from .npu_performance import PassCycles |
| 37 | from .operation import NpuBlockType |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 38 | from .operation import Op |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 39 | from .operation import Operation |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 40 | from .shared_buffer_allocation import find_block_configs_suitable_for_pass_and_shared_buffer |
| 41 | from .shared_buffer_allocation import shared_buffer_allocation_for_pass_and_block_config |
| 42 | from .tensor import MemArea |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 43 | from .tensor import MemType |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 44 | from .tensor import TensorFormat |
| 45 | from .tensor import TensorPurpose |
| 46 | from .tensor import TensorSubPurpose |
Jacob Bohlin | 1a66697 | 2020-09-11 10:04:15 +0200 | [diff] [blame] | 47 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 48 | |
| 49 | class ParetoMetric(enum.Enum): |
| 50 | BwCycMem = 1 |
| 51 | BwCycMemBlkH = 2 |
| 52 | |
| 53 | def __str__(self): |
| 54 | return self.name |
| 55 | |
| 56 | |
| 57 | class SchedulerOptions: |
| 58 | def __init__( |
| 59 | self, |
| 60 | use_cascading=True, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 61 | verbose_schedule=False, |
| 62 | verbose_pareto_frontier_schedules=False, |
| 63 | use_ifm_streaming=True, |
| 64 | pareto_metric=ParetoMetric.BwCycMem, |
Charles Xu | 7b8823f | 2020-05-29 13:53:10 +0200 | [diff] [blame] | 65 | use_nhcwb16_between_cascaded_passes=True, |
Tim Hall | 14e8a20 | 2020-11-27 12:23:42 +0000 | [diff] [blame] | 66 | cache_bias_scale_tensor=True, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 67 | ): |
| 68 | self.use_cascading = use_cascading |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 69 | self.verbose_schedule = verbose_schedule |
| 70 | self.verbose_pareto_frontier_schedules = verbose_pareto_frontier_schedules |
| 71 | self.use_ifm_streaming = use_ifm_streaming |
| 72 | self.pareto_metric = pareto_metric |
Charles Xu | 7b8823f | 2020-05-29 13:53:10 +0200 | [diff] [blame] | 73 | self.use_nhcwb16_between_cascaded_passes = use_nhcwb16_between_cascaded_passes |
Tim Hall | 14e8a20 | 2020-11-27 12:23:42 +0000 | [diff] [blame] | 74 | self.cache_bias_scale_tensor = cache_bias_scale_tensor |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 75 | |
| 76 | def __str__(self): |
| 77 | return type(self).__name__ + ": " + str(self.__dict__) |
| 78 | |
| 79 | __repr__ = __str__ |
| 80 | |
| 81 | |
| 82 | class 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 |
Diqing Zhong | 69aadd0 | 2020-12-08 13:08:48 +0100 | [diff] [blame] | 109 | if self.macs != other.macs: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 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 | |
| 150 | class 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 |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 190 | if self.macs != other.macs: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 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 | |
| 211 | empty_strategy = Strategy( |
Diqing Zhong | 69aadd0 | 2020-12-08 13:08:48 +0100 | [diff] [blame] | 212 | SchedulingStrategy.Unknown, None, [], [], [], make_bandwidth_array(), 0, make_cycles_array(), 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 213 | ) |
| 214 | INFINITY = 1e30 |
| 215 | |
| 216 | ABORT_SEARCH = [] |
| 217 | |
| 218 | |
| 219 | def flatten_list_of_lists(lstlst): |
| 220 | lst = [] |
| 221 | for v in lstlst: |
| 222 | lst.extend(v) |
| 223 | return lst |
| 224 | |
| 225 | |
| 226 | class 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 Gustavsson | 3ab9452 | 2020-06-29 17:36:55 +0200 | [diff] [blame] | 237 | else: |
Patrik Gustavsson | fad90c2 | 2020-11-03 13:07:40 +0100 | [diff] [blame] | 238 | self.use_ifm_ofm_overlap = True |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 239 | |
| 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 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 250 | self.pareto_max_candidates = 16 |
| 251 | |
| 252 | self.ifm_stream_npu_blocks = set( |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 253 | (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling,) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 254 | ) |
| 255 | |
| 256 | num_pareto_metrics = 4 |
| 257 | view_values = ",".join(["d"] * num_pareto_metrics) |
| 258 | order_values = ["f%d" % (idx,) for idx in range(num_pareto_metrics)] |
| 259 | |
| 260 | def pareto_metric(self, candidate): |
| 261 | strat, strat_set = candidate |
| 262 | total_cycles = strat.cycles[PassCycles.Total] + strat_set.cycles[PassCycles.Total] |
| 263 | bws = strat.bws + strat_set.bws |
| 264 | last_block_height = 0 |
| 265 | if self.options.pareto_metric == ParetoMetric.BwCycMemBlkH and len(strat.block_configs) > 0: |
| 266 | last_block_height = strat.block_configs[-1][0] |
| 267 | |
| 268 | return ( |
| 269 | np.tensordot(bws, self.bandwidth_weights, axes=3) + total_cycles * self.cycles_weight, |
| 270 | strat_set.max_sram_used, |
| 271 | strat.sram_used, |
| 272 | last_block_height, |
| 273 | ) |
| 274 | |
| 275 | def filter_pareto_frontier(self, candidates, remove_equally_good_candidates): |
| 276 | |
| 277 | candidates = [cand for cand in candidates if max(cand[0].sram_used, cand[1].max_sram_used) <= self.sram_limit] |
| 278 | |
| 279 | if len(candidates) <= 1: |
| 280 | return candidates |
| 281 | assert remove_equally_good_candidates |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 282 | pareto_vals = np.zeros((len(candidates), DynamicProgrammingScheduler.num_pareto_metrics)) |
| 283 | ids = np.arange(len(candidates), dtype=np.int32) |
| 284 | for idx, cand in enumerate(candidates): |
| 285 | pareto_vals[idx] = self.pareto_metric(cand) |
| 286 | |
| 287 | sort_order = np.argsort( |
| 288 | pareto_vals.view(DynamicProgrammingScheduler.view_values), |
| 289 | order=DynamicProgrammingScheduler.order_values, |
| 290 | axis=0, |
| 291 | kind="stable", |
| 292 | ).flatten() |
| 293 | pareto_vals = pareto_vals[sort_order] |
| 294 | ids = ids[sort_order] |
| 295 | |
| 296 | pareto_frontier = [] |
| 297 | while len(ids) > 0: |
| 298 | pareto_frontier.append(candidates[ids[0]]) |
| 299 | not_dominated_by_first = (pareto_vals < pareto_vals[0]).any(axis=1) |
| 300 | ids = ids[not_dominated_by_first] |
| 301 | pareto_vals = pareto_vals[not_dominated_by_first] |
| 302 | |
| 303 | if len(pareto_frontier) > self.pareto_max_candidates: |
| 304 | pareto_frontier = self.sort_by_candidate_metric(pareto_frontier) |
| 305 | pareto_frontier = pareto_frontier[: self.pareto_max_candidates] |
| 306 | |
| 307 | return pareto_frontier |
| 308 | |
| 309 | def candidate_metric(self, candidate): |
| 310 | strat, strat_set = candidate |
| 311 | max_sram_used = max(strat_set.max_sram_used, strat.sram_used) |
| 312 | bws = strat.bws + strat_set.bws |
| 313 | total_cycles = strat.cycles[PassCycles.Total] + strat_set.cycles[PassCycles.Total] |
| 314 | |
| 315 | return ( |
| 316 | max_sram_used * self.max_sram_used_weight |
| 317 | + np.tensordot(bws, self.bandwidth_weights, axes=3) |
| 318 | + total_cycles * self.cycles_weight |
| 319 | ) |
| 320 | |
| 321 | def sort_by_candidate_metric(self, candidate_list): |
| 322 | sorted_list = list(sorted(candidate_list, key=self.candidate_metric)) |
| 323 | return sorted_list |
| 324 | |
| 325 | def best_candidate(self, candidate_list): |
| 326 | if len(candidate_list) == 0: |
| 327 | return ABORT_SEARCH |
| 328 | if len(candidate_list) == 1: |
| 329 | return candidate_list[0] |
| 330 | sorted_list = self.sort_by_candidate_metric(candidate_list) |
| 331 | return sorted_list[0] |
| 332 | |
| 333 | def graduate_strat(self, strat_type, sram_used, old_strat_data): |
| 334 | res = [] |
| 335 | for old_strat, old_strat_set in old_strat_data: |
| 336 | if old_strat.sram_used + sram_used > self.sram_limit: |
| 337 | continue # This strategy is bad, drop it |
| 338 | if old_strat_set.max_sram_used > self.sram_limit: |
| 339 | continue # This strategy is bad, drop it |
| 340 | assert old_strat.strat == SchedulingStrategy.Unknown |
| 341 | |
| 342 | new_strat = old_strat.clone() |
| 343 | new_strat.strat = strat_type |
| 344 | new_strat.sram_used = old_strat.sram_used + sram_used |
| 345 | |
| 346 | if self.use_ifm_ofm_overlap: |
| 347 | overlap = calc_allowed_ofm_ifm_overlap_for_pass_list( |
| 348 | new_strat.strat, new_strat.passes, new_strat.block_configs |
| 349 | ) |
| 350 | new_strat.sram_used -= overlap |
| 351 | |
| 352 | new_strat_set = old_strat_set.clone_add_strategy(new_strat) |
| 353 | res.append((empty_strategy, new_strat_set)) |
| 354 | return self.filter_pareto_frontier(res, remove_equally_good_candidates=True) |
| 355 | |
| 356 | def append_sram(self, sram_used, old_strat_data): |
| 357 | res = [] |
| 358 | for old_strat, strat_set in old_strat_data: |
| 359 | assert old_strat.strat == SchedulingStrategy.Unknown |
| 360 | assert old_strat.sram_used == 0 |
| 361 | new_strat = old_strat.clone() |
| 362 | new_strat.sram_used = old_strat.sram_used + sram_used |
| 363 | |
| 364 | res.append((new_strat, strat_set)) |
| 365 | return res |
| 366 | |
| 367 | def append_sram_block_config_performance_metrics(self, sram_used, block_config, metrics, old_strat_data): |
| 368 | res = [] |
| 369 | for old_strat, strat_set in old_strat_data: |
| 370 | assert old_strat.strat == SchedulingStrategy.Unknown |
| 371 | new_strat = old_strat.clone() |
| 372 | bws, macs, cycles = metrics[:3] |
| 373 | |
| 374 | new_strat.sram_used = old_strat.sram_used + sram_used |
| 375 | new_strat.block_configs = old_strat.block_configs + [block_config] |
| 376 | new_strat.bws = old_strat.bws + bws |
| 377 | new_strat.macs = old_strat.macs + macs |
| 378 | new_strat.cycles = old_strat.cycles + cycles |
| 379 | new_strat.bws, new_strat.macs, new_strat.cycles = npu_performance.collate_stats_for_cascaded_pass( |
| 380 | self.arch, new_strat.bws, new_strat.macs, new_strat.cycles |
| 381 | ) |
| 382 | |
| 383 | res.append((new_strat, strat_set)) |
| 384 | return res |
| 385 | |
| 386 | def append_sram_pass_block_config_performance_metrics_rewrite_list( |
| 387 | self, sram_used, new_pass, block_config, metrics, rewrite_list, old_strat_data |
| 388 | ): |
| 389 | res = [] |
| 390 | for old_strat, strat_set in old_strat_data: |
| 391 | assert old_strat.strat == SchedulingStrategy.Unknown |
| 392 | new_strat = old_strat.clone() |
| 393 | bws, macs, cycles = metrics[:3] |
| 394 | new_strat.sram_used = old_strat.sram_used + sram_used |
| 395 | new_strat.block_configs = old_strat.block_configs + [block_config] |
| 396 | new_strat.bws = old_strat.bws + bws |
| 397 | new_strat.macs = old_strat.macs + macs |
| 398 | new_strat.cycles = old_strat.cycles + cycles |
| 399 | new_strat.passes = old_strat.passes + [new_pass] |
| 400 | new_strat.bws, new_strat.macs, new_strat.cycles = npu_performance.collate_stats_for_cascaded_pass( |
| 401 | self.arch, new_strat.bws, new_strat.macs, new_strat.cycles |
| 402 | ) |
| 403 | new_strat.rewrite_list = old_strat.rewrite_list + rewrite_list |
| 404 | res.append((new_strat, strat_set)) |
| 405 | return res |
| 406 | |
| 407 | def append_sram_rewrite_list(self, sram_used, rewrite_list, old_strat_data): |
| 408 | res = [] |
| 409 | for old_strat, strat_set in old_strat_data: |
| 410 | assert old_strat.strat == SchedulingStrategy.Unknown |
| 411 | new_strat = old_strat.clone() |
| 412 | new_strat.sram_used = old_strat.sram_used + sram_used |
| 413 | new_strat.rewrite_list = old_strat.rewrite_list + rewrite_list |
| 414 | res.append((new_strat, strat_set)) |
| 415 | return res |
| 416 | |
| 417 | def pass_to_strat(self, strat_data): |
| 418 | res = {} |
| 419 | for strat in strat_data[1].strats.values(): |
| 420 | for ps in strat.passes: |
| 421 | res[ps] = strat |
| 422 | return res |
| 423 | |
| 424 | def compatible_strats(self, a, b): |
| 425 | intersection = a.keys() & b.keys() |
| 426 | for k in intersection: |
| 427 | if a[k] != b[k]: |
| 428 | return False |
| 429 | return True |
| 430 | |
| 431 | def collate_strats_for_passes(self, all_passes): |
| 432 | if len(all_passes) == 0: |
| 433 | return [(empty_strategy, StrategySet(dict()))] |
| 434 | if len(all_passes) == 1: |
| 435 | return all_passes[0] # save some space in the common case |
| 436 | all_strands = [[self.pass_to_strat(strat_data) for strat_data in strand] for strand in all_passes] |
| 437 | prev_combos = [dict()] |
| 438 | for j, strand in enumerate(all_strands): |
| 439 | new_combos = [] |
| 440 | for i, alt in enumerate(strand): |
| 441 | for prev in prev_combos: |
| 442 | if self.compatible_strats(prev, alt): |
| 443 | cmb = dict(prev) |
| 444 | cmb.update(all_passes[j][i][1].strats) |
| 445 | new_combos.append(cmb) |
| 446 | prev_combos = new_combos |
| 447 | |
| 448 | res = [] |
| 449 | for d in prev_combos: |
| 450 | s = StrategySet(d) |
| 451 | s.update_statistics() |
| 452 | res.append((empty_strategy, s)) |
| 453 | return res |
| 454 | |
| 455 | def search_all_but_one_predecessor(self, ps, pred_pass, pred_pass_data): |
| 456 | # get the rest of the predecessors |
| 457 | other_predecessors = [pred for pred in ps.dag_predecessors if pred != pred_pass] |
| 458 | other_predecessor_data = self.search_pass_list(other_predecessors) |
| 459 | |
| 460 | # pred strat data has an incomplete strategy, which we need |
| 461 | # to continue on, whereas the other ones have completed strategies. |
| 462 | # we need to merge these, but keep the incomplete strategy too. |
| 463 | |
| 464 | res = [] |
| 465 | for pred_pass_strat, pred_pass_strat_set in pred_pass_data: |
| 466 | all_strats = [ |
| 467 | [(empty_strategy, pred_pass_strat_set)], # pred strat data but with a dummy empty strategy |
| 468 | other_predecessor_data, # this one is fine to use as-is |
| 469 | ] |
| 470 | collated_strat_data = self.collate_strats_for_passes(all_strats) |
| 471 | strat_data = [(pred_pass_strat, strat_set) for _, strat_set in collated_strat_data] |
| 472 | res.extend(strat_data) |
| 473 | return res |
| 474 | |
| 475 | def calc_non_local_mem_usage(self): |
| 476 | ignore_subgraph_input_output_tensors = self.sg.placement == PassPlacement.Cpu |
| 477 | range_set = live_range.extract_live_ranges_from_passes( |
Patrik Gustavsson | a151f59 | 2020-10-16 13:59:52 +0200 | [diff] [blame] | 478 | self.sg, self.mem_area, ignore_subgraph_input_output_tensors=ignore_subgraph_input_output_tensors, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 479 | ) |
| 480 | range_dict = range_set.ranges |
| 481 | |
| 482 | # find which ranges overlap passes but aren't input/outputs of the passes. |
| 483 | # these won't be counted by the dynamic programming search and must be counted in manually. |
| 484 | end_pos = max(ps.time for ps in self.sg.passes) + 2 |
| 485 | mem_usage = np.zeros(end_pos) + self.sg.base_sram_used |
| 486 | non_local_mem_usage = np.zeros(end_pos, dtype=np.int64) |
| 487 | |
| 488 | for tens, rng in range_dict.items(): |
| 489 | storage_size = tens.storage_size() |
| 490 | assert tens.mem_area == self.mem_area |
| 491 | mem_usage[rng.start_time : rng.end_time] += storage_size |
| 492 | |
| 493 | for ps in self.sg.passes: |
| 494 | local_mem_usage = 0 |
| 495 | for tens in ps.inputs + ps.outputs + ps.intermediates: |
| 496 | if tens.mem_area != self.mem_area: |
| 497 | continue |
| 498 | |
| 499 | local_mem_usage += tens.storage_size() |
| 500 | |
| 501 | non_local_mem_usage[ps.time] = mem_usage[ps.time] - local_mem_usage |
| 502 | |
| 503 | self.non_local_mem_usage = non_local_mem_usage |
| 504 | |
| 505 | def search(self): |
| 506 | self.calc_non_local_mem_usage() |
| 507 | starting_passes = [ps for ps in self.sg.passes if not ps.successors] |
| 508 | strat_data = self.search_pass_list(starting_passes) |
| 509 | |
| 510 | _, best_set = self.best_candidate(strat_data) |
| 511 | |
| 512 | if self.verbose_pareto_frontier_schedules: |
| 513 | print( |
| 514 | "Scheduler searched %d combinations and found %d candidate schedules along the pareto frontier" |
Diqing Zhong | 504d6b6 | 2020-09-17 12:21:10 +0200 | [diff] [blame] | 515 | % (self.n_combinations_searched, len(strat_data)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 516 | ) |
| 517 | for idx, (_, strat_set) in enumerate(strat_data): |
| 518 | extra = "" |
| 519 | if strat_set == best_set: |
| 520 | extra = "(Best candidate)" |
| 521 | print("Candidate", idx, extra) |
| 522 | memory_used = {MemArea.Sram: strat_set.max_sram_used} |
| 523 | stats_writer.print_performance_metrics_for_strat( |
| 524 | self.arch, |
| 525 | "", |
| 526 | strat_set.cycles, |
| 527 | strat_set.macs, |
| 528 | strat_set.bws, |
| 529 | self.nng.batch_size, |
| 530 | memory_used, |
| 531 | len(self.sg.passes), |
| 532 | len(strat_set.strats), |
| 533 | ) |
| 534 | |
| 535 | return best_set |
| 536 | |
| 537 | def search_pass_list(self, pass_list): |
| 538 | all_strats = [] |
| 539 | for ps in pass_list: |
| 540 | strat = self.search_output(ps) |
| 541 | all_strats.append(strat) |
| 542 | strat_data = self.collate_strats_for_passes(all_strats) |
| 543 | for strd in strat_data: |
| 544 | for ps in pass_list: |
| 545 | assert ps in strd[1].strats # should have strategies for everything we asked to search |
| 546 | return strat_data |
| 547 | |
| 548 | def search_predecessors(self, ps): |
| 549 | |
| 550 | # protect against graphs with loops. collate_strats_for_passes will sort this out later so that |
| 551 | # we have strats for all passes |
| 552 | |
| 553 | pass_list = ps.dag_predecessors |
| 554 | strat_data = self.search_pass_list(pass_list) |
| 555 | |
| 556 | return strat_data |
| 557 | |
| 558 | @lru_cache(maxsize=None) |
| 559 | def search_output(self, ps): |
| 560 | |
| 561 | assert ps in self.sg.passes |
| 562 | candidate_list = [] |
| 563 | |
| 564 | candidate_list.extend(self.search_weight_streaming_output(ps)) |
| 565 | |
Patrik Gustavsson | 34b9dc1 | 2020-11-25 13:41:22 +0100 | [diff] [blame] | 566 | if self.options.use_ifm_streaming: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 567 | candidate_list.extend(self.search_ifm_streaming_output(ps)) |
| 568 | |
| 569 | best = self.filter_pareto_frontier(candidate_list, remove_equally_good_candidates=True) |
| 570 | |
| 571 | if not best: |
| 572 | print( |
| 573 | "Warning: Dynamic search programming algorithm failed for pass %s, invoking fallback strategy" |
| 574 | % (ps.name,) |
| 575 | ) |
| 576 | return self.search_predecessors(ps) |
| 577 | |
| 578 | return best |
| 579 | |
| 580 | def search_ifm_streaming_output(self, ps): |
| 581 | if ps.placement != PassPlacement.Npu: |
| 582 | return ABORT_SEARCH |
| 583 | if ps.npu_block_type not in self.ifm_stream_npu_blocks: |
| 584 | return ABORT_SEARCH |
| 585 | strat_data = self.search_ifm_streaming_body(ps, False) |
| 586 | |
| 587 | sram_used = self.non_local_mem_usage[ps.time] |
| 588 | for tens in ps.outputs: |
| 589 | if tens.mem_area == self.mem_area: |
| 590 | sram_used += tens.storage_size() |
| 591 | |
| 592 | return self.graduate_strat(SchedulingStrategy.IfmStream, sram_used, strat_data) |
| 593 | |
| 594 | @lru_cache(maxsize=None) |
| 595 | def search_ifm_streaming_body(self, ps, force_outputs_to_fast_storage): |
| 596 | if ps.placement != PassPlacement.Npu: |
| 597 | return ABORT_SEARCH |
| 598 | if ps.npu_block_type not in self.ifm_stream_npu_blocks: |
| 599 | return ABORT_SEARCH |
| 600 | ifm_input_search_resuls = self.search_ifm_streaming_input(ps) |
| 601 | res = [] |
| 602 | |
| 603 | base_sram_used = 0 |
| 604 | for tens in ps.intermediates: |
| 605 | if tens.mem_area == self.mem_area: |
Patrik Gustavsson | 90831bc | 2020-08-24 16:26:11 +0200 | [diff] [blame] | 606 | if tens.purpose == TensorPurpose.Weights: |
| 607 | base_sram_used = tens.storage_size(self.arch.weight_estimation_scaling) |
| 608 | else: |
| 609 | base_sram_used += tens.storage_size() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 610 | |
| 611 | all_block_configs = self.get_block_configs(ps) |
| 612 | for block_config in all_block_configs: |
| 613 | all_strats = [] |
| 614 | |
| 615 | if self.use_cascading: |
| 616 | all_strats.extend(self.search_ifm_streaming_partial(ps, block_config)) |
| 617 | |
| 618 | all_strats.extend(ifm_input_search_resuls) |
| 619 | |
| 620 | rewrite_list = [] |
| 621 | sram_used = base_sram_used |
| 622 | |
| 623 | metrics = npu_performance.performance_metrics_for_pass( |
| 624 | self.arch, |
| 625 | ps, |
| 626 | block_config, |
| 627 | rewrite_list=rewrite_list, |
| 628 | force_outputs_to_fast_storage=force_outputs_to_fast_storage, |
| 629 | ) |
| 630 | |
| 631 | res.extend( |
| 632 | self.append_sram_pass_block_config_performance_metrics_rewrite_list( |
| 633 | sram_used, ps, block_config, metrics, rewrite_list, all_strats |
| 634 | ) |
| 635 | ) |
| 636 | |
| 637 | self.n_combinations_searched += len(res) |
| 638 | res = self.filter_pareto_frontier(res, remove_equally_good_candidates=True) |
| 639 | return res |
| 640 | |
Diqing Zhong | 504d6b6 | 2020-09-17 12:21:10 +0200 | [diff] [blame] | 641 | def avoid_for_cascading(self, pred_candidate): |
Patrik Gustavsson | c0bb899 | 2020-08-11 16:45:35 +0200 | [diff] [blame] | 642 | for op in pred_candidate.ops: |
Diqing Zhong | 504d6b6 | 2020-09-17 12:21:10 +0200 | [diff] [blame] | 643 | if ( |
Patrik Gustavsson | 2446e59 | 2021-02-11 08:36:12 +0100 | [diff] [blame] | 644 | op.memory_function == Op.ConcatSliceWrite |
Diqing Zhong | 504d6b6 | 2020-09-17 12:21:10 +0200 | [diff] [blame] | 645 | and self.arch.feature_map_storage_mem_area != self.arch.fast_storage_mem_area |
| 646 | ): |
| 647 | # For SRAM spilling, concat op is avoided as predecessor |
Patrik Gustavsson | c0bb899 | 2020-08-11 16:45:35 +0200 | [diff] [blame] | 648 | return True |
Jacob Bohlin | 1a66697 | 2020-09-11 10:04:15 +0200 | [diff] [blame] | 649 | if len(op.outputs) > 1 or len(op.outputs[0].consumer_list) > 1: |
| 650 | # The op has consumers in other subgraphs |
| 651 | return True |
Patrik Gustavsson | c0bb899 | 2020-08-11 16:45:35 +0200 | [diff] [blame] | 652 | return False |
| 653 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 654 | def search_ifm_streaming_partial(self, ps, block_config): |
| 655 | if ps.placement != PassPlacement.Npu: |
| 656 | return ABORT_SEARCH |
| 657 | |
| 658 | if len(ps.inputs) < 1: |
| 659 | return ABORT_SEARCH |
| 660 | |
| 661 | ifm_tensor = ps.ifm_tensor |
| 662 | |
| 663 | if ifm_tensor is None: |
| 664 | return ABORT_SEARCH |
| 665 | if ifm_tensor.purpose != TensorPurpose.FeatureMap: |
| 666 | return ABORT_SEARCH |
| 667 | if not ifm_tensor.storage_shape or len(ifm_tensor.storage_shape) != 4: |
| 668 | return ABORT_SEARCH |
| 669 | |
| 670 | pred_pass_list = [] |
| 671 | for pred_candidate in ps.dag_predecessors: |
| 672 | if len(pred_candidate.outputs) == 1 and pred_candidate.outputs[0] == ifm_tensor: |
| 673 | # we found a predecessor that produces this IFM tensor |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 674 | if not ifm_tensor.avoid_NHCWB16: |
| 675 | # and NHCWB16 format is not to be avoided |
| 676 | if len(pred_candidate.successors) == 1 and pred_candidate.successors[0] == ps: |
| 677 | # and it only has one successor, namely us |
| 678 | if pred_candidate.placement == PassPlacement.Npu: |
| 679 | if pred_candidate.npu_block_type in self.ifm_stream_npu_blocks: |
| 680 | # and it is on the Npu |
Diqing Zhong | 504d6b6 | 2020-09-17 12:21:10 +0200 | [diff] [blame] | 681 | if not self.avoid_for_cascading(pred_candidate): |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 682 | # and fusable - it's a candidate |
| 683 | pred_pass_list.append(pred_candidate) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 684 | |
| 685 | if not pred_pass_list: |
| 686 | return ABORT_SEARCH |
| 687 | |
| 688 | all_candidates = [] |
| 689 | for pred_pass in pred_pass_list: |
| 690 | # recurse into the next pass |
Tim Hall | 1bd531d | 2020-11-01 20:59:36 +0000 | [diff] [blame] | 691 | ifm_strat_data = self.search_ifm_streaming_body(pred_pass, self.arch.is_spilling_enabled()) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 692 | |
| 693 | strat_data = self.search_all_but_one_predecessor(ps, pred_pass, ifm_strat_data) |
| 694 | for strat_opt in strat_data: |
| 695 | |
| 696 | pred_pass_block_config = strat_opt[0].block_configs[-1] |
| 697 | rolling_buffer_dims = npu_performance.rolling_buffer_dims_from_passes( |
| 698 | self.arch, pred_pass, pred_pass_block_config, ps, block_config |
| 699 | ) |
| 700 | if rolling_buffer_dims is None: |
| 701 | continue # this does not pack properly, skip it. |
| 702 | |
| 703 | sram_used = 0 |
| 704 | for tens in ps.inputs: |
| 705 | if tens != ifm_tensor: |
| 706 | if tens.mem_area == self.mem_area: |
| 707 | sram_used += tens.storage_size() |
| 708 | |
| 709 | rolling_buffer_y, rolling_buffer_x = rolling_buffer_dims |
| 710 | |
| 711 | rewrite_list = [ |
| 712 | ( |
| 713 | SchedulerRewrite.ChangeTensorSubPurpose, |
| 714 | ifm_tensor, |
| 715 | TensorSubPurpose.RollingBufferY, |
| 716 | rolling_buffer_y, |
| 717 | None, |
| 718 | ps, |
| 719 | ) |
| 720 | ] |
| 721 | sram_used += ifm_tensor.storage_size_for_sub_purpose( |
Patrik Gustavsson | 90831bc | 2020-08-24 16:26:11 +0200 | [diff] [blame] | 722 | self.arch, TensorSubPurpose.RollingBufferY, rolling_buffer_y, None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 723 | ) |
| 724 | |
| 725 | all_candidates.extend(self.append_sram_rewrite_list(sram_used, rewrite_list, [strat_opt])) |
| 726 | |
| 727 | self.n_combinations_searched += len(all_candidates) |
| 728 | return all_candidates |
| 729 | |
| 730 | def get_block_configs(self, ps): |
| 731 | if ps.placement != PassPlacement.Npu: |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 732 | return [(1, 1, 1, 1)] # default |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 733 | |
| 734 | block_configs = find_block_configs_suitable_for_pass_and_shared_buffer(self.arch, ps) |
| 735 | |
| 736 | # Take a limited number of the largest blocks |
| 737 | if self.arch.block_config_limit > 0: |
| 738 | # Sort by block area, followed by depth |
| 739 | block_configs.sort(key=lambda cfg: (cfg[0] * cfg[1]) << 8 | cfg[3], reverse=True) |
| 740 | bound = min(len(block_configs), self.arch.block_config_limit) |
| 741 | # We take 'n' from the fat end of the list, and 'n' from the thin end of the list. |
| 742 | tmp = block_configs[:bound] |
| 743 | tmp.extend(block_configs[max(bound, len(block_configs) - bound) :]) |
| 744 | block_configs = tmp |
| 745 | |
| 746 | return block_configs |
| 747 | |
| 748 | def search_ifm_streaming_input(self, ps): |
| 749 | sram_used = 0 |
| 750 | for tens in ps.inputs: |
| 751 | if tens.mem_area == self.mem_area: |
| 752 | sram_used += tens.storage_size() |
| 753 | |
| 754 | return self.append_sram(sram_used, self.search_predecessors(ps)) |
| 755 | |
| 756 | def search_weight_streaming_output(self, ps): |
| 757 | strat_data = self.search_weight_streaming_body(ps) |
| 758 | |
| 759 | sram_used = self.non_local_mem_usage[ps.time] |
| 760 | for tens in ps.outputs: |
| 761 | if tens.mem_area == self.mem_area: |
| 762 | sram_used += tens.storage_size() |
| 763 | |
| 764 | return self.graduate_strat(SchedulingStrategy.WeightStream, sram_used, strat_data) |
| 765 | |
| 766 | @lru_cache(maxsize=None) |
| 767 | def search_weight_streaming_body(self, ps): |
| 768 | |
| 769 | strat_data = self.search_weight_streaming_input(ps) |
| 770 | |
| 771 | res = [] |
| 772 | |
| 773 | all_block_configs = self.get_block_configs(ps) |
| 774 | |
| 775 | for block_config in all_block_configs: |
| 776 | |
| 777 | sram_used = 0 |
| 778 | rewrite_list = [] |
| 779 | |
| 780 | for tens in ps.intermediates: |
| 781 | if tens.mem_area == self.mem_area: |
| 782 | if tens.purpose == TensorPurpose.Weights: |
Patrik Gustavsson | 90831bc | 2020-08-24 16:26:11 +0200 | [diff] [blame] | 783 | sram_used += tens.storage_size_for_sub_purpose( |
| 784 | self.arch, TensorSubPurpose.DoubleBuffer, block_config[3] |
| 785 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 786 | rewrite_list.append( |
| 787 | ( |
| 788 | SchedulerRewrite.ChangeTensorSubPurpose, |
| 789 | tens, |
| 790 | TensorSubPurpose.DoubleBuffer, |
| 791 | block_config[3], |
| 792 | None, |
| 793 | ps, |
| 794 | ) |
| 795 | ) |
| 796 | else: |
| 797 | sram_used += tens.storage_size() |
| 798 | |
| 799 | metrics = npu_performance.performance_metrics_for_pass( |
| 800 | self.arch, ps, block_config, rewrite_list=rewrite_list |
| 801 | ) |
| 802 | |
| 803 | res.extend( |
| 804 | self.append_sram_pass_block_config_performance_metrics_rewrite_list( |
| 805 | sram_used, ps, block_config, metrics, rewrite_list, strat_data |
| 806 | ) |
| 807 | ) |
| 808 | |
| 809 | self.n_combinations_searched += len(res) |
| 810 | res = self.filter_pareto_frontier(res, remove_equally_good_candidates=True) |
| 811 | return res |
| 812 | |
| 813 | def search_weight_streaming_input(self, ps): |
| 814 | sram_used = 0 |
| 815 | for tens in ps.inputs: |
| 816 | if tens.mem_area == self.mem_area: |
| 817 | sram_used += tens.storage_size() |
| 818 | |
| 819 | return self.append_sram(sram_used, self.search_predecessors(ps)) |
| 820 | |
| 821 | def apply_result(self, strat_set, arch): |
| 822 | pass_to_cascaded_pass = dict() |
| 823 | for _, strat in strat_set.strats.items(): |
| 824 | # rewrite the tensors that need this first. e.g. make rolling buffers |
| 825 | inputs = [] |
| 826 | intermediates = [] |
| 827 | outputs = [] |
| 828 | |
| 829 | for ps in strat.passes: |
| 830 | inputs += ps.inputs |
| 831 | intermediates += ps.intermediates |
| 832 | outputs += ps.outputs |
| 833 | |
| 834 | for tens in set(inputs) & set(outputs): |
| 835 | # tensors that are in both sets are intermediates |
| 836 | |
| 837 | # find pass with input/output tensor, and check if they are both placed on NPU |
| 838 | input_placement = None |
| 839 | output_placement = None |
| 840 | for ps in strat.passes: |
| 841 | if tens in ps.inputs: |
| 842 | input_placement = ps.placement |
| 843 | if tens in ps.outputs: |
| 844 | output_placement = ps.placement |
| 845 | if input_placement == output_placement == PassPlacement.Npu: |
| 846 | tens.set_format(TensorFormat.NHCWB16, arch) |
| 847 | |
| 848 | intermediates.append(tens) |
| 849 | inputs.remove(tens) |
| 850 | outputs.remove(tens) |
| 851 | |
| 852 | for rewrite_op, tens, sub_purpose, param_a, param_b, ps in strat.rewrite_list: |
| 853 | if rewrite_op == SchedulerRewrite.ChangeTensorSubPurpose: |
| 854 | tens.mem_area = self.arch.fast_storage_mem_area |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 855 | tens.mem_type = MemType.Scratch_fast |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 856 | tens.set_new_sub_purpose(sub_purpose, param_a, param_b) |
| 857 | else: |
| 858 | assert 0, "unknown rewrite_op " + str(rewrite_op) |
| 859 | |
| 860 | is_element_wise = True |
| 861 | for ps in strat.passes: |
| 862 | assert ps.placement == strat.passes[0].placement |
| 863 | if not ps.is_element_wise: |
| 864 | is_element_wise = False |
| 865 | break |
| 866 | |
| 867 | cascaded_pass = CascadedPass( |
| 868 | strat.passes[0].name, |
| 869 | strat.strat, |
| 870 | inputs, |
| 871 | intermediates, |
| 872 | outputs, |
| 873 | strat.passes, |
| 874 | strat.passes[0].placement, |
| 875 | is_element_wise, |
| 876 | ) |
| 877 | assert strat.sram_used >= 0 |
| 878 | cascaded_pass.sram_used = strat.sram_used |
| 879 | |
| 880 | for idx, ps in enumerate(strat.passes): |
| 881 | assert ps not in pass_to_cascaded_pass |
| 882 | pass_to_cascaded_pass[ps] = cascaded_pass |
| 883 | ps.cascade = cascaded_pass |
| 884 | ps.block_config = strat.block_configs[idx] |
| 885 | |
| 886 | if ps.placement == PassPlacement.Npu: |
| 887 | ps.shared_buffer = shared_buffer_allocation_for_pass_and_block_config( |
| 888 | self.arch, ps, ps.block_config |
| 889 | ) |
| 890 | assert ps.shared_buffer is not None |
| 891 | |
Diqing Zhong | 504d6b6 | 2020-09-17 12:21:10 +0200 | [diff] [blame] | 892 | sram_used = max(self.non_local_mem_usage[ps.time], 0) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 893 | for op in ps.ops: |
| 894 | subgraph = op.attrs.get("subgraph") |
| 895 | if subgraph: |
Diqing Zhong | 504d6b6 | 2020-09-17 12:21:10 +0200 | [diff] [blame] | 896 | subgraph.base_sram_used = sram_used |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 897 | |
| 898 | # all passes should have a cascaded pass now |
| 899 | if len(pass_to_cascaded_pass) != len(self.sg.passes): |
| 900 | print( |
| 901 | "mismatch: we have %d passes, but only %d have cascaded passes associated" |
| 902 | % (len(self.sg.passes), len(pass_to_cascaded_pass)) |
| 903 | ) |
| 904 | for ps in self.sg.passes: |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 905 | if ps not in pass_to_cascaded_pass: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 906 | print("%3d pass missing cascaded pass %s" % (ps.time, ps)) |
| 907 | |
| 908 | assert len(pass_to_cascaded_pass) == len(self.sg.passes) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 909 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 910 | cascaded_passes = [] |
Charles Xu | 19515e8 | 2020-06-10 10:48:33 +0200 | [diff] [blame] | 911 | if self.sg.placement == PassPlacement.Cpu: |
| 912 | # Retain the pass order for CPU subgraph |
| 913 | cascaded_passes = [ps.cascade for ps in self.sg.passes] |
| 914 | else: |
| 915 | # we have all the passes, but we need to put them in order and build predecessor/successor links. |
| 916 | visit_pass_set = set() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 917 | |
Charles Xu | 19515e8 | 2020-06-10 10:48:33 +0200 | [diff] [blame] | 918 | def visit_pass(ps): |
| 919 | if ps in visit_pass_set: |
| 920 | return |
| 921 | visit_pass_set.add(ps) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 922 | |
Charles Xu | 19515e8 | 2020-06-10 10:48:33 +0200 | [diff] [blame] | 923 | cps = ps.cascade |
| 924 | dont_traverse = set(cps.passes) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 925 | |
Charles Xu | 19515e8 | 2020-06-10 10:48:33 +0200 | [diff] [blame] | 926 | for ps in cps.passes: |
| 927 | for pred in ps.predecessors: |
| 928 | if pred in dont_traverse: |
| 929 | continue |
| 930 | visit_pass(pred) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 931 | |
Charles Xu | 19515e8 | 2020-06-10 10:48:33 +0200 | [diff] [blame] | 932 | cascaded_passes.append(cps) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 933 | |
Charles Xu | 19515e8 | 2020-06-10 10:48:33 +0200 | [diff] [blame] | 934 | starting_passes = [ps for ps in self.sg.passes if not ps.successors] |
| 935 | for ps in starting_passes: |
| 936 | visit_pass(ps) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 937 | |
| 938 | # reorder so startup init cascaded passes come first |
| 939 | def is_startup_cascaded_pass(cps): |
| 940 | if not cps.passes: |
| 941 | return False |
| 942 | return cps.placement == PassPlacement.StartupInit |
| 943 | |
| 944 | cascaded_passes = [cps for cps in cascaded_passes if is_startup_cascaded_pass(cps)] + [ |
| 945 | cps for cps in cascaded_passes if not is_startup_cascaded_pass(cps) |
| 946 | ] |
| 947 | |
| 948 | self.sg.cascaded_passes = cascaded_passes |
| 949 | self.sg.build_cascaded_pass_links() |
| 950 | |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 951 | # Check if NHCWB16 and/or fast storage can be used in between cascaded passes |
| 952 | # (NHCWB16 within cascaded passes has been handled earlier in this function) |
| 953 | if self.sg.placement == PassPlacement.Npu: |
| 954 | # Dictionary tensor -> list of ops, containing feature maps that can be attempted |
| 955 | # to be moved to fast storage |
| 956 | fast_storage_tensor_rewrites = {} |
| 957 | last_op_in_subgraph = self.sg.cascaded_passes[-1].passes[-1].primary_op |
Fredrik Svedberg | fd31428 | 2020-11-06 13:48:15 +0100 | [diff] [blame] | 958 | # Memory only passes have no primary_op, so use the last op in ops |
| 959 | if last_op_in_subgraph is None: |
| 960 | last_op_in_subgraph = self.sg.cascaded_passes[-1].passes[-1].ops[-1] |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 961 | for ps in self.sg.cascaded_passes: |
| 962 | if ps.placement != PassPlacement.Npu: |
| 963 | continue |
| 964 | for output in ps.outputs: |
Patrik Gustavsson | d1836c7 | 2021-02-04 08:22:18 +0100 | [diff] [blame] | 965 | if output.purpose != TensorPurpose.FeatureMap: |
Patrik Gustavsson | feeb06d | 2020-04-22 12:53:47 +0200 | [diff] [blame] | 966 | continue |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 967 | |
Patrik Gustavsson | d1836c7 | 2021-02-04 08:22:18 +0100 | [diff] [blame] | 968 | use_NHCWB16 = not output.avoid_NHCWB16 |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 969 | use_fast_storage = True |
| 970 | rewrites = [] |
| 971 | for op in output.consumer_list: |
| 972 | if op is None: |
| 973 | use_NHCWB16 = False |
| 974 | use_fast_storage = False |
Charles Xu | 7b8823f | 2020-05-29 13:53:10 +0200 | [diff] [blame] | 975 | continue |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 976 | if op.type == Op.ReduceSum and output.dtype == DataType.int32: |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 977 | use_NHCWB16 = False |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 978 | elif op.type == Op.Reshape: |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 979 | # Using NHCWB16 format for a no-op reshape is only an option if subsequent |
| 980 | # consumers do not also need to perform a reshape or if the OFM is going to |
| 981 | # be processed by CPU operations. No-op reshape consumers with empty lists |
| 982 | # (those that have no consumers, or null-consumers used as list terminators) |
| 983 | # must use normal NHWC output. |
Fredrik Svedberg | fd31428 | 2020-11-06 13:48:15 +0100 | [diff] [blame] | 984 | def incompatible_consumers(oper): |
| 985 | if oper and oper.type == Op.Reshape: |
| 986 | for consumer in oper.outputs[0].consumer_list: |
| 987 | yield from incompatible_consumers(consumer) |
| 988 | yield not oper or not oper.run_on_npu or oper is last_op_in_subgraph |
| 989 | |
| 990 | if not any(incompatible_consumers(op)): |
| 991 | |
| 992 | def get_rewrites(oper): |
| 993 | if oper and oper.type == Op.Reshape: |
| 994 | for consumer in oper.outputs[0].consumer_list: |
| 995 | yield from get_rewrites(consumer) |
| 996 | yield oper |
| 997 | |
| 998 | rewrites.extend(get_rewrites(op)) |
| 999 | # Detect no-op reshapes by comparing their full input and output tensor shapes. |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 1000 | inshape = op.ifm_shapes[0] |
| 1001 | compatible_shape = [(inshape == oper.ofm_shapes[0]) for oper in get_rewrites(op)] |
Patrik Gustavsson | d1836c7 | 2021-02-04 08:22:18 +0100 | [diff] [blame] | 1002 | use_NHCWB16 &= compatible_shape and all(compatible_shape) |
Tim Hall | ba69518 | 2020-08-26 17:27:19 +0100 | [diff] [blame] | 1003 | else: |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 1004 | use_NHCWB16 = False |
| 1005 | use_fast_storage = False |
| 1006 | use_NHCWB16 &= op.run_on_npu |
| 1007 | use_fast_storage &= op.run_on_npu |
Patrik Gustavsson | feeb06d | 2020-04-22 12:53:47 +0200 | [diff] [blame] | 1008 | |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 1009 | if use_fast_storage: |
| 1010 | fast_storage_tensor_rewrites[output] = rewrites |
| 1011 | if use_NHCWB16 and self.options.use_nhcwb16_between_cascaded_passes: |
| 1012 | output.set_format(TensorFormat.NHCWB16, arch) |
| 1013 | for rewrite_op in rewrites: |
| 1014 | rewrite_op.outputs[0].set_format(TensorFormat.NHCWB16, arch) |
Tim Hall | 1bd531d | 2020-11-01 20:59:36 +0000 | [diff] [blame] | 1015 | if arch.is_spilling_enabled(): |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 1016 | # Remember feature maps that can be moved to fast storage for later use |
| 1017 | # in use_fast_storage_for_feature_maps |
| 1018 | self.sg.scheduling_info["feature_map_rewrites"] = fast_storage_tensor_rewrites |
Patrik Gustavsson | feeb06d | 2020-04-22 12:53:47 +0200 | [diff] [blame] | 1019 | |
Andreas Nevalainen | 27d36f0 | 2020-11-19 11:27:50 +0100 | [diff] [blame] | 1020 | |
| 1021 | def move_scales_to_fast_storage(nng, arch): |
| 1022 | for sg in nng.subgraphs: |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1023 | # IFM streamed ops reads bias tensors several times, move these to fast storage |
| 1024 | for cp in sg.cascaded_passes: |
| 1025 | if cp.strategy == SchedulingStrategy.IfmStream: |
Andreas Nevalainen | 27d36f0 | 2020-11-19 11:27:50 +0100 | [diff] [blame] | 1026 | # Calculate SRAM usage |
| 1027 | new_size = 0 |
| 1028 | all_tens = [] |
| 1029 | for ps in cp.passes: |
| 1030 | pass_tens = np.array([ps.ifm_tensor, ps.ifm2_tensor, ps.ofm_tensor, ps.weight_tensor]) |
| 1031 | pass_tens = np.append(pass_tens, ps.intermediates) |
| 1032 | for tens in pass_tens: |
| 1033 | if tens and tens.mem_area == MemArea.Sram and tens not in all_tens: |
| 1034 | all_tens.append(tens) |
| 1035 | new_size += tens.storage_size() |
| 1036 | |
| 1037 | cp.sram_used = new_size |
| 1038 | |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1039 | for ps in cp.passes: |
Andreas Nevalainen | ed67b88 | 2020-11-17 09:16:11 +0100 | [diff] [blame] | 1040 | if ps.scale_tensor: |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1041 | tens = ps.scale_tensor |
| 1042 | |
| 1043 | # Find op using scale tensor |
| 1044 | op = next((op for op in ps.ops if tens in op.inputs), None) |
| 1045 | assert op |
| 1046 | |
| 1047 | # Create fast storage tensor |
| 1048 | new_tens = tens.clone_into_fast_storage(arch) |
| 1049 | new_tens.consumer_list = tens.consumer_list.copy() |
| 1050 | new_tens.purpose = TensorPurpose.FSBias |
Andreas Nevalainen | ed67b88 | 2020-11-17 09:16:11 +0100 | [diff] [blame] | 1051 | new_tens_size = new_tens.storage_size() |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1052 | |
Andreas Nevalainen | 27d36f0 | 2020-11-19 11:27:50 +0100 | [diff] [blame] | 1053 | if (cp.sram_used + new_tens_size) <= arch.sram_size: |
Andreas Nevalainen | ed67b88 | 2020-11-17 09:16:11 +0100 | [diff] [blame] | 1054 | # Create DMA cmd |
| 1055 | dma_cmd = Operation(Op.DMA, tens.ops[0].name + "_dma") |
| 1056 | dma_cmd.inputs = [tens] |
| 1057 | dma_cmd.set_output_tensor(new_tens) |
| 1058 | dma_cmd.attrs["source"] = tens.mem_area |
| 1059 | dma_cmd.attrs["destination"] = new_tens.mem_area |
| 1060 | dma_cmd.run_on_npu = True |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1061 | |
Andreas Nevalainen | ed67b88 | 2020-11-17 09:16:11 +0100 | [diff] [blame] | 1062 | tens.consumer_list.clear() |
| 1063 | tens.consumer_list.append(dma_cmd) |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1064 | |
Andreas Nevalainen | ed67b88 | 2020-11-17 09:16:11 +0100 | [diff] [blame] | 1065 | # Replace tensor and op |
| 1066 | idx = op.inputs.index(tens) |
| 1067 | op.inputs[idx] = new_tens |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1068 | |
Andreas Nevalainen | ed67b88 | 2020-11-17 09:16:11 +0100 | [diff] [blame] | 1069 | ps.ops.insert(0, dma_cmd) |
| 1070 | ps.scale_tensor = new_tens |
| 1071 | ps.intermediates.append(new_tens) |
| 1072 | ps.cascade.intermediates.append(new_tens) |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1073 | |
Andreas Nevalainen | ed67b88 | 2020-11-17 09:16:11 +0100 | [diff] [blame] | 1074 | cp.sram_used += new_tens_size |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1075 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1076 | |
| 1077 | def schedule_passes(nng, arch, options: SchedulerOptions): |
| 1078 | |
| 1079 | for sg in nng.subgraphs: |
| 1080 | sg.base_sram_used = 0 |
| 1081 | |
| 1082 | for sg in nng.subgraphs: |
| 1083 | # re-entering the same nodes from different contexts requires us to |
| 1084 | # build a simplified directed acyclic (DAG) version of the graph to |
| 1085 | # use for traversal, rather than using a visit dictionary. this avoids |
| 1086 | # recursing infinitely due to loops. |
| 1087 | sg.build_pass_dag_predecessors() |
| 1088 | |
| 1089 | dps = DynamicProgrammingScheduler(nng, sg, arch, arch.sram_size, options) |
| 1090 | |
| 1091 | strat_set = dps.search() |
| 1092 | |
| 1093 | dps.apply_result(strat_set, arch) |
| 1094 | |
| 1095 | if options.verbose_schedule: |
| 1096 | sg.print_cascaded_passes() |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 1097 | |
| 1098 | |
| 1099 | def _calc_tens_to_cps(sg, tensor_rewrites): |
| 1100 | # Determines for each tensor the list of affected cascaded passes, in terms of SRAM consumption. |
| 1101 | # Returns dictionary tensor -> list of cascaded passes |
| 1102 | # Note: if cascaded passes are A, B, C, D, and a tensor is output |
| 1103 | # of A and input to D, then it also consumes SRAM in passes B and C. |
| 1104 | if "tens_to_cps" in sg.scheduling_info: |
| 1105 | return sg.scheduling_info["tens_to_cps"] |
| 1106 | # Determine life-time of tensors |
| 1107 | min_index = {} |
| 1108 | max_index = {} |
| 1109 | index = 0 |
| 1110 | cps_list = [cps for cps in sg.cascaded_passes if cps.placement == PassPlacement.Npu] |
| 1111 | for cps in cps_list: |
| 1112 | for tens in cps.inputs + cps.outputs: |
| 1113 | if tens in tensor_rewrites: |
| 1114 | min_index[tens] = min(index, min_index.get(tens, len(cps_list))) |
| 1115 | max_index[tens] = index |
| 1116 | index += 1 |
| 1117 | # Convert to affected cps-es |
| 1118 | tens_to_cps = {} |
| 1119 | for tens in min_index: |
| 1120 | tens_to_cps[tens] = cps_list[min_index[tens] : max_index[tens] + 1] |
| 1121 | sg.scheduling_info["tens_to_cps"] = tens_to_cps |
| 1122 | return tens_to_cps |
| 1123 | |
| 1124 | |
| 1125 | def use_fast_storage_for_feature_maps(sg, sram_limit, arch): |
| 1126 | # Attempts to use as much fast storage as possible for feature maps shared between cascaded passes. |
| 1127 | tensor_rewrites = sg.scheduling_info.get("feature_map_rewrites", {}) |
| 1128 | tens_to_cps = _calc_tens_to_cps(sg, tensor_rewrites) |
| 1129 | # Sort tensors first on life-time (smallest first), then on size (biggest first) |
| 1130 | tens_list = sorted([(len(tens_to_cps[tens]), -tens.storage_size(), tens.name, tens) for tens in tens_to_cps]) |
| 1131 | for _, _, _, tens in tens_list: |
| 1132 | cps_list = tens_to_cps[tens] |
Fredrik Svedberg | fd31428 | 2020-11-06 13:48:15 +0100 | [diff] [blame] | 1133 | if len(cps_list) < 1: |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 1134 | continue |
| 1135 | sz = tens.storage_size() |
| 1136 | fits_in_fast_storage = all([cps.sram_used + sz <= sram_limit for cps in cps_list]) |
| 1137 | if fits_in_fast_storage: |
| 1138 | tens.mem_area = arch.fast_storage_mem_area |
| 1139 | tens.mem_type = MemType.Scratch_fast |
| 1140 | tens.set_new_sub_purpose(TensorSubPurpose.Standard, None, None) |
| 1141 | assert tens in tensor_rewrites |
| 1142 | # Also rewrite reshapes |
| 1143 | for rewrite_op in tensor_rewrites[tens]: |
| 1144 | tens2 = rewrite_op.outputs[0] |
| 1145 | tens2.mem_area = arch.fast_storage_mem_area |
| 1146 | tens2.mem_type = MemType.Scratch_fast |
| 1147 | tens2.set_new_sub_purpose(TensorSubPurpose.Standard, None, None) |
| 1148 | for cps in cps_list: |
| 1149 | cps.sram_used += sz |
| 1150 | |
| 1151 | |
| 1152 | def undo_use_fast_storage(sg, arch): |
| 1153 | # Undoes the effects of a previous call to use_fast_storage_for_feature_maps |
| 1154 | tensor_rewrites = sg.scheduling_info.get("feature_map_rewrites", {}) |
| 1155 | tens_to_cps = _calc_tens_to_cps(sg, tensor_rewrites) |
| 1156 | mem_area = arch.tensor_storage_mem_area[TensorPurpose.FeatureMap] |
| 1157 | for tens, cps_list in tens_to_cps.items(): |
| 1158 | if tens.mem_type == MemType.Scratch_fast: |
| 1159 | sz = tens.storage_size() |
| 1160 | tens.mem_area = mem_area |
| 1161 | tens.mem_type = MemType.Scratch |
| 1162 | # Also undo reshapes |
| 1163 | for rewrite_op in tensor_rewrites[tens]: |
| 1164 | tens2 = rewrite_op.outputs[0] |
| 1165 | tens2.mem_area = mem_area |
| 1166 | tens2.mem_type = MemType.Scratch |
| 1167 | for cps in cps_list: |
| 1168 | cps.sram_used -= sz |