blob: fa7d2d11a885cc0c27dcc9d72d30c0be74792d82 [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
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010023from .architecture_features import Accelerator
24from .architecture_features import ArchitectureFeatures
Diego Russoe8a10452020-04-21 17:39:10 +010025from .data_type import DataType
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010026from .errors import typecheck
Louis Verhaard7db78962020-05-25 15:05:26 +020027from .errors import UnsupportedFeatureError
Diego Russoe8a10452020-04-21 17:39:10 +010028from .nn_graph import SchedulingStrategy
29from .numeric_util import round_up
Patrik Gustavssond89c09e2020-07-08 11:27:12 +020030from .numeric_util import round_up_divide
Diego Russoe8a10452020-04-21 17:39:10 +010031from .operation import NpuBlockType
32from .scaling import quantise_scale
33from .scaling import reduced_quantise_scale
34from .tensor import TensorBlockTraversal
35from .tensor import TensorFormat
36from .tensor import TensorPurpose
37from .tensor import TensorSubPurpose
Jacob Bohline843d332020-06-23 12:12:56 +020038from ethosu import mlw_codec
Diego Russoe8a10452020-04-21 17:39:10 +010039
Tim Hall79d07d22020-04-27 18:20:16 +010040
Louis Verhaard3c07c972020-05-07 08:12:58 +020041# Contains meta info for a weight compression. If two tensors have identical weight compression config,
42# then they also will have identical compressed weights.
43WeightCompressionConfig = namedtuple(
Louis Verhaardb2fb2122020-06-04 15:51:24 +020044 "WeightCompressionConfig", ["npu_block_type", "ofm_block_depth", "ofm_depth_step", "dilation", "equivalence_id"]
Louis Verhaard3c07c972020-05-07 08:12:58 +020045)
46
47
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010048@typecheck
49def encode_weights(
50 accelerator: Accelerator,
51 weights_volume: np.ndarray,
52 dilation_xy: tuple,
53 ifm_bitdepth: int,
54 ofm_block_depth: int,
55 is_depthwise: bool,
56 is_partkernel: bool,
57):
58 """
59 Public facing API to use the ethosu weight encoding.
60
61 :param accelerator: architecture_features.Accelerator enum to pick the correct ethosu accelerator
62 :param weights_volume: numpy.ndarray in OHWI layout with a shape of four
63 :param dilation_xy: a two element tuple of dilation attributes in x,y dimension
64 :param ifm_bitdepth: the bitdepth of input feature map
65 :param ofm_block_depth: the depth of blocks for ethosu processing
66 :param is_depthwise: a boolean indicating these weights are used for a depthwise traversal
67 :param is_partkernel: a boolean indicating these weights are traversed on sub-kernal basis
68 :return: a bytearray of compressed weights
69 """
70
71 # Checks for weight layout
72 assert len(weights_volume.shape) == 4, "weights ndarray should have a shape of 4"
73
74 # It cannot be both partkernel and depthwise
75 assert not (is_depthwise and is_partkernel), "encode_weights :: partkernel and depthwise are mutually exclusive"
76
77 # Check valid values for dilation
78 assert dilation_xy[0] in (1, 2), "encode_weights :: dilation x should be 1 or 2 not {}".format(dilation_xy[0])
79 assert dilation_xy[1] in (1, 2), "encode_weights :: dilation y should be 1 or 2 not {}".format(dilation_xy[1])
80
81 ifm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ifm_ublock
82 ofm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ofm_ublock
83 raw_stream = generate_brick(
84 ifm_ublock=ifm_ublock,
85 ofm_ublock=ofm_ublock,
86 brick_weights=weights_volume,
87 ofm_block_depth=ofm_block_depth,
88 is_depthwise=is_depthwise,
89 is_partkernel=is_partkernel,
90 ifm_bitdepth=ifm_bitdepth,
91 dilation=dilation_xy,
92 )
93 encoded_stream = encode(raw_stream)
94 return encoded_stream
95
96
Manupa Karunaratnebef228b2020-07-29 18:06:28 +010097@typecheck
98def encode_bias(bias: np.int64, scale: int, shift: int):
99 """
100 Public facing API to pack bias and scale values as required by the hardware
101 :param bias: 64bit signed number that includes 40bit signed bias
102 :param scale: 32bit scale value
103 :param shift: 6bit shift value
104 :return: packed 80bit [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)]
105 """
106 assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range
107 assert 0 <= scale < (1 << 32) # unsigned 32-bit range
108 assert 0 <= shift < (1 << 6) # unsigned 6-bit range
109
110 data = bytearray(10)
111 data[0] = (bias >> (0 * 8)) & 0xFF
112 data[1] = (bias >> (1 * 8)) & 0xFF
113 data[2] = (bias >> (2 * 8)) & 0xFF
114 data[3] = (bias >> (3 * 8)) & 0xFF
115 data[4] = (bias >> (4 * 8)) & 0xFF
116 data[5] = (scale >> (0 * 8)) & 0xFF
117 data[6] = (scale >> (1 * 8)) & 0xFF
118 data[7] = (scale >> (2 * 8)) & 0xFF
119 data[8] = (scale >> (3 * 8)) & 0xFF
120 data[9] = shift & 0x3F
121 return data
122
123
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200124def create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Louis Verhaard3c07c972020-05-07 08:12:58 +0200125 # Note: for an ofm block only its depth is used in weight compression.
126 # And block depth > ofm depth gives same result as block depth == ofm depth
127 block_depth = min(ofm_block_depth, tens.quant_values.shape[-1])
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200128 return WeightCompressionConfig(npu_block_type, block_depth, ofm_depth_step, dilation, tens.equivalence_id)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200129
130
131def set_storage_shape(tens):
132 # Sets the storage shape depending on the tensor's sub purpose
133 if tens.sub_purpose == TensorSubPurpose.DoubleBuffer and len(tens.compressed_values) > 2:
134 offset = 2 * np.amax([len(x) for x in tens.compressed_values])
135 assert offset % 16 == 0
136 else:
137 offset = tens.weight_compressed_offsets[-1]
138 tens.storage_shape = [1, 1, 1, offset]
139
140
141class CompressedWeightCache:
142 # Contains weight compressions for all weight tensors in a graph
143 def __init__(self):
144 self.cache = {} # maps from WeightCompressionConfig to a tensor clone containing compressed weights
145
146 def get_tensor_with_same_compression(self, wcc):
147 return self.cache.get(wcc)
148
149 def add(self, tens):
150 # Adds the compressed weights from the tensor to the cache
151 wcc = tens.weight_compression_config
152 # Clone the tensor to make sure that nothing related to the weight compression is modified
153 tens_clone = tens.clone("_weights{}_{}".format(wcc.ofm_block_depth, wcc.ofm_depth_step))
154 self.cache[wcc] = tens_clone
155
156
Tim Hall79d07d22020-04-27 18:20:16 +0100157def encode(weight_stream):
Patrik Gustavsson5ff99442020-07-10 10:12:17 +0200158 if len(weight_stream) == 0:
159 return []
Tim Hall79d07d22020-04-27 18:20:16 +0100160 assert np.amin(weight_stream) >= -255
161 assert np.amax(weight_stream) <= 255
162
163 # Encode flattened signed weight stream
164 compressed = mlw_codec.encode(weight_stream)
165
166 # pad with 0xFF as needed so the length of the weight stream
167 # is a multiple of 16
Diego Russoea6111a2020-04-14 18:41:58 +0100168
Tim Hall79d07d22020-04-27 18:20:16 +0100169 while (len(compressed) % 16) != 0:
170 compressed.append(0xFF)
171
172 return compressed
173
174
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100175def generate_brick(
176 ifm_ublock, ofm_ublock, brick_weights, ofm_block_depth, is_depthwise, is_partkernel, ifm_bitdepth, dilation
177):
178
179 decomp_h = ArchitectureFeatures.SubKernelMax.height // dilation[0]
180 decomp_w = ArchitectureFeatures.SubKernelMax.width // dilation[1]
Tim Hallf7e810a2020-06-25 15:04:31 +0100181 # Expect weights formatted OHWI
182 ofm_depth = brick_weights.shape[-4]
183 ifm_depth = brick_weights.shape[-1]
184 kernel_width = brick_weights.shape[-2]
185 kernel_height = brick_weights.shape[-3]
Tim Hall79d07d22020-04-27 18:20:16 +0100186 # IFM block depth
187 if is_partkernel or (ifm_bitdepth == 16):
188 # IFM block depth is always 16 for part-kernel-first
189 ifm_block_depth = 16
190 elif ifm_bitdepth == 8:
191 ifm_block_depth = 32
192 else:
193 assert False
194
195 stream = []
196
197 # Top level striping - OFM blocks in the entire brick's depth
Louis Verhaard3c07c972020-05-07 08:12:58 +0200198 for ofm_block_z in range(0, ofm_depth, ofm_block_depth):
199 clipped_ofm_block_depth = min(ofm_block_depth, ofm_depth - ofm_block_z)
Tim Hall79d07d22020-04-27 18:20:16 +0100200 # IFM blocks required for the brick
201 for ifm_block_z in range(0, (1 if is_depthwise else ifm_depth), ifm_block_depth):
202 if is_depthwise:
203 clipped_ifm_block_depth = ifm_ublock.depth
204 else:
205 clipped_ifm_block_depth = (
206 min(ifm_block_depth, ifm_depth - ifm_block_z) if is_partkernel else ifm_block_depth
207 )
208 # Weight decomposition
209 # Subkernel Splitting (H)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200210 for subkernel_y in range(0, kernel_height, decomp_h):
211 sub_height = min(kernel_height - subkernel_y, decomp_h)
Tim Hall79d07d22020-04-27 18:20:16 +0100212 # Subkernel splitting (W)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200213 for subkernel_x in range(0, kernel_width, decomp_w):
214 sub_width = min(kernel_width - subkernel_x, decomp_w)
Tim Hall79d07d22020-04-27 18:20:16 +0100215 subkernel_elements = sub_width * sub_height
216 # Part kernel first works across the kernel H/W and needs padding
217 if is_partkernel:
218 if ifm_bitdepth == 16 and subkernel_elements % 2 != 0:
219 subkernel_elements = int(math.ceil(subkernel_elements / 2) * 2)
220 elif ifm_bitdepth == 8 and subkernel_elements % 4 != 0:
221 subkernel_elements = int(math.ceil(subkernel_elements / 4) * 4)
222
223 # Depthwise Conv requires multiple of 4 kernel elements in its weight block
224 # this is different from normal conv which is considered "weights depth-first"
225 elif is_depthwise:
226 subkernel_elements = int(math.ceil(subkernel_elements / 4.0) * 4)
227
228 ifm_block_depth_outer = clipped_ifm_block_depth if is_partkernel else 1
229 ifm_block_depth_inner = 1 if is_partkernel else clipped_ifm_block_depth
230 # IFM Ublocks in IFM-block over depth for part-kernel-first mode
231 # For depth-first IFM Ublocks are traversed after subkernel elements so this loop is ignored.
232 for ifm_ublk_outer in range(0, ifm_block_depth_outer, ifm_ublock.depth):
233 # OFM Ublocks in OFM-block over depth
234 for ofm_ublk in range(0, clipped_ofm_block_depth, ofm_ublock.depth):
235 # HW Kernel element traversal - cannot be a H/W loop due to element
236 # padding requirement on depthwise/part-kernel configurations
237 for element in range(subkernel_elements):
238 kx = element % sub_width
239 ky = element // sub_width
240 # IFM Ublocks in IFM-block over depth (only 1 ublock if depthwise)
241 # In case of part-kernel-first IFM Ublock traversal have already been handled
242 # and this loop is ignored.
243 for ifm_ublk_inner in range(0, ifm_block_depth_inner, ifm_ublock.depth):
244 # Feed OFM ublock elements
245 for ofm_ublock_z in range(ofm_ublock.depth):
246 # Source IFM ublock elements (only 1 element deep if depthwise)
247 for ifm_ublock_z in range(1 if is_depthwise else ifm_ublock.depth):
248 # Source position within the current subkernel
249 wx = subkernel_x + kx
250 wy = subkernel_y + ky
251 # Source IFM/OFM slices
252 ifm_ublk = ifm_ublk_inner + ifm_ublk_outer
253 ifm_z = ifm_block_z + ifm_ublk + ifm_ublock_z
254 ofm_z = ofm_block_z + ofm_ublk + ofm_ublock_z
255 if (ifm_z >= ifm_depth) or (ofm_z >= ofm_depth) or (ky >= sub_height):
256 stream.append(0)
257 else:
Tim Hallf7e810a2020-06-25 15:04:31 +0100258 stream.append(brick_weights[ofm_z][wy][wx][ifm_z])
Tim Hall79d07d22020-04-27 18:20:16 +0100259 return stream
260
Jacob Bohline843d332020-06-23 12:12:56 +0200261
Tim Hallf7e810a2020-06-25 15:04:31 +0100262def core_deinterleave(hwio, core, ncores):
263 # Put weights back into OHWI
Jacob Bohline843d332020-06-23 12:12:56 +0200264 ohwi = np.transpose(hwio, (3, 0, 1, 2))
265 return ohwi[core : ohwi.shape[0] : ncores]
266
Tim Hall79d07d22020-04-27 18:20:16 +0100267
268# Compress the weights
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200269def compress_weights(arch, nng, tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Tim Hall79d07d22020-04-27 18:20:16 +0100270 assert tens.purpose == TensorPurpose.Weights
271 assert tens.format == TensorFormat.WeightsCompressed
272
Louis Verhaard3c07c972020-05-07 08:12:58 +0200273 # Check the weight cache
274 if nng.weight_cache is None:
275 nng.weight_cache = CompressedWeightCache()
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200276 wcc = create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200277 tens.weight_compression_config = wcc
278 tens_cached = nng.weight_cache.get_tensor_with_same_compression(wcc)
279 if tens_cached is not None:
280 # Cache hit, copy weights from the cache
281 tens.copy_compressed_weight_info(tens_cached)
282 set_storage_shape(tens)
283 return
Tim Hall79d07d22020-04-27 18:20:16 +0100284
Louis Verhaard3c07c972020-05-07 08:12:58 +0200285 # No cache hit, perform the compression
Tim Hall79d07d22020-04-27 18:20:16 +0100286 assert tens.quantization is not None
287 assert tens.quantization.scale_f32 is not None
288 assert tens.quantization.zero_point is not None
289
290 zero_point = tens.quantization.zero_point
291 quant_buf = tens.quant_values.astype(np.int64)
292
293 # Early zero-point correction
294 weights = quant_buf - zero_point
295
296 if len(weights.shape) == 2:
297 weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0)
298 weights_shape = (weights.shape[0], 1, 1, weights.shape[1])
299 else:
300 weights_shape = weights.shape
301
302 compression_scales = []
303 compressed_offsets = []
304 encoded_streams = []
Tim Hallf7e810a2020-06-25 15:04:31 +0100305 encoded_streams_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100306 offset = 0
Tim Hallf7e810a2020-06-25 15:04:31 +0100307 max_single_buffer_len = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100308
309 ifm_bitdepth = tens.consumer_list[0].inputs[0].dtype.size_in_bits()
310 ifm_depth = weights.shape[-2]
311 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
312 tens.block_traversal = TensorBlockTraversal.DepthWise
313 if npu_block_type == NpuBlockType.ConvolutionMxN:
314 # Determine which block traversal strategy has better DPU utilization
315 kernel_size = weights_shape[0] * weights_shape[1]
316 depth_utilization = weights_shape[2] / round_up(weights_shape[2], 32 if ifm_bitdepth == 8 else 16)
317 part_kernel_utilization = (weights_shape[2] / round_up(weights_shape[2], 8)) * (
318 kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)
319 )
320 if part_kernel_utilization >= depth_utilization or ifm_depth <= 8:
321 # Part-kernel first is always better for ifm depths <= 8
322 tens.block_traversal = TensorBlockTraversal.PartKernelFirst
323 else:
324 tens.block_traversal = TensorBlockTraversal.DepthFirst
325
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100326 is_depthwise = tens.block_traversal == TensorBlockTraversal.DepthWise
327 is_partkernel = tens.block_traversal == TensorBlockTraversal.PartKernelFirst
328
Jacob Bohlincf7da102020-05-20 09:03:40 +0200329 if tens.consumer_list[0].type == "Conv2DBackpropInputSwitchedBias":
330 # Transpose Convoluion, reverse weights in H and W axes
Tim Hallc30f4952020-06-15 20:47:35 +0100331 weights = np.flip(weights, axis=(0, 1))
Jacob Bohlincf7da102020-05-20 09:03:40 +0200332
Jacob Bohline843d332020-06-23 12:12:56 +0200333 # Calculate brick size
334 brick_size = (weights_shape[0], weights_shape[1], weights_shape[2], min(tens.shape[-1], ofm_depth_step))
335 elements_in_brick = np.prod(brick_size)
336
Tim Hall79d07d22020-04-27 18:20:16 +0100337 # Slice weight stream up depth-ways into bricks and compress
338 full_ofm_depth = quant_buf.shape[-1]
339 for idx in range(0, full_ofm_depth, ofm_depth_step):
340 # Get the weights necessary for this brick
341 count = min(full_ofm_depth - idx, ofm_depth_step)
342 brick_weights = weights[:, :, :, idx : idx + count]
343
Tim Hallf7e810a2020-06-25 15:04:31 +0100344 substream_offsets = [0]
345 encoded_stream = []
Tim Hallf7e810a2020-06-25 15:04:31 +0100346
347 # For each core, deinterleave weights from the larger volume
348 # and generate separate compressed streams.
349 for core in range(0, min(arch.ncores, full_ofm_depth)):
350 core_weights = core_deinterleave(brick_weights, core, arch.ncores)
Tim Hall62316762020-06-25 16:55:02 +0100351
352 block_depth = (ofm_block_depth + arch.ncores - 1 - core) // arch.ncores
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100353 encoded_substream = []
Tim Hall62316762020-06-25 16:55:02 +0100354 if block_depth != 0:
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100355 encoded_substream = encode_weights(
356 accelerator=arch.accelerator_config,
357 weights_volume=core_weights,
358 dilation_xy=dilation,
359 ifm_bitdepth=ifm_bitdepth,
360 ofm_block_depth=block_depth,
361 is_depthwise=is_depthwise,
362 is_partkernel=is_partkernel,
Jacob Bohline843d332020-06-23 12:12:56 +0200363 )
Jacob Bohline843d332020-06-23 12:12:56 +0200364 encoded_stream.extend(encoded_substream)
365 substream_offsets.append(len(encoded_stream))
Tim Hallf7e810a2020-06-25 15:04:31 +0100366
Jacob Bohline843d332020-06-23 12:12:56 +0200367 encoded_streams.append(encoded_stream)
368 encoded_streams_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100369
370 # Remember maximum encoded length for DoubleBuffering
371 max_single_buffer_len = max(max_single_buffer_len, len(encoded_stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100372
Tim Hall79d07d22020-04-27 18:20:16 +0100373 # Remember where we put it for linear addressing
374 compressed_offsets.append(offset)
Tim Hallf7e810a2020-06-25 15:04:31 +0100375 offset += len(encoded_stream)
Tim Hall79d07d22020-04-27 18:20:16 +0100376 assert offset % 16 == 0
377
378 # Compression scale tracking
Jacob Bohline843d332020-06-23 12:12:56 +0200379 compression_scales.append(len(encoded_stream) / elements_in_brick)
Tim Hall79d07d22020-04-27 18:20:16 +0100380
Tim Hallf7e810a2020-06-25 15:04:31 +0100381 # Track total length as last element of the offsets array
Tim Hall79d07d22020-04-27 18:20:16 +0100382 compressed_offsets.append(offset)
383
Tim Hall79d07d22020-04-27 18:20:16 +0100384 tens.weight_compression_scales = compression_scales
Tim Hall79d07d22020-04-27 18:20:16 +0100385 tens.weight_compressed_offsets = compressed_offsets
386 tens.compression_scale_for_worst_weight_stream = np.amax(compression_scales)
387 tens.storage_compression_scale = tens.bandwidth_compression_scale = np.average(compression_scales)
388 tens.compressed_values = encoded_streams
Tim Hallf7e810a2020-06-25 15:04:31 +0100389 tens.compressed_values_substream_offsets = encoded_streams_substream_offsets
Jacob Bohline843d332020-06-23 12:12:56 +0200390 tens.brick_size = brick_size
Louis Verhaard3c07c972020-05-07 08:12:58 +0200391 set_storage_shape(tens)
392 nng.weight_cache.add(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100393
Jacob Bohline843d332020-06-23 12:12:56 +0200394
Tim Hallf7e810a2020-06-25 15:04:31 +0100395def calc_scales_and_pack_biases(tens, arch, ofm_depth_step, rescale_for_faf=False):
Tim Hall79d07d22020-04-27 18:20:16 +0100396 assert tens.purpose == TensorPurpose.FeatureMap
397 assert tens.format == TensorFormat.NHWC
398 # the connected operator should expect a bias input unless it is a FullyConnected
399 assert "Bias" in tens.consumer_list[0].type or tens.consumer_list[0].type.startswith("FullyConnected")
400 # the input bias tensor is the same as that connected to the operator
Jacob Bohlincf7da102020-05-20 09:03:40 +0200401 _, _, bias_tens, _ = tens.consumer_list[0].get_ifm_weights_biases_ofm()
402 assert tens is bias_tens
403
Tim Hall79d07d22020-04-27 18:20:16 +0100404 # the operator should only have a single output
405 assert len(tens.consumer_list[0].outputs) == 1
Tim Hall79d07d22020-04-27 18:20:16 +0100406 biases = tens.quant_values
407
408 first_consumer_op = tens.consumer_list[0]
409 ifm_dtype = first_consumer_op.inputs[0].dtype
410 ifm_scale = first_consumer_op.inputs[0].quantization.scale_f32
411 ofm_scale = first_consumer_op.outputs[0].quantization.scale_f32
412 weight_scales = first_consumer_op.inputs[1].quantization.scale_f32
413
414 # biases can have multiple consumers for rnn cells. if so, then check that they are all the same
415 for op in tens.consumer_list[1:]:
416 assert ifm_scale == op.inputs[0].quantization.scale_f32
417 assert ofm_scale == op.outputs[0].quantization.scale_f32
418 assert weight_scales == op.inputs[1].quantization.scale_f32
419
420 if not hasattr(weight_scales, "__iter__"):
421 # If weight_scales is not already an iterable make it into a list
422 weight_scales = [weight_scales]
423
424 # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which
425 # uses double during scaling calculations
426 # TensorFlow Lite casts the scales slightly differently for uint8 and int8
427 if not rescale_for_faf:
428 if ifm_dtype == DataType.uint8:
429 scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200430 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100431 scales = [
432 (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale)
433 for weight_scale in weight_scales
434 ]
435 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200436 raise UnsupportedFeatureError(
437 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
438 )
Tim Hall79d07d22020-04-27 18:20:16 +0100439 else:
440 if ifm_dtype == DataType.uint8:
441 scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200442 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100443 scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales]
444 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200445 raise UnsupportedFeatureError(
446 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
447 )
Tim Hall79d07d22020-04-27 18:20:16 +0100448
449 # quantise all of the weight scales into (scale_factor, shift)
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200450 if ifm_dtype == DataType.int16:
451 quantised_scales = [reduced_quantise_scale(scale) for scale in scales]
452 else:
453 quantised_scales = [quantise_scale(scale) for scale in scales]
Tim Hall79d07d22020-04-27 18:20:16 +0100454
455 for _, shift in quantised_scales:
456 assert shift >= 16
457
458 # pack the biases and scales
Tim Hall79d07d22020-04-27 18:20:16 +0100459 if len(quantised_scales) == 1:
460 # If only 1 quantised scale is used, repeat that value for the length of the biases
461 quantised_scales = [quantised_scales[0]] * len(biases)
462
463 assert len(quantised_scales) == len(biases)
Tim Hall79d07d22020-04-27 18:20:16 +0100464 tens.element_size_bytes = 10
Tim Hallf7e810a2020-06-25 15:04:31 +0100465 tens.compressed_values = []
466 tens.compressed_values_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100467
Tim Hallf7e810a2020-06-25 15:04:31 +0100468 total_elements = len(quantised_scales)
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200469 alignment_bytes = 0
Tim Hallf7e810a2020-06-25 15:04:31 +0100470 for i in range(0, total_elements, ofm_depth_step):
471 # Extract streams from brick to generate substreams for each core
472 stream = bytearray()
473 substream_offsets = [0]
474 max_len = min(ofm_depth_step, total_elements - i)
475 for core in range(0, min(arch.ncores, max_len)):
Jacob Bohline843d332020-06-23 12:12:56 +0200476 core_scales = quantised_scales[i + core : i + core + max_len : arch.ncores]
477 core_biases = biases[i + core : i + core + max_len : arch.ncores]
Tim Hallf7e810a2020-06-25 15:04:31 +0100478 for j, core_bias in enumerate(core_biases):
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100479 stream.extend(encode_bias(np.int64(core_bias), *core_scales[j]))
Tim Hall79d07d22020-04-27 18:20:16 +0100480
Tim Hallf7e810a2020-06-25 15:04:31 +0100481 # Align to 16 for start for next substream
Jacob Bohline843d332020-06-23 12:12:56 +0200482 remainder = (len(stream)) % 16
Tim Hallf7e810a2020-06-25 15:04:31 +0100483 if remainder > 0:
Jacob Bohline843d332020-06-23 12:12:56 +0200484 stream.extend(bytearray(16 - remainder))
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200485 alignment_bytes += 16 - remainder
Tim Hall79d07d22020-04-27 18:20:16 +0100486
Jacob Bohline843d332020-06-23 12:12:56 +0200487 substream_offsets.append(len(stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100488
Tim Hallf7e810a2020-06-25 15:04:31 +0100489 # Add to compressed values with their substream offset lists to the tensor
Jacob Bohline843d332020-06-23 12:12:56 +0200490 tens.compressed_values.append(stream)
491 tens.compressed_values_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100492
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200493 tens.storage_shape = [total_elements + round_up_divide(alignment_bytes, tens.element_size_bytes)]
Tim Hall79d07d22020-04-27 18:20:16 +0100494
Jacob Bohline843d332020-06-23 12:12:56 +0200495
Tim Hall79d07d22020-04-27 18:20:16 +0100496def update_pass_weight_and_scale_tensors(nng, arch):
Tim Hall79d07d22020-04-27 18:20:16 +0100497 for sg in nng.subgraphs:
498 for ps in sg.passes:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200499 tens = ps.weight_tensor
500 if tens is not None:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200501 op = tens.find_npu_op()
502 npu_usage_of_tensor = op.attrs["npu_block_type"]
Louis Verhaard3c07c972020-05-07 08:12:58 +0200503 needs_dma = tens.needs_dma()
Tim Hall79d07d22020-04-27 18:20:16 +0100504 if ps.cascade.strategy == SchedulingStrategy.WeightStream and needs_dma:
505 ofm_depth_step = ps.block_config[-1]
506 else:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200507 ofm_depth_step = tens.shape[-1]
Tim Hall79d07d22020-04-27 18:20:16 +0100508 compress_weights(
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200509 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 +0100510 )
511 # Update source tensor
Louis Verhaard3c07c972020-05-07 08:12:58 +0200512 if needs_dma:
513 src_tens = tens.get_dma_src_tensor()
514 src_tens.shape = tens.shape
515 src_tens.quant_values = tens.quant_values
516 src_tens.copy_compressed_weight_info(tens)
517 set_storage_shape(src_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100518
Diego Russoea6111a2020-04-14 18:41:58 +0100519 if ps.scale_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100520 rescale_for_faf = False
521 activation_ops = set(("Sigmoid", "Tanh"))
522 if (ps.ops[-1].type in activation_ops) and (ps.npu_block_type != NpuBlockType.ElementWise):
523 rescale_for_faf = True
Tim Hallf7e810a2020-06-25 15:04:31 +0100524 calc_scales_and_pack_biases(ps.scale_tensor, arch, ofm_depth_step, rescale_for_faf)