blob: 80f2c2791d26da6c8946765323e0f938bc8a17dc [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 Cpu = auto()
64 SramAccess = auto()
65 DramAccess = auto()
66 OnChipFlashAccess = auto()
67 OffChipFlashAccess = auto()
68 Total = auto()
69 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +010070
71 def display_name(self):
72 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020073 "NPU",
Tim Hall79d07d22020-04-27 18:20:16 +010074 "CPU",
75 "SRAM Access",
Tim Hall79d07d22020-04-27 18:20:16 +010076 "DRAM Access",
77 "On-chip Flash Access",
78 "Off-chip Flash Access",
79 "Total",
80 "Size",
81 )[self.value]
82
83 def identifier_name(self):
84 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020085 "npu",
Tim Hall79d07d22020-04-27 18:20:16 +010086 "cpu",
87 "sram_access",
Tim Hall79d07d22020-04-27 18:20:16 +010088 "dram_access",
89 "on_chip_flash_access",
90 "off_chip_flash_access",
91 "total",
92 "size",
93 )[self.value]
94
95 @staticmethod
96 def all():
97 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020098 PassCycles.Npu,
Tim Hall79d07d22020-04-27 18:20:16 +010099 PassCycles.Cpu,
100 PassCycles.SramAccess,
101 PassCycles.DramAccess,
102 PassCycles.OnChipFlashAccess,
103 PassCycles.OffChipFlashAccess,
104 PassCycles.Total,
105 )
106
107
Diqing Zhonge168b962020-11-05 17:18:47 +0100108class MacCount(IntEnum):
Tim Hall79d07d22020-04-27 18:20:16 +0100109 NeuralNetworkMacs = 0
Diqing Zhonge168b962020-11-05 17:18:47 +0100110 HardwareMacs = auto()
111 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +0100112
113 def display_name(self):
114 return ("Neural Network Macs", "Hardware Macs", "Size")[self.value]
115
116 def identifier_name(self):
117 return ("nn_macs", "hardware_macs", "size")[self.value]
118
119 @staticmethod
120 def all():
121 return (MacCount.NeuralNetworkMacs, MacCount.HardwareMacs)
122
123
Diqing Zhonge168b962020-11-05 17:18:47 +0100124class BandwidthDirection(IntEnum):
Tim Hall79d07d22020-04-27 18:20:16 +0100125 Read = 0
Diqing Zhonge168b962020-11-05 17:18:47 +0100126 Write = auto()
127 Size = auto()
Tim Hall79d07d22020-04-27 18:20:16 +0100128
129 def display_name(self):
130 return self.name
131
132 def identifier_name(self):
133 return self.name.lower()
134
135 @staticmethod
136 def all():
137 return (BandwidthDirection.Read, BandwidthDirection.Write)
138
139
140def make_bandwidth_array():
141 return np.zeros((MemArea.Size, TensorPurpose.Size, BandwidthDirection.Size))
142
143
144def make_macs_array():
145 return np.zeros(MacCount.Size, np.int)
146
147
148def make_cycles_array():
149 return np.zeros(PassCycles.Size)
150
151
152def make_metrics_arrays():
153 return (make_bandwidth_array(), make_macs_array(), make_cycles_array())
154
155
156def get_n_blocks_and_area(
157 ifm_brick_size, ifm_height_width, orig_skirt, clamped_skirt, block_config, min_block_size, strides
158):
159
160 ifm_block_config = (block_config[0] * strides[1], block_config[1] * strides[2])
161
162 n_normal_blocks = []
163 remainder_size = []
164 for i in range(2):
165 non_skirt_dim = ifm_height_width[i] - orig_skirt[i] - orig_skirt[2 + i]
166 n_blocks = non_skirt_dim // ifm_block_config[i]
167 n_normal_blocks.append(n_blocks)
168 remainder_dim = numeric_util.round_up(
169 ((non_skirt_dim - n_blocks * ifm_block_config[i] - 1) // strides[i + 1]) + 1, min_block_size[i]
170 )
171 remainder_size.append(remainder_dim)
172
173 # this will actually calculate reads into the edge padding.
174
175 # there are four cases in total, handling the edges that will not fill a complete block.
176
177 # 0000000001
178 # 0000000001
179 # 0000000001
180 # 0000000001
181 # 0000000001
182 # 0000000001
183 # 2222222223
184 total_blocks = 0
185 total_area = 0
186
187 block_setup = (
188 (n_normal_blocks[0] * n_normal_blocks[1], block_config),
189 (1 * n_normal_blocks[1], (remainder_size[0], block_config[1])),
190 (n_normal_blocks[0] * 1, (block_config[0], remainder_size[1])),
191 (1 * 1, remainder_size),
192 )
193
194 for n_blocks, block_size in block_setup:
195 if block_size[0] == 0 or block_size[1] == 0:
196 continue
197 read_dims = [0, 0]
198 for i in range(2):
199 read_dims[i] = (
200 numeric_util.round_up(clamped_skirt[i], ifm_brick_size[i + 1])
201 + block_size[i] * strides[i + 1]
202 + numeric_util.round_up(clamped_skirt[2 + i], ifm_brick_size[i + 1])
203 )
204 assert n_blocks >= 0
205 total_blocks += n_blocks
206 total_area += n_blocks * read_dims[0] * read_dims[1]
207 assert total_blocks >= 1
208 return total_blocks, total_area, block_setup
209
210
Diqing Zhong42e833d2020-10-02 13:18:42 +0200211def get_ifm_block_depth(npu_block_type, ifm_depth, ifm_elemwidth, block_traversal, ofm_blk_depth):
212 ifm_blk_depth = ofm_blk_depth
213
214 if npu_block_type == NpuBlockType.ConvolutionMxN or npu_block_type == NpuBlockType.ReduceSum:
215 if ifm_elemwidth == 16 or block_traversal == TensorBlockTraversal.PartKernelFirst:
216 ifm_blk_depth = 16
217 elif ifm_elemwidth == 8:
218 ifm_blk_depth = 32
219 else:
220 ifm_blk_depth = 8
221
222 return min(ifm_depth, ifm_blk_depth)
223
224
225def estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200226 arch, npu_block_type, primary_op, num_elems, ifm_tensor, ofm_tensor, ifm2_tensor, use_acc_40bits=False
227):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100228 faf = None if primary_op.activation is None else primary_op.activation.op_type
Diqing Zhong09387e22020-09-28 18:46:22 +0200229 if npu_block_type == NpuBlockType.ElementWise and ifm_tensor.dtype == DataType.int32:
230 if ifm2_tensor is None:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200231 # Unary op
232 output_perf_index = 0
233 else:
234 # Binary op
235 output_perf_index = 1
Diqing Zhong09387e22020-09-28 18:46:22 +0200236 elif primary_op.type == Op.Mul and ofm_tensor.dtype == DataType.int32:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200237 output_perf_index = 2
Diqing Zhong09387e22020-09-28 18:46:22 +0200238 elif primary_op.type == Op.Mul or (
Diqing Zhonge8887a32020-09-24 09:53:48 +0200239 npu_block_type
240 in (
241 NpuBlockType.ConvolutionMxN,
242 NpuBlockType.ConvolutionDepthWise,
243 NpuBlockType.Pooling,
244 NpuBlockType.ReduceSum,
245 NpuBlockType.VectorProduct,
246 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200247 and use_acc_40bits
Diqing Zhonge8887a32020-09-24 09:53:48 +0200248 ):
249 output_perf_index = 3
Diqing Zhong09387e22020-09-28 18:46:22 +0200250 elif primary_op.type in (Op.Add, Op.Sub):
251 input_scale = ifm_tensor.quantization.scale_f32
252 input2_scale = ifm2_tensor.quantization.scale_f32
253 output_scale = ofm_tensor.quantization.scale_f32
Diqing Zhonge8887a32020-09-24 09:53:48 +0200254
255 if "resizebilinear" in primary_op.attrs:
256 output_scale = input2_scale
257
258 if None in (input_scale, input2_scale, output_scale) or input_scale == input2_scale:
259 # Simple Add/Sub
260 output_perf_index = 4
261 else:
262 # Advanced Add/Sub
263 output_perf_index = 5
Diqing Zhong09387e22020-09-28 18:46:22 +0200264 elif primary_op.type.is_maxpool_op():
Diqing Zhonge8887a32020-09-24 09:53:48 +0200265 output_perf_index = 6
266 else:
267 output_perf_index = 7
268
269 if faf in (Op.Sigmoid, Op.Tanh, Op.LUT):
270 activation_perf_index = 0
271 elif faf in (Op.Relu, Op.Relu6, Op.ReluN1To1):
272 activation_perf_index = 1
273 else:
274 activation_perf_index = 2
275
Diqing Zhonge8887a32020-09-24 09:53:48 +0200276 cycle_per_elem = max(
277 arch.output_cycles_per_elem[output_perf_index], arch.activation_cycles_per_elem[activation_perf_index]
278 )
279 return num_elems * cycle_per_elem
280
281
Diqing Zhong42e833d2020-10-02 13:18:42 +0200282def estimate_conv_pooling_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200283 arch, npu_block_type, primary_op, block_config: Block, block_traversal, kernel_dims, ifm_tensor, ofm_tensor
284):
Diqing Zhonge5204a62020-10-13 11:42:37 +0200285 ofm_ublock = Block(arch.config.ofm_ublock.width, arch.config.ofm_ublock.height, arch.config.ofm_ublock.depth)
286 ifm_tens_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
287 ofm_tens_shape = numeric_util.full_shape(4, ofm_tensor.shape, 1)
288
289 if (
290 arch.config.ofm_ublock.height == 2
291 and npu_block_type
292 in (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.VectorProduct)
293 and ofm_tens_shape[1] == 1
294 # Optimisation only applies for even width tensors
295 and ofm_tens_shape[2] % 2 == 0
296 and kernel_dims[0] == 1
297 ):
298 ofm_ublock.width = 4
299 ofm_ublock.height = 1
300 block_config.height = 1
301
Diqing Zhong09387e22020-09-28 18:46:22 +0200302 num_ublk = (
Diqing Zhonge5204a62020-10-13 11:42:37 +0200303 numeric_util.round_up_divide(block_config.width, ofm_ublock.width)
304 * (block_config.height // ofm_ublock.height)
305 * (block_config.depth // ofm_ublock.depth)
Diqing Zhong09387e22020-09-28 18:46:22 +0200306 )
307 num_ofm_blk = 0
308 total_cycles = 0
309 num_elems_blk = block_config.width * block_config.height * block_config.depth
Diqing Zhonge5204a62020-10-13 11:42:37 +0200310
Diqing Zhong09387e22020-09-28 18:46:22 +0200311 use_acc_40bits = is_acc_40bits_used(npu_block_type, ifm_tensor, ofm_tensor)
312
313 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
314 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
315 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
316 sub_kernel_x = [
317 min((kernel_dims[1] - i * sub_kernel_limits[1]), sub_kernel_limits[1]) for i in range(n_sub_kernels_x)
318 ]
319 sub_kernel_y = [
320 min((kernel_dims[0] - i * sub_kernel_limits[0]), sub_kernel_limits[0]) for i in range(n_sub_kernels_y)
321 ]
322 sub_kernel_size = (x * y for y in sub_kernel_y for x in sub_kernel_x)
323
Diqing Zhong42e833d2020-10-02 13:18:42 +0200324 ifm_blk_depth = get_ifm_block_depth(
325 npu_block_type, ifm_tens_shape[3], ifm_tensor.dtype.size_in_bits(), block_traversal, block_config.depth
326 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200327 cycles_dpu_blk = 0
328
329 for num_kernel_elems in sub_kernel_size:
330 if npu_block_type == NpuBlockType.Pooling:
331 cycles = max(4, num_kernel_elems) * num_ublk
332 if ifm_tensor.dtype.size_in_bits() == 16 and arch.accelerator_config != Accelerator.Ethos_U55_32:
333 cycles *= 2
334 elif npu_block_type == NpuBlockType.ConvolutionDepthWise:
335 cycles = 4 * numeric_util.round_up_divide(num_kernel_elems, 4) * num_ublk
336 if ifm_tensor.dtype.size_in_bits() == 16:
337 cycles *= 2
338 elif (
339 (npu_block_type == NpuBlockType.ConvolutionMxN and block_traversal != TensorBlockTraversal.PartKernelFirst)
340 or npu_block_type == NpuBlockType.VectorProduct
341 or npu_block_type == NpuBlockType.ReduceSum
342 ):
343 cycles = 4 * num_kernel_elems * num_ublk * numeric_util.round_up_divide(ifm_tens_shape[3], ifm_blk_depth)
344 else:
345 assert block_traversal == TensorBlockTraversal.PartKernelFirst
346 divider = 2 if ifm_tensor.dtype.size_in_bits() == 16 else 4
347 cycles = 4 * (
348 numeric_util.round_up_divide(num_kernel_elems, divider)
349 * numeric_util.round_up_divide(ifm_blk_depth, 8)
350 * num_ublk
351 * 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
367 if cycles_dpu_blk > cycles_output_blk:
368 total_cycles = cycles_dpu_blk * num_ofm_blk + cycles_output_blk
369 else:
370 total_cycles = cycles_output_blk * num_ofm_blk + cycles_dpu_blk
371
372 return total_cycles
373
374
Diqing Zhonge168b962020-11-05 17:18:47 +0100375def estimate_memory_bandwidth(arch, mem_area, direction, tensor, block_size: Block, replace_bw=None):
376 if tensor.format not in (TensorFormat.NHWC, TensorFormat.NHCWB16):
377 return tensor.bandwidth() if replace_bw is None else replace_bw
378
379 # Estimate memory transfer efficiency by calculating the burst length
380 # this is related to data format, block shape, and tensor shape, etc.
381 max_burst_len = 32 if mem_area == MemArea.Sram else 128
382 burst_len = 0
383 elem_size = tensor.dtype.size_in_bytes()
384 is_ifm = direction == BandwidthDirection.Read
385 tens = tensor.clone()
386 if not tens.avoid_NHCWB16:
387 tens.set_format(TensorFormat.NHCWB16, arch)
388
389 if tens.format == TensorFormat.NHCWB16:
390 if tens.get_strides()[1] == block_size.depth:
391 burst_len = elem_size * block_size.depth * block_size.width
392 elif is_ifm:
393 burst_len = 16 * elem_size * block_size.width
394 else:
395 burst_len = 16 * elem_size * block_size.width * arch.ncores
396 else:
397 assert tens.format == TensorFormat.NHWC
398 if is_ifm:
399 if tens.get_strides()[3] == block_size.depth:
400 burst_len = elem_size * block_size.depth * block_size.width
401 else:
402 burst_len = elem_size * block_size.depth
403 else:
404 if block_size.depth <= 16 and tens.get_strides()[3] == block_size.depth:
405 burst_len = elem_size * block_size.depth * block_size.width
406 else:
407 burst_len = min(64, 16 * elem_size * arch.ncores, block_size.depth * elem_size)
408
409 burst_len = min(max_burst_len, burst_len)
410 bw = tens.bandwidth() if replace_bw is None else replace_bw
411
412 return bw * (max_burst_len / burst_len)
413
414
Tim Hall79d07d22020-04-27 18:20:16 +0100415def performance_metrics_for_pass(arch, ps, block_config=None, rewrite_list=[], force_outputs_to_fast_storage=False):
416 if block_config is None:
417 block_config = ps.block_config
418 bws = make_bandwidth_array()
419 macs = make_macs_array()
420 cycles = make_cycles_array()
421 blocks = 0
422 ifm_read_multiple = 1
423 weight_read_multiple = 0
424
425 if ps.placement in set((PassPlacement.MemoryOnly, PassPlacement.StartupInit)):
426 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple # nothing real happening in this pass
427
428 min_block_size = arch.min_block_sizes[ps.npu_block_type]
429
430 skirt = (0, 0, 0, 0)
431 explicit_padding = (0, 0, 0, 0)
432 primary_op = ps.primary_op
433 replacement_read_bws = {}
Diqing Zhonge168b962020-11-05 17:18:47 +0100434 ofm_block = Block(block_config[1], block_config[0], block_config[3])
435 ifm_block = Block(block_config[1], block_config[0], block_config[3])
436
Charles Xub02c8d92020-06-25 16:05:25 +0200437 if ps.placement == PassPlacement.Cpu:
438 cycles[PassCycles.Cpu] = arch.cpu_cycle_estimate(ps.ops[0])
439 elif primary_op:
Tim Hall79d07d22020-04-27 18:20:16 +0100440 skirt = primary_op.attrs.get("skirt", skirt)
441 explicit_padding = primary_op.attrs.get("explicit_padding", explicit_padding)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200442 assert primary_op.type.npu_block_type == ps.npu_block_type
443 npu_block_type = primary_op.type.npu_block_type
Diqing Zhong42e833d2020-10-02 13:18:42 +0200444 block_traversal = TensorBlockTraversal.Default
Tim Hall79d07d22020-04-27 18:20:16 +0100445
446 ifm_tensor, _, weight_tensor, ofm_tensor = ps.get_primary_op_ifm_ifm2_weights_ofm()
Diqing Zhonge168b962020-11-05 17:18:47 +0100447 ifm_tensor_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100448
Tim Hallc30f4952020-06-15 20:47:35 +0100449 if npu_block_type in set(
Diqing Zhong09387e22020-09-28 18:46:22 +0200450 (
451 NpuBlockType.ConvolutionMxN,
452 NpuBlockType.ConvolutionDepthWise,
453 NpuBlockType.Pooling,
454 NpuBlockType.ReduceSum,
455 )
Tim Hallc30f4952020-06-15 20:47:35 +0100456 ):
Charles Xu3e9c4342020-04-22 08:31:43 +0200457 # extent the ifm to full dimension
458 ifm_tensor_brick_size = tuple(numeric_util.full_shape(4, list(ifm_tensor.brick_size), 1))
Charles Xu3e9c4342020-04-22 08:31:43 +0200459 ifm_tensor_bandwidth_shape = numeric_util.full_shape(4, ifm_tensor.bandwidth_shape, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100460
Diqing Zhong42e833d2020-10-02 13:18:42 +0200461 batch_size = ifm_tensor_shape[0]
Charles Xu3e9c4342020-04-22 08:31:43 +0200462 ifm_depth = ifm_tensor_bandwidth_shape[3]
Tim Hall79d07d22020-04-27 18:20:16 +0100463
464 # add in padding
465 ifm_tensor_shape[1] += explicit_padding[0] + explicit_padding[2] # height += top and bottom
466 ifm_tensor_shape[2] += explicit_padding[1] + explicit_padding[3] # width += left and right
467
468 strides = primary_op.attrs["strides"]
469 if npu_block_type != NpuBlockType.Pooling:
Diqing Zhong09387e22020-09-28 18:46:22 +0200470 if npu_block_type == NpuBlockType.ReduceSum:
471 block_traversal = TensorBlockTraversal.DepthFirst
472 weight_tensor_shape = [1, 1, ifm_tensor.shape[3], ofm_tensor.shape[3]]
473 weight_tensor_bandwidth_shape = [0] * 4
474 weight_tensor_element_size = 0
475 weight_tensor_bandwidth_compression_scale = 0.0
476 else:
477 block_traversal = weight_tensor.block_traversal
478 weight_tensor_shape = weight_tensor.shape
479 weight_tensor_bandwidth_shape = weight_tensor.bandwidth_shape
480 weight_tensor_element_size = weight_tensor.element_size()
481 weight_tensor_bandwidth_compression_scale = weight_tensor.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100482 nn_ops = (
483 int(ofm_tensor.shape[0])
484 * int(ofm_tensor.shape[1])
485 * int(ofm_tensor.shape[2])
486 * int(weight_tensor_shape[0])
487 * int(weight_tensor_shape[1])
488 * int(weight_tensor_shape[2])
489 * int(weight_tensor_shape[3])
Tim Hall79d07d22020-04-27 18:20:16 +0100490 )
491 else:
492 weight_tensor_shape = [
493 primary_op.attrs["ksize"][1],
494 primary_op.attrs["ksize"][2],
495 1,
496 ifm_tensor_shape[3],
497 ]
498 weight_tensor_bandwidth_shape = weight_tensor_shape
499 weight_tensor_element_size = 0
500 weight_tensor_bandwidth_compression_scale = 0.0
501 nn_ops = 0 # pooling doesn't count as NN ops
502
503 kernel_dims = weight_tensor_shape[:2]
504
505 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
506 # count the sub kernels; the IFM block needs to be refetched for each of them
507 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
508 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
509 n_sub_kernels = n_sub_kernels_y * n_sub_kernels_x
510
511 clamped_skirt = list(skirt)
512 clamped_skirt[2] = min(clamped_skirt[2], sub_kernel_limits[0] - 1 - clamped_skirt[0])
513 clamped_skirt[3] = min(clamped_skirt[3], sub_kernel_limits[1] - 1 - clamped_skirt[1])
514 n_blocks, area, block_setup = get_n_blocks_and_area(
Charles Xu3e9c4342020-04-22 08:31:43 +0200515 ifm_tensor_brick_size,
Tim Hall79d07d22020-04-27 18:20:16 +0100516 ifm_tensor_shape[1:3],
517 skirt,
518 clamped_skirt,
519 block_config,
520 min_block_size,
521 strides,
522 )
523
Diqing Zhonge168b962020-11-05 17:18:47 +0100524 blocks = n_blocks * numeric_util.round_up_divide(weight_tensor_shape[3], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100525
Diqing Zhonge168b962020-11-05 17:18:47 +0100526 n_weight_stages = numeric_util.round_up_divide(weight_tensor_bandwidth_shape[3], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100527 if npu_block_type == NpuBlockType.ConvolutionDepthWise or npu_block_type == NpuBlockType.Pooling:
528 n_weight_stages = 1 # force to no reread
529
530 ifm_tensor_bw = (
531 n_sub_kernels
532 * batch_size
533 * area
534 * ifm_depth
535 * n_weight_stages
536 * ifm_tensor.element_size()
537 * ifm_tensor.bandwidth_compression_scale
538 )
539 replacement_read_bws[ifm_tensor] = ifm_tensor_bw
540 ifm_read_multiple = n_weight_stages
541
542 replacement_read_bws[weight_tensor] = (
543 batch_size
544 * shape_num_elements(weight_tensor_bandwidth_shape)
545 * weight_tensor_element_size
546 * weight_tensor_bandwidth_compression_scale
547 * n_blocks
548 ) # read once per block and batch
549 weight_read_multiple = n_blocks
550
551 n_kernel_xy = kernel_dims[0] * kernel_dims[1]
552 n_input_channels_at_a_time = block_config[2]
553
Diqing Zhong09387e22020-09-28 18:46:22 +0200554 if npu_block_type == NpuBlockType.Pooling or block_traversal in set(
Tim Hall79d07d22020-04-27 18:20:16 +0100555 (TensorBlockTraversal.PartKernelFirst, TensorBlockTraversal.DepthWise)
556 ):
557 n_input_channels_at_a_time = numeric_util.round_up_divide(n_input_channels_at_a_time, 4)
558 n_kernel_xy = max(
559 n_kernel_xy, 4
560 ) # need at least 4, as this is the minimum duty cycle for secondary accumulator writes
561 if weight_tensor is not None:
Diego Russoea6111a2020-04-14 18:41:58 +0100562 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 +0100563
564 num_mac_ops = 0
565 for n_blocks_for_size, block_size in block_setup:
566 num_mac_ops += (
567 batch_size
568 * n_blocks_for_size
569 * block_size[0]
570 * block_size[1]
571 * numeric_util.round_up(weight_tensor_shape[2], n_input_channels_at_a_time)
Diqing Zhonge168b962020-11-05 17:18:47 +0100572 * numeric_util.round_up(weight_tensor_shape[3], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100573 * n_kernel_xy
574 )
575
Tim Hall79d07d22020-04-27 18:20:16 +0100576 macs[MacCount.NeuralNetworkMacs] += nn_ops
577 macs[MacCount.HardwareMacs] += num_mac_ops
Diqing Zhong42e833d2020-10-02 13:18:42 +0200578 cycles[PassCycles.Npu] = estimate_conv_pooling_cycles(
Diqing Zhonge168b962020-11-05 17:18:47 +0100579 arch, npu_block_type, primary_op, ofm_block, block_traversal, kernel_dims, ifm_tensor, ofm_tensor,
Diqing Zhong09387e22020-09-28 18:46:22 +0200580 )
Tim Hall79d07d22020-04-27 18:20:16 +0100581 elif npu_block_type == NpuBlockType.VectorProduct:
582 nn_macs = (
583 ifm_tensor.shape[0]
584 * numeric_util.round_up(weight_tensor.shape[-2], block_config[2])
585 * numeric_util.round_up(weight_tensor.shape[-1], block_config[3])
586 )
587 num_mac_ops = nn_macs
Diqing Zhonge168b962020-11-05 17:18:47 +0100588 block_traversal = weight_tensor.block_traversal
Tim Hall79d07d22020-04-27 18:20:16 +0100589
Diqing Zhong42e833d2020-10-02 13:18:42 +0200590 cycles[PassCycles.Npu] = estimate_conv_pooling_cycles(
Diqing Zhonge168b962020-11-05 17:18:47 +0100591 arch, npu_block_type, primary_op, ofm_block, block_traversal, [1, 1], ifm_tensor, ofm_tensor,
Diqing Zhong09387e22020-09-28 18:46:22 +0200592 )
Tim Hall79d07d22020-04-27 18:20:16 +0100593 macs[MacCount.NeuralNetworkMacs] += nn_macs
594 macs[MacCount.HardwareMacs] += num_mac_ops
595
Diqing Zhonge168b962020-11-05 17:18:47 +0100596 blocks = 1 * numeric_util.round_up_divide(weight_tensor.shape[-1], ofm_block.depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100597
598 non_zero_fraction = 1.0
599 if ifm_tensor.values is not None:
600 nz_vector = np.amax(ifm_tensor.values != 0, axis=0) # max across batch axis
601 non_zero_fraction = np.average(nz_vector)
602
603 replacement_read_bws[ifm_tensor] = ifm_tensor.bandwidth()
604 replacement_read_bws[weight_tensor] = weight_tensor.bandwidth() * non_zero_fraction
605 ifm_read_multiple = 1
606 weight_read_multiple = non_zero_fraction
Diqing Zhonge8887a32020-09-24 09:53:48 +0200607 elif npu_block_type == NpuBlockType.ElementWise:
Tim Hall79d07d22020-04-27 18:20:16 +0100608 # Work out how many elements we have and calculate performance.
Diqing Zhong42e833d2020-10-02 13:18:42 +0200609 cycles[PassCycles.Npu] = estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200610 arch, npu_block_type, primary_op, ofm_tensor.elements(), ps.ifm_tensor, ps.ofm_tensor, ps.ifm2_tensor
611 )
Diqing Zhong42e833d2020-10-02 13:18:42 +0200612
Diqing Zhonge168b962020-11-05 17:18:47 +0100613 ifm_block_depth = get_ifm_block_depth(
614 npu_block_type, ifm_tensor_shape[3], ifm_tensor.dtype.size_in_bits(), block_traversal, ofm_block.depth
615 )
616 ifm_block = arch.get_ifm_block_size(ifm_block_depth, ofm_block, primary_op.kernel)
617
Diqing Zhong42e833d2020-10-02 13:18:42 +0200618 prev_npu_pass = next((npu_ps for npu_ps in ps.dag_predecessors if npu_ps.placement is PassPlacement.Npu), None)
619 if prev_npu_pass is None:
620 # cycles for DMA ops in first pass
621 dma_ops = (op for op in ps.ops if op.type == Op.DMA)
622 for dma_op in dma_ops:
623 mem_area = dma_op.attrs["source"]
624 for tens in dma_op.inputs:
625 cycles[PassCycles.Npu] += tens.storage_size() / arch.memory_bandwidths_per_cycle[mem_area]
626
Tim Hall79d07d22020-04-27 18:20:16 +0100627 # apply the desired rewrites
628 for rewrite_op, tens, _, _, _, ps_to_rewrite in rewrite_list:
629 if ps != ps_to_rewrite:
630 continue
631 if rewrite_op == SchedulerRewrite.Nop:
632 pass # these are fine, no bandwidth changes
633 elif rewrite_op in (SchedulerRewrite.ChangeTensorSubPurpose,):
Diqing Zhonge168b962020-11-05 17:18:47 +0100634 if tens.purpose == TensorPurpose.FeatureMap:
635 bw = estimate_memory_bandwidth(
636 arch,
637 arch.fast_storage_mem_area,
638 BandwidthDirection.Read,
639 tens,
640 ifm_block,
641 replacement_read_bws[tens],
642 )
643 else:
644 bw = replacement_read_bws[tens]
645 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Read] += bw
Tim Hall79d07d22020-04-27 18:20:16 +0100646 replacement_read_bws[tens] = 0
647
648 for tens in ps.outputs:
649 if force_outputs_to_fast_storage:
Diqing Zhonge168b962020-11-05 17:18:47 +0100650 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Write] += estimate_memory_bandwidth(
651 arch, arch.fast_storage_mem_area, BandwidthDirection.Write, tens, ofm_block
652 )
Tim Hall79d07d22020-04-27 18:20:16 +0100653 else:
Diqing Zhonge168b962020-11-05 17:18:47 +0100654 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += estimate_memory_bandwidth(
655 arch, tens.mem_area, BandwidthDirection.Write, tens, ofm_block
656 )
Tim Hall79d07d22020-04-27 18:20:16 +0100657
658 for tens in ps.intermediates:
659 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
660
661 if tens in replacement_read_bws:
662 bw = replacement_read_bws[tens]
663 else:
664 bw = tens.bandwidth()
665
666 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += bw
667
668 for tens in ps.inputs:
Diqing Zhonge168b962020-11-05 17:18:47 +0100669 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += estimate_memory_bandwidth(
670 arch, tens.mem_area, BandwidthDirection.Read, tens, ifm_block, replacement_read_bws.get(tens)
671 )
Tim Hall79d07d22020-04-27 18:20:16 +0100672
673 # quick build access counts for only current pass, even though these aren't the final numbers
Diqing Zhonge168b962020-11-05 17:18:47 +0100674 update_summary_cycles(arch, bws, cycles)
Tim Hall79d07d22020-04-27 18:20:16 +0100675
676 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple
677
678
Diqing Zhonge168b962020-11-05 17:18:47 +0100679def update_summary_cycles(arch, bws, cycles):
680 cycles[PassCycles.SramAccess] = np.sum(bws[MemArea.Sram]) / arch.memory_bandwidths_per_cycle[MemArea.Sram]
Tim Hall79d07d22020-04-27 18:20:16 +0100681 cycles[PassCycles.DramAccess] = np.sum(bws[MemArea.Dram]) / arch.memory_bandwidths_per_cycle[MemArea.Dram]
682 cycles[PassCycles.OnChipFlashAccess] = (
683 np.sum(bws[MemArea.OnChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OnChipFlash]
684 )
685 cycles[PassCycles.OffChipFlashAccess] = (
686 np.sum(bws[MemArea.OffChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OffChipFlash]
687 )
688
689 cycles[PassCycles.Total] = np.max(cycles[: PassCycles.Total])
690 return cycles
691
692
693def collate_stats_for_cascaded_pass(arch, bws, macs, cycles):
694 return bws, macs, cycles
695
696
697def performance_for_cascaded_pass(arch, cps):
698 total_bws = make_bandwidth_array()
699 total_macs = make_macs_array()
700 total_cycles = make_cycles_array()
701
702 for ps in cps.passes:
703 bws, macs, cycles, blocks, _, _ = performance_metrics_for_pass(arch, ps)
704 ps.bandwidths = bws
705 ps.macs = macs
706 ps.cycles = cycles
707 ps.n_blocks = blocks
708 total_bws += bws
709 total_macs += macs
710 total_cycles += cycles
711
712 bws, macs, cycles = collate_stats_for_cascaded_pass(arch, total_bws, total_macs, total_cycles)
713 cps.bandwidths = bws
714 cps.macs = macs
715 cps.cycles = cycles
716 return bws, macs, cycles
717
718
719def calc_performance_for_network(nng, arch):
720 total_bws = make_bandwidth_array()
721 total_macs = np.zeros(MacCount.Size)
722 total_cycles = np.zeros(PassCycles.Size)
723
724 for sg in nng.subgraphs:
725 for cps in sg.cascaded_passes:
726 bws, macs, cycles = performance_for_cascaded_pass(arch, cps)
727 total_bws += bws
728 total_macs += macs
729 total_cycles += cycles
Tim Hall79d07d22020-04-27 18:20:16 +0100730
731 nng.bandwidths = total_bws
732 nng.macs = total_macs
733 nng.cycles = total_cycles