blob: df7ff751f7871b92ff54b8da6df5e4c199e8448d [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 +010022
Diego Russoe8a10452020-04-21 17:39:10 +010023from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020024from .errors import UnsupportedFeatureError
Diego Russoe8a10452020-04-21 17:39:10 +010025from .nn_graph import SchedulingStrategy
26from .numeric_util import round_up
27from .operation import NpuBlockType
28from .scaling import quantise_scale
29from .scaling import reduced_quantise_scale
30from .tensor import TensorBlockTraversal
31from .tensor import TensorFormat
32from .tensor import TensorPurpose
33from .tensor import TensorSubPurpose
Jacob Bohline843d332020-06-23 12:12:56 +020034from ethosu import mlw_codec
Diego Russoe8a10452020-04-21 17:39:10 +010035
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(
Louis Verhaardb2fb2122020-06-04 15:51:24 +020040 "WeightCompressionConfig", ["npu_block_type", "ofm_block_depth", "ofm_depth_step", "dilation", "equivalence_id"]
Louis Verhaard3c07c972020-05-07 08:12:58 +020041)
42
43
Louis Verhaardb2fb2122020-06-04 15:51:24 +020044def create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Louis Verhaard3c07c972020-05-07 08:12:58 +020045 # 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])
Louis Verhaardb2fb2122020-06-04 15:51:24 +020048 return WeightCompressionConfig(npu_block_type, block_depth, ofm_depth_step, dilation, tens.equivalence_id)
Louis Verhaard3c07c972020-05-07 08:12:58 +020049
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 Verhaardb2fb2122020-06-04 15:51:24 +020093def generate_brick(arch, brick_weights, ofm_block_depth, block_traversal, ifm_bitdepth, dilation):
Tim Hall79d07d22020-04-27 18:20:16 +010094 is_depthwise = block_traversal == TensorBlockTraversal.DepthWise
95 is_partkernel = block_traversal == TensorBlockTraversal.PartKernelFirst
Louis Verhaardb2fb2122020-06-04 15:51:24 +020096 decomp_h = arch.subkernel_max.height // dilation[0]
97 decomp_w = arch.subkernel_max.width // dilation[1]
Tim Hall79d07d22020-04-27 18:20:16 +010098 ofm_ublock = arch.ofm_ublock
99 ifm_ublock = arch.ifm_ublock
Tim Hallf7e810a2020-06-25 15:04:31 +0100100 # Expect weights formatted OHWI
101 ofm_depth = brick_weights.shape[-4]
102 ifm_depth = brick_weights.shape[-1]
103 kernel_width = brick_weights.shape[-2]
104 kernel_height = brick_weights.shape[-3]
Tim Hall79d07d22020-04-27 18:20:16 +0100105 # IFM block depth
106 if is_partkernel or (ifm_bitdepth == 16):
107 # IFM block depth is always 16 for part-kernel-first
108 ifm_block_depth = 16
109 elif ifm_bitdepth == 8:
110 ifm_block_depth = 32
111 else:
112 assert False
113
114 stream = []
115
116 # Top level striping - OFM blocks in the entire brick's depth
Louis Verhaard3c07c972020-05-07 08:12:58 +0200117 for ofm_block_z in range(0, ofm_depth, ofm_block_depth):
118 clipped_ofm_block_depth = min(ofm_block_depth, ofm_depth - ofm_block_z)
Tim Hall79d07d22020-04-27 18:20:16 +0100119 # IFM blocks required for the brick
120 for ifm_block_z in range(0, (1 if is_depthwise else ifm_depth), ifm_block_depth):
121 if is_depthwise:
122 clipped_ifm_block_depth = ifm_ublock.depth
123 else:
124 clipped_ifm_block_depth = (
125 min(ifm_block_depth, ifm_depth - ifm_block_z) if is_partkernel else ifm_block_depth
126 )
127 # Weight decomposition
128 # Subkernel Splitting (H)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200129 for subkernel_y in range(0, kernel_height, decomp_h):
130 sub_height = min(kernel_height - subkernel_y, decomp_h)
Tim Hall79d07d22020-04-27 18:20:16 +0100131 # Subkernel splitting (W)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200132 for subkernel_x in range(0, kernel_width, decomp_w):
133 sub_width = min(kernel_width - subkernel_x, decomp_w)
Tim Hall79d07d22020-04-27 18:20:16 +0100134 subkernel_elements = sub_width * sub_height
135 # Part kernel first works across the kernel H/W and needs padding
136 if is_partkernel:
137 if ifm_bitdepth == 16 and subkernel_elements % 2 != 0:
138 subkernel_elements = int(math.ceil(subkernel_elements / 2) * 2)
139 elif ifm_bitdepth == 8 and subkernel_elements % 4 != 0:
140 subkernel_elements = int(math.ceil(subkernel_elements / 4) * 4)
141
142 # Depthwise Conv requires multiple of 4 kernel elements in its weight block
143 # this is different from normal conv which is considered "weights depth-first"
144 elif is_depthwise:
145 subkernel_elements = int(math.ceil(subkernel_elements / 4.0) * 4)
146
147 ifm_block_depth_outer = clipped_ifm_block_depth if is_partkernel else 1
148 ifm_block_depth_inner = 1 if is_partkernel else clipped_ifm_block_depth
149 # IFM Ublocks in IFM-block over depth for part-kernel-first mode
150 # For depth-first IFM Ublocks are traversed after subkernel elements so this loop is ignored.
151 for ifm_ublk_outer in range(0, ifm_block_depth_outer, ifm_ublock.depth):
152 # OFM Ublocks in OFM-block over depth
153 for ofm_ublk in range(0, clipped_ofm_block_depth, ofm_ublock.depth):
154 # HW Kernel element traversal - cannot be a H/W loop due to element
155 # padding requirement on depthwise/part-kernel configurations
156 for element in range(subkernel_elements):
157 kx = element % sub_width
158 ky = element // sub_width
159 # IFM Ublocks in IFM-block over depth (only 1 ublock if depthwise)
160 # In case of part-kernel-first IFM Ublock traversal have already been handled
161 # and this loop is ignored.
162 for ifm_ublk_inner in range(0, ifm_block_depth_inner, ifm_ublock.depth):
163 # Feed OFM ublock elements
164 for ofm_ublock_z in range(ofm_ublock.depth):
165 # Source IFM ublock elements (only 1 element deep if depthwise)
166 for ifm_ublock_z in range(1 if is_depthwise else ifm_ublock.depth):
167 # Source position within the current subkernel
168 wx = subkernel_x + kx
169 wy = subkernel_y + ky
170 # Source IFM/OFM slices
171 ifm_ublk = ifm_ublk_inner + ifm_ublk_outer
172 ifm_z = ifm_block_z + ifm_ublk + ifm_ublock_z
173 ofm_z = ofm_block_z + ofm_ublk + ofm_ublock_z
174 if (ifm_z >= ifm_depth) or (ofm_z >= ofm_depth) or (ky >= sub_height):
175 stream.append(0)
176 else:
Tim Hallf7e810a2020-06-25 15:04:31 +0100177 stream.append(brick_weights[ofm_z][wy][wx][ifm_z])
Tim Hall79d07d22020-04-27 18:20:16 +0100178 return stream
179
Jacob Bohline843d332020-06-23 12:12:56 +0200180
Tim Hallf7e810a2020-06-25 15:04:31 +0100181def core_deinterleave(hwio, core, ncores):
182 # Put weights back into OHWI
Jacob Bohline843d332020-06-23 12:12:56 +0200183 ohwi = np.transpose(hwio, (3, 0, 1, 2))
184 return ohwi[core : ohwi.shape[0] : ncores]
185
Tim Hall79d07d22020-04-27 18:20:16 +0100186
187# Compress the weights
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200188def compress_weights(arch, nng, tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Tim Hall79d07d22020-04-27 18:20:16 +0100189 assert tens.purpose == TensorPurpose.Weights
190 assert tens.format == TensorFormat.WeightsCompressed
191
Louis Verhaard3c07c972020-05-07 08:12:58 +0200192 # Check the weight cache
193 if nng.weight_cache is None:
194 nng.weight_cache = CompressedWeightCache()
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200195 wcc = create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200196 tens.weight_compression_config = wcc
197 tens_cached = nng.weight_cache.get_tensor_with_same_compression(wcc)
198 if tens_cached is not None:
199 # Cache hit, copy weights from the cache
200 tens.copy_compressed_weight_info(tens_cached)
201 set_storage_shape(tens)
202 return
Tim Hall79d07d22020-04-27 18:20:16 +0100203
Louis Verhaard3c07c972020-05-07 08:12:58 +0200204 # No cache hit, perform the compression
Tim Hall79d07d22020-04-27 18:20:16 +0100205 assert tens.quantization is not None
206 assert tens.quantization.scale_f32 is not None
207 assert tens.quantization.zero_point is not None
208
209 zero_point = tens.quantization.zero_point
210 quant_buf = tens.quant_values.astype(np.int64)
211
212 # Early zero-point correction
213 weights = quant_buf - zero_point
214
215 if len(weights.shape) == 2:
216 weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0)
217 weights_shape = (weights.shape[0], 1, 1, weights.shape[1])
218 else:
219 weights_shape = weights.shape
220
221 compression_scales = []
222 compressed_offsets = []
223 encoded_streams = []
Tim Hallf7e810a2020-06-25 15:04:31 +0100224 encoded_streams_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100225 offset = 0
Tim Hallf7e810a2020-06-25 15:04:31 +0100226 max_single_buffer_len = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100227
228 ifm_bitdepth = tens.consumer_list[0].inputs[0].dtype.size_in_bits()
229 ifm_depth = weights.shape[-2]
230 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
231 tens.block_traversal = TensorBlockTraversal.DepthWise
232 if npu_block_type == NpuBlockType.ConvolutionMxN:
233 # Determine which block traversal strategy has better DPU utilization
234 kernel_size = weights_shape[0] * weights_shape[1]
235 depth_utilization = weights_shape[2] / round_up(weights_shape[2], 32 if ifm_bitdepth == 8 else 16)
236 part_kernel_utilization = (weights_shape[2] / round_up(weights_shape[2], 8)) * (
237 kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)
238 )
239 if part_kernel_utilization >= depth_utilization or ifm_depth <= 8:
240 # Part-kernel first is always better for ifm depths <= 8
241 tens.block_traversal = TensorBlockTraversal.PartKernelFirst
242 else:
243 tens.block_traversal = TensorBlockTraversal.DepthFirst
244
Jacob Bohlincf7da102020-05-20 09:03:40 +0200245 if tens.consumer_list[0].type == "Conv2DBackpropInputSwitchedBias":
246 # Transpose Convoluion, reverse weights in H and W axes
Tim Hallc30f4952020-06-15 20:47:35 +0100247 weights = np.flip(weights, axis=(0, 1))
Jacob Bohlincf7da102020-05-20 09:03:40 +0200248
Jacob Bohline843d332020-06-23 12:12:56 +0200249 # Calculate brick size
250 brick_size = (weights_shape[0], weights_shape[1], weights_shape[2], min(tens.shape[-1], ofm_depth_step))
251 elements_in_brick = np.prod(brick_size)
252
Tim Hall79d07d22020-04-27 18:20:16 +0100253 # Slice weight stream up depth-ways into bricks and compress
254 full_ofm_depth = quant_buf.shape[-1]
255 for idx in range(0, full_ofm_depth, ofm_depth_step):
256 # Get the weights necessary for this brick
257 count = min(full_ofm_depth - idx, ofm_depth_step)
258 brick_weights = weights[:, :, :, idx : idx + count]
259
Tim Hallf7e810a2020-06-25 15:04:31 +0100260 substream_offsets = [0]
261 encoded_stream = []
262 raw_size = 0
263
264 # For each core, deinterleave weights from the larger volume
265 # and generate separate compressed streams.
266 for core in range(0, min(arch.ncores, full_ofm_depth)):
267 core_weights = core_deinterleave(brick_weights, core, arch.ncores)
Tim Hall62316762020-06-25 16:55:02 +0100268
269 block_depth = (ofm_block_depth + arch.ncores - 1 - core) // arch.ncores
270 if block_depth != 0:
Jacob Bohline843d332020-06-23 12:12:56 +0200271 raw_stream = generate_brick(
272 arch, core_weights, block_depth, tens.block_traversal, ifm_bitdepth, dilation
273 )
Tim Hall62316762020-06-25 16:55:02 +0100274 else:
275 raw_stream = []
276
Jacob Bohline843d332020-06-23 12:12:56 +0200277 raw_size += len(raw_stream)
278 encoded_substream = encode(raw_stream)
279 encoded_stream.extend(encoded_substream)
280 substream_offsets.append(len(encoded_stream))
Tim Hallf7e810a2020-06-25 15:04:31 +0100281
Jacob Bohline843d332020-06-23 12:12:56 +0200282 encoded_streams.append(encoded_stream)
283 encoded_streams_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100284
285 # Remember maximum encoded length for DoubleBuffering
286 max_single_buffer_len = max(max_single_buffer_len, len(encoded_stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100287
Tim Hall79d07d22020-04-27 18:20:16 +0100288 # Remember where we put it for linear addressing
289 compressed_offsets.append(offset)
Tim Hallf7e810a2020-06-25 15:04:31 +0100290 offset += len(encoded_stream)
Tim Hall79d07d22020-04-27 18:20:16 +0100291 assert offset % 16 == 0
292
293 # Compression scale tracking
Jacob Bohline843d332020-06-23 12:12:56 +0200294 compression_scales.append(len(encoded_stream) / elements_in_brick)
Tim Hall79d07d22020-04-27 18:20:16 +0100295
Tim Hallf7e810a2020-06-25 15:04:31 +0100296 # Track total length as last element of the offsets array
Tim Hall79d07d22020-04-27 18:20:16 +0100297 compressed_offsets.append(offset)
298
Tim Hall79d07d22020-04-27 18:20:16 +0100299 tens.weight_compression_scales = compression_scales
Tim Hall79d07d22020-04-27 18:20:16 +0100300 tens.weight_compressed_offsets = compressed_offsets
301 tens.compression_scale_for_worst_weight_stream = np.amax(compression_scales)
302 tens.storage_compression_scale = tens.bandwidth_compression_scale = np.average(compression_scales)
303 tens.compressed_values = encoded_streams
Tim Hallf7e810a2020-06-25 15:04:31 +0100304 tens.compressed_values_substream_offsets = encoded_streams_substream_offsets
Jacob Bohline843d332020-06-23 12:12:56 +0200305 tens.brick_size = brick_size
Louis Verhaard3c07c972020-05-07 08:12:58 +0200306 set_storage_shape(tens)
307 nng.weight_cache.add(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100308
Jacob Bohline843d332020-06-23 12:12:56 +0200309
Tim Hallf7e810a2020-06-25 15:04:31 +0100310def calc_scales_and_pack_biases(tens, arch, ofm_depth_step, rescale_for_faf=False):
Tim Hall79d07d22020-04-27 18:20:16 +0100311 assert tens.purpose == TensorPurpose.FeatureMap
312 assert tens.format == TensorFormat.NHWC
313 # the connected operator should expect a bias input unless it is a FullyConnected
314 assert "Bias" in tens.consumer_list[0].type or tens.consumer_list[0].type.startswith("FullyConnected")
315 # the input bias tensor is the same as that connected to the operator
Jacob Bohlincf7da102020-05-20 09:03:40 +0200316 _, _, bias_tens, _ = tens.consumer_list[0].get_ifm_weights_biases_ofm()
317 assert tens is bias_tens
318
Tim Hall79d07d22020-04-27 18:20:16 +0100319 # the operator should only have a single output
320 assert len(tens.consumer_list[0].outputs) == 1
321
322 def pack_bias_and_scale(bias, scale, shift):
323 bias = np.int64(bias)
324 assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range
325 assert 0 <= scale < (1 << 32) # unsigned 32-bit range
326 assert 0 <= shift < (1 << 6) # unsigned 6-bit range
327
328 # pack the 80 bit value = [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)]
329 data = bytearray(10)
330 data[0] = (bias >> (0 * 8)) & 0xFF
331 data[1] = (bias >> (1 * 8)) & 0xFF
332 data[2] = (bias >> (2 * 8)) & 0xFF
333 data[3] = (bias >> (3 * 8)) & 0xFF
334 data[4] = (bias >> (4 * 8)) & 0xFF
335 data[5] = (scale >> (0 * 8)) & 0xFF
336 data[6] = (scale >> (1 * 8)) & 0xFF
337 data[7] = (scale >> (2 * 8)) & 0xFF
338 data[8] = (scale >> (3 * 8)) & 0xFF
339 data[9] = shift & 0x3F
340 return data
341
342 biases = tens.quant_values
343
344 first_consumer_op = tens.consumer_list[0]
345 ifm_dtype = first_consumer_op.inputs[0].dtype
346 ifm_scale = first_consumer_op.inputs[0].quantization.scale_f32
347 ofm_scale = first_consumer_op.outputs[0].quantization.scale_f32
348 weight_scales = first_consumer_op.inputs[1].quantization.scale_f32
349
350 # biases can have multiple consumers for rnn cells. if so, then check that they are all the same
351 for op in tens.consumer_list[1:]:
352 assert ifm_scale == op.inputs[0].quantization.scale_f32
353 assert ofm_scale == op.outputs[0].quantization.scale_f32
354 assert weight_scales == op.inputs[1].quantization.scale_f32
355
356 if not hasattr(weight_scales, "__iter__"):
357 # If weight_scales is not already an iterable make it into a list
358 weight_scales = [weight_scales]
359
360 # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which
361 # uses double during scaling calculations
362 # TensorFlow Lite casts the scales slightly differently for uint8 and int8
363 if not rescale_for_faf:
364 if ifm_dtype == DataType.uint8:
365 scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200366 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100367 scales = [
368 (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale)
369 for weight_scale in weight_scales
370 ]
371 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200372 raise UnsupportedFeatureError(
373 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
374 )
Tim Hall79d07d22020-04-27 18:20:16 +0100375 else:
376 if ifm_dtype == DataType.uint8:
377 scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200378 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100379 scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales]
380 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200381 raise UnsupportedFeatureError(
382 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
383 )
Tim Hall79d07d22020-04-27 18:20:16 +0100384
385 # quantise all of the weight scales into (scale_factor, shift)
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200386 if ifm_dtype == DataType.int16:
387 quantised_scales = [reduced_quantise_scale(scale) for scale in scales]
388 else:
389 quantised_scales = [quantise_scale(scale) for scale in scales]
Tim Hall79d07d22020-04-27 18:20:16 +0100390
391 for _, shift in quantised_scales:
392 assert shift >= 16
393
394 # pack the biases and scales
Tim Hall79d07d22020-04-27 18:20:16 +0100395 if len(quantised_scales) == 1:
396 # If only 1 quantised scale is used, repeat that value for the length of the biases
397 quantised_scales = [quantised_scales[0]] * len(biases)
398
399 assert len(quantised_scales) == len(biases)
Tim Hall79d07d22020-04-27 18:20:16 +0100400 tens.element_size_bytes = 10
Tim Hallf7e810a2020-06-25 15:04:31 +0100401 tens.compressed_values = []
402 tens.compressed_values_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100403
Tim Hallf7e810a2020-06-25 15:04:31 +0100404 total_elements = len(quantised_scales)
405 for i in range(0, total_elements, ofm_depth_step):
406 # Extract streams from brick to generate substreams for each core
407 stream = bytearray()
408 substream_offsets = [0]
409 max_len = min(ofm_depth_step, total_elements - i)
410 for core in range(0, min(arch.ncores, max_len)):
Jacob Bohline843d332020-06-23 12:12:56 +0200411 core_scales = quantised_scales[i + core : i + core + max_len : arch.ncores]
412 core_biases = biases[i + core : i + core + max_len : arch.ncores]
Tim Hallf7e810a2020-06-25 15:04:31 +0100413 for j, core_bias in enumerate(core_biases):
Jacob Bohline843d332020-06-23 12:12:56 +0200414 stream.extend(pack_bias_and_scale(core_bias, *core_scales[j]))
Tim Hall79d07d22020-04-27 18:20:16 +0100415
Tim Hallf7e810a2020-06-25 15:04:31 +0100416 # Align to 16 for start for next substream
Jacob Bohline843d332020-06-23 12:12:56 +0200417 remainder = (len(stream)) % 16
Tim Hallf7e810a2020-06-25 15:04:31 +0100418 if remainder > 0:
Jacob Bohline843d332020-06-23 12:12:56 +0200419 stream.extend(bytearray(16 - remainder))
Tim Hall79d07d22020-04-27 18:20:16 +0100420
Jacob Bohline843d332020-06-23 12:12:56 +0200421 substream_offsets.append(len(stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100422
Tim Hallf7e810a2020-06-25 15:04:31 +0100423 # Add to compressed values with their substream offset lists to the tensor
Jacob Bohline843d332020-06-23 12:12:56 +0200424 tens.compressed_values.append(stream)
425 tens.compressed_values_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100426
Tim Hallea499452020-07-07 12:04:37 +0100427 tens.storage_shape = [total_elements]
428
Tim Hall79d07d22020-04-27 18:20:16 +0100429
Jacob Bohline843d332020-06-23 12:12:56 +0200430
Tim Hall79d07d22020-04-27 18:20:16 +0100431def update_pass_weight_and_scale_tensors(nng, arch):
Tim Hall79d07d22020-04-27 18:20:16 +0100432 for sg in nng.subgraphs:
433 for ps in sg.passes:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200434 tens = ps.weight_tensor
435 if tens is not None:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200436 op = tens.find_npu_op()
437 npu_usage_of_tensor = op.attrs["npu_block_type"]
Louis Verhaard3c07c972020-05-07 08:12:58 +0200438 needs_dma = tens.needs_dma()
Tim Hall79d07d22020-04-27 18:20:16 +0100439 if ps.cascade.strategy == SchedulingStrategy.WeightStream and needs_dma:
440 ofm_depth_step = ps.block_config[-1]
441 else:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200442 ofm_depth_step = tens.shape[-1]
Tim Hall79d07d22020-04-27 18:20:16 +0100443 compress_weights(
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200444 arch, nng, tens, npu_usage_of_tensor, ps.block_config[-1], ofm_depth_step, op.get_dilation_h_w()
Tim Hall79d07d22020-04-27 18:20:16 +0100445 )
446 # Update source tensor
Louis Verhaard3c07c972020-05-07 08:12:58 +0200447 if needs_dma:
448 src_tens = tens.get_dma_src_tensor()
449 src_tens.shape = tens.shape
450 src_tens.quant_values = tens.quant_values
451 src_tens.copy_compressed_weight_info(tens)
452 set_storage_shape(src_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100453
Diego Russoea6111a2020-04-14 18:41:58 +0100454 if ps.scale_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100455 rescale_for_faf = False
456 activation_ops = set(("Sigmoid", "Tanh"))
457 if (ps.ops[-1].type in activation_ops) and (ps.npu_block_type != NpuBlockType.ElementWise):
458 rescale_for_faf = True
Tim Hallf7e810a2020-06-25 15:04:31 +0100459 calc_scales_and_pack_biases(ps.scale_tensor, arch, ofm_depth_step, rescale_for_faf)