blob: ee554b5c6f33d45af005f3ed0807a61801750b5f [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.
16
17
18# Description:
19# Compresses and pads the weigths. It also calculates the scales and packs with the biases.
20
Tim Hall79d07d22020-04-27 18:20:16 +010021import math
Tim Hall79d07d22020-04-27 18:20:16 +010022from collections import namedtuple
Diego Russoea6111a2020-04-14 18:41:58 +010023
24import numpy as np
25
Tim Hall79d07d22020-04-27 18:20:16 +010026from .numeric_util import round_up
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +020027from .scaling import quantise_scale, reduced_quantise_scale
Tim Hall79d07d22020-04-27 18:20:16 +010028from .tensor import TensorPurpose, TensorSubPurpose, TensorFormat, TensorBlockTraversal
29from .operation import NpuBlockType
30from .architecture_features import Block
31from .nn_graph import SchedulingStrategy
32from .data_type import DataType
33
34from ethosu import mlw_codec
35
36
37def encode(weight_stream):
38 assert np.amin(weight_stream) >= -255
39 assert np.amax(weight_stream) <= 255
40
41 # Encode flattened signed weight stream
42 compressed = mlw_codec.encode(weight_stream)
43
44 # pad with 0xFF as needed so the length of the weight stream
45 # is a multiple of 16
Diego Russoea6111a2020-04-14 18:41:58 +010046
Tim Hall79d07d22020-04-27 18:20:16 +010047 while (len(compressed) % 16) != 0:
48 compressed.append(0xFF)
49
50 return compressed
51
52
53def generate_brick(arch, brick_weights, ofm_block, block_traversal, ifm_bitdepth):
54 is_depthwise = block_traversal == TensorBlockTraversal.DepthWise
55 is_partkernel = block_traversal == TensorBlockTraversal.PartKernelFirst
56 subkernel_max = arch.subkernel_max
57 ofm_ublock = arch.ofm_ublock
58 ifm_ublock = arch.ifm_ublock
59 # Expect weights formatted HWIO
60 ofm_depth = brick_weights.shape[-1]
61 ifm_depth = brick_weights.shape[-2]
62 kernel_width = brick_weights.shape[-3]
63 kernel_height = brick_weights.shape[-4]
64 # IFM block depth
65 if is_partkernel or (ifm_bitdepth == 16):
66 # IFM block depth is always 16 for part-kernel-first
67 ifm_block_depth = 16
68 elif ifm_bitdepth == 8:
69 ifm_block_depth = 32
70 else:
71 assert False
72
73 stream = []
74
75 # Top level striping - OFM blocks in the entire brick's depth
76 for ofm_block_z in range(0, ofm_depth, ofm_block.depth):
77 clipped_ofm_block_depth = min(ofm_block.depth, ofm_depth - ofm_block_z)
78 # IFM blocks required for the brick
79 for ifm_block_z in range(0, (1 if is_depthwise else ifm_depth), ifm_block_depth):
80 if is_depthwise:
81 clipped_ifm_block_depth = ifm_ublock.depth
82 else:
83 clipped_ifm_block_depth = (
84 min(ifm_block_depth, ifm_depth - ifm_block_z) if is_partkernel else ifm_block_depth
85 )
86 # Weight decomposition
87 # Subkernel Splitting (H)
88 for subkernel_y in range(0, kernel_height, subkernel_max.height):
89 sub_height = min(kernel_height - subkernel_y, subkernel_max.height)
90 # Subkernel splitting (W)
91 for subkernel_x in range(0, kernel_width, subkernel_max.width):
92 sub_width = min(kernel_width - subkernel_x, subkernel_max.width)
93 subkernel_elements = sub_width * sub_height
94 # Part kernel first works across the kernel H/W and needs padding
95 if is_partkernel:
96 if ifm_bitdepth == 16 and subkernel_elements % 2 != 0:
97 subkernel_elements = int(math.ceil(subkernel_elements / 2) * 2)
98 elif ifm_bitdepth == 8 and subkernel_elements % 4 != 0:
99 subkernel_elements = int(math.ceil(subkernel_elements / 4) * 4)
100
101 # Depthwise Conv requires multiple of 4 kernel elements in its weight block
102 # this is different from normal conv which is considered "weights depth-first"
103 elif is_depthwise:
104 subkernel_elements = int(math.ceil(subkernel_elements / 4.0) * 4)
105
106 ifm_block_depth_outer = clipped_ifm_block_depth if is_partkernel else 1
107 ifm_block_depth_inner = 1 if is_partkernel else clipped_ifm_block_depth
108 # IFM Ublocks in IFM-block over depth for part-kernel-first mode
109 # For depth-first IFM Ublocks are traversed after subkernel elements so this loop is ignored.
110 for ifm_ublk_outer in range(0, ifm_block_depth_outer, ifm_ublock.depth):
111 # OFM Ublocks in OFM-block over depth
112 for ofm_ublk in range(0, clipped_ofm_block_depth, ofm_ublock.depth):
113 # HW Kernel element traversal - cannot be a H/W loop due to element
114 # padding requirement on depthwise/part-kernel configurations
115 for element in range(subkernel_elements):
116 kx = element % sub_width
117 ky = element // sub_width
118 # IFM Ublocks in IFM-block over depth (only 1 ublock if depthwise)
119 # In case of part-kernel-first IFM Ublock traversal have already been handled
120 # and this loop is ignored.
121 for ifm_ublk_inner in range(0, ifm_block_depth_inner, ifm_ublock.depth):
122 # Feed OFM ublock elements
123 for ofm_ublock_z in range(ofm_ublock.depth):
124 # Source IFM ublock elements (only 1 element deep if depthwise)
125 for ifm_ublock_z in range(1 if is_depthwise else ifm_ublock.depth):
126 # Source position within the current subkernel
127 wx = subkernel_x + kx
128 wy = subkernel_y + ky
129 # Source IFM/OFM slices
130 ifm_ublk = ifm_ublk_inner + ifm_ublk_outer
131 ifm_z = ifm_block_z + ifm_ublk + ifm_ublock_z
132 ofm_z = ofm_block_z + ofm_ublk + ofm_ublock_z
133 if (ifm_z >= ifm_depth) or (ofm_z >= ofm_depth) or (ky >= sub_height):
134 stream.append(0)
135 else:
136 stream.append(brick_weights[wy][wx][ifm_z][ofm_z])
137 return stream
138
139
140# Compress the weights
141def compress_weights(tens, arch, npu_block_type, ofm_block, ofm_depth_step, min_val=None, max_val=None):
142 assert tens.purpose == TensorPurpose.Weights
143 assert tens.format == TensorFormat.WeightsCompressed
144
145 WeightCompressionConfig = namedtuple("WeightCompressionConfig", ["npu_block_type", "ofm_block", "ofm_depth_step"])
146
147 # check if weights have already been compressed
148 wcc = tens.weight_compression_config
149 if wcc is not None:
150 assert wcc.npu_block_type == npu_block_type, "Weights not used by the same operator type"
151
152 if wcc.ofm_block == ofm_block and wcc.ofm_depth_step == ofm_depth_step:
153 return
154
155 assert tens.quantization is not None
156 assert tens.quantization.scale_f32 is not None
157 assert tens.quantization.zero_point is not None
158
159 zero_point = tens.quantization.zero_point
160 quant_buf = tens.quant_values.astype(np.int64)
161
162 # Early zero-point correction
163 weights = quant_buf - zero_point
164
165 if len(weights.shape) == 2:
166 weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0)
167 weights_shape = (weights.shape[0], 1, 1, weights.shape[1])
168 else:
169 weights_shape = weights.shape
170
171 compression_scales = []
172 compressed_offsets = []
173 encoded_streams = []
174 offset = 0
175 max_single_buffer_len = 0
176
177 ifm_bitdepth = tens.consumer_list[0].inputs[0].dtype.size_in_bits()
178 ifm_depth = weights.shape[-2]
179 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
180 tens.block_traversal = TensorBlockTraversal.DepthWise
181 if npu_block_type == NpuBlockType.ConvolutionMxN:
182 # Determine which block traversal strategy has better DPU utilization
183 kernel_size = weights_shape[0] * weights_shape[1]
184 depth_utilization = weights_shape[2] / round_up(weights_shape[2], 32 if ifm_bitdepth == 8 else 16)
185 part_kernel_utilization = (weights_shape[2] / round_up(weights_shape[2], 8)) * (
186 kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)
187 )
188 if part_kernel_utilization >= depth_utilization or ifm_depth <= 8:
189 # Part-kernel first is always better for ifm depths <= 8
190 tens.block_traversal = TensorBlockTraversal.PartKernelFirst
191 else:
192 tens.block_traversal = TensorBlockTraversal.DepthFirst
193
194 # Slice weight stream up depth-ways into bricks and compress
195 full_ofm_depth = quant_buf.shape[-1]
196 for idx in range(0, full_ofm_depth, ofm_depth_step):
197 # Get the weights necessary for this brick
198 count = min(full_ofm_depth - idx, ofm_depth_step)
199 brick_weights = weights[:, :, :, idx : idx + count]
200
201 # Encode all weights into one chunk
202 raw_stream = generate_brick(arch, brick_weights, ofm_block, tens.block_traversal, ifm_bitdepth)
203 encoded = encode(raw_stream)
204 encoded_streams.append(encoded)
205
206 # Remember maximum encoded length for DoubleBuffering
207 if max_single_buffer_len < len(encoded):
208 max_single_buffer_len = len(encoded)
209
210 # Remember where we put it for linear addressing
211 compressed_offsets.append(offset)
212 offset += len(encoded)
213 assert offset % 16 == 0
214
215 # Compression scale tracking
216 compression_scales.append(len(encoded) / len(raw_stream))
217
218 # Also track complete length in the offsets array
219 compressed_offsets.append(offset)
220
221 if tens.sub_purpose == TensorSubPurpose.DoubleBuffer and len(encoded_streams) > 2:
222 offset = 2 * max_single_buffer_len
223 assert offset % 16 == 0
224
225 tens.storage_shape = [1, 1, 1, offset]
226 tens.weight_compression_scales = compression_scales
227 tens.weight_compression_config = WeightCompressionConfig(npu_block_type, ofm_block, ofm_depth_step)
228 tens.weight_compressed_offsets = compressed_offsets
229 tens.compression_scale_for_worst_weight_stream = np.amax(compression_scales)
230 tens.storage_compression_scale = tens.bandwidth_compression_scale = np.average(compression_scales)
231 tens.compressed_values = encoded_streams
232 tens.brick_size = (weights_shape[0], weights_shape[1], weights_shape[2], min(tens.shape[-1], ofm_depth_step))
233
234
235def calc_scales_and_pack_biases(tens, arch, oc_quantum, rescale_for_faf=False):
236 assert tens.purpose == TensorPurpose.FeatureMap
237 assert tens.format == TensorFormat.NHWC
238 # the connected operator should expect a bias input unless it is a FullyConnected
239 assert "Bias" in tens.consumer_list[0].type or tens.consumer_list[0].type.startswith("FullyConnected")
240 # the input bias tensor is the same as that connected to the operator
241 assert tens is tens.consumer_list[0].inputs[2]
242 # the operator should only have a single output
243 assert len(tens.consumer_list[0].outputs) == 1
244
245 def pack_bias_and_scale(bias, scale, shift):
246 bias = np.int64(bias)
247 assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range
248 assert 0 <= scale < (1 << 32) # unsigned 32-bit range
249 assert 0 <= shift < (1 << 6) # unsigned 6-bit range
250
251 # pack the 80 bit value = [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)]
252 data = bytearray(10)
253 data[0] = (bias >> (0 * 8)) & 0xFF
254 data[1] = (bias >> (1 * 8)) & 0xFF
255 data[2] = (bias >> (2 * 8)) & 0xFF
256 data[3] = (bias >> (3 * 8)) & 0xFF
257 data[4] = (bias >> (4 * 8)) & 0xFF
258 data[5] = (scale >> (0 * 8)) & 0xFF
259 data[6] = (scale >> (1 * 8)) & 0xFF
260 data[7] = (scale >> (2 * 8)) & 0xFF
261 data[8] = (scale >> (3 * 8)) & 0xFF
262 data[9] = shift & 0x3F
263 return data
264
265 biases = tens.quant_values
266
267 first_consumer_op = tens.consumer_list[0]
268 ifm_dtype = first_consumer_op.inputs[0].dtype
269 ifm_scale = first_consumer_op.inputs[0].quantization.scale_f32
270 ofm_scale = first_consumer_op.outputs[0].quantization.scale_f32
271 weight_scales = first_consumer_op.inputs[1].quantization.scale_f32
272
273 # biases can have multiple consumers for rnn cells. if so, then check that they are all the same
274 for op in tens.consumer_list[1:]:
275 assert ifm_scale == op.inputs[0].quantization.scale_f32
276 assert ofm_scale == op.outputs[0].quantization.scale_f32
277 assert weight_scales == op.inputs[1].quantization.scale_f32
278
279 if not hasattr(weight_scales, "__iter__"):
280 # If weight_scales is not already an iterable make it into a list
281 weight_scales = [weight_scales]
282
283 # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which
284 # uses double during scaling calculations
285 # TensorFlow Lite casts the scales slightly differently for uint8 and int8
286 if not rescale_for_faf:
287 if ifm_dtype == DataType.uint8:
288 scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200289 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100290 scales = [
291 (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale)
292 for weight_scale in weight_scales
293 ]
294 else:
295 assert False, str(ifm_dtype) + " not implemented"
296 else:
297 if ifm_dtype == DataType.uint8:
298 scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200299 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100300 scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales]
301 else:
302 assert False, str(ifm_dtype) + " not implemented"
303
304 # quantise all of the weight scales into (scale_factor, shift)
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200305 if ifm_dtype == DataType.int16:
306 quantised_scales = [reduced_quantise_scale(scale) for scale in scales]
307 else:
308 quantised_scales = [quantise_scale(scale) for scale in scales]
Tim Hall79d07d22020-04-27 18:20:16 +0100309
310 for _, shift in quantised_scales:
311 assert shift >= 16
312
313 # pack the biases and scales
314 tens.compressed_values = []
315 if len(quantised_scales) == 1:
316 # If only 1 quantised scale is used, repeat that value for the length of the biases
317 quantised_scales = [quantised_scales[0]] * len(biases)
318
319 assert len(quantised_scales) == len(biases)
320 for i, bias in enumerate(biases):
321 tens.compressed_values.append(pack_bias_and_scale(bias, *quantised_scales[i]))
322
323 tens.element_size_bytes = 10
324
325 # Figure out if we need padded storage (extra whole elements)
326 padding = (len(tens.compressed_values) * tens.element_size_bytes) % 16
327 if padding != 0:
328 padding = 16 - padding
329
330 # This adds enough padding to allow over-reads
331 while padding > 0:
332 tens.compressed_values.append(pack_bias_and_scale(0, 0, 0))
333 padding = padding - tens.element_size_bytes
334
335 tens.storage_shape = [len(tens.compressed_values)]
336
337
338def update_pass_weight_and_scale_tensors(nng, arch):
339 def find_npu_usage_of_tensor(tens):
340 # TODO: This function is identical to the one in mark_tensors.py. A common version should be used.
341 for op in tens.consumers():
342 if op.type == "DMA":
343 return find_npu_usage_of_tensor(op.outputs[0])
344 if "npu_block_type" in op.attrs:
345 return op.attrs["npu_block_type"]
346 return NpuBlockType.Default
347
348 for sg in nng.subgraphs:
349 for ps in sg.passes:
Diego Russoea6111a2020-04-14 18:41:58 +0100350 if ps.weight_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100351 npu_usage_of_tensor = find_npu_usage_of_tensor(ps.weight_tensor)
352 if npu_usage_of_tensor == NpuBlockType.ConvolutionDepthWise:
353 ps.weight_tensor.quant_values = np.transpose(ps.weight_tensor.quant_values, (0, 1, 3, 2))
354 ps.weight_tensor.shape = ps.weight_tensor.storage_shape = ps.weight_tensor.bandwidth_shape = list(
355 ps.weight_tensor.quant_values.shape
356 )
357 ps.weight_tensor.weight_transpose_depthwise = True
358
359 needs_dma = len(ps.weight_tensor.ops) == 1 and ps.weight_tensor.ops[0].type == "DMA"
360 if ps.cascade.strategy == SchedulingStrategy.WeightStream and needs_dma:
361 ofm_depth_step = ps.block_config[-1]
362 else:
363 ofm_depth_step = ps.weight_tensor.shape[-1]
364
365 compress_weights(
366 ps.weight_tensor,
367 arch,
368 npu_usage_of_tensor,
369 Block(ps.block_config[-3], ps.block_config[-4], ps.block_config[-1]),
370 ofm_depth_step,
371 )
372 # Update source tensor
373 if len(ps.weight_tensor.ops) == 1 and ps.weight_tensor.ops[0].type == "DMA":
374 src_tens = ps.weight_tensor.ops[0].inputs[0]
375 src_tens.shape = ps.weight_tensor.shape
376 src_tens.weight_transpose_depthwise = ps.weight_tensor.weight_transpose_depthwise
377 src_tens.quant_values = ps.weight_tensor.quant_values
378 src_tens.compressed_values = ps.weight_tensor.compressed_values
379 src_tens.storage_shape = [1, 1, 1, ps.weight_tensor.weight_compressed_offsets[-1]]
380 src_tens.brick_size = ps.weight_tensor.brick_size
381 src_tens.weight_compression_scales = ps.weight_tensor.weight_compression_scales
382 src_tens.weight_compressed_offsets = ps.weight_tensor.weight_compressed_offsets
383
Diego Russoea6111a2020-04-14 18:41:58 +0100384 if ps.scale_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100385 rescale_for_faf = False
386 activation_ops = set(("Sigmoid", "Tanh"))
387 if (ps.ops[-1].type in activation_ops) and (ps.npu_block_type != NpuBlockType.ElementWise):
388 rescale_for_faf = True
389 calc_scales_and_pack_biases(ps.scale_tensor, arch, ps.block_config[3], rescale_for_faf)