blob: 30e1c872b6c38c1d707af661a2d6fa7415e69a47 [file] [log] [blame]
Tim Halld8339a72021-05-27 18:49:40 +01001# Copyright (C) 2021 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17# Description: Architecture SHRAM allocator
18import enum
19import math
20from typing import Optional
21from typing import Tuple
22
23from .architecture_features import ArchitectureFeatures
24from .architecture_features import Block
25from .architecture_features import SHRAMConfig
26from .architecture_features import SHRAMElements
27from .ethos_u55_regs.ethos_u55_regs import resampling_mode
28from .numeric_util import round_up
29from .numeric_util import round_up_divide
30from .operation import Kernel
31from .operation import NpuBlockType
32from .range_set import MemoryRangeSet
33from .shape4d import Shape4D
34from .tensor import MemArea
35
36
37class SHRAMLayout:
38 def __init__(self):
39 self.ib_start = 0
40 self.ib_end = 0
41 self.ib_start2 = 0
42 self.ab_start = 0
43 self.lut_start = 0
44
45
46class ArchitectureBlockConfig:
47 def __init__(self):
48 self.layout = SHRAMLayout()
49 self.ifm_block = Shape4D()
50 self.ofm_block = Shape4D()
51 self.acc_type = SHRAMElements.Acc32
52 self.is_partkernel = False
53 self.bank_size = 0
54
55 def get_shram_memory_access_range(self):
56 # Returns the SHRAM memory access range used by this shared buffer,
57 # excluding access to LUT
58 return MemoryRangeSet(MemArea.Shram, 0, self.layout.lut_start * self.bank_size)
59
60 def old_style_representation(self):
61 return [self.ofm_block.height, self.ofm_block.width, self.ifm_block.depth, self.ofm_block.depth]
62
63 def __str__(self):
64 return str(self.old_style_representation())
65
66
67_AccumulatorBits = {SHRAMElements.Acc16: 16, SHRAMElements.Acc32: 32, SHRAMElements.Acc40: 40}
68
69
70class ElementwiseUsage(enum.IntEnum):
71 No = 0
72 Full = 1
73 Scalar = 2
74
75
76def _try_block_config(
77 shram: SHRAMConfig,
78 ew_usage: ElementwiseUsage,
79 ofm_block: Block,
80 ifm_block: Block,
81 ifm_bits: int,
82 ifm_granule: int,
83 acc_bits: int,
84 acc_granule: int,
85 lut_banks: int,
86) -> SHRAMLayout:
87 assert (acc_bits > 0) and (acc_granule > 0)
88 assert (ifm_bits >= 8) and ((ifm_bits % 8) == 0) and (ifm_granule > 0)
89
90 # Aways need IFM space
91 ifm_bytes = ifm_block.elements_wh() * round_up((ifm_block.depth * ifm_bits) / 8, 8)
92 ifm_banks = round_up_divide(ifm_bytes, shram.bank_size_bytes) * 2
93 ifm_banks = round_up(ifm_banks, ifm_granule)
94
95 # Calculate SHRAM boundaries of the IFM and Accumulators
96 lut_start = shram.total_banks - lut_banks
97 ifm_end = shram.reserved_output_banks + ifm_banks
98 ifm2_start = ifm_end
99 acc_start = lut_start
100
101 # If not elementwise then we need accumulator space
102 if ew_usage == ElementwiseUsage.No:
103 acc_bytes = (ofm_block.elements_wh() * round_up(ofm_block.depth, 8) * acc_bits) // 8
104 acc_banks = round_up_divide(acc_bytes, shram.bank_size_bytes) * 2
105 acc_banks = round_up(acc_banks, acc_granule)
106 acc_start = acc_start - acc_banks
107 else:
108 ifm2_banks = ifm_banks if ew_usage == ElementwiseUsage.Full else 0
109 if ifm2_start + ifm2_banks > acc_start:
110 return None
111 ifm_end = acc_start
112
113 # IFM must still fit before accumulators
114 if ifm_end > acc_start:
115 return None
116
117 # Should all fit, so return this layout
118 layout = SHRAMLayout()
119 layout.ib_start = shram.reserved_output_banks
120 layout.ib_start2 = ifm2_start
121 layout.ib_end = ifm_end
122 layout.ab_start = acc_start
123 layout.lut_start = lut_start
124 return layout
125
126
127def _choose_kernel_method(ifm_shape: Shape4D, ifm_bits: int, kernel: Kernel) -> bool:
128 if ifm_shape.depth <= 8:
129 return True
130
131 # Compare part-kernel to depth-kernel and choose the one with best utilisation
132 kernel_elements = kernel.elements_wh()
133 depth_utilisation = ifm_shape.depth / round_up(ifm_shape.depth, 32 if ifm_bits == 8 else 16)
134 part_utilisation = (
135 ifm_shape.depth
136 * kernel_elements
137 / (round_up(ifm_shape.depth, 8) * round_up(kernel_elements, 4 if ifm_bits == 8 else 2))
138 )
139
140 return part_utilisation > depth_utilisation
141
142
143def _ew_usage(npu_op_type: NpuBlockType, uses_scalar: bool) -> ElementwiseUsage:
144 ew_usage = ElementwiseUsage.No
145 if npu_op_type == NpuBlockType.ElementWise:
146 ew_usage = ElementwiseUsage.Full
147 if uses_scalar:
148 ew_usage = ElementwiseUsage.Scalar
149 return ew_usage
150
151
152def _acc_type(npu_op_type: NpuBlockType, ifm_bits: int, scaled: bool) -> int:
153 """Returns accumulator type"""
154 acc_type = SHRAMElements.Acc32
155 if (ifm_bits == 16) and npu_op_type != NpuBlockType.Pooling and scaled:
156 acc_type = SHRAMElements.Acc40
157 return acc_type
158
159
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200160def is_nearest(ifm_resampling: resampling_mode) -> bool:
161 return ifm_resampling == resampling_mode.NEAREST
162
163
Tim Halld8339a72021-05-27 18:49:40 +0100164def to_upscale(ifm_resampling: resampling_mode) -> int:
165 # Upscaling depending on resampling mode
166 return 1 if ifm_resampling == resampling_mode.NONE else 2
167
168
169def _ifm_blockdepth(arch, ifm_shape: Shape4D, ifm_bits: int, is_partkernel: bool):
170 if ifm_bits == 16:
171 ifm_blockdepth = round_up(min(ifm_shape.depth, 16), 4)
172 else:
173 ifm_blockdepth = round_up(min(ifm_shape.depth, 16 if is_partkernel else 32), arch.ifm_ublock.depth)
174 return ifm_blockdepth
175
176
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200177def _required_size(value: int, stride: int, border: int, upscale: int, nearest: bool) -> int:
178 return int(math.ceil(((value - 1) * stride + border + nearest) / upscale))
Tim Halld8339a72021-05-27 18:49:40 +0100179
180
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200181def get_ifm_area_required(ofm_shape: Shape4D, kernel: Kernel, resampling_mode: resampling_mode) -> Tuple[int, int]:
182 upscale = to_upscale(resampling_mode)
183 nearest = is_nearest(resampling_mode)
184 h1 = _required_size(ofm_shape.height, kernel.stride.y, kernel.area_height(), upscale, nearest)
185 w1 = _required_size(ofm_shape.width, kernel.stride.x, kernel.area_width(), upscale, nearest)
Tim Halld8339a72021-05-27 18:49:40 +0100186 return (w1, h1)
187
188
189def _get_ifm_blocksize(
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200190 ofm_block: Shape4D, kernel: Kernel, ublock: Block, subkernel_limit: Block, upscale: int, nearest: bool
Tim Halld8339a72021-05-27 18:49:40 +0100191) -> Shape4D:
192 # IFM block height
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200193 h1 = _required_size(
194 ofm_block.height, kernel.stride.y, min(kernel.area_height(), subkernel_limit.height), upscale, nearest
195 )
Tim Halld8339a72021-05-27 18:49:40 +0100196 h2 = h1
197 height = round_up(min(h1, h2), ublock.height)
198
199 # IFM block width
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200200 w1 = _required_size(
201 ofm_block.width, kernel.stride.x, min(kernel.area_width(), subkernel_limit.width), upscale, nearest
202 )
Tim Halld8339a72021-05-27 18:49:40 +0100203 w2 = w1
204 width = round_up(min(w1, w2), ublock.width)
205
206 return Shape4D(1, height, width, ofm_block.depth)
207
208
Tim Hall30161572021-06-17 17:03:49 +0100209def fit_block_for_ofm(arch: ArchitectureFeatures, ofm_shape: Shape4D, kernel: Kernel, block: Shape4D):
210 # 256/512 Conv1D optimisation (ratio of IFM:Accumulators changes) This is a specific
211 # interpretation of a more general constraint that can't be applied because the
212 # find_block_config function must return block configs that can be applied to any OFM shape.
213 if (ofm_shape.height == 1) and (kernel.height == 1) and (arch.ofm_ublock.height == 2):
214 return Shape4D(1, min(block.height, ofm_shape.height), block.width, block.depth)
215 return block
216
217
Tim Halld8339a72021-05-27 18:49:40 +0100218def find_block_config(
219 arch: ArchitectureFeatures,
220 npu_op_type: NpuBlockType,
221 ofm_shape: Shape4D,
222 ifm_shape: Shape4D,
223 ifm2_shape: Shape4D,
224 uses_scalar: bool,
225 ifm_bits: int,
226 kernel: Kernel,
227 lut_banks: int,
228 scaled: bool,
229 ifm_resampling: resampling_mode,
230) -> ArchitectureBlockConfig:
231 SplitDepth = ArchitectureFeatures.OFMSplitDepth
232 # Elementwise larger-volume correction
233 if ifm2_shape is not None and ifm2_shape.elements() > ifm_shape.elements():
234 ifm_shape = ifm2_shape
235
236 # Figure out if SHRAM should be portioned for elementwise
237 ew_usage = _ew_usage(npu_op_type, uses_scalar)
238
239 # Operator typing help
240 is_pooling = npu_op_type == NpuBlockType.Pooling
241 is_depthwise = npu_op_type == NpuBlockType.ConvolutionDepthWise
242 is_equal_depth_op = (ew_usage != ElementwiseUsage.No) or is_pooling or is_depthwise
243 is_convolution = (npu_op_type == NpuBlockType.ConvolutionMxN) or is_depthwise
244
245 # Block config to be returned
246 config = ArchitectureBlockConfig()
247 config.is_partkernel = is_convolution and _choose_kernel_method(ifm_shape, ifm_bits, kernel)
248
249 # Accumulator & granule settings
250 config.acc_type = _acc_type(npu_op_type, ifm_bits, scaled)
251
252 # Memory rounding granules
253 acc_granule = arch.accumulator_granules[config.acc_type]
254 acc_bits = _AccumulatorBits[config.acc_type]
255 if ew_usage != ElementwiseUsage.No:
256 ifm_granule = arch.ifm_ew_bank_granules[ifm_bits]
257 else:
258 ifm_granule = arch.ifm_bank_granules[ifm_bits]
259 lut_banks = max(lut_banks, arch.shram.reserved_end_banks)
260 upscale = to_upscale(ifm_resampling)
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200261 nearest = is_nearest(ifm_resampling)
Tim Halld8339a72021-05-27 18:49:40 +0100262
263 # Subkernel repeats of the IFM
264 ifm_repeats = round_up_divide(kernel.area_width(), arch.SubKernelMax.width) * round_up_divide(
265 kernel.area_height(), arch.SubKernelMax.height
266 )
267 ifm_blockdepth = _ifm_blockdepth(arch, ifm_shape, ifm_bits, config.is_partkernel)
268
269 # Weights fetch (for operators that have them)
270 weight_fetch_wh = (kernel.area_width() * kernel.area_height()) if is_convolution else 0
271
272 search_space = Shape4D.min(ofm_shape, Shape4D(arch.ofm_block_max.to_hwc()))
273 search_space = Shape4D.round_up(search_space, Shape4D(arch.ofm_ublock.to_hwc()))
274
275 # Block WHC search, loops across the search space looking for best efficiency
276 best_cost = math.inf
Tim Halldaed1522021-07-19 21:22:46 +0100277 best_coverage = math.inf
Tim Halld8339a72021-05-27 18:49:40 +0100278 depth = max(arch.ofm_ublock.depth, min(search_space.depth, SplitDepth))
279 if depth < ofm_shape.depth:
280 depth = round_up(depth, SplitDepth)
281
282 while depth <= search_space.depth:
283 wont_fit = {}
284 for height in range(arch.ofm_ublock.height, search_space.height + 1, arch.ofm_ublock.height):
285 for width in range(arch.ofm_ublock.width, search_space.width + 1, arch.ofm_ublock.width):
286 # Avoid checking W/H transposed blocks that already didn't fit. i.e. if 8x4x16 didn't
287 # fit, then 4x8x16 won't either.
288 if wont_fit.get((height, width), False):
289 continue
290
291 # Calculate the IFM block dimensions required to feed this OFM block
292 ofm_block = Shape4D(1, height, width, depth)
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200293 ifm_block = _get_ifm_blocksize(ofm_block, kernel, arch.ofm_ublock, arch.SubKernelMax, upscale, nearest)
Tim Halld8339a72021-05-27 18:49:40 +0100294 if not is_equal_depth_op:
295 ifm_block = ifm_block.with_depth(ifm_blockdepth)
296
297 # Test if the IFM/OFM blocks fit into SHRAM
Tim Hall30161572021-06-17 17:03:49 +0100298 ofm_block = fit_block_for_ofm(arch, ofm_shape, kernel, ofm_block)
Tim Halld8339a72021-05-27 18:49:40 +0100299 layout = _try_block_config(
300 arch.shram, ew_usage, ofm_block, ifm_block, ifm_bits, ifm_granule, acc_bits, acc_granule, lut_banks
301 )
302
303 if layout:
Tim Hall789e6f32021-06-17 17:02:31 +0100304 full_blocks = Shape4D.div_round_up(ofm_shape, ofm_block)
305 blocks = ofm_shape / ofm_block
Tim Halld8339a72021-05-27 18:49:40 +0100306
Tim Hall789e6f32021-06-17 17:02:31 +0100307 # Weights fetching
308 weight_fetch = weight_fetch_wh * ifm_shape.depth * full_blocks.elements_wh()
309 if not is_depthwise:
310 weight_fetch *= ofm_block.depth * blocks.depth
Tim Halld8339a72021-05-27 18:49:40 +0100311
Tim Hall789e6f32021-06-17 17:02:31 +0100312 # IFM fetching
313 ifm_fetch = ifm_block.elements_wh() * ifm_shape.depth * ifm_repeats * blocks.elements_wh()
314 if not is_equal_depth_op:
315 ifm_fetch *= full_blocks.depth
Tim Halld8339a72021-05-27 18:49:40 +0100316
Tim Hall789e6f32021-06-17 17:02:31 +0100317 # Scale relative to every output OFM element
318 relative_cost = (ifm_fetch + weight_fetch) / ofm_shape.elements()
Tim Halld8339a72021-05-27 18:49:40 +0100319
320 # If the entire IFM can be encompassed by both buffers, bias to prefer this configuration
321 if ifm_shape.elements() < ifm_block.elements() * 2:
322 relative_cost = relative_cost / 2
323
Tim Halldaed1522021-07-19 21:22:46 +0100324 # Choose based on relative minimum cost or larger IFM area (if equal cost)
325 if relative_cost <= best_cost:
326 choose_this = False
327 # Check IFM coverage only when it's equal best_cost and small OFM
328 if relative_cost == best_cost:
329 coverage_shape = Shape4D.min(ifm_shape, ifm_block)
330 coverage = ifm_shape.elements_wh() / coverage_shape.elements_wh()
331 # Small 4x4 IFM constraint found through analysis of networks
332 if coverage <= best_coverage and (height <= 4 and width <= 4):
333 best_coverage = coverage
334 choose_this = True
335 else:
336 best_coverage = math.inf
337 choose_this = True
338
339 if choose_this:
340 best_cost = relative_cost
341 config.layout = layout
342 config.bank_size = arch.shram_bank_size
343 config.ifm_block = ifm_block
344 config.ofm_block = Shape4D(1, height, width, depth)
Tim Halld8339a72021-05-27 18:49:40 +0100345 else:
346 wont_fit[(width, height)] = True
347
348 depth = depth + arch.ofm_ublock.depth
349 if depth < ofm_shape.depth:
350 depth = round_up(depth, SplitDepth)
351
352 if best_cost != math.inf:
353 return config
354
355 return None
356
357
358def try_block_config(
359 block_config: Block,
360 arch: ArchitectureFeatures,
361 npu_op_type: NpuBlockType,
Tim Hall30161572021-06-17 17:03:49 +0100362 ofm_shape: Block,
Tim Halld8339a72021-05-27 18:49:40 +0100363 ifm_shape: Block,
364 ifm2_shape: Optional[Block],
365 uses_scalar: bool,
366 ifm_bits: int,
367 is_partkernel: bool,
368 kernel: Kernel,
369 lut_banks: int,
370 scaled: bool,
371 ifm_resampling: resampling_mode,
372) -> Optional[ArchitectureBlockConfig]:
373 """
374 Given a block_config, returns a corresponding ArchitectureBlockConfig.
375 Returns None if the block_config does not fit or is invalid.
376 """
377 # Check block config validity
378 if not all(
379 blk > 0 and blk <= blk_max and blk % ublk == 0
380 for blk, blk_max, ublk in zip(block_config.as_list(), arch.ofm_block_max.as_list(), arch.ofm_ublock.as_list())
381 ):
382 return None
383 # Elementwise larger-volume correction
384 if ifm2_shape is not None and ifm2_shape.elements() > ifm_shape.elements():
385 ifm_shape = ifm2_shape
386
387 ew_usage = _ew_usage(npu_op_type, uses_scalar)
388
389 # Operator typing help
390 is_pooling = npu_op_type == NpuBlockType.Pooling
391 is_depthwise = npu_op_type == NpuBlockType.ConvolutionDepthWise
392 is_equal_depth_op = (ew_usage != ElementwiseUsage.No) or is_pooling or is_depthwise
393
394 # Block config to be returned
395 config = ArchitectureBlockConfig()
396 config.is_partkernel = is_partkernel
397
398 # Accumulator & granule settings
399 config.acc_type = _acc_type(npu_op_type, ifm_bits, scaled)
400
401 # Memory rounding granules
402 acc_granule = arch.accumulator_granules[config.acc_type]
403 acc_bits = _AccumulatorBits[config.acc_type]
404 if ew_usage != ElementwiseUsage.No:
405 ifm_granule = arch.ifm_ew_bank_granules[ifm_bits]
406 else:
407 ifm_granule = arch.ifm_bank_granules[ifm_bits]
408 lut_banks = max(lut_banks, arch.shram.reserved_end_banks)
409 upscale = to_upscale(ifm_resampling)
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200410 nearest = is_nearest(ifm_resampling)
Tim Halld8339a72021-05-27 18:49:40 +0100411 ifm_blockdepth = _ifm_blockdepth(arch, ifm_shape, ifm_bits, is_partkernel)
Fredrik Svedberg3ff7a4a2021-09-29 10:08:04 +0200412 ifm_block = _get_ifm_blocksize(block_config, kernel, arch.ofm_ublock, arch.SubKernelMax, upscale, nearest)
Tim Halld8339a72021-05-27 18:49:40 +0100413 if not is_equal_depth_op:
414 ifm_block = ifm_block.with_depth(ifm_blockdepth)
415
Tim Hall30161572021-06-17 17:03:49 +0100416 # 256/512 Conv1D optimisation (ratio of IFM:Accumulators changes)
417 block_config = fit_block_for_ofm(arch, ofm_shape, kernel, block_config)
418
Tim Halld8339a72021-05-27 18:49:40 +0100419 layout = _try_block_config(
420 arch.shram, ew_usage, block_config, ifm_block, ifm_bits, ifm_granule, acc_bits, acc_granule, lut_banks
421 )
422 if layout is None:
423 return None
424 config.layout = layout
425 config.bank_size = arch.shram_bank_size
426 config.ifm_block = ifm_block
Jacob Bohlinb8060f52021-08-09 12:22:51 +0100427 config.ofm_block = block_config
Tim Halld8339a72021-05-27 18:49:40 +0100428 return config