blob: d1be5a508241607515336662780257354b81772e [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# 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.
Diqing Zhonge168b962020-11-05 17:18:47 +010022from enum import auto
23from enum import IntEnum
Diego Russoea6111a2020-04-14 18:41:58 +010024
Tim Hall79d07d22020-04-27 18:20:16 +010025import numpy as np
Diego Russoea6111a2020-04-14 18:41:58 +010026
27from . import numeric_util
Diqing Zhong09387e22020-09-28 18:46:22 +020028from .architecture_features import Accelerator
Diego Russoe8a10452020-04-21 17:39:10 +010029from .architecture_features import Block
Diqing Zhonge8887a32020-09-24 09:53:48 +020030from .data_type import DataType
Diego Russoe8a10452020-04-21 17:39:10 +010031from .nn_graph import PassPlacement
32from .nn_graph import SchedulerRewrite
Diego Russoea6111a2020-04-14 18:41:58 +010033from .operation import NpuBlockType
Diqing Zhonge8887a32020-09-24 09:53:48 +020034from .operation import Op
Diqing Zhong09387e22020-09-28 18:46:22 +020035from .shared_buffer_allocation import is_acc_40bits_used
Diego Russoe8a10452020-04-21 17:39:10 +010036from .tensor import MemArea
37from .tensor import shape_num_elements
38from .tensor import TensorBlockTraversal
Diqing Zhonge168b962020-11-05 17:18:47 +010039from .tensor import TensorFormat
Diego Russoe8a10452020-04-21 17:39:10 +010040from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010041
42
43def rolling_buffer_dims_from_passes(arch, ps1, block_config_ps1, ps2, block_config_ps2):
Tim Hall79d07d22020-04-27 18:20:16 +010044 ofm_block = Block(block_config_ps2[-3], block_config_ps2[-4], block_config_ps2[-1])
Tim Hall4ed38bc2020-10-20 18:54:20 +010045 kernel = ps2.primary_op.kernel
Tim Hall79d07d22020-04-27 18:20:16 +010046
47 if ps2.npu_block_type in set((NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct)):
Louis Verhaard93dc5532020-06-07 12:40:18 +020048 op = ps2.primary_op
Louis Verhaardaee5d752020-09-30 09:01:52 +020049 ifm_block_depth = arch.calc_ifm_block_depth(op.ifm.shape[-1], op.ifm.dtype.size_in_bits())
Tim Hall79d07d22020-04-27 18:20:16 +010050 else:
51 ifm_block_depth = block_config_ps2[-1]
52
Louis Verhaard93dc5532020-06-07 12:40:18 +020053 ifm_block = arch.get_ifm_block_size(ifm_block_depth, ofm_block, kernel, arch.ofm_block_max)
Tim Hall79d07d22020-04-27 18:20:16 +010054
55 # The performed height calculation is for worst case
56 height = numeric_util.round_up(ifm_block.height + block_config_ps1[0], block_config_ps1[0])
57 width = ifm_block.width
Louis Verhaard93dc5532020-06-07 12:40:18 +020058 return [height, width]
Tim Hall79d07d22020-04-27 18:20:16 +010059
60
Diqing Zhonge168b962020-11-05 17:18:47 +010061class PassCycles(IntEnum):
Diqing Zhong42e833d2020-10-02 13:18:42 +020062 Npu = 0
Diqing Zhonge168b962020-11-05 17:18:47 +010063 SramAccess = auto()
64 DramAccess = auto()
65 OnChipFlashAccess = auto()
66 OffChipFlashAccess = auto()
67 Total = auto()
68 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +010069
70 def display_name(self):
Tim Hall1bd531d2020-11-01 20:59:36 +000071 return ("NPU", "SRAM Access", "DRAM Access", "On-chip Flash Access", "Off-chip Flash Access", "Total", "Size",)[
72 self.value
73 ]
Tim Hall79d07d22020-04-27 18:20:16 +010074
75 def identifier_name(self):
Tim Hall1bd531d2020-11-01 20:59:36 +000076 return ("npu", "sram_access", "dram_access", "on_chip_flash_access", "off_chip_flash_access", "total", "size",)[
77 self.value
78 ]
Tim Hall79d07d22020-04-27 18:20:16 +010079
80 @staticmethod
81 def all():
82 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020083 PassCycles.Npu,
Tim Hall79d07d22020-04-27 18:20:16 +010084 PassCycles.SramAccess,
85 PassCycles.DramAccess,
86 PassCycles.OnChipFlashAccess,
87 PassCycles.OffChipFlashAccess,
88 PassCycles.Total,
89 )
90
91
Diqing Zhonge168b962020-11-05 17:18:47 +010092class MacCount(IntEnum):
Tim Hall79d07d22020-04-27 18:20:16 +010093 NeuralNetworkMacs = 0
Diqing Zhonge168b962020-11-05 17:18:47 +010094 HardwareMacs = auto()
95 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +010096
97 def display_name(self):
98 return ("Neural Network Macs", "Hardware Macs", "Size")[self.value]
99
100 def identifier_name(self):
101 return ("nn_macs", "hardware_macs", "size")[self.value]
102
103 @staticmethod
104 def all():
105 return (MacCount.NeuralNetworkMacs, MacCount.HardwareMacs)
106
107
Diqing Zhonge168b962020-11-05 17:18:47 +0100108class BandwidthDirection(IntEnum):
Tim Hall79d07d22020-04-27 18:20:16 +0100109 Read = 0
Diqing Zhonge168b962020-11-05 17:18:47 +0100110 Write = auto()
111 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +0100112
113 def display_name(self):
114 return self.name
115
116 def identifier_name(self):
117 return self.name.lower()
118
119 @staticmethod
120 def all():
121 return (BandwidthDirection.Read, BandwidthDirection.Write)
122
123
124def make_bandwidth_array():
125 return np.zeros((MemArea.Size, TensorPurpose.Size, BandwidthDirection.Size))
126
127
128def make_macs_array():
129 return np.zeros(MacCount.Size, np.int)
130
131
132def make_cycles_array():
133 return np.zeros(PassCycles.Size)
134
135
136def make_metrics_arrays():
137 return (make_bandwidth_array(), make_macs_array(), make_cycles_array())
138
139
140def get_n_blocks_and_area(
141 ifm_brick_size, ifm_height_width, orig_skirt, clamped_skirt, block_config, min_block_size, strides
142):
143
144 ifm_block_config = (block_config[0] * strides[1], block_config[1] * strides[2])
145
146 n_normal_blocks = []
147 remainder_size = []
148 for i in range(2):
149 non_skirt_dim = ifm_height_width[i] - orig_skirt[i] - orig_skirt[2 + i]
150 n_blocks = non_skirt_dim // ifm_block_config[i]
151 n_normal_blocks.append(n_blocks)
152 remainder_dim = numeric_util.round_up(
153 ((non_skirt_dim - n_blocks * ifm_block_config[i] - 1) // strides[i + 1]) + 1, min_block_size[i]
154 )
155 remainder_size.append(remainder_dim)
156
157 # this will actually calculate reads into the edge padding.
158
159 # there are four cases in total, handling the edges that will not fill a complete block.
160
161 # 0000000001
162 # 0000000001
163 # 0000000001
164 # 0000000001
165 # 0000000001
166 # 0000000001
167 # 2222222223
168 total_blocks = 0
169 total_area = 0
170
171 block_setup = (
172 (n_normal_blocks[0] * n_normal_blocks[1], block_config),
173 (1 * n_normal_blocks[1], (remainder_size[0], block_config[1])),
174 (n_normal_blocks[0] * 1, (block_config[0], remainder_size[1])),
175 (1 * 1, remainder_size),
176 )
177
178 for n_blocks, block_size in block_setup:
179 if block_size[0] == 0 or block_size[1] == 0:
180 continue
181 read_dims = [0, 0]
182 for i in range(2):
183 read_dims[i] = (
184 numeric_util.round_up(clamped_skirt[i], ifm_brick_size[i + 1])
185 + block_size[i] * strides[i + 1]
186 + numeric_util.round_up(clamped_skirt[2 + i], ifm_brick_size[i + 1])
187 )
188 assert n_blocks >= 0
189 total_blocks += n_blocks
190 total_area += n_blocks * read_dims[0] * read_dims[1]
191 assert total_blocks >= 1
192 return total_blocks, total_area, block_setup
193
194
Diqing Zhong42e833d2020-10-02 13:18:42 +0200195def get_ifm_block_depth(npu_block_type, ifm_depth, ifm_elemwidth, block_traversal, ofm_blk_depth):
196 ifm_blk_depth = ofm_blk_depth
197
198 if npu_block_type == NpuBlockType.ConvolutionMxN or npu_block_type == NpuBlockType.ReduceSum:
199 if ifm_elemwidth == 16 or block_traversal == TensorBlockTraversal.PartKernelFirst:
200 ifm_blk_depth = 16
201 elif ifm_elemwidth == 8:
202 ifm_blk_depth = 32
203 else:
204 ifm_blk_depth = 8
205
206 return min(ifm_depth, ifm_blk_depth)
207
208
209def estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200210 arch, npu_block_type, primary_op, num_elems, ifm_tensor, ofm_tensor, ifm2_tensor, use_acc_40bits=False
211):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100212 faf = None if primary_op.activation is None else primary_op.activation.op_type
Diqing Zhong09387e22020-09-28 18:46:22 +0200213 if npu_block_type == NpuBlockType.ElementWise and ifm_tensor.dtype == DataType.int32:
214 if ifm2_tensor is None:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200215 # Unary op
216 output_perf_index = 0
217 else:
218 # Binary op
219 output_perf_index = 1
Diqing Zhong09387e22020-09-28 18:46:22 +0200220 elif primary_op.type == Op.Mul and ofm_tensor.dtype == DataType.int32:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200221 output_perf_index = 2
Diqing Zhong09387e22020-09-28 18:46:22 +0200222 elif primary_op.type == Op.Mul or (
Diqing Zhonge8887a32020-09-24 09:53:48 +0200223 npu_block_type
224 in (
225 NpuBlockType.ConvolutionMxN,
226 NpuBlockType.ConvolutionDepthWise,
227 NpuBlockType.Pooling,
228 NpuBlockType.ReduceSum,
229 NpuBlockType.VectorProduct,
230 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200231 and use_acc_40bits
Diqing Zhonge8887a32020-09-24 09:53:48 +0200232 ):
233 output_perf_index = 3
Diqing Zhong09387e22020-09-28 18:46:22 +0200234 elif primary_op.type in (Op.Add, Op.Sub):
235 input_scale = ifm_tensor.quantization.scale_f32
236 input2_scale = ifm2_tensor.quantization.scale_f32
237 output_scale = ofm_tensor.quantization.scale_f32
Diqing Zhonge8887a32020-09-24 09:53:48 +0200238
239 if "resizebilinear" in primary_op.attrs:
240 output_scale = input2_scale
241
242 if None in (input_scale, input2_scale, output_scale) or input_scale == input2_scale:
243 # Simple Add/Sub
244 output_perf_index = 4
245 else:
246 # Advanced Add/Sub
247 output_perf_index = 5
Diqing Zhong09387e22020-09-28 18:46:22 +0200248 elif primary_op.type.is_maxpool_op():
Diqing Zhonge8887a32020-09-24 09:53:48 +0200249 output_perf_index = 6
250 else:
251 output_perf_index = 7
252
253 if faf in (Op.Sigmoid, Op.Tanh, Op.LUT):
254 activation_perf_index = 0
255 elif faf in (Op.Relu, Op.Relu6, Op.ReluN1To1):
256 activation_perf_index = 1
257 else:
258 activation_perf_index = 2
259
Diqing Zhonge8887a32020-09-24 09:53:48 +0200260 cycle_per_elem = max(
261 arch.output_cycles_per_elem[output_perf_index], arch.activation_cycles_per_elem[activation_perf_index]
262 )
Diqing Zhong986e3192020-11-16 16:15:56 +0100263
Diqing Zhonge8887a32020-09-24 09:53:48 +0200264 return num_elems * cycle_per_elem
265
266
Diqing Zhong42e833d2020-10-02 13:18:42 +0200267def estimate_conv_pooling_cycles(
Diqing Zhong986e3192020-11-16 16:15:56 +0100268 arch,
269 npu_block_type,
270 primary_op,
271 block_config: Block,
272 block_traversal,
273 kernel_dims,
274 ifm_tensor,
275 ofm_tensor,
276 scale_tensor=None,
Diqing Zhong09387e22020-09-28 18:46:22 +0200277):
Diqing Zhonge5204a62020-10-13 11:42:37 +0200278 ofm_ublock = Block(arch.config.ofm_ublock.width, arch.config.ofm_ublock.height, arch.config.ofm_ublock.depth)
279 ifm_tens_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
280 ofm_tens_shape = numeric_util.full_shape(4, ofm_tensor.shape, 1)
281
282 if (
283 arch.config.ofm_ublock.height == 2
284 and npu_block_type
285 in (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.VectorProduct)
286 and ofm_tens_shape[1] == 1
287 # Optimisation only applies for even width tensors
288 and ofm_tens_shape[2] % 2 == 0
289 and kernel_dims[0] == 1
290 ):
291 ofm_ublock.width = 4
292 ofm_ublock.height = 1
293 block_config.height = 1
294
Diqing Zhong986e3192020-11-16 16:15:56 +0100295 num_ublk_xy = numeric_util.round_up_divide(block_config.width, ofm_ublock.width) * (
296 block_config.height // ofm_ublock.height
Diqing Zhong09387e22020-09-28 18:46:22 +0200297 )
Diqing Zhong986e3192020-11-16 16:15:56 +0100298 num_ublk_z = block_config.depth // ofm_ublock.depth
299
Diqing Zhong09387e22020-09-28 18:46:22 +0200300 num_ofm_blk = 0
301 total_cycles = 0
302 num_elems_blk = block_config.width * block_config.height * block_config.depth
Diqing Zhonge5204a62020-10-13 11:42:37 +0200303
Diqing Zhong09387e22020-09-28 18:46:22 +0200304 use_acc_40bits = is_acc_40bits_used(npu_block_type, ifm_tensor, ofm_tensor)
305
306 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
307 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
308 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
309 sub_kernel_x = [
310 min((kernel_dims[1] - i * sub_kernel_limits[1]), sub_kernel_limits[1]) for i in range(n_sub_kernels_x)
311 ]
312 sub_kernel_y = [
313 min((kernel_dims[0] - i * sub_kernel_limits[0]), sub_kernel_limits[0]) for i in range(n_sub_kernels_y)
314 ]
315 sub_kernel_size = (x * y for y in sub_kernel_y for x in sub_kernel_x)
316
Diqing Zhong42e833d2020-10-02 13:18:42 +0200317 ifm_blk_depth = get_ifm_block_depth(
318 npu_block_type, ifm_tens_shape[3], ifm_tensor.dtype.size_in_bits(), block_traversal, block_config.depth
319 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200320 cycles_dpu_blk = 0
Diqing Zhong986e3192020-11-16 16:15:56 +0100321 cycles_wb = 32 * ofm_ublock.depth // 8
Diqing Zhong09387e22020-09-28 18:46:22 +0200322
323 for num_kernel_elems in sub_kernel_size:
324 if npu_block_type == NpuBlockType.Pooling:
Diqing Zhong986e3192020-11-16 16:15:56 +0100325 cycles = max(4, num_kernel_elems) * num_ublk_xy * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200326 if ifm_tensor.dtype.size_in_bits() == 16 and arch.accelerator_config != Accelerator.Ethos_U55_32:
327 cycles *= 2
328 elif npu_block_type == NpuBlockType.ConvolutionDepthWise:
Diqing Zhong986e3192020-11-16 16:15:56 +0100329 cycles = 4 * num_ublk_xy
Diqing Zhong09387e22020-09-28 18:46:22 +0200330 if ifm_tensor.dtype.size_in_bits() == 16:
331 cycles *= 2
Diqing Zhong986e3192020-11-16 16:15:56 +0100332 cycles = max(cycles_wb, cycles) * numeric_util.round_up_divide(num_kernel_elems, 4) * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200333 elif (
334 (npu_block_type == NpuBlockType.ConvolutionMxN and block_traversal != TensorBlockTraversal.PartKernelFirst)
335 or npu_block_type == NpuBlockType.VectorProduct
336 or npu_block_type == NpuBlockType.ReduceSum
337 ):
Diqing Zhong986e3192020-11-16 16:15:56 +0100338 cycles = (
339 max(cycles_wb, 4 * num_ublk_xy)
340 * num_kernel_elems
341 * num_ublk_z
342 * numeric_util.round_up_divide(ifm_tens_shape[3], ifm_blk_depth)
343 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200344 else:
345 assert block_traversal == TensorBlockTraversal.PartKernelFirst
346 divider = 2 if ifm_tensor.dtype.size_in_bits() == 16 else 4
Diqing Zhong986e3192020-11-16 16:15:56 +0100347 cycles = max(cycles_wb, 4 * num_ublk_xy) * (
Diqing Zhong09387e22020-09-28 18:46:22 +0200348 numeric_util.round_up_divide(num_kernel_elems, divider)
349 * numeric_util.round_up_divide(ifm_blk_depth, 8)
Diqing Zhong986e3192020-11-16 16:15:56 +0100350 * num_ublk_z
Diqing Zhong09387e22020-09-28 18:46:22 +0200351 * numeric_util.round_up_divide(ifm_tens_shape[3], ifm_blk_depth)
352 )
353 cycles_dpu_blk += cycles
354
355 cycles_dpu_blk /= arch.ncores
356
357 num_ofm_blk = (
358 numeric_util.round_up_divide(ofm_tens_shape[1], block_config.height)
359 * numeric_util.round_up_divide(ofm_tens_shape[2], block_config.width)
360 * numeric_util.round_up_divide(ofm_tens_shape[3], block_config.depth)
361 )
362
Diqing Zhong42e833d2020-10-02 13:18:42 +0200363 cycles_output_blk = estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200364 arch, npu_block_type, primary_op, num_elems_blk, ifm_tensor, ofm_tensor, None, use_acc_40bits
365 )
366
Diqing Zhong986e3192020-11-16 16:15:56 +0100367 if scale_tensor:
368 if scale_tensor.mem_area is MemArea.Sram:
369 latency = 32
370 elif scale_tensor.mem_area is MemArea.Dram:
371 latency = 500
372 else:
373 latency = 64
374 cycles_bias_blk = 10 * min(block_config.depth, ofm_tens_shape[3]) * latency / 256
375 cycles_output_blk = max(cycles_output_blk, cycles_bias_blk)
376
Diqing Zhong09387e22020-09-28 18:46:22 +0200377 if cycles_dpu_blk > cycles_output_blk:
378 total_cycles = cycles_dpu_blk * num_ofm_blk + cycles_output_blk
379 else:
380 total_cycles = cycles_output_blk * num_ofm_blk + cycles_dpu_blk
381
382 return total_cycles
383
384
Diqing Zhonge168b962020-11-05 17:18:47 +0100385def estimate_memory_bandwidth(arch, mem_area, direction, tensor, block_size: Block, replace_bw=None):
386 if tensor.format not in (TensorFormat.NHWC, TensorFormat.NHCWB16):
387 return tensor.bandwidth() if replace_bw is None else replace_bw
388
389 # Estimate memory transfer efficiency by calculating the burst length
390 # this is related to data format, block shape, and tensor shape, etc.
391 max_burst_len = 32 if mem_area == MemArea.Sram else 128
392 burst_len = 0
393 elem_size = tensor.dtype.size_in_bytes()
394 is_ifm = direction == BandwidthDirection.Read
395 tens = tensor.clone()
396 if not tens.avoid_NHCWB16:
397 tens.set_format(TensorFormat.NHCWB16, arch)
398
399 if tens.format == TensorFormat.NHCWB16:
400 if tens.get_strides()[1] == block_size.depth:
401 burst_len = elem_size * block_size.depth * block_size.width
402 elif is_ifm:
403 burst_len = 16 * elem_size * block_size.width
404 else:
405 burst_len = 16 * elem_size * block_size.width * arch.ncores
406 else:
407 assert tens.format == TensorFormat.NHWC
408 if is_ifm:
409 if tens.get_strides()[3] == block_size.depth:
410 burst_len = elem_size * block_size.depth * block_size.width
411 else:
412 burst_len = elem_size * block_size.depth
413 else:
414 if block_size.depth <= 16 and tens.get_strides()[3] == block_size.depth:
415 burst_len = elem_size * block_size.depth * block_size.width
416 else:
417 burst_len = min(64, 16 * elem_size * arch.ncores, block_size.depth * elem_size)
418
419 burst_len = min(max_burst_len, burst_len)
420 bw = tens.bandwidth() if replace_bw is None else replace_bw
421
422 return bw * (max_burst_len / burst_len)
423
424
Tim Hall79d07d22020-04-27 18:20:16 +0100425def performance_metrics_for_pass(arch, ps, block_config=None, rewrite_list=[], force_outputs_to_fast_storage=False):
426 if block_config is None:
427 block_config = ps.block_config
428 bws = make_bandwidth_array()
429 macs = make_macs_array()
430 cycles = make_cycles_array()
431 blocks = 0
432 ifm_read_multiple = 1
433 weight_read_multiple = 0
434
435 if ps.placement in set((PassPlacement.MemoryOnly, PassPlacement.StartupInit)):
436 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple # nothing real happening in this pass
437
438 min_block_size = arch.min_block_sizes[ps.npu_block_type]
439
440 skirt = (0, 0, 0, 0)
441 explicit_padding = (0, 0, 0, 0)
442 primary_op = ps.primary_op
443 replacement_read_bws = {}
Diqing Zhonge168b962020-11-05 17:18:47 +0100444 ofm_block = Block(block_config[1], block_config[0], block_config[3])
445 ifm_block = Block(block_config[1], block_config[0], block_config[3])
446
Tim Hall1bd531d2020-11-01 20:59:36 +0000447 if ps.placement == PassPlacement.Npu and primary_op:
Tim Hall79d07d22020-04-27 18:20:16 +0100448 skirt = primary_op.attrs.get("skirt", skirt)
449 explicit_padding = primary_op.attrs.get("explicit_padding", explicit_padding)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200450 assert primary_op.type.npu_block_type == ps.npu_block_type
451 npu_block_type = primary_op.type.npu_block_type
Diqing Zhong42e833d2020-10-02 13:18:42 +0200452 block_traversal = TensorBlockTraversal.Default
Tim Hall79d07d22020-04-27 18:20:16 +0100453
454 ifm_tensor, _, weight_tensor, ofm_tensor = ps.get_primary_op_ifm_ifm2_weights_ofm()
Diqing Zhonge168b962020-11-05 17:18:47 +0100455 ifm_tensor_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100456
Tim Hallc30f4952020-06-15 20:47:35 +0100457 if npu_block_type in set(
Diqing Zhong09387e22020-09-28 18:46:22 +0200458 (
459 NpuBlockType.ConvolutionMxN,
460 NpuBlockType.ConvolutionDepthWise,
461 NpuBlockType.Pooling,
462 NpuBlockType.ReduceSum,
463 )
Tim Hallc30f4952020-06-15 20:47:35 +0100464 ):
Charles Xu3e9c4342020-04-22 08:31:43 +0200465 # extent the ifm to full dimension
466 ifm_tensor_brick_size = tuple(numeric_util.full_shape(4, list(ifm_tensor.brick_size), 1))
Charles Xu3e9c4342020-04-22 08:31:43 +0200467 ifm_tensor_bandwidth_shape = numeric_util.full_shape(4, ifm_tensor.bandwidth_shape, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100468
Diqing Zhong42e833d2020-10-02 13:18:42 +0200469 batch_size = ifm_tensor_shape[0]
Charles Xu3e9c4342020-04-22 08:31:43 +0200470 ifm_depth = ifm_tensor_bandwidth_shape[3]
Tim Hall79d07d22020-04-27 18:20:16 +0100471
472 # add in padding
473 ifm_tensor_shape[1] += explicit_padding[0] + explicit_padding[2] # height += top and bottom
474 ifm_tensor_shape[2] += explicit_padding[1] + explicit_padding[3] # width += left and right
475
476 strides = primary_op.attrs["strides"]
477 if npu_block_type != NpuBlockType.Pooling:
Diqing Zhong09387e22020-09-28 18:46:22 +0200478 if npu_block_type == NpuBlockType.ReduceSum:
479 block_traversal = TensorBlockTraversal.DepthFirst
480 weight_tensor_shape = [1, 1, ifm_tensor.shape[3], ofm_tensor.shape[3]]
481 weight_tensor_bandwidth_shape = [0] * 4
482 weight_tensor_element_size = 0
483 weight_tensor_bandwidth_compression_scale = 0.0
484 else:
485 block_traversal = weight_tensor.block_traversal
486 weight_tensor_shape = weight_tensor.shape
487 weight_tensor_bandwidth_shape = weight_tensor.bandwidth_shape
488 weight_tensor_element_size = weight_tensor.element_size()
489 weight_tensor_bandwidth_compression_scale = weight_tensor.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100490 nn_ops = (
491 int(ofm_tensor.shape[0])
492 * int(ofm_tensor.shape[1])
493 * int(ofm_tensor.shape[2])
494 * int(weight_tensor_shape[0])
495 * int(weight_tensor_shape[1])
496 * int(weight_tensor_shape[2])
497 * int(weight_tensor_shape[3])
Tim Hall79d07d22020-04-27 18:20:16 +0100498 )
499 else:
500 weight_tensor_shape = [
501 primary_op.attrs["ksize"][1],
502 primary_op.attrs["ksize"][2],
503 1,
504 ifm_tensor_shape[3],
505 ]
506 weight_tensor_bandwidth_shape = weight_tensor_shape
507 weight_tensor_element_size = 0
508 weight_tensor_bandwidth_compression_scale = 0.0
509 nn_ops = 0 # pooling doesn't count as NN ops
510
511 kernel_dims = weight_tensor_shape[:2]
512
513 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
514 # count the sub kernels; the IFM block needs to be refetched for each of them
515 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
516 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
517 n_sub_kernels = n_sub_kernels_y * n_sub_kernels_x
518
519 clamped_skirt = list(skirt)
520 clamped_skirt[2] = min(clamped_skirt[2], sub_kernel_limits[0] - 1 - clamped_skirt[0])
521 clamped_skirt[3] = min(clamped_skirt[3], sub_kernel_limits[1] - 1 - clamped_skirt[1])
522 n_blocks, area, block_setup = get_n_blocks_and_area(
Charles Xu3e9c4342020-04-22 08:31:43 +0200523 ifm_tensor_brick_size,
Tim Hall79d07d22020-04-27 18:20:16 +0100524 ifm_tensor_shape[1:3],
525 skirt,
526 clamped_skirt,
527 block_config,
528 min_block_size,
529 strides,
530 )
531
Diqing Zhonge168b962020-11-05 17:18:47 +0100532 blocks = n_blocks * numeric_util.round_up_divide(weight_tensor_shape[3], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100533
Diqing Zhonge168b962020-11-05 17:18:47 +0100534 n_weight_stages = numeric_util.round_up_divide(weight_tensor_bandwidth_shape[3], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100535 if npu_block_type == NpuBlockType.ConvolutionDepthWise or npu_block_type == NpuBlockType.Pooling:
536 n_weight_stages = 1 # force to no reread
537
538 ifm_tensor_bw = (
539 n_sub_kernels
540 * batch_size
541 * area
542 * ifm_depth
543 * n_weight_stages
544 * ifm_tensor.element_size()
545 * ifm_tensor.bandwidth_compression_scale
546 )
547 replacement_read_bws[ifm_tensor] = ifm_tensor_bw
548 ifm_read_multiple = n_weight_stages
549
550 replacement_read_bws[weight_tensor] = (
551 batch_size
552 * shape_num_elements(weight_tensor_bandwidth_shape)
553 * weight_tensor_element_size
554 * weight_tensor_bandwidth_compression_scale
555 * n_blocks
556 ) # read once per block and batch
557 weight_read_multiple = n_blocks
558
559 n_kernel_xy = kernel_dims[0] * kernel_dims[1]
560 n_input_channels_at_a_time = block_config[2]
561
Diqing Zhong09387e22020-09-28 18:46:22 +0200562 if npu_block_type == NpuBlockType.Pooling or block_traversal in set(
Tim Hall79d07d22020-04-27 18:20:16 +0100563 (TensorBlockTraversal.PartKernelFirst, TensorBlockTraversal.DepthWise)
564 ):
565 n_input_channels_at_a_time = numeric_util.round_up_divide(n_input_channels_at_a_time, 4)
566 n_kernel_xy = max(
567 n_kernel_xy, 4
568 ) # need at least 4, as this is the minimum duty cycle for secondary accumulator writes
569 if weight_tensor is not None:
Diego Russoea6111a2020-04-14 18:41:58 +0100570 n_kernel_xy = numeric_util.round_up(n_kernel_xy, 4) # weights need to be read in blocks of 4
Tim Hall79d07d22020-04-27 18:20:16 +0100571
572 num_mac_ops = 0
573 for n_blocks_for_size, block_size in block_setup:
574 num_mac_ops += (
575 batch_size
576 * n_blocks_for_size
577 * block_size[0]
578 * block_size[1]
579 * numeric_util.round_up(weight_tensor_shape[2], n_input_channels_at_a_time)
Diqing Zhonge168b962020-11-05 17:18:47 +0100580 * numeric_util.round_up(weight_tensor_shape[3], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100581 * n_kernel_xy
582 )
583
Tim Hall79d07d22020-04-27 18:20:16 +0100584 macs[MacCount.NeuralNetworkMacs] += nn_ops
585 macs[MacCount.HardwareMacs] += num_mac_ops
Diqing Zhong42e833d2020-10-02 13:18:42 +0200586 cycles[PassCycles.Npu] = estimate_conv_pooling_cycles(
Diqing Zhong986e3192020-11-16 16:15:56 +0100587 arch,
588 npu_block_type,
589 primary_op,
590 ofm_block,
591 block_traversal,
592 kernel_dims,
593 ifm_tensor,
594 ofm_tensor,
595 ps.scale_tensor,
Diqing Zhong09387e22020-09-28 18:46:22 +0200596 )
Tim Hall79d07d22020-04-27 18:20:16 +0100597 elif npu_block_type == NpuBlockType.VectorProduct:
598 nn_macs = (
599 ifm_tensor.shape[0]
600 * numeric_util.round_up(weight_tensor.shape[-2], block_config[2])
601 * numeric_util.round_up(weight_tensor.shape[-1], block_config[3])
602 )
603 num_mac_ops = nn_macs
Diqing Zhonge168b962020-11-05 17:18:47 +0100604 block_traversal = weight_tensor.block_traversal
Tim Hall79d07d22020-04-27 18:20:16 +0100605
Diqing Zhong42e833d2020-10-02 13:18:42 +0200606 cycles[PassCycles.Npu] = estimate_conv_pooling_cycles(
Diqing Zhonge168b962020-11-05 17:18:47 +0100607 arch, npu_block_type, primary_op, ofm_block, block_traversal, [1, 1], ifm_tensor, ofm_tensor,
Diqing Zhong09387e22020-09-28 18:46:22 +0200608 )
Tim Hall79d07d22020-04-27 18:20:16 +0100609 macs[MacCount.NeuralNetworkMacs] += nn_macs
610 macs[MacCount.HardwareMacs] += num_mac_ops
611
Diqing Zhonge168b962020-11-05 17:18:47 +0100612 blocks = 1 * numeric_util.round_up_divide(weight_tensor.shape[-1], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100613
614 non_zero_fraction = 1.0
615 if ifm_tensor.values is not None:
616 nz_vector = np.amax(ifm_tensor.values != 0, axis=0) # max across batch axis
617 non_zero_fraction = np.average(nz_vector)
618
619 replacement_read_bws[ifm_tensor] = ifm_tensor.bandwidth()
620 replacement_read_bws[weight_tensor] = weight_tensor.bandwidth() * non_zero_fraction
621 ifm_read_multiple = 1
622 weight_read_multiple = non_zero_fraction
Diqing Zhonge8887a32020-09-24 09:53:48 +0200623 elif npu_block_type == NpuBlockType.ElementWise:
Tim Hall79d07d22020-04-27 18:20:16 +0100624 # Work out how many elements we have and calculate performance.
Diqing Zhong42e833d2020-10-02 13:18:42 +0200625 cycles[PassCycles.Npu] = estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200626 arch, npu_block_type, primary_op, ofm_tensor.elements(), ps.ifm_tensor, ps.ofm_tensor, ps.ifm2_tensor
627 )
Diqing Zhong42e833d2020-10-02 13:18:42 +0200628
Diqing Zhonge168b962020-11-05 17:18:47 +0100629 ifm_block_depth = get_ifm_block_depth(
630 npu_block_type, ifm_tensor_shape[3], ifm_tensor.dtype.size_in_bits(), block_traversal, ofm_block.depth
631 )
632 ifm_block = arch.get_ifm_block_size(ifm_block_depth, ofm_block, primary_op.kernel)
633
Diqing Zhong42e833d2020-10-02 13:18:42 +0200634 prev_npu_pass = next((npu_ps for npu_ps in ps.dag_predecessors if npu_ps.placement is PassPlacement.Npu), None)
635 if prev_npu_pass is None:
636 # cycles for DMA ops in first pass
637 dma_ops = (op for op in ps.ops if op.type == Op.DMA)
638 for dma_op in dma_ops:
639 mem_area = dma_op.attrs["source"]
640 for tens in dma_op.inputs:
641 cycles[PassCycles.Npu] += tens.storage_size() / arch.memory_bandwidths_per_cycle[mem_area]
642
Tim Hall79d07d22020-04-27 18:20:16 +0100643 # apply the desired rewrites
644 for rewrite_op, tens, _, _, _, ps_to_rewrite in rewrite_list:
645 if ps != ps_to_rewrite:
646 continue
647 if rewrite_op == SchedulerRewrite.Nop:
648 pass # these are fine, no bandwidth changes
649 elif rewrite_op in (SchedulerRewrite.ChangeTensorSubPurpose,):
Diqing Zhonge168b962020-11-05 17:18:47 +0100650 if tens.purpose == TensorPurpose.FeatureMap:
651 bw = estimate_memory_bandwidth(
652 arch,
653 arch.fast_storage_mem_area,
654 BandwidthDirection.Read,
655 tens,
656 ifm_block,
657 replacement_read_bws[tens],
658 )
659 else:
660 bw = replacement_read_bws[tens]
661 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Read] += bw
Tim Hall79d07d22020-04-27 18:20:16 +0100662 replacement_read_bws[tens] = 0
663
664 for tens in ps.outputs:
665 if force_outputs_to_fast_storage:
Diqing Zhonge168b962020-11-05 17:18:47 +0100666 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Write] += estimate_memory_bandwidth(
667 arch, arch.fast_storage_mem_area, BandwidthDirection.Write, tens, ofm_block
668 )
Tim Hall79d07d22020-04-27 18:20:16 +0100669 else:
Diqing Zhonge168b962020-11-05 17:18:47 +0100670 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += estimate_memory_bandwidth(
671 arch, tens.mem_area, BandwidthDirection.Write, tens, ofm_block
672 )
Tim Hall79d07d22020-04-27 18:20:16 +0100673
674 for tens in ps.intermediates:
675 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
676
677 if tens in replacement_read_bws:
678 bw = replacement_read_bws[tens]
679 else:
680 bw = tens.bandwidth()
681
682 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += bw
683
684 for tens in ps.inputs:
Diqing Zhonge168b962020-11-05 17:18:47 +0100685 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += estimate_memory_bandwidth(
686 arch, tens.mem_area, BandwidthDirection.Read, tens, ifm_block, replacement_read_bws.get(tens)
687 )
Tim Hall79d07d22020-04-27 18:20:16 +0100688
689 # quick build access counts for only current pass, even though these aren't the final numbers
Diqing Zhonge168b962020-11-05 17:18:47 +0100690 update_summary_cycles(arch, bws, cycles)
Tim Hall79d07d22020-04-27 18:20:16 +0100691
692 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple
693
694
Diqing Zhonge168b962020-11-05 17:18:47 +0100695def update_summary_cycles(arch, bws, cycles):
696 cycles[PassCycles.SramAccess] = np.sum(bws[MemArea.Sram]) / arch.memory_bandwidths_per_cycle[MemArea.Sram]
Tim Hall79d07d22020-04-27 18:20:16 +0100697 cycles[PassCycles.DramAccess] = np.sum(bws[MemArea.Dram]) / arch.memory_bandwidths_per_cycle[MemArea.Dram]
698 cycles[PassCycles.OnChipFlashAccess] = (
699 np.sum(bws[MemArea.OnChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OnChipFlash]
700 )
701 cycles[PassCycles.OffChipFlashAccess] = (
702 np.sum(bws[MemArea.OffChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OffChipFlash]
703 )
704
705 cycles[PassCycles.Total] = np.max(cycles[: PassCycles.Total])
706 return cycles
707
708
709def collate_stats_for_cascaded_pass(arch, bws, macs, cycles):
710 return bws, macs, cycles
711
712
713def performance_for_cascaded_pass(arch, cps):
714 total_bws = make_bandwidth_array()
715 total_macs = make_macs_array()
716 total_cycles = make_cycles_array()
717
718 for ps in cps.passes:
719 bws, macs, cycles, blocks, _, _ = performance_metrics_for_pass(arch, ps)
720 ps.bandwidths = bws
721 ps.macs = macs
722 ps.cycles = cycles
723 ps.n_blocks = blocks
724 total_bws += bws
725 total_macs += macs
726 total_cycles += cycles
727
728 bws, macs, cycles = collate_stats_for_cascaded_pass(arch, total_bws, total_macs, total_cycles)
729 cps.bandwidths = bws
730 cps.macs = macs
731 cps.cycles = cycles
732 return bws, macs, cycles
733
734
735def calc_performance_for_network(nng, arch):
736 total_bws = make_bandwidth_array()
737 total_macs = np.zeros(MacCount.Size)
738 total_cycles = np.zeros(PassCycles.Size)
739
740 for sg in nng.subgraphs:
741 for cps in sg.cascaded_passes:
742 bws, macs, cycles = performance_for_cascaded_pass(arch, cps)
743 total_bws += bws
744 total_macs += macs
745 total_cycles += cycles
Tim Hall79d07d22020-04-27 18:20:16 +0100746
747 nng.bandwidths = total_bws
748 nng.macs = total_macs
749 nng.cycles = total_cycles