Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1 | # Copyright (C) 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 | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 16 | # |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 17 | # Description: |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 18 | # The scheduler creates and searches for an optimal plan for the network, selecting block configurations and |
| 19 | # subdivisions for the Operators |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 20 | # For Class name forward references for the type annotations. (see PEP 563). |
| 21 | from __future__ import annotations |
| 22 | |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 23 | import copy |
Johan Alfvén | 5e0ae55 | 2022-02-09 21:20:10 +0100 | [diff] [blame] | 24 | from collections import namedtuple |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 25 | from enum import auto |
| 26 | from enum import IntEnum |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 27 | from typing import Any |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 28 | from typing import Dict |
| 29 | from typing import List |
| 30 | from typing import Optional |
| 31 | from typing import Tuple |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 32 | from typing import TYPE_CHECKING |
| 33 | |
| 34 | # Import needed for Type annotations. Only import for Type checking to avoid run-time errors due to cyclic import. |
| 35 | if TYPE_CHECKING: |
| 36 | from .npu_performance import CycleCost |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 37 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 38 | import numpy as np |
| 39 | |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 40 | from . import live_range |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 41 | from . import npu_performance |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 42 | from . import tensor_allocation |
| 43 | from . import weight_compressor |
| 44 | from .architecture_allocator import ArchitectureBlockConfig |
| 45 | from .architecture_allocator import find_block_config |
| 46 | from .architecture_allocator import get_ifm_area_required |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 47 | from .architecture_features import ArchitectureFeatures |
| 48 | from .architecture_features import Block |
| 49 | from .cascade_builder import CascadeBuilder |
| 50 | from .cascade_builder import CascadeInfo |
Fredrik Svedberg | 880e735 | 2020-08-25 11:31:47 +0200 | [diff] [blame] | 51 | from .data_type import DataType |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 52 | from .nn_graph import CascadedPass |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 53 | from .nn_graph import Graph |
| 54 | from .nn_graph import Pass |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 55 | from .nn_graph import PassPlacement |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 56 | from .nn_graph import SchedulingStrategy |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 57 | from .nn_graph import Subgraph |
| 58 | from .numeric_util import round_down |
| 59 | from .numeric_util import round_up |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 60 | from .operation import NpuBlockType |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 61 | from .operation import Op |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 62 | from .shape4d import Shape4D |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 63 | from .tensor import MemArea |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 64 | from .tensor import MemType |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 65 | from .tensor import Tensor |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 66 | from .tensor import TensorFormat |
| 67 | from .tensor import TensorPurpose |
| 68 | from .tensor import TensorSubPurpose |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 69 | from .weight_compressor import NpuWeightTensor |
Jacob Bohlin | 1a66697 | 2020-09-11 10:04:15 +0200 | [diff] [blame] | 70 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 71 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 72 | def shape_for_format(shape: Shape4D, tensor_format: TensorFormat) -> Shape4D: |
| 73 | if tensor_format == TensorFormat.NHCWB16: |
| 74 | return shape.with_depth(round_up(shape.depth, 16)) |
| 75 | |
| 76 | return shape |
| 77 | |
| 78 | |
| 79 | class OptimizationStrategy(IntEnum): |
| 80 | """Enum defining the different optimization strategies for the Scheduler""" |
| 81 | |
| 82 | Size = auto() |
| 83 | Performance = auto() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 84 | |
| 85 | def __str__(self): |
| 86 | return self.name |
| 87 | |
| 88 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 89 | class SchedulerOpInfo: |
| 90 | """Contains metadata about a SchedulerOperation that is unique to one Schedule""" |
| 91 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 92 | def __init__( |
| 93 | self, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 94 | block_config: ArchitectureBlockConfig, |
| 95 | weights_size: int, |
| 96 | stripe_input: Shape4D, |
| 97 | stripe_input2: Optional[Shape4D], |
| 98 | stripe: Shape4D, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 99 | ): |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 100 | self.block_config = block_config |
| 101 | self.weights_size = weights_size |
| 102 | self.stripe_input = stripe_input |
| 103 | self.stripe_input2 = stripe_input2 |
| 104 | self.stripe = stripe |
| 105 | self.cascade = 0 # Assigned by CascadeBuilder. 0 means not part of a cascade |
| 106 | self.time_index = None # Set by update_op_memory_snapshot |
| 107 | self.ofm_depth_slices: List[int] = [0, stripe.depth] |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 108 | self.npu_weights_tensor: Optional[NpuWeightTensor] = None |
| 109 | self.npu_scales_tensor: Optional[NpuWeightTensor] = None |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 110 | self.buffered_weight_tensors: List[Tensor] = [] |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 111 | self.cycles: Optional[CycleCost] = None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 112 | self.slack_buffering_cycles = 0 |
| 113 | self.slack_buffering_memory = 0 |
| 114 | self.full_weight_transfer_cycles = 0 |
| 115 | |
| 116 | def copy(self): |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 117 | res = SchedulerOpInfo( |
| 118 | self.block_config, |
| 119 | self.weights_size, |
| 120 | self.stripe_input, |
| 121 | self.stripe_input2, |
| 122 | self.stripe, |
| 123 | ) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 124 | res.cascade = self.cascade |
| 125 | return res |
| 126 | |
| 127 | def __str__(self): |
| 128 | res = f"\t\tBlock Config = {self.block_config}\n" |
| 129 | res += f"\t\tOFM Block = {self.block_config.ofm_block}\n" |
| 130 | res += f"\t\tIFM Stripe = {self.stripe_input}\n" |
| 131 | res += f"\t\tIFM2 Stripe = {self.stripe_input2}\n" |
| 132 | res += f"\t\tOFM Stripe = {self.stripe}\n" |
| 133 | res += f"\t\tEncoded Weights = {self.npu_weights_tensor and len(self.npu_weights_tensor.buffer)} bytes\n" |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 134 | for idx, tens in enumerate(self.buffered_weight_tensors): |
| 135 | res += f"\t\tWeight buffer{idx + 1} = {tens.storage_size()} bytes\n" |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 136 | res += f"\t\tDepth slices = {self.ofm_depth_slices}\n" |
| 137 | res += f"\t\tAssigned Cascade = {self.cascade}" |
| 138 | return res |
| 139 | |
| 140 | |
| 141 | class SchedulerOptions: |
| 142 | """Contains options for the Scheduler""" |
| 143 | |
| 144 | def __init__( |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 145 | self, |
| 146 | optimization_strategy, |
| 147 | sram_target, |
| 148 | verbose_schedule, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 149 | ): |
| 150 | self.optimization_strategy = optimization_strategy |
| 151 | self.optimization_sram_limit = sram_target |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 152 | self.verbose_schedule = verbose_schedule |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 153 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 154 | def __str__(self) -> str: |
| 155 | return f"{type(self).__name__}: {str(self.__dict__)}" |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 156 | |
| 157 | __repr__ = __str__ |
| 158 | |
| 159 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 160 | class SchedulerTensor: |
| 161 | def __init__(self, shape, dt, mem_area, _format): |
| 162 | self.dtype = dt |
| 163 | self.mem_area = mem_area |
| 164 | self.shape = shape |
| 165 | self.format = _format |
| 166 | self.connection = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 167 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 168 | |
| 169 | class SchedulerOperation: |
| 170 | """Scheduler internal representation of 'Operation' |
| 171 | This class can be seen as a node within the Scheduler Graph representation |
| 172 | """ |
| 173 | |
| 174 | def __init__(self, ps: Pass, arch: ArchitectureFeatures, nng: Graph): |
| 175 | self.arch = arch |
| 176 | self.parent_ps = ps |
| 177 | self.parent_op = ps.primary_op |
| 178 | self.name = ps.primary_op.name |
| 179 | self.op_type = ps.primary_op.type |
| 180 | self.activation = ps.primary_op.activation |
| 181 | self.kernel = ps.primary_op.kernel |
Tim Hall | 3c5cfe9 | 2022-03-16 16:31:57 +0000 | [diff] [blame] | 182 | self.resampling_mode = ps.primary_op.ifm_resampling_mode |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 183 | self.uses_scalar = ps.primary_op.ifm2 is not None and ( |
| 184 | ps.primary_op.ifm.shape == [] or ps.primary_op.ifm2.shape == [] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 185 | ) |
erik.andersson@arm.com | 6b2a0b4 | 2022-03-22 15:35:30 +0100 | [diff] [blame^] | 186 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 187 | self.ifm_ublock = arch.ifm_ublock |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 188 | |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 189 | self.ifm = SchedulerTensor( |
| 190 | ps.ifm_shapes[0], |
| 191 | ps.ifm_tensor.dtype, |
| 192 | ps.ifm_tensor.mem_area, |
| 193 | ps.ifm_tensor.format, |
| 194 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 195 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 196 | self.ifm2 = None |
| 197 | if ps.ifm2_tensor: |
| 198 | self.ifm2 = SchedulerTensor( |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 199 | ps.ifm_shapes[1], |
| 200 | ps.ifm2_tensor.dtype, |
| 201 | ps.ifm2_tensor.mem_area, |
| 202 | ps.ifm2_tensor.format, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 203 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 204 | |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 205 | self.ofm = SchedulerTensor( |
| 206 | ps.ofm_shapes[0], |
| 207 | ps.ofm_tensor.dtype, |
| 208 | ps.ofm_tensor.mem_area, |
| 209 | ps.ofm_tensor.format, |
| 210 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 211 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 212 | # Input volume width and height required to produce the smallest possible stripe |
| 213 | self.min_stripe_input_w, self.min_stripe_input_h = self._calculate_min_stripe_input() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 214 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 215 | # Flags that marks whether this SchedulerOperation requires full IFM/OFM |
| 216 | self.requires_full_ifm = False |
| 217 | self.requires_full_ifm2 = False |
| 218 | self.requires_full_ofm = False |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 219 | |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 220 | self.evicted_fms_size = 0 |
| 221 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 222 | self.index = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 223 | |
erik.andersson@arm.com | 6b2a0b4 | 2022-03-22 15:35:30 +0100 | [diff] [blame^] | 224 | # Perform an IFM swap for certain binary elementwise operators |
| 225 | # in order to enable cascading, if the SchedOp conforms to |
| 226 | # Elementwise cascading rules. |
| 227 | if self.op_type.is_binary_elementwise_op() and CascadeBuilder.element_wise_cascading_conformity(self): |
| 228 | ifm1 = ps.ifm_tensor |
| 229 | ifm2 = ps.ifm2_tensor |
| 230 | ofm = ps.ofm_tensor |
| 231 | assert ifm1.elements() > 0 |
| 232 | assert ifm2.elements() > 0 |
| 233 | |
| 234 | if ( |
| 235 | # The non-constant IFM should be the primary input |
| 236 | (ifm1.ops[0].type == Op.Const and ifm2.ops[0].type != Op.Const) |
| 237 | # The non-broadcasted IFM should be the primary input |
| 238 | or (ifm1.shape != ofm.shape and ifm2.shape == ofm.shape) |
| 239 | ): |
| 240 | self.ifm, self.ifm2 = self.ifm2, self.ifm |
| 241 | |
| 242 | self.parent_ps.ifm_shapes = self.parent_ps.ifm_shapes[::-1] |
| 243 | self.parent_ps.inputs = self.parent_ps.inputs[::-1] |
| 244 | self.parent_ps.ifm_tensor, self.parent_ps.ifm2_tensor = ( |
| 245 | self.parent_ps.ifm2_tensor, |
| 246 | self.parent_ps.ifm_tensor, |
| 247 | ) |
| 248 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 249 | def add_ifm_connection(self, conn: "Connection"): |
| 250 | """Add input connection to another SchedulerOperation or Subgraph Input""" |
| 251 | conn.consumers.append(self) |
| 252 | self.ifm.connection = conn |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 253 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 254 | def add_ifm2_connection(self, conn: "Connection"): |
| 255 | """Add input connection to another SchedulerOperation or Subgraph Input""" |
| 256 | if self.ifm2: |
| 257 | conn.consumers.append(self) |
| 258 | self.ifm2.connection = conn |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 259 | else: |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 260 | assert False, f"Trying to set an IFM2 Connection to {self} which has no IFM2" |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 261 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 262 | def add_ofm_connection(self, conn: "Connection"): |
| 263 | """Add output connection to another SchedulerOperation or Subgraph Output""" |
| 264 | conn.producers.append(self) |
| 265 | self.ofm.connection = conn |
| 266 | |
| 267 | def get_dependants(self): |
| 268 | """Returns a list of the Ops that depend on this Operation's OFM""" |
| 269 | return self.ofm.connection.consumers |
| 270 | |
| 271 | def ifm_size_in_bytes(self) -> int: |
| 272 | """Returns size of the IFM in bytes""" |
| 273 | ifm_storage_shape = shape_for_format(self.ifm.shape, self.ifm.format) |
| 274 | return round_up(ifm_storage_shape.elements() * self.ifm.dtype.size_in_bytes(), Tensor.AllocationQuantum) |
| 275 | |
| 276 | def ifm2_size_in_bytes(self) -> int: |
| 277 | """Returns size of the IFM2 in bytes""" |
| 278 | if self.ifm2: |
| 279 | ifm2_storage_shape = shape_for_format(self.ifm2.shape, self.ifm2.format) |
| 280 | return round_up(ifm2_storage_shape.elements() * self.ifm2.dtype.size_in_bytes(), Tensor.AllocationQuantum) |
| 281 | |
| 282 | return 0 |
| 283 | |
| 284 | def ofm_size_in_bytes(self) -> int: |
| 285 | """Returns size of the OFM in bytes""" |
| 286 | ofm_storage_shape = shape_for_format(self.ofm.shape, self.ofm.format) |
| 287 | return round_up(ofm_storage_shape.elements() * self.ofm.dtype.size_in_bytes(), Tensor.AllocationQuantum) |
| 288 | |
| 289 | def create_scheduler_info(self, nng: Graph, stripe: Shape4D) -> SchedulerOpInfo: |
| 290 | """Returns schedule info about this SchedulerOperation based on how many ofm elements it should produce""" |
| 291 | ifm_shape = self.ifm.shape |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 292 | ifm2_shape = self.ifm2.shape if self.ifm2 is not None else None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 293 | ofm_shape = stripe |
| 294 | |
| 295 | if ofm_shape != self.ofm.shape: |
| 296 | # Striped Op - Need to calculate stripe input volume |
| 297 | stripe_input_w, stripe_input_h = self._get_stripe_input_requirement(stripe) |
| 298 | # Ensure stripe input volume is within the full IFM volume |
| 299 | stripe_input_h = min(stripe_input_h, self.ifm.shape.height) |
| 300 | stripe_input_w = min(stripe_input_w, self.ifm.shape.width) |
| 301 | ifm_shape = ifm_shape.with_hw(stripe_input_h, stripe_input_w) |
| 302 | |
| 303 | if self.ifm2: |
| 304 | stripe_input2_h = min(stripe_input_h, self.ifm2.shape.height) |
| 305 | stripe_input2_w = min(stripe_input_w, self.ifm2.shape.width) |
| 306 | ifm2_shape = ifm2_shape.with_hw(stripe_input2_h, stripe_input2_w) |
| 307 | |
| 308 | block_config = self._get_block_config(ifm_shape, ifm2_shape, self.uses_scalar, ofm_shape) |
| 309 | |
| 310 | scheduler_op_info = SchedulerOpInfo(block_config, 0, ifm_shape, ifm2_shape, ofm_shape) |
| 311 | if self.parent_op.weights: |
| 312 | # Default full-depth weight encoding with no buffering |
Tim Hall | d784af7 | 2021-06-08 21:25:57 +0100 | [diff] [blame] | 313 | ( |
| 314 | scheduler_op_info.npu_weights_tensor, |
| 315 | scheduler_op_info.npu_scales_tensor, |
| 316 | ) = weight_compressor.encode_weight_and_scale_tensor( |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 317 | self.arch, |
| 318 | self.parent_op, |
| 319 | self.parent_op.weights, |
| 320 | self.parent_op.bias, |
| 321 | self.kernel, |
| 322 | block_config, |
| 323 | [0, self.ofm.shape.depth], |
| 324 | ) |
| 325 | |
| 326 | self.parent_ps.block_config = block_config.old_style_representation() |
| 327 | return scheduler_op_info |
| 328 | |
| 329 | def _get_stripe_input_requirement(self, stripe_shape: Shape4D) -> Tuple[int, int]: |
| 330 | """Returns the amount of IFM required to produce the stripe with shape:'stripe_shape'""" |
| 331 | ofm_shape_to_produce = Block.from_shape(stripe_shape.as_list()) |
| 332 | |
Fredrik Svedberg | 3ff7a4a | 2021-09-29 10:08:04 +0200 | [diff] [blame] | 333 | return get_ifm_area_required(ofm_shape_to_produce, self.kernel, self.resampling_mode) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 334 | |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 335 | def _calculate_min_stripe_input(self) -> Tuple[int, int]: |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 336 | # Calculate the input volume required height and width for the smallest possible stripe (h,w = 1,1) |
| 337 | min_stripe = self.ofm.shape.with_hw(1, 1) |
| 338 | return self._get_stripe_input_requirement(min_stripe) |
| 339 | |
| 340 | def _get_block_config( |
| 341 | self, ifm_shape: Shape4D, ifm2_shape: Optional[Shape4D], uses_scalar: bool, ofm_shape: Shape4D |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 342 | ) -> Optional[ArchitectureBlockConfig]: |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 343 | # Returns a block config and SHRAM layout |
| 344 | lut_banks = 2 if self.parent_op.activation_lut else 0 |
| 345 | return find_block_config( |
| 346 | self.arch, |
| 347 | self.op_type.npu_block_type, |
| 348 | ofm_shape, |
| 349 | ifm_shape, |
| 350 | ifm2_shape, |
| 351 | uses_scalar, |
| 352 | self.ifm.dtype.size_in_bits(), |
| 353 | self.kernel, |
| 354 | lut_banks, |
| 355 | self.parent_op.has_scaling(), |
| 356 | self.resampling_mode, |
| 357 | ) |
| 358 | |
| 359 | |
| 360 | class Connection: |
| 361 | """Scheduler internal representation of a Tensor that connects two SchedulerOperations |
| 362 | This class can be seen as an edge within the Scheduler Graph representation |
| 363 | """ |
| 364 | |
| 365 | def __init__(self, tensor: Tensor): |
| 366 | self.parent_tens = tensor |
| 367 | |
| 368 | # SchedulerOperation relationships |
| 369 | self.producers: List[SchedulerOperation] = [] |
| 370 | self.consumers: List[SchedulerOperation] = [] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 371 | |
| 372 | def __str__(self): |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 373 | return f"<Connection {self.parent_tens.name}>" |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 374 | |
| 375 | __repr__ = __str__ |
| 376 | |
| 377 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 378 | class Schedule: |
| 379 | """Class that contains a solution of how to schedule an NPU subgraph and its cost""" |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 380 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 381 | def __init__(self, sg: Subgraph, label: str): |
| 382 | self.sg = sg |
| 383 | self.label = label |
| 384 | self.cost_map: Dict[SchedulerOperation, SchedulerOpInfo] = {} |
| 385 | self.cascades: Dict[int, CascadeInfo] = {} |
| 386 | self.fast_storage_peak_usage = 0 |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 387 | self.memory_snapshot: Optional[List[int]] = None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 388 | |
| 389 | @property |
| 390 | def name(self): |
| 391 | return f"{self.sg.name}_{self.label}" |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 392 | |
| 393 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 394 | class Scheduler: |
| 395 | """Main class of the Vela Scheduling""" |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 396 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 397 | def __init__(self, nng: Graph, sg: Subgraph, arch: ArchitectureFeatures, options: SchedulerOptions): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 398 | self.nng = nng |
| 399 | self.sg = sg |
| 400 | self.arch = arch |
Ayaan Masood | b801dda | 2022-02-22 11:28:55 +0000 | [diff] [blame] | 401 | self.sched_ops: List[SchedulerOperation] = [] |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 402 | self.max_schedule: Optional[Schedule] = None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 403 | self.scheduler_options = options |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 404 | |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 405 | self.scratched_fms: Dict[Tensor, Any] = {} |
| 406 | self.evicted_fms: List[live_range.LiveRange] = [] |
| 407 | |
Johan Alfvén | 5e0ae55 | 2022-02-09 21:20:10 +0100 | [diff] [blame] | 408 | def avoid_nhcwb16_for_ofm(self, tens, ps, arch): |
| 409 | # Only run this check for opt strategy Size |
| 410 | if self.scheduler_options.optimization_strategy == OptimizationStrategy.Performance: |
| 411 | return False |
| 412 | |
| 413 | op = ps.primary_op |
| 414 | if not op.type.is_elementwise_op(): |
| 415 | return False |
| 416 | |
| 417 | depth = op.ofm_shapes[0][-1] |
| 418 | if (depth % 16) == 0: |
| 419 | return False |
| 420 | |
| 421 | # Check if overwriting the inputs can be allowed |
| 422 | OpShapeTens = namedtuple("OpShapeTens", ["op_shape", "tens"]) |
| 423 | outp = OpShapeTens(op.ofm_shapes[0], op.ofm) |
| 424 | inps = [] |
| 425 | if op.ifm is not None: |
| 426 | inps.append(OpShapeTens(op.ifm_shapes[0], op.ifm)) |
| 427 | if op.ifm2 is not None: |
| 428 | inps.append(OpShapeTens(op.ifm_shapes[1], op.ifm2)) |
| 429 | |
| 430 | # Find an input tensor that can be overwritten by the output |
| 431 | for inp in inps: |
| 432 | if ( |
| 433 | # check op input and output shapes allow overlapping |
| 434 | inp.op_shape == outp.op_shape |
| 435 | # check input tensor is valid |
| 436 | and inp.tens is not None |
| 437 | and inp.tens.shape != [] |
| 438 | # check input and output tensors are compatible |
| 439 | and inp.tens.format == outp.tens.format |
| 440 | and inp.tens.dtype == outp.tens.dtype |
| 441 | ): |
| 442 | if inp.tens.format == TensorFormat.NHWC: |
| 443 | return True |
| 444 | |
| 445 | return False |
| 446 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 447 | def create_scheduler_representation(self, arch: ArchitectureFeatures): |
| 448 | """Creates a Scheduler Graph representation""" |
| 449 | # Temporary dict for creating connections between the Operations |
| 450 | connections: Dict[Tensor, Connection] = {} |
| 451 | # Memory required for the largest FeatureMap that has to be full |
| 452 | min_memory_req = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 453 | for ps in self.sg.passes: |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 454 | if ps.primary_op: |
| 455 | # Set tensor format to NHCWB16 for output FeatureMaps, if possible |
Louis Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 456 | for output in ps.outputs: |
Jacob Bohlin | a5e8c1c | 2021-06-14 13:33:39 +0200 | [diff] [blame] | 457 | if output in self.sg.output_tensors or output.purpose != TensorPurpose.FeatureMap: |
Patrik Gustavsson | feeb06d | 2020-04-22 12:53:47 +0200 | [diff] [blame] | 458 | continue |
Johan Alfvén | 5e0ae55 | 2022-02-09 21:20:10 +0100 | [diff] [blame] | 459 | |
| 460 | if output.needs_linear_format: |
| 461 | continue |
| 462 | |
| 463 | if self.avoid_nhcwb16_for_ofm(output, ps, arch): |
| 464 | output.needs_linear_format = True |
| 465 | continue |
| 466 | |
| 467 | output.set_format(TensorFormat.NHCWB16, arch) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 468 | |
| 469 | # Create SchedulerOperations |
| 470 | op = SchedulerOperation(ps, arch, self.nng) |
| 471 | op.index = len(self.sched_ops) |
| 472 | |
| 473 | # Make connections |
| 474 | if ps.ifm_tensor not in connections: |
| 475 | connections[ps.ifm_tensor] = Connection(ps.ifm_tensor) |
| 476 | if ps.ifm2_tensor and ps.ifm2_tensor not in connections: |
| 477 | connections[ps.ifm2_tensor] = Connection(ps.ifm2_tensor) |
| 478 | if ps.ofm_tensor not in connections: |
| 479 | connections[ps.ofm_tensor] = Connection(ps.ofm_tensor) |
| 480 | |
| 481 | op.add_ifm_connection(connections[ps.ifm_tensor]) |
| 482 | if ps.ifm2_tensor: |
| 483 | op.add_ifm2_connection(connections[ps.ifm2_tensor]) |
| 484 | op.add_ofm_connection(connections[ps.ofm_tensor]) |
| 485 | |
| 486 | # Set requirements on the ifm/ofm buffers |
| 487 | self.sched_ops.append(op) |
| 488 | if ps.ifm_tensor in self.sg.input_tensors: |
| 489 | # This Op consumes a subgraph input |
| 490 | op.requires_full_ifm = True |
| 491 | if ps.ifm2_tensor and ps.ifm2_tensor in self.sg.input_tensors: |
| 492 | # This Op consumes a subgraph input |
| 493 | op.requires_full_ifm2 = True |
| 494 | if ps.ofm_tensor in self.sg.output_tensors: |
| 495 | # This Op produces a subgraph output |
| 496 | op.requires_full_ofm = True |
| 497 | if ps.ifm_tensor.needs_linear_format: |
| 498 | op.requires_full_ifm = True |
| 499 | if ps.ifm2_tensor and ps.ifm2_tensor.needs_linear_format: |
| 500 | op.requires_full_ifm2 = True |
| 501 | if ps.ofm_tensor.needs_linear_format or ps.primary_op.memory_function == Op.ConcatSliceWrite: |
| 502 | op.requires_full_ofm = True |
| 503 | if len(ps.primary_op.outputs) > 1 or len(ps.primary_op.outputs[0].consumer_list) > 1: |
| 504 | # Op has multiple outputs or consumers - requires full OFM |
| 505 | op.requires_full_ofm = True |
| 506 | |
| 507 | # Check memory requirements if this Op requires any full FeatureMaps |
| 508 | op_memory_req = 0 |
| 509 | if op.requires_full_ifm: |
| 510 | op_memory_req += op.ifm_size_in_bytes() |
| 511 | if op.requires_full_ifm2: |
| 512 | op_memory_req += op.ifm2_size_in_bytes() |
| 513 | if op.requires_full_ofm: |
| 514 | op_memory_req += op.ofm_size_in_bytes() |
| 515 | |
| 516 | min_memory_req = max(op_memory_req, min_memory_req) |
| 517 | |
| 518 | # Theoretical minimum required memory - used to guide the cascade building |
| 519 | self.min_memory_req = min_memory_req |
| 520 | |
| 521 | def create_initial_schedule(self) -> Schedule: |
| 522 | """Creates an initial schedule with no cascading or buffering of any kind""" |
| 523 | schedule = Schedule(self.sg, "MAX") |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 524 | for op in self.sched_ops: |
| 525 | cost = op.create_scheduler_info(self.nng, op.ofm.shape) |
| 526 | cost.cycles = self.estimate_op_performance(op, cost.block_config, op.ofm.shape.depth) |
| 527 | schedule.cost_map[op] = cost |
| 528 | |
| 529 | return schedule |
| 530 | |
| 531 | def update_op_memory_snapshot(self, schedule: Schedule): |
| 532 | memories_list = [(self.arch.fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))] |
| 533 | |
| 534 | # Collect live ranges from tensors |
| 535 | lr_graph = live_range.LiveRangeGraph() |
| 536 | for mem_area, mem_type_set in memories_list: |
| 537 | live_range.extract_live_ranges_from_cascaded_passes( |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 538 | self.nng.get_root_subgraph(), |
| 539 | mem_area, |
| 540 | mem_type_set, |
| 541 | lr_graph, |
| 542 | Tensor.AllocationQuantum, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 543 | ) |
| 544 | |
| 545 | # Populate time-array with memory used by live ranges |
| 546 | temporal_usage = lr_graph.get_temporal_memory_usage(self.arch.fast_storage_mem_area) |
| 547 | schedule.memory_snapshot = temporal_usage |
| 548 | |
| 549 | # Set the peak memory usage |
| 550 | schedule.fast_storage_peak_usage = max(temporal_usage, default=0) |
| 551 | |
| 552 | def estimate_op_performance(self, op: SchedulerOperation, block_config, ofm_depth): |
| 553 | query = npu_performance.PerformanceQuery(op.op_type.npu_block_type) |
| 554 | query.ifm_shape = op.ifm.shape |
| 555 | query.ifm_memory_area = op.ifm.mem_area |
| 556 | query.ifm_bits = op.ifm.dtype.size_in_bits() |
| 557 | query.ifm_format = op.ifm.format |
| 558 | query.ifm2_shape = op.ifm2 and op.ifm2.shape |
| 559 | query.ifm2_memory_area = op.ifm2 and op.ifm2.mem_area |
| 560 | query.ifm2_bits = op.ifm2 and op.ifm2.dtype.size_in_bits() |
| 561 | query.ifm2_format = op.ifm2 and op.ifm2.format |
| 562 | query.ofm_shape = op.ofm.shape.with_depth(ofm_depth) |
| 563 | query.ofm_memory_area = op.ofm.mem_area |
| 564 | query.ofm_bits = op.ofm.dtype.size_in_bits() |
| 565 | query.ofm_format = op.ofm.format |
| 566 | if op.parent_op.bias: |
| 567 | query.const_shape = Shape4D(1, 1, 1, op.ofm.shape.depth) |
| 568 | query.const_memory_area = self.arch.fast_storage_mem_area |
| 569 | |
| 570 | query.kernel = op.kernel |
| 571 | query.config = block_config |
| 572 | |
| 573 | return npu_performance.measure_cycle_cost(self.arch, op.op_type, op.activation and op.activation.op_type, query) |
| 574 | |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 575 | def estimate_element_access(self, op: SchedulerOperation, block_config, ofm_depth): |
| 576 | query = npu_performance.PerformanceQuery(op.op_type.npu_block_type) |
| 577 | query.ifm_shape = op.ifm.shape |
| 578 | query.ifm_memory_area = op.ifm.mem_area |
| 579 | query.ifm_bits = op.ifm.dtype.size_in_bits() |
| 580 | query.ifm_format = op.ifm.format |
| 581 | query.ifm2_shape = op.ifm2 and op.ifm2.shape |
| 582 | query.ifm2_memory_area = op.ifm2 and op.ifm2.mem_area |
| 583 | query.ifm2_bits = op.ifm2 and op.ifm2.dtype.size_in_bits() |
| 584 | query.ifm2_format = op.ifm2 and op.ifm2.format |
| 585 | query.ofm_shape = op.ofm.shape.with_depth(ofm_depth) |
| 586 | query.ofm_memory_area = op.ofm.mem_area |
| 587 | query.ofm_bits = op.ofm.dtype.size_in_bits() |
| 588 | query.ofm_format = op.ofm.format |
| 589 | if op.parent_op.bias: |
| 590 | query.const_shape = Shape4D(1, 1, 1, op.ofm.shape.depth) |
| 591 | query.const_memory_area = self.arch.fast_storage_mem_area |
| 592 | |
| 593 | query.kernel = op.kernel |
| 594 | query.config = block_config |
| 595 | |
| 596 | return npu_performance.measure_element_access(self.arch, query) |
| 597 | |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 598 | def propose_schedule_buffering(self, ref_schedule: Schedule, staging_limit_bytes): |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 599 | """Create a buffered schedule""" |
| 600 | buffered_schedule = Schedule(self.sg, f"{ref_schedule.label}_BUFFERED") |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 601 | |
| 602 | prev_op = None |
| 603 | for sched_op in self.sched_ops: |
| 604 | if sched_op not in ref_schedule.cost_map: |
| 605 | # sched_op is not part of this sub-schedule - skip |
| 606 | continue |
| 607 | |
| 608 | self.propose_operator_buffering(sched_op, prev_op, buffered_schedule, ref_schedule, staging_limit_bytes) |
| 609 | prev_op = sched_op |
| 610 | |
| 611 | return buffered_schedule |
| 612 | |
| 613 | def propose_operator_buffering( |
| 614 | self, |
| 615 | sched_op: SchedulerOperation, |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 616 | prev_op: Optional[SchedulerOperation], |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 617 | buffered_schedule: Schedule, |
| 618 | ref_schedule: Schedule, |
| 619 | staging_limit_bytes, |
| 620 | ): |
| 621 | # Mild recursion might mean this Op has already been seen |
| 622 | if sched_op in buffered_schedule.cost_map: |
| 623 | return |
| 624 | |
| 625 | # Take the reference schedule as default costings for this schedule |
| 626 | ref_cost = ref_schedule.cost_map[sched_op] |
| 627 | cost = copy.copy(ref_cost) |
| 628 | cost.slack_buffering_cycles = ref_cost.cycles.op_cycles |
| 629 | memory_snapshot = ref_schedule.memory_snapshot |
| 630 | ref_memory_usage = memory_snapshot[ref_cost.time_index] if ref_cost.time_index < len(memory_snapshot) else 0 |
| 631 | cost.slack_buffering_memory = staging_limit_bytes - ref_memory_usage |
| 632 | buffered_schedule.cost_map[sched_op] = cost |
| 633 | |
| 634 | # Attempt weight buffering on anything with a weights tensor |
| 635 | if sched_op.parent_op.weights: |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 636 | buffer_limit_bytes = cost.slack_buffering_memory |
| 637 | |
| 638 | # If applicable apply size limitation, but keep it within reason (ratio 1.5). |
| 639 | # Size limitation is used when use_fast_storage_for_feature_maps have |
| 640 | # detected that there are fms that do not fit in fast storage. |
| 641 | if sched_op.evicted_fms_size and ((buffer_limit_bytes / sched_op.evicted_fms_size) >= 1.5): |
| 642 | buffer_limit_bytes -= sched_op.evicted_fms_size |
| 643 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 644 | self.propose_weight_buffering( |
| 645 | sched_op.parent_op.weights, |
| 646 | sched_op.parent_op.bias, |
| 647 | sched_op, |
| 648 | prev_op, |
| 649 | buffered_schedule, |
| 650 | ref_schedule, |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 651 | buffer_limit_bytes, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 652 | ) |
| 653 | |
| 654 | return cost |
| 655 | |
| 656 | def weights_needs_dma(self, weight_tensor): |
| 657 | if weight_tensor and weight_tensor.mem_type not in (MemType.Scratch, MemType.Scratch_fast): |
| 658 | # Weights are in permanent storage |
| 659 | # Only when permanent storage differs from feature map storage, there is a point moving the data |
| 660 | if ( |
| 661 | weight_tensor.mem_area in (MemArea.Dram, MemArea.OffChipFlash) |
| 662 | and self.arch.permanent_storage_mem_area != self.arch.fast_storage_mem_area |
| 663 | ): |
| 664 | return True |
| 665 | return False |
| 666 | |
| 667 | def propose_weight_buffering( |
| 668 | self, |
| 669 | weight_tensor, |
| 670 | scale_tensor, |
| 671 | sched_op: SchedulerOperation, |
| 672 | prev_op: SchedulerOperation, |
| 673 | buffered_schedule: Schedule, |
| 674 | ref_schedule: Schedule, |
| 675 | buffer_limit_bytes, |
| 676 | ): |
| 677 | cost = buffered_schedule.cost_map[sched_op] |
| 678 | prev_cost = buffered_schedule.cost_map.get(prev_op) |
| 679 | ref_cost = ref_schedule.cost_map[sched_op] |
| 680 | assert cost and ref_cost |
| 681 | |
| 682 | needs_dma = self.weights_needs_dma(weight_tensor) |
| 683 | |
| 684 | ofm_full_depth_slices = [0, ref_cost.stripe.depth] |
| 685 | |
| 686 | # Encode weights for the full depth |
Tim Hall | d784af7 | 2021-06-08 21:25:57 +0100 | [diff] [blame] | 687 | full_weights, full_scales = weight_compressor.encode_weight_and_scale_tensor( |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 688 | self.arch, |
| 689 | sched_op.parent_op, |
| 690 | weight_tensor, |
| 691 | scale_tensor, |
| 692 | sched_op.kernel, |
| 693 | cost.block_config, |
| 694 | ofm_full_depth_slices, |
| 695 | ) |
| 696 | full_weights_bytes = len(full_weights.buffer) |
| 697 | cost.ofm_depth_slices = ofm_full_depth_slices |
| 698 | |
| 699 | # No buffering required - take all the weights from permanent storage |
| 700 | if sched_op.op_type == Op.FullyConnected or not needs_dma: |
| 701 | cost.npu_weights_tensor = full_weights |
Tim Hall | d784af7 | 2021-06-08 21:25:57 +0100 | [diff] [blame] | 702 | cost.npu_scales_tensor = full_scales |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 703 | return |
| 704 | |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 705 | encoded_weights: Optional[NpuWeightTensor] = full_weights |
Tim Hall | d784af7 | 2021-06-08 21:25:57 +0100 | [diff] [blame] | 706 | encoded_scales = full_scales |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 707 | |
| 708 | # How many NPU cycles are available under the previously executing |
| 709 | # operator and SRAM unused for performing buffered DMA transfers |
| 710 | slack_cycles = prev_cost.slack_buffering_cycles if prev_cost else 0 |
| 711 | slack_memory = prev_cost.slack_buffering_memory if prev_cost else 0 |
| 712 | |
| 713 | # Force full depth for cascaded Ops |
| 714 | if ref_cost.cascade != 0: |
| 715 | weight_tensor_purpose = TensorSubPurpose.Standard |
| 716 | weight_buffer_size = full_weights_bytes |
| 717 | # Update the memory snapshot to reflect the added size of the weights |
| 718 | ref_schedule.memory_snapshot[ref_cost.time_index] += weight_buffer_size |
| 719 | else: |
| 720 | # Estimate the buffering cycle time for the full set of weights |
| 721 | full_transfer_cycles = npu_performance.measure_mem2mem_cycles( |
| 722 | self.arch, weight_tensor.mem_area, self.arch.fast_storage_mem_area, full_weights_bytes |
| 723 | ) |
| 724 | cost.full_weight_transfer_cycles = full_transfer_cycles |
| 725 | |
| 726 | # Calculate the amount of prebuffering necessary (or what is possible with limited |
| 727 | # double buffer buffer size) |
| 728 | half_buffer_limit = buffer_limit_bytes // 2 |
| 729 | if full_transfer_cycles > slack_cycles: |
| 730 | prebuffer_ratio = slack_cycles / full_transfer_cycles |
| 731 | prebuffer_bytes = min(prebuffer_ratio * full_weights_bytes, half_buffer_limit) |
| 732 | else: |
| 733 | prebuffer_bytes = min(full_weights_bytes, half_buffer_limit) |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 734 | |
| 735 | prebuffer_ratio = prebuffer_bytes / full_weights_bytes |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 736 | |
| 737 | # Have to split the weights if the initial buffering can't store |
| 738 | # all of the compressed weights |
| 739 | if prebuffer_bytes < full_weights_bytes: |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 740 | block_depth = cost.block_config.ofm_block.depth |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 741 | |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 742 | # Choose initial prebuffering depth (already buffer clamped) |
| 743 | prebuffer_depth = ref_cost.stripe.depth * prebuffer_ratio |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 744 | prebuffer_depth = int(max(16, round_down(prebuffer_depth, ArchitectureFeatures.OFMSplitDepth))) |
| 745 | |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 746 | # Calculate cycles executed during the prebuffer |
| 747 | pre_op_cycles = self.estimate_op_performance(sched_op, cost.block_config, prebuffer_depth) |
| 748 | buffering_depth = ref_cost.stripe.depth * (pre_op_cycles.op_cycles / full_transfer_cycles) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 749 | |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 750 | # Choose initial buffering depth and clamp to the double buffering limit |
| 751 | buffering_depth = round_up(buffering_depth, block_depth) |
| 752 | buffering_bytes = (buffering_depth / ref_cost.stripe.depth) * full_weights_bytes |
| 753 | if buffering_bytes > half_buffer_limit: |
| 754 | buffering_depth = (half_buffer_limit / full_weights_bytes) * ref_cost.stripe.depth |
| 755 | |
| 756 | while True: |
| 757 | # Attempt to buffer whole blocks |
Johan Alfvén | cce7f2d | 2022-04-08 10:47:09 +0200 | [diff] [blame] | 758 | if buffering_depth > block_depth: |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 759 | buffering_depth = round_down(buffering_depth, block_depth) |
| 760 | else: |
| 761 | buffering_depth = round_down(buffering_depth, ArchitectureFeatures.OFMSplitDepth) |
| 762 | buffering_depth = int(max(buffering_depth, ArchitectureFeatures.OFMSplitDepth)) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 763 | |
| 764 | # Create list of depth slices |
| 765 | depth_slices = [0] |
| 766 | if prebuffer_depth < ref_cost.stripe.depth: |
| 767 | depth_slices += list(range(prebuffer_depth, ref_cost.stripe.depth, buffering_depth)) |
| 768 | depth_slices.append(ref_cost.stripe.depth) |
| 769 | |
| 770 | # Encode weights based depth slices |
| 771 | cost.ofm_depth_slices = depth_slices |
Tim Hall | d784af7 | 2021-06-08 21:25:57 +0100 | [diff] [blame] | 772 | encoded_weights, encoded_scales = weight_compressor.encode_weight_and_scale_tensor( |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 773 | self.arch, |
| 774 | sched_op.parent_op, |
| 775 | weight_tensor, |
| 776 | scale_tensor, |
| 777 | sched_op.kernel, |
| 778 | cost.block_config, |
| 779 | cost.ofm_depth_slices, |
| 780 | ) |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 781 | assert encoded_weights is not None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 782 | # Chosen buffering might not fit at all, iterate until it does |
| 783 | # or until the minimum usable slice size is reached |
| 784 | if ( |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 785 | encoded_weights.double_buffer_size() <= buffer_limit_bytes |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 786 | or prebuffer_depth == ArchitectureFeatures.OFMSplitDepth |
| 787 | ): |
| 788 | break |
| 789 | |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 790 | if buffering_depth > prebuffer_depth: |
| 791 | buffering_depth = round_up(buffering_depth // 2, ArchitectureFeatures.OFMSplitDepth) |
| 792 | else: |
| 793 | prebuffer_depth = round_up(prebuffer_depth // 2, ArchitectureFeatures.OFMSplitDepth) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 794 | |
| 795 | # Calculate cycles required to run the last op for use as future slack |
| 796 | tail_cycles = self.estimate_op_performance( |
| 797 | sched_op, cost.block_config, depth_slices[-1] - depth_slices[-2] |
| 798 | ) |
| 799 | cost.slack_buffering_cycles = tail_cycles.op_cycles |
| 800 | |
| 801 | # Determine whether the weights need to be double buffered |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 802 | weight_buffer_size = min(len(encoded_weights.buffer), encoded_weights.max_range_bytes()) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 803 | |
| 804 | # Only buffer weights if there's still space left for the buffer |
| 805 | if weight_buffer_size <= buffer_limit_bytes: |
| 806 | assert weight_buffer_size % 16 == 0 |
| 807 | # Determine whether to double buffer or single buffer |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 808 | double_buffer_size = encoded_weights.double_buffer_size() |
| 809 | if (double_buffer_size <= buffer_limit_bytes) and (weight_buffer_size < len(encoded_weights.buffer)): |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 810 | weight_tensor_purpose = TensorSubPurpose.DoubleBuffer |
| 811 | else: |
| 812 | weight_tensor_purpose = TensorSubPurpose.Standard |
| 813 | |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 814 | cost.buffered_weight_tensors = [ |
| 815 | self.buffer_tensor( |
| 816 | encoded_weights, |
| 817 | weight_tensor_purpose, |
| 818 | encoded_weights.double_buffer_sizes[0], |
| 819 | weight_tensor.name + "_buffer", |
| 820 | ) |
| 821 | ] |
| 822 | if weight_tensor_purpose == TensorSubPurpose.DoubleBuffer: |
| 823 | buf2 = self.buffer_tensor( |
| 824 | encoded_weights, |
| 825 | weight_tensor_purpose, |
| 826 | encoded_weights.double_buffer_sizes[1], |
| 827 | weight_tensor.name + "_buffer2", |
| 828 | ) |
| 829 | cost.buffered_weight_tensors.append(buf2) |
| 830 | |
| 831 | last_used_buffer_idx = len(cost.ofm_depth_slices) % len(cost.buffered_weight_tensors) |
| 832 | weight_buffer_size = encoded_weights.double_buffer_sizes[last_used_buffer_idx] |
| 833 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 834 | if ref_cost.cascade == 0: |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 835 | # Determine if the lifetime can be extended and pre-buffer the first weight buffer |
| 836 | # under the previous operation |
| 837 | cost.buffered_weight_tensors[0].pre_buffer = encoded_weights.double_buffer_size() < slack_memory |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 838 | |
| 839 | cost.slack_buffering_memory -= weight_buffer_size |
| 840 | else: |
| 841 | # Don't slice or buffer - use the whole depth from persistent storage |
| 842 | cost.ofm_depth_slices = ofm_full_depth_slices |
| 843 | encoded_weights = full_weights |
Tim Hall | d784af7 | 2021-06-08 21:25:57 +0100 | [diff] [blame] | 844 | encoded_scales = full_scales |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 845 | |
| 846 | cost.npu_weights_tensor = encoded_weights |
Tim Hall | d784af7 | 2021-06-08 21:25:57 +0100 | [diff] [blame] | 847 | cost.npu_scales_tensor = encoded_scales |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 848 | |
Jacob Bohlin | eee9e5d | 2021-08-17 17:44:45 +0200 | [diff] [blame] | 849 | def buffer_tensor(self, src_tensor: Tensor, sub_purpose: TensorSubPurpose, buffer_size: int, name: str) -> Tensor: |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 850 | buffered_weight_tensor = Tensor([1, 1, 1, buffer_size], DataType.uint8, name) |
Jacob Bohlin | eee9e5d | 2021-08-17 17:44:45 +0200 | [diff] [blame] | 851 | buffered_weight_tensor.src_tensor = src_tensor |
| 852 | buffered_weight_tensor.mem_area = self.arch.fast_storage_mem_area |
| 853 | buffered_weight_tensor.mem_type = MemType.Scratch_fast |
| 854 | buffered_weight_tensor.purpose = TensorPurpose.Weights |
| 855 | buffered_weight_tensor.sub_purpose = sub_purpose |
| 856 | return buffered_weight_tensor |
| 857 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 858 | def propose_minimal_schedule(self) -> Schedule: |
| 859 | """Proposes scheduling parameters where every operator is subdivided into the smallest stripe that satisfies the |
| 860 | next operators stride""" |
| 861 | min_schedule = Schedule(self.sg, "MIN") |
| 862 | cost_map = min_schedule.cost_map |
| 863 | |
| 864 | # Keep track of the previous Op - which consumes the current Op's OFM |
Jonas Ohlsson | 845e232 | 2022-03-01 12:39:55 +0100 | [diff] [blame] | 865 | prev_op: Optional[SchedulerOperation] = None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 866 | for sched_op in reversed(self.sched_ops): |
| 867 | min_stripe_height = prev_op.kernel.stride.y if prev_op else 1 |
| 868 | min_stripe = sched_op.ofm.shape.with_height(min_stripe_height) |
| 869 | |
| 870 | cost = sched_op.create_scheduler_info(self.nng, min_stripe) |
| 871 | cost.cycles = self.estimate_op_performance(sched_op, cost.block_config, sched_op.ofm.shape.depth) |
| 872 | cost_map[sched_op] = cost |
| 873 | |
| 874 | prev_op = sched_op |
| 875 | |
| 876 | return min_schedule |
| 877 | |
| 878 | def propose_schedule_striping(self, final_stripe: Shape4D, label: str, ref_schedule: Schedule) -> Schedule: |
| 879 | """Proposes new striping for a schedule. The stripe is derived from the ifm requirements of the next Op down""" |
| 880 | ref_cost = ref_schedule.cost_map |
| 881 | |
| 882 | striped_schedule = Schedule(self.sg, label) |
| 883 | stripe = final_stripe |
| 884 | for sched_op in reversed(self.sched_ops): |
| 885 | if sched_op not in ref_cost: |
| 886 | # sched_op is not part of the sub-schedule - skip |
| 887 | continue |
| 888 | |
| 889 | # Create a cost entry with the new stripe |
| 890 | cost = sched_op.create_scheduler_info(self.nng, stripe) |
| 891 | |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 892 | weight_tensor = cost.npu_weights_tensor |
| 893 | for idx, buffered_tens in enumerate(ref_cost[sched_op].buffered_weight_tensors): |
Jacob Bohlin | eee9e5d | 2021-08-17 17:44:45 +0200 | [diff] [blame] | 894 | # If the weights are buffered in the reference schedule they should be in the new proposal |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 895 | cost.buffered_weight_tensors.append( |
| 896 | self.buffer_tensor( |
| 897 | weight_tensor, |
| 898 | buffered_tens.sub_purpose, |
| 899 | weight_tensor.double_buffer_sizes[idx], |
| 900 | buffered_tens.name, |
| 901 | ) |
Jacob Bohlin | eee9e5d | 2021-08-17 17:44:45 +0200 | [diff] [blame] | 902 | ) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 903 | |
| 904 | # Estimate performance |
| 905 | cost.cycles = self.estimate_op_performance(sched_op, cost.block_config, sched_op.ofm.shape.depth) |
| 906 | striped_schedule.cost_map[sched_op] = cost |
| 907 | |
| 908 | # Calculate the preceeding Op's stripe |
| 909 | stripe = sched_op.ifm.shape.with_height(stripe.height * sched_op.kernel.stride.y) |
| 910 | |
| 911 | return striped_schedule |
| 912 | |
| 913 | def estimate_schedule_memory_usage(self, schedule: Schedule, non_local_mem_usage: dict): |
| 914 | """Estimates the memory usage of a schedule""" |
| 915 | cost = schedule.cost_map |
| 916 | cascades = schedule.cascades |
| 917 | peak_mem_usage = 0 |
| 918 | for sched_op in self.sched_ops: |
| 919 | if sched_op not in cost: |
| 920 | # sched_op is not part of the sub-schedule - skip |
| 921 | continue |
| 922 | |
| 923 | if cost[sched_op].cascade: |
| 924 | # This Op is part of a cascade - use the cascade's memory usage |
| 925 | cascade_info = cascades[cost[sched_op].cascade] |
| 926 | # Non-local memory usage is already included in the cascade_info |
| 927 | peak_mem_usage = max(cascade_info.mem_usage, peak_mem_usage) |
| 928 | else: |
| 929 | # This Op is not part of a cascade - calculate the memory usage |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 930 | op_weight_buffer = sum(tens.storage_size() for tens in cost[sched_op].buffered_weight_tensors) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 931 | |
| 932 | op_mem_usage = ( |
| 933 | sched_op.ifm_size_in_bytes() |
| 934 | + sched_op.ofm_size_in_bytes() |
| 935 | + op_weight_buffer |
| 936 | + non_local_mem_usage.get(sched_op, 0) |
| 937 | ) |
| 938 | peak_mem_usage = max(op_mem_usage, peak_mem_usage) |
| 939 | |
| 940 | return peak_mem_usage |
| 941 | |
| 942 | def optimize_sub_schedule( |
| 943 | self, cascade_info: CascadeInfo, ref_schedule: Schedule, max_template: Schedule, memory_limit: int |
| 944 | ) -> Schedule: |
| 945 | """Extracts the Ops covered by the given cascade and creates a sub-schedule. The sub-schedule is optimized by |
| 946 | proposing weight buffering and then continously proposing new stripe sizes""" |
| 947 | ref_cost = ref_schedule.cost_map |
| 948 | # Extract the ops that are part of this sub-schedule |
| 949 | start = cascade_info.start |
| 950 | end = cascade_info.end |
| 951 | sub_schedule_ops = self.sched_ops[start : end + 1] |
| 952 | # Create a sub-schedule that contains only the costs for the Ops that are part of the sub-schedule |
| 953 | sub_schedule = Schedule(self.sg, f"SUB_{start}_{end}") |
| 954 | for sched_op in sub_schedule_ops: |
| 955 | sub_schedule.cost_map[sched_op] = ref_cost[sched_op] |
| 956 | |
| 957 | sub_schedule.cascades[end] = cascade_info |
| 958 | # Use the memory snapshot from the reference schedule |
| 959 | sub_schedule.memory_snapshot = ref_schedule.memory_snapshot |
| 960 | |
| 961 | # Calculate memory usage that is live during the sub-schedule but not part of it |
| 962 | time_for_cascade = ref_cost[sub_schedule_ops[0]].time_index |
| 963 | mem_usage_parallel_to_sub_schedule = ref_schedule.memory_snapshot[time_for_cascade] - cascade_info.mem_usage |
| 964 | # If the first Op's IFM has other consumers it has to live throughout the whole sub-schedule whether it's |
| 965 | # included in a cascade or not |
| 966 | persistent_initial_ifm = ( |
| 967 | sub_schedule_ops[0].ifm_size_in_bytes() if len(sub_schedule_ops[0].ifm.connection.consumers) > 1 else 0 |
| 968 | ) |
| 969 | # Calculate non-local-mem-usage per Operator |
| 970 | non_local_mem_usage = {} |
| 971 | for idx, sched_op in enumerate(sub_schedule_ops): |
| 972 | non_local_mem_usage[sched_op] = mem_usage_parallel_to_sub_schedule |
| 973 | if idx != 0: |
| 974 | non_local_mem_usage[sched_op] += persistent_initial_ifm |
| 975 | |
| 976 | cascade_builder = CascadeBuilder(sub_schedule_ops, self.arch.is_spilling_enabled(), non_local_mem_usage) |
| 977 | |
| 978 | # Start by adding buffering |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 979 | buffered_sub_schedule = self.propose_schedule_buffering( |
| 980 | sub_schedule, self.scheduler_options.optimization_sram_limit |
| 981 | ) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 982 | # Copy the cascades over from the unbuffered-schedule |
| 983 | buffered_sub_schedule.cascades = sub_schedule.cascades |
| 984 | |
| 985 | # Generate the possible stripings for the final Op in the sub-schedule |
| 986 | final_ofm_shape = sub_schedule_ops[-1].ofm.shape |
| 987 | possible_stripes = [ |
| 988 | final_ofm_shape.with_height(stripe_h) for stripe_h in range(1, final_ofm_shape.height // 2 + 1) |
| 989 | ] |
| 990 | |
| 991 | # Propose different striping - the possible stripes are proposed similarly to a binary search |
Jacob Bohlin | fad7204 | 2021-08-24 21:51:41 +0200 | [diff] [blame] | 992 | best_schedule = None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 993 | iteration = 0 |
| 994 | while len(possible_stripes) > 1: |
| 995 | proposed_stripe = possible_stripes[len(possible_stripes) // 2] |
| 996 | proposed_schedule = self.propose_schedule_striping( |
| 997 | proposed_stripe, f"OPTIMIZED_{iteration}", buffered_sub_schedule |
| 998 | ) |
| 999 | |
| 1000 | cascade_builder.build_cascades(proposed_schedule, max_template, memory_limit) |
| 1001 | |
| 1002 | # Check if proposal fits |
| 1003 | proposed_schedule_mem_usage = self.estimate_schedule_memory_usage(proposed_schedule, non_local_mem_usage) |
| 1004 | if (proposed_schedule_mem_usage) <= memory_limit: |
| 1005 | # Remove all possible stripes smaller than this |
| 1006 | possible_stripes = possible_stripes[len(possible_stripes) // 2 :] |
| 1007 | best_schedule = proposed_schedule |
| 1008 | if not proposed_schedule.cascades: |
| 1009 | # No cascading required - early exit |
| 1010 | break |
| 1011 | else: |
| 1012 | # Proposal doesn't fit within the limit - remove all possible stripes larger than this |
| 1013 | possible_stripes = possible_stripes[: len(possible_stripes) // 2] |
| 1014 | |
| 1015 | iteration += 1 |
| 1016 | |
| 1017 | return best_schedule |
| 1018 | |
| 1019 | def optimize_schedule( |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 1020 | self, |
| 1021 | schedule: Schedule, |
| 1022 | max_sched: Schedule, |
| 1023 | max_template: Schedule, |
| 1024 | options: SchedulerOptions, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1025 | ) -> Schedule: |
| 1026 | """Extracts sub-schedules based on the cascades and optimizes them and applies them to the final schedule""" |
| 1027 | sram_limit = options.optimization_sram_limit |
| 1028 | if max_sched.fast_storage_peak_usage < sram_limit and not self.arch.is_spilling_enabled(): |
| 1029 | # Maximum performance schedule fits within the SRAM target |
| 1030 | return max_sched |
| 1031 | |
Jacob Bohlin | fad7204 | 2021-08-24 21:51:41 +0200 | [diff] [blame] | 1032 | # Iterate over a copy of the cascades since they may change during the loop |
| 1033 | for cascade_info in list(schedule.cascades.values()): |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1034 | # Optimize the sub-schedule in this cascade |
| 1035 | opt_sub_schedule = self.optimize_sub_schedule(cascade_info, schedule, max_template, sram_limit) |
Jacob Bohlin | fad7204 | 2021-08-24 21:51:41 +0200 | [diff] [blame] | 1036 | if opt_sub_schedule: |
| 1037 | # Remove the existing cascade |
| 1038 | del schedule.cascades[cascade_info.end] |
| 1039 | # Update the sub-schedule Op and cascade costs to the full schedule |
| 1040 | schedule.cost_map.update(opt_sub_schedule.cost_map) |
| 1041 | schedule.cascades.update(opt_sub_schedule.cascades) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1042 | |
| 1043 | # Update memory snapshot |
| 1044 | self.sg.schedule = schedule |
| 1045 | self.update_op_memory_snapshot(schedule) |
| 1046 | # Propose schedule buffering to the optimized schedule |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 1047 | optimized_sched = self.propose_schedule_buffering(schedule, self.scheduler_options.optimization_sram_limit) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1048 | # Copy the cascade's metadata from the unbuffered schedule |
| 1049 | optimized_sched.cascades = schedule.cascades |
| 1050 | return optimized_sched |
| 1051 | |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1052 | def optimize_weight_buffering_size( |
| 1053 | self, |
| 1054 | min_schedule: Schedule, |
| 1055 | options: SchedulerOptions, |
| 1056 | ): |
| 1057 | default_schedule = self.sg.schedule |
Tim Hall | c1be087 | 2022-03-03 17:50:52 +0000 | [diff] [blame] | 1058 | npu_performance.calc_new_performance_for_network(self.nng, self.arch, None, False) |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1059 | default_tot_cycles = self.nng.cycles[npu_performance.PassCycles.Total] |
| 1060 | default_dram_cycles = self.nng.cycles[npu_performance.PassCycles.DramAccess] |
| 1061 | |
| 1062 | # Restore mem/type for scratched_fms |
| 1063 | for tens in self.scratched_fms: |
| 1064 | tens.mem_area = self.scratched_fms[tens][0] |
| 1065 | tens.mem_type = self.scratched_fms[tens][1] |
| 1066 | |
| 1067 | self.update_op_memory_snapshot(self.sg.schedule) |
| 1068 | |
| 1069 | # Collect live ranges from tensors |
| 1070 | memories_list = [(self.arch.fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))] |
| 1071 | lr_graph = live_range.LiveRangeGraph() |
| 1072 | for mem_area, mem_type_set in memories_list: |
| 1073 | live_range.extract_live_ranges_from_cascaded_passes( |
| 1074 | self.nng.get_root_subgraph(), |
| 1075 | mem_area, |
| 1076 | mem_type_set, |
| 1077 | lr_graph, |
| 1078 | Tensor.AllocationQuantum, |
| 1079 | ) |
| 1080 | |
| 1081 | # Find the relation between the sched_op and the buffering tensor |
| 1082 | weight_ops = {} |
| 1083 | for sched_op in self.sched_ops: |
| 1084 | cost = self.sg.schedule.cost_map[sched_op] |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 1085 | for tens in cost.buffered_weight_tensors: |
| 1086 | weight_ops[tens] = sched_op |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1087 | |
| 1088 | # Filter out weight buffer live ranges |
| 1089 | weight_lrs = [] |
| 1090 | for lr in lr_graph.lrs: |
| 1091 | for tens in lr.tensors: |
| 1092 | if weight_ops.get(tens): |
| 1093 | weight_lrs.append(lr) |
| 1094 | break |
| 1095 | |
| 1096 | # See if any evicted fm overlaps with a weight buffering op. |
| 1097 | # If this is the case add a size limitation to the buffering op |
| 1098 | for lr in self.evicted_fms: |
| 1099 | for weight_lr in weight_lrs: |
| 1100 | if lr.overlaps_ranges(weight_lr): |
| 1101 | for tens in weight_lr.tensors: |
| 1102 | sched_op = weight_ops.get(tens) |
| 1103 | if sched_op: |
| 1104 | # Add size reduction to the op |
| 1105 | sched_op.evicted_fms_size += lr.size |
| 1106 | break |
| 1107 | |
| 1108 | self.sg.schedule = min_schedule |
| 1109 | self.update_op_memory_snapshot(self.sg.schedule) |
| 1110 | |
| 1111 | # Run schedule buffering - with weight buffer size reduction |
| 1112 | schedule = self.propose_schedule_buffering(self.sg.schedule, options.optimization_sram_limit) |
| 1113 | schedule.cascades = self.sg.schedule.cascades |
| 1114 | self.sg.schedule = schedule |
| 1115 | |
| 1116 | # Apply new buffer schdule and calc new performance |
| 1117 | self.update_op_memory_snapshot(self.sg.schedule) |
| 1118 | self.apply_schedule(self.sg.schedule) |
| 1119 | self.use_fast_storage_for_feature_maps(self.sg.schedule, options.optimization_sram_limit) |
| 1120 | |
Tim Hall | c1be087 | 2022-03-03 17:50:52 +0000 | [diff] [blame] | 1121 | npu_performance.calc_new_performance_for_network(self.nng, self.arch, None, False) |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1122 | new_tot_cycles = self.nng.cycles[npu_performance.PassCycles.Total] |
| 1123 | new_dram_cycles = self.nng.cycles[npu_performance.PassCycles.DramAccess] |
| 1124 | |
Tim Hall | 8bc7a65 | 2022-05-19 15:29:23 +0100 | [diff] [blame] | 1125 | improvement_tot = ( |
| 1126 | round((default_tot_cycles - new_tot_cycles) / default_tot_cycles, 2) if default_tot_cycles != 0 else 0 |
| 1127 | ) |
| 1128 | improvement_dram = ( |
| 1129 | round((default_dram_cycles - new_dram_cycles) / default_dram_cycles, 2) if default_dram_cycles != 0 else 0 |
| 1130 | ) |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1131 | |
| 1132 | # Compare both total and dram improvement |
Johan Alfvén | 3dae1b6 | 2022-05-17 10:26:48 +0200 | [diff] [blame] | 1133 | if not (improvement_tot >= 0 and improvement_dram > 0): |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1134 | # No improvement, restore the default schedule |
| 1135 | for sched_op in self.sched_ops: |
| 1136 | sched_op.evicted_fms_size = 0 |
| 1137 | |
| 1138 | for tens in self.scratched_fms: |
| 1139 | tens.mem_area = self.scratched_fms[tens][0] |
| 1140 | tens.mem_type = self.scratched_fms[tens][1] |
| 1141 | |
| 1142 | self.sg.schedule = default_schedule |
| 1143 | self.update_op_memory_snapshot(self.sg.schedule) |
| 1144 | self.apply_schedule(self.sg.schedule) |
| 1145 | self.use_fast_storage_for_feature_maps(self.sg.schedule, options.optimization_sram_limit) |
| 1146 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1147 | def apply_schedule(self, sched: Schedule): |
| 1148 | """Applies the given schedule as a final solution""" |
| 1149 | for sched_op in self.sched_ops: |
| 1150 | op_info = sched.cost_map[sched_op] |
| 1151 | cascade_info = sched.cascades.get(op_info.cascade, None) |
| 1152 | if cascade_info and sched_op in cascade_info.buffers: |
| 1153 | buffer_tens = sched_op.ifm.connection.parent_tens |
| 1154 | # Apply memory area and type |
| 1155 | buffer_tens.mem_area = self.arch.fast_storage_mem_area |
| 1156 | buffer_tens.mem_type = MemType.Scratch_fast |
| 1157 | # Apply Rolling buffer |
| 1158 | buffer_tens.set_format(TensorFormat.NHCWB16, self.arch) |
| 1159 | buffer_tens.set_new_sub_purpose(TensorSubPurpose.RollingBufferY, cascade_info.buffers[sched_op].height) |
| 1160 | |
| 1161 | sched_op.parent_ps.block_config = op_info.block_config.old_style_representation() |
| 1162 | |
| 1163 | # Ensure that the src_tensor reference is set correctly |
Rickard Bolin | fd8b500 | 2022-05-16 09:11:06 +0000 | [diff] [blame] | 1164 | for tens in op_info.buffered_weight_tensors: |
| 1165 | tens.src_tensor = op_info.npu_weights_tensor |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1166 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1167 | def use_fast_storage_for_feature_maps(self, schedule, staging_limit): |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1168 | max_mem_usage = [] |
| 1169 | base_mem_usage = [] |
| 1170 | fast_storage_type = MemType.Scratch_fast |
| 1171 | fast_storage_mem_area = self.arch.fast_storage_mem_area |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1172 | self.evicted_fms = [] |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1173 | |
| 1174 | # Force all OFMs to fast-storage |
| 1175 | for sched_op in self.sched_ops: |
| 1176 | cost = schedule.cost_map[sched_op] |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1177 | if cost.cascade == 0 and sched_op.get_dependants(): |
| 1178 | ofm_tens = sched_op.ofm.connection.parent_tens |
| 1179 | if not any(cons is None for cons in ofm_tens.consumer_list): |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1180 | if ofm_tens not in self.scratched_fms: |
| 1181 | # Remember default mem area and mem type, only done once |
| 1182 | self.scratched_fms[ofm_tens] = (ofm_tens.mem_area, ofm_tens.mem_type) |
| 1183 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1184 | ofm_tens.mem_area = fast_storage_mem_area |
| 1185 | ofm_tens.mem_type = fast_storage_type |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1186 | |
| 1187 | # Collect live ranges from tensors |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1188 | memories_list = [(fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))] |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1189 | lr_graph = live_range.LiveRangeGraph() |
| 1190 | for mem_area, mem_type_set in memories_list: |
| 1191 | live_range.extract_live_ranges_from_cascaded_passes( |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 1192 | self.nng.get_root_subgraph(), |
| 1193 | mem_area, |
| 1194 | mem_type_set, |
| 1195 | lr_graph, |
| 1196 | Tensor.AllocationQuantum, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1197 | ) |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1198 | max_mem_usage = lr_graph.get_temporal_memory_usage(fast_storage_mem_area) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1199 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1200 | # If true, everything fits and we can proceed |
| 1201 | if max(max_mem_usage) <= staging_limit: |
| 1202 | return |
| 1203 | |
| 1204 | # Build up the base memory usage by removing the |
| 1205 | # mem_usage of the lrs we previously moved to fast-storage |
| 1206 | base_mem_usage = np.array(max_mem_usage) |
| 1207 | curr_lrs = [] |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1208 | for lr in lr_graph.lrs: |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1209 | for tens in lr.tensors: |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1210 | if self.scratched_fms.get(tens): |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1211 | curr_lrs.append(lr) |
| 1212 | base_mem_usage[lr.start_time : lr.end_time + 1] -= lr.size |
| 1213 | break |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1214 | competing_lrs = [] |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1215 | competing_tens_access = {} |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1216 | for lr in curr_lrs: |
| 1217 | base_usage = max(base_mem_usage[lr.start_time : lr.end_time + 1]) |
| 1218 | # If true, the lr will never fit and may thus be evicted |
| 1219 | if base_usage + lr.size > staging_limit: |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1220 | self.evicted_fms.append(lr) |
| 1221 | FastStorageComponentAllocator.evict(lr, max_mem_usage, self.scratched_fms) |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1222 | continue |
| 1223 | # Since max_mem_usage is the memory usage with all FMs still in fast-storage, |
| 1224 | # the memory limit cannot be exceeded if max_mem_usage does not. |
| 1225 | # Thus, the affected lrs can remain in fast-storage if the following is true |
| 1226 | if max(max_mem_usage[lr.start_time : lr.end_time + 1]) <= staging_limit: |
| 1227 | FastStorageComponentAllocator.keep(lr, base_mem_usage, staging_limit) |
| 1228 | else: |
| 1229 | competing_lrs.append(lr) |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1230 | for tens in lr.tensors: |
| 1231 | competing_tens_access[tens] = 0 |
| 1232 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1233 | sz = len(competing_lrs) |
| 1234 | # All lrs and their tensors have been handled if sz is zero, we may thus return |
| 1235 | if sz == 0: |
| 1236 | return |
| 1237 | |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1238 | # Estimate element access for all tensors that are competing for a place in fast-storage. |
| 1239 | # This number is used when deciding which tensor that stays in fast-storage |
| 1240 | for sched_op in self.sched_ops: |
| 1241 | cost = schedule.cost_map[sched_op] |
| 1242 | |
| 1243 | if competing_tens_access.get(sched_op.ifm.connection.parent_tens) is not None: |
| 1244 | tens = sched_op.ifm.connection.parent_tens |
| 1245 | access = self.estimate_element_access(sched_op, cost.block_config, sched_op.ofm.shape.depth) |
| 1246 | competing_tens_access[tens] += access.ifm_read[0] |
| 1247 | |
| 1248 | if sched_op.ifm2 and competing_tens_access.get(sched_op.ifm2.connection.parent_tens) is not None: |
| 1249 | tens = sched_op.ifm2.connection.parent_tens |
| 1250 | access = self.estimate_element_access(sched_op, cost.block_config, sched_op.ofm.shape.depth) |
| 1251 | competing_tens_access[tens] += access.ifm_read[1] |
| 1252 | |
| 1253 | if competing_tens_access.get(sched_op.ofm.connection.parent_tens) is not None: |
| 1254 | tens = sched_op.ofm.connection.parent_tens |
| 1255 | access = self.estimate_element_access(sched_op, cost.block_config, sched_op.ofm.shape.depth) |
| 1256 | competing_tens_access[tens] += access.ofm_write |
| 1257 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1258 | competing_lrs = sorted(competing_lrs, key=lambda lr: (lr.start_time, lr.end_time + 1, lr.size)) |
| 1259 | start = 0 |
| 1260 | start_time = competing_lrs[0].start_time |
| 1261 | end_time = competing_lrs[0].end_time |
| 1262 | component_allocator = FastStorageComponentAllocator(base_mem_usage, max_mem_usage, staging_limit) |
| 1263 | # Build up components and then allocate each separately |
| 1264 | for i, lr in enumerate(competing_lrs): |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1265 | if lr.start_time <= end_time and i - start < component_allocator.MAX_EXHAUSTIVE_LIFE_RANGE: |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1266 | start_time = min(start_time, lr.start_time) |
| 1267 | end_time = max(end_time, lr.end_time) |
| 1268 | else: |
| 1269 | component_allocator.allocate_component( |
| 1270 | component_allocator, |
| 1271 | competing_lrs[start:i], |
| 1272 | max_mem_usage, |
| 1273 | base_mem_usage, |
| 1274 | staging_limit, |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1275 | self.scratched_fms, |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1276 | competing_tens_access, |
Johan Alfvén | 68b8f2f | 2022-06-24 08:42:19 +0200 | [diff] [blame] | 1277 | self.evicted_fms, |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1278 | ) |
| 1279 | start = i |
| 1280 | start_time = lr.start_time |
| 1281 | end_time = lr.end_time |
| 1282 | component_allocator.allocate_component( |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1283 | component_allocator, |
| 1284 | competing_lrs[start:sz], |
| 1285 | max_mem_usage, |
| 1286 | base_mem_usage, |
| 1287 | staging_limit, |
| 1288 | self.scratched_fms, |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1289 | competing_tens_access, |
Johan Alfvén | 68b8f2f | 2022-06-24 08:42:19 +0200 | [diff] [blame] | 1290 | self.evicted_fms, |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1291 | ) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1292 | |
| 1293 | def move_constant_data(self): |
| 1294 | """Determine if data, can be moved from permanent storage to another memory area. A move |
| 1295 | will generate a DMA command in the high-level command stream""" |
| 1296 | for sched_op in self.sched_ops: |
| 1297 | parent_op = sched_op.parent_op |
| 1298 | is_lut_used = any(inp.purpose == TensorPurpose.LUT for inp in parent_op.inputs) |
| 1299 | max_ifm_shram_avail = ( |
| 1300 | (self.arch.available_shram_banks(is_lut_used) - self.arch.shram_reserved_output_banks) |
| 1301 | * self.arch.shram_bank_size |
| 1302 | // 2 |
| 1303 | ) |
| 1304 | |
| 1305 | for idx, tens in enumerate(parent_op.inputs): |
| 1306 | if tens.mem_type not in (MemType.Scratch, MemType.Scratch_fast): |
| 1307 | # Tensor is in permanent storage |
| 1308 | # Only when permanent storage differs from feature map storage, there is a point moving the data |
| 1309 | if ( |
| 1310 | tens.mem_area in self.arch.permanent_storage_mem_area |
| 1311 | and self.arch.permanent_storage_mem_area != self.arch.feature_map_storage_mem_area |
| 1312 | ) or tens.purpose == TensorPurpose.LUT: |
| 1313 | if tens.purpose == TensorPurpose.LUT or ( |
Patrik Gustavsson | 94292fe | 2021-09-02 08:22:58 +0200 | [diff] [blame] | 1314 | # For elementwise broadcast |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1315 | tens.purpose == TensorPurpose.FeatureMap |
| 1316 | and sched_op.op_type.is_binary_elementwise_op() |
| 1317 | and tens.shape != [] |
| 1318 | and sched_op.ifm.shape != sched_op.ofm.shape |
Patrik Gustavsson | 94292fe | 2021-09-02 08:22:58 +0200 | [diff] [blame] | 1319 | and parent_op.write_shape is None |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1320 | and tens.storage_size() > max_ifm_shram_avail |
| 1321 | ): |
| 1322 | only_vector_product_consumers = all( |
| 1323 | oper and oper.type.npu_block_type == NpuBlockType.VectorProduct |
| 1324 | for oper in tens.consumers() |
| 1325 | ) |
| 1326 | |
| 1327 | if (not only_vector_product_consumers) or tens.purpose == TensorPurpose.LUT: |
| 1328 | new_tens = tens.clone_into_fast_storage(self.arch) |
| 1329 | if tens.purpose == TensorPurpose.LUT: |
| 1330 | new_tens.mem_area = MemArea.Shram |
| 1331 | |
| 1332 | new_tens.consumer_list.append(parent_op) |
| 1333 | parent_op.inputs[idx] = new_tens |
Dwight Lidman | 352607c | 2021-09-29 17:00:09 +0200 | [diff] [blame] | 1334 | # If the index is out of range, IFM and IFM2 are the same tensor |
| 1335 | # and pass inputs don't have duplicates |
| 1336 | if idx < len(sched_op.parent_ps.inputs): |
| 1337 | sched_op.parent_ps.inputs[idx] = new_tens |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1338 | |
| 1339 | def print_schedule(self, schedule: Schedule): |
| 1340 | print(f"Schedule: '{schedule.name}'") |
| 1341 | for sched_op in self.sched_ops: |
| 1342 | if sched_op not in schedule.cost_map: |
| 1343 | # Sub-schedule printing |
| 1344 | continue |
| 1345 | |
| 1346 | op_info = schedule.cost_map[sched_op] |
| 1347 | print(f"\t{sched_op.index}: Operation {sched_op.name} - OFM {sched_op.ofm.shape}") |
| 1348 | print(f"\t\tType: {sched_op.op_type}") |
| 1349 | print(f"\t\tKernel: {sched_op.kernel}") |
| 1350 | print(f"{op_info}") |
| 1351 | mem_usage = ( |
| 1352 | schedule.memory_snapshot[op_info.time_index] |
| 1353 | if op_info.time_index < len(schedule.memory_snapshot) |
| 1354 | else 0 |
| 1355 | ) |
| 1356 | print(f"\t\tSRAM Used: {mem_usage} bytes") |
| 1357 | |
Jonas Ohlsson | 25e700c | 2022-03-04 14:58:56 +0100 | [diff] [blame] | 1358 | print("\tCascades:") |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1359 | for i, cascade in enumerate(schedule.cascades.values()): |
| 1360 | print(f"\t\t{i}: {cascade.start} -> {cascade.end}, size: {cascade.mem_usage}") |
Patrik Gustavsson | feeb06d | 2020-04-22 12:53:47 +0200 | [diff] [blame] | 1361 | |
Andreas Nevalainen | 27d36f0 | 2020-11-19 11:27:50 +0100 | [diff] [blame] | 1362 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1363 | def _update_tensor_allocation(nng: Graph, arch: ArchitectureFeatures, options): |
| 1364 | """ |
| 1365 | Creates live ranges and runs tensor allocator for the current schedule |
| 1366 | (i.e. sg.schedule for all subgraphs), returns the maximum memory usage |
| 1367 | and updates SchedulerOpInfo.mem_usage for all operations in the schedule. |
| 1368 | """ |
| 1369 | root_sg = nng.get_root_subgraph() |
| 1370 | |
| 1371 | alloc_list = [] |
| 1372 | if arch.is_spilling_enabled(): |
| 1373 | mem_alloc_scratch_fast = (arch.fast_storage_mem_area, set((MemType.Scratch_fast,))) |
| 1374 | mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch,))) |
| 1375 | # Order is important |
| 1376 | alloc_list.append(mem_alloc_scratch_fast) |
| 1377 | alloc_list.append(mem_alloc_scratch) |
| 1378 | else: |
| 1379 | mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast))) |
| 1380 | alloc_list.append(mem_alloc_scratch) |
| 1381 | |
| 1382 | for mem_area, mem_type_set in alloc_list: |
| 1383 | tensor_allocation.allocate_tensors( |
| 1384 | nng, |
| 1385 | root_sg, |
| 1386 | arch, |
| 1387 | mem_area, |
| 1388 | mem_type_set, |
| 1389 | tensor_allocator=options.tensor_allocator, |
| 1390 | verbose_allocation=options.verbose_allocation, |
| 1391 | cpu_tensor_alignment=options.cpu_tensor_alignment, |
Tim Hall | cda4fcb | 2022-05-19 12:36:58 +0100 | [diff] [blame] | 1392 | hillclimb_max_iterations=options.hillclimb_max_iterations, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1393 | ) |
| 1394 | |
| 1395 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1396 | class FastStorageComponentAllocator: |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1397 | MAX_EXHAUSTIVE_LIFE_RANGE = 20 |
| 1398 | |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1399 | def __init__(self, base_mem_usage, max_mem_usage, staging_limit): |
| 1400 | self.base_mem_usage = base_mem_usage |
| 1401 | self.max_mem_usage = list(max_mem_usage) |
| 1402 | self.staging_limit = staging_limit |
| 1403 | self.lrs = [] |
| 1404 | self.evicted = [] |
| 1405 | self.curr_evicted = [] |
| 1406 | self.remaining_total_size = [] |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1407 | self.best_score = 0 |
| 1408 | self.competing_tens_access = {} |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1409 | |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1410 | def allocate_exhaustive(self, ix, score): |
| 1411 | # Favour tensors with highest element access (score) |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1412 | if ix >= len(self.lrs): |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1413 | if score > self.best_score: |
| 1414 | self.best_score = score |
Louis Verhaard | 5c8f1e5 | 2022-02-23 14:13:07 +0100 | [diff] [blame] | 1415 | self.evicted = self.curr_evicted.copy() |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1416 | return |
| 1417 | |
| 1418 | lr = self.lrs[ix] |
| 1419 | for t in range(lr.start_time, lr.end_time): |
| 1420 | assert self.base_mem_usage[t] <= self.max_mem_usage[t] |
| 1421 | base_usage = max(self.base_mem_usage[lr.start_time : lr.end_time + 1]) |
| 1422 | can_fit = base_usage + lr.size <= self.staging_limit |
| 1423 | always_fits = can_fit |
| 1424 | |
| 1425 | if can_fit: |
| 1426 | max_usage = max(self.max_mem_usage[lr.start_time : lr.end_time + 1]) |
| 1427 | always_fits = max_usage <= self.staging_limit |
| 1428 | |
| 1429 | if can_fit or always_fits: |
| 1430 | self.curr_evicted[ix] = False |
| 1431 | self.base_mem_usage = self.update_mem_usage(self.base_mem_usage, lr, True) |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1432 | tens = lr.tensors[0] |
| 1433 | # Tensor is being included - add tensor element access to the score |
| 1434 | self.allocate_exhaustive(ix + 1, score + self.competing_tens_access[tens]) |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1435 | self.base_mem_usage = self.update_mem_usage(self.base_mem_usage, lr, False) |
| 1436 | |
| 1437 | if not always_fits: |
| 1438 | self.curr_evicted[ix] = True |
| 1439 | self.max_mem_usage = self.update_mem_usage(self.max_mem_usage, lr, False) |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1440 | self.allocate_exhaustive(ix + 1, score) |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1441 | self.max_mem_usage = self.update_mem_usage(self.max_mem_usage, lr, True) |
| 1442 | |
| 1443 | @staticmethod |
| 1444 | def update_mem_usage(mem_usage, lr, increase): |
| 1445 | for t in range(lr.start_time, lr.end_time + 1): |
| 1446 | mem_usage[t] += lr.size if increase else -lr.size |
| 1447 | assert mem_usage[t] >= 0 |
| 1448 | return mem_usage |
| 1449 | |
| 1450 | @staticmethod |
| 1451 | def evict(lr, max_mem_usage, scratched_fms): |
| 1452 | for t in range(lr.start_time, lr.end_time + 1): |
| 1453 | max_mem_usage[t] -= lr.size |
| 1454 | for tens in lr.tensors: |
| 1455 | if tens in scratched_fms: |
| 1456 | tens.mem_area = scratched_fms[tens][0] |
| 1457 | tens.mem_type = scratched_fms[tens][1] |
| 1458 | |
| 1459 | @staticmethod |
| 1460 | def keep(lr, base_mem_usage, staging_limit): |
| 1461 | for t in range(lr.start_time, lr.end_time + 1): |
| 1462 | base_mem_usage[t] += lr.size |
| 1463 | assert base_mem_usage[t] <= staging_limit |
| 1464 | |
Johan Alfvén | 68b8f2f | 2022-06-24 08:42:19 +0200 | [diff] [blame] | 1465 | def allocate_component( |
| 1466 | self, allocator, lrs, max_mem, min_mem, staging_limit, scratched_fms, competing_tens_access, evicted_fms |
| 1467 | ): |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1468 | sz = len(lrs) |
| 1469 | allocator.lrs = lrs |
| 1470 | allocator.evicted = [0] * len(lrs) |
| 1471 | allocator.curr_evicted = [0] * sz |
Johan Alfvén | 5c30971 | 2022-06-10 15:40:58 +0200 | [diff] [blame] | 1472 | allocator.best_score = -1 |
| 1473 | allocator.competing_tens_access = competing_tens_access |
| 1474 | # Recursively evaluate all permutations of allocations of the lrs found in the component. |
| 1475 | # For every permutation that fits within the staging_limit there is a score calculated. |
| 1476 | # The permutation with the highest score will then be chosen. The score is calculated |
| 1477 | # as the sum of the actual element access (ifm read and ofm write) for all the |
| 1478 | # including tensors. So it is not necessary the tensor with the biggest size that ends up |
| 1479 | # being included in the result. |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1480 | allocator.allocate_exhaustive(0, 0) |
| 1481 | |
| 1482 | # Optimal allocation has been found, move lrs accordingly |
| 1483 | for i, e in enumerate(allocator.evicted): |
| 1484 | if e: |
| 1485 | self.evict(lrs[i], max_mem, scratched_fms) |
Johan Alfvén | 68b8f2f | 2022-06-24 08:42:19 +0200 | [diff] [blame] | 1486 | if lrs[i] not in evicted_fms: |
| 1487 | evicted_fms.append(lrs[i]) |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1488 | else: |
| 1489 | self.keep(lrs[i], min_mem, staging_limit) |
Johan Alfvén | 68b8f2f | 2022-06-24 08:42:19 +0200 | [diff] [blame] | 1490 | if lrs[i] in evicted_fms: |
| 1491 | evicted_fms.remove(lrs[i]) |
erik.andersson@arm.com | de6cb64 | 2022-02-02 14:03:15 +0100 | [diff] [blame] | 1492 | |
| 1493 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1494 | def schedule_passes(nng: Graph, arch: ArchitectureFeatures, options, scheduler_options: SchedulerOptions): |
| 1495 | """Entry point for the Scheduler""" |
| 1496 | # Initialize CPU subgraphs |
| 1497 | schedulers = dict() |
| 1498 | # Initialize schedulers with max schedule. Only schedule NPU subgraphs |
Andreas Nevalainen | 27d36f0 | 2020-11-19 11:27:50 +0100 | [diff] [blame] | 1499 | for sg in nng.subgraphs: |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1500 | if sg.placement != PassPlacement.Npu: |
| 1501 | # Create cascaded passes for CPU Ops |
| 1502 | cascaded_passes = [] |
| 1503 | for idx, ps in enumerate(sg.passes): |
| 1504 | cps = CascadedPass( |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 1505 | ps.name, |
| 1506 | SchedulingStrategy.WeightStream, |
| 1507 | ps.inputs, |
| 1508 | [], |
| 1509 | ps.outputs, |
| 1510 | [ps], |
| 1511 | ps.placement, |
| 1512 | False, |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1513 | ) |
Andreas Nevalainen | 27d36f0 | 2020-11-19 11:27:50 +0100 | [diff] [blame] | 1514 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1515 | cps.time = idx |
| 1516 | ps.cascade = cps |
| 1517 | cascaded_passes.append(cps) |
Andreas Nevalainen | 27d36f0 | 2020-11-19 11:27:50 +0100 | [diff] [blame] | 1518 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1519 | sg.cascaded_passes = cascaded_passes |
| 1520 | else: |
| 1521 | # Npu subgraph - create schedule |
| 1522 | scheduler = Scheduler(nng, sg, arch, scheduler_options) |
| 1523 | schedulers[sg] = scheduler |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1524 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1525 | scheduler.create_scheduler_representation(arch) |
| 1526 | sg.sched_ops = scheduler.sched_ops |
| 1527 | scheduler.move_constant_data() |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1528 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1529 | # Create the Max schedule template |
| 1530 | max_schedule_template = scheduler.create_initial_schedule() |
| 1531 | scheduler.max_schedule = max_schedule_template |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1532 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1533 | # Create the optimimised Max schedule |
| 1534 | sg.schedule = max_schedule_template |
| 1535 | scheduler.update_op_memory_snapshot(max_schedule_template) |
Tim Hall | 789e6f3 | 2021-06-17 17:02:31 +0100 | [diff] [blame] | 1536 | opt_max_schedule = scheduler.propose_schedule_buffering(max_schedule_template, 1 << 32) |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1537 | sg.schedule = opt_max_schedule |
| 1538 | scheduler.update_op_memory_snapshot(opt_max_schedule) |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1539 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1540 | # Create Min schedule |
| 1541 | min_schedule = scheduler.propose_minimal_schedule() |
| 1542 | initial_sram_limit = scheduler_options.optimization_sram_limit |
| 1543 | if scheduler_options.optimization_strategy == OptimizationStrategy.Size: |
| 1544 | initial_sram_limit = scheduler.min_memory_req |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1545 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1546 | cascade_builder = CascadeBuilder(scheduler.sched_ops, arch.is_spilling_enabled()) |
| 1547 | cascade_builder.build_cascades(min_schedule, max_schedule_template, initial_sram_limit) |
| 1548 | sg.schedule = min_schedule |
| 1549 | scheduler.update_op_memory_snapshot(min_schedule) |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1550 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1551 | if scheduler_options.optimization_strategy == OptimizationStrategy.Performance: |
| 1552 | # Create an optimized schedule |
| 1553 | sg.schedule = scheduler.optimize_schedule( |
| 1554 | min_schedule, opt_max_schedule, max_schedule_template, scheduler_options |
| 1555 | ) |
| 1556 | scheduler.update_op_memory_snapshot(sg.schedule) |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1557 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1558 | scheduler.apply_schedule(sg.schedule) |
| 1559 | scheduler.use_fast_storage_for_feature_maps(sg.schedule, scheduler_options.optimization_sram_limit) |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 1560 | |
Johan Alfvén | 6f4cb03 | 2022-05-05 08:42:46 +0200 | [diff] [blame] | 1561 | if scheduler_options.optimization_strategy == OptimizationStrategy.Performance and scheduler.evicted_fms: |
| 1562 | # It might be possible to gain performance by reducing |
| 1563 | # weight buffer size and instead fit fms in fast storage |
| 1564 | scheduler.optimize_weight_buffering_size(min_schedule, scheduler_options) |
| 1565 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1566 | if scheduler_options.verbose_schedule: |
| 1567 | scheduler.print_schedule(sg.schedule) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1568 | |
Tim Hall | d8339a7 | 2021-05-27 18:49:40 +0100 | [diff] [blame] | 1569 | # Evaluate schedule |
| 1570 | _update_tensor_allocation(nng, arch, options) |