blob: 73133bcd829f9496a6a91e90c2fe62675769c4eb [file] [log] [blame]
Tim Halld8339a72021-05-27 18:49:40 +01001# Copyright (C) 2021 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
27from typing import Dict
28from typing import List
29from typing import Optional
30from typing import Tuple
Jonas Ohlsson845e2322022-03-01 12:39:55 +010031from typing import TYPE_CHECKING
32
33# Import needed for Type annotations. Only import for Type checking to avoid run-time errors due to cyclic import.
34if TYPE_CHECKING:
35 from .npu_performance import CycleCost
Diego Russoea6111a2020-04-14 18:41:58 +010036
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +010037import numpy as np
38
Diego Russoea6111a2020-04-14 18:41:58 +010039from . import live_range
Tim Hall79d07d22020-04-27 18:20:16 +010040from . import npu_performance
Tim Halld8339a72021-05-27 18:49:40 +010041from . import tensor_allocation
42from . import weight_compressor
43from .architecture_allocator import ArchitectureBlockConfig
44from .architecture_allocator import find_block_config
45from .architecture_allocator import get_ifm_area_required
Tim Halld8339a72021-05-27 18:49:40 +010046from .architecture_features import ArchitectureFeatures
47from .architecture_features import Block
48from .cascade_builder import CascadeBuilder
49from .cascade_builder import CascadeInfo
Fredrik Svedberg880e7352020-08-25 11:31:47 +020050from .data_type import DataType
Diego Russoe8a10452020-04-21 17:39:10 +010051from .nn_graph import CascadedPass
Tim Halld8339a72021-05-27 18:49:40 +010052from .nn_graph import Graph
53from .nn_graph import Pass
Diego Russoe8a10452020-04-21 17:39:10 +010054from .nn_graph import PassPlacement
Diego Russoe8a10452020-04-21 17:39:10 +010055from .nn_graph import SchedulingStrategy
Tim Halld8339a72021-05-27 18:49:40 +010056from .nn_graph import Subgraph
57from .numeric_util import round_down
58from .numeric_util import round_up
Diego Russoe8a10452020-04-21 17:39:10 +010059from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020060from .operation import Op
Tim Halld8339a72021-05-27 18:49:40 +010061from .shape4d import Shape4D
Diego Russoe8a10452020-04-21 17:39:10 +010062from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020063from .tensor import MemType
Tim Halld8339a72021-05-27 18:49:40 +010064from .tensor import Tensor
Diego Russoe8a10452020-04-21 17:39:10 +010065from .tensor import TensorFormat
66from .tensor import TensorPurpose
67from .tensor import TensorSubPurpose
Jonas Ohlsson845e2322022-03-01 12:39:55 +010068from .weight_compressor import NpuWeightTensor
Jacob Bohlin1a666972020-09-11 10:04:15 +020069
Tim Hall79d07d22020-04-27 18:20:16 +010070
Tim Halld8339a72021-05-27 18:49:40 +010071def shape_for_format(shape: Shape4D, tensor_format: TensorFormat) -> Shape4D:
72 if tensor_format == TensorFormat.NHCWB16:
73 return shape.with_depth(round_up(shape.depth, 16))
74
75 return shape
76
77
78class OptimizationStrategy(IntEnum):
79 """Enum defining the different optimization strategies for the Scheduler"""
80
81 Size = auto()
82 Performance = auto()
Tim Hall79d07d22020-04-27 18:20:16 +010083
84 def __str__(self):
85 return self.name
86
87
Tim Halld8339a72021-05-27 18:49:40 +010088class SchedulerOpInfo:
89 """Contains metadata about a SchedulerOperation that is unique to one Schedule"""
90
Tim Hall79d07d22020-04-27 18:20:16 +010091 def __init__(
92 self,
Tim Halld8339a72021-05-27 18:49:40 +010093 block_config: ArchitectureBlockConfig,
94 weights_size: int,
95 stripe_input: Shape4D,
96 stripe_input2: Optional[Shape4D],
97 stripe: Shape4D,
Tim Hall79d07d22020-04-27 18:20:16 +010098 ):
Tim Halld8339a72021-05-27 18:49:40 +010099 self.block_config = block_config
100 self.weights_size = weights_size
101 self.stripe_input = stripe_input
102 self.stripe_input2 = stripe_input2
103 self.stripe = stripe
104 self.cascade = 0 # Assigned by CascadeBuilder. 0 means not part of a cascade
105 self.time_index = None # Set by update_op_memory_snapshot
106 self.ofm_depth_slices: List[int] = [0, stripe.depth]
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100107 self.npu_weights_tensor: Optional[NpuWeightTensor] = None
108 self.npu_scales_tensor: Optional[NpuWeightTensor] = None
109 self.buffered_weight_tensor: Optional[Tensor] = None
110 self.cycles: Optional[CycleCost] = None
Tim Halld8339a72021-05-27 18:49:40 +0100111 self.slack_buffering_cycles = 0
112 self.slack_buffering_memory = 0
113 self.full_weight_transfer_cycles = 0
114
115 def copy(self):
116 res = SchedulerOpInfo(self.block_config, self.weights_size, self.stripe_input, self.stripe_input2, self.stripe,)
117 res.cascade = self.cascade
118 return res
119
120 def __str__(self):
121 res = f"\t\tBlock Config = {self.block_config}\n"
122 res += f"\t\tOFM Block = {self.block_config.ofm_block}\n"
123 res += f"\t\tIFM Stripe = {self.stripe_input}\n"
124 res += f"\t\tIFM2 Stripe = {self.stripe_input2}\n"
125 res += f"\t\tOFM Stripe = {self.stripe}\n"
126 res += f"\t\tEncoded Weights = {self.npu_weights_tensor and len(self.npu_weights_tensor.buffer)} bytes\n"
127 res += (
128 f"\t\tWeight buffer = {self.buffered_weight_tensor and self.buffered_weight_tensor.storage_size()} bytes\n"
129 )
130 res += f"\t\tDepth slices = {self.ofm_depth_slices}\n"
131 res += f"\t\tAssigned Cascade = {self.cascade}"
132 return res
133
134
135class SchedulerOptions:
136 """Contains options for the Scheduler"""
137
138 def __init__(
139 self, optimization_strategy, sram_target, verbose_schedule,
140 ):
141 self.optimization_strategy = optimization_strategy
142 self.optimization_sram_limit = sram_target
Tim Hall79d07d22020-04-27 18:20:16 +0100143 self.verbose_schedule = verbose_schedule
Tim Hall79d07d22020-04-27 18:20:16 +0100144
Tim Halld8339a72021-05-27 18:49:40 +0100145 def __str__(self) -> str:
146 return f"{type(self).__name__}: {str(self.__dict__)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100147
148 __repr__ = __str__
149
150
Tim Halld8339a72021-05-27 18:49:40 +0100151class SchedulerTensor:
152 def __init__(self, shape, dt, mem_area, _format):
153 self.dtype = dt
154 self.mem_area = mem_area
155 self.shape = shape
156 self.format = _format
157 self.connection = None
Tim Hall79d07d22020-04-27 18:20:16 +0100158
Tim Halld8339a72021-05-27 18:49:40 +0100159
160class SchedulerOperation:
161 """Scheduler internal representation of 'Operation'
162 This class can be seen as a node within the Scheduler Graph representation
163 """
164
165 def __init__(self, ps: Pass, arch: ArchitectureFeatures, nng: Graph):
166 self.arch = arch
167 self.parent_ps = ps
168 self.parent_op = ps.primary_op
169 self.name = ps.primary_op.name
170 self.op_type = ps.primary_op.type
171 self.activation = ps.primary_op.activation
172 self.kernel = ps.primary_op.kernel
173 self.resampling_mode = ps.primary_op.ifm.resampling_mode
174 self.uses_scalar = ps.primary_op.ifm2 is not None and (
175 ps.primary_op.ifm.shape == [] or ps.primary_op.ifm2.shape == []
Tim Hall79d07d22020-04-27 18:20:16 +0100176 )
Tim Halld8339a72021-05-27 18:49:40 +0100177 self.ifm_ublock = arch.ifm_ublock
Tim Hall79d07d22020-04-27 18:20:16 +0100178
Tim Halld8339a72021-05-27 18:49:40 +0100179 self.ifm = SchedulerTensor(ps.ifm_shapes[0], ps.ifm_tensor.dtype, ps.ifm_tensor.mem_area, ps.ifm_tensor.format,)
Tim Hall79d07d22020-04-27 18:20:16 +0100180
Tim Halld8339a72021-05-27 18:49:40 +0100181 self.ifm2 = None
182 if ps.ifm2_tensor:
183 self.ifm2 = SchedulerTensor(
184 ps.ifm_shapes[1], ps.ifm2_tensor.dtype, ps.ifm2_tensor.mem_area, ps.ifm2_tensor.format,
185 )
Tim Hall79d07d22020-04-27 18:20:16 +0100186
Tim Halld8339a72021-05-27 18:49:40 +0100187 self.ofm = SchedulerTensor(ps.ofm_shapes[0], ps.ofm_tensor.dtype, ps.ofm_tensor.mem_area, ps.ofm_tensor.format,)
Tim Hall79d07d22020-04-27 18:20:16 +0100188
Tim Halld8339a72021-05-27 18:49:40 +0100189 # Input volume width and height required to produce the smallest possible stripe
190 self.min_stripe_input_w, self.min_stripe_input_h = self._calculate_min_stripe_input()
Tim Hall79d07d22020-04-27 18:20:16 +0100191
Tim Halld8339a72021-05-27 18:49:40 +0100192 # Flags that marks whether this SchedulerOperation requires full IFM/OFM
193 self.requires_full_ifm = False
194 self.requires_full_ifm2 = False
195 self.requires_full_ofm = False
Tim Hall79d07d22020-04-27 18:20:16 +0100196
Tim Halld8339a72021-05-27 18:49:40 +0100197 self.index = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100198
Tim Halld8339a72021-05-27 18:49:40 +0100199 def add_ifm_connection(self, conn: "Connection"):
200 """Add input connection to another SchedulerOperation or Subgraph Input"""
201 conn.consumers.append(self)
202 self.ifm.connection = conn
Tim Hall79d07d22020-04-27 18:20:16 +0100203
Tim Halld8339a72021-05-27 18:49:40 +0100204 def add_ifm2_connection(self, conn: "Connection"):
205 """Add input connection to another SchedulerOperation or Subgraph Input"""
206 if self.ifm2:
207 conn.consumers.append(self)
208 self.ifm2.connection = conn
Tim Hall79d07d22020-04-27 18:20:16 +0100209 else:
Tim Halld8339a72021-05-27 18:49:40 +0100210 assert False, f"Trying to set an IFM2 Connection to {self} which has no IFM2"
Tim Hall79d07d22020-04-27 18:20:16 +0100211
Tim Halld8339a72021-05-27 18:49:40 +0100212 def add_ofm_connection(self, conn: "Connection"):
213 """Add output connection to another SchedulerOperation or Subgraph Output"""
214 conn.producers.append(self)
215 self.ofm.connection = conn
216
217 def get_dependants(self):
218 """Returns a list of the Ops that depend on this Operation's OFM"""
219 return self.ofm.connection.consumers
220
221 def ifm_size_in_bytes(self) -> int:
222 """Returns size of the IFM in bytes"""
223 ifm_storage_shape = shape_for_format(self.ifm.shape, self.ifm.format)
224 return round_up(ifm_storage_shape.elements() * self.ifm.dtype.size_in_bytes(), Tensor.AllocationQuantum)
225
226 def ifm2_size_in_bytes(self) -> int:
227 """Returns size of the IFM2 in bytes"""
228 if self.ifm2:
229 ifm2_storage_shape = shape_for_format(self.ifm2.shape, self.ifm2.format)
230 return round_up(ifm2_storage_shape.elements() * self.ifm2.dtype.size_in_bytes(), Tensor.AllocationQuantum)
231
232 return 0
233
234 def ofm_size_in_bytes(self) -> int:
235 """Returns size of the OFM in bytes"""
236 ofm_storage_shape = shape_for_format(self.ofm.shape, self.ofm.format)
237 return round_up(ofm_storage_shape.elements() * self.ofm.dtype.size_in_bytes(), Tensor.AllocationQuantum)
238
239 def create_scheduler_info(self, nng: Graph, stripe: Shape4D) -> SchedulerOpInfo:
240 """Returns schedule info about this SchedulerOperation based on how many ofm elements it should produce"""
241 ifm_shape = self.ifm.shape
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100242 ifm2_shape = self.ifm2.shape if self.ifm2 is not None else None
Tim Halld8339a72021-05-27 18:49:40 +0100243 ofm_shape = stripe
244
245 if ofm_shape != self.ofm.shape:
246 # Striped Op - Need to calculate stripe input volume
247 stripe_input_w, stripe_input_h = self._get_stripe_input_requirement(stripe)
248 # Ensure stripe input volume is within the full IFM volume
249 stripe_input_h = min(stripe_input_h, self.ifm.shape.height)
250 stripe_input_w = min(stripe_input_w, self.ifm.shape.width)
251 ifm_shape = ifm_shape.with_hw(stripe_input_h, stripe_input_w)
252
253 if self.ifm2:
254 stripe_input2_h = min(stripe_input_h, self.ifm2.shape.height)
255 stripe_input2_w = min(stripe_input_w, self.ifm2.shape.width)
256 ifm2_shape = ifm2_shape.with_hw(stripe_input2_h, stripe_input2_w)
257
258 block_config = self._get_block_config(ifm_shape, ifm2_shape, self.uses_scalar, ofm_shape)
259
260 scheduler_op_info = SchedulerOpInfo(block_config, 0, ifm_shape, ifm2_shape, ofm_shape)
261 if self.parent_op.weights:
262 # Default full-depth weight encoding with no buffering
Tim Halld784af72021-06-08 21:25:57 +0100263 (
264 scheduler_op_info.npu_weights_tensor,
265 scheduler_op_info.npu_scales_tensor,
266 ) = weight_compressor.encode_weight_and_scale_tensor(
Tim Halld8339a72021-05-27 18:49:40 +0100267 self.arch,
268 self.parent_op,
269 self.parent_op.weights,
270 self.parent_op.bias,
271 self.kernel,
272 block_config,
273 [0, self.ofm.shape.depth],
274 )
275
276 self.parent_ps.block_config = block_config.old_style_representation()
277 return scheduler_op_info
278
279 def _get_stripe_input_requirement(self, stripe_shape: Shape4D) -> Tuple[int, int]:
280 """Returns the amount of IFM required to produce the stripe with shape:'stripe_shape'"""
281 ofm_shape_to_produce = Block.from_shape(stripe_shape.as_list())
282
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200283 return get_ifm_area_required(ofm_shape_to_produce, self.kernel, self.resampling_mode)
Tim Halld8339a72021-05-27 18:49:40 +0100284
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100285 def _calculate_min_stripe_input(self) -> Tuple[int, int]:
Tim Halld8339a72021-05-27 18:49:40 +0100286 # Calculate the input volume required height and width for the smallest possible stripe (h,w = 1,1)
287 min_stripe = self.ofm.shape.with_hw(1, 1)
288 return self._get_stripe_input_requirement(min_stripe)
289
290 def _get_block_config(
291 self, ifm_shape: Shape4D, ifm2_shape: Optional[Shape4D], uses_scalar: bool, ofm_shape: Shape4D
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100292 ) -> Optional[ArchitectureBlockConfig]:
Tim Halld8339a72021-05-27 18:49:40 +0100293 # Returns a block config and SHRAM layout
294 lut_banks = 2 if self.parent_op.activation_lut else 0
295 return find_block_config(
296 self.arch,
297 self.op_type.npu_block_type,
298 ofm_shape,
299 ifm_shape,
300 ifm2_shape,
301 uses_scalar,
302 self.ifm.dtype.size_in_bits(),
303 self.kernel,
304 lut_banks,
305 self.parent_op.has_scaling(),
306 self.resampling_mode,
307 )
308
309
310class Connection:
311 """Scheduler internal representation of a Tensor that connects two SchedulerOperations
312 This class can be seen as an edge within the Scheduler Graph representation
313 """
314
315 def __init__(self, tensor: Tensor):
316 self.parent_tens = tensor
317
318 # SchedulerOperation relationships
319 self.producers: List[SchedulerOperation] = []
320 self.consumers: List[SchedulerOperation] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100321
322 def __str__(self):
Tim Halld8339a72021-05-27 18:49:40 +0100323 return f"<Connection {self.parent_tens.name}>"
Tim Hall79d07d22020-04-27 18:20:16 +0100324
325 __repr__ = __str__
326
327
Tim Halld8339a72021-05-27 18:49:40 +0100328class Schedule:
329 """Class that contains a solution of how to schedule an NPU subgraph and its cost"""
Tim Hall79d07d22020-04-27 18:20:16 +0100330
Tim Halld8339a72021-05-27 18:49:40 +0100331 def __init__(self, sg: Subgraph, label: str):
332 self.sg = sg
333 self.label = label
334 self.cost_map: Dict[SchedulerOperation, SchedulerOpInfo] = {}
335 self.cascades: Dict[int, CascadeInfo] = {}
336 self.fast_storage_peak_usage = 0
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100337 self.memory_snapshot: Optional[List[int]] = None
Tim Halld8339a72021-05-27 18:49:40 +0100338
339 @property
340 def name(self):
341 return f"{self.sg.name}_{self.label}"
Tim Hall79d07d22020-04-27 18:20:16 +0100342
343
Tim Halld8339a72021-05-27 18:49:40 +0100344class Scheduler:
345 """Main class of the Vela Scheduling"""
Tim Hall79d07d22020-04-27 18:20:16 +0100346
Tim Halld8339a72021-05-27 18:49:40 +0100347 def __init__(self, nng: Graph, sg: Subgraph, arch: ArchitectureFeatures, options: SchedulerOptions):
Tim Hall79d07d22020-04-27 18:20:16 +0100348 self.nng = nng
349 self.sg = sg
350 self.arch = arch
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000351 self.sched_ops: List[SchedulerOperation] = []
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100352 self.max_schedule: Optional[Schedule] = None
Tim Halld8339a72021-05-27 18:49:40 +0100353 self.scheduler_options = options
Tim Hall79d07d22020-04-27 18:20:16 +0100354
Johan Alfvén5e0ae552022-02-09 21:20:10 +0100355 def avoid_nhcwb16_for_ofm(self, tens, ps, arch):
356 # Only run this check for opt strategy Size
357 if self.scheduler_options.optimization_strategy == OptimizationStrategy.Performance:
358 return False
359
360 op = ps.primary_op
361 if not op.type.is_elementwise_op():
362 return False
363
364 depth = op.ofm_shapes[0][-1]
365 if (depth % 16) == 0:
366 return False
367
368 # Check if overwriting the inputs can be allowed
369 OpShapeTens = namedtuple("OpShapeTens", ["op_shape", "tens"])
370 outp = OpShapeTens(op.ofm_shapes[0], op.ofm)
371 inps = []
372 if op.ifm is not None:
373 inps.append(OpShapeTens(op.ifm_shapes[0], op.ifm))
374 if op.ifm2 is not None:
375 inps.append(OpShapeTens(op.ifm_shapes[1], op.ifm2))
376
377 # Find an input tensor that can be overwritten by the output
378 for inp in inps:
379 if (
380 # check op input and output shapes allow overlapping
381 inp.op_shape == outp.op_shape
382 # check input tensor is valid
383 and inp.tens is not None
384 and inp.tens.shape != []
385 # check input and output tensors are compatible
386 and inp.tens.format == outp.tens.format
387 and inp.tens.dtype == outp.tens.dtype
388 ):
389 if inp.tens.format == TensorFormat.NHWC:
390 return True
391
392 return False
393
Tim Halld8339a72021-05-27 18:49:40 +0100394 def create_scheduler_representation(self, arch: ArchitectureFeatures):
395 """Creates a Scheduler Graph representation"""
396 # Temporary dict for creating connections between the Operations
397 connections: Dict[Tensor, Connection] = {}
398 # Memory required for the largest FeatureMap that has to be full
399 min_memory_req = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100400 for ps in self.sg.passes:
Tim Halld8339a72021-05-27 18:49:40 +0100401 if ps.primary_op:
402 # Set tensor format to NHCWB16 for output FeatureMaps, if possible
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200403 for output in ps.outputs:
Jacob Bohlina5e8c1c2021-06-14 13:33:39 +0200404 if output in self.sg.output_tensors or output.purpose != TensorPurpose.FeatureMap:
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +0200405 continue
Johan Alfvén5e0ae552022-02-09 21:20:10 +0100406
407 if output.needs_linear_format:
408 continue
409
410 if self.avoid_nhcwb16_for_ofm(output, ps, arch):
411 output.needs_linear_format = True
412 continue
413
414 output.set_format(TensorFormat.NHCWB16, arch)
Tim Halld8339a72021-05-27 18:49:40 +0100415
416 # Create SchedulerOperations
417 op = SchedulerOperation(ps, arch, self.nng)
418 op.index = len(self.sched_ops)
419
420 # Make connections
421 if ps.ifm_tensor not in connections:
422 connections[ps.ifm_tensor] = Connection(ps.ifm_tensor)
423 if ps.ifm2_tensor and ps.ifm2_tensor not in connections:
424 connections[ps.ifm2_tensor] = Connection(ps.ifm2_tensor)
425 if ps.ofm_tensor not in connections:
426 connections[ps.ofm_tensor] = Connection(ps.ofm_tensor)
427
428 op.add_ifm_connection(connections[ps.ifm_tensor])
429 if ps.ifm2_tensor:
430 op.add_ifm2_connection(connections[ps.ifm2_tensor])
431 op.add_ofm_connection(connections[ps.ofm_tensor])
432
433 # Set requirements on the ifm/ofm buffers
434 self.sched_ops.append(op)
435 if ps.ifm_tensor in self.sg.input_tensors:
436 # This Op consumes a subgraph input
437 op.requires_full_ifm = True
438 if ps.ifm2_tensor and ps.ifm2_tensor in self.sg.input_tensors:
439 # This Op consumes a subgraph input
440 op.requires_full_ifm2 = True
441 if ps.ofm_tensor in self.sg.output_tensors:
442 # This Op produces a subgraph output
443 op.requires_full_ofm = True
444 if ps.ifm_tensor.needs_linear_format:
445 op.requires_full_ifm = True
446 if ps.ifm2_tensor and ps.ifm2_tensor.needs_linear_format:
447 op.requires_full_ifm2 = True
448 if ps.ofm_tensor.needs_linear_format or ps.primary_op.memory_function == Op.ConcatSliceWrite:
449 op.requires_full_ofm = True
450 if len(ps.primary_op.outputs) > 1 or len(ps.primary_op.outputs[0].consumer_list) > 1:
451 # Op has multiple outputs or consumers - requires full OFM
452 op.requires_full_ofm = True
453
454 # Check memory requirements if this Op requires any full FeatureMaps
455 op_memory_req = 0
456 if op.requires_full_ifm:
457 op_memory_req += op.ifm_size_in_bytes()
458 if op.requires_full_ifm2:
459 op_memory_req += op.ifm2_size_in_bytes()
460 if op.requires_full_ofm:
461 op_memory_req += op.ofm_size_in_bytes()
462
463 min_memory_req = max(op_memory_req, min_memory_req)
464
465 # Theoretical minimum required memory - used to guide the cascade building
466 self.min_memory_req = min_memory_req
467
468 def create_initial_schedule(self) -> Schedule:
469 """Creates an initial schedule with no cascading or buffering of any kind"""
470 schedule = Schedule(self.sg, "MAX")
Tim Halld8339a72021-05-27 18:49:40 +0100471 for op in self.sched_ops:
472 cost = op.create_scheduler_info(self.nng, op.ofm.shape)
473 cost.cycles = self.estimate_op_performance(op, cost.block_config, op.ofm.shape.depth)
474 schedule.cost_map[op] = cost
475
476 return schedule
477
478 def update_op_memory_snapshot(self, schedule: Schedule):
479 memories_list = [(self.arch.fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))]
480
481 # Collect live ranges from tensors
482 lr_graph = live_range.LiveRangeGraph()
483 for mem_area, mem_type_set in memories_list:
484 live_range.extract_live_ranges_from_cascaded_passes(
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200485 self.nng.get_root_subgraph(), mem_area, mem_type_set, lr_graph, Tensor.AllocationQuantum,
Tim Halld8339a72021-05-27 18:49:40 +0100486 )
487
488 # Populate time-array with memory used by live ranges
489 temporal_usage = lr_graph.get_temporal_memory_usage(self.arch.fast_storage_mem_area)
490 schedule.memory_snapshot = temporal_usage
491
492 # Set the peak memory usage
493 schedule.fast_storage_peak_usage = max(temporal_usage, default=0)
494
495 def estimate_op_performance(self, op: SchedulerOperation, block_config, ofm_depth):
496 query = npu_performance.PerformanceQuery(op.op_type.npu_block_type)
497 query.ifm_shape = op.ifm.shape
498 query.ifm_memory_area = op.ifm.mem_area
499 query.ifm_bits = op.ifm.dtype.size_in_bits()
500 query.ifm_format = op.ifm.format
501 query.ifm2_shape = op.ifm2 and op.ifm2.shape
502 query.ifm2_memory_area = op.ifm2 and op.ifm2.mem_area
503 query.ifm2_bits = op.ifm2 and op.ifm2.dtype.size_in_bits()
504 query.ifm2_format = op.ifm2 and op.ifm2.format
505 query.ofm_shape = op.ofm.shape.with_depth(ofm_depth)
506 query.ofm_memory_area = op.ofm.mem_area
507 query.ofm_bits = op.ofm.dtype.size_in_bits()
508 query.ofm_format = op.ofm.format
509 if op.parent_op.bias:
510 query.const_shape = Shape4D(1, 1, 1, op.ofm.shape.depth)
511 query.const_memory_area = self.arch.fast_storage_mem_area
512
513 query.kernel = op.kernel
514 query.config = block_config
515
516 return npu_performance.measure_cycle_cost(self.arch, op.op_type, op.activation and op.activation.op_type, query)
517
Tim Hall789e6f32021-06-17 17:02:31 +0100518 def propose_schedule_buffering(self, ref_schedule: Schedule, staging_limit_bytes):
Tim Halld8339a72021-05-27 18:49:40 +0100519 """Create a buffered schedule"""
520 buffered_schedule = Schedule(self.sg, f"{ref_schedule.label}_BUFFERED")
Tim Halld8339a72021-05-27 18:49:40 +0100521
522 prev_op = None
523 for sched_op in self.sched_ops:
524 if sched_op not in ref_schedule.cost_map:
525 # sched_op is not part of this sub-schedule - skip
526 continue
527
528 self.propose_operator_buffering(sched_op, prev_op, buffered_schedule, ref_schedule, staging_limit_bytes)
529 prev_op = sched_op
530
531 return buffered_schedule
532
533 def propose_operator_buffering(
534 self,
535 sched_op: SchedulerOperation,
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100536 prev_op: Optional[SchedulerOperation],
Tim Halld8339a72021-05-27 18:49:40 +0100537 buffered_schedule: Schedule,
538 ref_schedule: Schedule,
539 staging_limit_bytes,
540 ):
541 # Mild recursion might mean this Op has already been seen
542 if sched_op in buffered_schedule.cost_map:
543 return
544
545 # Take the reference schedule as default costings for this schedule
546 ref_cost = ref_schedule.cost_map[sched_op]
547 cost = copy.copy(ref_cost)
548 cost.slack_buffering_cycles = ref_cost.cycles.op_cycles
549 memory_snapshot = ref_schedule.memory_snapshot
550 ref_memory_usage = memory_snapshot[ref_cost.time_index] if ref_cost.time_index < len(memory_snapshot) else 0
551 cost.slack_buffering_memory = staging_limit_bytes - ref_memory_usage
552 buffered_schedule.cost_map[sched_op] = cost
553
554 # Attempt weight buffering on anything with a weights tensor
555 if sched_op.parent_op.weights:
556 self.propose_weight_buffering(
557 sched_op.parent_op.weights,
558 sched_op.parent_op.bias,
559 sched_op,
560 prev_op,
561 buffered_schedule,
562 ref_schedule,
563 cost.slack_buffering_memory,
564 )
565
566 return cost
567
568 def weights_needs_dma(self, weight_tensor):
569 if weight_tensor and weight_tensor.mem_type not in (MemType.Scratch, MemType.Scratch_fast):
570 # Weights are in permanent storage
571 # Only when permanent storage differs from feature map storage, there is a point moving the data
572 if (
573 weight_tensor.mem_area in (MemArea.Dram, MemArea.OffChipFlash)
574 and self.arch.permanent_storage_mem_area != self.arch.fast_storage_mem_area
575 ):
576 return True
577 return False
578
579 def propose_weight_buffering(
580 self,
581 weight_tensor,
582 scale_tensor,
583 sched_op: SchedulerOperation,
584 prev_op: SchedulerOperation,
585 buffered_schedule: Schedule,
586 ref_schedule: Schedule,
587 buffer_limit_bytes,
588 ):
589 cost = buffered_schedule.cost_map[sched_op]
590 prev_cost = buffered_schedule.cost_map.get(prev_op)
591 ref_cost = ref_schedule.cost_map[sched_op]
592 assert cost and ref_cost
593
594 needs_dma = self.weights_needs_dma(weight_tensor)
595
596 ofm_full_depth_slices = [0, ref_cost.stripe.depth]
597
598 # Encode weights for the full depth
Tim Halld784af72021-06-08 21:25:57 +0100599 full_weights, full_scales = weight_compressor.encode_weight_and_scale_tensor(
Tim Halld8339a72021-05-27 18:49:40 +0100600 self.arch,
601 sched_op.parent_op,
602 weight_tensor,
603 scale_tensor,
604 sched_op.kernel,
605 cost.block_config,
606 ofm_full_depth_slices,
607 )
608 full_weights_bytes = len(full_weights.buffer)
609 cost.ofm_depth_slices = ofm_full_depth_slices
610
611 # No buffering required - take all the weights from permanent storage
612 if sched_op.op_type == Op.FullyConnected or not needs_dma:
613 cost.npu_weights_tensor = full_weights
Tim Halld784af72021-06-08 21:25:57 +0100614 cost.npu_scales_tensor = full_scales
Tim Halld8339a72021-05-27 18:49:40 +0100615 return
616
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100617 encoded_weights: Optional[NpuWeightTensor] = full_weights
Tim Halld784af72021-06-08 21:25:57 +0100618 encoded_scales = full_scales
Tim Halld8339a72021-05-27 18:49:40 +0100619
620 # How many NPU cycles are available under the previously executing
621 # operator and SRAM unused for performing buffered DMA transfers
622 slack_cycles = prev_cost.slack_buffering_cycles if prev_cost else 0
623 slack_memory = prev_cost.slack_buffering_memory if prev_cost else 0
624
625 # Force full depth for cascaded Ops
626 if ref_cost.cascade != 0:
627 weight_tensor_purpose = TensorSubPurpose.Standard
628 weight_buffer_size = full_weights_bytes
629 # Update the memory snapshot to reflect the added size of the weights
630 ref_schedule.memory_snapshot[ref_cost.time_index] += weight_buffer_size
631 else:
632 # Estimate the buffering cycle time for the full set of weights
633 full_transfer_cycles = npu_performance.measure_mem2mem_cycles(
634 self.arch, weight_tensor.mem_area, self.arch.fast_storage_mem_area, full_weights_bytes
635 )
636 cost.full_weight_transfer_cycles = full_transfer_cycles
637
638 # Calculate the amount of prebuffering necessary (or what is possible with limited
639 # double buffer buffer size)
640 half_buffer_limit = buffer_limit_bytes // 2
641 if full_transfer_cycles > slack_cycles:
642 prebuffer_ratio = slack_cycles / full_transfer_cycles
643 prebuffer_bytes = min(prebuffer_ratio * full_weights_bytes, half_buffer_limit)
644 else:
645 prebuffer_bytes = min(full_weights_bytes, half_buffer_limit)
Tim Hall789e6f32021-06-17 17:02:31 +0100646
647 prebuffer_ratio = prebuffer_bytes / full_weights_bytes
Tim Halld8339a72021-05-27 18:49:40 +0100648
649 # Have to split the weights if the initial buffering can't store
650 # all of the compressed weights
651 if prebuffer_bytes < full_weights_bytes:
Tim Hall789e6f32021-06-17 17:02:31 +0100652 block_depth = cost.block_config.ofm_block.depth
Tim Halld8339a72021-05-27 18:49:40 +0100653
Tim Hall789e6f32021-06-17 17:02:31 +0100654 # Choose initial prebuffering depth (already buffer clamped)
655 prebuffer_depth = ref_cost.stripe.depth * prebuffer_ratio
Tim Halld8339a72021-05-27 18:49:40 +0100656 prebuffer_depth = int(max(16, round_down(prebuffer_depth, ArchitectureFeatures.OFMSplitDepth)))
657
Tim Hall789e6f32021-06-17 17:02:31 +0100658 # Calculate cycles executed during the prebuffer
659 pre_op_cycles = self.estimate_op_performance(sched_op, cost.block_config, prebuffer_depth)
660 buffering_depth = ref_cost.stripe.depth * (pre_op_cycles.op_cycles / full_transfer_cycles)
Tim Halld8339a72021-05-27 18:49:40 +0100661
Tim Hall789e6f32021-06-17 17:02:31 +0100662 # Choose initial buffering depth and clamp to the double buffering limit
663 buffering_depth = round_up(buffering_depth, block_depth)
664 buffering_bytes = (buffering_depth / ref_cost.stripe.depth) * full_weights_bytes
665 if buffering_bytes > half_buffer_limit:
666 buffering_depth = (half_buffer_limit / full_weights_bytes) * ref_cost.stripe.depth
667
668 while True:
669 # Attempt to buffer whole blocks
670 if buffering_bytes > block_depth:
671 buffering_depth = round_down(buffering_depth, block_depth)
672 else:
673 buffering_depth = round_down(buffering_depth, ArchitectureFeatures.OFMSplitDepth)
674 buffering_depth = int(max(buffering_depth, ArchitectureFeatures.OFMSplitDepth))
Tim Halld8339a72021-05-27 18:49:40 +0100675
676 # Create list of depth slices
677 depth_slices = [0]
678 if prebuffer_depth < ref_cost.stripe.depth:
679 depth_slices += list(range(prebuffer_depth, ref_cost.stripe.depth, buffering_depth))
680 depth_slices.append(ref_cost.stripe.depth)
681
682 # Encode weights based depth slices
683 cost.ofm_depth_slices = depth_slices
Tim Halld784af72021-06-08 21:25:57 +0100684 encoded_weights, encoded_scales = weight_compressor.encode_weight_and_scale_tensor(
Tim Halld8339a72021-05-27 18:49:40 +0100685 self.arch,
686 sched_op.parent_op,
687 weight_tensor,
688 scale_tensor,
689 sched_op.kernel,
690 cost.block_config,
691 cost.ofm_depth_slices,
692 )
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100693 assert encoded_weights is not None
Tim Halld8339a72021-05-27 18:49:40 +0100694 # Chosen buffering might not fit at all, iterate until it does
695 # or until the minimum usable slice size is reached
696 if (
697 encoded_weights.max_range_bytes <= half_buffer_limit
698 or prebuffer_depth == ArchitectureFeatures.OFMSplitDepth
699 ):
700 break
701
Tim Hall789e6f32021-06-17 17:02:31 +0100702 if buffering_depth > prebuffer_depth:
703 buffering_depth = round_up(buffering_depth // 2, ArchitectureFeatures.OFMSplitDepth)
704 else:
705 prebuffer_depth = round_up(prebuffer_depth // 2, ArchitectureFeatures.OFMSplitDepth)
Tim Halld8339a72021-05-27 18:49:40 +0100706
707 # Calculate cycles required to run the last op for use as future slack
708 tail_cycles = self.estimate_op_performance(
709 sched_op, cost.block_config, depth_slices[-1] - depth_slices[-2]
710 )
711 cost.slack_buffering_cycles = tail_cycles.op_cycles
712
713 # Determine whether the weights need to be double buffered
714 weight_buffer_size = min(len(encoded_weights.buffer), encoded_weights.max_range_bytes)
715
716 # Only buffer weights if there's still space left for the buffer
717 if weight_buffer_size <= buffer_limit_bytes:
718 assert weight_buffer_size % 16 == 0
719 # Determine whether to double buffer or single buffer
720 if (weight_buffer_size * 2 <= buffer_limit_bytes) and (weight_buffer_size < len(encoded_weights.buffer)):
721 weight_buffer_size = weight_buffer_size * 2
722 weight_tensor_purpose = TensorSubPurpose.DoubleBuffer
723 else:
724 weight_tensor_purpose = TensorSubPurpose.Standard
725
Jacob Bohlineee9e5d2021-08-17 17:44:45 +0200726 cost.buffered_weight_tensor = self.buffer_tensor(
727 encoded_weights, weight_tensor_purpose, weight_buffer_size, weight_tensor.name
Tim Halld8339a72021-05-27 18:49:40 +0100728 )
Tim Halld8339a72021-05-27 18:49:40 +0100729 if ref_cost.cascade == 0:
730 # Determine if the lifetime can be extended and pre-buffer weights under the previous operation
731 cost.buffered_weight_tensor.pre_buffer = weight_buffer_size < slack_memory
732
733 cost.slack_buffering_memory -= weight_buffer_size
734 else:
735 # Don't slice or buffer - use the whole depth from persistent storage
736 cost.ofm_depth_slices = ofm_full_depth_slices
737 encoded_weights = full_weights
Tim Halld784af72021-06-08 21:25:57 +0100738 encoded_scales = full_scales
Tim Halld8339a72021-05-27 18:49:40 +0100739
740 cost.npu_weights_tensor = encoded_weights
Tim Halld784af72021-06-08 21:25:57 +0100741 cost.npu_scales_tensor = encoded_scales
Tim Halld8339a72021-05-27 18:49:40 +0100742
Jacob Bohlineee9e5d2021-08-17 17:44:45 +0200743 def buffer_tensor(self, src_tensor: Tensor, sub_purpose: TensorSubPurpose, buffer_size: int, name: str) -> Tensor:
744 buffered_weight_tensor = Tensor([1, 1, 1, buffer_size], DataType.uint8, name + "_buffer")
745 buffered_weight_tensor.src_tensor = src_tensor
746 buffered_weight_tensor.mem_area = self.arch.fast_storage_mem_area
747 buffered_weight_tensor.mem_type = MemType.Scratch_fast
748 buffered_weight_tensor.purpose = TensorPurpose.Weights
749 buffered_weight_tensor.sub_purpose = sub_purpose
750 return buffered_weight_tensor
751
Tim Halld8339a72021-05-27 18:49:40 +0100752 def propose_minimal_schedule(self) -> Schedule:
753 """Proposes scheduling parameters where every operator is subdivided into the smallest stripe that satisfies the
754 next operators stride"""
755 min_schedule = Schedule(self.sg, "MIN")
756 cost_map = min_schedule.cost_map
757
758 # Keep track of the previous Op - which consumes the current Op's OFM
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100759 prev_op: Optional[SchedulerOperation] = None
Tim Halld8339a72021-05-27 18:49:40 +0100760 for sched_op in reversed(self.sched_ops):
761 min_stripe_height = prev_op.kernel.stride.y if prev_op else 1
762 min_stripe = sched_op.ofm.shape.with_height(min_stripe_height)
763
764 cost = sched_op.create_scheduler_info(self.nng, min_stripe)
765 cost.cycles = self.estimate_op_performance(sched_op, cost.block_config, sched_op.ofm.shape.depth)
766 cost_map[sched_op] = cost
767
768 prev_op = sched_op
769
770 return min_schedule
771
772 def propose_schedule_striping(self, final_stripe: Shape4D, label: str, ref_schedule: Schedule) -> Schedule:
773 """Proposes new striping for a schedule. The stripe is derived from the ifm requirements of the next Op down"""
774 ref_cost = ref_schedule.cost_map
775
776 striped_schedule = Schedule(self.sg, label)
777 stripe = final_stripe
778 for sched_op in reversed(self.sched_ops):
779 if sched_op not in ref_cost:
780 # sched_op is not part of the sub-schedule - skip
781 continue
782
783 # Create a cost entry with the new stripe
784 cost = sched_op.create_scheduler_info(self.nng, stripe)
785
Jacob Bohlineee9e5d2021-08-17 17:44:45 +0200786 if ref_cost[sched_op].buffered_weight_tensor:
787 # If the weights are buffered in the reference schedule they should be in the new proposal
788 weight_tensor = cost.npu_weights_tensor
789 cost.buffered_weight_tensor = self.buffer_tensor(
790 weight_tensor, TensorSubPurpose.Standard, len(weight_tensor.buffer), weight_tensor.name
791 )
Tim Halld8339a72021-05-27 18:49:40 +0100792
793 # Estimate performance
794 cost.cycles = self.estimate_op_performance(sched_op, cost.block_config, sched_op.ofm.shape.depth)
795 striped_schedule.cost_map[sched_op] = cost
796
797 # Calculate the preceeding Op's stripe
798 stripe = sched_op.ifm.shape.with_height(stripe.height * sched_op.kernel.stride.y)
799
800 return striped_schedule
801
802 def estimate_schedule_memory_usage(self, schedule: Schedule, non_local_mem_usage: dict):
803 """Estimates the memory usage of a schedule"""
804 cost = schedule.cost_map
805 cascades = schedule.cascades
806 peak_mem_usage = 0
807 for sched_op in self.sched_ops:
808 if sched_op not in cost:
809 # sched_op is not part of the sub-schedule - skip
810 continue
811
812 if cost[sched_op].cascade:
813 # This Op is part of a cascade - use the cascade's memory usage
814 cascade_info = cascades[cost[sched_op].cascade]
815 # Non-local memory usage is already included in the cascade_info
816 peak_mem_usage = max(cascade_info.mem_usage, peak_mem_usage)
817 else:
818 # This Op is not part of a cascade - calculate the memory usage
819 op_weight_buffer = 0
820 if cost[sched_op].buffered_weight_tensor:
821 op_weight_buffer = cost[sched_op].buffered_weight_tensor.storage_size()
822
823 op_mem_usage = (
824 sched_op.ifm_size_in_bytes()
825 + sched_op.ofm_size_in_bytes()
826 + op_weight_buffer
827 + non_local_mem_usage.get(sched_op, 0)
828 )
829 peak_mem_usage = max(op_mem_usage, peak_mem_usage)
830
831 return peak_mem_usage
832
833 def optimize_sub_schedule(
834 self, cascade_info: CascadeInfo, ref_schedule: Schedule, max_template: Schedule, memory_limit: int
835 ) -> Schedule:
836 """Extracts the Ops covered by the given cascade and creates a sub-schedule. The sub-schedule is optimized by
837 proposing weight buffering and then continously proposing new stripe sizes"""
838 ref_cost = ref_schedule.cost_map
839 # Extract the ops that are part of this sub-schedule
840 start = cascade_info.start
841 end = cascade_info.end
842 sub_schedule_ops = self.sched_ops[start : end + 1]
843 # Create a sub-schedule that contains only the costs for the Ops that are part of the sub-schedule
844 sub_schedule = Schedule(self.sg, f"SUB_{start}_{end}")
845 for sched_op in sub_schedule_ops:
846 sub_schedule.cost_map[sched_op] = ref_cost[sched_op]
847
848 sub_schedule.cascades[end] = cascade_info
849 # Use the memory snapshot from the reference schedule
850 sub_schedule.memory_snapshot = ref_schedule.memory_snapshot
851
852 # Calculate memory usage that is live during the sub-schedule but not part of it
853 time_for_cascade = ref_cost[sub_schedule_ops[0]].time_index
854 mem_usage_parallel_to_sub_schedule = ref_schedule.memory_snapshot[time_for_cascade] - cascade_info.mem_usage
855 # If the first Op's IFM has other consumers it has to live throughout the whole sub-schedule whether it's
856 # included in a cascade or not
857 persistent_initial_ifm = (
858 sub_schedule_ops[0].ifm_size_in_bytes() if len(sub_schedule_ops[0].ifm.connection.consumers) > 1 else 0
859 )
860 # Calculate non-local-mem-usage per Operator
861 non_local_mem_usage = {}
862 for idx, sched_op in enumerate(sub_schedule_ops):
863 non_local_mem_usage[sched_op] = mem_usage_parallel_to_sub_schedule
864 if idx != 0:
865 non_local_mem_usage[sched_op] += persistent_initial_ifm
866
867 cascade_builder = CascadeBuilder(sub_schedule_ops, self.arch.is_spilling_enabled(), non_local_mem_usage)
868
869 # Start by adding buffering
Tim Hall789e6f32021-06-17 17:02:31 +0100870 buffered_sub_schedule = self.propose_schedule_buffering(
871 sub_schedule, self.scheduler_options.optimization_sram_limit
872 )
Tim Halld8339a72021-05-27 18:49:40 +0100873 # Copy the cascades over from the unbuffered-schedule
874 buffered_sub_schedule.cascades = sub_schedule.cascades
875
876 # Generate the possible stripings for the final Op in the sub-schedule
877 final_ofm_shape = sub_schedule_ops[-1].ofm.shape
878 possible_stripes = [
879 final_ofm_shape.with_height(stripe_h) for stripe_h in range(1, final_ofm_shape.height // 2 + 1)
880 ]
881
882 # Propose different striping - the possible stripes are proposed similarly to a binary search
Jacob Bohlinfad72042021-08-24 21:51:41 +0200883 best_schedule = None
Tim Halld8339a72021-05-27 18:49:40 +0100884 iteration = 0
885 while len(possible_stripes) > 1:
886 proposed_stripe = possible_stripes[len(possible_stripes) // 2]
887 proposed_schedule = self.propose_schedule_striping(
888 proposed_stripe, f"OPTIMIZED_{iteration}", buffered_sub_schedule
889 )
890
891 cascade_builder.build_cascades(proposed_schedule, max_template, memory_limit)
892
893 # Check if proposal fits
894 proposed_schedule_mem_usage = self.estimate_schedule_memory_usage(proposed_schedule, non_local_mem_usage)
895 if (proposed_schedule_mem_usage) <= memory_limit:
896 # Remove all possible stripes smaller than this
897 possible_stripes = possible_stripes[len(possible_stripes) // 2 :]
898 best_schedule = proposed_schedule
899 if not proposed_schedule.cascades:
900 # No cascading required - early exit
901 break
902 else:
903 # Proposal doesn't fit within the limit - remove all possible stripes larger than this
904 possible_stripes = possible_stripes[: len(possible_stripes) // 2]
905
906 iteration += 1
907
908 return best_schedule
909
910 def optimize_schedule(
911 self, schedule: Schedule, max_sched: Schedule, max_template: Schedule, options: SchedulerOptions,
912 ) -> Schedule:
913 """Extracts sub-schedules based on the cascades and optimizes them and applies them to the final schedule"""
914 sram_limit = options.optimization_sram_limit
915 if max_sched.fast_storage_peak_usage < sram_limit and not self.arch.is_spilling_enabled():
916 # Maximum performance schedule fits within the SRAM target
917 return max_sched
918
Jacob Bohlinfad72042021-08-24 21:51:41 +0200919 # Iterate over a copy of the cascades since they may change during the loop
920 for cascade_info in list(schedule.cascades.values()):
Tim Halld8339a72021-05-27 18:49:40 +0100921 # Optimize the sub-schedule in this cascade
922 opt_sub_schedule = self.optimize_sub_schedule(cascade_info, schedule, max_template, sram_limit)
Jacob Bohlinfad72042021-08-24 21:51:41 +0200923 if opt_sub_schedule:
924 # Remove the existing cascade
925 del schedule.cascades[cascade_info.end]
926 # Update the sub-schedule Op and cascade costs to the full schedule
927 schedule.cost_map.update(opt_sub_schedule.cost_map)
928 schedule.cascades.update(opt_sub_schedule.cascades)
Tim Halld8339a72021-05-27 18:49:40 +0100929
930 # Update memory snapshot
931 self.sg.schedule = schedule
932 self.update_op_memory_snapshot(schedule)
933 # Propose schedule buffering to the optimized schedule
Tim Hall789e6f32021-06-17 17:02:31 +0100934 optimized_sched = self.propose_schedule_buffering(schedule, self.scheduler_options.optimization_sram_limit)
Tim Halld8339a72021-05-27 18:49:40 +0100935 # Copy the cascade's metadata from the unbuffered schedule
936 optimized_sched.cascades = schedule.cascades
937 return optimized_sched
938
939 def apply_schedule(self, sched: Schedule):
940 """Applies the given schedule as a final solution"""
941 for sched_op in self.sched_ops:
942 op_info = sched.cost_map[sched_op]
943 cascade_info = sched.cascades.get(op_info.cascade, None)
944 if cascade_info and sched_op in cascade_info.buffers:
945 buffer_tens = sched_op.ifm.connection.parent_tens
946 # Apply memory area and type
947 buffer_tens.mem_area = self.arch.fast_storage_mem_area
948 buffer_tens.mem_type = MemType.Scratch_fast
949 # Apply Rolling buffer
950 buffer_tens.set_format(TensorFormat.NHCWB16, self.arch)
951 buffer_tens.set_new_sub_purpose(TensorSubPurpose.RollingBufferY, cascade_info.buffers[sched_op].height)
952
953 sched_op.parent_ps.block_config = op_info.block_config.old_style_representation()
954
955 # Ensure that the src_tensor reference is set correctly
956 if op_info.buffered_weight_tensor:
957 op_info.buffered_weight_tensor.src_tensor = op_info.npu_weights_tensor
958
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100959 def use_fast_storage_for_feature_maps(self, schedule, staging_limit):
960 scratched_fms = {}
961 max_mem_usage = []
962 base_mem_usage = []
963 fast_storage_type = MemType.Scratch_fast
964 fast_storage_mem_area = self.arch.fast_storage_mem_area
Tim Halld8339a72021-05-27 18:49:40 +0100965
966 # Force all OFMs to fast-storage
967 for sched_op in self.sched_ops:
968 cost = schedule.cost_map[sched_op]
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100969 if cost.cascade == 0 and sched_op.get_dependants():
970 ofm_tens = sched_op.ofm.connection.parent_tens
971 if not any(cons is None for cons in ofm_tens.consumer_list):
972 if ofm_tens not in scratched_fms:
973 scratched_fms[ofm_tens] = (ofm_tens.mem_area, ofm_tens.mem_type)
974 ofm_tens.mem_area = fast_storage_mem_area
975 ofm_tens.mem_type = fast_storage_type
Tim Halld8339a72021-05-27 18:49:40 +0100976
977 # Collect live ranges from tensors
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100978 memories_list = [(fast_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))]
Tim Halld8339a72021-05-27 18:49:40 +0100979 lr_graph = live_range.LiveRangeGraph()
980 for mem_area, mem_type_set in memories_list:
981 live_range.extract_live_ranges_from_cascaded_passes(
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200982 self.nng.get_root_subgraph(), mem_area, mem_type_set, lr_graph, Tensor.AllocationQuantum,
Tim Halld8339a72021-05-27 18:49:40 +0100983 )
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100984 max_mem_usage = lr_graph.get_temporal_memory_usage(fast_storage_mem_area)
Tim Halld8339a72021-05-27 18:49:40 +0100985
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100986 # If true, everything fits and we can proceed
987 if max(max_mem_usage) <= staging_limit:
988 return
989
990 # Build up the base memory usage by removing the
991 # mem_usage of the lrs we previously moved to fast-storage
992 base_mem_usage = np.array(max_mem_usage)
993 curr_lrs = []
Tim Halld8339a72021-05-27 18:49:40 +0100994 for lr in lr_graph.lrs:
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100995 for tens in lr.tensors:
996 if scratched_fms.get(tens):
997 curr_lrs.append(lr)
998 base_mem_usage[lr.start_time : lr.end_time + 1] -= lr.size
999 break
1000
1001 competing_lrs = []
1002 for lr in curr_lrs:
1003 base_usage = max(base_mem_usage[lr.start_time : lr.end_time + 1])
1004 # If true, the lr will never fit and may thus be evicted
1005 if base_usage + lr.size > staging_limit:
1006 FastStorageComponentAllocator.evict(lr, max_mem_usage, scratched_fms)
1007 continue
1008 # Since max_mem_usage is the memory usage with all FMs still in fast-storage,
1009 # the memory limit cannot be exceeded if max_mem_usage does not.
1010 # Thus, the affected lrs can remain in fast-storage if the following is true
1011 if max(max_mem_usage[lr.start_time : lr.end_time + 1]) <= staging_limit:
1012 FastStorageComponentAllocator.keep(lr, base_mem_usage, staging_limit)
1013 else:
1014 competing_lrs.append(lr)
1015 sz = len(competing_lrs)
1016 # All lrs and their tensors have been handled if sz is zero, we may thus return
1017 if sz == 0:
1018 return
1019
1020 competing_lrs = sorted(competing_lrs, key=lambda lr: (lr.start_time, lr.end_time + 1, lr.size))
1021 start = 0
1022 start_time = competing_lrs[0].start_time
1023 end_time = competing_lrs[0].end_time
1024 component_allocator = FastStorageComponentAllocator(base_mem_usage, max_mem_usage, staging_limit)
1025 # Build up components and then allocate each separately
1026 for i, lr in enumerate(competing_lrs):
1027 if lr.start_time <= end_time and i - start < component_allocator.max_exhaustive_size:
1028 start_time = min(start_time, lr.start_time)
1029 end_time = max(end_time, lr.end_time)
1030 else:
1031 component_allocator.allocate_component(
1032 component_allocator,
1033 competing_lrs[start:i],
1034 max_mem_usage,
1035 base_mem_usage,
1036 staging_limit,
1037 scratched_fms,
1038 )
1039 start = i
1040 start_time = lr.start_time
1041 end_time = lr.end_time
1042 component_allocator.allocate_component(
1043 component_allocator, competing_lrs[start:sz], max_mem_usage, base_mem_usage, staging_limit, scratched_fms
1044 )
Tim Halld8339a72021-05-27 18:49:40 +01001045
1046 def move_constant_data(self):
1047 """Determine if data, can be moved from permanent storage to another memory area. A move
1048 will generate a DMA command in the high-level command stream"""
1049 for sched_op in self.sched_ops:
1050 parent_op = sched_op.parent_op
1051 is_lut_used = any(inp.purpose == TensorPurpose.LUT for inp in parent_op.inputs)
1052 max_ifm_shram_avail = (
1053 (self.arch.available_shram_banks(is_lut_used) - self.arch.shram_reserved_output_banks)
1054 * self.arch.shram_bank_size
1055 // 2
1056 )
1057
1058 for idx, tens in enumerate(parent_op.inputs):
1059 if tens.mem_type not in (MemType.Scratch, MemType.Scratch_fast):
1060 # Tensor is in permanent storage
1061 # Only when permanent storage differs from feature map storage, there is a point moving the data
1062 if (
1063 tens.mem_area in self.arch.permanent_storage_mem_area
1064 and self.arch.permanent_storage_mem_area != self.arch.feature_map_storage_mem_area
1065 ) or tens.purpose == TensorPurpose.LUT:
1066 if tens.purpose == TensorPurpose.LUT or (
Patrik Gustavsson94292fe2021-09-02 08:22:58 +02001067 # For elementwise broadcast
Tim Halld8339a72021-05-27 18:49:40 +01001068 tens.purpose == TensorPurpose.FeatureMap
1069 and sched_op.op_type.is_binary_elementwise_op()
1070 and tens.shape != []
1071 and sched_op.ifm.shape != sched_op.ofm.shape
Patrik Gustavsson94292fe2021-09-02 08:22:58 +02001072 and parent_op.write_shape is None
Tim Halld8339a72021-05-27 18:49:40 +01001073 and tens.storage_size() > max_ifm_shram_avail
1074 ):
1075 only_vector_product_consumers = all(
1076 oper and oper.type.npu_block_type == NpuBlockType.VectorProduct
1077 for oper in tens.consumers()
1078 )
1079
1080 if (not only_vector_product_consumers) or tens.purpose == TensorPurpose.LUT:
1081 new_tens = tens.clone_into_fast_storage(self.arch)
1082 if tens.purpose == TensorPurpose.LUT:
1083 new_tens.mem_area = MemArea.Shram
1084
1085 new_tens.consumer_list.append(parent_op)
1086 parent_op.inputs[idx] = new_tens
Dwight Lidman352607c2021-09-29 17:00:09 +02001087 # If the index is out of range, IFM and IFM2 are the same tensor
1088 # and pass inputs don't have duplicates
1089 if idx < len(sched_op.parent_ps.inputs):
1090 sched_op.parent_ps.inputs[idx] = new_tens
Tim Halld8339a72021-05-27 18:49:40 +01001091
1092 def print_schedule(self, schedule: Schedule):
1093 print(f"Schedule: '{schedule.name}'")
1094 for sched_op in self.sched_ops:
1095 if sched_op not in schedule.cost_map:
1096 # Sub-schedule printing
1097 continue
1098
1099 op_info = schedule.cost_map[sched_op]
1100 print(f"\t{sched_op.index}: Operation {sched_op.name} - OFM {sched_op.ofm.shape}")
1101 print(f"\t\tType: {sched_op.op_type}")
1102 print(f"\t\tKernel: {sched_op.kernel}")
1103 print(f"{op_info}")
1104 mem_usage = (
1105 schedule.memory_snapshot[op_info.time_index]
1106 if op_info.time_index < len(schedule.memory_snapshot)
1107 else 0
1108 )
1109 print(f"\t\tSRAM Used: {mem_usage} bytes")
1110
Jonas Ohlsson25e700c2022-03-04 14:58:56 +01001111 print("\tCascades:")
Tim Halld8339a72021-05-27 18:49:40 +01001112 for i, cascade in enumerate(schedule.cascades.values()):
1113 print(f"\t\t{i}: {cascade.start} -> {cascade.end}, size: {cascade.mem_usage}")
Patrik Gustavssonfeeb06d2020-04-22 12:53:47 +02001114
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001115
Tim Halld8339a72021-05-27 18:49:40 +01001116def _update_tensor_allocation(nng: Graph, arch: ArchitectureFeatures, options):
1117 """
1118 Creates live ranges and runs tensor allocator for the current schedule
1119 (i.e. sg.schedule for all subgraphs), returns the maximum memory usage
1120 and updates SchedulerOpInfo.mem_usage for all operations in the schedule.
1121 """
1122 root_sg = nng.get_root_subgraph()
1123
1124 alloc_list = []
1125 if arch.is_spilling_enabled():
1126 mem_alloc_scratch_fast = (arch.fast_storage_mem_area, set((MemType.Scratch_fast,)))
1127 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch,)))
1128 # Order is important
1129 alloc_list.append(mem_alloc_scratch_fast)
1130 alloc_list.append(mem_alloc_scratch)
1131 else:
1132 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))
1133 alloc_list.append(mem_alloc_scratch)
1134
1135 for mem_area, mem_type_set in alloc_list:
1136 tensor_allocation.allocate_tensors(
1137 nng,
1138 root_sg,
1139 arch,
1140 mem_area,
1141 mem_type_set,
1142 tensor_allocator=options.tensor_allocator,
1143 verbose_allocation=options.verbose_allocation,
1144 cpu_tensor_alignment=options.cpu_tensor_alignment,
1145 )
1146
1147
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001148class FastStorageComponentAllocator:
1149 def __init__(self, base_mem_usage, max_mem_usage, staging_limit):
1150 self.base_mem_usage = base_mem_usage
1151 self.max_mem_usage = list(max_mem_usage)
1152 self.staging_limit = staging_limit
1153 self.lrs = []
1154 self.evicted = []
1155 self.curr_evicted = []
1156 self.remaining_total_size = []
1157 self.best_allocated_size = 0
1158 self.max_exhaustive_size = 20
1159
1160 def allocate_exhaustive(self, ix, alloc_size):
1161 if ix >= len(self.lrs):
1162 if alloc_size > self.best_allocated_size:
1163 self.best_allocated_size = alloc_size
Louis Verhaard5c8f1e52022-02-23 14:13:07 +01001164 self.evicted = self.curr_evicted.copy()
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +01001165 return
1166
1167 lr = self.lrs[ix]
1168 for t in range(lr.start_time, lr.end_time):
1169 assert self.base_mem_usage[t] <= self.max_mem_usage[t]
1170 base_usage = max(self.base_mem_usage[lr.start_time : lr.end_time + 1])
1171 can_fit = base_usage + lr.size <= self.staging_limit
1172 always_fits = can_fit
1173
1174 if can_fit:
1175 max_usage = max(self.max_mem_usage[lr.start_time : lr.end_time + 1])
1176 always_fits = max_usage <= self.staging_limit
1177
1178 if can_fit or always_fits:
1179 self.curr_evicted[ix] = False
1180 self.base_mem_usage = self.update_mem_usage(self.base_mem_usage, lr, True)
1181 self.allocate_exhaustive(ix + 1, alloc_size + lr.size)
1182 self.base_mem_usage = self.update_mem_usage(self.base_mem_usage, lr, False)
1183
1184 if not always_fits:
1185 self.curr_evicted[ix] = True
1186 self.max_mem_usage = self.update_mem_usage(self.max_mem_usage, lr, False)
1187 self.allocate_exhaustive(ix + 1, alloc_size)
1188 self.max_mem_usage = self.update_mem_usage(self.max_mem_usage, lr, True)
1189
1190 @staticmethod
1191 def update_mem_usage(mem_usage, lr, increase):
1192 for t in range(lr.start_time, lr.end_time + 1):
1193 mem_usage[t] += lr.size if increase else -lr.size
1194 assert mem_usage[t] >= 0
1195 return mem_usage
1196
1197 @staticmethod
1198 def evict(lr, max_mem_usage, scratched_fms):
1199 for t in range(lr.start_time, lr.end_time + 1):
1200 max_mem_usage[t] -= lr.size
1201 for tens in lr.tensors:
1202 if tens in scratched_fms:
1203 tens.mem_area = scratched_fms[tens][0]
1204 tens.mem_type = scratched_fms[tens][1]
1205
1206 @staticmethod
1207 def keep(lr, base_mem_usage, staging_limit):
1208 for t in range(lr.start_time, lr.end_time + 1):
1209 base_mem_usage[t] += lr.size
1210 assert base_mem_usage[t] <= staging_limit
1211
1212 def allocate_component(self, allocator, lrs, max_mem, min_mem, staging_limit, scratched_fms):
1213 sz = len(lrs)
1214 allocator.lrs = lrs
1215 allocator.evicted = [0] * len(lrs)
1216 allocator.curr_evicted = [0] * sz
1217 allocator.best_allocated_size = -1
1218 # Recursively evaluate all permutations of allocations of the lrs found in the component
1219 allocator.allocate_exhaustive(0, 0)
1220
1221 # Optimal allocation has been found, move lrs accordingly
1222 for i, e in enumerate(allocator.evicted):
1223 if e:
1224 self.evict(lrs[i], max_mem, scratched_fms)
1225 else:
1226 self.keep(lrs[i], min_mem, staging_limit)
1227
1228
Tim Halld8339a72021-05-27 18:49:40 +01001229def schedule_passes(nng: Graph, arch: ArchitectureFeatures, options, scheduler_options: SchedulerOptions):
1230 """Entry point for the Scheduler"""
1231 # Initialize CPU subgraphs
1232 schedulers = dict()
1233 # Initialize schedulers with max schedule. Only schedule NPU subgraphs
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001234 for sg in nng.subgraphs:
Tim Halld8339a72021-05-27 18:49:40 +01001235 if sg.placement != PassPlacement.Npu:
1236 # Create cascaded passes for CPU Ops
1237 cascaded_passes = []
1238 for idx, ps in enumerate(sg.passes):
1239 cps = CascadedPass(
1240 ps.name, SchedulingStrategy.WeightStream, ps.inputs, [], ps.outputs, [ps], ps.placement, False,
1241 )
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001242
Tim Halld8339a72021-05-27 18:49:40 +01001243 cps.time = idx
1244 ps.cascade = cps
1245 cascaded_passes.append(cps)
Andreas Nevalainen27d36f02020-11-19 11:27:50 +01001246
Tim Halld8339a72021-05-27 18:49:40 +01001247 sg.cascaded_passes = cascaded_passes
1248 else:
1249 # Npu subgraph - create schedule
1250 scheduler = Scheduler(nng, sg, arch, scheduler_options)
1251 schedulers[sg] = scheduler
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001252
Tim Halld8339a72021-05-27 18:49:40 +01001253 scheduler.create_scheduler_representation(arch)
1254 sg.sched_ops = scheduler.sched_ops
1255 scheduler.move_constant_data()
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001256
Tim Halld8339a72021-05-27 18:49:40 +01001257 # Create the Max schedule template
1258 max_schedule_template = scheduler.create_initial_schedule()
1259 scheduler.max_schedule = max_schedule_template
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001260
Tim Halld8339a72021-05-27 18:49:40 +01001261 # Create the optimimised Max schedule
1262 sg.schedule = max_schedule_template
1263 scheduler.update_op_memory_snapshot(max_schedule_template)
Tim Hall789e6f32021-06-17 17:02:31 +01001264 opt_max_schedule = scheduler.propose_schedule_buffering(max_schedule_template, 1 << 32)
Tim Halld8339a72021-05-27 18:49:40 +01001265 sg.schedule = opt_max_schedule
1266 scheduler.update_op_memory_snapshot(opt_max_schedule)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001267
Tim Halld8339a72021-05-27 18:49:40 +01001268 # Create Min schedule
1269 min_schedule = scheduler.propose_minimal_schedule()
1270 initial_sram_limit = scheduler_options.optimization_sram_limit
1271 if scheduler_options.optimization_strategy == OptimizationStrategy.Size:
1272 initial_sram_limit = scheduler.min_memory_req
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001273
Tim Halld8339a72021-05-27 18:49:40 +01001274 cascade_builder = CascadeBuilder(scheduler.sched_ops, arch.is_spilling_enabled())
1275 cascade_builder.build_cascades(min_schedule, max_schedule_template, initial_sram_limit)
1276 sg.schedule = min_schedule
1277 scheduler.update_op_memory_snapshot(min_schedule)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001278
Tim Halld8339a72021-05-27 18:49:40 +01001279 if scheduler_options.optimization_strategy == OptimizationStrategy.Performance:
1280 # Create an optimized schedule
1281 sg.schedule = scheduler.optimize_schedule(
1282 min_schedule, opt_max_schedule, max_schedule_template, scheduler_options
1283 )
1284 scheduler.update_op_memory_snapshot(sg.schedule)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001285
Tim Halld8339a72021-05-27 18:49:40 +01001286 scheduler.apply_schedule(sg.schedule)
1287 scheduler.use_fast_storage_for_feature_maps(sg.schedule, scheduler_options.optimization_sram_limit)
Andreas Nevalainen897cc142020-10-28 15:42:08 +01001288
Tim Halld8339a72021-05-27 18:49:40 +01001289 if scheduler_options.verbose_schedule:
1290 scheduler.print_schedule(sg.schedule)
Tim Hall79d07d22020-04-27 18:20:16 +01001291
Tim Halld8339a72021-05-27 18:49:40 +01001292 # Evaluate schedule
1293 _update_tensor_allocation(nng, arch, options)