blob: 1bf9d950b05840a64eeaffda4e8f65e8d9dd5b27 [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
Diego Russoe8a10452020-04-21 17:39:10 +010025from .numeric_util import round_up
26from .numeric_util import round_up_divide
Diego Russoea6111a2020-04-14 18:41:58 +010027from .operation import NpuBlockType
Diego Russoea6111a2020-04-14 18:41:58 +010028from .supported_operators import SupportedOperators
Diego Russoe8a10452020-04-21 17:39:10 +010029from .tensor import MemArea
30from .tensor import TensorFormat
31from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010032
33PointXY = namedtuple("PointXY", "x y")
34PointXYZ = namedtuple("PointXYZ", "x y z")
35
36
37class Block:
38 def __init__(self, w, h, d):
39 self.width = w
40 self.height = h
41 self.depth = d
42
43 def __eq__(self, other):
44 if self.width == other.width and self.height == other.height and self.depth == other.depth:
45 return True
46 else:
47 return False
48
49 def __repr__(self):
50 return "<Block: {0},{1},{2}>".format(self.width, self.height, self.depth)
51
52 @classmethod
53 def from_string(cls, s):
54 w, h, c = (int(v) for v in s.split("x"))
55 return cls(w, h, c)
56
57
58class Rect:
59 def __init__(self, x, y, z, x2, y2, z2):
60 self.x = x
61 self.y = y
62 self.z = z
63 self.x2 = x2
64 self.y2 = y2
65 self.z2 = z2
66
67 def start(self):
68 return PointXYZ(self.x, self.y, self.z)
69
70 def end(self):
71 return PointXYZ(self.x2, self.y2, self.z2)
72
73 def size(self):
74 return Block(self.x2 - self.x + 1, self.y2 - self.y + 1, self.z2 - self.z + 1)
75
76 def __repr__(self):
77 return "<Rect: ({0},{1},{2}) ({3},{4},{5})>".format(self.x, self.y, self.z, self.x2, self.y2, self.z2)
78
79
80class Kernel:
81 def __init__(self, w, h, sx=1, sy=1, dx=1, dy=1):
82 assert sx > 0 and sy > 0
83 assert dx > 0 and dy > 0
84 self.width = w
85 self.height = h
86 self.stride = PointXY(sx, sy)
87 self.dilation = PointXY(dx, dy)
88
89
90class SHRAMElements:
91 IFM8 = 0
92 IFM16 = 1
93 IFM8_Elementwise = 2
94 IFM16_Elementwise = 3
95 Acc16 = 4
96 Acc32 = 5
97 Acc40 = 6
98 Last = Acc40
99 BitSizes = np.array([8, 16, 8, 16, 16, 32, 40], np.int32)
Louis Verhaardf98c6742020-05-12 14:22:38 +0200100 ByteSizes = BitSizes // 8
101 PostAlign = np.array([8, 8, 8, 8, 1, 1, 1], np.int32)
102 PreAlign = np.array([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
112# Area indices must match Ethos-U55 SHRAM layout spec
113class SharedBufferArea(enum.IntEnum):
114 OFM = 0
115 Weights = 1
116 IFM = 2
117 Accumulators = 3
118 Size = Accumulators + 1
119
120
121class ArchitectureFeatures:
122 """This class is a container for various parameters of the Ethos-U55 core
123and system configuration that can be tuned, either by command line
124parameters or by the Ethos-U55 architects. The class is often passed
125around to passes that need to do architecture-dependent actions.
126
127Note the difference between ArchitectureFeatures and CompilerOptions
128- ArchitectureFeatures is for changing the Ethos-U55 and system architecture
129- CompilerOptions is for changing the behaviour of the compiler
130
131"""
132
133 ArchitectureConfig = namedtuple(
134 "ArchitectureConfig", "macs cores ofm_ublock ifm_ublock shram_banks shram_granules elem_units"
135 )
136 accelerator_configs = {
137 "ethos-u55-256": ArchitectureConfig(256, 1, Block(2, 2, 8), Block(2, 2, 8), 48, [8, 8, 8, 8, 8, 16, 20], 8),
138 "ethos-u55-128": ArchitectureConfig(128, 1, Block(2, 1, 8), Block(2, 2, 8), 24, [4, 4, 4, 4, 4, 8, 12], 4),
139 "ethos-u55-64": ArchitectureConfig(64, 1, Block(1, 1, 8), Block(1, 1, 8), 16, [2, 2, 2, 2, 4, 4, 8], 2),
140 "ethos-u55-32": ArchitectureConfig(32, 1, Block(1, 1, 4), Block(1, 1, 8), 16, [2, 2, 2, 2, 4, 4, 4], 1),
141 }
142
143 OFMSplitDepth = 16
144
145 def __init__(
146 self,
147 vela_config: ConfigParser,
148 accelerator_config,
149 system_config,
150 permanent_storage,
151 inter_pass_cycle_delay,
152 dram_bandwidth,
153 override_block_config,
154 block_config_limit,
155 global_memory_clock_scale,
156 max_blockdep,
157 ):
158 accelerator_config = accelerator_config.lower()
159 self.vela_config = vela_config
160 self.accelerator_config = accelerator_config
Diego Russoea6111a2020-04-14 18:41:58 +0100161 if self.accelerator_config not in ArchitectureFeatures.accelerator_configs:
Louis Verhaard7db78962020-05-25 15:05:26 +0200162 raise OptionError("--accelerator-config", self.accelerator_config, "Unknown accelerator configuration")
Tim Hall79d07d22020-04-27 18:20:16 +0100163 accel_config = ArchitectureFeatures.accelerator_configs[self.accelerator_config]
164 self.config = accel_config
165
166 self.system_config = system_config
167
168 is_yoda_system = "yoda-" in self.accelerator_config
169
170 if is_yoda_system:
171 self.sram_size = 256 * 1024
172 else:
173 self.sram_size = 200 * 1024 * 1024
174
175 self.ncores = accel_config.cores
176 self.ofm_ublock = accel_config.ofm_ublock
177 self.ifm_ublock = accel_config.ifm_ublock
178 self.subkernel_max = Block(8, 8, 65536)
179 self.ofm_block_max = Block(64, 32, 128)
180 self.override_block_config = override_block_config
181 self.block_config_limit = block_config_limit
182
183 self.global_memory_clock_scale = global_memory_clock_scale
184 if self.global_memory_clock_scale <= 0.0 or self.global_memory_clock_scale > 1.0:
185 raise Exception(
186 "Invalid global_memory_clock_scale = "
187 + str(self.global_memory_clock_scale)
188 + " (must be > 0.0 and <= 1.0)"
189 )
190
191 self.max_blockdep = max_blockdep
192
193 dpu_min_height = accel_config.ofm_ublock.height
194 dpu_min_width = accel_config.ofm_ublock.width
195 dpu_dot_product_width = 8
196 dpu_min_ofm_channels = accel_config.ofm_ublock.depth
197
198 self.num_elem_wise_units = accel_config.elem_units
199 self.num_macs_per_cycle = dpu_min_height * dpu_min_width * dpu_dot_product_width * dpu_min_ofm_channels
200
201 self.memory_clock_scales = np.zeros(MemArea.Size)
202 self.memory_port_widths = np.zeros(MemArea.Size)
203
204 # Get system configuration
205 self.__read_sys_config()
206
207 # apply the global memory clock scales to the individual ones from the system config
208 for mem in MemArea.all():
209 self.memory_clock_scales[mem] *= self.global_memory_clock_scale
210
211 self.memory_clocks = self.memory_clock_scales * self.npu_clock
212 self.memory_bandwidths_per_cycle = self.memory_port_widths * self.memory_clock_scales / 8
213
214 if dram_bandwidth != 0:
215 self.memory_bandwidths_per_cycle[MemArea.Dram] = dram_bandwidth * 1e9 / self.npu_clock
216
217 self.memory_bandwidths_per_second = self.memory_bandwidths_per_cycle * self.npu_clock
218
219 # sizes as N x H x W x C. we need to round up to these when allocating storage
220 self.storage_rounding_quantums = {
221 TensorFormat.Unknown: (1, 1, 1, 1),
222 TensorFormat.WeightsCompressed: (1, 1, 1, 1),
223 TensorFormat.NHWC: (1, 1, 1, 1),
224 TensorFormat.NHCWB16: (1, 1, 1, 16),
225 }
226
227 # brick sizes as N x H x W x C. We have to fetch whole bricks at a time
228 self.brick_sizes = {
229 TensorFormat.Unknown: (1, 1, 1, 1),
230 TensorFormat.WeightsCompressed: (1, 1, 1, 1),
231 TensorFormat.NHWC: (1, 1, 1, 1),
232 TensorFormat.NHCWB16: (1, 1, 1, 16),
233 }
234
235 self.inter_pass_cycle_delay = inter_pass_cycle_delay
236
237 self.default_weight_format = TensorFormat.WeightsCompressed
238 self.default_feature_map_format = TensorFormat.NHWC
239
240 if permanent_storage != MemArea.OffChipFlash:
241 self.permanent_storage_mem_area = permanent_storage
242
243 self.tensor_storage_mem_area = {
244 # permanent mem_area
245 TensorPurpose.Weights: self.permanent_storage_mem_area,
246 TensorPurpose.FeatureMap: self.feature_map_storage_mem_area,
247 }
248
249 self.tensor_load_mem_area = dict(self.tensor_storage_mem_area)
250
251 if self.tensor_storage_mem_area[TensorPurpose.Weights] in (MemArea.OffChipFlash,):
252 self.tensor_load_mem_area[TensorPurpose.Weights] = MemArea.Sram
253
254 self.min_block_sizes = {
255 NpuBlockType.Default: (dpu_min_height, dpu_min_width),
256 NpuBlockType.VectorProduct: (1, 1),
257 NpuBlockType.ConvolutionMxN: (dpu_min_height, dpu_min_width),
258 NpuBlockType.Pooling: (dpu_min_height, dpu_min_width),
259 NpuBlockType.ConvolutionDepthWise: (dpu_min_height, dpu_min_width),
260 NpuBlockType.ElementWise: (1, 1),
261 }
262
263 self.sub_kernel_limits = {
264 NpuBlockType.Default: (8, 8),
265 NpuBlockType.VectorProduct: (1, 1),
266 NpuBlockType.ConvolutionMxN: (8, 8),
267 NpuBlockType.Pooling: (8, 8),
268 NpuBlockType.ConvolutionDepthWise: (8, 8),
269 NpuBlockType.ElementWise: (1, 1),
270 }
271
272 # weights for scheduler search
273 from .npu_performance import make_bandwidth_array
274
275 self.bandwidth_weights = make_bandwidth_array()
276 self.bandwidth_weights[MemArea.Sram] = 1.0
277 self.bandwidth_weights[MemArea.Dram] = 10.0
278 self.bandwidth_weights[MemArea.OnChipFlash] = 2.0
279 self.bandwidth_weights[MemArea.OffChipFlash] = 20.0
280 self.cycles_weight = 40
281 self.max_sram_used_weight = 1000
282
283 if is_yoda_system:
284 self.max_sram_used_weight = 0
285
286 # Shared Buffer Block allocations
287 self.shram_bank_size = 1024 # bytes
288 self.shram_size_bytes = accel_config.shram_banks * self.shram_bank_size
289 self.shram_reserved_output_banks = 2
290 self.shram_reserved_weight_banks = 0
291 self.shram_reserved_unused_banks = 2 if accel_config.shram_banks > 16 else 0
292 self.shram_total_banks = accel_config.shram_banks - self.shram_reserved_unused_banks
293 self.shram_bank_granules = np.array(accel_config.shram_granules, np.int32)
294
295 # Build a map of acceptable IFM/OFM block configurations up to the maximum
296 # IFM/OFM block size.
297 ifm_block_max = self.get_ifm_block_size(32, self.ofm_block_max, Kernel(8, 8))
298 self.block_config_map = dict()
299 self.generate_block_config_map(Block(ifm_block_max.width, ifm_block_max.height, 128))
300
301 # Setup supported operators and restriction checkers class
302 self.supported_operators = SupportedOperators()
303
304 # Calculate block configuration for ALL known IFM operations and
305 # accumulator sizes. Consumers will need to select their preferred
306 # operation and bit-width at read-time.
307 def generate_block_config(self, width, height, depth):
Louis Verhaardf98c6742020-05-12 14:22:38 +0200308 # Number of bytes required for any SHRAM element for a FM of given dimensions.
309 # For IFM: size = H*W*Align(D*BYTE_WIDTH, 8)
310 # For ACC: size = H*W*Align(D,8)*BYTE_WIDTH
311 d1 = round_up(depth, SHRAMElements.PreAlign)
312 d2 = round_up(d1 * SHRAMElements.ByteSizes, SHRAMElements.PostAlign)
313 size_bytes = (height * width) * d2
314
Tim Hall79d07d22020-04-27 18:20:16 +0100315 # Convert byte size (rounded) to size in banks
316 size_banks = round_up_divide(size_bytes, self.shram_bank_size)
317 size_banks *= 2 # Double buffer the IFM/Acc (need twice as many banks)
318 # Round bank requirement to bank granularity
319 required_banks = round_up(size_banks, self.shram_bank_granules)
320 return SHRAMBlockConfig(size_bytes, required_banks)
321
322 @staticmethod
323 def make_block_config_key(width, height, depth):
324 return (int(height), int(width), int(depth))
325
326 def get_block_config(self, width, height, depth):
327 assert depth <= self.ofm_block_max.depth
328 key = ArchitectureFeatures.make_block_config_key(width, height, depth)
329 config = self.block_config_map.get(key, None)
330 return config
331
332 # Generate a key:value map of possible block configurations, where the
333 # key is compounded from the block dimensions: 0x00HHWWCC
334 def generate_block_config_map(self, block: Block):
335 for h in range(1, block.height + 1):
336 for w in range(1, block.width + 1):
337 # All possible IFM/OFM depth values
338 for c in [4, 8, 12, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128]:
339 key = ArchitectureFeatures.make_block_config_key(w, h, c)
340 self.block_config_map[key] = self.generate_block_config(w, h, c)
341
342 def calc_ifm_block_depth(self, ifm_depth, ifm_bits):
343 assert ifm_bits == 8 or ifm_bits == 16
344 assert ifm_depth > 0
345 ifm_depth = round_up(ifm_depth, self.ifm_ublock.depth)
346 max_block_depth = 32 if ifm_bits == 8 else 16
347 return min(max_block_depth, ifm_depth)
348
349 # Calculate the size of the IFM block given a depth, target OFM block and a kernel
350 def get_ifm_block_size(
351 self, ifm_block_depth, ofm_block: Block, kernel: Kernel, subkernel: Block = Block(8, 8, 65536)
352 ):
353 upscaling = 1
354 # Height
355 ifm_odd_2x_height_enable = 0
356 dilated_kernel_height = ((kernel.height - 1) * kernel.dilation.y) + 1
357 ifm_block_height = (
358 (ofm_block.height - 1) * kernel.stride.y
359 + min(subkernel.height, dilated_kernel_height)
360 + ifm_odd_2x_height_enable
361 ) // upscaling
362
Dwight Lidman0538a772020-05-06 14:09:17 +0200363 ifm_block_height = round_up(ifm_block_height, self.ofm_ublock.height)
Tim Hall79d07d22020-04-27 18:20:16 +0100364
365 # Width
366 ifm_odd_2x_width_enable = 0
367 dilated_kernel_width = ((kernel.width - 1) * kernel.dilation.x) + 1
368 ifm_block_width = (
369 (ofm_block.width - 1) * kernel.stride.x
370 + min(subkernel.width, dilated_kernel_width)
371 + ifm_odd_2x_width_enable
372 ) // upscaling
373
Dwight Lidman0538a772020-05-06 14:09:17 +0200374 ifm_block_width = round_up(ifm_block_width, self.ofm_ublock.width)
Tim Hall79d07d22020-04-27 18:20:16 +0100375
376 return Block(ifm_block_width, ifm_block_height, ifm_block_depth)
377
378 @staticmethod
379 def intersects(start_a, end_a, start_b, end_b):
380 start_x = max(start_a[0], start_b[0])
381 end_x = min(end_a[0], end_b[0])
382 start_y = max(start_a[1], start_b[1])
383 end_y = min(end_a[1], end_b[1])
384 start_z = max(start_a[2], start_b[2])
385 end_z = min(end_a[2], end_b[2])
386 return ((end_x - start_x) > 0) and ((end_y - start_y) > 0) and ((end_z - start_z) > 0)
387
388 # Block job dependency:
389 # Does the VOLUME of IFMs for block job B(0) overlap with VOLUME of OFMs block jobs A(8,9,10)
390 #
391 # A | B
392 # ----------------------+------------------
393 # .... 3,4,5,6,7,8,9,10 | 0,1,2,3,4,5,6,8 10 < JOB NUMBER
394 # |<------->| dependency offset
395 #
396 MAX_BLOCKDEP = 3
397
398 # Get the coordinates of a block offset from either the end (negative)
399 # or the start (zero or positive) of the given 3d area
400 def get_offset_block_coords(self, area: Rect, block: Block, offset):
401 size = area.size()
402 # Dimensions of the region, in blocks
403 width_blocks = round_up_divide(size.width, block.width)
404 height_blocks = round_up_divide(size.height, block.height)
405 depth_blocks = round_up_divide(size.depth, block.depth)
406 total_blocks = width_blocks * height_blocks * depth_blocks
407 if offset < 0:
408 index = total_blocks + offset
409 else:
410 index = offset
411
412 if index >= total_blocks:
413 return None
414
415 # Coordinates of the indexed block
416 coord_z = block.depth * (index % depth_blocks)
417 coord_y = block.height * (index // (depth_blocks * width_blocks))
418 coord_x = block.width * ((index // depth_blocks) % width_blocks)
419
420 return (coord_x + area.x, coord_y + area.y, coord_z + area.z)
421
422 def get_first_job_input_volume(
423 self, ifm: Rect, ofm: Rect, ifm_block_depth, ofm_block: Block, kernel: Kernel, padLT, block_offset
424 ):
425 # Get ifm block size (jobs are invisibly decomposed into subkernels)
426 ifm_block = self.get_ifm_block_size(ifm_block_depth, ofm_block, kernel, self.ofm_block_max)
427 ifm_depth_blocks = round_up_divide(ifm.size().depth, ifm_block_depth)
428
429 # Which OFM block are we calculating
430 ofm_coord = self.get_offset_block_coords(ofm, ofm_block, block_offset // ifm_depth_blocks)
431 if ofm_coord is None:
432 return None
433
434 # Coordinate of the source IFM block
435 ifm_coord_x = max(0, ofm_coord[0] * kernel.stride.x - padLT[0])
436 ifm_coord_y = max(0, ofm_coord[1] * kernel.stride.y - padLT[1])
437 ifm_coord_z = ifm.z + (block_offset % ifm_depth_blocks) * ifm_block.depth
438
439 # IFM block that will be sampled for the FIRST+block_offset job in the next operator's OFM
440 start_coord = (ifm_coord_x, ifm_coord_y, ifm_coord_z)
441 end_coord = (
442 start_coord[0] + ifm_block.width,
443 start_coord[1] + ifm_block.height,
444 start_coord[2] + ifm_block.depth,
445 )
446
447 return (start_coord, end_coord, 1) # start, end, total jobs
448
449 def get_prev_job_output_volume(
450 self, ifm: Block, ofm: Rect, ifm_block_depth, ofm_block: Block, kernel: Kernel, block_offset
451 ):
452 assert block_offset >= 0
453
454 # Get OFM block's volume coordinates
455 start_coord = self.get_offset_block_coords(ofm, ofm_block, -1 - block_offset)
456 if start_coord is None:
457 return None
458 end_coord = (
459 start_coord[0] + ofm_block.width,
460 start_coord[1] + ofm_block.height,
461 start_coord[2] + ofm_block.depth,
462 )
463
464 # Calculate how many IFM blocks this OFM block requires (i.e how many jobs)
Tim Hall79d07d22020-04-27 18:20:16 +0100465 ifm_depth_blocks = round_up_divide(ifm.size().depth, ifm_block_depth)
466 ifm_depth_blocks = 1 # Overwrite with 1 to force OFM block dependency, not IFM
467
468 return (start_coord, end_coord, ifm_depth_blocks) # start, end, total jobs for this OFM block
469
470 def calc_block_dep(
471 self,
472 prev_ifm: Block,
473 prev_ofm: Block,
474 prev_ifm_block_depth,
475 prev_ofm_block: Block,
476 prev_kernel: Kernel,
477 ifm: Block,
478 ofm: Block,
479 ifm_block_depth,
480 ofm_block: Block,
481 kernel: Kernel,
482 padLT,
483 ):
484
485 blockdep = ArchitectureFeatures.MAX_BLOCKDEP
486
487 # Iterate over the next BLOCKDEP inputs, checking to see if a sliding window
488 # of IFM area overlaps with any previous OFM block generation.
489 elapsed_jobs = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100490 for forward_offset in range(ArchitectureFeatures.MAX_BLOCKDEP):
491 # This is the IFM block we want to sample from
492 in_area = self.get_first_job_input_volume(
493 ifm, ofm, ifm_block_depth, ofm_block, kernel, padLT, forward_offset
494 )
495 if in_area is None:
496 break
497
498 # Try several previous-OFM blocks in the past (they still might comprise multiple IFM jobs)
499 outstanding_jobs = 0
500 for block_offset in range(ArchitectureFeatures.MAX_BLOCKDEP):
501 # This is the OFM block being generated by the previous op
502 out_area = self.get_prev_job_output_volume(
503 prev_ifm, prev_ofm, prev_ifm_block_depth, prev_ofm_block, prev_kernel, block_offset
504 )
505 if out_area is None:
506 break
507
508 # Block dependency is the max number of allowed outstanding jobs
509 # in the pipeline. Selected by determining how many jobs occur
510 # in between two operators' overlapping OFM->IFM block volumes
511 if ArchitectureFeatures.intersects(in_area[0], in_area[1], out_area[0], out_area[1]):
512 break
513 # Early exit if no intersections and we've seen enough jobs in the pipeline
514 elif outstanding_jobs > ArchitectureFeatures.MAX_BLOCKDEP:
515 break
516
517 # This OFM had this many jobs (accumulate over multiple OFM blocks)
518 outstanding_jobs += out_area[2]
519
520 blockdep = min(blockdep, elapsed_jobs + outstanding_jobs)
521 elapsed_jobs += in_area[2]
522 # Early exit if no intersections and we've seen enough jobs in the pipeline
523 if elapsed_jobs > ArchitectureFeatures.MAX_BLOCKDEP:
524 break
525
526 return blockdep
527
528 def cpu_cycle_estimate(self, op):
529 """
530 Gets estimated performance of a CPU operation, based on a linear model of intercept, slope,
531 specified in the vela config file, in ConfigParser file format (.ini file).
532 Example configuration snippet:
533 [CpuPerformance.MyOperationType]
534 Cortex-Mx.intercept=<some float value>
535 Cortex-Mx.slope=<some float value>
536 """
537 section = "CpuPerformance." + op.type
538 if self.vela_config is not None and section in self.vela_config:
539 op_config = self.vela_config[section]
540 try:
541 intercept = float(op_config.get(self.cpu_config + ".intercept", op_config["default.intercept"]))
542 slope = float(op_config.get(self.cpu_config + ".slope", op_config["default.slope"]))
543 n_elements = op.inputs[0].elements()
544 cycles = intercept + n_elements * slope
545 return cycles
Diego Russoea6111a2020-04-14 18:41:58 +0100546 except Exception:
Tim Hall79d07d22020-04-27 18:20:16 +0100547 print("Error: Reading CPU cycle estimate in vela configuration file, section {}".format(section))
548 raise
549
550 print("Warning: No configured CPU performance estimate for", op.type)
551 return 0
552
553 def __read_sys_config(self):
554 """
555 Gets the system configuration with the given name from the vela configuration file
556 Example configuration snippet:
557 [SysConfig.MyConfigName]
558 npu_freq=<some float value>
559 cpu=Cortex-Mx
560 ...
561 """
562 # Get system configuration from the vela configuration file
563 if self.vela_config is None:
564 print("Warning: Using default values for system configuration")
565 else:
566 section_key = "SysConfig." + self.system_config
Diego Russoea6111a2020-04-14 18:41:58 +0100567 if section_key not in self.vela_config:
Louis Verhaard7db78962020-05-25 15:05:26 +0200568 raise OptionError("--system-config", self.system_config, "Unknown system configuration")
Tim Hall79d07d22020-04-27 18:20:16 +0100569
570 try:
571 self.npu_clock = float(self.__sys_config("npu_freq", "500e6"))
572 self.cpu_config = self.__sys_config("cpu", "Cortex-M7")
573
574 self.memory_clock_scales[MemArea.Sram] = float(self.__sys_config("Sram_clock_scale", "1"))
575 self.memory_port_widths[MemArea.Sram] = int(self.__sys_config("Sram_port_width", "64"))
576
577 self.memory_clock_scales[MemArea.OnChipFlash] = float(self.__sys_config("OnChipFlash_clock_scale", "1"))
578 self.memory_port_widths[MemArea.OnChipFlash] = int(self.__sys_config("OnChipFlash_port_width", "64"))
579
580 self.memory_clock_scales[MemArea.OffChipFlash] = float(
581 self.__sys_config("OffChipFlash_clock_scale", "0.25")
582 )
583 self.memory_port_widths[MemArea.OffChipFlash] = int(self.__sys_config("OffChipFlash_port_width", "32"))
584
585 self.memory_clock_scales[MemArea.Dram] = float(self.__sys_config("Dram_clock_scale", "1"))
586 self.memory_port_widths[MemArea.Dram] = int(self.__sys_config("Dram_port_width", "32"))
587
588 self.fast_storage_mem_area = MemArea[self.__sys_config("fast_storage_mem_area", "Sram")]
589 self.feature_map_storage_mem_area = MemArea[self.__sys_config("feature_map_storage_mem_area", "Sram")]
590 self.permanent_storage_mem_area = MemArea[self.__sys_config("permanent_storage_mem_area", "OffChipFlash")]
591 if self.permanent_storage_mem_area not in set((MemArea.OnChipFlash, MemArea.OffChipFlash)):
592 raise Exception(
593 "Invalid permanent_storage_mem_area = "
594 + str(self.permanent_storage_mem_area)
595 + " (must be 'OnChipFlash' or 'OffChipFlash'). To store the weights and other constant data in SRAM"
596 " select 'OnChipFlash'"
597 )
Diego Russoea6111a2020-04-14 18:41:58 +0100598 except Exception:
Tim Hall79d07d22020-04-27 18:20:16 +0100599 print("Error: Reading System Configuration in vela configuration file, section {}".format(section_key))
600 raise
601
602 def __sys_config(self, key, default_value):
603 """
604 Gets the system configuration value with the given key from the vela config file.
605 """
606 if self.vela_config is None:
607 return default_value
608 section = "SysConfig." + self.system_config
609 result = self.vela_config[section].get(key, None)
610 if result is None:
611 raise Exception("Error: System Configuration Missing key {} in section [{}] ".format(key, section))
612 return result