blob: ec7380a605bc0eb51c154928b92edecb2c3db3e2 [file] [log] [blame]
erik.andersson@arm.com8912f3a2022-08-16 11:08:57 +02001# Copyright (C) 2022 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Halld8339a72021-05-27 18:49:40 +010016#
Tim Hall79d07d22020-04-27 18:20:16 +010017# Description:
Tim Halld8339a72021-05-27 18:49:40 +010018# The scheduler creates and searches for an optimal plan for the network, selecting block configurations and
19# subdivisions for the Operators
Jonas Ohlsson845e2322022-03-01 12:39:55 +010020# For Class name forward references for the type annotations. (see PEP 563).
21from __future__ import annotations
22
Diego Russoea6111a2020-04-14 18:41:58 +010023import copy
Johan Alfvén5e0ae552022-02-09 21:20:10 +010024from collections import namedtuple
Tim Halld8339a72021-05-27 18:49:40 +010025from enum import auto
26from enum import IntEnum
Johan Alfvén6f4cb032022-05-05 08:42:46 +020027from typing import Any
Tim Halld8339a72021-05-27 18:49:40 +010028from typing import Dict
29from typing import List
30from typing import Optional
31from typing import Tuple
Jonas Ohlsson845e2322022-03-01 12:39:55 +010032from 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.
35if TYPE_CHECKING:
36 from .npu_performance import CycleCost
Diego Russoea6111a2020-04-14 18:41:58 +010037
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +010038import numpy as np
39
Diego Russoea6111a2020-04-14 18:41:58 +010040from . import live_range
Tim Hall79d07d22020-04-27 18:20:16 +010041from . import npu_performance
Tim Halld8339a72021-05-27 18:49:40 +010042from . import tensor_allocation
43from . import weight_compressor
44from .architecture_allocator import ArchitectureBlockConfig
45from .architecture_allocator import find_block_config
46from .architecture_allocator import get_ifm_area_required
Fredrik Svedbergd03dc502022-06-30 10:44:12 +020047from .architecture_allocator import to_upscale
erik.andersson@arm.com8912f3a2022-08-16 11:08:57 +020048from .architecture_allocator import is_nearest
Tim Halld8339a72021-05-27 18:49:40 +010049from .architecture_features import ArchitectureFeatures
50from .architecture_features import Block
51from .cascade_builder import CascadeBuilder
52from .cascade_builder import CascadeInfo
Fredrik Svedberg880e7352020-08-25 11:31:47 +020053from .data_type import DataType
Diego Russoe8a10452020-04-21 17:39:10 +010054from .nn_graph import CascadedPass
Tim Halld8339a72021-05-27 18:49:40 +010055from .nn_graph import Graph
56from .nn_graph import Pass
Diego Russoe8a10452020-04-21 17:39:10 +010057from .nn_graph import PassPlacement
Diego Russoe8a10452020-04-21 17:39:10 +010058from .nn_graph import SchedulingStrategy
Tim Halld8339a72021-05-27 18:49:40 +010059from .nn_graph import Subgraph
60from .numeric_util import round_down
61from .numeric_util import round_up
Diego Russoe8a10452020-04-21 17:39:10 +010062from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020063from .operation import Op
Tim Halld8339a72021-05-27 18:49:40 +010064from .shape4d import Shape4D
Diego Russoe8a10452020-04-21 17:39:10 +010065from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020066from .tensor import MemType
Tim Halld8339a72021-05-27 18:49:40 +010067from .tensor import Tensor
Diego Russoe8a10452020-04-21 17:39:10 +010068from .tensor import TensorFormat
69from .tensor import TensorPurpose
70from .tensor import TensorSubPurpose
Jonas Ohlsson845e2322022-03-01 12:39:55 +010071from .weight_compressor import NpuWeightTensor
Jacob Bohlin1a666972020-09-11 10:04:15 +020072
Tim Hall79d07d22020-04-27 18:20:16 +010073
Tim Halld8339a72021-05-27 18:49:40 +010074def shape_for_format(shape: Shape4D, tensor_format: TensorFormat) -> Shape4D:
75 if tensor_format == TensorFormat.NHCWB16:
76 return shape.with_depth(round_up(shape.depth, 16))
77
78 return shape
79
80
81class OptimizationStrategy(IntEnum):
82 """Enum defining the different optimization strategies for the Scheduler"""
83
84 Size = auto()
85 Performance = auto()
Tim Hall79d07d22020-04-27 18:20:16 +010086
87 def __str__(self):
88 return self.name
89
90
Tim Halld8339a72021-05-27 18:49:40 +010091class SchedulerOpInfo:
92 """Contains metadata about a SchedulerOperation that is unique to one Schedule"""
93
Tim Hall79d07d22020-04-27 18:20:16 +010094 def __init__(
95 self,
Tim Halld8339a72021-05-27 18:49:40 +010096 block_config: ArchitectureBlockConfig,
97 weights_size: int,
98 stripe_input: Shape4D,
99 stripe_input2: Optional[Shape4D],
100 stripe: Shape4D,
Tim Hall79d07d22020-04-27 18:20:16 +0100101 ):
Tim Halld8339a72021-05-27 18:49:40 +0100102 self.block_config = block_config
103 self.weights_size = weights_size
104 self.stripe_input = stripe_input
105 self.stripe_input2 = stripe_input2
106 self.stripe = stripe
107 self.cascade = 0 # Assigned by CascadeBuilder. 0 means not part of a cascade
108 self.time_index = None # Set by update_op_memory_snapshot
109 self.ofm_depth_slices: List[int] = [0, stripe.depth]
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100110 self.npu_weights_tensor: Optional[NpuWeightTensor] = None
111 self.npu_scales_tensor: Optional[NpuWeightTensor] = None
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000112 self.buffered_weight_tensors: List[Tensor] = []
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100113 self.cycles: Optional[CycleCost] = None
Tim Halld8339a72021-05-27 18:49:40 +0100114 self.slack_buffering_cycles = 0
115 self.slack_buffering_memory = 0
116 self.full_weight_transfer_cycles = 0
117
118 def copy(self):
Jonas Ohlssond8575072022-03-30 10:30:25 +0200119 res = SchedulerOpInfo(
120 self.block_config,
121 self.weights_size,
122 self.stripe_input,
123 self.stripe_input2,
124 self.stripe,
125 )
Tim Halld8339a72021-05-27 18:49:40 +0100126 res.cascade = self.cascade
127 return res
128
129 def __str__(self):
130 res = f"\t\tBlock Config = {self.block_config}\n"
131 res += f"\t\tOFM Block = {self.block_config.ofm_block}\n"
132 res += f"\t\tIFM Stripe = {self.stripe_input}\n"
133 res += f"\t\tIFM2 Stripe = {self.stripe_input2}\n"
134 res += f"\t\tOFM Stripe = {self.stripe}\n"
135 res += f"\t\tEncoded Weights = {self.npu_weights_tensor and len(self.npu_weights_tensor.buffer)} bytes\n"
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000136 for idx, tens in enumerate(self.buffered_weight_tensors):
137 res += f"\t\tWeight buffer{idx + 1} = {tens.storage_size()} bytes\n"
Tim Halld8339a72021-05-27 18:49:40 +0100138 res += f"\t\tDepth slices = {self.ofm_depth_slices}\n"
139 res += f"\t\tAssigned Cascade = {self.cascade}"
140 return res
141
142
143class SchedulerOptions:
144 """Contains options for the Scheduler"""
145
146 def __init__(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200147 self,
148 optimization_strategy,
149 sram_target,
150 verbose_schedule,
Tim Halld8339a72021-05-27 18:49:40 +0100151 ):
152 self.optimization_strategy = optimization_strategy
153 self.optimization_sram_limit = sram_target
Tim Hall79d07d22020-04-27 18:20:16 +0100154 self.verbose_schedule = verbose_schedule
Tim Hall79d07d22020-04-27 18:20:16 +0100155
Tim Halld8339a72021-05-27 18:49:40 +0100156 def __str__(self) -> str:
157 return f"{type(self).__name__}: {str(self.__dict__)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100158
159 __repr__ = __str__
160
161
Tim Halld8339a72021-05-27 18:49:40 +0100162class SchedulerTensor:
163 def __init__(self, shape, dt, mem_area, _format):
164 self.dtype = dt
165 self.mem_area = mem_area
166 self.shape = shape
167 self.format = _format
168 self.connection = None
Tim Hall79d07d22020-04-27 18:20:16 +0100169
Tim Halld8339a72021-05-27 18:49:40 +0100170
171class SchedulerOperation:
172 """Scheduler internal representation of 'Operation'
173 This class can be seen as a node within the Scheduler Graph representation
174 """
175
176 def __init__(self, ps: Pass, arch: ArchitectureFeatures, nng: Graph):
177 self.arch = arch
178 self.parent_ps = ps
179 self.parent_op = ps.primary_op
180 self.name = ps.primary_op.name
181 self.op_type = ps.primary_op.type
182 self.activation = ps.primary_op.activation
183 self.kernel = ps.primary_op.kernel
Tim Hall3c5cfe92022-03-16 16:31:57 +0000184 self.resampling_mode = ps.primary_op.ifm_resampling_mode
Fredrik Svedbergb81e1bb2022-10-11 21:50:51 +0200185 self.reversed_operands = False
Tim Halld8339a72021-05-27 18:49:40 +0100186 self.uses_scalar = ps.primary_op.ifm2 is not None and (
187 ps.primary_op.ifm.shape == [] or ps.primary_op.ifm2.shape == []
Tim Hall79d07d22020-04-27 18:20:16 +0100188 )
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +0100189
Tim Halld8339a72021-05-27 18:49:40 +0100190 self.ifm_ublock = arch.ifm_ublock
Tim Hall79d07d22020-04-27 18:20:16 +0100191
Jonas Ohlssond8575072022-03-30 10:30:25 +0200192 self.ifm = SchedulerTensor(
193 ps.ifm_shapes[0],
194 ps.ifm_tensor.dtype,
195 ps.ifm_tensor.mem_area,
196 ps.ifm_tensor.format,
197 )
Tim Hall79d07d22020-04-27 18:20:16 +0100198
Tim Halld8339a72021-05-27 18:49:40 +0100199 self.ifm2 = None
200 if ps.ifm2_tensor:
201 self.ifm2 = SchedulerTensor(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200202 ps.ifm_shapes[1],
203 ps.ifm2_tensor.dtype,
204 ps.ifm2_tensor.mem_area,
205 ps.ifm2_tensor.format,
Tim Halld8339a72021-05-27 18:49:40 +0100206 )
Tim Hall79d07d22020-04-27 18:20:16 +0100207
Jonas Ohlssond8575072022-03-30 10:30:25 +0200208 self.ofm = SchedulerTensor(
209 ps.ofm_shapes[0],
210 ps.ofm_tensor.dtype,
211 ps.ofm_tensor.mem_area,
212 ps.ofm_tensor.format,
213 )
Tim Hall79d07d22020-04-27 18:20:16 +0100214
Tim Halld8339a72021-05-27 18:49:40 +0100215 # Input volume width and height required to produce the smallest possible stripe
216 self.min_stripe_input_w, self.min_stripe_input_h = self._calculate_min_stripe_input()
Tim Hall79d07d22020-04-27 18:20:16 +0100217
Tim Halld8339a72021-05-27 18:49:40 +0100218 # Flags that marks whether this SchedulerOperation requires full IFM/OFM
219 self.requires_full_ifm = False
220 self.requires_full_ifm2 = False
221 self.requires_full_ofm = False
Tim Hall79d07d22020-04-27 18:20:16 +0100222
Johan Alfvén6f4cb032022-05-05 08:42:46 +0200223 self.evicted_fms_size = 0
224
Tim Halld8339a72021-05-27 18:49:40 +0100225 self.index = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100226
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +0100227 # Perform an IFM swap for certain binary elementwise operators
228 # in order to enable cascading, if the SchedOp conforms to
229 # Elementwise cascading rules.
Johan Alfvén56a71b02022-10-19 11:20:12 +0200230 if self.op_type.is_binary_elementwise_op() and CascadeBuilder.elementwise_cascading_conformity(self):
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +0100231 ifm1 = ps.ifm_tensor
232 ifm2 = ps.ifm2_tensor
233 ofm = ps.ofm_tensor
234 assert ifm1.elements() > 0
235 assert ifm2.elements() > 0
236
237 if (
238 # The non-constant IFM should be the primary input
239 (ifm1.ops[0].type == Op.Const and ifm2.ops[0].type != Op.Const)
240 # The non-broadcasted IFM should be the primary input
241 or (ifm1.shape != ofm.shape and ifm2.shape == ofm.shape)
242 ):
Fredrik Svedbergb81e1bb2022-10-11 21:50:51 +0200243 self.reversed_operands = True
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +0100244 self.ifm, self.ifm2 = self.ifm2, self.ifm
245
246 self.parent_ps.ifm_shapes = self.parent_ps.ifm_shapes[::-1]
247 self.parent_ps.inputs = self.parent_ps.inputs[::-1]
248 self.parent_ps.ifm_tensor, self.parent_ps.ifm2_tensor = (
249 self.parent_ps.ifm2_tensor,
250 self.parent_ps.ifm_tensor,
251 )
252
Tim Halld8339a72021-05-27 18:49:40 +0100253 def add_ifm_connection(self, conn: "Connection"):
254 """Add input connection to another SchedulerOperation or Subgraph Input"""
255 conn.consumers.append(self)
256 self.ifm.connection = conn
Tim Hall79d07d22020-04-27 18:20:16 +0100257
Tim Halld8339a72021-05-27 18:49:40 +0100258 def add_ifm2_connection(self, conn: "Connection"):
259 """Add input connection to another SchedulerOperation or Subgraph Input"""
260 if self.ifm2:
261 conn.consumers.append(self)
262 self.ifm2.connection = conn
Tim Hall79d07d22020-04-27 18:20:16 +0100263 else:
Tim Halld8339a72021-05-27 18:49:40 +0100264 assert False, f"Trying to set an IFM2 Connection to {self} which has no IFM2"
Tim Hall79d07d22020-04-27 18:20:16 +0100265
Tim Halld8339a72021-05-27 18:49:40 +0100266 def add_ofm_connection(self, conn: "Connection"):
267 """Add output connection to another SchedulerOperation or Subgraph Output"""
268 conn.producers.append(self)
269 self.ofm.connection = conn
270
271 def get_dependants(self):
272 """Returns a list of the Ops that depend on this Operation's OFM"""
273 return self.ofm.connection.consumers
274
275 def ifm_size_in_bytes(self) -> int:
276 """Returns size of the IFM in bytes"""
277 ifm_storage_shape = shape_for_format(self.ifm.shape, self.ifm.format)
278 return round_up(ifm_storage_shape.elements() * self.ifm.dtype.size_in_bytes(), Tensor.AllocationQuantum)
279
280 def ifm2_size_in_bytes(self) -> int:
281 """Returns size of the IFM2 in bytes"""
282 if self.ifm2:
283 ifm2_storage_shape = shape_for_format(self.ifm2.shape, self.ifm2.format)
284 return round_up(ifm2_storage_shape.elements() * self.ifm2.dtype.size_in_bytes(), Tensor.AllocationQuantum)
285
286 return 0
287
288 def ofm_size_in_bytes(self) -> int:
289 """Returns size of the OFM in bytes"""
290 ofm_storage_shape = shape_for_format(self.ofm.shape, self.ofm.format)
291 return round_up(ofm_storage_shape.elements() * self.ofm.dtype.size_in_bytes(), Tensor.AllocationQuantum)
292
293 def create_scheduler_info(self, nng: Graph, stripe: Shape4D) -> SchedulerOpInfo:
294 """Returns schedule info about this SchedulerOperation based on how many ofm elements it should produce"""
295 ifm_shape = self.ifm.shape
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100296 ifm2_shape = self.ifm2.shape if self.ifm2 is not None else None
Tim Halld8339a72021-05-27 18:49:40 +0100297 ofm_shape = stripe
298
299 if ofm_shape != self.ofm.shape:
300 # Striped Op - Need to calculate stripe input volume
301 stripe_input_w, stripe_input_h = self._get_stripe_input_requirement(stripe)
302 # Ensure stripe input volume is within the full IFM volume
303 stripe_input_h = min(stripe_input_h, self.ifm.shape.height)
304 stripe_input_w = min(stripe_input_w, self.ifm.shape.width)
305 ifm_shape = ifm_shape.with_hw(stripe_input_h, stripe_input_w)
306
307 if self.ifm2:
308 stripe_input2_h = min(stripe_input_h, self.ifm2.shape.height)
309 stripe_input2_w = min(stripe_input_w, self.ifm2.shape.width)
310 ifm2_shape = ifm2_shape.with_hw(stripe_input2_h, stripe_input2_w)
311
312 block_config = self._get_block_config(ifm_shape, ifm2_shape, self.uses_scalar, ofm_shape)
313
314 scheduler_op_info = SchedulerOpInfo(block_config, 0, ifm_shape, ifm2_shape, ofm_shape)
315 if self.parent_op.weights:
316 # Default full-depth weight encoding with no buffering
Tim Halld784af72021-06-08 21:25:57 +0100317 (
318 scheduler_op_info.npu_weights_tensor,
319 scheduler_op_info.npu_scales_tensor,
320 ) = weight_compressor.encode_weight_and_scale_tensor(
Tim Halld8339a72021-05-27 18:49:40 +0100321 self.arch,
322 self.parent_op,
323 self.parent_op.weights,
324 self.parent_op.bias,
325 self.kernel,
326 block_config,
327 [0, self.ofm.shape.depth],
328 )
329
330 self.parent_ps.block_config = block_config.old_style_representation()
331 return scheduler_op_info
332
333 def _get_stripe_input_requirement(self, stripe_shape: Shape4D) -> Tuple[int, int]:
334 """Returns the amount of IFM required to produce the stripe with shape:'stripe_shape'"""
335 ofm_shape_to_produce = Block.from_shape(stripe_shape.as_list())
336
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200337 return get_ifm_area_required(ofm_shape_to_produce, self.kernel, self.resampling_mode)
Tim Halld8339a72021-05-27 18:49:40 +0100338
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100339 def _calculate_min_stripe_input(self) -> Tuple[int, int]:
Tim Halld8339a72021-05-27 18:49:40 +0100340 # Calculate the input volume required height and width for the smallest possible stripe (h,w = 1,1)
341 min_stripe = self.ofm.shape.with_hw(1, 1)
342 return self._get_stripe_input_requirement(min_stripe)
343
344 def _get_block_config(
345 self, ifm_shape: Shape4D, ifm2_shape: Optional[Shape4D], uses_scalar: bool, ofm_shape: Shape4D
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100346 ) -> Optional[ArchitectureBlockConfig]:
Tim Halld8339a72021-05-27 18:49:40 +0100347 # Returns a block config and SHRAM layout
348 lut_banks = 2 if self.parent_op.activation_lut else 0
349 return find_block_config(
350 self.arch,
351 self.op_type.npu_block_type,
352 ofm_shape,
353 ifm_shape,
354 ifm2_shape,
355 uses_scalar,
356 self.ifm.dtype.size_in_bits(),
357 self.kernel,
358 lut_banks,
359 self.parent_op.has_scaling(),
360 self.resampling_mode,
361 )
362
363
364class Connection:
365 """Scheduler internal representation of a Tensor that connects two SchedulerOperations
366 This class can be seen as an edge within the Scheduler Graph representation
367 """
368
369 def __init__(self, tensor: Tensor):
370 self.parent_tens = tensor
371
372 # SchedulerOperation relationships
373 self.producers: List[SchedulerOperation] = []
374 self.consumers: List[SchedulerOperation] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100375
376 def __str__(self):
Tim Halld8339a72021-05-27 18:49:40 +0100377 return f"<Connection {self.parent_tens.name}>"
Tim Hall79d07d22020-04-27 18:20:16 +0100378
379 __repr__ = __str__
380
381
Tim Halld8339a72021-05-27 18:49:40 +0100382class Schedule:
383 """Class that contains a solution of how to schedule an NPU subgraph and its cost"""
Tim Hall79d07d22020-04-27 18:20:16 +0100384
Tim Halld8339a72021-05-27 18:49:40 +0100385 def __init__(self, sg: Subgraph, label: str):
386 self.sg = sg
387 self.label = label
388 self.cost_map: Dict[SchedulerOperation, SchedulerOpInfo] = {}
389 self.cascades: Dict[int, CascadeInfo] = {}
390 self.fast_storage_peak_usage = 0
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100391 self.memory_snapshot: Optional[List[int]] = None
Tim Halld8339a72021-05-27 18:49:40 +0100392
393 @property
394 def name(self):
395 return f"{self.sg.name}_{self.label}"
Tim Hall79d07d22020-04-27 18:20:16 +0100396
397
Tim Halld8339a72021-05-27 18:49:40 +0100398class Scheduler:
399 """Main class of the Vela Scheduling"""
Tim Hall79d07d22020-04-27 18:20:16 +0100400
Tim Halld8339a72021-05-27 18:49:40 +0100401 def __init__(self, nng: Graph, sg: Subgraph, arch: ArchitectureFeatures, options: SchedulerOptions):
Tim Hall79d07d22020-04-27 18:20:16 +0100402 self.nng = nng
403 self.sg = sg
404 self.arch = arch
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000405 self.sched_ops: List[SchedulerOperation] = []
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100406 self.max_schedule: Optional[Schedule] = None
Tim Halld8339a72021-05-27 18:49:40 +0100407 self.scheduler_options = options
Tim Hall79d07d22020-04-27 18:20:16 +0100408
Johan Alfvén6f4cb032022-05-05 08:42:46 +0200409 self.scratched_fms: Dict[Tensor, Any] = {}
410 self.evicted_fms: List[live_range.LiveRange] = []
411
Johan Alfvén5e0ae552022-02-09 21:20:10 +0100412 def avoid_nhcwb16_for_ofm(self, tens, ps, arch):
413 # Only run this check for opt strategy Size
414 if self.scheduler_options.optimization_strategy == OptimizationStrategy.Performance:
415 return False
416
417 op = ps.primary_op
418 if not op.type.is_elementwise_op():
419 return False
420
421 depth = op.ofm_shapes[0][-1]
422 if (depth % 16) == 0:
423 return False
424
425 # Check if overwriting the inputs can be allowed
426 OpShapeTens = namedtuple("OpShapeTens", ["op_shape", "tens"])
427 outp = OpShapeTens(op.ofm_shapes[0], op.ofm)
428 inps = []
429 if op.ifm is not None:
430 inps.append(OpShapeTens(op.ifm_shapes[0], op.ifm))
431 if op.ifm2 is not None:
432 inps.append(OpShapeTens(op.ifm_shapes[1], op.ifm2))
433
434 # Find an input tensor that can be overwritten by the output
435 for inp in inps:
436 if (
437 # check op input and output shapes allow overlapping
438 inp.op_shape == outp.op_shape
439 # check input tensor is valid
440 and inp.tens is not None
441 and inp.tens.shape != []
442 # check input and output tensors are compatible
443 and inp.tens.format == outp.tens.format
444 and inp.tens.dtype == outp.tens.dtype
445 ):
446 if inp.tens.format == TensorFormat.NHWC:
447 return True
448
449 return False
450
Tim Halld8339a72021-05-27 18:49:40 +0100451 def create_scheduler_representation(self, arch: ArchitectureFeatures):
452 """Creates a Scheduler Graph representation"""
453 # Temporary dict for creating connections between the Operations
454 connections: Dict[Tensor, Connection] = {}
455 # Memory required for the largest FeatureMap that has to be full
456 min_memory_req = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100457 for ps in self.sg.passes:
Tim Halld8339a72021-05-27 18:49:40 +0100458 if ps.primary_op:
459 # Set tensor format to NHCWB16 for output FeatureMaps, if possible
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200460 for output in ps.outputs:
Jacob Bohlina5e8c1c2021-06-14 13:33:39 +0200461 if output in self.sg.output_tensors or output.purpose != TensorPurpose.FeatureMap:
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +0200462 continue
Johan Alfvén5e0ae552022-02-09 21:20:10 +0100463
464 if output.needs_linear_format:
465 continue
466
467 if self.avoid_nhcwb16_for_ofm(output, ps, arch):
468 output.needs_linear_format = True
469 continue
470
471 output.set_format(TensorFormat.NHCWB16, arch)
Tim Halld8339a72021-05-27 18:49:40 +0100472
473 # Create SchedulerOperations
474 op = SchedulerOperation(ps, arch, self.nng)
475 op.index = len(self.sched_ops)
476
477 # Make connections
478 if ps.ifm_tensor not in connections:
479 connections[ps.ifm_tensor] = Connection(ps.ifm_tensor)
480 if ps.ifm2_tensor and ps.ifm2_tensor not in connections:
481 connections[ps.ifm2_tensor] = Connection(ps.ifm2_tensor)
482 if ps.ofm_tensor not in connections:
483 connections[ps.ofm_tensor] = Connection(ps.ofm_tensor)
484
485 op.add_ifm_connection(connections[ps.ifm_tensor])
486 if ps.ifm2_tensor:
487 op.add_ifm2_connection(connections[ps.ifm2_tensor])
488 op.add_ofm_connection(connections[ps.ofm_tensor])
489
490 # Set requirements on the ifm/ofm buffers
491 self.sched_ops.append(op)
492 if ps.ifm_tensor in self.sg.input_tensors:
493 # This Op consumes a subgraph input
494 op.requires_full_ifm = True
495 if ps.ifm2_tensor and ps.ifm2_tensor in self.sg.input_tensors:
496 # This Op consumes a subgraph input
497 op.requires_full_ifm2 = True
498 if ps.ofm_tensor in self.sg.output_tensors:
499 # This Op produces a subgraph output
500 op.requires_full_ofm = True
501 if ps.ifm_tensor.needs_linear_format:
502 op.requires_full_ifm = True
503 if ps.ifm2_tensor and ps.ifm2_tensor.needs_linear_format:
504 op.requires_full_ifm2 = True
505 if ps.ofm_tensor.needs_linear_format or ps.primary_op.memory_function == Op.ConcatSliceWrite:
506 op.requires_full_ofm = True
507 if len(ps.primary_op.outputs) > 1 or len(ps.primary_op.outputs[0].consumer_list) > 1:
508 # Op has multiple outputs or consumers - requires full OFM
509 op.requires_full_ofm = True
510
511 # Check memory requirements if this Op requires any full FeatureMaps
512 op_memory_req = 0
513 if op.requires_full_ifm:
514 op_memory_req += op.ifm_size_in_bytes()
515 if op.requires_full_ifm2:
516 op_memory_req += op.ifm2_size_in_bytes()
517 if op.requires_full_ofm:
518 op_memory_req += op.ofm_size_in_bytes()
519
520 min_memory_req = max(op_memory_req, min_memory_req)
521
522 # Theoretical minimum required memory - used to guide the cascade building
523 self.min_memory_req = min_memory_req
524
525 def create_initial_schedule(self) -> Schedule:
526 """Creates an initial schedule with no cascading or buffering of any kind"""
527 schedule = Schedule(self.sg, "MAX")
Tim Halld8339a72021-05-27 18:49:40 +0100528 for op in self.sched_ops:
529 cost = op.create_scheduler_info(self.nng, op.ofm.shape)
530 cost.cycles = self.estimate_op_performance(op, cost.block_config, op.ofm.shape.depth)
531 schedule.cost_map[op] = cost
532
533 return schedule
534
535 def update_op_memory_snapshot(self, schedule: Schedule):
536 memories_list = [(self.arch.fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))]
537
538 # Collect live ranges from tensors
539 lr_graph = live_range.LiveRangeGraph()
540 for mem_area, mem_type_set in memories_list:
541 live_range.extract_live_ranges_from_cascaded_passes(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200542 self.nng.get_root_subgraph(),
543 mem_area,
544 mem_type_set,
545 lr_graph,
546 Tensor.AllocationQuantum,
Tim Halld8339a72021-05-27 18:49:40 +0100547 )
548
549 # Populate time-array with memory used by live ranges
550 temporal_usage = lr_graph.get_temporal_memory_usage(self.arch.fast_storage_mem_area)
551 schedule.memory_snapshot = temporal_usage
552
553 # Set the peak memory usage
554 schedule.fast_storage_peak_usage = max(temporal_usage, default=0)
555
556 def estimate_op_performance(self, op: SchedulerOperation, block_config, ofm_depth):
557 query = npu_performance.PerformanceQuery(op.op_type.npu_block_type)
558 query.ifm_shape = op.ifm.shape
559 query.ifm_memory_area = op.ifm.mem_area
560 query.ifm_bits = op.ifm.dtype.size_in_bits()
561 query.ifm_format = op.ifm.format
562 query.ifm2_shape = op.ifm2 and op.ifm2.shape
563 query.ifm2_memory_area = op.ifm2 and op.ifm2.mem_area
564 query.ifm2_bits = op.ifm2 and op.ifm2.dtype.size_in_bits()
565 query.ifm2_format = op.ifm2 and op.ifm2.format
566 query.ofm_shape = op.ofm.shape.with_depth(ofm_depth)
567 query.ofm_memory_area = op.ofm.mem_area
568 query.ofm_bits = op.ofm.dtype.size_in_bits()
569 query.ofm_format = op.ofm.format
570 if op.parent_op.bias:
571 query.const_shape = Shape4D(1, 1, 1, op.ofm.shape.depth)
572 query.const_memory_area = self.arch.fast_storage_mem_area
573
574 query.kernel = op.kernel
575 query.config = block_config
576
577 return npu_performance.measure_cycle_cost(self.arch, op.op_type, op.activation and op.activation.op_type, query)
578
Johan Alfvén5c309712022-06-10 15:40:58 +0200579 def estimate_element_access(self, op: SchedulerOperation, block_config, ofm_depth):
580 query = npu_performance.PerformanceQuery(op.op_type.npu_block_type)
581 query.ifm_shape = op.ifm.shape
582 query.ifm_memory_area = op.ifm.mem_area
583 query.ifm_bits = op.ifm.dtype.size_in_bits()
584 query.ifm_format = op.ifm.format
585 query.ifm2_shape = op.ifm2 and op.ifm2.shape
586 query.ifm2_memory_area = op.ifm2 and op.ifm2.mem_area
587 query.ifm2_bits = op.ifm2 and op.ifm2.dtype.size_in_bits()
588 query.ifm2_format = op.ifm2 and op.ifm2.format
589 query.ofm_shape = op.ofm.shape.with_depth(ofm_depth)
590 query.ofm_memory_area = op.ofm.mem_area
591 query.ofm_bits = op.ofm.dtype.size_in_bits()
592 query.ofm_format = op.ofm.format
593 if op.parent_op.bias:
594 query.const_shape = Shape4D(1, 1, 1, op.ofm.shape.depth)
595 query.const_memory_area = self.arch.fast_storage_mem_area
596
597 query.kernel = op.kernel
598 query.config = block_config
599
600 return npu_performance.measure_element_access(self.arch, query)
601
Tim Hall789e6f32021-06-17 17:02:31 +0100602 def propose_schedule_buffering(self, ref_schedule: Schedule, staging_limit_bytes):
Tim Halld8339a72021-05-27 18:49:40 +0100603 """Create a buffered schedule"""
604 buffered_schedule = Schedule(self.sg, f"{ref_schedule.label}_BUFFERED")
Tim Halld8339a72021-05-27 18:49:40 +0100605
606 prev_op = None
607 for sched_op in self.sched_ops:
608 if sched_op not in ref_schedule.cost_map:
609 # sched_op is not part of this sub-schedule - skip
610 continue
611
612 self.propose_operator_buffering(sched_op, prev_op, buffered_schedule, ref_schedule, staging_limit_bytes)
613 prev_op = sched_op
614
615 return buffered_schedule
616
617 def propose_operator_buffering(
618 self,
619 sched_op: SchedulerOperation,
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100620 prev_op: Optional[SchedulerOperation],
Tim Halld8339a72021-05-27 18:49:40 +0100621 buffered_schedule: Schedule,
622 ref_schedule: Schedule,
623 staging_limit_bytes,
624 ):
625 # Mild recursion might mean this Op has already been seen
626 if sched_op in buffered_schedule.cost_map:
627 return
628
629 # Take the reference schedule as default costings for this schedule
630 ref_cost = ref_schedule.cost_map[sched_op]
631 cost = copy.copy(ref_cost)
632 cost.slack_buffering_cycles = ref_cost.cycles.op_cycles
633 memory_snapshot = ref_schedule.memory_snapshot
634 ref_memory_usage = memory_snapshot[ref_cost.time_index] if ref_cost.time_index < len(memory_snapshot) else 0
635 cost.slack_buffering_memory = staging_limit_bytes - ref_memory_usage
636 buffered_schedule.cost_map[sched_op] = cost
637
638 # Attempt weight buffering on anything with a weights tensor
639 if sched_op.parent_op.weights:
Johan Alfvén6f4cb032022-05-05 08:42:46 +0200640 buffer_limit_bytes = cost.slack_buffering_memory
641
642 # If applicable apply size limitation, but keep it within reason (ratio 1.5).
643 # Size limitation is used when use_fast_storage_for_feature_maps have
644 # detected that there are fms that do not fit in fast storage.
645 if sched_op.evicted_fms_size and ((buffer_limit_bytes / sched_op.evicted_fms_size) >= 1.5):
646 buffer_limit_bytes -= sched_op.evicted_fms_size
647
Tim Halld8339a72021-05-27 18:49:40 +0100648 self.propose_weight_buffering(
649 sched_op.parent_op.weights,
650 sched_op.parent_op.bias,
651 sched_op,
652 prev_op,
653 buffered_schedule,
654 ref_schedule,
Johan Alfvén6f4cb032022-05-05 08:42:46 +0200655 buffer_limit_bytes,
Tim Halld8339a72021-05-27 18:49:40 +0100656 )
657
658 return cost
659
660 def weights_needs_dma(self, weight_tensor):
661 if weight_tensor and weight_tensor.mem_type not in (MemType.Scratch, MemType.Scratch_fast):
662 # Weights are in permanent storage
663 # Only when permanent storage differs from feature map storage, there is a point moving the data
664 if (
665 weight_tensor.mem_area in (MemArea.Dram, MemArea.OffChipFlash)
666 and self.arch.permanent_storage_mem_area != self.arch.fast_storage_mem_area
667 ):
668 return True
669 return False
670
671 def propose_weight_buffering(
672 self,
673 weight_tensor,
674 scale_tensor,
675 sched_op: SchedulerOperation,
676 prev_op: SchedulerOperation,
677 buffered_schedule: Schedule,
678 ref_schedule: Schedule,
679 buffer_limit_bytes,
680 ):
681 cost = buffered_schedule.cost_map[sched_op]
682 prev_cost = buffered_schedule.cost_map.get(prev_op)
683 ref_cost = ref_schedule.cost_map[sched_op]
684 assert cost and ref_cost
685
686 needs_dma = self.weights_needs_dma(weight_tensor)
687
688 ofm_full_depth_slices = [0, ref_cost.stripe.depth]
689
690 # Encode weights for the full depth
Tim Halld784af72021-06-08 21:25:57 +0100691 full_weights, full_scales = weight_compressor.encode_weight_and_scale_tensor(
Tim Halld8339a72021-05-27 18:49:40 +0100692 self.arch,
693 sched_op.parent_op,
694 weight_tensor,
695 scale_tensor,
696 sched_op.kernel,
697 cost.block_config,
698 ofm_full_depth_slices,
699 )
700 full_weights_bytes = len(full_weights.buffer)
701 cost.ofm_depth_slices = ofm_full_depth_slices
702
703 # No buffering required - take all the weights from permanent storage
704 if sched_op.op_type == Op.FullyConnected or not needs_dma:
705 cost.npu_weights_tensor = full_weights
Tim Halld784af72021-06-08 21:25:57 +0100706 cost.npu_scales_tensor = full_scales
Tim Halld8339a72021-05-27 18:49:40 +0100707 return
708
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100709 encoded_weights: Optional[NpuWeightTensor] = full_weights
Tim Halld784af72021-06-08 21:25:57 +0100710 encoded_scales = full_scales
Tim Halld8339a72021-05-27 18:49:40 +0100711
712 # How many NPU cycles are available under the previously executing
713 # operator and SRAM unused for performing buffered DMA transfers
714 slack_cycles = prev_cost.slack_buffering_cycles if prev_cost else 0
715 slack_memory = prev_cost.slack_buffering_memory if prev_cost else 0
716
717 # Force full depth for cascaded Ops
718 if ref_cost.cascade != 0:
719 weight_tensor_purpose = TensorSubPurpose.Standard
720 weight_buffer_size = full_weights_bytes
721 # Update the memory snapshot to reflect the added size of the weights
722 ref_schedule.memory_snapshot[ref_cost.time_index] += weight_buffer_size
723 else:
724 # Estimate the buffering cycle time for the full set of weights
725 full_transfer_cycles = npu_performance.measure_mem2mem_cycles(
726 self.arch, weight_tensor.mem_area, self.arch.fast_storage_mem_area, full_weights_bytes
727 )
728 cost.full_weight_transfer_cycles = full_transfer_cycles
729
730 # Calculate the amount of prebuffering necessary (or what is possible with limited
731 # double buffer buffer size)
732 half_buffer_limit = buffer_limit_bytes // 2
733 if full_transfer_cycles > slack_cycles:
734 prebuffer_ratio = slack_cycles / full_transfer_cycles
735 prebuffer_bytes = min(prebuffer_ratio * full_weights_bytes, half_buffer_limit)
736 else:
737 prebuffer_bytes = min(full_weights_bytes, half_buffer_limit)
Tim Hall789e6f32021-06-17 17:02:31 +0100738
739 prebuffer_ratio = prebuffer_bytes / full_weights_bytes
Tim Halld8339a72021-05-27 18:49:40 +0100740
741 # Have to split the weights if the initial buffering can't store
742 # all of the compressed weights
743 if prebuffer_bytes < full_weights_bytes:
Tim Hall789e6f32021-06-17 17:02:31 +0100744 block_depth = cost.block_config.ofm_block.depth
Tim Halld8339a72021-05-27 18:49:40 +0100745
Tim Hall789e6f32021-06-17 17:02:31 +0100746 # Choose initial prebuffering depth (already buffer clamped)
747 prebuffer_depth = ref_cost.stripe.depth * prebuffer_ratio
Tim Halld8339a72021-05-27 18:49:40 +0100748 prebuffer_depth = int(max(16, round_down(prebuffer_depth, ArchitectureFeatures.OFMSplitDepth)))
749
Tim Hall789e6f32021-06-17 17:02:31 +0100750 # Calculate cycles executed during the prebuffer
751 pre_op_cycles = self.estimate_op_performance(sched_op, cost.block_config, prebuffer_depth)
752 buffering_depth = ref_cost.stripe.depth * (pre_op_cycles.op_cycles / full_transfer_cycles)
Tim Halld8339a72021-05-27 18:49:40 +0100753
Tim Hall789e6f32021-06-17 17:02:31 +0100754 # Choose initial buffering depth and clamp to the double buffering limit
755 buffering_depth = round_up(buffering_depth, block_depth)
756 buffering_bytes = (buffering_depth / ref_cost.stripe.depth) * full_weights_bytes
757 if buffering_bytes > half_buffer_limit:
758 buffering_depth = (half_buffer_limit / full_weights_bytes) * ref_cost.stripe.depth
759
760 while True:
761 # Attempt to buffer whole blocks
Johan Alfvéncce7f2d2022-04-08 10:47:09 +0200762 if buffering_depth > block_depth:
Tim Hall789e6f32021-06-17 17:02:31 +0100763 buffering_depth = round_down(buffering_depth, block_depth)
764 else:
765 buffering_depth = round_down(buffering_depth, ArchitectureFeatures.OFMSplitDepth)
766 buffering_depth = int(max(buffering_depth, ArchitectureFeatures.OFMSplitDepth))
Tim Halld8339a72021-05-27 18:49:40 +0100767
768 # Create list of depth slices
769 depth_slices = [0]
770 if prebuffer_depth < ref_cost.stripe.depth:
771 depth_slices += list(range(prebuffer_depth, ref_cost.stripe.depth, buffering_depth))
772 depth_slices.append(ref_cost.stripe.depth)
773
774 # Encode weights based depth slices
775 cost.ofm_depth_slices = depth_slices
Tim Halld784af72021-06-08 21:25:57 +0100776 encoded_weights, encoded_scales = weight_compressor.encode_weight_and_scale_tensor(
Tim Halld8339a72021-05-27 18:49:40 +0100777 self.arch,
778 sched_op.parent_op,
779 weight_tensor,
780 scale_tensor,
781 sched_op.kernel,
782 cost.block_config,
783 cost.ofm_depth_slices,
784 )
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100785 assert encoded_weights is not None
Tim Halld8339a72021-05-27 18:49:40 +0100786 # Chosen buffering might not fit at all, iterate until it does
787 # or until the minimum usable slice size is reached
788 if (
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000789 encoded_weights.double_buffer_size() <= buffer_limit_bytes
Tim Halld8339a72021-05-27 18:49:40 +0100790 or prebuffer_depth == ArchitectureFeatures.OFMSplitDepth
791 ):
792 break
793
Tim Hall789e6f32021-06-17 17:02:31 +0100794 if buffering_depth > prebuffer_depth:
795 buffering_depth = round_up(buffering_depth // 2, ArchitectureFeatures.OFMSplitDepth)
796 else:
797 prebuffer_depth = round_up(prebuffer_depth // 2, ArchitectureFeatures.OFMSplitDepth)
Tim Halld8339a72021-05-27 18:49:40 +0100798
799 # Calculate cycles required to run the last op for use as future slack
800 tail_cycles = self.estimate_op_performance(
801 sched_op, cost.block_config, depth_slices[-1] - depth_slices[-2]
802 )
803 cost.slack_buffering_cycles = tail_cycles.op_cycles
804
805 # Determine whether the weights need to be double buffered
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000806 weight_buffer_size = min(len(encoded_weights.buffer), encoded_weights.max_range_bytes())
Tim Halld8339a72021-05-27 18:49:40 +0100807
808 # Only buffer weights if there's still space left for the buffer
809 if weight_buffer_size <= buffer_limit_bytes:
810 assert weight_buffer_size % 16 == 0
811 # Determine whether to double buffer or single buffer
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000812 double_buffer_size = encoded_weights.double_buffer_size()
813 if (double_buffer_size <= buffer_limit_bytes) and (weight_buffer_size < len(encoded_weights.buffer)):
Tim Halld8339a72021-05-27 18:49:40 +0100814 weight_tensor_purpose = TensorSubPurpose.DoubleBuffer
815 else:
816 weight_tensor_purpose = TensorSubPurpose.Standard
817
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000818 cost.buffered_weight_tensors = [
819 self.buffer_tensor(
820 encoded_weights,
821 weight_tensor_purpose,
822 encoded_weights.double_buffer_sizes[0],
823 weight_tensor.name + "_buffer",
824 )
825 ]
826 if weight_tensor_purpose == TensorSubPurpose.DoubleBuffer:
827 buf2 = self.buffer_tensor(
828 encoded_weights,
829 weight_tensor_purpose,
830 encoded_weights.double_buffer_sizes[1],
831 weight_tensor.name + "_buffer2",
832 )
833 cost.buffered_weight_tensors.append(buf2)
834
835 last_used_buffer_idx = len(cost.ofm_depth_slices) % len(cost.buffered_weight_tensors)
836 weight_buffer_size = encoded_weights.double_buffer_sizes[last_used_buffer_idx]
837
Tim Halld8339a72021-05-27 18:49:40 +0100838 if ref_cost.cascade == 0:
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000839 # Determine if the lifetime can be extended and pre-buffer the first weight buffer
840 # under the previous operation
841 cost.buffered_weight_tensors[0].pre_buffer = encoded_weights.double_buffer_size() < slack_memory
Tim Halld8339a72021-05-27 18:49:40 +0100842
843 cost.slack_buffering_memory -= weight_buffer_size
844 else:
845 # Don't slice or buffer - use the whole depth from persistent storage
846 cost.ofm_depth_slices = ofm_full_depth_slices
847 encoded_weights = full_weights
Tim Halld784af72021-06-08 21:25:57 +0100848 encoded_scales = full_scales
Tim Halld8339a72021-05-27 18:49:40 +0100849
850 cost.npu_weights_tensor = encoded_weights
Tim Halld784af72021-06-08 21:25:57 +0100851 cost.npu_scales_tensor = encoded_scales
Tim Halld8339a72021-05-27 18:49:40 +0100852
Jacob Bohlineee9e5d2021-08-17 17:44:45 +0200853 def buffer_tensor(self, src_tensor: Tensor, sub_purpose: TensorSubPurpose, buffer_size: int, name: str) -> Tensor:
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000854 buffered_weight_tensor = Tensor([1, 1, 1, buffer_size], DataType.uint8, name)
Jacob Bohlineee9e5d2021-08-17 17:44:45 +0200855 buffered_weight_tensor.src_tensor = src_tensor
856 buffered_weight_tensor.mem_area = self.arch.fast_storage_mem_area
857 buffered_weight_tensor.mem_type = MemType.Scratch_fast
858 buffered_weight_tensor.purpose = TensorPurpose.Weights
859 buffered_weight_tensor.sub_purpose = sub_purpose
860 return buffered_weight_tensor
861
Tim Halld8339a72021-05-27 18:49:40 +0100862 def propose_minimal_schedule(self) -> Schedule:
863 """Proposes scheduling parameters where every operator is subdivided into the smallest stripe that satisfies the
864 next operators stride"""
865 min_schedule = Schedule(self.sg, "MIN")
866 cost_map = min_schedule.cost_map
867
868 # Keep track of the previous Op - which consumes the current Op's OFM
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100869 prev_op: Optional[SchedulerOperation] = None
Tim Halld8339a72021-05-27 18:49:40 +0100870 for sched_op in reversed(self.sched_ops):
871 min_stripe_height = prev_op.kernel.stride.y if prev_op else 1
872 min_stripe = sched_op.ofm.shape.with_height(min_stripe_height)
873
874 cost = sched_op.create_scheduler_info(self.nng, min_stripe)
875 cost.cycles = self.estimate_op_performance(sched_op, cost.block_config, sched_op.ofm.shape.depth)
876 cost_map[sched_op] = cost
877
878 prev_op = sched_op
879
880 return min_schedule
881
882 def propose_schedule_striping(self, final_stripe: Shape4D, label: str, ref_schedule: Schedule) -> Schedule:
883 """Proposes new striping for a schedule. The stripe is derived from the ifm requirements of the next Op down"""
884 ref_cost = ref_schedule.cost_map
885
886 striped_schedule = Schedule(self.sg, label)
887 stripe = final_stripe
888 for sched_op in reversed(self.sched_ops):
889 if sched_op not in ref_cost:
890 # sched_op is not part of the sub-schedule - skip
891 continue
892
893 # Create a cost entry with the new stripe
894 cost = sched_op.create_scheduler_info(self.nng, stripe)
895
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000896 weight_tensor = cost.npu_weights_tensor
897 for idx, buffered_tens in enumerate(ref_cost[sched_op].buffered_weight_tensors):
Jacob Bohlineee9e5d2021-08-17 17:44:45 +0200898 # If the weights are buffered in the reference schedule they should be in the new proposal
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000899 cost.buffered_weight_tensors.append(
900 self.buffer_tensor(
901 weight_tensor,
902 buffered_tens.sub_purpose,
903 weight_tensor.double_buffer_sizes[idx],
904 buffered_tens.name,
905 )
Jacob Bohlineee9e5d2021-08-17 17:44:45 +0200906 )
Tim Halld8339a72021-05-27 18:49:40 +0100907
908 # Estimate performance
909 cost.cycles = self.estimate_op_performance(sched_op, cost.block_config, sched_op.ofm.shape.depth)
910 striped_schedule.cost_map[sched_op] = cost
911
erik.andersson@arm.com8912f3a2022-08-16 11:08:57 +0200912 # Calculate the preceeding Op's stripe.
913
914 # In certain cases where an upscaling Op is cascaded,
915 # it may get instructed to produce an odd stripe height.
916 # Thus we need to force it back to even heights.
917 force_even_stripe_heights = False
918 for op in self.sched_ops:
919 # Check if the cascade has a Nearest Neighbor-op.
920 # If that is the case, force the stripes to be even.
921 if (
922 ref_cost.get(op, None)
923 and ref_cost.get(sched_op, None)
924 and ref_cost[op].cascade == ref_cost[sched_op].cascade
925 and is_nearest(op.resampling_mode)
926 ):
927 force_even_stripe_heights = True
928 break
929 upscaling_remainder = stripe.height % to_upscale(sched_op.resampling_mode)
930 height = stripe.height + (stripe.height % 2 if force_even_stripe_heights else upscaling_remainder)
Fredrik Svedbergd03dc502022-06-30 10:44:12 +0200931 stripe = sched_op.ifm.shape.with_height(height * sched_op.kernel.stride.y)
Tim Halld8339a72021-05-27 18:49:40 +0100932
933 return striped_schedule
934
935 def estimate_schedule_memory_usage(self, schedule: Schedule, non_local_mem_usage: dict):
936 """Estimates the memory usage of a schedule"""
937 cost = schedule.cost_map
938 cascades = schedule.cascades
939 peak_mem_usage = 0
940 for sched_op in self.sched_ops:
941 if sched_op not in cost:
942 # sched_op is not part of the sub-schedule - skip
943 continue
944
945 if cost[sched_op].cascade:
946 # This Op is part of a cascade - use the cascade's memory usage
947 cascade_info = cascades[cost[sched_op].cascade]
948 # Non-local memory usage is already included in the cascade_info
949 peak_mem_usage = max(cascade_info.mem_usage, peak_mem_usage)
950 else:
951 # This Op is not part of a cascade - calculate the memory usage
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000952 op_weight_buffer = sum(tens.storage_size() for tens in cost[sched_op].buffered_weight_tensors)
Tim Halld8339a72021-05-27 18:49:40 +0100953
954 op_mem_usage = (
955 sched_op.ifm_size_in_bytes()
956 + sched_op.ofm_size_in_bytes()
957 + op_weight_buffer
958 + non_local_mem_usage.get(sched_op, 0)
959 )
960 peak_mem_usage = max(op_mem_usage, peak_mem_usage)
961
962 return peak_mem_usage
963
Johan Alfvén255dad72022-07-16 18:27:05 +0200964 def build_cascades_for_min_schedule(self, min_schedule: Schedule, max_template: Schedule, memory_limit: int):
965 # Update memory snapshot
966 self.sg.schedule = min_schedule
967 self.update_op_memory_snapshot(min_schedule)
968
969 # Calculate residual memory for Min schedule
970 non_local_mem_usage = {}
971 for sched_op in self.sched_ops:
972 time_index = min_schedule.cost_map[sched_op].time_index
973
974 if self.arch.is_spilling_enabled():
975 # For Dedicated SRAM only the intermediate buffers are in SRAM, hence op_mem_usage is 0
976 op_mem_usage = 0
977 else:
978 # Min schedule only have ifm and ofm in SRAM (no buffered weigth tensors)
979 op_mem_usage = sched_op.ifm_size_in_bytes() + sched_op.ofm_size_in_bytes()
980
981 non_local_mem_usage[sched_op] = min_schedule.memory_snapshot[time_index] - op_mem_usage
982
983 # Crate cascades for Min schedule
984 cascade_builder = CascadeBuilder(self.sched_ops, self.arch.is_spilling_enabled(), non_local_mem_usage)
985 cascade_builder.build_cascades(min_schedule, max_template, memory_limit)
986
Tim Halld8339a72021-05-27 18:49:40 +0100987 def optimize_sub_schedule(
988 self, cascade_info: CascadeInfo, ref_schedule: Schedule, max_template: Schedule, memory_limit: int
989 ) -> Schedule:
990 """Extracts the Ops covered by the given cascade and creates a sub-schedule. The sub-schedule is optimized by
991 proposing weight buffering and then continously proposing new stripe sizes"""
992 ref_cost = ref_schedule.cost_map
993 # Extract the ops that are part of this sub-schedule
994 start = cascade_info.start
995 end = cascade_info.end
996 sub_schedule_ops = self.sched_ops[start : end + 1]
997 # Create a sub-schedule that contains only the costs for the Ops that are part of the sub-schedule
998 sub_schedule = Schedule(self.sg, f"SUB_{start}_{end}")
999 for sched_op in sub_schedule_ops:
1000 sub_schedule.cost_map[sched_op] = ref_cost[sched_op]
1001
1002 sub_schedule.cascades[end] = cascade_info
1003 # Use the memory snapshot from the reference schedule
1004 sub_schedule.memory_snapshot = ref_schedule.memory_snapshot
1005
1006 # Calculate memory usage that is live during the sub-schedule but not part of it
1007 time_for_cascade = ref_cost[sub_schedule_ops[0]].time_index
1008 mem_usage_parallel_to_sub_schedule = ref_schedule.memory_snapshot[time_for_cascade] - cascade_info.mem_usage
1009 # If the first Op's IFM has other consumers it has to live throughout the whole sub-schedule whether it's
1010 # included in a cascade or not
1011 persistent_initial_ifm = (
1012 sub_schedule_ops[0].ifm_size_in_bytes() if len(sub_schedule_ops[0].ifm.connection.consumers) > 1 else 0
1013 )
1014 # Calculate non-local-mem-usage per Operator
1015 non_local_mem_usage = {}
1016 for idx, sched_op in enumerate(sub_schedule_ops):
1017 non_local_mem_usage[sched_op] = mem_usage_parallel_to_sub_schedule
1018 if idx != 0:
1019 non_local_mem_usage[sched_op] += persistent_initial_ifm
1020
1021 cascade_builder = CascadeBuilder(sub_schedule_ops, self.arch.is_spilling_enabled(), non_local_mem_usage)
1022
1023 # Start by adding buffering
Tim Hall789e6f32021-06-17 17:02:31 +01001024 buffered_sub_schedule = self.propose_schedule_buffering(
1025 sub_schedule, self.scheduler_options.optimization_sram_limit
1026 )
Tim Halld8339a72021-05-27 18:49:40 +01001027 # Copy the cascades over from the unbuffered-schedule
1028 buffered_sub_schedule.cascades = sub_schedule.cascades
1029
1030 # Generate the possible stripings for the final Op in the sub-schedule
1031 final_ofm_shape = sub_schedule_ops[-1].ofm.shape
Johan Alfvén2a285fc2022-08-17 14:59:58 +02001032
1033 # Skip testing the min stripe used in the MIN schedule since that will be used
1034 # anyway if no new cascades are created below
1035 last_op = sub_schedule_ops[-1]
1036 min_stripe_h = sub_schedule.cost_map[last_op].stripe.height + 1
1037
Tim Halld8339a72021-05-27 18:49:40 +01001038 possible_stripes = [
Johan Alfvén2a285fc2022-08-17 14:59:58 +02001039 final_ofm_shape.with_height(stripe_h) for stripe_h in range(min_stripe_h, final_ofm_shape.height // 2 + 1)
Tim Halld8339a72021-05-27 18:49:40 +01001040 ]
Johan Alfvén2a285fc2022-08-17 14:59:58 +02001041 # Propose different striping
Jacob Bohlinfad72042021-08-24 21:51:41 +02001042 best_schedule = None
Johan Alfvén2a285fc2022-08-17 14:59:58 +02001043 max_nbr_of_cascades = 0
1044 for iteration, proposed_stripe in enumerate(possible_stripes):
Tim Halld8339a72021-05-27 18:49:40 +01001045 proposed_schedule = self.propose_schedule_striping(
1046 proposed_stripe, f"OPTIMIZED_{iteration}", buffered_sub_schedule
1047 )
1048
1049 cascade_builder.build_cascades(proposed_schedule, max_template, memory_limit)
1050
1051 # Check if proposal fits
1052 proposed_schedule_mem_usage = self.estimate_schedule_memory_usage(proposed_schedule, non_local_mem_usage)
Johan Alfvén2a285fc2022-08-17 14:59:58 +02001053
1054 nbr_of_cascades = len(proposed_schedule.cascades)
1055
1056 if iteration == 0:
1057 # First iteration - used as limit to prevent splitting up the cascades
1058 # Long cascades are better in order to reduce IFM/IFM dram bandwidth
1059 max_nbr_of_cascades = nbr_of_cascades
1060
1061 if (proposed_schedule_mem_usage) <= memory_limit and nbr_of_cascades <= max_nbr_of_cascades:
Tim Halld8339a72021-05-27 18:49:40 +01001062 best_schedule = proposed_schedule
Johan Alfvén2a285fc2022-08-17 14:59:58 +02001063
Tim Halld8339a72021-05-27 18:49:40 +01001064 if not proposed_schedule.cascades:
1065 # No cascading required - early exit
1066 break
1067 else:
Johan Alfvén2a285fc2022-08-17 14:59:58 +02001068 break
Tim Halld8339a72021-05-27 18:49:40 +01001069
1070 return best_schedule
1071
1072 def optimize_schedule(
Jonas Ohlssond8575072022-03-30 10:30:25 +02001073 self,
1074 schedule: Schedule,
1075 max_sched: Schedule,
1076 max_template: Schedule,
1077 options: SchedulerOptions,
Tim Halld8339a72021-05-27 18:49:40 +01001078 ) -> Schedule:
1079 """Extracts sub-schedules based on the cascades and optimizes them and applies them to the final schedule"""
1080 sram_limit = options.optimization_sram_limit
1081 if max_sched.fast_storage_peak_usage < sram_limit and not self.arch.is_spilling_enabled():
1082 # Maximum performance schedule fits within the SRAM target
1083 return max_sched
1084
Jacob Bohlinfad72042021-08-24 21:51:41 +02001085 # Iterate over a copy of the cascades since they may change during the loop
1086 for cascade_info in list(schedule.cascades.values()):
Tim Halld8339a72021-05-27 18:49:40 +01001087 # Optimize the sub-schedule in this cascade
1088 opt_sub_schedule = self.optimize_sub_schedule(cascade_info, schedule, max_template, sram_limit)
Jacob Bohlinfad72042021-08-24 21:51:41 +02001089 if opt_sub_schedule:
1090 # Remove the existing cascade
1091 del schedule.cascades[cascade_info.end]
1092 # Update the sub-schedule Op and cascade costs to the full schedule
1093 schedule.cost_map.update(opt_sub_schedule.cost_map)
1094 schedule.cascades.update(opt_sub_schedule.cascades)
Tim Halld8339a72021-05-27 18:49:40 +01001095
1096 # Update memory snapshot
1097 self.sg.schedule = schedule
1098 self.update_op_memory_snapshot(schedule)
1099 # Propose schedule buffering to the optimized schedule
Tim Hall789e6f32021-06-17 17:02:31 +01001100 optimized_sched = self.propose_schedule_buffering(schedule, self.scheduler_options.optimization_sram_limit)
Tim Halld8339a72021-05-27 18:49:40 +01001101 # Copy the cascade's metadata from the unbuffered schedule
1102 optimized_sched.cascades = schedule.cascades
1103 return optimized_sched
1104
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001105 def optimize_weight_buffering_size(
1106 self,
1107 min_schedule: Schedule,
1108 options: SchedulerOptions,
1109 ):
1110 default_schedule = self.sg.schedule
Tim Hallc1be0872022-03-03 17:50:52 +00001111 npu_performance.calc_new_performance_for_network(self.nng, self.arch, None, False)
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001112 default_tot_cycles = self.nng.cycles[npu_performance.PassCycles.Total]
1113 default_dram_cycles = self.nng.cycles[npu_performance.PassCycles.DramAccess]
1114
1115 # Restore mem/type for scratched_fms
1116 for tens in self.scratched_fms:
1117 tens.mem_area = self.scratched_fms[tens][0]
1118 tens.mem_type = self.scratched_fms[tens][1]
1119
1120 self.update_op_memory_snapshot(self.sg.schedule)
1121
1122 # Collect live ranges from tensors
1123 memories_list = [(self.arch.fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))]
1124 lr_graph = live_range.LiveRangeGraph()
1125 for mem_area, mem_type_set in memories_list:
1126 live_range.extract_live_ranges_from_cascaded_passes(
1127 self.nng.get_root_subgraph(),
1128 mem_area,
1129 mem_type_set,
1130 lr_graph,
1131 Tensor.AllocationQuantum,
1132 )
1133
1134 # Find the relation between the sched_op and the buffering tensor
1135 weight_ops = {}
1136 for sched_op in self.sched_ops:
1137 cost = self.sg.schedule.cost_map[sched_op]
Rickard Bolinfd8b5002022-05-16 09:11:06 +00001138 for tens in cost.buffered_weight_tensors:
1139 weight_ops[tens] = sched_op
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001140
1141 # Filter out weight buffer live ranges
1142 weight_lrs = []
1143 for lr in lr_graph.lrs:
1144 for tens in lr.tensors:
1145 if weight_ops.get(tens):
1146 weight_lrs.append(lr)
1147 break
1148
1149 # See if any evicted fm overlaps with a weight buffering op.
1150 # If this is the case add a size limitation to the buffering op
1151 for lr in self.evicted_fms:
1152 for weight_lr in weight_lrs:
1153 if lr.overlaps_ranges(weight_lr):
1154 for tens in weight_lr.tensors:
1155 sched_op = weight_ops.get(tens)
1156 if sched_op:
1157 # Add size reduction to the op
1158 sched_op.evicted_fms_size += lr.size
1159 break
1160
1161 self.sg.schedule = min_schedule
1162 self.update_op_memory_snapshot(self.sg.schedule)
1163
1164 # Run schedule buffering - with weight buffer size reduction
1165 schedule = self.propose_schedule_buffering(self.sg.schedule, options.optimization_sram_limit)
1166 schedule.cascades = self.sg.schedule.cascades
1167 self.sg.schedule = schedule
1168
1169 # Apply new buffer schdule and calc new performance
1170 self.update_op_memory_snapshot(self.sg.schedule)
1171 self.apply_schedule(self.sg.schedule)
1172 self.use_fast_storage_for_feature_maps(self.sg.schedule, options.optimization_sram_limit)
1173
Tim Hallc1be0872022-03-03 17:50:52 +00001174 npu_performance.calc_new_performance_for_network(self.nng, self.arch, None, False)
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001175 new_tot_cycles = self.nng.cycles[npu_performance.PassCycles.Total]
1176 new_dram_cycles = self.nng.cycles[npu_performance.PassCycles.DramAccess]
1177
Tim Hall8bc7a652022-05-19 15:29:23 +01001178 improvement_tot = (
1179 round((default_tot_cycles - new_tot_cycles) / default_tot_cycles, 2) if default_tot_cycles != 0 else 0
1180 )
1181 improvement_dram = (
1182 round((default_dram_cycles - new_dram_cycles) / default_dram_cycles, 2) if default_dram_cycles != 0 else 0
1183 )
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001184
1185 # Compare both total and dram improvement
Johan Alfvén3dae1b62022-05-17 10:26:48 +02001186 if not (improvement_tot >= 0 and improvement_dram > 0):
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001187 # No improvement, restore the default schedule
1188 for sched_op in self.sched_ops:
1189 sched_op.evicted_fms_size = 0
1190
1191 for tens in self.scratched_fms:
1192 tens.mem_area = self.scratched_fms[tens][0]
1193 tens.mem_type = self.scratched_fms[tens][1]
1194
1195 self.sg.schedule = default_schedule
1196 self.update_op_memory_snapshot(self.sg.schedule)
1197 self.apply_schedule(self.sg.schedule)
1198 self.use_fast_storage_for_feature_maps(self.sg.schedule, options.optimization_sram_limit)
1199
Tim Halld8339a72021-05-27 18:49:40 +01001200 def apply_schedule(self, sched: Schedule):
1201 """Applies the given schedule as a final solution"""
1202 for sched_op in self.sched_ops:
1203 op_info = sched.cost_map[sched_op]
1204 cascade_info = sched.cascades.get(op_info.cascade, None)
1205 if cascade_info and sched_op in cascade_info.buffers:
1206 buffer_tens = sched_op.ifm.connection.parent_tens
1207 # Apply memory area and type
1208 buffer_tens.mem_area = self.arch.fast_storage_mem_area
1209 buffer_tens.mem_type = MemType.Scratch_fast
1210 # Apply Rolling buffer
1211 buffer_tens.set_format(TensorFormat.NHCWB16, self.arch)
1212 buffer_tens.set_new_sub_purpose(TensorSubPurpose.RollingBufferY, cascade_info.buffers[sched_op].height)
1213
1214 sched_op.parent_ps.block_config = op_info.block_config.old_style_representation()
1215
1216 # Ensure that the src_tensor reference is set correctly
Rickard Bolinfd8b5002022-05-16 09:11:06 +00001217 for tens in op_info.buffered_weight_tensors:
1218 tens.src_tensor = op_info.npu_weights_tensor
Tim Halld8339a72021-05-27 18:49:40 +01001219
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001220 def use_fast_storage_for_feature_maps(self, schedule, staging_limit):
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001221 max_mem_usage = []
1222 base_mem_usage = []
1223 fast_storage_type = MemType.Scratch_fast
1224 fast_storage_mem_area = self.arch.fast_storage_mem_area
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001225 self.evicted_fms = []
Tim Halld8339a72021-05-27 18:49:40 +01001226
1227 # Force all OFMs to fast-storage
1228 for sched_op in self.sched_ops:
1229 cost = schedule.cost_map[sched_op]
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001230 if cost.cascade == 0 and sched_op.get_dependants():
1231 ofm_tens = sched_op.ofm.connection.parent_tens
1232 if not any(cons is None for cons in ofm_tens.consumer_list):
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001233 if ofm_tens not in self.scratched_fms:
1234 # Remember default mem area and mem type, only done once
1235 self.scratched_fms[ofm_tens] = (ofm_tens.mem_area, ofm_tens.mem_type)
1236
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001237 ofm_tens.mem_area = fast_storage_mem_area
1238 ofm_tens.mem_type = fast_storage_type
Tim Halld8339a72021-05-27 18:49:40 +01001239
1240 # Collect live ranges from tensors
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001241 memories_list = [(fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))]
Tim Halld8339a72021-05-27 18:49:40 +01001242 lr_graph = live_range.LiveRangeGraph()
1243 for mem_area, mem_type_set in memories_list:
1244 live_range.extract_live_ranges_from_cascaded_passes(
Jonas Ohlssond8575072022-03-30 10:30:25 +02001245 self.nng.get_root_subgraph(),
1246 mem_area,
1247 mem_type_set,
1248 lr_graph,
1249 Tensor.AllocationQuantum,
Tim Halld8339a72021-05-27 18:49:40 +01001250 )
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001251 max_mem_usage = lr_graph.get_temporal_memory_usage(fast_storage_mem_area)
Tim Halld8339a72021-05-27 18:49:40 +01001252
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001253 # If true, everything fits and we can proceed
1254 if max(max_mem_usage) <= staging_limit:
1255 return
1256
1257 # Build up the base memory usage by removing the
1258 # mem_usage of the lrs we previously moved to fast-storage
1259 base_mem_usage = np.array(max_mem_usage)
1260 curr_lrs = []
Tim Halld8339a72021-05-27 18:49:40 +01001261 for lr in lr_graph.lrs:
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001262 for tens in lr.tensors:
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001263 if self.scratched_fms.get(tens):
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001264 curr_lrs.append(lr)
1265 base_mem_usage[lr.start_time : lr.end_time + 1] -= lr.size
1266 break
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001267 competing_lrs = []
Johan Alfvén5c309712022-06-10 15:40:58 +02001268 competing_tens_access = {}
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001269 for lr in curr_lrs:
1270 base_usage = max(base_mem_usage[lr.start_time : lr.end_time + 1])
1271 # If true, the lr will never fit and may thus be evicted
1272 if base_usage + lr.size > staging_limit:
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001273 self.evicted_fms.append(lr)
1274 FastStorageComponentAllocator.evict(lr, max_mem_usage, self.scratched_fms)
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001275 continue
1276 # Since max_mem_usage is the memory usage with all FMs still in fast-storage,
1277 # the memory limit cannot be exceeded if max_mem_usage does not.
1278 # Thus, the affected lrs can remain in fast-storage if the following is true
1279 if max(max_mem_usage[lr.start_time : lr.end_time + 1]) <= staging_limit:
1280 FastStorageComponentAllocator.keep(lr, base_mem_usage, staging_limit)
1281 else:
1282 competing_lrs.append(lr)
Johan Alfvén5c309712022-06-10 15:40:58 +02001283 for tens in lr.tensors:
1284 competing_tens_access[tens] = 0
1285
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001286 sz = len(competing_lrs)
1287 # All lrs and their tensors have been handled if sz is zero, we may thus return
1288 if sz == 0:
1289 return
1290
Johan Alfvén5c309712022-06-10 15:40:58 +02001291 # Estimate element access for all tensors that are competing for a place in fast-storage.
1292 # This number is used when deciding which tensor that stays in fast-storage
1293 for sched_op in self.sched_ops:
1294 cost = schedule.cost_map[sched_op]
1295
1296 if competing_tens_access.get(sched_op.ifm.connection.parent_tens) is not None:
1297 tens = sched_op.ifm.connection.parent_tens
1298 access = self.estimate_element_access(sched_op, cost.block_config, sched_op.ofm.shape.depth)
1299 competing_tens_access[tens] += access.ifm_read[0]
1300
1301 if sched_op.ifm2 and competing_tens_access.get(sched_op.ifm2.connection.parent_tens) is not None:
1302 tens = sched_op.ifm2.connection.parent_tens
1303 access = self.estimate_element_access(sched_op, cost.block_config, sched_op.ofm.shape.depth)
1304 competing_tens_access[tens] += access.ifm_read[1]
1305
1306 if competing_tens_access.get(sched_op.ofm.connection.parent_tens) is not None:
1307 tens = sched_op.ofm.connection.parent_tens
1308 access = self.estimate_element_access(sched_op, cost.block_config, sched_op.ofm.shape.depth)
1309 competing_tens_access[tens] += access.ofm_write
1310
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001311 competing_lrs = sorted(competing_lrs, key=lambda lr: (lr.start_time, lr.end_time + 1, lr.size))
1312 start = 0
1313 start_time = competing_lrs[0].start_time
1314 end_time = competing_lrs[0].end_time
1315 component_allocator = FastStorageComponentAllocator(base_mem_usage, max_mem_usage, staging_limit)
1316 # Build up components and then allocate each separately
1317 for i, lr in enumerate(competing_lrs):
Johan Alfvén5c309712022-06-10 15:40:58 +02001318 if lr.start_time <= end_time and i - start < component_allocator.MAX_EXHAUSTIVE_LIFE_RANGE:
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001319 start_time = min(start_time, lr.start_time)
1320 end_time = max(end_time, lr.end_time)
1321 else:
1322 component_allocator.allocate_component(
1323 component_allocator,
1324 competing_lrs[start:i],
1325 max_mem_usage,
1326 base_mem_usage,
1327 staging_limit,
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001328 self.scratched_fms,
Johan Alfvén5c309712022-06-10 15:40:58 +02001329 competing_tens_access,
Johan Alfvén68b8f2f2022-06-24 08:42:19 +02001330 self.evicted_fms,
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001331 )
1332 start = i
1333 start_time = lr.start_time
1334 end_time = lr.end_time
1335 component_allocator.allocate_component(
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001336 component_allocator,
1337 competing_lrs[start:sz],
1338 max_mem_usage,
1339 base_mem_usage,
1340 staging_limit,
1341 self.scratched_fms,
Johan Alfvén5c309712022-06-10 15:40:58 +02001342 competing_tens_access,
Johan Alfvén68b8f2f2022-06-24 08:42:19 +02001343 self.evicted_fms,
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001344 )
Tim Halld8339a72021-05-27 18:49:40 +01001345
1346 def move_constant_data(self):
1347 """Determine if data, can be moved from permanent storage to another memory area. A move
1348 will generate a DMA command in the high-level command stream"""
1349 for sched_op in self.sched_ops:
1350 parent_op = sched_op.parent_op
1351 is_lut_used = any(inp.purpose == TensorPurpose.LUT for inp in parent_op.inputs)
1352 max_ifm_shram_avail = (
1353 (self.arch.available_shram_banks(is_lut_used) - self.arch.shram_reserved_output_banks)
1354 * self.arch.shram_bank_size
1355 // 2
1356 )
1357
1358 for idx, tens in enumerate(parent_op.inputs):
1359 if tens.mem_type not in (MemType.Scratch, MemType.Scratch_fast):
1360 # Tensor is in permanent storage
1361 # Only when permanent storage differs from feature map storage, there is a point moving the data
1362 if (
1363 tens.mem_area in self.arch.permanent_storage_mem_area
1364 and self.arch.permanent_storage_mem_area != self.arch.feature_map_storage_mem_area
1365 ) or tens.purpose == TensorPurpose.LUT:
1366 if tens.purpose == TensorPurpose.LUT or (
Patrik Gustavsson94292fe2021-09-02 08:22:58 +02001367 # For elementwise broadcast
Tim Halld8339a72021-05-27 18:49:40 +01001368 tens.purpose == TensorPurpose.FeatureMap
1369 and sched_op.op_type.is_binary_elementwise_op()
1370 and tens.shape != []
1371 and sched_op.ifm.shape != sched_op.ofm.shape
Patrik Gustavsson94292fe2021-09-02 08:22:58 +02001372 and parent_op.write_shape is None
Tim Halld8339a72021-05-27 18:49:40 +01001373 and tens.storage_size() > max_ifm_shram_avail
1374 ):
1375 only_vector_product_consumers = all(
1376 oper and oper.type.npu_block_type == NpuBlockType.VectorProduct
1377 for oper in tens.consumers()
1378 )
1379
1380 if (not only_vector_product_consumers) or tens.purpose == TensorPurpose.LUT:
1381 new_tens = tens.clone_into_fast_storage(self.arch)
1382 if tens.purpose == TensorPurpose.LUT:
1383 new_tens.mem_area = MemArea.Shram
1384
1385 new_tens.consumer_list.append(parent_op)
1386 parent_op.inputs[idx] = new_tens
Dwight Lidman352607c2021-09-29 17:00:09 +02001387 # If the index is out of range, IFM and IFM2 are the same tensor
1388 # and pass inputs don't have duplicates
1389 if idx < len(sched_op.parent_ps.inputs):
1390 sched_op.parent_ps.inputs[idx] = new_tens
Tim Halld8339a72021-05-27 18:49:40 +01001391
1392 def print_schedule(self, schedule: Schedule):
1393 print(f"Schedule: '{schedule.name}'")
1394 for sched_op in self.sched_ops:
1395 if sched_op not in schedule.cost_map:
1396 # Sub-schedule printing
1397 continue
1398
1399 op_info = schedule.cost_map[sched_op]
1400 print(f"\t{sched_op.index}: Operation {sched_op.name} - OFM {sched_op.ofm.shape}")
1401 print(f"\t\tType: {sched_op.op_type}")
1402 print(f"\t\tKernel: {sched_op.kernel}")
1403 print(f"{op_info}")
1404 mem_usage = (
1405 schedule.memory_snapshot[op_info.time_index]
1406 if op_info.time_index < len(schedule.memory_snapshot)
1407 else 0
1408 )
1409 print(f"\t\tSRAM Used: {mem_usage} bytes")
1410
Jonas Ohlsson25e700c2022-03-04 14:58:56 +01001411 print("\tCascades:")
Tim Halld8339a72021-05-27 18:49:40 +01001412 for i, cascade in enumerate(schedule.cascades.values()):
1413 print(f"\t\t{i}: {cascade.start} -> {cascade.end}, size: {cascade.mem_usage}")
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +02001414
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001415
Tim Halld8339a72021-05-27 18:49:40 +01001416def _update_tensor_allocation(nng: Graph, arch: ArchitectureFeatures, options):
1417 """
1418 Creates live ranges and runs tensor allocator for the current schedule
1419 (i.e. sg.schedule for all subgraphs), returns the maximum memory usage
1420 and updates SchedulerOpInfo.mem_usage for all operations in the schedule.
1421 """
1422 root_sg = nng.get_root_subgraph()
1423
1424 alloc_list = []
1425 if arch.is_spilling_enabled():
1426 mem_alloc_scratch_fast = (arch.fast_storage_mem_area, set((MemType.Scratch_fast,)))
1427 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch,)))
1428 # Order is important
1429 alloc_list.append(mem_alloc_scratch_fast)
1430 alloc_list.append(mem_alloc_scratch)
1431 else:
1432 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))
1433 alloc_list.append(mem_alloc_scratch)
1434
1435 for mem_area, mem_type_set in alloc_list:
1436 tensor_allocation.allocate_tensors(
1437 nng,
1438 root_sg,
1439 arch,
1440 mem_area,
1441 mem_type_set,
1442 tensor_allocator=options.tensor_allocator,
1443 verbose_allocation=options.verbose_allocation,
1444 cpu_tensor_alignment=options.cpu_tensor_alignment,
Tim Hallcda4fcb2022-05-19 12:36:58 +01001445 hillclimb_max_iterations=options.hillclimb_max_iterations,
Tim Halld8339a72021-05-27 18:49:40 +01001446 )
1447
1448
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001449class FastStorageComponentAllocator:
Johan Alfvén5c309712022-06-10 15:40:58 +02001450 MAX_EXHAUSTIVE_LIFE_RANGE = 20
1451
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001452 def __init__(self, base_mem_usage, max_mem_usage, staging_limit):
1453 self.base_mem_usage = base_mem_usage
1454 self.max_mem_usage = list(max_mem_usage)
1455 self.staging_limit = staging_limit
1456 self.lrs = []
1457 self.evicted = []
1458 self.curr_evicted = []
1459 self.remaining_total_size = []
Johan Alfvén5c309712022-06-10 15:40:58 +02001460 self.best_score = 0
1461 self.competing_tens_access = {}
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001462
Johan Alfvén5c309712022-06-10 15:40:58 +02001463 def allocate_exhaustive(self, ix, score):
1464 # Favour tensors with highest element access (score)
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001465 if ix >= len(self.lrs):
Johan Alfvén5c309712022-06-10 15:40:58 +02001466 if score > self.best_score:
1467 self.best_score = score
Louis Verhaard5c8f1e52022-02-23 14:13:07 +01001468 self.evicted = self.curr_evicted.copy()
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001469 return
1470
1471 lr = self.lrs[ix]
1472 for t in range(lr.start_time, lr.end_time):
1473 assert self.base_mem_usage[t] <= self.max_mem_usage[t]
1474 base_usage = max(self.base_mem_usage[lr.start_time : lr.end_time + 1])
1475 can_fit = base_usage + lr.size <= self.staging_limit
1476 always_fits = can_fit
1477
1478 if can_fit:
1479 max_usage = max(self.max_mem_usage[lr.start_time : lr.end_time + 1])
1480 always_fits = max_usage <= self.staging_limit
1481
1482 if can_fit or always_fits:
1483 self.curr_evicted[ix] = False
1484 self.base_mem_usage = self.update_mem_usage(self.base_mem_usage, lr, True)
Johan Alfvén5c309712022-06-10 15:40:58 +02001485 tens = lr.tensors[0]
1486 # Tensor is being included - add tensor element access to the score
1487 self.allocate_exhaustive(ix + 1, score + self.competing_tens_access[tens])
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001488 self.base_mem_usage = self.update_mem_usage(self.base_mem_usage, lr, False)
1489
1490 if not always_fits:
1491 self.curr_evicted[ix] = True
1492 self.max_mem_usage = self.update_mem_usage(self.max_mem_usage, lr, False)
Johan Alfvén5c309712022-06-10 15:40:58 +02001493 self.allocate_exhaustive(ix + 1, score)
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001494 self.max_mem_usage = self.update_mem_usage(self.max_mem_usage, lr, True)
1495
1496 @staticmethod
1497 def update_mem_usage(mem_usage, lr, increase):
1498 for t in range(lr.start_time, lr.end_time + 1):
1499 mem_usage[t] += lr.size if increase else -lr.size
1500 assert mem_usage[t] >= 0
1501 return mem_usage
1502
1503 @staticmethod
1504 def evict(lr, max_mem_usage, scratched_fms):
1505 for t in range(lr.start_time, lr.end_time + 1):
1506 max_mem_usage[t] -= lr.size
1507 for tens in lr.tensors:
1508 if tens in scratched_fms:
1509 tens.mem_area = scratched_fms[tens][0]
1510 tens.mem_type = scratched_fms[tens][1]
1511
1512 @staticmethod
1513 def keep(lr, base_mem_usage, staging_limit):
1514 for t in range(lr.start_time, lr.end_time + 1):
1515 base_mem_usage[t] += lr.size
1516 assert base_mem_usage[t] <= staging_limit
1517
Johan Alfvén68b8f2f2022-06-24 08:42:19 +02001518 def allocate_component(
1519 self, allocator, lrs, max_mem, min_mem, staging_limit, scratched_fms, competing_tens_access, evicted_fms
1520 ):
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001521 sz = len(lrs)
1522 allocator.lrs = lrs
1523 allocator.evicted = [0] * len(lrs)
1524 allocator.curr_evicted = [0] * sz
Johan Alfvén5c309712022-06-10 15:40:58 +02001525 allocator.best_score = -1
1526 allocator.competing_tens_access = competing_tens_access
1527 # Recursively evaluate all permutations of allocations of the lrs found in the component.
1528 # For every permutation that fits within the staging_limit there is a score calculated.
1529 # The permutation with the highest score will then be chosen. The score is calculated
1530 # as the sum of the actual element access (ifm read and ofm write) for all the
1531 # including tensors. So it is not necessary the tensor with the biggest size that ends up
1532 # being included in the result.
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001533 allocator.allocate_exhaustive(0, 0)
1534
1535 # Optimal allocation has been found, move lrs accordingly
1536 for i, e in enumerate(allocator.evicted):
1537 if e:
1538 self.evict(lrs[i], max_mem, scratched_fms)
Johan Alfvén68b8f2f2022-06-24 08:42:19 +02001539 if lrs[i] not in evicted_fms:
1540 evicted_fms.append(lrs[i])
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001541 else:
1542 self.keep(lrs[i], min_mem, staging_limit)
Johan Alfvén68b8f2f2022-06-24 08:42:19 +02001543 if lrs[i] in evicted_fms:
1544 evicted_fms.remove(lrs[i])
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001545
1546
Tim Halld8339a72021-05-27 18:49:40 +01001547def schedule_passes(nng: Graph, arch: ArchitectureFeatures, options, scheduler_options: SchedulerOptions):
1548 """Entry point for the Scheduler"""
1549 # Initialize CPU subgraphs
1550 schedulers = dict()
1551 # Initialize schedulers with max schedule. Only schedule NPU subgraphs
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001552 for sg in nng.subgraphs:
Tim Halld8339a72021-05-27 18:49:40 +01001553 if sg.placement != PassPlacement.Npu:
1554 # Create cascaded passes for CPU Ops
1555 cascaded_passes = []
1556 for idx, ps in enumerate(sg.passes):
1557 cps = CascadedPass(
Jonas Ohlssond8575072022-03-30 10:30:25 +02001558 ps.name,
1559 SchedulingStrategy.WeightStream,
1560 ps.inputs,
1561 [],
1562 ps.outputs,
1563 [ps],
1564 ps.placement,
1565 False,
Tim Halld8339a72021-05-27 18:49:40 +01001566 )
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001567
Tim Halld8339a72021-05-27 18:49:40 +01001568 cps.time = idx
1569 ps.cascade = cps
1570 cascaded_passes.append(cps)
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001571
Tim Halld8339a72021-05-27 18:49:40 +01001572 sg.cascaded_passes = cascaded_passes
1573 else:
1574 # Npu subgraph - create schedule
1575 scheduler = Scheduler(nng, sg, arch, scheduler_options)
1576 schedulers[sg] = scheduler
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001577
Tim Halld8339a72021-05-27 18:49:40 +01001578 scheduler.create_scheduler_representation(arch)
1579 sg.sched_ops = scheduler.sched_ops
1580 scheduler.move_constant_data()
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001581
Tim Halld8339a72021-05-27 18:49:40 +01001582 # Create the Max schedule template
1583 max_schedule_template = scheduler.create_initial_schedule()
1584 scheduler.max_schedule = max_schedule_template
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001585
Tim Halld8339a72021-05-27 18:49:40 +01001586 # Create the optimimised Max schedule
1587 sg.schedule = max_schedule_template
1588 scheduler.update_op_memory_snapshot(max_schedule_template)
Tim Hall789e6f32021-06-17 17:02:31 +01001589 opt_max_schedule = scheduler.propose_schedule_buffering(max_schedule_template, 1 << 32)
Tim Halld8339a72021-05-27 18:49:40 +01001590 sg.schedule = opt_max_schedule
1591 scheduler.update_op_memory_snapshot(opt_max_schedule)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001592
Tim Halld8339a72021-05-27 18:49:40 +01001593 # Create Min schedule
1594 min_schedule = scheduler.propose_minimal_schedule()
1595 initial_sram_limit = scheduler_options.optimization_sram_limit
1596 if scheduler_options.optimization_strategy == OptimizationStrategy.Size:
1597 initial_sram_limit = scheduler.min_memory_req
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001598
Johan Alfvén255dad72022-07-16 18:27:05 +02001599 # Build cascades for Min schedule
1600 scheduler.build_cascades_for_min_schedule(min_schedule, max_schedule_template, initial_sram_limit)
Tim Halld8339a72021-05-27 18:49:40 +01001601 sg.schedule = min_schedule
1602 scheduler.update_op_memory_snapshot(min_schedule)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001603
Tim Halld8339a72021-05-27 18:49:40 +01001604 if scheduler_options.optimization_strategy == OptimizationStrategy.Performance:
1605 # Create an optimized schedule
1606 sg.schedule = scheduler.optimize_schedule(
1607 min_schedule, opt_max_schedule, max_schedule_template, scheduler_options
1608 )
1609 scheduler.update_op_memory_snapshot(sg.schedule)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001610
Tim Halld8339a72021-05-27 18:49:40 +01001611 scheduler.apply_schedule(sg.schedule)
1612 scheduler.use_fast_storage_for_feature_maps(sg.schedule, scheduler_options.optimization_sram_limit)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001613
Johan Alfvén6f4cb032022-05-05 08:42:46 +02001614 if scheduler_options.optimization_strategy == OptimizationStrategy.Performance and scheduler.evicted_fms:
1615 # It might be possible to gain performance by reducing
1616 # weight buffer size and instead fit fms in fast storage
1617 scheduler.optimize_weight_buffering_size(min_schedule, scheduler_options)
1618
Tim Halld8339a72021-05-27 18:49:40 +01001619 if scheduler_options.verbose_schedule:
1620 scheduler.print_schedule(sg.schedule)
Tim Hall79d07d22020-04-27 18:20:16 +01001621
Tim Halld8339a72021-05-27 18:49:40 +01001622 # Evaluate schedule
1623 _update_tensor_allocation(nng, arch, options)