blob: 450e091ef6dfd9b45d4cdaedc66466f221d0179f [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# Compresses and pads the weigths. It also calculates the scales and packs with the biases.
Tim Hall79d07d22020-04-27 18:20:16 +010018import math
Tim Hall79d07d22020-04-27 18:20:16 +010019from collections import namedtuple
Diego Russoea6111a2020-04-14 18:41:58 +010020
21import numpy as np
Tim Hall79d07d22020-04-27 18:20:16 +010022from ethosu import mlw_codec
23
Diego Russoe8a10452020-04-21 17:39:10 +010024from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020025from .errors import UnsupportedFeatureError
Diego Russoe8a10452020-04-21 17:39:10 +010026from .nn_graph import SchedulingStrategy
27from .numeric_util import round_up
28from .operation import NpuBlockType
29from .scaling import quantise_scale
30from .scaling import reduced_quantise_scale
31from .tensor import TensorBlockTraversal
32from .tensor import TensorFormat
33from .tensor import TensorPurpose
34from .tensor import TensorSubPurpose
35
Tim Hall79d07d22020-04-27 18:20:16 +010036
Louis Verhaard3c07c972020-05-07 08:12:58 +020037# Contains meta info for a weight compression. If two tensors have identical weight compression config,
38# then they also will have identical compressed weights.
39WeightCompressionConfig = namedtuple(
40 "WeightCompressionConfig", ["npu_block_type", "ofm_block_depth", "ofm_depth_step", "equivalence_id"]
41)
42
43
44def create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step):
45 # Note: for an ofm block only its depth is used in weight compression.
46 # And block depth > ofm depth gives same result as block depth == ofm depth
47 block_depth = min(ofm_block_depth, tens.quant_values.shape[-1])
48 return WeightCompressionConfig(npu_block_type, block_depth, ofm_depth_step, tens.equivalence_id)
49
50
51def set_storage_shape(tens):
52 # Sets the storage shape depending on the tensor's sub purpose
53 if tens.sub_purpose == TensorSubPurpose.DoubleBuffer and len(tens.compressed_values) > 2:
54 offset = 2 * np.amax([len(x) for x in tens.compressed_values])
55 assert offset % 16 == 0
56 else:
57 offset = tens.weight_compressed_offsets[-1]
58 tens.storage_shape = [1, 1, 1, offset]
59
60
61class CompressedWeightCache:
62 # Contains weight compressions for all weight tensors in a graph
63 def __init__(self):
64 self.cache = {} # maps from WeightCompressionConfig to a tensor clone containing compressed weights
65
66 def get_tensor_with_same_compression(self, wcc):
67 return self.cache.get(wcc)
68
69 def add(self, tens):
70 # Adds the compressed weights from the tensor to the cache
71 wcc = tens.weight_compression_config
72 # Clone the tensor to make sure that nothing related to the weight compression is modified
73 tens_clone = tens.clone("_weights{}_{}".format(wcc.ofm_block_depth, wcc.ofm_depth_step))
74 self.cache[wcc] = tens_clone
75
76
Tim Hall79d07d22020-04-27 18:20:16 +010077def encode(weight_stream):
78 assert np.amin(weight_stream) >= -255
79 assert np.amax(weight_stream) <= 255
80
81 # Encode flattened signed weight stream
82 compressed = mlw_codec.encode(weight_stream)
83
84 # pad with 0xFF as needed so the length of the weight stream
85 # is a multiple of 16
Diego Russoea6111a2020-04-14 18:41:58 +010086
Tim Hall79d07d22020-04-27 18:20:16 +010087 while (len(compressed) % 16) != 0:
88 compressed.append(0xFF)
89
90 return compressed
91
92
Louis Verhaard3c07c972020-05-07 08:12:58 +020093def generate_brick(arch, brick_weights, ofm_block_depth, block_traversal, ifm_bitdepth):
Tim Hall79d07d22020-04-27 18:20:16 +010094 is_depthwise = block_traversal == TensorBlockTraversal.DepthWise
95 is_partkernel = block_traversal == TensorBlockTraversal.PartKernelFirst
96 subkernel_max = arch.subkernel_max
97 ofm_ublock = arch.ofm_ublock
98 ifm_ublock = arch.ifm_ublock
99 # Expect weights formatted HWIO
100 ofm_depth = brick_weights.shape[-1]
101 ifm_depth = brick_weights.shape[-2]
102 kernel_width = brick_weights.shape[-3]
103 kernel_height = brick_weights.shape[-4]
104 # IFM block depth
105 if is_partkernel or (ifm_bitdepth == 16):
106 # IFM block depth is always 16 for part-kernel-first
107 ifm_block_depth = 16
108 elif ifm_bitdepth == 8:
109 ifm_block_depth = 32
110 else:
111 assert False
112
113 stream = []
114
115 # Top level striping - OFM blocks in the entire brick's depth
Louis Verhaard3c07c972020-05-07 08:12:58 +0200116 for ofm_block_z in range(0, ofm_depth, ofm_block_depth):
117 clipped_ofm_block_depth = min(ofm_block_depth, ofm_depth - ofm_block_z)
Tim Hall79d07d22020-04-27 18:20:16 +0100118 # IFM blocks required for the brick
119 for ifm_block_z in range(0, (1 if is_depthwise else ifm_depth), ifm_block_depth):
120 if is_depthwise:
121 clipped_ifm_block_depth = ifm_ublock.depth
122 else:
123 clipped_ifm_block_depth = (
124 min(ifm_block_depth, ifm_depth - ifm_block_z) if is_partkernel else ifm_block_depth
125 )
126 # Weight decomposition
127 # Subkernel Splitting (H)
128 for subkernel_y in range(0, kernel_height, subkernel_max.height):
129 sub_height = min(kernel_height - subkernel_y, subkernel_max.height)
130 # Subkernel splitting (W)
131 for subkernel_x in range(0, kernel_width, subkernel_max.width):
132 sub_width = min(kernel_width - subkernel_x, subkernel_max.width)
133 subkernel_elements = sub_width * sub_height
134 # Part kernel first works across the kernel H/W and needs padding
135 if is_partkernel:
136 if ifm_bitdepth == 16 and subkernel_elements % 2 != 0:
137 subkernel_elements = int(math.ceil(subkernel_elements / 2) * 2)
138 elif ifm_bitdepth == 8 and subkernel_elements % 4 != 0:
139 subkernel_elements = int(math.ceil(subkernel_elements / 4) * 4)
140
141 # Depthwise Conv requires multiple of 4 kernel elements in its weight block
142 # this is different from normal conv which is considered "weights depth-first"
143 elif is_depthwise:
144 subkernel_elements = int(math.ceil(subkernel_elements / 4.0) * 4)
145
146 ifm_block_depth_outer = clipped_ifm_block_depth if is_partkernel else 1
147 ifm_block_depth_inner = 1 if is_partkernel else clipped_ifm_block_depth
148 # IFM Ublocks in IFM-block over depth for part-kernel-first mode
149 # For depth-first IFM Ublocks are traversed after subkernel elements so this loop is ignored.
150 for ifm_ublk_outer in range(0, ifm_block_depth_outer, ifm_ublock.depth):
151 # OFM Ublocks in OFM-block over depth
152 for ofm_ublk in range(0, clipped_ofm_block_depth, ofm_ublock.depth):
153 # HW Kernel element traversal - cannot be a H/W loop due to element
154 # padding requirement on depthwise/part-kernel configurations
155 for element in range(subkernel_elements):
156 kx = element % sub_width
157 ky = element // sub_width
158 # IFM Ublocks in IFM-block over depth (only 1 ublock if depthwise)
159 # In case of part-kernel-first IFM Ublock traversal have already been handled
160 # and this loop is ignored.
161 for ifm_ublk_inner in range(0, ifm_block_depth_inner, ifm_ublock.depth):
162 # Feed OFM ublock elements
163 for ofm_ublock_z in range(ofm_ublock.depth):
164 # Source IFM ublock elements (only 1 element deep if depthwise)
165 for ifm_ublock_z in range(1 if is_depthwise else ifm_ublock.depth):
166 # Source position within the current subkernel
167 wx = subkernel_x + kx
168 wy = subkernel_y + ky
169 # Source IFM/OFM slices
170 ifm_ublk = ifm_ublk_inner + ifm_ublk_outer
171 ifm_z = ifm_block_z + ifm_ublk + ifm_ublock_z
172 ofm_z = ofm_block_z + ofm_ublk + ofm_ublock_z
173 if (ifm_z >= ifm_depth) or (ofm_z >= ofm_depth) or (ky >= sub_height):
174 stream.append(0)
175 else:
176 stream.append(brick_weights[wy][wx][ifm_z][ofm_z])
177 return stream
178
179
180# Compress the weights
Louis Verhaard3c07c972020-05-07 08:12:58 +0200181def compress_weights(arch, nng, tens, npu_block_type, ofm_block_depth, ofm_depth_step):
Tim Hall79d07d22020-04-27 18:20:16 +0100182 assert tens.purpose == TensorPurpose.Weights
183 assert tens.format == TensorFormat.WeightsCompressed
184
Louis Verhaard3c07c972020-05-07 08:12:58 +0200185 # Check the weight cache
186 if nng.weight_cache is None:
187 nng.weight_cache = CompressedWeightCache()
188 wcc = create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step)
189 tens.weight_compression_config = wcc
190 tens_cached = nng.weight_cache.get_tensor_with_same_compression(wcc)
191 if tens_cached is not None:
192 # Cache hit, copy weights from the cache
193 tens.copy_compressed_weight_info(tens_cached)
194 set_storage_shape(tens)
195 return
Tim Hall79d07d22020-04-27 18:20:16 +0100196
Louis Verhaard3c07c972020-05-07 08:12:58 +0200197 # No cache hit, perform the compression
Tim Hall79d07d22020-04-27 18:20:16 +0100198 assert tens.quantization is not None
199 assert tens.quantization.scale_f32 is not None
200 assert tens.quantization.zero_point is not None
201
202 zero_point = tens.quantization.zero_point
203 quant_buf = tens.quant_values.astype(np.int64)
204
205 # Early zero-point correction
206 weights = quant_buf - zero_point
207
208 if len(weights.shape) == 2:
209 weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0)
210 weights_shape = (weights.shape[0], 1, 1, weights.shape[1])
211 else:
212 weights_shape = weights.shape
213
214 compression_scales = []
215 compressed_offsets = []
216 encoded_streams = []
217 offset = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100218
219 ifm_bitdepth = tens.consumer_list[0].inputs[0].dtype.size_in_bits()
220 ifm_depth = weights.shape[-2]
221 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
222 tens.block_traversal = TensorBlockTraversal.DepthWise
223 if npu_block_type == NpuBlockType.ConvolutionMxN:
224 # Determine which block traversal strategy has better DPU utilization
225 kernel_size = weights_shape[0] * weights_shape[1]
226 depth_utilization = weights_shape[2] / round_up(weights_shape[2], 32 if ifm_bitdepth == 8 else 16)
227 part_kernel_utilization = (weights_shape[2] / round_up(weights_shape[2], 8)) * (
228 kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)
229 )
230 if part_kernel_utilization >= depth_utilization or ifm_depth <= 8:
231 # Part-kernel first is always better for ifm depths <= 8
232 tens.block_traversal = TensorBlockTraversal.PartKernelFirst
233 else:
234 tens.block_traversal = TensorBlockTraversal.DepthFirst
235
236 # Slice weight stream up depth-ways into bricks and compress
237 full_ofm_depth = quant_buf.shape[-1]
238 for idx in range(0, full_ofm_depth, ofm_depth_step):
239 # Get the weights necessary for this brick
240 count = min(full_ofm_depth - idx, ofm_depth_step)
241 brick_weights = weights[:, :, :, idx : idx + count]
242
243 # Encode all weights into one chunk
Louis Verhaard3c07c972020-05-07 08:12:58 +0200244 raw_stream = generate_brick(arch, brick_weights, ofm_block_depth, tens.block_traversal, ifm_bitdepth)
Tim Hall79d07d22020-04-27 18:20:16 +0100245 encoded = encode(raw_stream)
246 encoded_streams.append(encoded)
247
Tim Hall79d07d22020-04-27 18:20:16 +0100248 # Remember where we put it for linear addressing
249 compressed_offsets.append(offset)
250 offset += len(encoded)
251 assert offset % 16 == 0
252
253 # Compression scale tracking
254 compression_scales.append(len(encoded) / len(raw_stream))
255
256 # Also track complete length in the offsets array
257 compressed_offsets.append(offset)
258
Tim Hall79d07d22020-04-27 18:20:16 +0100259 tens.weight_compression_scales = compression_scales
Tim Hall79d07d22020-04-27 18:20:16 +0100260 tens.weight_compressed_offsets = compressed_offsets
261 tens.compression_scale_for_worst_weight_stream = np.amax(compression_scales)
262 tens.storage_compression_scale = tens.bandwidth_compression_scale = np.average(compression_scales)
263 tens.compressed_values = encoded_streams
264 tens.brick_size = (weights_shape[0], weights_shape[1], weights_shape[2], min(tens.shape[-1], ofm_depth_step))
Louis Verhaard3c07c972020-05-07 08:12:58 +0200265 set_storage_shape(tens)
266 nng.weight_cache.add(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100267
268
269def calc_scales_and_pack_biases(tens, arch, oc_quantum, rescale_for_faf=False):
270 assert tens.purpose == TensorPurpose.FeatureMap
271 assert tens.format == TensorFormat.NHWC
272 # the connected operator should expect a bias input unless it is a FullyConnected
273 assert "Bias" in tens.consumer_list[0].type or tens.consumer_list[0].type.startswith("FullyConnected")
274 # the input bias tensor is the same as that connected to the operator
275 assert tens is tens.consumer_list[0].inputs[2]
276 # the operator should only have a single output
277 assert len(tens.consumer_list[0].outputs) == 1
278
279 def pack_bias_and_scale(bias, scale, shift):
280 bias = np.int64(bias)
281 assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range
282 assert 0 <= scale < (1 << 32) # unsigned 32-bit range
283 assert 0 <= shift < (1 << 6) # unsigned 6-bit range
284
285 # pack the 80 bit value = [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)]
286 data = bytearray(10)
287 data[0] = (bias >> (0 * 8)) & 0xFF
288 data[1] = (bias >> (1 * 8)) & 0xFF
289 data[2] = (bias >> (2 * 8)) & 0xFF
290 data[3] = (bias >> (3 * 8)) & 0xFF
291 data[4] = (bias >> (4 * 8)) & 0xFF
292 data[5] = (scale >> (0 * 8)) & 0xFF
293 data[6] = (scale >> (1 * 8)) & 0xFF
294 data[7] = (scale >> (2 * 8)) & 0xFF
295 data[8] = (scale >> (3 * 8)) & 0xFF
296 data[9] = shift & 0x3F
297 return data
298
299 biases = tens.quant_values
300
301 first_consumer_op = tens.consumer_list[0]
302 ifm_dtype = first_consumer_op.inputs[0].dtype
303 ifm_scale = first_consumer_op.inputs[0].quantization.scale_f32
304 ofm_scale = first_consumer_op.outputs[0].quantization.scale_f32
305 weight_scales = first_consumer_op.inputs[1].quantization.scale_f32
306
307 # biases can have multiple consumers for rnn cells. if so, then check that they are all the same
308 for op in tens.consumer_list[1:]:
309 assert ifm_scale == op.inputs[0].quantization.scale_f32
310 assert ofm_scale == op.outputs[0].quantization.scale_f32
311 assert weight_scales == op.inputs[1].quantization.scale_f32
312
313 if not hasattr(weight_scales, "__iter__"):
314 # If weight_scales is not already an iterable make it into a list
315 weight_scales = [weight_scales]
316
317 # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which
318 # uses double during scaling calculations
319 # TensorFlow Lite casts the scales slightly differently for uint8 and int8
320 if not rescale_for_faf:
321 if ifm_dtype == DataType.uint8:
322 scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200323 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100324 scales = [
325 (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale)
326 for weight_scale in weight_scales
327 ]
328 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200329 raise UnsupportedFeatureError(
330 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
331 )
Tim Hall79d07d22020-04-27 18:20:16 +0100332 else:
333 if ifm_dtype == DataType.uint8:
334 scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200335 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100336 scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales]
337 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200338 raise UnsupportedFeatureError(
339 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
340 )
Tim Hall79d07d22020-04-27 18:20:16 +0100341
342 # quantise all of the weight scales into (scale_factor, shift)
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200343 if ifm_dtype == DataType.int16:
344 quantised_scales = [reduced_quantise_scale(scale) for scale in scales]
345 else:
346 quantised_scales = [quantise_scale(scale) for scale in scales]
Tim Hall79d07d22020-04-27 18:20:16 +0100347
348 for _, shift in quantised_scales:
349 assert shift >= 16
350
351 # pack the biases and scales
352 tens.compressed_values = []
353 if len(quantised_scales) == 1:
354 # If only 1 quantised scale is used, repeat that value for the length of the biases
355 quantised_scales = [quantised_scales[0]] * len(biases)
356
357 assert len(quantised_scales) == len(biases)
358 for i, bias in enumerate(biases):
359 tens.compressed_values.append(pack_bias_and_scale(bias, *quantised_scales[i]))
360
361 tens.element_size_bytes = 10
362
363 # Figure out if we need padded storage (extra whole elements)
364 padding = (len(tens.compressed_values) * tens.element_size_bytes) % 16
365 if padding != 0:
366 padding = 16 - padding
367
368 # This adds enough padding to allow over-reads
369 while padding > 0:
370 tens.compressed_values.append(pack_bias_and_scale(0, 0, 0))
371 padding = padding - tens.element_size_bytes
372
373 tens.storage_shape = [len(tens.compressed_values)]
374
375
376def update_pass_weight_and_scale_tensors(nng, arch):
377 def find_npu_usage_of_tensor(tens):
378 # TODO: This function is identical to the one in mark_tensors.py. A common version should be used.
379 for op in tens.consumers():
380 if op.type == "DMA":
381 return find_npu_usage_of_tensor(op.outputs[0])
382 if "npu_block_type" in op.attrs:
383 return op.attrs["npu_block_type"]
384 return NpuBlockType.Default
385
386 for sg in nng.subgraphs:
387 for ps in sg.passes:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200388 tens = ps.weight_tensor
389 if tens is not None:
390 npu_usage_of_tensor = find_npu_usage_of_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100391 if npu_usage_of_tensor == NpuBlockType.ConvolutionDepthWise:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200392 tens.quant_values = np.transpose(tens.quant_values, (0, 1, 3, 2))
393 tens.shape = tens.storage_shape = tens.bandwidth_shape = list(tens.quant_values.shape)
394 tens.weight_transpose_depthwise = True
Tim Hall79d07d22020-04-27 18:20:16 +0100395
Louis Verhaard3c07c972020-05-07 08:12:58 +0200396 needs_dma = tens.needs_dma()
Tim Hall79d07d22020-04-27 18:20:16 +0100397 if ps.cascade.strategy == SchedulingStrategy.WeightStream and needs_dma:
398 ofm_depth_step = ps.block_config[-1]
399 else:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200400 ofm_depth_step = tens.shape[-1]
Tim Hall79d07d22020-04-27 18:20:16 +0100401 compress_weights(
Louis Verhaard3c07c972020-05-07 08:12:58 +0200402 arch, nng, tens, npu_usage_of_tensor, ps.block_config[-1], ofm_depth_step,
Tim Hall79d07d22020-04-27 18:20:16 +0100403 )
404 # Update source tensor
Louis Verhaard3c07c972020-05-07 08:12:58 +0200405 if needs_dma:
406 src_tens = tens.get_dma_src_tensor()
407 src_tens.shape = tens.shape
408 src_tens.quant_values = tens.quant_values
409 src_tens.copy_compressed_weight_info(tens)
410 set_storage_shape(src_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100411
Diego Russoea6111a2020-04-14 18:41:58 +0100412 if ps.scale_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100413 rescale_for_faf = False
414 activation_ops = set(("Sigmoid", "Tanh"))
415 if (ps.ops[-1].type in activation_ops) and (ps.npu_block_type != NpuBlockType.ElementWise):
416 rescale_for_faf = True
417 calc_scales_and_pack_biases(ps.scale_tensor, arch, ps.block_config[3], rescale_for_faf)