blob: c308a4ae60ac530cf2bcbc50ec111924653e2f33 [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:
282 # Calculate cost in terms of OFM pixels per IFM+Weights fetch
283 ifm_fetch = ifm_block.elements_wh() * ifm_shape.depth
284 weight_fetch = weight_fetch_wh * ifm_shape.depth * (1 if is_depthwise else ofm_block.depth)
285 relative_fetch = (ifm_fetch * ifm_repeats + weight_fetch) / ofm_block.elements()
286
287 # Bias by the number of blocks we'd need to fill the OFM area (fewer, larger, blocks are better)
288 block_bias = round_up_divide(ofm_shape.height, ofm_block.height)
289 block_bias *= round_up_divide(ofm_shape.width, ofm_block.width)
290 # Check waste on all axes (prefer depth, width then height)
291 waste_ratio = 1 + (1.2 * ((ofm_shape.depth % ofm_block.depth) / ofm_block.depth))
292 waste_ratio *= 1 + (1.1 * ((ofm_shape.width % ofm_block.width) / ofm_block.width))
293 waste_ratio *= 1 + (1.0 * ((ofm_shape.height % ofm_block.height) / ofm_block.height))
294
295 # Bias for larger area coverage (or volume if not depthwise)
296 area_bias = 1 / (ofm_block.height * ofm_block.width)
297 if not (is_depthwise or is_pooling):
298 area_bias = area_bias / ofm_block.depth
299
300 relative_cost = relative_fetch * block_bias * waste_ratio * area_bias
301
302 # If the entire IFM can be encompassed by both buffers, bias to prefer this configuration
303 if ifm_shape.elements() < ifm_block.elements() * 2:
304 relative_cost = relative_cost / 2
305
306 if relative_cost < best_cost:
307 best_cost = relative_cost
308 config.layout = layout
309 config.bank_size = arch.shram_bank_size
310 config.ifm_block = ifm_block
311 config.ofm_block = ofm_block
312 else:
313 wont_fit[(width, height)] = True
314
315 depth = depth + arch.ofm_ublock.depth
316 if depth < ofm_shape.depth:
317 depth = round_up(depth, SplitDepth)
318
319 if best_cost != math.inf:
320 return config
321
322 return None
323
324
325def try_block_config(
326 block_config: Block,
327 arch: ArchitectureFeatures,
328 npu_op_type: NpuBlockType,
329 ifm_shape: Block,
330 ifm2_shape: Optional[Block],
331 uses_scalar: bool,
332 ifm_bits: int,
333 is_partkernel: bool,
334 kernel: Kernel,
335 lut_banks: int,
336 scaled: bool,
337 ifm_resampling: resampling_mode,
338) -> Optional[ArchitectureBlockConfig]:
339 """
340 Given a block_config, returns a corresponding ArchitectureBlockConfig.
341 Returns None if the block_config does not fit or is invalid.
342 """
343 # Check block config validity
344 if not all(
345 blk > 0 and blk <= blk_max and blk % ublk == 0
346 for blk, blk_max, ublk in zip(block_config.as_list(), arch.ofm_block_max.as_list(), arch.ofm_ublock.as_list())
347 ):
348 return None
349 # Elementwise larger-volume correction
350 if ifm2_shape is not None and ifm2_shape.elements() > ifm_shape.elements():
351 ifm_shape = ifm2_shape
352
353 ew_usage = _ew_usage(npu_op_type, uses_scalar)
354
355 # Operator typing help
356 is_pooling = npu_op_type == NpuBlockType.Pooling
357 is_depthwise = npu_op_type == NpuBlockType.ConvolutionDepthWise
358 is_equal_depth_op = (ew_usage != ElementwiseUsage.No) or is_pooling or is_depthwise
359
360 # Block config to be returned
361 config = ArchitectureBlockConfig()
362 config.is_partkernel = is_partkernel
363
364 # Accumulator & granule settings
365 config.acc_type = _acc_type(npu_op_type, ifm_bits, scaled)
366
367 # Memory rounding granules
368 acc_granule = arch.accumulator_granules[config.acc_type]
369 acc_bits = _AccumulatorBits[config.acc_type]
370 if ew_usage != ElementwiseUsage.No:
371 ifm_granule = arch.ifm_ew_bank_granules[ifm_bits]
372 else:
373 ifm_granule = arch.ifm_bank_granules[ifm_bits]
374 lut_banks = max(lut_banks, arch.shram.reserved_end_banks)
375 upscale = to_upscale(ifm_resampling)
376 ifm_blockdepth = _ifm_blockdepth(arch, ifm_shape, ifm_bits, is_partkernel)
377 ifm_block = _get_ifm_blocksize(block_config, kernel, arch.ofm_ublock, arch.SubKernelMax, upscale)
378 if not is_equal_depth_op:
379 ifm_block = ifm_block.with_depth(ifm_blockdepth)
380
381 layout = _try_block_config(
382 arch.shram, ew_usage, block_config, ifm_block, ifm_bits, ifm_granule, acc_bits, acc_granule, lut_banks
383 )
384 if layout is None:
385 return None
386 config.layout = layout
387 config.bank_size = arch.shram_bank_size
388 config.ifm_block = ifm_block
389 return config