blob: 1957952052239f3dd33d44faa26f2b2d37f6901c [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.
Tim Hall79d07d22020-04-27 18:20:16 +010022import enum
Diego Russoea6111a2020-04-14 18:41:58 +010023
Tim Hall79d07d22020-04-27 18:20:16 +010024import numpy as np
Diego Russoea6111a2020-04-14 18:41:58 +010025
26from . import numeric_util
Diqing Zhong09387e22020-09-28 18:46:22 +020027from .architecture_features import Accelerator
Diego Russoe8a10452020-04-21 17:39:10 +010028from .architecture_features import Block
Diqing Zhonge8887a32020-09-24 09:53:48 +020029from .data_type import DataType
Diego Russoe8a10452020-04-21 17:39:10 +010030from .nn_graph import PassPlacement
31from .nn_graph import SchedulerRewrite
Diego Russoea6111a2020-04-14 18:41:58 +010032from .operation import NpuBlockType
Diqing Zhonge8887a32020-09-24 09:53:48 +020033from .operation import Op
Diqing Zhong09387e22020-09-28 18:46:22 +020034from .shared_buffer_allocation import is_acc_40bits_used
Diego Russoe8a10452020-04-21 17:39:10 +010035from .tensor import MemArea
36from .tensor import shape_num_elements
37from .tensor import TensorBlockTraversal
38from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010039
40
41def rolling_buffer_dims_from_passes(arch, ps1, block_config_ps1, ps2, block_config_ps2):
Tim Hall79d07d22020-04-27 18:20:16 +010042 ofm_block = Block(block_config_ps2[-3], block_config_ps2[-4], block_config_ps2[-1])
Tim Hall4ed38bc2020-10-20 18:54:20 +010043 kernel = ps2.primary_op.kernel
Tim Hall79d07d22020-04-27 18:20:16 +010044
45 if ps2.npu_block_type in set((NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct)):
Louis Verhaard93dc5532020-06-07 12:40:18 +020046 op = ps2.primary_op
Louis Verhaardaee5d752020-09-30 09:01:52 +020047 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 +010048 else:
49 ifm_block_depth = block_config_ps2[-1]
50
Louis Verhaard93dc5532020-06-07 12:40:18 +020051 ifm_block = arch.get_ifm_block_size(ifm_block_depth, ofm_block, kernel, arch.ofm_block_max)
Tim Hall79d07d22020-04-27 18:20:16 +010052
53 # The performed height calculation is for worst case
54 height = numeric_util.round_up(ifm_block.height + block_config_ps1[0], block_config_ps1[0])
55 width = ifm_block.width
Louis Verhaard93dc5532020-06-07 12:40:18 +020056 return [height, width]
Tim Hall79d07d22020-04-27 18:20:16 +010057
58
59class PassCycles(enum.IntEnum):
Diqing Zhong42e833d2020-10-02 13:18:42 +020060 Npu = 0
61 Cpu = 1
62 SramAccess = 2
63 TotalPerPass = 3
64 DramAccess = 4
65 OnChipFlashAccess = 5
66 OffChipFlashAccess = 6
67 Total = 7
68 Size = 8
Tim Hall79d07d22020-04-27 18:20:16 +010069
70 def display_name(self):
71 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020072 "NPU",
Tim Hall79d07d22020-04-27 18:20:16 +010073 "CPU",
74 "SRAM Access",
75 "Total per Pass",
76 "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",
88 "total_per_pass",
89 "dram_access",
90 "on_chip_flash_access",
91 "off_chip_flash_access",
92 "total",
93 "size",
94 )[self.value]
95
96 @staticmethod
97 def all():
98 return (
Diqing Zhong42e833d2020-10-02 13:18:42 +020099 PassCycles.Npu,
Tim Hall79d07d22020-04-27 18:20:16 +0100100 PassCycles.Cpu,
101 PassCycles.SramAccess,
102 PassCycles.DramAccess,
103 PassCycles.OnChipFlashAccess,
104 PassCycles.OffChipFlashAccess,
105 PassCycles.Total,
106 )
107
108
109class MacCount(enum.IntEnum):
110 NeuralNetworkMacs = 0
111 HardwareMacs = 1
112 Size = 2
113
114 def display_name(self):
115 return ("Neural Network Macs", "Hardware Macs", "Size")[self.value]
116
117 def identifier_name(self):
118 return ("nn_macs", "hardware_macs", "size")[self.value]
119
120 @staticmethod
121 def all():
122 return (MacCount.NeuralNetworkMacs, MacCount.HardwareMacs)
123
124
125class BandwidthDirection(enum.IntEnum):
126 Read = 0
127 Write = 1
128 Size = 2
129
130 def display_name(self):
131 return self.name
132
133 def identifier_name(self):
134 return self.name.lower()
135
136 @staticmethod
137 def all():
138 return (BandwidthDirection.Read, BandwidthDirection.Write)
139
140
141def make_bandwidth_array():
142 return np.zeros((MemArea.Size, TensorPurpose.Size, BandwidthDirection.Size))
143
144
145def make_macs_array():
146 return np.zeros(MacCount.Size, np.int)
147
148
149def make_cycles_array():
150 return np.zeros(PassCycles.Size)
151
152
153def make_metrics_arrays():
154 return (make_bandwidth_array(), make_macs_array(), make_cycles_array())
155
156
157def get_n_blocks_and_area(
158 ifm_brick_size, ifm_height_width, orig_skirt, clamped_skirt, block_config, min_block_size, strides
159):
160
161 ifm_block_config = (block_config[0] * strides[1], block_config[1] * strides[2])
162
163 n_normal_blocks = []
164 remainder_size = []
165 for i in range(2):
166 non_skirt_dim = ifm_height_width[i] - orig_skirt[i] - orig_skirt[2 + i]
167 n_blocks = non_skirt_dim // ifm_block_config[i]
168 n_normal_blocks.append(n_blocks)
169 remainder_dim = numeric_util.round_up(
170 ((non_skirt_dim - n_blocks * ifm_block_config[i] - 1) // strides[i + 1]) + 1, min_block_size[i]
171 )
172 remainder_size.append(remainder_dim)
173
174 # this will actually calculate reads into the edge padding.
175
176 # there are four cases in total, handling the edges that will not fill a complete block.
177
178 # 0000000001
179 # 0000000001
180 # 0000000001
181 # 0000000001
182 # 0000000001
183 # 0000000001
184 # 2222222223
185 total_blocks = 0
186 total_area = 0
187
188 block_setup = (
189 (n_normal_blocks[0] * n_normal_blocks[1], block_config),
190 (1 * n_normal_blocks[1], (remainder_size[0], block_config[1])),
191 (n_normal_blocks[0] * 1, (block_config[0], remainder_size[1])),
192 (1 * 1, remainder_size),
193 )
194
195 for n_blocks, block_size in block_setup:
196 if block_size[0] == 0 or block_size[1] == 0:
197 continue
198 read_dims = [0, 0]
199 for i in range(2):
200 read_dims[i] = (
201 numeric_util.round_up(clamped_skirt[i], ifm_brick_size[i + 1])
202 + block_size[i] * strides[i + 1]
203 + numeric_util.round_up(clamped_skirt[2 + i], ifm_brick_size[i + 1])
204 )
205 assert n_blocks >= 0
206 total_blocks += n_blocks
207 total_area += n_blocks * read_dims[0] * read_dims[1]
208 assert total_blocks >= 1
209 return total_blocks, total_area, block_setup
210
211
Diqing Zhong42e833d2020-10-02 13:18:42 +0200212def get_ifm_block_depth(npu_block_type, ifm_depth, ifm_elemwidth, block_traversal, ofm_blk_depth):
213 ifm_blk_depth = ofm_blk_depth
214
215 if npu_block_type == NpuBlockType.ConvolutionMxN or npu_block_type == NpuBlockType.ReduceSum:
216 if ifm_elemwidth == 16 or block_traversal == TensorBlockTraversal.PartKernelFirst:
217 ifm_blk_depth = 16
218 elif ifm_elemwidth == 8:
219 ifm_blk_depth = 32
220 else:
221 ifm_blk_depth = 8
222
223 return min(ifm_depth, ifm_blk_depth)
224
225
226def estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200227 arch, npu_block_type, primary_op, num_elems, ifm_tensor, ofm_tensor, ifm2_tensor, use_acc_40bits=False
228):
Diqing Zhonge8887a32020-09-24 09:53:48 +0200229 faf = primary_op.activation
Diqing Zhong09387e22020-09-28 18:46:22 +0200230 if npu_block_type == NpuBlockType.ElementWise and ifm_tensor.dtype == DataType.int32:
231 if ifm2_tensor is None:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200232 # Unary op
233 output_perf_index = 0
234 else:
235 # Binary op
236 output_perf_index = 1
Diqing Zhong09387e22020-09-28 18:46:22 +0200237 elif primary_op.type == Op.Mul and ofm_tensor.dtype == DataType.int32:
Diqing Zhonge8887a32020-09-24 09:53:48 +0200238 output_perf_index = 2
Diqing Zhong09387e22020-09-28 18:46:22 +0200239 elif primary_op.type == Op.Mul or (
Diqing Zhonge8887a32020-09-24 09:53:48 +0200240 npu_block_type
241 in (
242 NpuBlockType.ConvolutionMxN,
243 NpuBlockType.ConvolutionDepthWise,
244 NpuBlockType.Pooling,
245 NpuBlockType.ReduceSum,
246 NpuBlockType.VectorProduct,
247 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200248 and use_acc_40bits
Diqing Zhonge8887a32020-09-24 09:53:48 +0200249 ):
250 output_perf_index = 3
Diqing Zhong09387e22020-09-28 18:46:22 +0200251 elif primary_op.type in (Op.Add, Op.Sub):
252 input_scale = ifm_tensor.quantization.scale_f32
253 input2_scale = ifm2_tensor.quantization.scale_f32
254 output_scale = ofm_tensor.quantization.scale_f32
Diqing Zhonge8887a32020-09-24 09:53:48 +0200255
256 if "resizebilinear" in primary_op.attrs:
257 output_scale = input2_scale
258
259 if None in (input_scale, input2_scale, output_scale) or input_scale == input2_scale:
260 # Simple Add/Sub
261 output_perf_index = 4
262 else:
263 # Advanced Add/Sub
264 output_perf_index = 5
Diqing Zhong09387e22020-09-28 18:46:22 +0200265 elif primary_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
270 if faf in (Op.Sigmoid, Op.Tanh, Op.LUT):
271 activation_perf_index = 0
272 elif faf in (Op.Relu, Op.Relu6, Op.ReluN1To1):
273 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 )
280 return num_elems * cycle_per_elem
281
282
Diqing Zhong42e833d2020-10-02 13:18:42 +0200283def estimate_conv_pooling_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200284 arch, npu_block_type, primary_op, block_config: Block, block_traversal, kernel_dims, ifm_tensor, ofm_tensor
285):
286 num_ublk = (
287 (block_config.width // arch.config.ofm_ublock.width)
288 * (block_config.height // arch.config.ofm_ublock.height)
289 * (block_config.depth // arch.config.ofm_ublock.depth)
290 )
291 num_ofm_blk = 0
292 total_cycles = 0
293 num_elems_blk = block_config.width * block_config.height * block_config.depth
294 ifm_tens_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
295 ofm_tens_shape = numeric_util.full_shape(4, ofm_tensor.shape, 1)
296 use_acc_40bits = is_acc_40bits_used(npu_block_type, ifm_tensor, ofm_tensor)
297
298 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
299 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
300 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
301 sub_kernel_x = [
302 min((kernel_dims[1] - i * sub_kernel_limits[1]), sub_kernel_limits[1]) for i in range(n_sub_kernels_x)
303 ]
304 sub_kernel_y = [
305 min((kernel_dims[0] - i * sub_kernel_limits[0]), sub_kernel_limits[0]) for i in range(n_sub_kernels_y)
306 ]
307 sub_kernel_size = (x * y for y in sub_kernel_y for x in sub_kernel_x)
308
Diqing Zhong42e833d2020-10-02 13:18:42 +0200309 ifm_blk_depth = get_ifm_block_depth(
310 npu_block_type, ifm_tens_shape[3], ifm_tensor.dtype.size_in_bits(), block_traversal, block_config.depth
311 )
Diqing Zhong09387e22020-09-28 18:46:22 +0200312 cycles_dpu_blk = 0
313
314 for num_kernel_elems in sub_kernel_size:
315 if npu_block_type == NpuBlockType.Pooling:
316 cycles = max(4, num_kernel_elems) * num_ublk
317 if ifm_tensor.dtype.size_in_bits() == 16 and arch.accelerator_config != Accelerator.Ethos_U55_32:
318 cycles *= 2
319 elif npu_block_type == NpuBlockType.ConvolutionDepthWise:
320 cycles = 4 * numeric_util.round_up_divide(num_kernel_elems, 4) * num_ublk
321 if ifm_tensor.dtype.size_in_bits() == 16:
322 cycles *= 2
323 elif (
324 (npu_block_type == NpuBlockType.ConvolutionMxN and block_traversal != TensorBlockTraversal.PartKernelFirst)
325 or npu_block_type == NpuBlockType.VectorProduct
326 or npu_block_type == NpuBlockType.ReduceSum
327 ):
328 cycles = 4 * num_kernel_elems * num_ublk * numeric_util.round_up_divide(ifm_tens_shape[3], ifm_blk_depth)
329 else:
330 assert block_traversal == TensorBlockTraversal.PartKernelFirst
331 divider = 2 if ifm_tensor.dtype.size_in_bits() == 16 else 4
332 cycles = 4 * (
333 numeric_util.round_up_divide(num_kernel_elems, divider)
334 * numeric_util.round_up_divide(ifm_blk_depth, 8)
335 * num_ublk
336 * numeric_util.round_up_divide(ifm_tens_shape[3], ifm_blk_depth)
337 )
338 cycles_dpu_blk += cycles
339
340 cycles_dpu_blk /= arch.ncores
341
342 num_ofm_blk = (
343 numeric_util.round_up_divide(ofm_tens_shape[1], block_config.height)
344 * numeric_util.round_up_divide(ofm_tens_shape[2], block_config.width)
345 * numeric_util.round_up_divide(ofm_tens_shape[3], block_config.depth)
346 )
347
Diqing Zhong42e833d2020-10-02 13:18:42 +0200348 cycles_output_blk = estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200349 arch, npu_block_type, primary_op, num_elems_blk, ifm_tensor, ofm_tensor, None, use_acc_40bits
350 )
351
352 if cycles_dpu_blk > cycles_output_blk:
353 total_cycles = cycles_dpu_blk * num_ofm_blk + cycles_output_blk
354 else:
355 total_cycles = cycles_output_blk * num_ofm_blk + cycles_dpu_blk
356
357 return total_cycles
358
359
Tim Hall79d07d22020-04-27 18:20:16 +0100360def performance_metrics_for_pass(arch, ps, block_config=None, rewrite_list=[], force_outputs_to_fast_storage=False):
361 if block_config is None:
362 block_config = ps.block_config
363 bws = make_bandwidth_array()
364 macs = make_macs_array()
365 cycles = make_cycles_array()
366 blocks = 0
367 ifm_read_multiple = 1
368 weight_read_multiple = 0
369
370 if ps.placement in set((PassPlacement.MemoryOnly, PassPlacement.StartupInit)):
371 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple # nothing real happening in this pass
372
373 min_block_size = arch.min_block_sizes[ps.npu_block_type]
374
375 skirt = (0, 0, 0, 0)
376 explicit_padding = (0, 0, 0, 0)
377 primary_op = ps.primary_op
378 replacement_read_bws = {}
Charles Xub02c8d92020-06-25 16:05:25 +0200379 if ps.placement == PassPlacement.Cpu:
380 cycles[PassCycles.Cpu] = arch.cpu_cycle_estimate(ps.ops[0])
381 elif primary_op:
Tim Hall79d07d22020-04-27 18:20:16 +0100382 skirt = primary_op.attrs.get("skirt", skirt)
383 explicit_padding = primary_op.attrs.get("explicit_padding", explicit_padding)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200384 assert primary_op.type.npu_block_type == ps.npu_block_type
385 npu_block_type = primary_op.type.npu_block_type
Diqing Zhong42e833d2020-10-02 13:18:42 +0200386 block_traversal = TensorBlockTraversal.Default
Tim Hall79d07d22020-04-27 18:20:16 +0100387
388 ifm_tensor, _, weight_tensor, ofm_tensor = ps.get_primary_op_ifm_ifm2_weights_ofm()
389
Tim Hallc30f4952020-06-15 20:47:35 +0100390 if npu_block_type in set(
Diqing Zhong09387e22020-09-28 18:46:22 +0200391 (
392 NpuBlockType.ConvolutionMxN,
393 NpuBlockType.ConvolutionDepthWise,
394 NpuBlockType.Pooling,
395 NpuBlockType.ReduceSum,
396 )
Tim Hallc30f4952020-06-15 20:47:35 +0100397 ):
Charles Xu3e9c4342020-04-22 08:31:43 +0200398 # extent the ifm to full dimension
399 ifm_tensor_brick_size = tuple(numeric_util.full_shape(4, list(ifm_tensor.brick_size), 1))
400 ifm_tensor_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
401 ifm_tensor_bandwidth_shape = numeric_util.full_shape(4, ifm_tensor.bandwidth_shape, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100402
Diqing Zhong42e833d2020-10-02 13:18:42 +0200403 batch_size = ifm_tensor_shape[0]
Charles Xu3e9c4342020-04-22 08:31:43 +0200404 ifm_depth = ifm_tensor_bandwidth_shape[3]
Tim Hall79d07d22020-04-27 18:20:16 +0100405
406 # add in padding
407 ifm_tensor_shape[1] += explicit_padding[0] + explicit_padding[2] # height += top and bottom
408 ifm_tensor_shape[2] += explicit_padding[1] + explicit_padding[3] # width += left and right
409
410 strides = primary_op.attrs["strides"]
411 if npu_block_type != NpuBlockType.Pooling:
Diqing Zhong09387e22020-09-28 18:46:22 +0200412 if npu_block_type == NpuBlockType.ReduceSum:
413 block_traversal = TensorBlockTraversal.DepthFirst
414 weight_tensor_shape = [1, 1, ifm_tensor.shape[3], ofm_tensor.shape[3]]
415 weight_tensor_bandwidth_shape = [0] * 4
416 weight_tensor_element_size = 0
417 weight_tensor_bandwidth_compression_scale = 0.0
418 else:
419 block_traversal = weight_tensor.block_traversal
420 weight_tensor_shape = weight_tensor.shape
421 weight_tensor_bandwidth_shape = weight_tensor.bandwidth_shape
422 weight_tensor_element_size = weight_tensor.element_size()
423 weight_tensor_bandwidth_compression_scale = weight_tensor.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100424 nn_ops = (
425 int(ofm_tensor.shape[0])
426 * int(ofm_tensor.shape[1])
427 * int(ofm_tensor.shape[2])
428 * int(weight_tensor_shape[0])
429 * int(weight_tensor_shape[1])
430 * int(weight_tensor_shape[2])
431 * int(weight_tensor_shape[3])
Tim Hall79d07d22020-04-27 18:20:16 +0100432 )
433 else:
434 weight_tensor_shape = [
435 primary_op.attrs["ksize"][1],
436 primary_op.attrs["ksize"][2],
437 1,
438 ifm_tensor_shape[3],
439 ]
440 weight_tensor_bandwidth_shape = weight_tensor_shape
441 weight_tensor_element_size = 0
442 weight_tensor_bandwidth_compression_scale = 0.0
443 nn_ops = 0 # pooling doesn't count as NN ops
444
445 kernel_dims = weight_tensor_shape[:2]
446
447 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
448 # count the sub kernels; the IFM block needs to be refetched for each of them
449 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
450 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
451 n_sub_kernels = n_sub_kernels_y * n_sub_kernels_x
452
453 clamped_skirt = list(skirt)
454 clamped_skirt[2] = min(clamped_skirt[2], sub_kernel_limits[0] - 1 - clamped_skirt[0])
455 clamped_skirt[3] = min(clamped_skirt[3], sub_kernel_limits[1] - 1 - clamped_skirt[1])
456 n_blocks, area, block_setup = get_n_blocks_and_area(
Charles Xu3e9c4342020-04-22 08:31:43 +0200457 ifm_tensor_brick_size,
Tim Hall79d07d22020-04-27 18:20:16 +0100458 ifm_tensor_shape[1:3],
459 skirt,
460 clamped_skirt,
461 block_config,
462 min_block_size,
463 strides,
464 )
465
466 blocks = n_blocks * numeric_util.round_up_divide(weight_tensor_shape[3], block_config[3])
467
468 n_weight_stages = numeric_util.round_up_divide(weight_tensor_bandwidth_shape[3], block_config[3])
469 if npu_block_type == NpuBlockType.ConvolutionDepthWise or npu_block_type == NpuBlockType.Pooling:
470 n_weight_stages = 1 # force to no reread
471
472 ifm_tensor_bw = (
473 n_sub_kernels
474 * batch_size
475 * area
476 * ifm_depth
477 * n_weight_stages
478 * ifm_tensor.element_size()
479 * ifm_tensor.bandwidth_compression_scale
480 )
481 replacement_read_bws[ifm_tensor] = ifm_tensor_bw
482 ifm_read_multiple = n_weight_stages
483
484 replacement_read_bws[weight_tensor] = (
485 batch_size
486 * shape_num_elements(weight_tensor_bandwidth_shape)
487 * weight_tensor_element_size
488 * weight_tensor_bandwidth_compression_scale
489 * n_blocks
490 ) # read once per block and batch
491 weight_read_multiple = n_blocks
492
493 n_kernel_xy = kernel_dims[0] * kernel_dims[1]
494 n_input_channels_at_a_time = block_config[2]
495
Diqing Zhong09387e22020-09-28 18:46:22 +0200496 if npu_block_type == NpuBlockType.Pooling or block_traversal in set(
Tim Hall79d07d22020-04-27 18:20:16 +0100497 (TensorBlockTraversal.PartKernelFirst, TensorBlockTraversal.DepthWise)
498 ):
499 n_input_channels_at_a_time = numeric_util.round_up_divide(n_input_channels_at_a_time, 4)
500 n_kernel_xy = max(
501 n_kernel_xy, 4
502 ) # need at least 4, as this is the minimum duty cycle for secondary accumulator writes
503 if weight_tensor is not None:
Diego Russoea6111a2020-04-14 18:41:58 +0100504 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 +0100505
506 num_mac_ops = 0
507 for n_blocks_for_size, block_size in block_setup:
508 num_mac_ops += (
509 batch_size
510 * n_blocks_for_size
511 * block_size[0]
512 * block_size[1]
513 * numeric_util.round_up(weight_tensor_shape[2], n_input_channels_at_a_time)
514 * numeric_util.round_up(weight_tensor_shape[3], block_config[3])
515 * n_kernel_xy
516 )
517
Tim Hall79d07d22020-04-27 18:20:16 +0100518 macs[MacCount.NeuralNetworkMacs] += nn_ops
519 macs[MacCount.HardwareMacs] += num_mac_ops
Diqing Zhong42e833d2020-10-02 13:18:42 +0200520 cycles[PassCycles.Npu] = estimate_conv_pooling_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200521 arch,
522 npu_block_type,
523 primary_op,
524 Block(block_config[1], block_config[0], block_config[3]),
525 block_traversal,
526 kernel_dims,
527 ifm_tensor,
528 ofm_tensor,
529 )
Tim Hall79d07d22020-04-27 18:20:16 +0100530 elif npu_block_type == NpuBlockType.VectorProduct:
531 nn_macs = (
532 ifm_tensor.shape[0]
533 * numeric_util.round_up(weight_tensor.shape[-2], block_config[2])
534 * numeric_util.round_up(weight_tensor.shape[-1], block_config[3])
535 )
536 num_mac_ops = nn_macs
537
Diqing Zhong42e833d2020-10-02 13:18:42 +0200538 cycles[PassCycles.Npu] = estimate_conv_pooling_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200539 arch,
540 npu_block_type,
541 primary_op,
542 Block(block_config[1], block_config[0], block_config[3]),
543 weight_tensor.block_traversal,
544 [1, 1],
545 ifm_tensor,
546 ofm_tensor,
547 )
Tim Hall79d07d22020-04-27 18:20:16 +0100548 macs[MacCount.NeuralNetworkMacs] += nn_macs
549 macs[MacCount.HardwareMacs] += num_mac_ops
550
551 blocks = 1 * numeric_util.round_up_divide(weight_tensor.shape[-1], block_config[3])
552
553 non_zero_fraction = 1.0
554 if ifm_tensor.values is not None:
555 nz_vector = np.amax(ifm_tensor.values != 0, axis=0) # max across batch axis
556 non_zero_fraction = np.average(nz_vector)
557
558 replacement_read_bws[ifm_tensor] = ifm_tensor.bandwidth()
559 replacement_read_bws[weight_tensor] = weight_tensor.bandwidth() * non_zero_fraction
560 ifm_read_multiple = 1
561 weight_read_multiple = non_zero_fraction
Diqing Zhonge8887a32020-09-24 09:53:48 +0200562 elif npu_block_type == NpuBlockType.ElementWise:
Tim Hall79d07d22020-04-27 18:20:16 +0100563 # Work out how many elements we have and calculate performance.
Diqing Zhong42e833d2020-10-02 13:18:42 +0200564 cycles[PassCycles.Npu] = estimate_output_cycles(
Diqing Zhong09387e22020-09-28 18:46:22 +0200565 arch, npu_block_type, primary_op, ofm_tensor.elements(), ps.ifm_tensor, ps.ofm_tensor, ps.ifm2_tensor
566 )
Diqing Zhong42e833d2020-10-02 13:18:42 +0200567
568 prev_npu_pass = next((npu_ps for npu_ps in ps.dag_predecessors if npu_ps.placement is PassPlacement.Npu), None)
569 if prev_npu_pass is None:
570 # cycles for DMA ops in first pass
571 dma_ops = (op for op in ps.ops if op.type == Op.DMA)
572 for dma_op in dma_ops:
573 mem_area = dma_op.attrs["source"]
574 for tens in dma_op.inputs:
575 cycles[PassCycles.Npu] += tens.storage_size() / arch.memory_bandwidths_per_cycle[mem_area]
576
Tim Hall79d07d22020-04-27 18:20:16 +0100577 # apply the desired rewrites
578 for rewrite_op, tens, _, _, _, ps_to_rewrite in rewrite_list:
579 if ps != ps_to_rewrite:
580 continue
581 if rewrite_op == SchedulerRewrite.Nop:
582 pass # these are fine, no bandwidth changes
583 elif rewrite_op in (SchedulerRewrite.ChangeTensorSubPurpose,):
584 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Read] += replacement_read_bws[tens]
585 replacement_read_bws[tens] = 0
586
587 for tens in ps.outputs:
588 if force_outputs_to_fast_storage:
589 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
590 else:
591 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
592
593 for tens in ps.intermediates:
594 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
595
596 if tens in replacement_read_bws:
597 bw = replacement_read_bws[tens]
598 else:
599 bw = tens.bandwidth()
600
601 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += bw
602
603 for tens in ps.inputs:
604 if tens in replacement_read_bws:
605 bw = replacement_read_bws[tens]
606 else:
607 bw = tens.bandwidth()
608
609 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += bw
610
611 cycles[PassCycles.SramAccess] = np.sum(bws[MemArea.Sram]) / arch.memory_bandwidths_per_cycle[MemArea.Sram]
612 cycles[PassCycles.TotalPerPass] = np.max(cycles[: PassCycles.TotalPerPass])
613
614 # quick build access counts for only current pass, even though these aren't the final numbers
615 update_summary_cycles(arch, bws, macs, cycles)
616
617 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple
618
619
620def update_summary_cycles(arch, bws, macs, cycles):
621 cycles[PassCycles.DramAccess] = np.sum(bws[MemArea.Dram]) / arch.memory_bandwidths_per_cycle[MemArea.Dram]
622 cycles[PassCycles.OnChipFlashAccess] = (
623 np.sum(bws[MemArea.OnChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OnChipFlash]
624 )
625 cycles[PassCycles.OffChipFlashAccess] = (
626 np.sum(bws[MemArea.OffChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OffChipFlash]
627 )
628
629 cycles[PassCycles.Total] = np.max(cycles[: PassCycles.Total])
630 return cycles
631
632
633def collate_stats_for_cascaded_pass(arch, bws, macs, cycles):
634 return bws, macs, cycles
635
636
637def performance_for_cascaded_pass(arch, cps):
638 total_bws = make_bandwidth_array()
639 total_macs = make_macs_array()
640 total_cycles = make_cycles_array()
641
642 for ps in cps.passes:
643 bws, macs, cycles, blocks, _, _ = performance_metrics_for_pass(arch, ps)
644 ps.bandwidths = bws
645 ps.macs = macs
646 ps.cycles = cycles
647 ps.n_blocks = blocks
648 total_bws += bws
649 total_macs += macs
650 total_cycles += cycles
651
652 bws, macs, cycles = collate_stats_for_cascaded_pass(arch, total_bws, total_macs, total_cycles)
653 cps.bandwidths = bws
654 cps.macs = macs
655 cps.cycles = cycles
656 return bws, macs, cycles
657
658
659def calc_performance_for_network(nng, arch):
660 total_bws = make_bandwidth_array()
661 total_macs = np.zeros(MacCount.Size)
662 total_cycles = np.zeros(PassCycles.Size)
663
664 for sg in nng.subgraphs:
665 for cps in sg.cascaded_passes:
666 bws, macs, cycles = performance_for_cascaded_pass(arch, cps)
667 total_bws += bws
668 total_macs += macs
669 total_cycles += cycles
Tim Hall79d07d22020-04-27 18:20:16 +0100670
671 nng.bandwidths = total_bws
672 nng.macs = total_macs
673 nng.cycles = total_cycles