blob: e43b841de137c4f4b27d9fc3bb00e317a412f8f0 [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
160def to_upscale(ifm_resampling: resampling_mode) -> int:
161 # Upscaling depending on resampling mode
162 return 1 if ifm_resampling == resampling_mode.NONE else 2
163
164
165def _ifm_blockdepth(arch, ifm_shape: Shape4D, ifm_bits: int, is_partkernel: bool):
166 if ifm_bits == 16:
167 ifm_blockdepth = round_up(min(ifm_shape.depth, 16), 4)
168 else:
169 ifm_blockdepth = round_up(min(ifm_shape.depth, 16 if is_partkernel else 32), arch.ifm_ublock.depth)
170 return ifm_blockdepth
171
172
173def _required_size(value: int, stride: int, border: int, upscale: int) -> int:
174 return int(math.ceil(((value - 1) * stride + border) / upscale))
175
176
177def get_ifm_area_required(ofm_shape: Shape4D, kernel: Kernel, upscale: int) -> Tuple[int, int]:
178 h1 = _required_size(ofm_shape.height, kernel.stride.y, kernel.area_height(), upscale)
179 w1 = _required_size(ofm_shape.width, kernel.stride.x, kernel.area_width(), upscale)
180 return (w1, h1)
181
182
183def _get_ifm_blocksize(
184 ofm_block: Shape4D, kernel: Kernel, ublock: Block, subkernel_limit: Block, upscale: int
185) -> Shape4D:
186 # IFM block height
187 h1 = _required_size(ofm_block.height, kernel.stride.y, min(kernel.area_height(), subkernel_limit.height), upscale)
188 h2 = h1
189 height = round_up(min(h1, h2), ublock.height)
190
191 # IFM block width
192 w1 = _required_size(ofm_block.width, kernel.stride.x, min(kernel.area_width(), subkernel_limit.width), upscale)
193 w2 = w1
194 width = round_up(min(w1, w2), ublock.width)
195
196 return Shape4D(1, height, width, ofm_block.depth)
197
198
199def find_block_config(
200 arch: ArchitectureFeatures,
201 npu_op_type: NpuBlockType,
202 ofm_shape: Shape4D,
203 ifm_shape: Shape4D,
204 ifm2_shape: Shape4D,
205 uses_scalar: bool,
206 ifm_bits: int,
207 kernel: Kernel,
208 lut_banks: int,
209 scaled: bool,
210 ifm_resampling: resampling_mode,
211) -> ArchitectureBlockConfig:
212 SplitDepth = ArchitectureFeatures.OFMSplitDepth
213 # Elementwise larger-volume correction
214 if ifm2_shape is not None and ifm2_shape.elements() > ifm_shape.elements():
215 ifm_shape = ifm2_shape
216
217 # Figure out if SHRAM should be portioned for elementwise
218 ew_usage = _ew_usage(npu_op_type, uses_scalar)
219
220 # Operator typing help
221 is_pooling = npu_op_type == NpuBlockType.Pooling
222 is_depthwise = npu_op_type == NpuBlockType.ConvolutionDepthWise
223 is_equal_depth_op = (ew_usage != ElementwiseUsage.No) or is_pooling or is_depthwise
224 is_convolution = (npu_op_type == NpuBlockType.ConvolutionMxN) or is_depthwise
225
226 # Block config to be returned
227 config = ArchitectureBlockConfig()
228 config.is_partkernel = is_convolution and _choose_kernel_method(ifm_shape, ifm_bits, kernel)
229
230 # Accumulator & granule settings
231 config.acc_type = _acc_type(npu_op_type, ifm_bits, scaled)
232
233 # Memory rounding granules
234 acc_granule = arch.accumulator_granules[config.acc_type]
235 acc_bits = _AccumulatorBits[config.acc_type]
236 if ew_usage != ElementwiseUsage.No:
237 ifm_granule = arch.ifm_ew_bank_granules[ifm_bits]
238 else:
239 ifm_granule = arch.ifm_bank_granules[ifm_bits]
240 lut_banks = max(lut_banks, arch.shram.reserved_end_banks)
241 upscale = to_upscale(ifm_resampling)
242
243 # Subkernel repeats of the IFM
244 ifm_repeats = round_up_divide(kernel.area_width(), arch.SubKernelMax.width) * round_up_divide(
245 kernel.area_height(), arch.SubKernelMax.height
246 )
247 ifm_blockdepth = _ifm_blockdepth(arch, ifm_shape, ifm_bits, config.is_partkernel)
248
249 # Weights fetch (for operators that have them)
250 weight_fetch_wh = (kernel.area_width() * kernel.area_height()) if is_convolution else 0
251
252 search_space = Shape4D.min(ofm_shape, Shape4D(arch.ofm_block_max.to_hwc()))
253 search_space = Shape4D.round_up(search_space, Shape4D(arch.ofm_ublock.to_hwc()))
254
255 # Block WHC search, loops across the search space looking for best efficiency
256 best_cost = math.inf
257 depth = max(arch.ofm_ublock.depth, min(search_space.depth, SplitDepth))
258 if depth < ofm_shape.depth:
259 depth = round_up(depth, SplitDepth)
260
261 while depth <= search_space.depth:
262 wont_fit = {}
263 for height in range(arch.ofm_ublock.height, search_space.height + 1, arch.ofm_ublock.height):
264 for width in range(arch.ofm_ublock.width, search_space.width + 1, arch.ofm_ublock.width):
265 # Avoid checking W/H transposed blocks that already didn't fit. i.e. if 8x4x16 didn't
266 # fit, then 4x8x16 won't either.
267 if wont_fit.get((height, width), False):
268 continue
269
270 # Calculate the IFM block dimensions required to feed this OFM block
271 ofm_block = Shape4D(1, height, width, depth)
272 ifm_block = _get_ifm_blocksize(ofm_block, kernel, arch.ofm_ublock, arch.SubKernelMax, upscale)
273 if not is_equal_depth_op:
274 ifm_block = ifm_block.with_depth(ifm_blockdepth)
275
276 # Test if the IFM/OFM blocks fit into SHRAM
277 layout = _try_block_config(
278 arch.shram, ew_usage, ofm_block, ifm_block, ifm_bits, ifm_granule, acc_bits, acc_granule, lut_banks
279 )
280
281 if layout:
Tim Hall789e6f32021-06-17 17:02:31 +0100282 full_blocks = Shape4D.div_round_up(ofm_shape, ofm_block)
283 blocks = ofm_shape / ofm_block
Tim Halld8339a72021-05-27 18:49:40 +0100284
Tim Hall789e6f32021-06-17 17:02:31 +0100285 # Weights fetching
286 weight_fetch = weight_fetch_wh * ifm_shape.depth * full_blocks.elements_wh()
287 if not is_depthwise:
288 weight_fetch *= ofm_block.depth * blocks.depth
Tim Halld8339a72021-05-27 18:49:40 +0100289
Tim Hall789e6f32021-06-17 17:02:31 +0100290 # IFM fetching
291 ifm_fetch = ifm_block.elements_wh() * ifm_shape.depth * ifm_repeats * blocks.elements_wh()
292 if not is_equal_depth_op:
293 ifm_fetch *= full_blocks.depth
Tim Halld8339a72021-05-27 18:49:40 +0100294
Tim Hall789e6f32021-06-17 17:02:31 +0100295 # Scale relative to every output OFM element
296 relative_cost = (ifm_fetch + weight_fetch) / ofm_shape.elements()
Tim Halld8339a72021-05-27 18:49:40 +0100297
298 # If the entire IFM can be encompassed by both buffers, bias to prefer this configuration
299 if ifm_shape.elements() < ifm_block.elements() * 2:
300 relative_cost = relative_cost / 2
301
302 if relative_cost < best_cost:
303 best_cost = relative_cost
304 config.layout = layout
305 config.bank_size = arch.shram_bank_size
306 config.ifm_block = ifm_block
307 config.ofm_block = ofm_block
308 else:
309 wont_fit[(width, height)] = True
310
311 depth = depth + arch.ofm_ublock.depth
312 if depth < ofm_shape.depth:
313 depth = round_up(depth, SplitDepth)
314
315 if best_cost != math.inf:
316 return config
317
318 return None
319
320
321def try_block_config(
322 block_config: Block,
323 arch: ArchitectureFeatures,
324 npu_op_type: NpuBlockType,
325 ifm_shape: Block,
326 ifm2_shape: Optional[Block],
327 uses_scalar: bool,
328 ifm_bits: int,
329 is_partkernel: bool,
330 kernel: Kernel,
331 lut_banks: int,
332 scaled: bool,
333 ifm_resampling: resampling_mode,
334) -> Optional[ArchitectureBlockConfig]:
335 """
336 Given a block_config, returns a corresponding ArchitectureBlockConfig.
337 Returns None if the block_config does not fit or is invalid.
338 """
339 # Check block config validity
340 if not all(
341 blk > 0 and blk <= blk_max and blk % ublk == 0
342 for blk, blk_max, ublk in zip(block_config.as_list(), arch.ofm_block_max.as_list(), arch.ofm_ublock.as_list())
343 ):
344 return None
345 # Elementwise larger-volume correction
346 if ifm2_shape is not None and ifm2_shape.elements() > ifm_shape.elements():
347 ifm_shape = ifm2_shape
348
349 ew_usage = _ew_usage(npu_op_type, uses_scalar)
350
351 # Operator typing help
352 is_pooling = npu_op_type == NpuBlockType.Pooling
353 is_depthwise = npu_op_type == NpuBlockType.ConvolutionDepthWise
354 is_equal_depth_op = (ew_usage != ElementwiseUsage.No) or is_pooling or is_depthwise
355
356 # Block config to be returned
357 config = ArchitectureBlockConfig()
358 config.is_partkernel = is_partkernel
359
360 # Accumulator & granule settings
361 config.acc_type = _acc_type(npu_op_type, ifm_bits, scaled)
362
363 # Memory rounding granules
364 acc_granule = arch.accumulator_granules[config.acc_type]
365 acc_bits = _AccumulatorBits[config.acc_type]
366 if ew_usage != ElementwiseUsage.No:
367 ifm_granule = arch.ifm_ew_bank_granules[ifm_bits]
368 else:
369 ifm_granule = arch.ifm_bank_granules[ifm_bits]
370 lut_banks = max(lut_banks, arch.shram.reserved_end_banks)
371 upscale = to_upscale(ifm_resampling)
372 ifm_blockdepth = _ifm_blockdepth(arch, ifm_shape, ifm_bits, is_partkernel)
373 ifm_block = _get_ifm_blocksize(block_config, kernel, arch.ofm_ublock, arch.SubKernelMax, upscale)
374 if not is_equal_depth_op:
375 ifm_block = ifm_block.with_depth(ifm_blockdepth)
376
377 layout = _try_block_config(
378 arch.shram, ew_usage, block_config, ifm_block, ifm_bits, ifm_granule, acc_bits, acc_granule, lut_banks
379 )
380 if layout is None:
381 return None
382 config.layout = layout
383 config.bank_size = arch.shram_bank_size
384 config.ifm_block = ifm_block
385 return config