blob: 0b8e0a6770c2944102599a92e61031b86da65008 [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
Ayaan Masoodb801dda2022-02-22 11:28:55 +000025from typing import Set
26from uuid import UUID
Diego Russoea6111a2020-04-14 18:41:58 +010027
Tim Hall79d07d22020-04-27 18:20:16 +010028import numpy as np
Diego Russoea6111a2020-04-14 18:41:58 +010029
30from . import numeric_util
Tim Halld8339a72021-05-27 18:49:40 +010031from .architecture_allocator import ArchitectureBlockConfig
Diqing Zhong09387e22020-09-28 18:46:22 +020032from .architecture_features import Accelerator
Tim Halld8339a72021-05-27 18:49:40 +010033from .architecture_features import NpuBlockType
34from .architecture_features import SHRAMElements
35from .architecture_features import TensorFormat
Ayaan Masoodb801dda2022-02-22 11:28:55 +000036from .nn_graph import Graph
Tim Halld8339a72021-05-27 18:49:40 +010037from .numeric_util import round_up
38from .operation import Kernel
Diqing Zhonge8887a32020-09-24 09:53:48 +020039from .operation import Op
Tim Halld8339a72021-05-27 18:49:40 +010040from .scheduler import Schedule
41from .scheduler import SchedulerOperation
Ayaan Masoodb801dda2022-02-22 11:28:55 +000042from .scheduler import SchedulerOpInfo
Tim Halld8339a72021-05-27 18:49:40 +010043from .shape4d import Shape4D
Diqing Zhongf842b692020-12-11 13:07:37 +010044from .tensor import BandwidthDirection
Diego Russoe8a10452020-04-21 17:39:10 +010045from .tensor import MemArea
Diego Russoe8a10452020-04-21 17:39:10 +010046from .tensor import TensorPurpose
Tim Halld8339a72021-05-27 18:49:40 +010047from .weight_compressor import WeightKey
Tim Hall79d07d22020-04-27 18:20:16 +010048
49
Diqing Zhonge168b962020-11-05 17:18:47 +010050class PassCycles(IntEnum):
Diqing Zhong42e833d2020-10-02 13:18:42 +020051 Npu = 0
Diqing Zhonge168b962020-11-05 17:18:47 +010052 SramAccess = auto()
53 DramAccess = auto()
54 OnChipFlashAccess = auto()
55 OffChipFlashAccess = auto()
56 Total = auto()
57 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +010058
59 def display_name(self):
Tim Hall1bd531d2020-11-01 20:59:36 +000060 return ("NPU", "SRAM Access", "DRAM Access", "On-chip Flash Access", "Off-chip Flash Access", "Total", "Size",)[
61 self.value
62 ]
Tim Hall79d07d22020-04-27 18:20:16 +010063
64 def identifier_name(self):
Tim Hall1bd531d2020-11-01 20:59:36 +000065 return ("npu", "sram_access", "dram_access", "on_chip_flash_access", "off_chip_flash_access", "total", "size",)[
66 self.value
67 ]
Tim Hall79d07d22020-04-27 18:20:16 +010068
69 @staticmethod
70 def all():
71 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020072 PassCycles.Npu,
Tim Hall79d07d22020-04-27 18:20:16 +010073 PassCycles.SramAccess,
74 PassCycles.DramAccess,
75 PassCycles.OnChipFlashAccess,
76 PassCycles.OffChipFlashAccess,
77 PassCycles.Total,
78 )
79
80
Tim Halld8339a72021-05-27 18:49:40 +010081class PerformanceQuery:
82 def __init__(self, npu_block_type=0):
83 self.npu_block_type = npu_block_type
84 self.ifm_shape = Shape4D(0)
85 self.ifm_format = TensorFormat.NHWC
86 self.ifm_memory_area = MemArea.Unknown
87 self.ifm2_memory_area = MemArea.Unknown
88 self.ifm_bits = 0
89 self.ifm2_bits = 0
90 self.ifm2_shape = None
91 self.ifm2_format = TensorFormat.NHWC
92 self.ofm_shape = Shape4D(0)
93 self.ofm_format = TensorFormat.NHWC
94 self.ofm_memory_area = MemArea.Unknown
95 self.ofm_bits = 0
96 self.const_shape = Shape4D(0)
97 self.const_memory_area = MemArea.Unknown
98 self.kernel = Kernel(1, 1)
99 self.config = ArchitectureBlockConfig()
Tim Hall79d07d22020-04-27 18:20:16 +0100100
101
Tim Halld8339a72021-05-27 18:49:40 +0100102class CycleCost:
103 def __init__(self):
104 self.op_macs = 0
105 self.op_cycles = 0
106
107 def __mul__(self, scale):
108 out = CycleCost()
109 out.op_macs = self.op_macs * scale
110 out.op_cycles = self.op_cycles * scale
111 return out
112
113 def __iadd__(self, rhs):
114 self.op_macs += rhs.op_macs
115 self.op_cycles += rhs.op_cycles
116 return self
117
118 def __str__(self):
119 return "macs = {}, cycles = {}".format(self.op_macs, self.op_cycles)
Tim Hall79d07d22020-04-27 18:20:16 +0100120
121
Tim Halld8339a72021-05-27 18:49:40 +0100122class ElementAccess:
123 def __init__(self):
124 # List of ONLY element access counts, consumers
125 # need to scale these values by the correct bitwidths
126 # to calculated memory bandwidth
127 self.ifm_read = [0, 0] # ifm1, ifm2
128 self.ofm_write = 0
129 self.weights_refetch = 0
130 self.const_read = [0, 0] # weights, scales
131
132 def __mul__(self, scale):
133 out = ElementAccess()
134 out.ifm_read[0] = self.ifm_read[0] * scale
135 out.ifm_read[1] = self.ifm_read[1] * scale
136 out.ofm_write = self.ofm_write * scale
137 out.weights_refetch = self.weights_refetch * scale
138 out.const_read[0] = self.const_read[0] * scale
139 out.const_read[1] = self.const_read[1] * scale
140 return out
141
142 def __iadd__(self, rhs):
143 self.ifm_read[0] += rhs.ifm_read[0]
144 self.ifm_read[1] += rhs.ifm_read[1]
145 self.ofm_write += rhs.ofm_write
146 self.weights_refetch += rhs.weights_refetch
147 self.const_read[0] += rhs.const_read[0]
148 self.const_read[1] += rhs.const_read[1]
149 return self
150
151 def __str__(self):
152 return "ifm read = {}, ofm write = {}, const read={}".format(self.ifm_read, self.ofm_write, self.const_read)
Tim Hall79d07d22020-04-27 18:20:16 +0100153
154
Tim Halld8339a72021-05-27 18:49:40 +0100155def _strides_for_shape(shape: Shape4D, format: TensorFormat, element_bits):
156 if format == TensorFormat.NHWC:
157 strides = [0, 0, 0, 0]
158 strides[3] = element_bits / 8 # +Z
159 strides[2] = (element_bits * shape.depth) // 8 # +X
160 strides[1] = (element_bits * shape.depth * shape.width) // 8 # +Y
161 strides[0] = (element_bits * shape.depth * shape.width * shape.height) // 8 # +N
162 elif format == TensorFormat.NHCWB16:
163 strides = [0, 0, 0, 0, 0]
164 strides[4] = element_bits / 8 # +Z
165 strides[3] = (element_bits * 16) / 8 # +X
166 strides[2] = (element_bits * 16 * shape.width) / 8 # +C
167 strides[1] = (element_bits * shape.width * shape.depth) / 8 # +Y
168 strides[0] = (element_bits * shape.width * shape.depth) / 8 # +N
Diqing Zhong42e833d2020-10-02 13:18:42 +0200169
Tim Halld8339a72021-05-27 18:49:40 +0100170 return strides
Diqing Zhong42e833d2020-10-02 13:18:42 +0200171
172
Tim Halld8339a72021-05-27 18:49:40 +0100173def _estimate_memory_transfer_efficiency(
174 arch, is_read, mem_area, format: TensorFormat, element_bits, block_size, shape4D, to_transfer
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100175):
Tim Halld8339a72021-05-27 18:49:40 +0100176 burst_len = 8
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100177
Tim Halld8339a72021-05-27 18:49:40 +0100178 strides = _strides_for_shape(shape4D, format, element_bits)
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100179
Tim Halld8339a72021-05-27 18:49:40 +0100180 if format == TensorFormat.NHCWB16:
181 if strides[2] == block_size.depth: # TODO is this check corrrect for non 8-bit
182 burst_len = element_bits * block_size.depth * block_size.width
183 elif is_read:
184 burst_len = 16 * element_bits * block_size.width
Diqing Zhonge8887a32020-09-24 09:53:48 +0200185 else:
Tim Halld8339a72021-05-27 18:49:40 +0100186 burst_len = 16 * element_bits * block_size.width * arch.ncores
187 elif format == TensorFormat.NHWC:
188 if is_read:
189 if strides[3] == block_size.depth:
190 burst_len = element_bits * block_size.depth * block_size.width
191 else:
192 burst_len = element_bits * block_size.depth
193 else:
194 if block_size.depth <= 16 and strides[3] == block_size.depth:
195 burst_len = element_bits * block_size.depth * block_size.width
196 else:
197 burst_len = min(64 * 8, 16 * element_bits * arch.ncores, block_size.depth * element_bits)
198
199 burst_len = burst_len // 8 # bits->bytes
200 burst_len = min(arch.memory_burst_length[mem_area], burst_len)
201 return to_transfer * (arch.memory_burst_length[mem_area] / burst_len)
202
203
204def _estimate_minimum_memory_cycles(arch, query: PerformanceQuery):
205 # Input block HW transfer (only for elements present)
206 ifm_bytes = Shape4D.min(query.ifm_shape, query.config.ifm_block).elements()
207 cycles_ifm_blk = arch.memory_latency[query.ifm_memory_area][BandwidthDirection.Read]
208 cycles_ifm_blk = cycles_ifm_blk + (
209 _estimate_memory_transfer_efficiency(
210 arch,
211 True,
212 query.ifm_memory_area,
213 query.ifm_format,
214 query.ifm_bits,
215 query.config.ifm_block,
216 query.ifm_shape,
217 ifm_bytes,
218 )
219 / arch.memory_bandwidths_per_cycle[query.ifm_memory_area]
220 )
221 # Output block HW transfer (only for elements present)
222 ofm_bytes = Shape4D.min(query.ofm_shape, query.config.ofm_block).elements()
223 cycles_ofm_blk = arch.memory_latency[query.ofm_memory_area][BandwidthDirection.Write]
224 cycles_ofm_blk = cycles_ofm_blk + (
225 _estimate_memory_transfer_efficiency(
226 arch,
227 False,
228 query.ofm_memory_area,
229 query.ofm_format,
230 query.ofm_bits,
231 query.config.ofm_block,
232 query.ofm_shape,
233 ofm_bytes,
234 )
235 / arch.memory_bandwidths_per_cycle[query.ofm_memory_area]
236 )
237 return cycles_ifm_blk, cycles_ofm_blk
238
239
240def _estimate_output_cycles_per_element(arch, op_type: Op, faf_type: Op, query: PerformanceQuery):
241 if query.npu_block_type == NpuBlockType.ElementWise and query.ifm_bits == 32:
242 # Unary op else Binary op
243 output_perf_index = 0 if query.ifm2_shape is not None else 1
244 elif op_type == Op.Mul and query.ofm_bits == 32:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200245 output_perf_index = 2
Tim Halld8339a72021-05-27 18:49:40 +0100246 elif op_type == Op.Mul or (
247 query.npu_block_type
Diqing Zhonge8887a32020-09-24 09:53:48 +0200248 in (
249 NpuBlockType.ConvolutionMxN,
250 NpuBlockType.ConvolutionDepthWise,
251 NpuBlockType.Pooling,
252 NpuBlockType.ReduceSum,
253 NpuBlockType.VectorProduct,
254 )
Tim Halld8339a72021-05-27 18:49:40 +0100255 and query.config.acc_type == SHRAMElements.Acc40
Diqing Zhonge8887a32020-09-24 09:53:48 +0200256 ):
257 output_perf_index = 3
Tim Halld8339a72021-05-27 18:49:40 +0100258 elif op_type in (Op.Add, Op.Sub):
259 if False:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200260 # Simple Add/Sub
261 output_perf_index = 4
262 else:
Tim Halld8339a72021-05-27 18:49:40 +0100263 # Advanced Add/Sub TODO: Add as perf selection as operator variant
Diqing Zhonge8887a32020-09-24 09:53:48 +0200264 output_perf_index = 5
Tim Halld8339a72021-05-27 18:49:40 +0100265 elif op_type.is_maxpool_op():
Diqing Zhonge8887a32020-09-24 09:53:48 +0200266 output_perf_index = 6
267 else:
268 output_perf_index = 7
269
Tim Halld8339a72021-05-27 18:49:40 +0100270 if faf_type in (Op.Sigmoid, Op.Tanh, Op.LUT):
Diqing Zhonge8887a32020-09-24 09:53:48 +0200271 activation_perf_index = 0
Tim Halld8339a72021-05-27 18:49:40 +0100272 elif faf_type in (Op.Relu, Op.Relu6, Op.ReluN1To1):
Diqing Zhonge8887a32020-09-24 09:53:48 +0200273 activation_perf_index = 1
274 else:
275 activation_perf_index = 2
276
Diqing Zhonge8887a32020-09-24 09:53:48 +0200277 cycle_per_elem = max(
278 arch.output_cycles_per_elem[output_perf_index], arch.activation_cycles_per_elem[activation_perf_index]
279 )
Diqing Zhong986e3192020-11-16 16:15:56 +0100280
Tim Halld8339a72021-05-27 18:49:40 +0100281 if op_type.is_elementwise_op():
282 num_elems_blk = query.config.ofm_block.elements()
283 ifm_blk_cycles, ofm_blk_cycles = _estimate_minimum_memory_cycles(arch, query)
284 cycle_cmd = ifm_blk_cycles + ofm_blk_cycles
285 cycle_cmd = (cycle_cmd + cycle_per_elem * num_elems_blk) / 4 # per DPU
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100286 cycle_per_elem = max(cycle_per_elem, cycle_cmd / num_elems_blk)
287
Tim Halld8339a72021-05-27 18:49:40 +0100288 return cycle_per_elem
Diqing Zhonge8887a32020-09-24 09:53:48 +0200289
290
Tim Halld8339a72021-05-27 18:49:40 +0100291def _estimate_conv_cycles(arch, op_type: Op, faf_type: Op, query: PerformanceQuery):
292 ifm_block = Shape4D.min(query.ifm_shape, query.config.ifm_block)
293 ofm_block = Shape4D.min(query.ofm_shape, query.config.ofm_block)
Diqing Zhonge5204a62020-10-13 11:42:37 +0200294
295 if (
296 arch.config.ofm_ublock.height == 2
Tim Halld8339a72021-05-27 18:49:40 +0100297 and query.npu_block_type
Diqing Zhonge5204a62020-10-13 11:42:37 +0200298 in (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.VectorProduct)
Tim Halld8339a72021-05-27 18:49:40 +0100299 and query.ofm_shape.height == 1
Diqing Zhonge5204a62020-10-13 11:42:37 +0200300 # Optimisation only applies for even width tensors
Tim Halld8339a72021-05-27 18:49:40 +0100301 and query.ofm_shape.width % 2 == 0
302 and query.kernel.height == 1
Diqing Zhonge5204a62020-10-13 11:42:37 +0200303 ):
Tim Halld8339a72021-05-27 18:49:40 +0100304 ofm_ublock = Shape4D(1, 1, 4, arch.config.ofm_ublock.depth)
305 ofm_block = ofm_block.with_height(1)
306 else:
307 ofm_ublock = Shape4D(arch.config.ofm_ublock.to_hwc())
Diqing Zhonge5204a62020-10-13 11:42:37 +0200308
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100309 num_ublk_x = numeric_util.round_up_divide(ofm_block.width, ofm_ublock.width)
Tim Halld8339a72021-05-27 18:49:40 +0100310 num_ublk_y = numeric_util.round_up_divide(ofm_block.height, ofm_ublock.height)
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100311 num_ublk_xy = num_ublk_x * num_ublk_y
Tim Halld8339a72021-05-27 18:49:40 +0100312 num_ublk_z = numeric_util.round_up_divide(ofm_block.depth, ofm_ublock.depth)
313 use_acc_40bits = query.config.acc_type == SHRAMElements.Acc40
Diqing Zhong09387e22020-09-28 18:46:22 +0200314
Tim Halld8339a72021-05-27 18:49:40 +0100315 sub_kernel_limits = arch.sub_kernel_limits[query.npu_block_type]
316 n_sub_kernels_y = numeric_util.round_up_divide(query.kernel.height, sub_kernel_limits[0])
317 n_sub_kernels_x = numeric_util.round_up_divide(query.kernel.width, sub_kernel_limits[1])
Diqing Zhong09387e22020-09-28 18:46:22 +0200318 sub_kernel_x = [
Tim Halld8339a72021-05-27 18:49:40 +0100319 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 +0200320 ]
321 sub_kernel_y = [
Tim Halld8339a72021-05-27 18:49:40 +0100322 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 +0200323 ]
324 sub_kernel_size = (x * y for y in sub_kernel_y for x in sub_kernel_x)
325
Diqing Zhong09387e22020-09-28 18:46:22 +0200326 cycles_dpu_blk = 0
Diqing Zhong986e3192020-11-16 16:15:56 +0100327 cycles_wb = 32 * ofm_ublock.depth // 8
Diqing Zhong09387e22020-09-28 18:46:22 +0200328
329 for num_kernel_elems in sub_kernel_size:
Tim Halld8339a72021-05-27 18:49:40 +0100330 if query.npu_block_type == NpuBlockType.Pooling:
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100331 num_kernel_steps = 1
Diqing Zhong986e3192020-11-16 16:15:56 +0100332 cycles = max(4, num_kernel_elems) * num_ublk_xy * num_ublk_z
Tim Halld8339a72021-05-27 18:49:40 +0100333 if query.ifm_bits == 16 and arch.accelerator_config != Accelerator.Ethos_U55_32:
Diqing Zhong09387e22020-09-28 18:46:22 +0200334 cycles *= 2
Tim Halld8339a72021-05-27 18:49:40 +0100335 elif query.npu_block_type == NpuBlockType.ConvolutionDepthWise:
Diqing Zhong986e3192020-11-16 16:15:56 +0100336 cycles = 4 * num_ublk_xy
Tim Halld8339a72021-05-27 18:49:40 +0100337 if query.ifm_bits == 16:
Diqing Zhong09387e22020-09-28 18:46:22 +0200338 cycles *= 2
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100339 num_kernel_steps = numeric_util.round_up_divide(num_kernel_elems, 4)
340 cycles = max(cycles_wb, cycles) * num_kernel_steps * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200341 elif (
Tim Halld8339a72021-05-27 18:49:40 +0100342 (query.npu_block_type == NpuBlockType.ConvolutionMxN and not query.config.is_partkernel)
343 or query.npu_block_type == NpuBlockType.VectorProduct
344 or query.npu_block_type == NpuBlockType.ReduceSum
Diqing Zhong09387e22020-09-28 18:46:22 +0200345 ):
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100346 num_kernel_steps = num_kernel_elems
347 cycles = max(cycles_wb, 4 * num_ublk_xy) * num_kernel_steps * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200348 else:
Tim Halld8339a72021-05-27 18:49:40 +0100349 assert query.config.is_partkernel
350 divider = 2 if query.ifm_bits == 16 else 4
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100351 num_kernel_steps = numeric_util.round_up_divide(num_kernel_elems, divider)
Diqing Zhong986e3192020-11-16 16:15:56 +0100352 cycles = max(cycles_wb, 4 * num_ublk_xy) * (
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100353 num_kernel_steps * numeric_util.round_up_divide(ifm_block.depth, 8) * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200354 )
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100355
356 delay_cycles = 0
357 if arch.accelerator_config is Accelerator.Ethos_U55_32:
358 delay = 7 if use_acc_40bits else 3
359 if num_ublk_x == 1 and num_ublk_y == 1:
360 if num_ublk_z == 1:
361 delay_cycles = delay * num_kernel_steps
362 elif num_kernel_steps > 1:
363 delay_cycles = delay * (num_kernel_steps - 1) * num_ublk_z
364 if (num_ublk_x == 1 or num_ublk_y == 1) and num_ublk_z > 1 and use_acc_40bits:
365 delay_cycles += delay * num_ublk_z
366 else:
Tim Halld8339a72021-05-27 18:49:40 +0100367 if use_acc_40bits and arch.accelerator_config in (Accelerator.Ethos_U55_64, Accelerator.Ethos_U55_128):
368 delay = 3
369 else:
370 delay = 2
371
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100372 if num_ublk_x == 1 and num_ublk_y == 1:
373 if num_ublk_z == 1:
374 delay_cycles = delay * num_kernel_steps
375 elif num_kernel_steps > 1:
376 delay_cycles = delay * (num_kernel_steps - 1) * num_ublk_z
377
Tim Halld8339a72021-05-27 18:49:40 +0100378 if query.npu_block_type == NpuBlockType.ConvolutionMxN and query.config.is_partkernel:
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100379 delay_cycles *= numeric_util.round_up_divide(ifm_block.depth, 8)
380
Diqing Zhong09387e22020-09-28 18:46:22 +0200381 cycles_dpu_blk += cycles
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100382 cycles_dpu_blk += delay_cycles
383
Tim Halld8339a72021-05-27 18:49:40 +0100384 if query.npu_block_type in (NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct, NpuBlockType.ReduceSum):
385 cycles_dpu_blk *= numeric_util.round_up_divide(query.ifm_shape.depth, ifm_block.depth)
Diqing Zhong09387e22020-09-28 18:46:22 +0200386
387 cycles_dpu_blk /= arch.ncores
388
Tim Halld8339a72021-05-27 18:49:40 +0100389 # Estimate output cycles
390 num_ofm_blks = query.ofm_shape.div_round_up(ofm_block).elements()
391 cycles_output_blk = _estimate_output_cycles_per_element(arch, op_type, faf_type, query) * ofm_block.elements()
Diqing Zhong09387e22020-09-28 18:46:22 +0200392
Tim Halld8339a72021-05-27 18:49:40 +0100393 # Scale and bias tensor
394 if query.const_shape.depth > 0:
Diqing Zhongf842b692020-12-11 13:07:37 +0100395 cycles_bias_blk = (
Tim Halld8339a72021-05-27 18:49:40 +0100396 10 * ofm_block.depth * arch.memory_latency[query.const_memory_area][BandwidthDirection.Read] / 256
Diqing Zhongf842b692020-12-11 13:07:37 +0100397 )
Diqing Zhong986e3192020-11-16 16:15:56 +0100398 cycles_output_blk = max(cycles_output_blk, cycles_bias_blk)
399
Tim Halld8339a72021-05-27 18:49:40 +0100400 ifm_blk_cycles, ofm_blk_cycles = _estimate_minimum_memory_cycles(arch, query)
401 cycles_cmd = ifm_blk_cycles + ofm_blk_cycles
402 cycles_cmd = (cycles_cmd + cycles_output_blk + cycles_dpu_blk) / 4 # per DPU
403
Diqing Zhongef0c7fe2020-11-24 14:38:20 +0100404 cycles_dpu_blk = max(cycles_dpu_blk, cycles_cmd)
405 cycles_output_blk = max(cycles_output_blk, cycles_cmd)
406
Diqing Zhong09387e22020-09-28 18:46:22 +0200407 if cycles_dpu_blk > cycles_output_blk:
Tim Halld8339a72021-05-27 18:49:40 +0100408 total_cycles = cycles_dpu_blk * num_ofm_blks + cycles_output_blk
Diqing Zhong09387e22020-09-28 18:46:22 +0200409 else:
Tim Halld8339a72021-05-27 18:49:40 +0100410 total_cycles = cycles_output_blk * num_ofm_blks + cycles_dpu_blk
Diqing Zhong09387e22020-09-28 18:46:22 +0200411
412 return total_cycles
413
414
Tim Halld8339a72021-05-27 18:49:40 +0100415def measure_mem2mem_cycles(arch, from_mem_area, to_mem_area, to_transfer):
416 from_cycles = to_transfer // arch.memory_bandwidths_per_cycle[from_mem_area]
Tim Hall789e6f32021-06-17 17:02:31 +0100417 from_cycles += arch.memory_latency[from_mem_area][BandwidthDirection.Read]
Tim Halld8339a72021-05-27 18:49:40 +0100418 to_cycles = to_transfer // arch.memory_bandwidths_per_cycle[to_mem_area]
419 return max(from_cycles, to_cycles)
Diqing Zhonge168b962020-11-05 17:18:47 +0100420
Patrik Gustavssonee99bb12021-04-08 09:04:00 +0200421
Tim Halld8339a72021-05-27 18:49:40 +0100422def measure_cycle_cost(arch, op_type: Op, faf_type: Op, query: PerformanceQuery):
423 cycles = CycleCost()
Diqing Zhonge168b962020-11-05 17:18:47 +0100424
Tim Halld8339a72021-05-27 18:49:40 +0100425 # Convolution/Vector product cycle calculation
426 if query.npu_block_type in (
427 NpuBlockType.ConvolutionMxN,
428 NpuBlockType.ConvolutionDepthWise,
429 NpuBlockType.VectorProduct,
430 NpuBlockType.Pooling,
431 NpuBlockType.ReduceSum,
432 ):
433 # cycles.op_macs and cycles.op_cycles should both handle >32-bits
434 if query.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling):
435 cycles.op_macs = int(query.kernel.elements_wh()) * 1 * int(query.ofm_shape.elements())
Diqing Zhonge168b962020-11-05 17:18:47 +0100436 else:
Tim Halld8339a72021-05-27 18:49:40 +0100437 cycles.op_macs = (
438 int(query.kernel.elements_wh()) * int(query.ifm_shape.depth) * int(query.ofm_shape.elements())
439 )
440
441 cycles.op_cycles = int(_estimate_conv_cycles(arch, op_type, faf_type, query))
442 # Elementwise cycle calculation
443 elif query.npu_block_type == NpuBlockType.ElementWise:
444 cycles.op_macs = 0
445 cycles.op_cycles = int(_estimate_output_cycles_per_element(arch, op_type, faf_type, query)) * int(
446 query.ofm_shape.elements()
447 )
Diqing Zhonge168b962020-11-05 17:18:47 +0100448 else:
Tim Halld8339a72021-05-27 18:49:40 +0100449 assert False
Diqing Zhonge168b962020-11-05 17:18:47 +0100450
Tim Halld8339a72021-05-27 18:49:40 +0100451 return cycles
Diqing Zhonge168b962020-11-05 17:18:47 +0100452
453
Tim Halld8339a72021-05-27 18:49:40 +0100454def measure_element_access(arch, query: PerformanceQuery):
455 access = ElementAccess()
Tim Hall79d07d22020-04-27 18:20:16 +0100456
Tim Halld8339a72021-05-27 18:49:40 +0100457 ifm_block = Shape4D.min(query.ifm_shape, query.config.ifm_block)
458 ofm_block = Shape4D.min(query.ofm_shape, query.config.ofm_block)
459 ifm_rounding = Shape4D(list(arch.storage_rounding_quantums[query.ifm_format]))
Tim Hall79d07d22020-04-27 18:20:16 +0100460
Tim Halld8339a72021-05-27 18:49:40 +0100461 # Number of ofm blocks in the overall output shape
462 ofm_blocks = query.ofm_shape.div_round_up(ofm_block)
463 ofm_block_depth = ofm_block.depth
464 if query.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling):
465 ofm_blocks = ofm_blocks.with_depth(1)
466 ofm_block_depth = query.ifm_shape.depth
Diqing Zhonge168b962020-11-05 17:18:47 +0100467
Tim Halld8339a72021-05-27 18:49:40 +0100468 # Convolution & pooling
469 if query.npu_block_type in (
470 NpuBlockType.ConvolutionMxN,
471 NpuBlockType.ConvolutionDepthWise,
472 NpuBlockType.VectorProduct,
473 NpuBlockType.Pooling,
474 NpuBlockType.ReduceSum,
475 ):
476 # Number of sub kernels
477 sub_kernel_limits = arch.sub_kernel_limits[query.npu_block_type]
478 subkernels = numeric_util.round_up_divide(query.kernel.width, sub_kernel_limits[0])
479 subkernels *= numeric_util.round_up_divide(query.kernel.height, sub_kernel_limits[1])
Tim Hall79d07d22020-04-27 18:20:16 +0100480
Tim Halld8339a72021-05-27 18:49:40 +0100481 ofm_block_count = ofm_blocks.elements()
Tim Hall79d07d22020-04-27 18:20:16 +0100482
Tim Halld8339a72021-05-27 18:49:40 +0100483 ifm_fetch = (
484 Shape4D.round_up(ifm_block, ifm_rounding).elements_wh()
485 * Shape4D.round_up(query.ifm_shape, ifm_rounding).depth
Diqing Zhonge168b962020-11-05 17:18:47 +0100486 )
Tim Hall79d07d22020-04-27 18:20:16 +0100487
Tim Halld8339a72021-05-27 18:49:40 +0100488 if query.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling):
489 kernel_read = query.kernel.elements_wh() * 1 # force to no reread
490 else:
491 kernel_read = query.kernel.elements_wh() * query.ifm_shape.depth
Tim Hall79d07d22020-04-27 18:20:16 +0100492
Tim Halld8339a72021-05-27 18:49:40 +0100493 weight_fetch = kernel_read * ofm_block_depth * ofm_block_count
494
495 access.ifm_read[0] = ifm_fetch * subkernels * ofm_block_count
496
497 if query.npu_block_type not in (NpuBlockType.Pooling, NpuBlockType.ReduceSum):
498 access.const_read[0] = weight_fetch
499 access.const_read[1] = query.ofm_shape.depth # Scales & biases
500 access.weights_refetch = ofm_blocks.elements_wh()
501 # Elementwise
502 elif query.npu_block_type == NpuBlockType.ElementWise:
503 if query.ifm_shape.elements() == 1:
504 if query.ifm_bits > 8:
505 # ifm is a non 8-bit scalar
506 access.ifm_read[0] = Shape4D.round_up(query.ifm_shape, ifm_rounding).elements()
507 if query.ifm2_shape:
508 access.ifm_read[1] = Shape4D.round_up(query.ofm_shape, ifm_rounding).elements()
509 else:
510 access.ifm_read[0] = Shape4D.round_up(query.ofm_shape, ifm_rounding).elements()
511 if query.ifm2_shape:
512 if query.ifm2_shape.elements() > 1:
513 access.ifm_read[1] = Shape4D.round_up(query.ofm_shape, ifm_rounding).elements()
514 elif query.ifm2_bits > 8:
515 # ifm2 is a non 8-bit scalar
516 access.ifm_read[1] = Shape4D.round_up(query.ifm2_shape, ifm_rounding).elements()
517 # Unknown
518 else:
519 assert False
520
521 ofm_rounding = Shape4D(list(arch.storage_rounding_quantums[query.ofm_format]))
522 access.ofm_write = Shape4D.round_up(query.ofm_shape, ofm_rounding).elements()
523 return access
524
525
526def measure_performance_cost(
527 arch, op_type: Op, faf_type: Op, query: PerformanceQuery, offset: Shape4D, sub_shape: Shape4D
528):
529 assert (query.ofm_bits > 0) and (query.ifm_bits > 0)
530 assert query.ofm_shape.elements() != 0
531
532 # Default to start if no offset provided
533 if offset is None:
534 offset = Shape4D(0, 0, 0, 0)
535
536 # Default to entire area if no sub-shape provided
537 if sub_shape is None:
538 sub_shape = query.ofm_shape
539 else:
540 sub_shape = Shape4D.min(sub_shape, query.ofm_shape)
541
542 sub_query = copy.deepcopy(query)
543 sub_query.ofm_shape = query.ofm_shape.clip(offset, sub_shape)
544
545 access = ElementAccess()
546 cycles = CycleCost()
547
548 cycle_tmp = measure_cycle_cost(arch, op_type, faf_type, sub_query)
549 cycles += cycle_tmp
550 access = measure_element_access(arch, sub_query)
551
552 return access, cycles
553
554
555def make_bandwidth_array():
556 return np.zeros((MemArea.Size, TensorPurpose.Size, BandwidthDirection.Size))
557
558
559def make_cycles_array():
560 return np.zeros(PassCycles.Size)
Tim Hall79d07d22020-04-27 18:20:16 +0100561
562
Diqing Zhonge168b962020-11-05 17:18:47 +0100563def update_summary_cycles(arch, bws, cycles):
564 cycles[PassCycles.SramAccess] = np.sum(bws[MemArea.Sram]) / arch.memory_bandwidths_per_cycle[MemArea.Sram]
Tim Hall79d07d22020-04-27 18:20:16 +0100565 cycles[PassCycles.DramAccess] = np.sum(bws[MemArea.Dram]) / arch.memory_bandwidths_per_cycle[MemArea.Dram]
566 cycles[PassCycles.OnChipFlashAccess] = (
567 np.sum(bws[MemArea.OnChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OnChipFlash]
568 )
569 cycles[PassCycles.OffChipFlashAccess] = (
570 np.sum(bws[MemArea.OffChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OffChipFlash]
571 )
572
573 cycles[PassCycles.Total] = np.max(cycles[: PassCycles.Total])
574 return cycles
575
576
Tim Halld8339a72021-05-27 18:49:40 +0100577def estimate_full_op_performance(
578 arch, schedule: Schedule, op: SchedulerOperation, prev_op: SchedulerOperation, block_config
579):
580 cycles_a = make_cycles_array()
581 bws = make_bandwidth_array()
582 scaled_bws = make_bandwidth_array() # scaled bw with memory transfer efficiency
583 macs = 0
584
585 query = PerformanceQuery(op.op_type.npu_block_type)
586 query.ifm_shape = op.ifm.shape
587 query.ifm_format = op.ifm.format
588 query.ifm_memory_area = op.ifm.mem_area
589 query.ifm_bits = op.ifm.dtype.size_in_bits()
590 query.ifm2_shape = op.ifm2 and op.ifm2.shape
591 query.ifm2_format = op.ifm2 and op.ifm2.format
592 query.ifm2_memory_area = op.ifm2 and op.ifm2.mem_area
593 query.ifm2_bits = op.ifm2 and op.ifm2.dtype.size_in_bits()
594 query.ofm_shape = op.ofm.shape
595 query.ofm_memory_area = op.ofm.mem_area
596 query.ofm_bits = op.ofm.dtype.size_in_bits()
597 query.ofm_format = op.ofm.format
598 query.kernel = op.kernel
599 query.config = block_config
600
601 cost = schedule.cost_map[op]
602 prev_cost = schedule.cost_map[prev_op] if prev_op else None
603 if op.parent_op.bias:
604 query.const_shape = Shape4D(1, 1, 1, op.ofm.shape.depth)
605 if cost.buffered_weight_tensor:
606 query.const_memory_area = cost.buffered_weight_tensor.mem_area
607 else:
608 query.const_memory_area = cost.npu_weights_tensor.mem_area
609
610 cycles = measure_cycle_cost(arch, op.op_type, op.parent_op.activation and op.parent_op.activation.op_type, query)
611 cycles_a[PassCycles.Npu] = cycles.op_cycles
612 macs = cycles.op_macs
613
614 access = measure_element_access(arch, query)
615
616 # How many NPU cycles are available under the previously executing
617 # operator for performing buffered DMA transfers
618 slack_cycles = prev_cost.slack_buffering_cycles if prev_cost else 0
619
620 # LUT Transfer
621 parent_op = op.parent_op
622 lut_transfer_cycles = 0
623 if parent_op.activation_lut:
624 lut_tensor = [tens for tens in parent_op.inputs if tens.purpose == TensorPurpose.LUT][0]
625 src_tensor = lut_tensor.src_tensor
626 if src_tensor and lut_tensor.mem_area != src_tensor.mem_area:
627 bw = src_tensor.storage_size()
628 lut_transfer_cycles = measure_mem2mem_cycles(arch, src_tensor.mem_area, lut_tensor.mem_area, bw)
629
630 bws[src_tensor.mem_area][lut_tensor.purpose][BandwidthDirection.Read] += bw
631 # LUT read from SHRAM TODO remove?
Ayaan Masoodd5cbef32022-02-22 15:56:35 +0000632 scaled_bws[lut_tensor.mem_area][lut_tensor.purpose][BandwidthDirection.Read] += bw
Tim Halld8339a72021-05-27 18:49:40 +0100633
634 if cost.npu_weights_tensor and cost.buffered_weight_tensor:
635 # DMA Weight Transfer
636 sz = 0
637 # Get the size of the first DMA
638 for core in range(0, arch.ncores):
639 key = WeightKey(core, 0)
640 if key in cost.npu_weights_tensor.encoded_ranges:
641 weight_range = cost.npu_weights_tensor.encoded_ranges[key]
642 sz += round_up(weight_range.total_bytes, 16)
643
644 total_sz = len(cost.npu_weights_tensor.buffer)
645 bws[cost.npu_weights_tensor.mem_area][TensorPurpose.Weights][BandwidthDirection.Read] += total_sz
646 bws[cost.buffered_weight_tensor.mem_area][TensorPurpose.Weights][BandwidthDirection.Write] += total_sz
647
648 ws_first_transfer_cycles = measure_mem2mem_cycles(
649 arch, cost.npu_weights_tensor.mem_area, cost.buffered_weight_tensor.mem_area, sz
650 )
651
652 # Add cycles for Weight + Scale Transfer
653 cycles_a[PassCycles.Npu] = max(
654 cost.full_weight_transfer_cycles - slack_cycles + cost.slack_buffering_cycles,
655 cycles.op_cycles + max(ws_first_transfer_cycles - slack_cycles, 0),
656 )
657
658 # Add cycles for LUT Transfer
659 cycles_a[PassCycles.Npu] += lut_transfer_cycles
660 else:
661 # Add cycles for LUT Transfer
662 cycles_a[PassCycles.Npu] += max(lut_transfer_cycles - slack_cycles, 0)
663
664 # OFM write
665 ofm = op.parent_op.ofm
666 bw = access.ofm_write * ofm.element_size()
667 bws[query.ofm_memory_area][ofm.purpose][BandwidthDirection.Write] += bw
668 scaled_bws[ofm.mem_area][ofm.purpose][BandwidthDirection.Write] += _estimate_memory_transfer_efficiency(
669 arch, False, query.ofm_memory_area, ofm.format, query.ofm_bits, query.config.ofm_block, query.ofm_shape, bw
670 )
671
672 # IFM read
673 ifm = op.parent_op.ifm
674 bw = access.ifm_read[0] * ifm.element_size()
675 bws[ifm.mem_area][ifm.purpose][BandwidthDirection.Read] += bw
676 scaled_bws[ifm.mem_area][ifm.purpose][BandwidthDirection.Read] += _estimate_memory_transfer_efficiency(
677 arch, True, query.ifm_memory_area, ifm.format, query.ifm_bits, query.config.ifm_block, query.ifm_shape, bw
678 )
679 if query.ifm2_shape:
680 ifm2 = op.parent_op.ifm2
681 bw = access.ifm_read[1] * ifm2.element_size()
682 bws[ifm2.mem_area][ifm2.purpose][BandwidthDirection.Read] += bw
683 scaled_bws[ifm2.mem_area][ifm2.purpose][BandwidthDirection.Read] += _estimate_memory_transfer_efficiency(
684 arch,
685 True,
686 query.ifm2_memory_area,
687 ifm2.format,
688 op.ifm2.dtype.size_in_bits(),
689 query.config.ifm_block,
690 query.ifm2_shape,
691 bw,
692 )
693
694 # Weight read
695 if access.const_read[0] > 0:
696 # alignment not accounted for in bandwidth_compression_scale_approx
697 encoded_size_approx = (
698 cost.npu_weights_tensor.elements() - access.const_read[1] * op.parent_op.bias.element_size()
699 )
700 orig_weight_size = parent_op.weights.elements()
701 bandwidth_compression_scale_approx = encoded_size_approx / orig_weight_size
702 bw = access.const_read[0] * bandwidth_compression_scale_approx
703 bws[query.const_memory_area][TensorPurpose.Weights][BandwidthDirection.Read] += bw
704
Patrik Gustavsson225e19d2021-06-01 12:43:43 +0200705 if not cost.buffered_weight_tensor:
706 scaled_bws[query.const_memory_area][TensorPurpose.Weights][BandwidthDirection.Read] += bw
707
Tim Halld8339a72021-05-27 18:49:40 +0100708 if access.const_read[1] > 0:
709 # Scales & biases
710 bw = access.const_read[1] * op.parent_op.bias.element_size()
711 bws[query.const_memory_area][TensorPurpose.FSBias][BandwidthDirection.Read] += bw
712
Patrik Gustavsson225e19d2021-06-01 12:43:43 +0200713 if not cost.buffered_weight_tensor:
714 scaled_bws[query.const_memory_area][TensorPurpose.FSBias][BandwidthDirection.Read] += bw
715
Tim Halld8339a72021-05-27 18:49:40 +0100716 update_summary_cycles(arch, scaled_bws, cycles_a)
717
718 return bws, macs, cycles_a
Tim Hall79d07d22020-04-27 18:20:16 +0100719
720
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000721def calc_new_performance_for_network(nng: Graph, arch):
Tim Hall79d07d22020-04-27 18:20:16 +0100722 total_bws = make_bandwidth_array()
Diqing Zhong69aadd02020-12-08 13:08:48 +0100723 total_macs = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100724 total_cycles = np.zeros(PassCycles.Size)
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000725 total_weight_size = 0
726 total_encoded_weight_size = 0
727
728 # Store unique instances of original/encoded weight tensor uuids to prevent double counting of weights
729 original_weight_uuids: Set[UUID] = set()
730 encoded_npu_weight_uuids: Set[UUID] = set()
Tim Hall79d07d22020-04-27 18:20:16 +0100731
732 for sg in nng.subgraphs:
Tim Halld8339a72021-05-27 18:49:40 +0100733 prev_op = None
734 for sched_op in sg.sched_ops:
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000735 op_info: SchedulerOpInfo = sg.schedule.cost_map[sched_op]
Tim Halld8339a72021-05-27 18:49:40 +0100736 bws, macs, cycles = estimate_full_op_performance(arch, sg.schedule, sched_op, prev_op, op_info.block_config)
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000737
738 # Tensors for calculating weight sizes
739 original_weight = sched_op.parent_op.weights
740 encoded_npu_weight = op_info.npu_weights_tensor
741
742 # Save UUIDs of original_weight so only unique instances of tensors are used to calculate weights
743 if original_weight and (original_weight.equivalence_id not in original_weight_uuids):
744
745 original_weight_uuids.add(original_weight.equivalence_id)
746 total_weight_size += original_weight.values.itemsize * original_weight.values.size
747
748 # Save UUIDs of encoded_npu_weight so only unique instances of tensors are used to calculate weights
749 if encoded_npu_weight and (encoded_npu_weight.equivalence_id not in encoded_npu_weight_uuids):
750
751 encoded_npu_weight_uuids.add(encoded_npu_weight)
752 total_encoded_weight_size += len(encoded_npu_weight.buffer)
753
Tim Hall79d07d22020-04-27 18:20:16 +0100754 total_bws += bws
755 total_macs += macs
756 total_cycles += cycles
Tim Halld8339a72021-05-27 18:49:40 +0100757 prev_op = sched_op
Tim Hall79d07d22020-04-27 18:20:16 +0100758
759 nng.bandwidths = total_bws
760 nng.macs = total_macs
761 nng.cycles = total_cycles
Ayaan Masoodb801dda2022-02-22 11:28:55 +0000762 nng.total_original_weights = total_weight_size
763 nng.total_npu_encoded_weights = total_encoded_weight_size