blob: 57a72a6a86bdce794fba8fcb963d662cf9de209c [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
Diego Russoe8a10452020-04-21 17:39:10 +010027from .architecture_features import Block
28from .architecture_features import Kernel
29from .nn_graph import PassPlacement
30from .nn_graph import SchedulerRewrite
Diego Russoea6111a2020-04-14 18:41:58 +010031from .operation import NpuBlockType
Louis Verhaard93dc5532020-06-07 12:40:18 +020032from .register_command_stream_generator import get_op_kernel
Diego Russoe8a10452020-04-21 17:39:10 +010033from .tensor import MemArea
34from .tensor import shape_num_elements
35from .tensor import TensorBlockTraversal
36from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010037
38
39def rolling_buffer_dims_from_passes(arch, ps1, block_config_ps1, ps2, block_config_ps2):
Tim Hall79d07d22020-04-27 18:20:16 +010040 ofm_block = Block(block_config_ps2[-3], block_config_ps2[-4], block_config_ps2[-1])
Louis Verhaard93dc5532020-06-07 12:40:18 +020041 kernel = get_op_kernel(ps2)
Tim Hall79d07d22020-04-27 18:20:16 +010042
43 if ps2.npu_block_type in set((NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct)):
Louis Verhaard93dc5532020-06-07 12:40:18 +020044 op = ps2.primary_op
45 ifm_idx, _, _, _, _ = op.get_ifm_ifm2_weight_bias_ofm_indices()
Tim Hall79d07d22020-04-27 18:20:16 +010046 ifm_block_depth = arch.calc_ifm_block_depth(
47 op.inputs[ifm_idx].shape[-1], op.inputs[ifm_idx].dtype.size_in_bits()
48 )
49 else:
50 ifm_block_depth = block_config_ps2[-1]
51
Louis Verhaard93dc5532020-06-07 12:40:18 +020052 ifm_block = arch.get_ifm_block_size(ifm_block_depth, ofm_block, kernel, arch.ofm_block_max)
Tim Hall79d07d22020-04-27 18:20:16 +010053
54 # The performed height calculation is for worst case
55 height = numeric_util.round_up(ifm_block.height + block_config_ps1[0], block_config_ps1[0])
56 width = ifm_block.width
Louis Verhaard93dc5532020-06-07 12:40:18 +020057 return [height, width]
Tim Hall79d07d22020-04-27 18:20:16 +010058
59
60class PassCycles(enum.IntEnum):
61 Dpu = 0
62 ElementWise = 1
63 Cpu = 2
64 SramAccess = 3
65 TotalPerPass = 4
66 DramAccess = 5
67 OnChipFlashAccess = 6
68 OffChipFlashAccess = 7
69 Total = 8
70 Size = 9
71
72 def display_name(self):
73 return (
74 "DPU",
75 "Element wise",
76 "CPU",
77 "SRAM Access",
78 "Total per Pass",
79 "DRAM Access",
80 "On-chip Flash Access",
81 "Off-chip Flash Access",
82 "Total",
83 "Size",
84 )[self.value]
85
86 def identifier_name(self):
87 return (
88 "dpu",
89 "element_wise",
90 "cpu",
91 "sram_access",
92 "total_per_pass",
93 "dram_access",
94 "on_chip_flash_access",
95 "off_chip_flash_access",
96 "total",
97 "size",
98 )[self.value]
99
100 @staticmethod
101 def all():
102 return (
103 PassCycles.Dpu,
104 PassCycles.ElementWise,
105 PassCycles.Cpu,
106 PassCycles.SramAccess,
107 PassCycles.DramAccess,
108 PassCycles.OnChipFlashAccess,
109 PassCycles.OffChipFlashAccess,
110 PassCycles.Total,
111 )
112
113
114class MacCount(enum.IntEnum):
115 NeuralNetworkMacs = 0
116 HardwareMacs = 1
117 Size = 2
118
119 def display_name(self):
120 return ("Neural Network Macs", "Hardware Macs", "Size")[self.value]
121
122 def identifier_name(self):
123 return ("nn_macs", "hardware_macs", "size")[self.value]
124
125 @staticmethod
126 def all():
127 return (MacCount.NeuralNetworkMacs, MacCount.HardwareMacs)
128
129
130class BandwidthDirection(enum.IntEnum):
131 Read = 0
132 Write = 1
133 Size = 2
134
135 def display_name(self):
136 return self.name
137
138 def identifier_name(self):
139 return self.name.lower()
140
141 @staticmethod
142 def all():
143 return (BandwidthDirection.Read, BandwidthDirection.Write)
144
145
146def make_bandwidth_array():
147 return np.zeros((MemArea.Size, TensorPurpose.Size, BandwidthDirection.Size))
148
149
150def make_macs_array():
151 return np.zeros(MacCount.Size, np.int)
152
153
154def make_cycles_array():
155 return np.zeros(PassCycles.Size)
156
157
158def make_metrics_arrays():
159 return (make_bandwidth_array(), make_macs_array(), make_cycles_array())
160
161
162def get_n_blocks_and_area(
163 ifm_brick_size, ifm_height_width, orig_skirt, clamped_skirt, block_config, min_block_size, strides
164):
165
166 ifm_block_config = (block_config[0] * strides[1], block_config[1] * strides[2])
167
168 n_normal_blocks = []
169 remainder_size = []
170 for i in range(2):
171 non_skirt_dim = ifm_height_width[i] - orig_skirt[i] - orig_skirt[2 + i]
172 n_blocks = non_skirt_dim // ifm_block_config[i]
173 n_normal_blocks.append(n_blocks)
174 remainder_dim = numeric_util.round_up(
175 ((non_skirt_dim - n_blocks * ifm_block_config[i] - 1) // strides[i + 1]) + 1, min_block_size[i]
176 )
177 remainder_size.append(remainder_dim)
178
179 # this will actually calculate reads into the edge padding.
180
181 # there are four cases in total, handling the edges that will not fill a complete block.
182
183 # 0000000001
184 # 0000000001
185 # 0000000001
186 # 0000000001
187 # 0000000001
188 # 0000000001
189 # 2222222223
190 total_blocks = 0
191 total_area = 0
192
193 block_setup = (
194 (n_normal_blocks[0] * n_normal_blocks[1], block_config),
195 (1 * n_normal_blocks[1], (remainder_size[0], block_config[1])),
196 (n_normal_blocks[0] * 1, (block_config[0], remainder_size[1])),
197 (1 * 1, remainder_size),
198 )
199
200 for n_blocks, block_size in block_setup:
201 if block_size[0] == 0 or block_size[1] == 0:
202 continue
203 read_dims = [0, 0]
204 for i in range(2):
205 read_dims[i] = (
206 numeric_util.round_up(clamped_skirt[i], ifm_brick_size[i + 1])
207 + block_size[i] * strides[i + 1]
208 + numeric_util.round_up(clamped_skirt[2 + i], ifm_brick_size[i + 1])
209 )
210 assert n_blocks >= 0
211 total_blocks += n_blocks
212 total_area += n_blocks * read_dims[0] * read_dims[1]
213 assert total_blocks >= 1
214 return total_blocks, total_area, block_setup
215
216
217def performance_metrics_for_pass(arch, ps, block_config=None, rewrite_list=[], force_outputs_to_fast_storage=False):
218 if block_config is None:
219 block_config = ps.block_config
220 bws = make_bandwidth_array()
221 macs = make_macs_array()
222 cycles = make_cycles_array()
223 blocks = 0
224 ifm_read_multiple = 1
225 weight_read_multiple = 0
226
227 if ps.placement in set((PassPlacement.MemoryOnly, PassPlacement.StartupInit)):
228 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple # nothing real happening in this pass
229
230 min_block_size = arch.min_block_sizes[ps.npu_block_type]
231
232 skirt = (0, 0, 0, 0)
233 explicit_padding = (0, 0, 0, 0)
234 primary_op = ps.primary_op
235 replacement_read_bws = {}
236 if primary_op:
237 skirt = primary_op.attrs.get("skirt", skirt)
238 explicit_padding = primary_op.attrs.get("explicit_padding", explicit_padding)
239 assert primary_op.attrs["npu_block_type"] == ps.npu_block_type
240 npu_block_type = primary_op.attrs["npu_block_type"]
241
242 ifm_tensor, _, weight_tensor, ofm_tensor = ps.get_primary_op_ifm_ifm2_weights_ofm()
243
Charles Xu3e9c4342020-04-22 08:31:43 +0200244 if npu_block_type in set((NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling)):
245 # extent the ifm to full dimension
246 ifm_tensor_brick_size = tuple(numeric_util.full_shape(4, list(ifm_tensor.brick_size), 1))
247 ifm_tensor_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
248 ifm_tensor_bandwidth_shape = numeric_util.full_shape(4, ifm_tensor.bandwidth_shape, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100249
250 batch_size = ifm_tensor.shape[0]
Charles Xu3e9c4342020-04-22 08:31:43 +0200251 ifm_depth = ifm_tensor_bandwidth_shape[3]
Tim Hall79d07d22020-04-27 18:20:16 +0100252
253 # add in padding
254 ifm_tensor_shape[1] += explicit_padding[0] + explicit_padding[2] # height += top and bottom
255 ifm_tensor_shape[2] += explicit_padding[1] + explicit_padding[3] # width += left and right
256
257 strides = primary_op.attrs["strides"]
258 if npu_block_type != NpuBlockType.Pooling:
259 weight_tensor_shape = weight_tensor.shape
260 weight_tensor_bandwidth_shape = weight_tensor.bandwidth_shape
261 weight_tensor_element_size = weight_tensor.element_size()
262 weight_tensor_bandwidth_compression_scale = weight_tensor.bandwidth_compression_scale
263 nn_ops = (
264 int(ofm_tensor.shape[0])
265 * int(ofm_tensor.shape[1])
266 * int(ofm_tensor.shape[2])
267 * int(weight_tensor_shape[0])
268 * int(weight_tensor_shape[1])
269 * int(weight_tensor_shape[2])
270 * int(weight_tensor_shape[3])
271 / int(strides[1])
272 / int(strides[2])
273 )
274 else:
275 weight_tensor_shape = [
276 primary_op.attrs["ksize"][1],
277 primary_op.attrs["ksize"][2],
278 1,
279 ifm_tensor_shape[3],
280 ]
281 weight_tensor_bandwidth_shape = weight_tensor_shape
282 weight_tensor_element_size = 0
283 weight_tensor_bandwidth_compression_scale = 0.0
284 nn_ops = 0 # pooling doesn't count as NN ops
285
286 kernel_dims = weight_tensor_shape[:2]
287
288 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
289 # count the sub kernels; the IFM block needs to be refetched for each of them
290 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
291 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
292 n_sub_kernels = n_sub_kernels_y * n_sub_kernels_x
293
294 clamped_skirt = list(skirt)
295 clamped_skirt[2] = min(clamped_skirt[2], sub_kernel_limits[0] - 1 - clamped_skirt[0])
296 clamped_skirt[3] = min(clamped_skirt[3], sub_kernel_limits[1] - 1 - clamped_skirt[1])
297 n_blocks, area, block_setup = get_n_blocks_and_area(
Charles Xu3e9c4342020-04-22 08:31:43 +0200298 ifm_tensor_brick_size,
Tim Hall79d07d22020-04-27 18:20:16 +0100299 ifm_tensor_shape[1:3],
300 skirt,
301 clamped_skirt,
302 block_config,
303 min_block_size,
304 strides,
305 )
306
307 blocks = n_blocks * numeric_util.round_up_divide(weight_tensor_shape[3], block_config[3])
308
309 n_weight_stages = numeric_util.round_up_divide(weight_tensor_bandwidth_shape[3], block_config[3])
310 if npu_block_type == NpuBlockType.ConvolutionDepthWise or npu_block_type == NpuBlockType.Pooling:
311 n_weight_stages = 1 # force to no reread
312
313 ifm_tensor_bw = (
314 n_sub_kernels
315 * batch_size
316 * area
317 * ifm_depth
318 * n_weight_stages
319 * ifm_tensor.element_size()
320 * ifm_tensor.bandwidth_compression_scale
321 )
322 replacement_read_bws[ifm_tensor] = ifm_tensor_bw
323 ifm_read_multiple = n_weight_stages
324
325 replacement_read_bws[weight_tensor] = (
326 batch_size
327 * shape_num_elements(weight_tensor_bandwidth_shape)
328 * weight_tensor_element_size
329 * weight_tensor_bandwidth_compression_scale
330 * n_blocks
331 ) # read once per block and batch
332 weight_read_multiple = n_blocks
333
334 n_kernel_xy = kernel_dims[0] * kernel_dims[1]
335 n_input_channels_at_a_time = block_config[2]
336
337 if npu_block_type == NpuBlockType.Pooling or weight_tensor.block_traversal in set(
338 (TensorBlockTraversal.PartKernelFirst, TensorBlockTraversal.DepthWise)
339 ):
340 n_input_channels_at_a_time = numeric_util.round_up_divide(n_input_channels_at_a_time, 4)
341 n_kernel_xy = max(
342 n_kernel_xy, 4
343 ) # need at least 4, as this is the minimum duty cycle for secondary accumulator writes
344 if weight_tensor is not None:
Diego Russoea6111a2020-04-14 18:41:58 +0100345 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 +0100346
347 num_mac_ops = 0
348 for n_blocks_for_size, block_size in block_setup:
349 num_mac_ops += (
350 batch_size
351 * n_blocks_for_size
352 * block_size[0]
353 * block_size[1]
354 * numeric_util.round_up(weight_tensor_shape[2], n_input_channels_at_a_time)
355 * numeric_util.round_up(weight_tensor_shape[3], block_config[3])
356 * n_kernel_xy
357 )
358
359 if npu_block_type == NpuBlockType.Pooling:
360 # TODO: improve pooling estimation
361 cycles[PassCycles.Dpu] = num_mac_ops / arch.num_macs_per_cycle / 2
362 else:
363 cycles[PassCycles.Dpu] = num_mac_ops / arch.num_macs_per_cycle
364 macs[MacCount.NeuralNetworkMacs] += nn_ops
365 macs[MacCount.HardwareMacs] += num_mac_ops
366
367 elif npu_block_type == NpuBlockType.VectorProduct:
368 nn_macs = (
369 ifm_tensor.shape[0]
370 * numeric_util.round_up(weight_tensor.shape[-2], block_config[2])
371 * numeric_util.round_up(weight_tensor.shape[-1], block_config[3])
372 )
373 num_mac_ops = nn_macs
374
375 cycles[PassCycles.Dpu] = num_mac_ops / arch.num_macs_per_cycle
376 macs[MacCount.NeuralNetworkMacs] += nn_macs
377 macs[MacCount.HardwareMacs] += num_mac_ops
378
379 blocks = 1 * numeric_util.round_up_divide(weight_tensor.shape[-1], block_config[3])
380
381 non_zero_fraction = 1.0
382 if ifm_tensor.values is not None:
383 nz_vector = np.amax(ifm_tensor.values != 0, axis=0) # max across batch axis
384 non_zero_fraction = np.average(nz_vector)
385
386 replacement_read_bws[ifm_tensor] = ifm_tensor.bandwidth()
387 replacement_read_bws[weight_tensor] = weight_tensor.bandwidth() * non_zero_fraction
388 ifm_read_multiple = 1
389 weight_read_multiple = non_zero_fraction
390 else:
391 if ps.placement == PassPlacement.Npu and len(ps.outputs):
392 # Assume element-wise operation going through the element pipelines.
393 # Work out how many elements we have and calculate performance.
394 out = ps.outputs[0]
395 elms = out.elements()
396
397 cycles[PassCycles.ElementWise] = numeric_util.round_up_divide(elms, arch.num_elem_wise_units)
398
399 if ps.placement == PassPlacement.Cpu:
400 cycles[PassCycles.Cpu] = arch.cpu_cycle_estimate(ps.ops[0])
401
402 # apply the desired rewrites
403 for rewrite_op, tens, _, _, _, ps_to_rewrite in rewrite_list:
404 if ps != ps_to_rewrite:
405 continue
406 if rewrite_op == SchedulerRewrite.Nop:
407 pass # these are fine, no bandwidth changes
408 elif rewrite_op in (SchedulerRewrite.ChangeTensorSubPurpose,):
409 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Read] += replacement_read_bws[tens]
410 replacement_read_bws[tens] = 0
411
412 for tens in ps.outputs:
413 if force_outputs_to_fast_storage:
414 bws[arch.fast_storage_mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
415 else:
416 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
417
418 for tens in ps.intermediates:
419 bws[tens.mem_area][tens.purpose][BandwidthDirection.Write] += tens.bandwidth()
420
421 if tens in replacement_read_bws:
422 bw = replacement_read_bws[tens]
423 else:
424 bw = tens.bandwidth()
425
426 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += bw
427
428 for tens in ps.inputs:
429 if tens in replacement_read_bws:
430 bw = replacement_read_bws[tens]
431 else:
432 bw = tens.bandwidth()
433
434 bws[tens.mem_area][tens.purpose][BandwidthDirection.Read] += bw
435
436 cycles[PassCycles.SramAccess] = np.sum(bws[MemArea.Sram]) / arch.memory_bandwidths_per_cycle[MemArea.Sram]
437 cycles[PassCycles.TotalPerPass] = np.max(cycles[: PassCycles.TotalPerPass])
438
439 # quick build access counts for only current pass, even though these aren't the final numbers
440 update_summary_cycles(arch, bws, macs, cycles)
441
442 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple
443
444
445def update_summary_cycles(arch, bws, macs, cycles):
446 cycles[PassCycles.DramAccess] = np.sum(bws[MemArea.Dram]) / arch.memory_bandwidths_per_cycle[MemArea.Dram]
447 cycles[PassCycles.OnChipFlashAccess] = (
448 np.sum(bws[MemArea.OnChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OnChipFlash]
449 )
450 cycles[PassCycles.OffChipFlashAccess] = (
451 np.sum(bws[MemArea.OffChipFlash]) / arch.memory_bandwidths_per_cycle[MemArea.OffChipFlash]
452 )
453
454 cycles[PassCycles.Total] = np.max(cycles[: PassCycles.Total])
455 return cycles
456
457
458def collate_stats_for_cascaded_pass(arch, bws, macs, cycles):
459 return bws, macs, cycles
460
461
462def performance_for_cascaded_pass(arch, cps):
463 total_bws = make_bandwidth_array()
464 total_macs = make_macs_array()
465 total_cycles = make_cycles_array()
466
467 for ps in cps.passes:
468 bws, macs, cycles, blocks, _, _ = performance_metrics_for_pass(arch, ps)
469 ps.bandwidths = bws
470 ps.macs = macs
471 ps.cycles = cycles
472 ps.n_blocks = blocks
473 total_bws += bws
474 total_macs += macs
475 total_cycles += cycles
476
477 bws, macs, cycles = collate_stats_for_cascaded_pass(arch, total_bws, total_macs, total_cycles)
478 cps.bandwidths = bws
479 cps.macs = macs
480 cps.cycles = cycles
481 return bws, macs, cycles
482
483
484def calc_performance_for_network(nng, arch):
485 total_bws = make_bandwidth_array()
486 total_macs = np.zeros(MacCount.Size)
487 total_cycles = np.zeros(PassCycles.Size)
488
489 for sg in nng.subgraphs:
490 for cps in sg.cascaded_passes:
491 bws, macs, cycles = performance_for_cascaded_pass(arch, cps)
492 total_bws += bws
493 total_macs += macs
494 total_cycles += cycles
495 total_cycles += arch.inter_pass_cycle_delay
496
497 nng.bandwidths = total_bws
498 nng.macs = total_macs
499 nng.cycles = total_cycles