blob: 1663c26beb34b0fb54d70ddad17752bec0d1bc55 [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
Diego Russoe8a10452020-04-21 17:39:10 +010028from .nn_graph import PassPlacement
29from .nn_graph import SchedulerRewrite
Diego Russoea6111a2020-04-14 18:41:58 +010030from .operation import NpuBlockType
Louis Verhaard93dc5532020-06-07 12:40:18 +020031from .register_command_stream_generator import get_op_kernel
Diego Russoe8a10452020-04-21 17:39:10 +010032from .tensor import MemArea
33from .tensor import shape_num_elements
34from .tensor import TensorBlockTraversal
35from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010036
37
38def rolling_buffer_dims_from_passes(arch, ps1, block_config_ps1, ps2, block_config_ps2):
Tim Hall79d07d22020-04-27 18:20:16 +010039 ofm_block = Block(block_config_ps2[-3], block_config_ps2[-4], block_config_ps2[-1])
Louis Verhaard93dc5532020-06-07 12:40:18 +020040 kernel = get_op_kernel(ps2)
Tim Hall79d07d22020-04-27 18:20:16 +010041
42 if ps2.npu_block_type in set((NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct)):
Louis Verhaard93dc5532020-06-07 12:40:18 +020043 op = ps2.primary_op
44 ifm_idx, _, _, _, _ = op.get_ifm_ifm2_weight_bias_ofm_indices()
Tim Hall79d07d22020-04-27 18:20:16 +010045 ifm_block_depth = arch.calc_ifm_block_depth(
46 op.inputs[ifm_idx].shape[-1], op.inputs[ifm_idx].dtype.size_in_bits()
47 )
48 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):
60 Dpu = 0
61 ElementWise = 1
62 Cpu = 2
63 SramAccess = 3
64 TotalPerPass = 4
65 DramAccess = 5
66 OnChipFlashAccess = 6
67 OffChipFlashAccess = 7
68 Total = 8
69 Size = 9
70
71 def display_name(self):
72 return (
73 "DPU",
74 "Element wise",
75 "CPU",
76 "SRAM Access",
77 "Total per Pass",
78 "DRAM Access",
79 "On-chip Flash Access",
80 "Off-chip Flash Access",
81 "Total",
82 "Size",
83 )[self.value]
84
85 def identifier_name(self):
86 return (
87 "dpu",
88 "element_wise",
89 "cpu",
90 "sram_access",
91 "total_per_pass",
92 "dram_access",
93 "on_chip_flash_access",
94 "off_chip_flash_access",
95 "total",
96 "size",
97 )[self.value]
98
99 @staticmethod
100 def all():
101 return (
102 PassCycles.Dpu,
103 PassCycles.ElementWise,
104 PassCycles.Cpu,
105 PassCycles.SramAccess,
106 PassCycles.DramAccess,
107 PassCycles.OnChipFlashAccess,
108 PassCycles.OffChipFlashAccess,
109 PassCycles.Total,
110 )
111
112
113class MacCount(enum.IntEnum):
114 NeuralNetworkMacs = 0
115 HardwareMacs = 1
116 Size = 2
117
118 def display_name(self):
119 return ("Neural Network Macs", "Hardware Macs", "Size")[self.value]
120
121 def identifier_name(self):
122 return ("nn_macs", "hardware_macs", "size")[self.value]
123
124 @staticmethod
125 def all():
126 return (MacCount.NeuralNetworkMacs, MacCount.HardwareMacs)
127
128
129class BandwidthDirection(enum.IntEnum):
130 Read = 0
131 Write = 1
132 Size = 2
133
134 def display_name(self):
135 return self.name
136
137 def identifier_name(self):
138 return self.name.lower()
139
140 @staticmethod
141 def all():
142 return (BandwidthDirection.Read, BandwidthDirection.Write)
143
144
145def make_bandwidth_array():
146 return np.zeros((MemArea.Size, TensorPurpose.Size, BandwidthDirection.Size))
147
148
149def make_macs_array():
150 return np.zeros(MacCount.Size, np.int)
151
152
153def make_cycles_array():
154 return np.zeros(PassCycles.Size)
155
156
157def make_metrics_arrays():
158 return (make_bandwidth_array(), make_macs_array(), make_cycles_array())
159
160
161def get_n_blocks_and_area(
162 ifm_brick_size, ifm_height_width, orig_skirt, clamped_skirt, block_config, min_block_size, strides
163):
164
165 ifm_block_config = (block_config[0] * strides[1], block_config[1] * strides[2])
166
167 n_normal_blocks = []
168 remainder_size = []
169 for i in range(2):
170 non_skirt_dim = ifm_height_width[i] - orig_skirt[i] - orig_skirt[2 + i]
171 n_blocks = non_skirt_dim // ifm_block_config[i]
172 n_normal_blocks.append(n_blocks)
173 remainder_dim = numeric_util.round_up(
174 ((non_skirt_dim - n_blocks * ifm_block_config[i] - 1) // strides[i + 1]) + 1, min_block_size[i]
175 )
176 remainder_size.append(remainder_dim)
177
178 # this will actually calculate reads into the edge padding.
179
180 # there are four cases in total, handling the edges that will not fill a complete block.
181
182 # 0000000001
183 # 0000000001
184 # 0000000001
185 # 0000000001
186 # 0000000001
187 # 0000000001
188 # 2222222223
189 total_blocks = 0
190 total_area = 0
191
192 block_setup = (
193 (n_normal_blocks[0] * n_normal_blocks[1], block_config),
194 (1 * n_normal_blocks[1], (remainder_size[0], block_config[1])),
195 (n_normal_blocks[0] * 1, (block_config[0], remainder_size[1])),
196 (1 * 1, remainder_size),
197 )
198
199 for n_blocks, block_size in block_setup:
200 if block_size[0] == 0 or block_size[1] == 0:
201 continue
202 read_dims = [0, 0]
203 for i in range(2):
204 read_dims[i] = (
205 numeric_util.round_up(clamped_skirt[i], ifm_brick_size[i + 1])
206 + block_size[i] * strides[i + 1]
207 + numeric_util.round_up(clamped_skirt[2 + i], ifm_brick_size[i + 1])
208 )
209 assert n_blocks >= 0
210 total_blocks += n_blocks
211 total_area += n_blocks * read_dims[0] * read_dims[1]
212 assert total_blocks >= 1
213 return total_blocks, total_area, block_setup
214
215
216def performance_metrics_for_pass(arch, ps, block_config=None, rewrite_list=[], force_outputs_to_fast_storage=False):
217 if block_config is None:
218 block_config = ps.block_config
219 bws = make_bandwidth_array()
220 macs = make_macs_array()
221 cycles = make_cycles_array()
222 blocks = 0
223 ifm_read_multiple = 1
224 weight_read_multiple = 0
225
226 if ps.placement in set((PassPlacement.MemoryOnly, PassPlacement.StartupInit)):
227 return bws, macs, cycles, blocks, ifm_read_multiple, weight_read_multiple # nothing real happening in this pass
228
229 min_block_size = arch.min_block_sizes[ps.npu_block_type]
230
231 skirt = (0, 0, 0, 0)
232 explicit_padding = (0, 0, 0, 0)
233 primary_op = ps.primary_op
234 replacement_read_bws = {}
Charles Xub02c8d92020-06-25 16:05:25 +0200235 if ps.placement == PassPlacement.Cpu:
236 cycles[PassCycles.Cpu] = arch.cpu_cycle_estimate(ps.ops[0])
237 elif primary_op:
Tim Hall79d07d22020-04-27 18:20:16 +0100238 skirt = primary_op.attrs.get("skirt", skirt)
239 explicit_padding = primary_op.attrs.get("explicit_padding", explicit_padding)
240 assert primary_op.attrs["npu_block_type"] == ps.npu_block_type
241 npu_block_type = primary_op.attrs["npu_block_type"]
242
243 ifm_tensor, _, weight_tensor, ofm_tensor = ps.get_primary_op_ifm_ifm2_weights_ofm()
244
Tim Hallc30f4952020-06-15 20:47:35 +0100245 if npu_block_type in set(
246 (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling)
247 ):
Charles Xu3e9c4342020-04-22 08:31:43 +0200248 # extent the ifm to full dimension
249 ifm_tensor_brick_size = tuple(numeric_util.full_shape(4, list(ifm_tensor.brick_size), 1))
250 ifm_tensor_shape = numeric_util.full_shape(4, ifm_tensor.shape, 1)
251 ifm_tensor_bandwidth_shape = numeric_util.full_shape(4, ifm_tensor.bandwidth_shape, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100252
253 batch_size = ifm_tensor.shape[0]
Charles Xu3e9c4342020-04-22 08:31:43 +0200254 ifm_depth = ifm_tensor_bandwidth_shape[3]
Tim Hall79d07d22020-04-27 18:20:16 +0100255
256 # add in padding
257 ifm_tensor_shape[1] += explicit_padding[0] + explicit_padding[2] # height += top and bottom
258 ifm_tensor_shape[2] += explicit_padding[1] + explicit_padding[3] # width += left and right
259
260 strides = primary_op.attrs["strides"]
261 if npu_block_type != NpuBlockType.Pooling:
262 weight_tensor_shape = weight_tensor.shape
263 weight_tensor_bandwidth_shape = weight_tensor.bandwidth_shape
264 weight_tensor_element_size = weight_tensor.element_size()
265 weight_tensor_bandwidth_compression_scale = weight_tensor.bandwidth_compression_scale
266 nn_ops = (
267 int(ofm_tensor.shape[0])
268 * int(ofm_tensor.shape[1])
269 * int(ofm_tensor.shape[2])
270 * int(weight_tensor_shape[0])
271 * int(weight_tensor_shape[1])
272 * int(weight_tensor_shape[2])
273 * int(weight_tensor_shape[3])
274 / int(strides[1])
275 / int(strides[2])
276 )
277 else:
278 weight_tensor_shape = [
279 primary_op.attrs["ksize"][1],
280 primary_op.attrs["ksize"][2],
281 1,
282 ifm_tensor_shape[3],
283 ]
284 weight_tensor_bandwidth_shape = weight_tensor_shape
285 weight_tensor_element_size = 0
286 weight_tensor_bandwidth_compression_scale = 0.0
287 nn_ops = 0 # pooling doesn't count as NN ops
288
289 kernel_dims = weight_tensor_shape[:2]
290
291 sub_kernel_limits = arch.sub_kernel_limits[npu_block_type]
292 # count the sub kernels; the IFM block needs to be refetched for each of them
293 n_sub_kernels_y = numeric_util.round_up_divide(kernel_dims[0], sub_kernel_limits[0])
294 n_sub_kernels_x = numeric_util.round_up_divide(kernel_dims[1], sub_kernel_limits[1])
295 n_sub_kernels = n_sub_kernels_y * n_sub_kernels_x
296
297 clamped_skirt = list(skirt)
298 clamped_skirt[2] = min(clamped_skirt[2], sub_kernel_limits[0] - 1 - clamped_skirt[0])
299 clamped_skirt[3] = min(clamped_skirt[3], sub_kernel_limits[1] - 1 - clamped_skirt[1])
300 n_blocks, area, block_setup = get_n_blocks_and_area(
Charles Xu3e9c4342020-04-22 08:31:43 +0200301 ifm_tensor_brick_size,
Tim Hall79d07d22020-04-27 18:20:16 +0100302 ifm_tensor_shape[1:3],
303 skirt,
304 clamped_skirt,
305 block_config,
306 min_block_size,
307 strides,
308 )
309
310 blocks = n_blocks * numeric_util.round_up_divide(weight_tensor_shape[3], block_config[3])
311
312 n_weight_stages = numeric_util.round_up_divide(weight_tensor_bandwidth_shape[3], block_config[3])
313 if npu_block_type == NpuBlockType.ConvolutionDepthWise or npu_block_type == NpuBlockType.Pooling:
314 n_weight_stages = 1 # force to no reread
315
316 ifm_tensor_bw = (
317 n_sub_kernels
318 * batch_size
319 * area
320 * ifm_depth
321 * n_weight_stages
322 * ifm_tensor.element_size()
323 * ifm_tensor.bandwidth_compression_scale
324 )
325 replacement_read_bws[ifm_tensor] = ifm_tensor_bw
326 ifm_read_multiple = n_weight_stages
327
328 replacement_read_bws[weight_tensor] = (
329 batch_size
330 * shape_num_elements(weight_tensor_bandwidth_shape)
331 * weight_tensor_element_size
332 * weight_tensor_bandwidth_compression_scale
333 * n_blocks
334 ) # read once per block and batch
335 weight_read_multiple = n_blocks
336
337 n_kernel_xy = kernel_dims[0] * kernel_dims[1]
338 n_input_channels_at_a_time = block_config[2]
339
340 if npu_block_type == NpuBlockType.Pooling or weight_tensor.block_traversal in set(
341 (TensorBlockTraversal.PartKernelFirst, TensorBlockTraversal.DepthWise)
342 ):
343 n_input_channels_at_a_time = numeric_util.round_up_divide(n_input_channels_at_a_time, 4)
344 n_kernel_xy = max(
345 n_kernel_xy, 4
346 ) # need at least 4, as this is the minimum duty cycle for secondary accumulator writes
347 if weight_tensor is not None:
Diego Russoea6111a2020-04-14 18:41:58 +0100348 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 +0100349
350 num_mac_ops = 0
351 for n_blocks_for_size, block_size in block_setup:
352 num_mac_ops += (
353 batch_size
354 * n_blocks_for_size
355 * block_size[0]
356 * block_size[1]
357 * numeric_util.round_up(weight_tensor_shape[2], n_input_channels_at_a_time)
358 * numeric_util.round_up(weight_tensor_shape[3], block_config[3])
359 * n_kernel_xy
360 )
361
362 if npu_block_type == NpuBlockType.Pooling:
363 # TODO: improve pooling estimation
364 cycles[PassCycles.Dpu] = num_mac_ops / arch.num_macs_per_cycle / 2
365 else:
366 cycles[PassCycles.Dpu] = num_mac_ops / arch.num_macs_per_cycle
367 macs[MacCount.NeuralNetworkMacs] += nn_ops
368 macs[MacCount.HardwareMacs] += num_mac_ops
369
370 elif npu_block_type == NpuBlockType.VectorProduct:
371 nn_macs = (
372 ifm_tensor.shape[0]
373 * numeric_util.round_up(weight_tensor.shape[-2], block_config[2])
374 * numeric_util.round_up(weight_tensor.shape[-1], block_config[3])
375 )
376 num_mac_ops = nn_macs
377
378 cycles[PassCycles.Dpu] = num_mac_ops / arch.num_macs_per_cycle
379 macs[MacCount.NeuralNetworkMacs] += nn_macs
380 macs[MacCount.HardwareMacs] += num_mac_ops
381
382 blocks = 1 * numeric_util.round_up_divide(weight_tensor.shape[-1], block_config[3])
383
384 non_zero_fraction = 1.0
385 if ifm_tensor.values is not None:
386 nz_vector = np.amax(ifm_tensor.values != 0, axis=0) # max across batch axis
387 non_zero_fraction = np.average(nz_vector)
388
389 replacement_read_bws[ifm_tensor] = ifm_tensor.bandwidth()
390 replacement_read_bws[weight_tensor] = weight_tensor.bandwidth() * non_zero_fraction
391 ifm_read_multiple = 1
392 weight_read_multiple = non_zero_fraction
393 else:
394 if ps.placement == PassPlacement.Npu and len(ps.outputs):
395 # Assume element-wise operation going through the element pipelines.
396 # Work out how many elements we have and calculate performance.
397 out = ps.outputs[0]
398 elms = out.elements()
399
400 cycles[PassCycles.ElementWise] = numeric_util.round_up_divide(elms, arch.num_elem_wise_units)
401
Tim Hall79d07d22020-04-27 18:20:16 +0100402 # 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
Tim Hall79d07d22020-04-27 18:20:16 +0100495
496 nng.bandwidths = total_bws
497 nng.macs = total_macs
498 nng.cycles = total_cycles