blob: 2e53a695476529c97f779e93c1dfb1242e9b41c7 [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:
17# Holds a container for Ethos-U55/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
Diego Russoe8a10452020-04-21 17:39:10 +010026from .numeric_util import round_up
27from .numeric_util import round_up_divide
Diego Russoea6111a2020-04-14 18:41:58 +010028from .operation import NpuBlockType
Diego Russoea6111a2020-04-14 18:41:58 +010029from .supported_operators import SupportedOperators
Diego Russoe8a10452020-04-21 17:39:10 +010030from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020031from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010032from .tensor import TensorFormat
33from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010034
35PointXY = namedtuple("PointXY", "x y")
36PointXYZ = namedtuple("PointXYZ", "x y z")
37
38
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
59
60class Rect:
61 def __init__(self, x, y, z, x2, y2, z2):
62 self.x = x
63 self.y = y
64 self.z = z
65 self.x2 = x2
66 self.y2 = y2
67 self.z2 = z2
68
69 def start(self):
70 return PointXYZ(self.x, self.y, self.z)
71
72 def end(self):
73 return PointXYZ(self.x2, self.y2, self.z2)
74
75 def size(self):
76 return Block(self.x2 - self.x + 1, self.y2 - self.y + 1, self.z2 - self.z + 1)
77
78 def __repr__(self):
79 return "<Rect: ({0},{1},{2}) ({3},{4},{5})>".format(self.x, self.y, self.z, self.x2, self.y2, self.z2)
80
81
82class Kernel:
83 def __init__(self, w, h, sx=1, sy=1, dx=1, dy=1):
84 assert sx > 0 and sy > 0
85 assert dx > 0 and dy > 0
86 self.width = w
87 self.height = h
88 self.stride = PointXY(sx, sy)
89 self.dilation = PointXY(dx, dy)
90
91
92class SHRAMElements:
93 IFM8 = 0
94 IFM16 = 1
95 IFM8_Elementwise = 2
96 IFM16_Elementwise = 3
Fredrik Svedberga0c36242020-06-03 15:43:31 +020097 IFM32_Elementwise = 4
98 Acc16 = 5
99 Acc32 = 6
100 Acc40 = 7
Tim Hall79d07d22020-04-27 18:20:16 +0100101 Last = Acc40
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200102 BitSizes = np.array([8, 16, 8, 16, 32, 16, 32, 40], np.int32)
Louis Verhaardf98c6742020-05-12 14:22:38 +0200103 ByteSizes = BitSizes // 8
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200104 PostAlign = np.array([8, 8, 8, 8, 8, 1, 1, 1], np.int32)
105 PreAlign = np.array([1, 1, 1, 1, 1, 8, 8, 8], np.int32)
Tim Hall79d07d22020-04-27 18:20:16 +0100106
107
108class SHRAMBlockConfig:
109 def __init__(self, sizes, banks):
110 assert len(banks) == SHRAMElements.Last + 1
111 self.sizes = sizes
112 self.banks = banks
113
114
115# Area indices must match Ethos-U55 SHRAM layout spec
116class SharedBufferArea(enum.IntEnum):
117 OFM = 0
118 Weights = 1
119 IFM = 2
120 Accumulators = 3
121 Size = Accumulators + 1
122
123
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100124class Accelerator(enum.Enum):
125 Ethos_U55_32 = "ethos-u55-32"
126 Ethos_U55_64 = "ethos-u55-64"
127 Ethos_U55_128 = "ethos-u55-128"
128 Ethos_U55_256 = "ethos-u55-256"
129 Yoda_256 = "yoda-256"
130 Yoda_512 = "yoda-512"
131
132 @classmethod
133 def member_list(cls):
134 return [e.value for e in cls]
135
136
Tim Hall79d07d22020-04-27 18:20:16 +0100137class ArchitectureFeatures:
138 """This class is a container for various parameters of the Ethos-U55 core
139and system configuration that can be tuned, either by command line
140parameters or by the Ethos-U55 architects. The class is often passed
141around to passes that need to do architecture-dependent actions.
142
143Note the difference between ArchitectureFeatures and CompilerOptions
144- ArchitectureFeatures is for changing the Ethos-U55 and system architecture
145- CompilerOptions is for changing the behaviour of the compiler
146
147"""
148
149 ArchitectureConfig = namedtuple(
150 "ArchitectureConfig", "macs cores ofm_ublock ifm_ublock shram_banks shram_granules elem_units"
151 )
152 accelerator_configs = {
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100153 Accelerator.Yoda_512: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200154 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 +0100155 ),
156 Accelerator.Yoda_256: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200157 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 +0100158 ),
159 Accelerator.Ethos_U55_256: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200160 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 +0100161 ),
162 Accelerator.Ethos_U55_128: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200163 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 +0100164 ),
165 Accelerator.Ethos_U55_64: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200166 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 +0100167 ),
168 Accelerator.Ethos_U55_32: ArchitectureConfig(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200169 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 +0100170 ),
Tim Hall79d07d22020-04-27 18:20:16 +0100171 }
172
173 OFMSplitDepth = 16
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100174 SubKernelMax = Block(8, 8, 65536)
Tim Hall79d07d22020-04-27 18:20:16 +0100175
176 def __init__(
177 self,
178 vela_config: ConfigParser,
179 accelerator_config,
180 system_config,
181 permanent_storage,
Tim Hall79d07d22020-04-27 18:20:16 +0100182 override_block_config,
183 block_config_limit,
184 global_memory_clock_scale,
185 max_blockdep,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200186 softmax_support,
Tim Hall79d07d22020-04-27 18:20:16 +0100187 ):
188 accelerator_config = accelerator_config.lower()
189 self.vela_config = vela_config
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100190 if accelerator_config not in Accelerator.member_list():
Louis Verhaard7db78962020-05-25 15:05:26 +0200191 raise OptionError("--accelerator-config", self.accelerator_config, "Unknown accelerator configuration")
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100192 self.accelerator_config = Accelerator(accelerator_config)
Tim Hall79d07d22020-04-27 18:20:16 +0100193 accel_config = ArchitectureFeatures.accelerator_configs[self.accelerator_config]
194 self.config = accel_config
195
196 self.system_config = system_config
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100197 self.is_yoda_system = self.accelerator_config in (Accelerator.Yoda_256, Accelerator.Yoda_512)
Tim Hall79d07d22020-04-27 18:20:16 +0100198
Tim Hall289a41d2020-08-04 21:40:14 +0100199 self.max_outstanding_dma = 2 if self.is_yoda_system else 1
200 self.max_outstanding_kernels = 3
201
Tim Hall79d07d22020-04-27 18:20:16 +0100202 self.ncores = accel_config.cores
203 self.ofm_ublock = accel_config.ofm_ublock
204 self.ifm_ublock = accel_config.ifm_ublock
Tim Hall79d07d22020-04-27 18:20:16 +0100205 self.ofm_block_max = Block(64, 32, 128)
206 self.override_block_config = override_block_config
207 self.block_config_limit = block_config_limit
208
209 self.global_memory_clock_scale = global_memory_clock_scale
210 if self.global_memory_clock_scale <= 0.0 or self.global_memory_clock_scale > 1.0:
211 raise Exception(
212 "Invalid global_memory_clock_scale = "
213 + str(self.global_memory_clock_scale)
214 + " (must be > 0.0 and <= 1.0)"
215 )
216
217 self.max_blockdep = max_blockdep
218
219 dpu_min_height = accel_config.ofm_ublock.height
220 dpu_min_width = accel_config.ofm_ublock.width
221 dpu_dot_product_width = 8
222 dpu_min_ofm_channels = accel_config.ofm_ublock.depth
223
224 self.num_elem_wise_units = accel_config.elem_units
225 self.num_macs_per_cycle = dpu_min_height * dpu_min_width * dpu_dot_product_width * dpu_min_ofm_channels
226
227 self.memory_clock_scales = np.zeros(MemArea.Size)
228 self.memory_port_widths = np.zeros(MemArea.Size)
229
230 # Get system configuration
Tim Hall42e41892020-07-06 10:51:31 +0100231 self.__read_sys_config(self.is_yoda_system)
Tim Hall79d07d22020-04-27 18:20:16 +0100232
233 # apply the global memory clock scales to the individual ones from the system config
234 for mem in MemArea.all():
235 self.memory_clock_scales[mem] *= self.global_memory_clock_scale
236
237 self.memory_clocks = self.memory_clock_scales * self.npu_clock
238 self.memory_bandwidths_per_cycle = self.memory_port_widths * self.memory_clock_scales / 8
239
Tim Hall79d07d22020-04-27 18:20:16 +0100240 self.memory_bandwidths_per_second = self.memory_bandwidths_per_cycle * self.npu_clock
241
242 # sizes as N x H x W x C. we need to round up to these when allocating storage
243 self.storage_rounding_quantums = {
244 TensorFormat.Unknown: (1, 1, 1, 1),
245 TensorFormat.WeightsCompressed: (1, 1, 1, 1),
246 TensorFormat.NHWC: (1, 1, 1, 1),
247 TensorFormat.NHCWB16: (1, 1, 1, 16),
248 }
249
250 # brick sizes as N x H x W x C. We have to fetch whole bricks at a time
251 self.brick_sizes = {
252 TensorFormat.Unknown: (1, 1, 1, 1),
253 TensorFormat.WeightsCompressed: (1, 1, 1, 1),
254 TensorFormat.NHWC: (1, 1, 1, 1),
255 TensorFormat.NHCWB16: (1, 1, 1, 16),
256 }
257
Tim Hall79d07d22020-04-27 18:20:16 +0100258 self.default_weight_format = TensorFormat.WeightsCompressed
259 self.default_feature_map_format = TensorFormat.NHWC
260
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200261 # This is to ignore permanent_storage = On/OffChipflash for Yoda
Tim Hall42e41892020-07-06 10:51:31 +0100262 if not self.is_yoda_system and permanent_storage != MemArea.OffChipFlash:
Tim Hall79d07d22020-04-27 18:20:16 +0100263 self.permanent_storage_mem_area = permanent_storage
264
265 self.tensor_storage_mem_area = {
266 # permanent mem_area
Tim Hall465582c2020-05-26 09:33:14 +0100267 TensorPurpose.Unknown: MemArea.Unknown,
Tim Hall79d07d22020-04-27 18:20:16 +0100268 TensorPurpose.Weights: self.permanent_storage_mem_area,
269 TensorPurpose.FeatureMap: self.feature_map_storage_mem_area,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200270 TensorPurpose.LUT: self.permanent_storage_mem_area,
Tim Hall79d07d22020-04-27 18:20:16 +0100271 }
272
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200273 self.tensor_storage_mem_type = {
Dwight Lidman1a9d20e2020-08-11 12:10:36 +0200274 TensorPurpose.Unknown: MemType.Unknown,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200275 TensorPurpose.Weights: MemType.Permanent_NPU,
276 TensorPurpose.FeatureMap: MemType.Scratch,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200277 TensorPurpose.LUT: MemType.Scratch,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200278 }
Tim Hall79d07d22020-04-27 18:20:16 +0100279
280 self.min_block_sizes = {
281 NpuBlockType.Default: (dpu_min_height, dpu_min_width),
282 NpuBlockType.VectorProduct: (1, 1),
283 NpuBlockType.ConvolutionMxN: (dpu_min_height, dpu_min_width),
284 NpuBlockType.Pooling: (dpu_min_height, dpu_min_width),
285 NpuBlockType.ConvolutionDepthWise: (dpu_min_height, dpu_min_width),
286 NpuBlockType.ElementWise: (1, 1),
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200287 NpuBlockType.ReduceSum: (dpu_min_height, dpu_min_width),
Tim Hall79d07d22020-04-27 18:20:16 +0100288 }
289
290 self.sub_kernel_limits = {
291 NpuBlockType.Default: (8, 8),
292 NpuBlockType.VectorProduct: (1, 1),
293 NpuBlockType.ConvolutionMxN: (8, 8),
294 NpuBlockType.Pooling: (8, 8),
295 NpuBlockType.ConvolutionDepthWise: (8, 8),
296 NpuBlockType.ElementWise: (1, 1),
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200297 NpuBlockType.ReduceSum: (8, 8),
Tim Hall79d07d22020-04-27 18:20:16 +0100298 }
299
300 # weights for scheduler search
301 from .npu_performance import make_bandwidth_array
302
303 self.bandwidth_weights = make_bandwidth_array()
304 self.bandwidth_weights[MemArea.Sram] = 1.0
305 self.bandwidth_weights[MemArea.Dram] = 10.0
306 self.bandwidth_weights[MemArea.OnChipFlash] = 2.0
307 self.bandwidth_weights[MemArea.OffChipFlash] = 20.0
308 self.cycles_weight = 40
309 self.max_sram_used_weight = 1000
310
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200311 if self.is_yoda_system and (self.fast_storage_mem_area != self.feature_map_storage_mem_area):
312 self.max_sram_used_weight = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100313
314 # Shared Buffer Block allocations
315 self.shram_bank_size = 1024 # bytes
316 self.shram_size_bytes = accel_config.shram_banks * self.shram_bank_size
317 self.shram_reserved_output_banks = 2
318 self.shram_reserved_weight_banks = 0
319 self.shram_reserved_unused_banks = 2 if accel_config.shram_banks > 16 else 0
320 self.shram_total_banks = accel_config.shram_banks - self.shram_reserved_unused_banks
321 self.shram_bank_granules = np.array(accel_config.shram_granules, np.int32)
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200322 self.shram_lut_size = 2048
323 # SHRAM base address of the activation lookup table
324 self.shram_lut_address = self.shram_bank_size * self.available_shram_banks(True)
Tim Hall79d07d22020-04-27 18:20:16 +0100325
326 # Build a map of acceptable IFM/OFM block configurations up to the maximum
327 # IFM/OFM block size.
328 ifm_block_max = self.get_ifm_block_size(32, self.ofm_block_max, Kernel(8, 8))
329 self.block_config_map = dict()
330 self.generate_block_config_map(Block(ifm_block_max.width, ifm_block_max.height, 128))
331
332 # Setup supported operators and restriction checkers class
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200333 self.supported_operators = SupportedOperators(softmax_support)
Tim Hall79d07d22020-04-27 18:20:16 +0100334
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200335 # Returns available number of SHRAM banks depending on activation lookup table
336 # being used or not
337 def available_shram_banks(self, uses_activation_lut):
338 banks = self.shram_total_banks
339 if uses_activation_lut and self.shram_reserved_unused_banks == 0:
340 banks -= 2
341 return banks
342
Tim Hall79d07d22020-04-27 18:20:16 +0100343 # Calculate block configuration for ALL known IFM operations and
344 # accumulator sizes. Consumers will need to select their preferred
345 # operation and bit-width at read-time.
346 def generate_block_config(self, width, height, depth):
Louis Verhaardf98c6742020-05-12 14:22:38 +0200347 # Number of bytes required for any SHRAM element for a FM of given dimensions.
348 # For IFM: size = H*W*Align(D*BYTE_WIDTH, 8)
349 # For ACC: size = H*W*Align(D,8)*BYTE_WIDTH
350 d1 = round_up(depth, SHRAMElements.PreAlign)
351 d2 = round_up(d1 * SHRAMElements.ByteSizes, SHRAMElements.PostAlign)
352 size_bytes = (height * width) * d2
353
Tim Hall79d07d22020-04-27 18:20:16 +0100354 # Convert byte size (rounded) to size in banks
355 size_banks = round_up_divide(size_bytes, self.shram_bank_size)
356 size_banks *= 2 # Double buffer the IFM/Acc (need twice as many banks)
357 # Round bank requirement to bank granularity
358 required_banks = round_up(size_banks, self.shram_bank_granules)
359 return SHRAMBlockConfig(size_bytes, required_banks)
360
361 @staticmethod
362 def make_block_config_key(width, height, depth):
363 return (int(height), int(width), int(depth))
364
365 def get_block_config(self, width, height, depth):
366 assert depth <= self.ofm_block_max.depth
367 key = ArchitectureFeatures.make_block_config_key(width, height, depth)
368 config = self.block_config_map.get(key, None)
369 return config
370
371 # Generate a key:value map of possible block configurations, where the
372 # key is compounded from the block dimensions: 0x00HHWWCC
373 def generate_block_config_map(self, block: Block):
374 for h in range(1, block.height + 1):
375 for w in range(1, block.width + 1):
376 # All possible IFM/OFM depth values
377 for c in [4, 8, 12, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128]:
378 key = ArchitectureFeatures.make_block_config_key(w, h, c)
379 self.block_config_map[key] = self.generate_block_config(w, h, c)
380
381 def calc_ifm_block_depth(self, ifm_depth, ifm_bits):
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200382 assert ifm_bits in (8, 16, 32)
Tim Hall79d07d22020-04-27 18:20:16 +0100383 assert ifm_depth > 0
384 ifm_depth = round_up(ifm_depth, self.ifm_ublock.depth)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200385 max_block_depth = 8 * 32 // ifm_bits
Tim Hall79d07d22020-04-27 18:20:16 +0100386 return min(max_block_depth, ifm_depth)
387
388 # Calculate the size of the IFM block given a depth, target OFM block and a kernel
Tim Hallc30f4952020-06-15 20:47:35 +0100389 def get_ifm_block_size(
390 self,
391 ifm_block_depth,
392 ofm_block: Block,
393 kernel: Kernel,
394 subkernel: Block = Block(8, 8, 65536),
395 ifm_resampling_mode=resampling_mode.NONE,
396 ):
Dwight Lidmana9390f72020-05-13 12:00:08 +0200397 upscaling = 1 if ifm_resampling_mode == resampling_mode.NONE else 2
Tim Hall79d07d22020-04-27 18:20:16 +0100398 # Height
399 ifm_odd_2x_height_enable = 0
400 dilated_kernel_height = ((kernel.height - 1) * kernel.dilation.y) + 1
401 ifm_block_height = (
402 (ofm_block.height - 1) * kernel.stride.y
403 + min(subkernel.height, dilated_kernel_height)
404 + ifm_odd_2x_height_enable
405 ) // upscaling
406
Dwight Lidman0538a772020-05-06 14:09:17 +0200407 ifm_block_height = round_up(ifm_block_height, self.ofm_ublock.height)
Tim Hall79d07d22020-04-27 18:20:16 +0100408
409 # Width
410 ifm_odd_2x_width_enable = 0
411 dilated_kernel_width = ((kernel.width - 1) * kernel.dilation.x) + 1
412 ifm_block_width = (
413 (ofm_block.width - 1) * kernel.stride.x
414 + min(subkernel.width, dilated_kernel_width)
415 + ifm_odd_2x_width_enable
416 ) // upscaling
417
Dwight Lidman0538a772020-05-06 14:09:17 +0200418 ifm_block_width = round_up(ifm_block_width, self.ofm_ublock.width)
Tim Hall79d07d22020-04-27 18:20:16 +0100419
420 return Block(ifm_block_width, ifm_block_height, ifm_block_depth)
421
422 @staticmethod
423 def intersects(start_a, end_a, start_b, end_b):
424 start_x = max(start_a[0], start_b[0])
425 end_x = min(end_a[0], end_b[0])
426 start_y = max(start_a[1], start_b[1])
427 end_y = min(end_a[1], end_b[1])
428 start_z = max(start_a[2], start_b[2])
429 end_z = min(end_a[2], end_b[2])
430 return ((end_x - start_x) > 0) and ((end_y - start_y) > 0) and ((end_z - start_z) > 0)
431
432 # Block job dependency:
433 # Does the VOLUME of IFMs for block job B(0) overlap with VOLUME of OFMs block jobs A(8,9,10)
434 #
435 # A | B
436 # ----------------------+------------------
437 # .... 3,4,5,6,7,8,9,10 | 0,1,2,3,4,5,6,8 10 < JOB NUMBER
438 # |<------->| dependency offset
439 #
440 MAX_BLOCKDEP = 3
441
442 # Get the coordinates of a block offset from either the end (negative)
443 # or the start (zero or positive) of the given 3d area
444 def get_offset_block_coords(self, area: Rect, block: Block, offset):
445 size = area.size()
446 # Dimensions of the region, in blocks
447 width_blocks = round_up_divide(size.width, block.width)
448 height_blocks = round_up_divide(size.height, block.height)
449 depth_blocks = round_up_divide(size.depth, block.depth)
450 total_blocks = width_blocks * height_blocks * depth_blocks
451 if offset < 0:
452 index = total_blocks + offset
453 else:
454 index = offset
455
456 if index >= total_blocks:
457 return None
458
459 # Coordinates of the indexed block
460 coord_z = block.depth * (index % depth_blocks)
461 coord_y = block.height * (index // (depth_blocks * width_blocks))
462 coord_x = block.width * ((index // depth_blocks) % width_blocks)
463
464 return (coord_x + area.x, coord_y + area.y, coord_z + area.z)
465
466 def get_first_job_input_volume(
467 self, ifm: Rect, ofm: Rect, ifm_block_depth, ofm_block: Block, kernel: Kernel, padLT, block_offset
468 ):
469 # Get ifm block size (jobs are invisibly decomposed into subkernels)
470 ifm_block = self.get_ifm_block_size(ifm_block_depth, ofm_block, kernel, self.ofm_block_max)
471 ifm_depth_blocks = round_up_divide(ifm.size().depth, ifm_block_depth)
472
473 # Which OFM block are we calculating
474 ofm_coord = self.get_offset_block_coords(ofm, ofm_block, block_offset // ifm_depth_blocks)
475 if ofm_coord is None:
476 return None
477
478 # Coordinate of the source IFM block
479 ifm_coord_x = max(0, ofm_coord[0] * kernel.stride.x - padLT[0])
480 ifm_coord_y = max(0, ofm_coord[1] * kernel.stride.y - padLT[1])
481 ifm_coord_z = ifm.z + (block_offset % ifm_depth_blocks) * ifm_block.depth
482
483 # IFM block that will be sampled for the FIRST+block_offset job in the next operator's OFM
484 start_coord = (ifm_coord_x, ifm_coord_y, ifm_coord_z)
485 end_coord = (
486 start_coord[0] + ifm_block.width,
487 start_coord[1] + ifm_block.height,
488 start_coord[2] + ifm_block.depth,
489 )
490
491 return (start_coord, end_coord, 1) # start, end, total jobs
492
493 def get_prev_job_output_volume(
494 self, ifm: Block, ofm: Rect, ifm_block_depth, ofm_block: Block, kernel: Kernel, block_offset
495 ):
496 assert block_offset >= 0
497
498 # Get OFM block's volume coordinates
499 start_coord = self.get_offset_block_coords(ofm, ofm_block, -1 - block_offset)
500 if start_coord is None:
501 return None
502 end_coord = (
503 start_coord[0] + ofm_block.width,
504 start_coord[1] + ofm_block.height,
505 start_coord[2] + ofm_block.depth,
506 )
507
508 # Calculate how many IFM blocks this OFM block requires (i.e how many jobs)
Tim Hall79d07d22020-04-27 18:20:16 +0100509 ifm_depth_blocks = round_up_divide(ifm.size().depth, ifm_block_depth)
510 ifm_depth_blocks = 1 # Overwrite with 1 to force OFM block dependency, not IFM
511
512 return (start_coord, end_coord, ifm_depth_blocks) # start, end, total jobs for this OFM block
513
514 def calc_block_dep(
515 self,
516 prev_ifm: Block,
517 prev_ofm: Block,
518 prev_ifm_block_depth,
519 prev_ofm_block: Block,
520 prev_kernel: Kernel,
521 ifm: Block,
522 ofm: Block,
523 ifm_block_depth,
524 ofm_block: Block,
525 kernel: Kernel,
526 padLT,
527 ):
528
529 blockdep = ArchitectureFeatures.MAX_BLOCKDEP
530
531 # Iterate over the next BLOCKDEP inputs, checking to see if a sliding window
532 # of IFM area overlaps with any previous OFM block generation.
533 elapsed_jobs = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100534 for forward_offset in range(ArchitectureFeatures.MAX_BLOCKDEP):
535 # This is the IFM block we want to sample from
536 in_area = self.get_first_job_input_volume(
537 ifm, ofm, ifm_block_depth, ofm_block, kernel, padLT, forward_offset
538 )
539 if in_area is None:
540 break
541
542 # Try several previous-OFM blocks in the past (they still might comprise multiple IFM jobs)
543 outstanding_jobs = 0
544 for block_offset in range(ArchitectureFeatures.MAX_BLOCKDEP):
545 # This is the OFM block being generated by the previous op
546 out_area = self.get_prev_job_output_volume(
547 prev_ifm, prev_ofm, prev_ifm_block_depth, prev_ofm_block, prev_kernel, block_offset
548 )
549 if out_area is None:
550 break
551
552 # Block dependency is the max number of allowed outstanding jobs
553 # in the pipeline. Selected by determining how many jobs occur
554 # in between two operators' overlapping OFM->IFM block volumes
555 if ArchitectureFeatures.intersects(in_area[0], in_area[1], out_area[0], out_area[1]):
556 break
557 # Early exit if no intersections and we've seen enough jobs in the pipeline
558 elif outstanding_jobs > ArchitectureFeatures.MAX_BLOCKDEP:
559 break
560
561 # This OFM had this many jobs (accumulate over multiple OFM blocks)
562 outstanding_jobs += out_area[2]
563
564 blockdep = min(blockdep, elapsed_jobs + outstanding_jobs)
565 elapsed_jobs += in_area[2]
566 # Early exit if no intersections and we've seen enough jobs in the pipeline
567 if elapsed_jobs > ArchitectureFeatures.MAX_BLOCKDEP:
568 break
569
570 return blockdep
571
572 def cpu_cycle_estimate(self, op):
573 """
574 Gets estimated performance of a CPU operation, based on a linear model of intercept, slope,
575 specified in the vela config file, in ConfigParser file format (.ini file).
576 Example configuration snippet:
577 [CpuPerformance.MyOperationType]
578 Cortex-Mx.intercept=<some float value>
579 Cortex-Mx.slope=<some float value>
580 """
581 section = "CpuPerformance." + op.type
582 if self.vela_config is not None and section in self.vela_config:
583 op_config = self.vela_config[section]
584 try:
585 intercept = float(op_config.get(self.cpu_config + ".intercept", op_config["default.intercept"]))
586 slope = float(op_config.get(self.cpu_config + ".slope", op_config["default.slope"]))
587 n_elements = op.inputs[0].elements()
588 cycles = intercept + n_elements * slope
589 return cycles
Diego Russoea6111a2020-04-14 18:41:58 +0100590 except Exception:
Tim Hall79d07d22020-04-27 18:20:16 +0100591 print("Error: Reading CPU cycle estimate in vela configuration file, section {}".format(section))
592 raise
593
594 print("Warning: No configured CPU performance estimate for", op.type)
595 return 0
596
Patrik Gustavsson5f47c052020-06-25 12:56:04 +0200597 def __read_sys_config(self, is_yoda_system):
Tim Hall79d07d22020-04-27 18:20:16 +0100598 """
599 Gets the system configuration with the given name from the vela configuration file
600 Example configuration snippet:
601 [SysConfig.MyConfigName]
602 npu_freq=<some float value>
603 cpu=Cortex-Mx
604 ...
605 """
606 # Get system configuration from the vela configuration file
607 if self.vela_config is None:
608 print("Warning: Using default values for system configuration")
609 else:
610 section_key = "SysConfig." + self.system_config
Diego Russoea6111a2020-04-14 18:41:58 +0100611 if section_key not in self.vela_config:
Louis Verhaard7db78962020-05-25 15:05:26 +0200612 raise OptionError("--system-config", self.system_config, "Unknown system configuration")
Tim Hall79d07d22020-04-27 18:20:16 +0100613
614 try:
615 self.npu_clock = float(self.__sys_config("npu_freq", "500e6"))
616 self.cpu_config = self.__sys_config("cpu", "Cortex-M7")
617
618 self.memory_clock_scales[MemArea.Sram] = float(self.__sys_config("Sram_clock_scale", "1"))
619 self.memory_port_widths[MemArea.Sram] = int(self.__sys_config("Sram_port_width", "64"))
620
621 self.memory_clock_scales[MemArea.OnChipFlash] = float(self.__sys_config("OnChipFlash_clock_scale", "1"))
622 self.memory_port_widths[MemArea.OnChipFlash] = int(self.__sys_config("OnChipFlash_port_width", "64"))
623
624 self.memory_clock_scales[MemArea.OffChipFlash] = float(
625 self.__sys_config("OffChipFlash_clock_scale", "0.25")
626 )
627 self.memory_port_widths[MemArea.OffChipFlash] = int(self.__sys_config("OffChipFlash_port_width", "32"))
628
629 self.memory_clock_scales[MemArea.Dram] = float(self.__sys_config("Dram_clock_scale", "1"))
630 self.memory_port_widths[MemArea.Dram] = int(self.__sys_config("Dram_port_width", "32"))
631
632 self.fast_storage_mem_area = MemArea[self.__sys_config("fast_storage_mem_area", "Sram")]
633 self.feature_map_storage_mem_area = MemArea[self.__sys_config("feature_map_storage_mem_area", "Sram")]
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200634
Tim Hall79d07d22020-04-27 18:20:16 +0100635 self.permanent_storage_mem_area = MemArea[self.__sys_config("permanent_storage_mem_area", "OffChipFlash")]
Patrik Gustavsson5f47c052020-06-25 12:56:04 +0200636 if is_yoda_system:
637 if self.permanent_storage_mem_area is not MemArea.Dram:
638 raise Exception(
639 "Invalid permanent_storage_mem_area = "
640 + str(self.permanent_storage_mem_area)
641 + " (must be 'DRAM' for Yoda)."
642 )
643 else:
644 if self.permanent_storage_mem_area not in set((MemArea.OnChipFlash, MemArea.OffChipFlash)):
645 raise Exception(
646 "Invalid permanent_storage_mem_area = "
647 + str(self.permanent_storage_mem_area)
648 + " (must be 'OnChipFlash' or 'OffChipFlash' for ethosu-55)."
649 " To store the weights and other constant data in SRAM on ethosu-55 select 'OnChipFlash'"
650 )
651
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200652 self.sram_size = 1024 * int(self.__sys_config("sram_size_kb", "204800"))
653
Diego Russoea6111a2020-04-14 18:41:58 +0100654 except Exception:
Tim Hall79d07d22020-04-27 18:20:16 +0100655 print("Error: Reading System Configuration in vela configuration file, section {}".format(section_key))
656 raise
657
658 def __sys_config(self, key, default_value):
659 """
660 Gets the system configuration value with the given key from the vela config file.
661 """
662 if self.vela_config is None:
663 return default_value
664 section = "SysConfig." + self.system_config
665 result = self.vela_config[section].get(key, None)
666 if result is None:
667 raise Exception("Error: System Configuration Missing key {} in section [{}] ".format(key, section))
668 return result