blob: b7607e6dcdd8ce92c7caf22baf16deab1acd7c87 [file] [log] [blame]
erik.andersson@arm.com460c6892021-02-24 14:38:09 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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# NPU performance estimation functions to estimate performance of a Pass and CascadedPass. Uses a model that takes the
18# maximum of the 'cycles required for bandwidth' and 'cycles required for computing'.
19#
20# Called during scheduling to evaluate different proposals, as well as post-scheduling to provide a final performance
21# estimate.
Tim Halld8339a72021-05-27 18:49:40 +010022import copy
Diqing Zhonge168b962020-11-05 17:18:47 +010023from enum import auto
24from enum import IntEnum
Jonas Ohlsson845e2322022-03-01 12:39:55 +010025from typing import Optional
Ayaan Masoodb801dda2022-02-22 11:28:55 +000026from typing import Set
27from uuid import UUID
Diego Russoea6111a2020-04-14 18:41:58 +010028
Tim Hall79d07d22020-04-27 18:20:16 +010029import numpy as np
Diego Russoea6111a2020-04-14 18:41:58 +010030
31from . import numeric_util
Tim Halld8339a72021-05-27 18:49:40 +010032from .architecture_allocator import ArchitectureBlockConfig
Diqing Zhong09387e22020-09-28 18:46:22 +020033from .architecture_features import Accelerator
Tim Hallc1be0872022-03-03 17:50:52 +000034from .architecture_features import ArchitectureFeatures
Tim Halld8339a72021-05-27 18:49:40 +010035from .architecture_features import NpuBlockType
36from .architecture_features import SHRAMElements
37from .architecture_features import TensorFormat
Tim Hallc1be0872022-03-03 17:50:52 +000038from .debug_database import DebugDatabase
Ayaan Masoodb801dda2022-02-22 11:28:55 +000039from .nn_graph import Graph
Tim Hallc1be0872022-03-03 17:50:52 +000040from .nn_graph import NetworkType
41from .nn_graph import PassPlacement
Tim Halld8339a72021-05-27 18:49:40 +010042from .numeric_util import round_up
Johan Alfvénf8e353b2022-02-04 17:24:23 +010043from .numeric_util import round_up_to_int
Tim Halld8339a72021-05-27 18:49:40 +010044from .operation import Kernel
Diqing Zhonge8887a32020-09-24 09:53:48 +020045from .operation import Op
Tim Halld8339a72021-05-27 18:49:40 +010046from .scheduler import Schedule
47from .scheduler import SchedulerOperation
Ayaan Masoodb801dda2022-02-22 11:28:55 +000048from .scheduler import SchedulerOpInfo
Tim Halld8339a72021-05-27 18:49:40 +010049from .shape4d import Shape4D
Diqing Zhongf842b692020-12-11 13:07:37 +010050from .tensor import BandwidthDirection
Diego Russoe8a10452020-04-21 17:39:10 +010051from .tensor import MemArea
Diego Russoe8a10452020-04-21 17:39:10 +010052from .tensor import TensorPurpose
Tim Hallc1be0872022-03-03 17:50:52 +000053from .tflite_mapping import optype_to_builtintype as tflite_optype_to_builtintype
54from .tosa_mapping import optype_to_tosa_op_type as tosa_optype_to_tosa_op_type
Tim Halld8339a72021-05-27 18:49:40 +010055from .weight_compressor import WeightKey
Tim Hall79d07d22020-04-27 18:20:16 +010056
57
Diqing Zhonge168b962020-11-05 17:18:47 +010058class PassCycles(IntEnum):
Diqing Zhong42e833d2020-10-02 13:18:42 +020059 Npu = 0
Diqing Zhonge168b962020-11-05 17:18:47 +010060 SramAccess = auto()
61 DramAccess = auto()
62 OnChipFlashAccess = auto()
63 OffChipFlashAccess = auto()
64 Total = auto()
65 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +010066
67 def display_name(self):
Jonas Ohlssond8575072022-03-30 10:30:25 +020068 return (
69 "NPU",
70 "SRAM Access",
71 "DRAM Access",
72 "On-chip Flash Access",
73 "Off-chip Flash Access",
74 "Total",
75 "Size",
76 )[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010077
78 def identifier_name(self):
Jonas Ohlssond8575072022-03-30 10:30:25 +020079 return (
80 "npu",
81 "sram_access",
82 "dram_access",
83 "on_chip_flash_access",
84 "off_chip_flash_access",
85 "total",
86 "size",
87 )[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010088
89 @staticmethod
90 def all():
91 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020092 PassCycles.Npu,
Tim Hall79d07d22020-04-27 18:20:16 +010093 PassCycles.SramAccess,
94 PassCycles.DramAccess,
95 PassCycles.OnChipFlashAccess,
96 PassCycles.OffChipFlashAccess,
97 PassCycles.Total,
98 )
99
100
Tim Halld8339a72021-05-27 18:49:40 +0100101class PerformanceQuery:
102 def __init__(self, npu_block_type=0):
103 self.npu_block_type = npu_block_type
104 self.ifm_shape = Shape4D(0)
105 self.ifm_format = TensorFormat.NHWC
106 self.ifm_memory_area = MemArea.Unknown
107 self.ifm2_memory_area = MemArea.Unknown
108 self.ifm_bits = 0
109 self.ifm2_bits = 0
110 self.ifm2_shape = None
111 self.ifm2_format = TensorFormat.NHWC
112 self.ofm_shape = Shape4D(0)
113 self.ofm_format = TensorFormat.NHWC
114 self.ofm_memory_area = MemArea.Unknown
115 self.ofm_bits = 0
116 self.const_shape = Shape4D(0)
117 self.const_memory_area = MemArea.Unknown
118 self.kernel = Kernel(1, 1)
119 self.config = ArchitectureBlockConfig()
Tim Hall79d07d22020-04-27 18:20:16 +0100120
121
Tim Halld8339a72021-05-27 18:49:40 +0100122class CycleCost:
123 def __init__(self):
124 self.op_macs = 0
125 self.op_cycles = 0
126
127 def __mul__(self, scale):
128 out = CycleCost()
129 out.op_macs = self.op_macs * scale
130 out.op_cycles = self.op_cycles * scale
131 return out
132
133 def __iadd__(self, rhs):
134 self.op_macs += rhs.op_macs
135 self.op_cycles += rhs.op_cycles
136 return self
137
138 def __str__(self):
139 return "macs = {}, cycles = {}".format(self.op_macs, self.op_cycles)
Tim Hall79d07d22020-04-27 18:20:16 +0100140
141
Tim Halld8339a72021-05-27 18:49:40 +0100142class ElementAccess:
143 def __init__(self):
144 # List of ONLY element access counts, consumers
145 # need to scale these values by the correct bitwidths
146 # to calculated memory bandwidth
147 self.ifm_read = [0, 0] # ifm1, ifm2
148 self.ofm_write = 0
149 self.weights_refetch = 0
150 self.const_read = [0, 0] # weights, scales
151
152 def __mul__(self, scale):
153 out = ElementAccess()
154 out.ifm_read[0] = self.ifm_read[0] * scale
155 out.ifm_read[1] = self.ifm_read[1] * scale
156 out.ofm_write = self.ofm_write * scale
157 out.weights_refetch = self.weights_refetch * scale
158 out.const_read[0] = self.const_read[0] * scale
159 out.const_read[1] = self.const_read[1] * scale
160 return out
161
162 def __iadd__(self, rhs):
163 self.ifm_read[0] += rhs.ifm_read[0]
164 self.ifm_read[1] += rhs.ifm_read[1]
165 self.ofm_write += rhs.ofm_write
166 self.weights_refetch += rhs.weights_refetch
167 self.const_read[0] += rhs.const_read[0]
168 self.const_read[1] += rhs.const_read[1]
169 return self
170
171 def __str__(self):
172 return "ifm read = {}, ofm write = {}, const read={}".format(self.ifm_read, self.ofm_write, self.const_read)
Tim Hall79d07d22020-04-27 18:20:16 +0100173
174
Tim Halld8339a72021-05-27 18:49:40 +0100175def _strides_for_shape(shape: Shape4D, format: TensorFormat, element_bits):
176 if format == TensorFormat.NHWC:
177 strides = [0, 0, 0, 0]
178 strides[3] = element_bits / 8 # +Z
179 strides[2] = (element_bits * shape.depth) // 8 # +X
180 strides[1] = (element_bits * shape.depth * shape.width) // 8 # +Y
181 strides[0] = (element_bits * shape.depth * shape.width * shape.height) // 8 # +N
182 elif format == TensorFormat.NHCWB16:
183 strides = [0, 0, 0, 0, 0]
184 strides[4] = element_bits / 8 # +Z
185 strides[3] = (element_bits * 16) / 8 # +X
186 strides[2] = (element_bits * 16 * shape.width) / 8 # +C
187 strides[1] = (element_bits * shape.width * shape.depth) / 8 # +Y
188 strides[0] = (element_bits * shape.width * shape.depth) / 8 # +N
Diqing Zhong42e833d2020-10-02 13:18:42 +0200189
Tim Halld8339a72021-05-27 18:49:40 +0100190 return strides
Diqing Zhong42e833d2020-10-02 13:18:42 +0200191
192
Tim Halld8339a72021-05-27 18:49:40 +0100193def _estimate_memory_transfer_efficiency(
194 arch, is_read, mem_area, format: TensorFormat, element_bits, block_size, shape4D, to_transfer
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100195):
Tim Halld8339a72021-05-27 18:49:40 +0100196 burst_len = 8
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100197
Tim Halld8339a72021-05-27 18:49:40 +0100198 strides = _strides_for_shape(shape4D, format, element_bits)
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100199
Tim Halld8339a72021-05-27 18:49:40 +0100200 if format == TensorFormat.NHCWB16:
201 if strides[2] == block_size.depth: # TODO is this check corrrect for non 8-bit
202 burst_len = element_bits * block_size.depth * block_size.width
203 elif is_read:
204 burst_len = 16 * element_bits * block_size.width
Diqing Zhonge8887a32020-09-24 09:53:48 +0200205 else:
Tim Halld8339a72021-05-27 18:49:40 +0100206 burst_len = 16 * element_bits * block_size.width * arch.ncores
207 elif format == TensorFormat.NHWC:
208 if is_read:
209 if strides[3] == block_size.depth:
210 burst_len = element_bits * block_size.depth * block_size.width
211 else:
212 burst_len = element_bits * block_size.depth
213 else:
214 if block_size.depth <= 16 and strides[3] == block_size.depth:
215 burst_len = element_bits * block_size.depth * block_size.width
216 else:
217 burst_len = min(64 * 8, 16 * element_bits * arch.ncores, block_size.depth * element_bits)
218
219 burst_len = burst_len // 8 # bits->bytes
220 burst_len = min(arch.memory_burst_length[mem_area], burst_len)
221 return to_transfer * (arch.memory_burst_length[mem_area] / burst_len)
222
223
224def _estimate_minimum_memory_cycles(arch, query: PerformanceQuery):
225 # Input block HW transfer (only for elements present)
226 ifm_bytes = Shape4D.min(query.ifm_shape, query.config.ifm_block).elements()
227 cycles_ifm_blk = arch.memory_latency[query.ifm_memory_area][BandwidthDirection.Read]
228 cycles_ifm_blk = cycles_ifm_blk + (
229 _estimate_memory_transfer_efficiency(
230 arch,
231 True,
232 query.ifm_memory_area,
233 query.ifm_format,
234 query.ifm_bits,
235 query.config.ifm_block,
236 query.ifm_shape,
237 ifm_bytes,
238 )
239 / arch.memory_bandwidths_per_cycle[query.ifm_memory_area]
240 )
241 # Output block HW transfer (only for elements present)
242 ofm_bytes = Shape4D.min(query.ofm_shape, query.config.ofm_block).elements()
243 cycles_ofm_blk = arch.memory_latency[query.ofm_memory_area][BandwidthDirection.Write]
244 cycles_ofm_blk = cycles_ofm_blk + (
245 _estimate_memory_transfer_efficiency(
246 arch,
247 False,
248 query.ofm_memory_area,
249 query.ofm_format,
250 query.ofm_bits,
251 query.config.ofm_block,
252 query.ofm_shape,
253 ofm_bytes,
254 )
255 / arch.memory_bandwidths_per_cycle[query.ofm_memory_area]
256 )
257 return cycles_ifm_blk, cycles_ofm_blk
258
259
260def _estimate_output_cycles_per_element(arch, op_type: Op, faf_type: Op, query: PerformanceQuery):
261 if query.npu_block_type == NpuBlockType.ElementWise and query.ifm_bits == 32:
262 # Unary op else Binary op
263 output_perf_index = 0 if query.ifm2_shape is not None else 1
264 elif op_type == Op.Mul and query.ofm_bits == 32:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200265 output_perf_index = 2
Tim Halld8339a72021-05-27 18:49:40 +0100266 elif op_type == Op.Mul or (
267 query.npu_block_type
Diqing Zhonge8887a32020-09-24 09:53:48 +0200268 in (
269 NpuBlockType.ConvolutionMxN,
270 NpuBlockType.ConvolutionDepthWise,
271 NpuBlockType.Pooling,
272 NpuBlockType.ReduceSum,
273 NpuBlockType.VectorProduct,
274 )
Tim Halld8339a72021-05-27 18:49:40 +0100275 and query.config.acc_type == SHRAMElements.Acc40
Diqing Zhonge8887a32020-09-24 09:53:48 +0200276 ):
277 output_perf_index = 3
Tim Halld8339a72021-05-27 18:49:40 +0100278 elif op_type in (Op.Add, Op.Sub):
279 if False:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200280 # Simple Add/Sub
281 output_perf_index = 4
282 else:
Tim Halld8339a72021-05-27 18:49:40 +0100283 # Advanced Add/Sub TODO: Add as perf selection as operator variant
Diqing Zhonge8887a32020-09-24 09:53:48 +0200284 output_perf_index = 5
Tim Halld8339a72021-05-27 18:49:40 +0100285 elif op_type.is_maxpool_op():
Diqing Zhonge8887a32020-09-24 09:53:48 +0200286 output_perf_index = 6
287 else:
288 output_perf_index = 7
289
Tim Halld8339a72021-05-27 18:49:40 +0100290 if faf_type in (Op.Sigmoid, Op.Tanh, Op.LUT):
Diqing Zhonge8887a32020-09-24 09:53:48 +0200291 activation_perf_index = 0
Tim Halld8339a72021-05-27 18:49:40 +0100292 elif faf_type in (Op.Relu, Op.Relu6, Op.ReluN1To1):
Diqing Zhonge8887a32020-09-24 09:53:48 +0200293 activation_perf_index = 1
294 else:
295 activation_perf_index = 2
296
Diqing Zhonge8887a32020-09-24 09:53:48 +0200297 cycle_per_elem = max(
298 arch.output_cycles_per_elem[output_perf_index], arch.activation_cycles_per_elem[activation_perf_index]
299 )
Diqing Zhong986e3192020-11-16 16:15:56 +0100300
Tim Halld8339a72021-05-27 18:49:40 +0100301 if op_type.is_elementwise_op():
302 num_elems_blk = query.config.ofm_block.elements()
303 ifm_blk_cycles, ofm_blk_cycles = _estimate_minimum_memory_cycles(arch, query)
304 cycle_cmd = ifm_blk_cycles + ofm_blk_cycles
305 cycle_cmd = (cycle_cmd + cycle_per_elem * num_elems_blk) / 4 # per DPU
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100306 cycle_per_elem = max(cycle_per_elem, cycle_cmd / num_elems_blk)
307
Tim Halld8339a72021-05-27 18:49:40 +0100308 return cycle_per_elem
Diqing Zhonge8887a32020-09-24 09:53:48 +0200309
310
Tim Halld8339a72021-05-27 18:49:40 +0100311def _estimate_conv_cycles(arch, op_type: Op, faf_type: Op, query: PerformanceQuery):
312 ifm_block = Shape4D.min(query.ifm_shape, query.config.ifm_block)
313 ofm_block = Shape4D.min(query.ofm_shape, query.config.ofm_block)
Diqing Zhonge5204a62020-10-13 11:42:37 +0200314
315 if (
316 arch.config.ofm_ublock.height == 2
Tim Halld8339a72021-05-27 18:49:40 +0100317 and query.npu_block_type
Diqing Zhonge5204a62020-10-13 11:42:37 +0200318 in (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.VectorProduct)
Tim Halld8339a72021-05-27 18:49:40 +0100319 and query.ofm_shape.height == 1
Diqing Zhonge5204a62020-10-13 11:42:37 +0200320 # Optimisation only applies for even width tensors
Tim Halld8339a72021-05-27 18:49:40 +0100321 and query.ofm_shape.width % 2 == 0
322 and query.kernel.height == 1
Diqing Zhonge5204a62020-10-13 11:42:37 +0200323 ):
Tim Halld8339a72021-05-27 18:49:40 +0100324 ofm_ublock = Shape4D(1, 1, 4, arch.config.ofm_ublock.depth)
325 ofm_block = ofm_block.with_height(1)
326 else:
327 ofm_ublock = Shape4D(arch.config.ofm_ublock.to_hwc())
Diqing Zhonge5204a62020-10-13 11:42:37 +0200328
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100329 num_ublk_x = numeric_util.round_up_divide(ofm_block.width, ofm_ublock.width)
Tim Halld8339a72021-05-27 18:49:40 +0100330 num_ublk_y = numeric_util.round_up_divide(ofm_block.height, ofm_ublock.height)
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100331 num_ublk_xy = num_ublk_x * num_ublk_y
Tim Halld8339a72021-05-27 18:49:40 +0100332 num_ublk_z = numeric_util.round_up_divide(ofm_block.depth, ofm_ublock.depth)
333 use_acc_40bits = query.config.acc_type == SHRAMElements.Acc40
Diqing Zhong09387e22020-09-28 18:46:22 +0200334
Tim Halld8339a72021-05-27 18:49:40 +0100335 sub_kernel_limits = arch.sub_kernel_limits[query.npu_block_type]
336 n_sub_kernels_y = numeric_util.round_up_divide(query.kernel.height, sub_kernel_limits[0])
337 n_sub_kernels_x = numeric_util.round_up_divide(query.kernel.width, sub_kernel_limits[1])
Diqing Zhong09387e22020-09-28 18:46:22 +0200338 sub_kernel_x = [
Tim Halld8339a72021-05-27 18:49:40 +0100339 min((query.kernel.width - i * sub_kernel_limits[1]), sub_kernel_limits[1]) for i in range(n_sub_kernels_x)
Diqing Zhong09387e22020-09-28 18:46:22 +0200340 ]
341 sub_kernel_y = [
Tim Halld8339a72021-05-27 18:49:40 +0100342 min((query.kernel.height - i * sub_kernel_limits[0]), sub_kernel_limits[0]) for i in range(n_sub_kernels_y)
Diqing Zhong09387e22020-09-28 18:46:22 +0200343 ]
344 sub_kernel_size = (x * y for y in sub_kernel_y for x in sub_kernel_x)
345
Diqing Zhong09387e22020-09-28 18:46:22 +0200346 cycles_dpu_blk = 0
Diqing Zhong986e3192020-11-16 16:15:56 +0100347 cycles_wb = 32 * ofm_ublock.depth // 8
Diqing Zhong09387e22020-09-28 18:46:22 +0200348
349 for num_kernel_elems in sub_kernel_size:
Tim Halld8339a72021-05-27 18:49:40 +0100350 if query.npu_block_type == NpuBlockType.Pooling:
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100351 num_kernel_steps = 1
Diqing Zhong986e3192020-11-16 16:15:56 +0100352 cycles = max(4, num_kernel_elems) * num_ublk_xy * num_ublk_z
Tim Halld8339a72021-05-27 18:49:40 +0100353 if query.ifm_bits == 16 and arch.accelerator_config != Accelerator.Ethos_U55_32:
Diqing Zhong09387e22020-09-28 18:46:22 +0200354 cycles *= 2
Tim Halld8339a72021-05-27 18:49:40 +0100355 elif query.npu_block_type == NpuBlockType.ConvolutionDepthWise:
Diqing Zhong986e3192020-11-16 16:15:56 +0100356 cycles = 4 * num_ublk_xy
Tim Halld8339a72021-05-27 18:49:40 +0100357 if query.ifm_bits == 16:
Diqing Zhong09387e22020-09-28 18:46:22 +0200358 cycles *= 2
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100359 num_kernel_steps = numeric_util.round_up_divide(num_kernel_elems, 4)
360 cycles = max(cycles_wb, cycles) * num_kernel_steps * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200361 elif (
Tim Halld8339a72021-05-27 18:49:40 +0100362 (query.npu_block_type == NpuBlockType.ConvolutionMxN and not query.config.is_partkernel)
363 or query.npu_block_type == NpuBlockType.VectorProduct
364 or query.npu_block_type == NpuBlockType.ReduceSum
Diqing Zhong09387e22020-09-28 18:46:22 +0200365 ):
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100366 num_kernel_steps = num_kernel_elems
367 cycles = max(cycles_wb, 4 * num_ublk_xy) * num_kernel_steps * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200368 else:
Tim Halld8339a72021-05-27 18:49:40 +0100369 assert query.config.is_partkernel
370 divider = 2 if query.ifm_bits == 16 else 4
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100371 num_kernel_steps = numeric_util.round_up_divide(num_kernel_elems, divider)
Diqing Zhong986e3192020-11-16 16:15:56 +0100372 cycles = max(cycles_wb, 4 * num_ublk_xy) * (
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100373 num_kernel_steps * numeric_util.round_up_divide(ifm_block.depth, 8) * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200374 )
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100375
376 delay_cycles = 0
377 if arch.accelerator_config is Accelerator.Ethos_U55_32:
378 delay = 7 if use_acc_40bits else 3
379 if num_ublk_x == 1 and num_ublk_y == 1:
380 if num_ublk_z == 1:
381 delay_cycles = delay * num_kernel_steps
382 elif num_kernel_steps > 1:
383 delay_cycles = delay * (num_kernel_steps - 1) * num_ublk_z
384 if (num_ublk_x == 1 or num_ublk_y == 1) and num_ublk_z > 1 and use_acc_40bits:
385 delay_cycles += delay * num_ublk_z
386 else:
Tim Halld8339a72021-05-27 18:49:40 +0100387 if use_acc_40bits and arch.accelerator_config in (Accelerator.Ethos_U55_64, Accelerator.Ethos_U55_128):
388 delay = 3
389 else:
390 delay = 2
391
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100392 if num_ublk_x == 1 and num_ublk_y == 1:
393 if num_ublk_z == 1:
394 delay_cycles = delay * num_kernel_steps
395 elif num_kernel_steps > 1:
396 delay_cycles = delay * (num_kernel_steps - 1) * num_ublk_z
397
Tim Halld8339a72021-05-27 18:49:40 +0100398 if query.npu_block_type == NpuBlockType.ConvolutionMxN and query.config.is_partkernel:
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100399 delay_cycles *= numeric_util.round_up_divide(ifm_block.depth, 8)
400
Diqing Zhong09387e22020-09-28 18:46:22 +0200401 cycles_dpu_blk += cycles
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100402 cycles_dpu_blk += delay_cycles
403
Tim Halld8339a72021-05-27 18:49:40 +0100404 if query.npu_block_type in (NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct, NpuBlockType.ReduceSum):
405 cycles_dpu_blk *= numeric_util.round_up_divide(query.ifm_shape.depth, ifm_block.depth)
Diqing Zhong09387e22020-09-28 18:46:22 +0200406
407 cycles_dpu_blk /= arch.ncores
408
Tim Halld8339a72021-05-27 18:49:40 +0100409 # Estimate output cycles
410 num_ofm_blks = query.ofm_shape.div_round_up(ofm_block).elements()
Johan Alfvénf8e353b2022-02-04 17:24:23 +0100411 cycles_output_blk = round_up_to_int(
412 _estimate_output_cycles_per_element(arch, op_type, faf_type, query) * ofm_block.elements()
413 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200414
Tim Halld8339a72021-05-27 18:49:40 +0100415 # Scale and bias tensor
416 if query.const_shape.depth > 0:
Diqing Zhongf842b692020-12-11 13:07:37 +0100417 cycles_bias_blk = (
Tim Halld8339a72021-05-27 18:49:40 +0100418 10 * ofm_block.depth * arch.memory_latency[query.const_memory_area][BandwidthDirection.Read] / 256
Diqing Zhongf842b692020-12-11 13:07:37 +0100419 )
Diqing Zhong986e3192020-11-16 16:15:56 +0100420 cycles_output_blk = max(cycles_output_blk, cycles_bias_blk)
421
Tim Halld8339a72021-05-27 18:49:40 +0100422 ifm_blk_cycles, ofm_blk_cycles = _estimate_minimum_memory_cycles(arch, query)
423 cycles_cmd = ifm_blk_cycles + ofm_blk_cycles
424 cycles_cmd = (cycles_cmd + cycles_output_blk + cycles_dpu_blk) / 4 # per DPU
425
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100426 cycles_dpu_blk = max(cycles_dpu_blk, cycles_cmd)
427 cycles_output_blk = max(cycles_output_blk, cycles_cmd)
428
Diqing Zhong09387e22020-09-28 18:46:22 +0200429 if cycles_dpu_blk > cycles_output_blk:
Tim Halld8339a72021-05-27 18:49:40 +0100430 total_cycles = cycles_dpu_blk * num_ofm_blks + cycles_output_blk
Diqing Zhong09387e22020-09-28 18:46:22 +0200431 else:
Tim Halld8339a72021-05-27 18:49:40 +0100432 total_cycles = cycles_output_blk * num_ofm_blks + cycles_dpu_blk
Diqing Zhong09387e22020-09-28 18:46:22 +0200433
434 return total_cycles
435
436
Tim Halld8339a72021-05-27 18:49:40 +0100437def measure_mem2mem_cycles(arch, from_mem_area, to_mem_area, to_transfer):
438 from_cycles = to_transfer // arch.memory_bandwidths_per_cycle[from_mem_area]
Tim Hall789e6f32021-06-17 17:02:31 +0100439 from_cycles += arch.memory_latency[from_mem_area][BandwidthDirection.Read]
Tim Halld8339a72021-05-27 18:49:40 +0100440 to_cycles = to_transfer // arch.memory_bandwidths_per_cycle[to_mem_area]
441 return max(from_cycles, to_cycles)
Diqing Zhonge168b962020-11-05 17:18:47 +0100442
Patrik Gustavssonee99bb12021-04-08 09:04:00 +0200443
Tim Halld8339a72021-05-27 18:49:40 +0100444def measure_cycle_cost(arch, op_type: Op, faf_type: Op, query: PerformanceQuery):
445 cycles = CycleCost()
Diqing Zhonge168b962020-11-05 17:18:47 +0100446
Tim Halld8339a72021-05-27 18:49:40 +0100447 # Convolution/Vector product cycle calculation
448 if query.npu_block_type in (
449 NpuBlockType.ConvolutionMxN,
450 NpuBlockType.ConvolutionDepthWise,
451 NpuBlockType.VectorProduct,
452 NpuBlockType.Pooling,
453 NpuBlockType.ReduceSum,
454 ):
455 # cycles.op_macs and cycles.op_cycles should both handle >32-bits
456 if query.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling):
457 cycles.op_macs = int(query.kernel.elements_wh()) * 1 * int(query.ofm_shape.elements())
Diqing Zhonge168b962020-11-05 17:18:47 +0100458 else:
Tim Halld8339a72021-05-27 18:49:40 +0100459 cycles.op_macs = (
460 int(query.kernel.elements_wh()) * int(query.ifm_shape.depth) * int(query.ofm_shape.elements())
461 )
462
463 cycles.op_cycles = int(_estimate_conv_cycles(arch, op_type, faf_type, query))
464 # Elementwise cycle calculation
465 elif query.npu_block_type == NpuBlockType.ElementWise:
466 cycles.op_macs = 0
Johan Alfvénf8e353b2022-02-04 17:24:23 +0100467 ofm_rounding = Shape4D(list(arch.storage_rounding_quantums[query.ofm_format]))
468 cycles.op_cycles = round_up_to_int(
469 _estimate_output_cycles_per_element(arch, op_type, faf_type, query)
470 * Shape4D.round_up(query.ofm_shape, ofm_rounding).elements()
Tim Halld8339a72021-05-27 18:49:40 +0100471 )
Diqing Zhonge168b962020-11-05 17:18:47 +0100472 else:
Tim Halld8339a72021-05-27 18:49:40 +0100473 assert False
Diqing Zhonge168b962020-11-05 17:18:47 +0100474
Tim Halld8339a72021-05-27 18:49:40 +0100475 return cycles
Diqing Zhonge168b962020-11-05 17:18:47 +0100476
477
Tim Halld8339a72021-05-27 18:49:40 +0100478def measure_element_access(arch, query: PerformanceQuery):
479 access = ElementAccess()
Tim Hall79d07d22020-04-27 18:20:16 +0100480
Tim Halld8339a72021-05-27 18:49:40 +0100481 ifm_block = Shape4D.min(query.ifm_shape, query.config.ifm_block)
482 ofm_block = Shape4D.min(query.ofm_shape, query.config.ofm_block)
483 ifm_rounding = Shape4D(list(arch.storage_rounding_quantums[query.ifm_format]))
Tim Hall79d07d22020-04-27 18:20:16 +0100484
Tim Halld8339a72021-05-27 18:49:40 +0100485 # Number of ofm blocks in the overall output shape
486 ofm_blocks = query.ofm_shape.div_round_up(ofm_block)
487 ofm_block_depth = ofm_block.depth
488 if query.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling):
489 ofm_blocks = ofm_blocks.with_depth(1)
490 ofm_block_depth = query.ifm_shape.depth
Diqing Zhonge168b962020-11-05 17:18:47 +0100491
Tim Halld8339a72021-05-27 18:49:40 +0100492 # Convolution & pooling
493 if query.npu_block_type in (
494 NpuBlockType.ConvolutionMxN,
495 NpuBlockType.ConvolutionDepthWise,
496 NpuBlockType.VectorProduct,
497 NpuBlockType.Pooling,
498 NpuBlockType.ReduceSum,
499 ):
500 # Number of sub kernels
501 sub_kernel_limits = arch.sub_kernel_limits[query.npu_block_type]
502 subkernels = numeric_util.round_up_divide(query.kernel.width, sub_kernel_limits[0])
503 subkernels *= numeric_util.round_up_divide(query.kernel.height, sub_kernel_limits[1])
Tim Hall79d07d22020-04-27 18:20:16 +0100504
Tim Halld8339a72021-05-27 18:49:40 +0100505 ofm_block_count = ofm_blocks.elements()
Tim Hall79d07d22020-04-27 18:20:16 +0100506
Tim Halld8339a72021-05-27 18:49:40 +0100507 ifm_fetch = (
508 Shape4D.round_up(ifm_block, ifm_rounding).elements_wh()
509 * Shape4D.round_up(query.ifm_shape, ifm_rounding).depth
Diqing Zhonge168b962020-11-05 17:18:47 +0100510 )
Tim Hall79d07d22020-04-27 18:20:16 +0100511
Tim Halld8339a72021-05-27 18:49:40 +0100512 if query.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling):
513 kernel_read = query.kernel.elements_wh() * 1 # force to no reread
514 else:
515 kernel_read = query.kernel.elements_wh() * query.ifm_shape.depth
Tim Hall79d07d22020-04-27 18:20:16 +0100516
Tim Halld8339a72021-05-27 18:49:40 +0100517 weight_fetch = kernel_read * ofm_block_depth * ofm_block_count
518
519 access.ifm_read[0] = ifm_fetch * subkernels * ofm_block_count
520
521 if query.npu_block_type not in (NpuBlockType.Pooling, NpuBlockType.ReduceSum):
522 access.const_read[0] = weight_fetch
523 access.const_read[1] = query.ofm_shape.depth # Scales & biases
524 access.weights_refetch = ofm_blocks.elements_wh()
525 # Elementwise
526 elif query.npu_block_type == NpuBlockType.ElementWise:
527 if query.ifm_shape.elements() == 1:
528 if query.ifm_bits > 8:
529 # ifm is a non 8-bit scalar
530 access.ifm_read[0] = Shape4D.round_up(query.ifm_shape, ifm_rounding).elements()
531 if query.ifm2_shape:
532 access.ifm_read[1] = Shape4D.round_up(query.ofm_shape, ifm_rounding).elements()
533 else:
534 access.ifm_read[0] = Shape4D.round_up(query.ofm_shape, ifm_rounding).elements()
535 if query.ifm2_shape:
536 if query.ifm2_shape.elements() > 1:
537 access.ifm_read[1] = Shape4D.round_up(query.ofm_shape, ifm_rounding).elements()
538 elif query.ifm2_bits > 8:
539 # ifm2 is a non 8-bit scalar
540 access.ifm_read[1] = Shape4D.round_up(query.ifm2_shape, ifm_rounding).elements()
541 # Unknown
542 else:
543 assert False
544
545 ofm_rounding = Shape4D(list(arch.storage_rounding_quantums[query.ofm_format]))
546 access.ofm_write = Shape4D.round_up(query.ofm_shape, ofm_rounding).elements()
547 return access
548
549
550def measure_performance_cost(
551 arch, op_type: Op, faf_type: Op, query: PerformanceQuery, offset: Shape4D, sub_shape: Shape4D
552):
553 assert (query.ofm_bits > 0) and (query.ifm_bits > 0)
554 assert query.ofm_shape.elements() != 0
555
556 # Default to start if no offset provided
557 if offset is None:
558 offset = Shape4D(0, 0, 0, 0)
559
560 # Default to entire area if no sub-shape provided
561 if sub_shape is None:
562 sub_shape = query.ofm_shape
563 else:
564 sub_shape = Shape4D.min(sub_shape, query.ofm_shape)
565
566 sub_query = copy.deepcopy(query)
567 sub_query.ofm_shape = query.ofm_shape.clip(offset, sub_shape)
568
569 access = ElementAccess()
570 cycles = CycleCost()
571
572 cycle_tmp = measure_cycle_cost(arch, op_type, faf_type, sub_query)
573 cycles += cycle_tmp
574 access = measure_element_access(arch, sub_query)
575
576 return access, cycles
577
578
579def make_bandwidth_array():
580 return np.zeros((MemArea.Size, TensorPurpose.Size, BandwidthDirection.Size))
581
582
583def make_cycles_array():
584 return np.zeros(PassCycles.Size)
Tim Hall79d07d22020-04-27 18:20:16 +0100585
586
Diqing Zhonge168b962020-11-05 17:18:47 +0100587def update_summary_cycles(arch, bws, cycles):
588 cycles[PassCycles.SramAccess] = np.sum(bws[MemArea.Sram]) / arch.memory_bandwidths_per_cycle[MemArea.Sram]
Tim Hall79d07d22020-04-27 18:20:16 +0100589 cycles[PassCycles.DramAccess] = np.sum(bws[MemArea.Dram]) / arch.memory_bandwidths_per_cycle[MemArea.Dram]
590 cycles[PassCycles.OnChipFlashAccess] = (
591 np.sum(bws[MemArea.OnChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OnChipFlash]
592 )
593 cycles[PassCycles.OffChipFlashAccess] = (
594 np.sum(bws[MemArea.OffChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OffChipFlash]
595 )
596
597 cycles[PassCycles.Total] = np.max(cycles[: PassCycles.Total])
598 return cycles
599
600
Tim Halld8339a72021-05-27 18:49:40 +0100601def estimate_full_op_performance(
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100602 arch, schedule: Schedule, op: SchedulerOperation, prev_op: Optional[SchedulerOperation], block_config
Tim Halld8339a72021-05-27 18:49:40 +0100603):
604 cycles_a = make_cycles_array()
605 bws = make_bandwidth_array()
606 scaled_bws = make_bandwidth_array() # scaled bw with memory transfer efficiency
607 macs = 0
608
609 query = PerformanceQuery(op.op_type.npu_block_type)
610 query.ifm_shape = op.ifm.shape
611 query.ifm_format = op.ifm.format
612 query.ifm_memory_area = op.ifm.mem_area
613 query.ifm_bits = op.ifm.dtype.size_in_bits()
614 query.ifm2_shape = op.ifm2 and op.ifm2.shape
615 query.ifm2_format = op.ifm2 and op.ifm2.format
616 query.ifm2_memory_area = op.ifm2 and op.ifm2.mem_area
617 query.ifm2_bits = op.ifm2 and op.ifm2.dtype.size_in_bits()
618 query.ofm_shape = op.ofm.shape
619 query.ofm_memory_area = op.ofm.mem_area
620 query.ofm_bits = op.ofm.dtype.size_in_bits()
621 query.ofm_format = op.ofm.format
622 query.kernel = op.kernel
623 query.config = block_config
624
625 cost = schedule.cost_map[op]
626 prev_cost = schedule.cost_map[prev_op] if prev_op else None
627 if op.parent_op.bias:
628 query.const_shape = Shape4D(1, 1, 1, op.ofm.shape.depth)
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000629 if cost.buffered_weight_tensors:
630 query.const_memory_area = cost.buffered_weight_tensors[0].mem_area
Tim Halld8339a72021-05-27 18:49:40 +0100631 else:
632 query.const_memory_area = cost.npu_weights_tensor.mem_area
633
634 cycles = measure_cycle_cost(arch, op.op_type, op.parent_op.activation and op.parent_op.activation.op_type, query)
635 cycles_a[PassCycles.Npu] = cycles.op_cycles
636 macs = cycles.op_macs
637
638 access = measure_element_access(arch, query)
639
640 # How many NPU cycles are available under the previously executing
641 # operator for performing buffered DMA transfers
642 slack_cycles = prev_cost.slack_buffering_cycles if prev_cost else 0
643
644 # LUT Transfer
645 parent_op = op.parent_op
646 lut_transfer_cycles = 0
647 if parent_op.activation_lut:
648 lut_tensor = [tens for tens in parent_op.inputs if tens.purpose == TensorPurpose.LUT][0]
649 src_tensor = lut_tensor.src_tensor
650 if src_tensor and lut_tensor.mem_area != src_tensor.mem_area:
651 bw = src_tensor.storage_size()
652 lut_transfer_cycles = measure_mem2mem_cycles(arch, src_tensor.mem_area, lut_tensor.mem_area, bw)
653
654 bws[src_tensor.mem_area][lut_tensor.purpose][BandwidthDirection.Read] += bw
655 # LUT read from SHRAM TODO remove?
Ayaan Masoodd5cbef32022-02-22 15:56:35 +0000656 scaled_bws[lut_tensor.mem_area][lut_tensor.purpose][BandwidthDirection.Read] += bw
Tim Halld8339a72021-05-27 18:49:40 +0100657
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000658 if cost.npu_weights_tensor and cost.buffered_weight_tensors:
Tim Halld8339a72021-05-27 18:49:40 +0100659 # DMA Weight Transfer
660 sz = 0
661 # Get the size of the first DMA
662 for core in range(0, arch.ncores):
663 key = WeightKey(core, 0)
664 if key in cost.npu_weights_tensor.encoded_ranges:
665 weight_range = cost.npu_weights_tensor.encoded_ranges[key]
666 sz += round_up(weight_range.total_bytes, 16)
667
668 total_sz = len(cost.npu_weights_tensor.buffer)
669 bws[cost.npu_weights_tensor.mem_area][TensorPurpose.Weights][BandwidthDirection.Read] += total_sz
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000670 bws[cost.buffered_weight_tensors[0].mem_area][TensorPurpose.Weights][BandwidthDirection.Write] += total_sz
Tim Halld8339a72021-05-27 18:49:40 +0100671
672 ws_first_transfer_cycles = measure_mem2mem_cycles(
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000673 arch, cost.npu_weights_tensor.mem_area, cost.buffered_weight_tensors[0].mem_area, sz
Tim Halld8339a72021-05-27 18:49:40 +0100674 )
675
676 # Add cycles for Weight + Scale Transfer
677 cycles_a[PassCycles.Npu] = max(
678 cost.full_weight_transfer_cycles - slack_cycles + cost.slack_buffering_cycles,
679 cycles.op_cycles + max(ws_first_transfer_cycles - slack_cycles, 0),
680 )
681
682 # Add cycles for LUT Transfer
683 cycles_a[PassCycles.Npu] += lut_transfer_cycles
684 else:
685 # Add cycles for LUT Transfer
686 cycles_a[PassCycles.Npu] += max(lut_transfer_cycles - slack_cycles, 0)
687
688 # OFM write
689 ofm = op.parent_op.ofm
690 bw = access.ofm_write * ofm.element_size()
691 bws[query.ofm_memory_area][ofm.purpose][BandwidthDirection.Write] += bw
692 scaled_bws[ofm.mem_area][ofm.purpose][BandwidthDirection.Write] += _estimate_memory_transfer_efficiency(
693 arch, False, query.ofm_memory_area, ofm.format, query.ofm_bits, query.config.ofm_block, query.ofm_shape, bw
694 )
695
696 # IFM read
697 ifm = op.parent_op.ifm
698 bw = access.ifm_read[0] * ifm.element_size()
699 bws[ifm.mem_area][ifm.purpose][BandwidthDirection.Read] += bw
700 scaled_bws[ifm.mem_area][ifm.purpose][BandwidthDirection.Read] += _estimate_memory_transfer_efficiency(
701 arch, True, query.ifm_memory_area, ifm.format, query.ifm_bits, query.config.ifm_block, query.ifm_shape, bw
702 )
703 if query.ifm2_shape:
704 ifm2 = op.parent_op.ifm2
705 bw = access.ifm_read[1] * ifm2.element_size()
706 bws[ifm2.mem_area][ifm2.purpose][BandwidthDirection.Read] += bw
707 scaled_bws[ifm2.mem_area][ifm2.purpose][BandwidthDirection.Read] += _estimate_memory_transfer_efficiency(
708 arch,
709 True,
710 query.ifm2_memory_area,
711 ifm2.format,
712 op.ifm2.dtype.size_in_bits(),
713 query.config.ifm_block,
714 query.ifm2_shape,
715 bw,
716 )
717
718 # Weight read
719 if access.const_read[0] > 0:
720 # alignment not accounted for in bandwidth_compression_scale_approx
721 encoded_size_approx = (
722 cost.npu_weights_tensor.elements() - access.const_read[1] * op.parent_op.bias.element_size()
723 )
724 orig_weight_size = parent_op.weights.elements()
725 bandwidth_compression_scale_approx = encoded_size_approx / orig_weight_size
726 bw = access.const_read[0] * bandwidth_compression_scale_approx
727 bws[query.const_memory_area][TensorPurpose.Weights][BandwidthDirection.Read] += bw
728
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000729 if not cost.buffered_weight_tensors:
Patrik Gustavsson225e19d2021-06-01 12:43:43 +0200730 scaled_bws[query.const_memory_area][TensorPurpose.Weights][BandwidthDirection.Read] += bw
731
Tim Halld8339a72021-05-27 18:49:40 +0100732 if access.const_read[1] > 0:
733 # Scales & biases
734 bw = access.const_read[1] * op.parent_op.bias.element_size()
735 bws[query.const_memory_area][TensorPurpose.FSBias][BandwidthDirection.Read] += bw
736
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000737 if not cost.buffered_weight_tensors:
Patrik Gustavsson225e19d2021-06-01 12:43:43 +0200738 scaled_bws[query.const_memory_area][TensorPurpose.FSBias][BandwidthDirection.Read] += bw
739
Tim Halld8339a72021-05-27 18:49:40 +0100740 update_summary_cycles(arch, scaled_bws, cycles_a)
741
742 return bws, macs, cycles_a
Tim Hall79d07d22020-04-27 18:20:16 +0100743
744
Tim Hallc1be0872022-03-03 17:50:52 +0000745def print_performance(
746 nng: Graph,
747 arch: ArchitectureFeatures,
748 network_type: NetworkType,
749 bws: dict,
750 macs: dict,
751 cycles: dict,
752 mem_usage: dict,
753):
754 if network_type == NetworkType.TFLite:
755 nng_optype_to_input_op_type = tflite_optype_to_builtintype
756 else:
757 nng_optype_to_input_op_type = tosa_optype_to_tosa_op_type
758
759 suid_inv_map = {v: k for k, v in DebugDatabase._sourceUID.items()}
760
761 for sg in nng.subgraphs:
762
763 if sg.placement != PassPlacement.Npu:
764 continue
765
766 print(f"\n{str('#') * 80}")
767 print(f"Performance for NPU Subgraph {sg.name}")
768 print(
769 f" {network_type.name + str(' Operator:'):20s}"
770 f" {str('NNG Operator:'):20s}"
771 f" {str('SRAM Usage'):>10s}"
772 f" ({str('Peak'):>6s}%):"
773 f"{str('Op Cycles'):>10s}"
774 f" ({str('Netwrk'):>6s}%)"
775 f" ["
776 f" {str('NPU'):>10s}"
777 f" {str('SRAM AC'):>10s}"
778 f" {str('DRAM AC'):>10s}"
779 f" {str('OnFlash AC'):>10s}"
780 f" {str('OffFlashAC'):>10s}"
781 f" ]:"
782 f"{str('MAC Count'):>10s}"
783 f" ({str('Netwrk'):>6s}% / {str('Util'):>6s}%):"
784 f"Name:"
785 )
786
787 for sched_op in sg.sched_ops:
788 # get source op name
789 sched_op_src_uid = DebugDatabase._optimisedUID[sched_op.parent_op][1]
790 if sched_op_src_uid == DebugDatabase.NULLREF:
791 src_op_type = None
792 else:
793 src_op_type = suid_inv_map[sched_op_src_uid].type
794
795 src_op_name = nng_optype_to_input_op_type(src_op_type)
796
797 max_macs = cycles[sched_op][PassCycles.Total] * arch.num_macs_per_cycle * arch.ncores
798
799 print(
800 f" {src_op_name:20s}"
801 f" {sched_op.op_type:20s}"
802 f" {mem_usage[sched_op]:10.0f}"
803 f" ({mem_usage[sched_op] / nng.memory_used[MemArea.Sram] * 100:6.2f}%)"
804 f" {cycles[sched_op][PassCycles.Total]:10.0f}"
805 f" ({cycles[sched_op][PassCycles.Total] / nng.cycles[PassCycles.Total] * 100:6.2f}%)"
806 f" ["
807 f" {cycles[sched_op][PassCycles.Npu]:10.0f}"
808 f" {cycles[sched_op][PassCycles.SramAccess]:10.0f}"
809 f" {cycles[sched_op][PassCycles.DramAccess]:10.0f}"
810 f" {cycles[sched_op][PassCycles.OnChipFlashAccess]:10.0f}"
811 f" {cycles[sched_op][PassCycles.OffChipFlashAccess]:10.0f}"
812 f" ]"
813 f" {macs[sched_op]:10d}"
814 f" ({macs[sched_op] / nng.macs * 100:6.2f}% / {macs[sched_op] / max_macs * 100:6.2f}%)"
815 f" {sched_op.name:s}"
816 )
817
818
819def calc_new_performance_for_network(nng: Graph, arch, network_type: NetworkType, verbose_performance: bool):
Tim Hall79d07d22020-04-27 18:20:16 +0100820 total_bws = make_bandwidth_array()
Diqing Zhong69aadd02020-12-08 13:08:48 +0100821 total_macs = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100822 total_cycles = np.zeros(PassCycles.Size)
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000823 total_weight_size = 0
824 total_encoded_weight_size = 0
825
826 # Store unique instances of original/encoded weight tensor uuids to prevent double counting of weights
827 original_weight_uuids: Set[UUID] = set()
828 encoded_npu_weight_uuids: Set[UUID] = set()
Tim Hall79d07d22020-04-27 18:20:16 +0100829
Tim Hallc1be0872022-03-03 17:50:52 +0000830 bws = {}
831 macs = {}
832 cycles = {}
833 mem_usage = {}
834
Tim Hall79d07d22020-04-27 18:20:16 +0100835 for sg in nng.subgraphs:
Tim Halld8339a72021-05-27 18:49:40 +0100836 prev_op = None
837 for sched_op in sg.sched_ops:
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000838 op_info: SchedulerOpInfo = sg.schedule.cost_map[sched_op]
Tim Hallc1be0872022-03-03 17:50:52 +0000839 bws[sched_op], macs[sched_op], cycles[sched_op] = estimate_full_op_performance(
840 arch, sg.schedule, sched_op, prev_op, op_info.block_config
841 )
842
843 # get op sram usage
844 mem_usage[sched_op] = (
845 sg.schedule.memory_snapshot[op_info.time_index]
846 if op_info.time_index < len(sg.schedule.memory_snapshot)
847 else 0
848 )
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000849
850 # Tensors for calculating weight sizes
851 original_weight = sched_op.parent_op.weights
852 encoded_npu_weight = op_info.npu_weights_tensor
853
854 # Save UUIDs of original_weight so only unique instances of tensors are used to calculate weights
855 if original_weight and (original_weight.equivalence_id not in original_weight_uuids):
856
857 original_weight_uuids.add(original_weight.equivalence_id)
858 total_weight_size += original_weight.values.itemsize * original_weight.values.size
859
860 # Save UUIDs of encoded_npu_weight so only unique instances of tensors are used to calculate weights
861 if encoded_npu_weight and (encoded_npu_weight.equivalence_id not in encoded_npu_weight_uuids):
862
Jonas Ohlsson77b448f2022-03-11 16:08:30 +0100863 encoded_npu_weight_uuids.add(encoded_npu_weight.equivalence_id)
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000864 total_encoded_weight_size += len(encoded_npu_weight.buffer)
865
Tim Hallc1be0872022-03-03 17:50:52 +0000866 total_bws += bws[sched_op]
867 total_macs += macs[sched_op]
868 total_cycles += cycles[sched_op]
Tim Halld8339a72021-05-27 18:49:40 +0100869 prev_op = sched_op
Tim Hall79d07d22020-04-27 18:20:16 +0100870
871 nng.bandwidths = total_bws
872 nng.macs = total_macs
873 nng.cycles = total_cycles
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000874 nng.total_original_weights = total_weight_size
875 nng.total_npu_encoded_weights = total_encoded_weight_size
Tim Hallc1be0872022-03-03 17:50:52 +0000876
877 if verbose_performance:
878 print_performance(nng, arch, network_type, bws, macs, cycles, mem_usage)