blob: 9ca4304c658c2f68e577ca5c2a72a643f4f96af9 [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 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.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
Tim Hallc8a73862020-10-27 12:43:14 +000017# Holds a container for Ethos-U and System architecture parameters.
Diego Russoea6111a2020-04-14 18:41:58 +010018import enum
Tim Hall79d07d22020-04-27 18:20:16 +010019from collections import namedtuple
20from configparser import ConfigParser
Diego Russoea6111a2020-04-14 18:41:58 +010021
Tim Hall79d07d22020-04-27 18:20:16 +010022import numpy as np
Diego Russoea6111a2020-04-14 18:41:58 +010023
Louis Verhaard7db78962020-05-25 15:05:26 +020024from .errors import OptionError
Dwight Lidmana9390f72020-05-13 12:00:08 +020025from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaard69b31762020-11-17 09:45:20 +010026from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010027from .numeric_util import round_up
28from .numeric_util import round_up_divide
Tim Hall4ed38bc2020-10-20 18:54:20 +010029from .operation import Kernel
Diego Russoea6111a2020-04-14 18:41:58 +010030from .operation import NpuBlockType
Tim Hall4ed38bc2020-10-20 18:54:20 +010031from .operation import PointXYZ
Diego Russoea6111a2020-04-14 18:41:58 +010032from .supported_operators import SupportedOperators
Diego Russoe8a10452020-04-21 17:39:10 +010033from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020034from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010035from .tensor import TensorFormat
36from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010037
Tim Hall79d07d22020-04-27 18:20:16 +010038
39class Block:
40 def __init__(self, w, h, d):
41 self.width = w
42 self.height = h
43 self.depth = d
44
45 def __eq__(self, other):
46 if self.width == other.width and self.height == other.height and self.depth == other.depth:
47 return True
48 else:
49 return False
50
51 def __repr__(self):
52 return "<Block: {0},{1},{2}>".format(self.width, self.height, self.depth)
53
54 @classmethod
55 def from_string(cls, s):
56 w, h, c = (int(v) for v in s.split("x"))
57 return cls(w, h, c)
58
Louis Verhaard69b31762020-11-17 09:45:20 +010059 @classmethod
60 def from_shape(cls, shape) -> "Block":
61 """Converts the shape to a Block"""
62 shp = full_shape(3, shape, 1)
63 # Note: index from end, as len(shp) may be > 3
64 return Block(shp[-2], shp[-3], shp[-1])
65
Tim Hall79d07d22020-04-27 18:20:16 +010066
67class Rect:
68 def __init__(self, x, y, z, x2, y2, z2):
69 self.x = x
70 self.y = y
71 self.z = z
72 self.x2 = x2
73 self.y2 = y2
74 self.z2 = z2
75
76 def start(self):
77 return PointXYZ(self.x, self.y, self.z)
78
79 def end(self):
80 return PointXYZ(self.x2, self.y2, self.z2)
81
82 def size(self):
83 return Block(self.x2 - self.x + 1, self.y2 - self.y + 1, self.z2 - self.z + 1)
84
85 def __repr__(self):
86 return "<Rect: ({0},{1},{2}) ({3},{4},{5})>".format(self.x, self.y, self.z, self.x2, self.y2, self.z2)
87
88
Tim Hall79d07d22020-04-27 18:20:16 +010089class SHRAMElements:
90 IFM8 = 0
91 IFM16 = 1
92 IFM8_Elementwise = 2
93 IFM16_Elementwise = 3
Fredrik Svedberg597fd3f2020-08-13 10:02:53 +020094 IFM32 = 4
Fredrik Svedberga0c36242020-06-03 15:43:31 +020095 Acc16 = 5
96 Acc32 = 6
97 Acc40 = 7
Tim Hall79d07d22020-04-27 18:20:16 +010098 Last = Acc40
Fredrik Svedberga0c36242020-06-03 15:43:31 +020099 BitSizes = np.array([8, 16, 8, 16, 32, 16, 32, 40], np.int32)
Louis Verhaardf98c6742020-05-12 14:22:38 +0200100 ByteSizes = BitSizes // 8
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200101 PostAlign = np.array([8, 8, 8, 8, 8, 1, 1, 1], np.int32)
102 PreAlign = np.array([1, 1, 1, 1, 1, 8, 8, 8], np.int32)
Tim Hall79d07d22020-04-27 18:20:16 +0100103
104
105class SHRAMBlockConfig:
106 def __init__(self, sizes, banks):
107 assert len(banks) == SHRAMElements.Last + 1
108 self.sizes = sizes
109 self.banks = banks
110
111
Tim Hallc8a73862020-10-27 12:43:14 +0000112# Area indices must match Ethos-U SHRAM layout spec
Tim Hall79d07d22020-04-27 18:20:16 +0100113class SharedBufferArea(enum.IntEnum):
114 OFM = 0
115 Weights = 1
116 IFM = 2
117 Accumulators = 3
118 Size = Accumulators + 1
119
120
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100121class Accelerator(enum.Enum):
122 Ethos_U55_32 = "ethos-u55-32"
123 Ethos_U55_64 = "ethos-u55-64"
124 Ethos_U55_128 = "ethos-u55-128"
125 Ethos_U55_256 = "ethos-u55-256"
Tim Hallc8a73862020-10-27 12:43:14 +0000126 Ethos_U65_256 = "ethos-u65-256"
127 Ethos_U65_512 = "ethos-u65-512"
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100128
129 @classmethod
130 def member_list(cls):
131 return [e.value for e in cls]
132
133
Tim Hall79d07d22020-04-27 18:20:16 +0100134class ArchitectureFeatures:
Tim Hallc8a73862020-10-27 12:43:14 +0000135 """This class is a container for various parameters of the Ethos-U core
Diqing Zhonge8887a32020-09-24 09:53:48 +0200136 and system configuration that can be tuned, either by command line
Tim Hallc8a73862020-10-27 12:43:14 +0000137 parameters or by the Ethos-U architects. The class is often passed
Diqing Zhonge8887a32020-09-24 09:53:48 +0200138 around to passes that need to do architecture-dependent actions.
Tim Hall79d07d22020-04-27 18:20:16 +0100139
Diqing Zhonge8887a32020-09-24 09:53:48 +0200140 Note the difference between ArchitectureFeatures and CompilerOptions
Tim Hallc8a73862020-10-27 12:43:14 +0000141 - ArchitectureFeatures is for changing the Ethos-U and system architecture
Diqing Zhonge8887a32020-09-24 09:53:48 +0200142 - CompilerOptions is for changing the behaviour of the compiler
143 """
Tim Hall79d07d22020-04-27 18:20:16 +0100144
145 ArchitectureConfig = namedtuple(
146 "ArchitectureConfig", "macs cores ofm_ublock ifm_ublock shram_banks shram_granules elem_units"
147 )
148 accelerator_configs = {
Tim Hallc8a73862020-10-27 12:43:14 +0000149 Accelerator.Ethos_U65_512: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200150 256, 2, Block(2, 2, 8), Block(2, 2, 8), 48, [8, 8, 8, 8, 16, 8, 16, 20], 8
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100151 ),
Tim Hallc8a73862020-10-27 12:43:14 +0000152 Accelerator.Ethos_U65_256: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200153 256, 1, Block(2, 2, 8), Block(2, 2, 8), 48, [8, 8, 8, 8, 16, 8, 16, 20], 8
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100154 ),
155 Accelerator.Ethos_U55_256: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200156 256, 1, Block(2, 2, 8), Block(2, 2, 8), 48, [8, 8, 8, 8, 16, 8, 16, 20], 8
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100157 ),
158 Accelerator.Ethos_U55_128: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200159 128, 1, Block(2, 1, 8), Block(2, 2, 8), 24, [4, 4, 4, 4, 8, 4, 8, 12], 4
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100160 ),
161 Accelerator.Ethos_U55_64: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200162 64, 1, Block(1, 1, 8), Block(1, 1, 8), 16, [2, 2, 2, 2, 4, 4, 4, 8], 2
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100163 ),
164 Accelerator.Ethos_U55_32: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200165 32, 1, Block(1, 1, 4), Block(1, 1, 8), 16, [2, 2, 2, 2, 4, 4, 4, 4], 1
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100166 ),
Tim Hall79d07d22020-04-27 18:20:16 +0100167 }
168
169 OFMSplitDepth = 16
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100170 SubKernelMax = Block(8, 8, 65536)
Tim Hall79d07d22020-04-27 18:20:16 +0100171
172 def __init__(
173 self,
174 vela_config: ConfigParser,
175 accelerator_config,
176 system_config,
Tim Hall79d07d22020-04-27 18:20:16 +0100177 override_block_config,
178 block_config_limit,
179 global_memory_clock_scale,
180 max_blockdep,
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200181 weight_estimation_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100182 ):
183 accelerator_config = accelerator_config.lower()
184 self.vela_config = vela_config
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100185 if accelerator_config not in Accelerator.member_list():
Louis Verhaard7db78962020-05-25 15:05:26 +0200186 raise OptionError("--accelerator-config", self.accelerator_config, "Unknown accelerator configuration")
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100187 self.accelerator_config = Accelerator(accelerator_config)
Tim Hall79d07d22020-04-27 18:20:16 +0100188 accel_config = ArchitectureFeatures.accelerator_configs[self.accelerator_config]
189 self.config = accel_config
190
191 self.system_config = system_config
Tim Hallc8a73862020-10-27 12:43:14 +0000192 self.is_ethos_u65_system = self.accelerator_config in (Accelerator.Ethos_U65_256, Accelerator.Ethos_U65_512)
Tim Hall79d07d22020-04-27 18:20:16 +0100193
Tim Hallc8a73862020-10-27 12:43:14 +0000194 self.max_outstanding_dma = 2 if self.is_ethos_u65_system else 1
Tim Hall289a41d2020-08-04 21:40:14 +0100195 self.max_outstanding_kernels = 3
196
Tim Hall79d07d22020-04-27 18:20:16 +0100197 self.ncores = accel_config.cores
198 self.ofm_ublock = accel_config.ofm_ublock
199 self.ifm_ublock = accel_config.ifm_ublock
Tim Hall79d07d22020-04-27 18:20:16 +0100200 self.ofm_block_max = Block(64, 32, 128)
201 self.override_block_config = override_block_config
202 self.block_config_limit = block_config_limit
203
204 self.global_memory_clock_scale = global_memory_clock_scale
205 if self.global_memory_clock_scale <= 0.0 or self.global_memory_clock_scale > 1.0:
206 raise Exception(
207 "Invalid global_memory_clock_scale = "
208 + str(self.global_memory_clock_scale)
209 + " (must be > 0.0 and <= 1.0)"
210 )
211
212 self.max_blockdep = max_blockdep
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200213 self.weight_estimation_scaling = weight_estimation_scaling
Tim Hall79d07d22020-04-27 18:20:16 +0100214
215 dpu_min_height = accel_config.ofm_ublock.height
216 dpu_min_width = accel_config.ofm_ublock.width
217 dpu_dot_product_width = 8
218 dpu_min_ofm_channels = accel_config.ofm_ublock.depth
219
220 self.num_elem_wise_units = accel_config.elem_units
221 self.num_macs_per_cycle = dpu_min_height * dpu_min_width * dpu_dot_product_width * dpu_min_ofm_channels
222
223 self.memory_clock_scales = np.zeros(MemArea.Size)
224 self.memory_port_widths = np.zeros(MemArea.Size)
225
226 # Get system configuration
Tim Hallc8a73862020-10-27 12:43:14 +0000227 self.__read_sys_config(self.is_ethos_u65_system)
Tim Hall79d07d22020-04-27 18:20:16 +0100228
229 # apply the global memory clock scales to the individual ones from the system config
230 for mem in MemArea.all():
231 self.memory_clock_scales[mem] *= self.global_memory_clock_scale
232
233 self.memory_clocks = self.memory_clock_scales * self.npu_clock
234 self.memory_bandwidths_per_cycle = self.memory_port_widths * self.memory_clock_scales / 8
235
Tim Hall79d07d22020-04-27 18:20:16 +0100236 self.memory_bandwidths_per_second = self.memory_bandwidths_per_cycle * self.npu_clock
237
Diqing Zhonge8887a32020-09-24 09:53:48 +0200238 # Get output/activation performance numbers
239 self._generate_output_perf_tables(self.accelerator_config)
240
Tim Hall79d07d22020-04-27 18:20:16 +0100241 # sizes as N x H x W x C. we need to round up to these when allocating storage
242 self.storage_rounding_quantums = {
243 TensorFormat.Unknown: (1, 1, 1, 1),
244 TensorFormat.WeightsCompressed: (1, 1, 1, 1),
245 TensorFormat.NHWC: (1, 1, 1, 1),
246 TensorFormat.NHCWB16: (1, 1, 1, 16),
247 }
248
249 # brick sizes as N x H x W x C. We have to fetch whole bricks at a time
250 self.brick_sizes = {
251 TensorFormat.Unknown: (1, 1, 1, 1),
252 TensorFormat.WeightsCompressed: (1, 1, 1, 1),
253 TensorFormat.NHWC: (1, 1, 1, 1),
254 TensorFormat.NHCWB16: (1, 1, 1, 16),
255 }
256
Tim Hall79d07d22020-04-27 18:20:16 +0100257 self.default_weight_format = TensorFormat.WeightsCompressed
258 self.default_feature_map_format = TensorFormat.NHWC
259
Tim Hall79d07d22020-04-27 18:20:16 +0100260 self.tensor_storage_mem_area = {
261 # permanent mem_area
Tim Hall465582c2020-05-26 09:33:14 +0100262 TensorPurpose.Unknown: MemArea.Unknown,
Tim Hall79d07d22020-04-27 18:20:16 +0100263 TensorPurpose.Weights: self.permanent_storage_mem_area,
264 TensorPurpose.FeatureMap: self.feature_map_storage_mem_area,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200265 TensorPurpose.LUT: self.permanent_storage_mem_area,
Tim Hall79d07d22020-04-27 18:20:16 +0100266 }
267
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200268 self.tensor_storage_mem_type = {
Dwight Lidman1a9d20e2020-08-11 12:10:36 +0200269 TensorPurpose.Unknown: MemType.Unknown,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200270 TensorPurpose.Weights: MemType.Permanent_NPU,
271 TensorPurpose.FeatureMap: MemType.Scratch,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200272 TensorPurpose.LUT: MemType.Scratch,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200273 }
Tim Hall79d07d22020-04-27 18:20:16 +0100274
275 self.min_block_sizes = {
276 NpuBlockType.Default: (dpu_min_height, dpu_min_width),
277 NpuBlockType.VectorProduct: (1, 1),
278 NpuBlockType.ConvolutionMxN: (dpu_min_height, dpu_min_width),
279 NpuBlockType.Pooling: (dpu_min_height, dpu_min_width),
280 NpuBlockType.ConvolutionDepthWise: (dpu_min_height, dpu_min_width),
281 NpuBlockType.ElementWise: (1, 1),
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200282 NpuBlockType.ReduceSum: (dpu_min_height, dpu_min_width),
Tim Hall79d07d22020-04-27 18:20:16 +0100283 }
284
285 self.sub_kernel_limits = {
286 NpuBlockType.Default: (8, 8),
287 NpuBlockType.VectorProduct: (1, 1),
288 NpuBlockType.ConvolutionMxN: (8, 8),
289 NpuBlockType.Pooling: (8, 8),
290 NpuBlockType.ConvolutionDepthWise: (8, 8),
291 NpuBlockType.ElementWise: (1, 1),
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200292 NpuBlockType.ReduceSum: (8, 8),
Tim Hall79d07d22020-04-27 18:20:16 +0100293 }
294
295 # weights for scheduler search
296 from .npu_performance import make_bandwidth_array
297
298 self.bandwidth_weights = make_bandwidth_array()
299 self.bandwidth_weights[MemArea.Sram] = 1.0
300 self.bandwidth_weights[MemArea.Dram] = 10.0
301 self.bandwidth_weights[MemArea.OnChipFlash] = 2.0
302 self.bandwidth_weights[MemArea.OffChipFlash] = 20.0
303 self.cycles_weight = 40
304 self.max_sram_used_weight = 1000
305
Tim Hallc8a73862020-10-27 12:43:14 +0000306 if self.is_ethos_u65_system and (self.fast_storage_mem_area != self.feature_map_storage_mem_area):
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200307 self.max_sram_used_weight = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100308
309 # Shared Buffer Block allocations
310 self.shram_bank_size = 1024 # bytes
311 self.shram_size_bytes = accel_config.shram_banks * self.shram_bank_size
312 self.shram_reserved_output_banks = 2
313 self.shram_reserved_weight_banks = 0
314 self.shram_reserved_unused_banks = 2 if accel_config.shram_banks > 16 else 0
315 self.shram_total_banks = accel_config.shram_banks - self.shram_reserved_unused_banks
316 self.shram_bank_granules = np.array(accel_config.shram_granules, np.int32)
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200317 self.shram_lut_size = 2048
318 # SHRAM base address of the activation lookup table
319 self.shram_lut_address = self.shram_bank_size * self.available_shram_banks(True)
Tim Hall79d07d22020-04-27 18:20:16 +0100320
321 # Build a map of acceptable IFM/OFM block configurations up to the maximum
322 # IFM/OFM block size.
323 ifm_block_max = self.get_ifm_block_size(32, self.ofm_block_max, Kernel(8, 8))
324 self.block_config_map = dict()
325 self.generate_block_config_map(Block(ifm_block_max.width, ifm_block_max.height, 128))
326
327 # Setup supported operators and restriction checkers class
Fredrik Svedberg880e7352020-08-25 11:31:47 +0200328 self.supported_operators = SupportedOperators()
Tim Hall79d07d22020-04-27 18:20:16 +0100329
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200330 # Returns available number of SHRAM banks depending on activation lookup table
331 # being used or not
332 def available_shram_banks(self, uses_activation_lut):
333 banks = self.shram_total_banks
334 if uses_activation_lut and self.shram_reserved_unused_banks == 0:
335 banks -= 2
336 return banks
337
Tim Hall79d07d22020-04-27 18:20:16 +0100338 # Calculate block configuration for ALL known IFM operations and
339 # accumulator sizes. Consumers will need to select their preferred
340 # operation and bit-width at read-time.
341 def generate_block_config(self, width, height, depth):
Louis Verhaardf98c6742020-05-12 14:22:38 +0200342 # Number of bytes required for any SHRAM element for a FM of given dimensions.
343 # For IFM: size = H*W*Align(D*BYTE_WIDTH, 8)
344 # For ACC: size = H*W*Align(D,8)*BYTE_WIDTH
345 d1 = round_up(depth, SHRAMElements.PreAlign)
346 d2 = round_up(d1 * SHRAMElements.ByteSizes, SHRAMElements.PostAlign)
347 size_bytes = (height * width) * d2
348
Tim Hall79d07d22020-04-27 18:20:16 +0100349 # Convert byte size (rounded) to size in banks
350 size_banks = round_up_divide(size_bytes, self.shram_bank_size)
351 size_banks *= 2 # Double buffer the IFM/Acc (need twice as many banks)
352 # Round bank requirement to bank granularity
353 required_banks = round_up(size_banks, self.shram_bank_granules)
354 return SHRAMBlockConfig(size_bytes, required_banks)
355
356 @staticmethod
357 def make_block_config_key(width, height, depth):
358 return (int(height), int(width), int(depth))
359
360 def get_block_config(self, width, height, depth):
361 assert depth <= self.ofm_block_max.depth
362 key = ArchitectureFeatures.make_block_config_key(width, height, depth)
363 config = self.block_config_map.get(key, None)
364 return config
365
366 # Generate a key:value map of possible block configurations, where the
367 # key is compounded from the block dimensions: 0x00HHWWCC
368 def generate_block_config_map(self, block: Block):
369 for h in range(1, block.height + 1):
370 for w in range(1, block.width + 1):
371 # All possible IFM/OFM depth values
372 for c in [4, 8, 12, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128]:
373 key = ArchitectureFeatures.make_block_config_key(w, h, c)
374 self.block_config_map[key] = self.generate_block_config(w, h, c)
375
Diqing Zhonge8887a32020-09-24 09:53:48 +0200376 def _generate_output_perf_tables(self, accel_config):
377 if accel_config == Accelerator.Ethos_U55_32:
378 self.output_cycles_per_elem = (2.0, 3.0, 3.0, 3.0, 4.0, 6.0, 1.0, 2.0)
379 self.activation_cycles_per_elem = (1.0, 1.0, 0.0)
380 elif accel_config == Accelerator.Ethos_U55_64:
381 self.output_cycles_per_elem = (1.0, 1.5, 1.5, 1.5, 2.0, 3.0, 0.5, 1.0)
382 self.activation_cycles_per_elem = (1.0, 1.0, 0.0)
383 elif accel_config == Accelerator.Ethos_U55_128:
384 self.output_cycles_per_elem = (0.75, 1.25, 0.75, 0.75, 1.0, 1.5, 0.25, 0.5)
385 self.activation_cycles_per_elem = (1.0, 0.5, 0.0)
Tim Hallc8a73862020-10-27 12:43:14 +0000386 elif accel_config in (Accelerator.Ethos_U55_256, Accelerator.Ethos_U65_256):
Diqing Zhonge8887a32020-09-24 09:53:48 +0200387 self.output_cycles_per_elem = (0.625, 1.125, 0.5, 0.375, 0.5, 0.75, 0.125, 0.25)
388 self.activation_cycles_per_elem = (1.0, 0.25, 0.0)
389 else:
Tim Hallc8a73862020-10-27 12:43:14 +0000390 assert accel_config == Accelerator.Ethos_U65_512
Diqing Zhonge8887a32020-09-24 09:53:48 +0200391 self.output_cycles_per_elem = (0.3125, 0.5625, 0.25, 0.1875, 0.25, 0.375, 0.0625, 0.125)
392 self.activation_cycles_per_elem = (0.5, 0.125, 0.0)
393
Tim Hall79d07d22020-04-27 18:20:16 +0100394 def calc_ifm_block_depth(self, ifm_depth, ifm_bits):
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200395 assert ifm_bits in (8, 16, 32)
Tim Hall79d07d22020-04-27 18:20:16 +0100396 assert ifm_depth > 0
397 ifm_depth = round_up(ifm_depth, self.ifm_ublock.depth)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200398 max_block_depth = 8 * 32 // ifm_bits
Tim Hall79d07d22020-04-27 18:20:16 +0100399 return min(max_block_depth, ifm_depth)
400
401 # Calculate the size of the IFM block given a depth, target OFM block and a kernel
Tim Hallc30f4952020-06-15 20:47:35 +0100402 def get_ifm_block_size(
403 self,
404 ifm_block_depth,
405 ofm_block: Block,
406 kernel: Kernel,
407 subkernel: Block = Block(8, 8, 65536),
408 ifm_resampling_mode=resampling_mode.NONE,
409 ):
Dwight Lidmana9390f72020-05-13 12:00:08 +0200410 upscaling = 1 if ifm_resampling_mode == resampling_mode.NONE else 2
Tim Hall79d07d22020-04-27 18:20:16 +0100411 # Height
412 ifm_odd_2x_height_enable = 0
413 dilated_kernel_height = ((kernel.height - 1) * kernel.dilation.y) + 1
414 ifm_block_height = (
415 (ofm_block.height - 1) * kernel.stride.y
416 + min(subkernel.height, dilated_kernel_height)
417 + ifm_odd_2x_height_enable
418 ) // upscaling
419
Dwight Lidman0538a772020-05-06 14:09:17 +0200420 ifm_block_height = round_up(ifm_block_height, self.ofm_ublock.height)
Tim Hall79d07d22020-04-27 18:20:16 +0100421
422 # Width
423 ifm_odd_2x_width_enable = 0
424 dilated_kernel_width = ((kernel.width - 1) * kernel.dilation.x) + 1
425 ifm_block_width = (
426 (ofm_block.width - 1) * kernel.stride.x
427 + min(subkernel.width, dilated_kernel_width)
428 + ifm_odd_2x_width_enable
429 ) // upscaling
430
Dwight Lidman0538a772020-05-06 14:09:17 +0200431 ifm_block_width = round_up(ifm_block_width, self.ofm_ublock.width)
Tim Hall79d07d22020-04-27 18:20:16 +0100432
433 return Block(ifm_block_width, ifm_block_height, ifm_block_depth)
434
435 @staticmethod
436 def intersects(start_a, end_a, start_b, end_b):
437 start_x = max(start_a[0], start_b[0])
438 end_x = min(end_a[0], end_b[0])
439 start_y = max(start_a[1], start_b[1])
440 end_y = min(end_a[1], end_b[1])
441 start_z = max(start_a[2], start_b[2])
442 end_z = min(end_a[2], end_b[2])
443 return ((end_x - start_x) > 0) and ((end_y - start_y) > 0) and ((end_z - start_z) > 0)
444
445 # Block job dependency:
446 # Does the VOLUME of IFMs for block job B(0) overlap with VOLUME of OFMs block jobs A(8,9,10)
447 #
448 # A | B
449 # ----------------------+------------------
450 # .... 3,4,5,6,7,8,9,10 | 0,1,2,3,4,5,6,8 10 < JOB NUMBER
451 # |<------->| dependency offset
452 #
453 MAX_BLOCKDEP = 3
454
455 # Get the coordinates of a block offset from either the end (negative)
456 # or the start (zero or positive) of the given 3d area
457 def get_offset_block_coords(self, area: Rect, block: Block, offset):
458 size = area.size()
459 # Dimensions of the region, in blocks
460 width_blocks = round_up_divide(size.width, block.width)
461 height_blocks = round_up_divide(size.height, block.height)
462 depth_blocks = round_up_divide(size.depth, block.depth)
463 total_blocks = width_blocks * height_blocks * depth_blocks
464 if offset < 0:
465 index = total_blocks + offset
466 else:
467 index = offset
468
469 if index >= total_blocks:
470 return None
471
472 # Coordinates of the indexed block
473 coord_z = block.depth * (index % depth_blocks)
474 coord_y = block.height * (index // (depth_blocks * width_blocks))
475 coord_x = block.width * ((index // depth_blocks) % width_blocks)
476
477 return (coord_x + area.x, coord_y + area.y, coord_z + area.z)
478
479 def get_first_job_input_volume(
480 self, ifm: Rect, ofm: Rect, ifm_block_depth, ofm_block: Block, kernel: Kernel, padLT, block_offset
481 ):
482 # Get ifm block size (jobs are invisibly decomposed into subkernels)
483 ifm_block = self.get_ifm_block_size(ifm_block_depth, ofm_block, kernel, self.ofm_block_max)
484 ifm_depth_blocks = round_up_divide(ifm.size().depth, ifm_block_depth)
485
486 # Which OFM block are we calculating
487 ofm_coord = self.get_offset_block_coords(ofm, ofm_block, block_offset // ifm_depth_blocks)
488 if ofm_coord is None:
489 return None
490
491 # Coordinate of the source IFM block
492 ifm_coord_x = max(0, ofm_coord[0] * kernel.stride.x - padLT[0])
493 ifm_coord_y = max(0, ofm_coord[1] * kernel.stride.y - padLT[1])
494 ifm_coord_z = ifm.z + (block_offset % ifm_depth_blocks) * ifm_block.depth
495
496 # IFM block that will be sampled for the FIRST+block_offset job in the next operator's OFM
497 start_coord = (ifm_coord_x, ifm_coord_y, ifm_coord_z)
498 end_coord = (
499 start_coord[0] + ifm_block.width,
500 start_coord[1] + ifm_block.height,
501 start_coord[2] + ifm_block.depth,
502 )
503
504 return (start_coord, end_coord, 1) # start, end, total jobs
505
506 def get_prev_job_output_volume(
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100507 self, ifm: Rect, ofm: Rect, ifm_block_depth, ofm_block: Block, kernel: Kernel, block_offset
Tim Hall79d07d22020-04-27 18:20:16 +0100508 ):
509 assert block_offset >= 0
510
511 # Get OFM block's volume coordinates
512 start_coord = self.get_offset_block_coords(ofm, ofm_block, -1 - block_offset)
513 if start_coord is None:
514 return None
515 end_coord = (
516 start_coord[0] + ofm_block.width,
517 start_coord[1] + ofm_block.height,
518 start_coord[2] + ofm_block.depth,
519 )
520
521 # Calculate how many IFM blocks this OFM block requires (i.e how many jobs)
Tim Hall79d07d22020-04-27 18:20:16 +0100522 ifm_depth_blocks = round_up_divide(ifm.size().depth, ifm_block_depth)
523 ifm_depth_blocks = 1 # Overwrite with 1 to force OFM block dependency, not IFM
524
525 return (start_coord, end_coord, ifm_depth_blocks) # start, end, total jobs for this OFM block
526
527 def calc_block_dep(
528 self,
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100529 prev_ifm: Rect,
530 prev_ofm: Rect,
Tim Hall79d07d22020-04-27 18:20:16 +0100531 prev_ifm_block_depth,
532 prev_ofm_block: Block,
533 prev_kernel: Kernel,
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100534 ifm: Rect,
535 ofm: Rect,
Tim Hall79d07d22020-04-27 18:20:16 +0100536 ifm_block_depth,
537 ofm_block: Block,
538 kernel: Kernel,
539 padLT,
540 ):
541
542 blockdep = ArchitectureFeatures.MAX_BLOCKDEP
543
544 # Iterate over the next BLOCKDEP inputs, checking to see if a sliding window
545 # of IFM area overlaps with any previous OFM block generation.
546 elapsed_jobs = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100547 for forward_offset in range(ArchitectureFeatures.MAX_BLOCKDEP):
548 # This is the IFM block we want to sample from
549 in_area = self.get_first_job_input_volume(
550 ifm, ofm, ifm_block_depth, ofm_block, kernel, padLT, forward_offset
551 )
552 if in_area is None:
553 break
554
555 # Try several previous-OFM blocks in the past (they still might comprise multiple IFM jobs)
556 outstanding_jobs = 0
557 for block_offset in range(ArchitectureFeatures.MAX_BLOCKDEP):
558 # This is the OFM block being generated by the previous op
559 out_area = self.get_prev_job_output_volume(
560 prev_ifm, prev_ofm, prev_ifm_block_depth, prev_ofm_block, prev_kernel, block_offset
561 )
562 if out_area is None:
563 break
564
565 # Block dependency is the max number of allowed outstanding jobs
566 # in the pipeline. Selected by determining how many jobs occur
567 # in between two operators' overlapping OFM->IFM block volumes
568 if ArchitectureFeatures.intersects(in_area[0], in_area[1], out_area[0], out_area[1]):
569 break
570 # Early exit if no intersections and we've seen enough jobs in the pipeline
571 elif outstanding_jobs > ArchitectureFeatures.MAX_BLOCKDEP:
572 break
573
574 # This OFM had this many jobs (accumulate over multiple OFM blocks)
575 outstanding_jobs += out_area[2]
576
577 blockdep = min(blockdep, elapsed_jobs + outstanding_jobs)
578 elapsed_jobs += in_area[2]
579 # Early exit if no intersections and we've seen enough jobs in the pipeline
580 if elapsed_jobs > ArchitectureFeatures.MAX_BLOCKDEP:
581 break
582
583 return blockdep
584
585 def cpu_cycle_estimate(self, op):
586 """
587 Gets estimated performance of a CPU operation, based on a linear model of intercept, slope,
588 specified in the vela config file, in ConfigParser file format (.ini file).
589 Example configuration snippet:
590 [CpuPerformance.MyOperationType]
591 Cortex-Mx.intercept=<some float value>
592 Cortex-Mx.slope=<some float value>
593 """
Louis Verhaardaee5d752020-09-30 09:01:52 +0200594 section = "CpuPerformance." + op.type.name
Tim Hall79d07d22020-04-27 18:20:16 +0100595 if self.vela_config is not None and section in self.vela_config:
596 op_config = self.vela_config[section]
597 try:
598 intercept = float(op_config.get(self.cpu_config + ".intercept", op_config["default.intercept"]))
599 slope = float(op_config.get(self.cpu_config + ".slope", op_config["default.slope"]))
600 n_elements = op.inputs[0].elements()
601 cycles = intercept + n_elements * slope
602 return cycles
Diego Russoea6111a2020-04-14 18:41:58 +0100603 except Exception:
Tim Hall79d07d22020-04-27 18:20:16 +0100604 print("Error: Reading CPU cycle estimate in vela configuration file, section {}".format(section))
605 raise
606
607 print("Warning: No configured CPU performance estimate for", op.type)
608 return 0
609
Tim Hallc8a73862020-10-27 12:43:14 +0000610 def __read_sys_config(self, is_ethos_u65_system):
Tim Hall79d07d22020-04-27 18:20:16 +0100611 """
612 Gets the system configuration with the given name from the vela configuration file
613 Example configuration snippet:
614 [SysConfig.MyConfigName]
615 npu_freq=<some float value>
616 cpu=Cortex-Mx
617 ...
618 """
619 # Get system configuration from the vela configuration file
620 if self.vela_config is None:
621 print("Warning: Using default values for system configuration")
622 else:
623 section_key = "SysConfig." + self.system_config
Diego Russoea6111a2020-04-14 18:41:58 +0100624 if section_key not in self.vela_config:
Louis Verhaard7db78962020-05-25 15:05:26 +0200625 raise OptionError("--system-config", self.system_config, "Unknown system configuration")
Tim Hall79d07d22020-04-27 18:20:16 +0100626
627 try:
628 self.npu_clock = float(self.__sys_config("npu_freq", "500e6"))
629 self.cpu_config = self.__sys_config("cpu", "Cortex-M7")
630
631 self.memory_clock_scales[MemArea.Sram] = float(self.__sys_config("Sram_clock_scale", "1"))
632 self.memory_port_widths[MemArea.Sram] = int(self.__sys_config("Sram_port_width", "64"))
633
634 self.memory_clock_scales[MemArea.OnChipFlash] = float(self.__sys_config("OnChipFlash_clock_scale", "1"))
635 self.memory_port_widths[MemArea.OnChipFlash] = int(self.__sys_config("OnChipFlash_port_width", "64"))
636
637 self.memory_clock_scales[MemArea.OffChipFlash] = float(
638 self.__sys_config("OffChipFlash_clock_scale", "0.25")
639 )
640 self.memory_port_widths[MemArea.OffChipFlash] = int(self.__sys_config("OffChipFlash_port_width", "32"))
641
642 self.memory_clock_scales[MemArea.Dram] = float(self.__sys_config("Dram_clock_scale", "1"))
643 self.memory_port_widths[MemArea.Dram] = int(self.__sys_config("Dram_port_width", "32"))
644
645 self.fast_storage_mem_area = MemArea[self.__sys_config("fast_storage_mem_area", "Sram")]
646 self.feature_map_storage_mem_area = MemArea[self.__sys_config("feature_map_storage_mem_area", "Sram")]
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200647
Tim Hall79d07d22020-04-27 18:20:16 +0100648 self.permanent_storage_mem_area = MemArea[self.__sys_config("permanent_storage_mem_area", "OffChipFlash")]
Tim Hallc8a73862020-10-27 12:43:14 +0000649 if is_ethos_u65_system:
Patrik Gustavsson5f47c052020-06-25 12:56:04 +0200650 if self.permanent_storage_mem_area is not MemArea.Dram:
651 raise Exception(
652 "Invalid permanent_storage_mem_area = "
653 + str(self.permanent_storage_mem_area)
Tim Hallc8a73862020-10-27 12:43:14 +0000654 + " (must be 'DRAM' for Ethos-U65)."
Patrik Gustavsson5f47c052020-06-25 12:56:04 +0200655 )
656 else:
657 if self.permanent_storage_mem_area not in set((MemArea.OnChipFlash, MemArea.OffChipFlash)):
658 raise Exception(
659 "Invalid permanent_storage_mem_area = "
660 + str(self.permanent_storage_mem_area)
Tim Hallc8a73862020-10-27 12:43:14 +0000661 + " (must be 'OnChipFlash' or 'OffChipFlash' for Ethos-U55)."
662 " To store the weights and other constant data in SRAM on Ethos-U55 select 'OnChipFlash'"
Patrik Gustavsson5f47c052020-06-25 12:56:04 +0200663 )
664
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200665 self.sram_size = 1024 * int(self.__sys_config("sram_size_kb", "204800"))
666
Diego Russoea6111a2020-04-14 18:41:58 +0100667 except Exception:
Tim Hall79d07d22020-04-27 18:20:16 +0100668 print("Error: Reading System Configuration in vela configuration file, section {}".format(section_key))
669 raise
670
671 def __sys_config(self, key, default_value):
672 """
673 Gets the system configuration value with the given key from the vela config file.
674 """
675 if self.vela_config is None:
676 return default_value
677 section = "SysConfig." + self.system_config
678 result = self.vela_config[section].get(key, None)
679 if result is None:
680 raise Exception("Error: System Configuration Missing key {} in section [{}] ".format(key, section))
681 return result