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