blob: 86b424a4b3afb5849a3ed12f9dfcb7fa8f0567a1 [file] [log] [blame]
erik.andersson@arm.com460c6892021-02-24 14:38:09 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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 +010018from collections import namedtuple
Tim Halld8339a72021-05-27 18:49:40 +010019from collections import OrderedDict
Jonas Ohlsson845e2322022-03-01 12:39:55 +010020from typing import Dict
21from typing import Optional
Louis Verhaardaeae5672020-11-02 18:04:27 +010022from typing import Tuple
Diego Russoea6111a2020-04-14 18:41:58 +010023
24import numpy as np
Tim Hall79d07d22020-04-27 18:20:16 +010025
Louis Verhaarde8a5a782020-11-02 18:04:27 +010026from .api import NpuBlockTraversal
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010027from .architecture_features import Accelerator
28from .architecture_features import ArchitectureFeatures
Diego Russoe8a10452020-04-21 17:39:10 +010029from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020030from .errors import UnsupportedFeatureError
Diego Russoe8a10452020-04-21 17:39:10 +010031from .numeric_util import round_up
32from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020033from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010034from .scaling import quantise_scale
35from .scaling import reduced_quantise_scale
Tim Halld8339a72021-05-27 18:49:40 +010036from .tensor import Tensor
Diego Russoe8a10452020-04-21 17:39:10 +010037from .tensor import TensorFormat
38from .tensor import TensorPurpose
Jacob Bohline843d332020-06-23 12:12:56 +020039from ethosu import mlw_codec
Diego Russoe8a10452020-04-21 17:39:10 +010040
Tim Hall79d07d22020-04-27 18:20:16 +010041
Louis Verhaard3c07c972020-05-07 08:12:58 +020042# Contains meta info for a weight compression. If two tensors have identical weight compression config,
43# then they also will have identical compressed weights.
44WeightCompressionConfig = namedtuple(
Jonas Ohlssond8575072022-03-30 10:30:25 +020045 "WeightCompressionConfig",
46 ["npu_block_type", "ofm_block_depth", "ofm_depth_step", "dilation", "weight_value_id"],
Louis Verhaard3c07c972020-05-07 08:12:58 +020047)
48
Tim Halld784af72021-06-08 21:25:57 +010049ScaleCompressionConfig = namedtuple("ScaleCompressionConfig", ["scale_value_id", "ifm_scale", "ofm_scale"])
50
Tim Halld8339a72021-05-27 18:49:40 +010051WeightKey = namedtuple("WeightKey", ["core", "depth"])
52
53
54class WeightRange:
55 def __init__(self):
56 self.offset = 0
57 self.scale_bytes = 0
58 self.weight_offset = 0
59 self.weight_bytes = 0
60 self.index = 0
61
62 @property
63 def total_bytes(self):
64 return self.scale_bytes + self.weight_bytes
65
66
67class NpuWeightTensor(Tensor):
68 def __init__(self, name):
69 Tensor.__init__(self, None, None, name + "_npu_encoded_weights")
70 self.buffer = []
Tim Hallb5df7732022-05-04 16:20:43 +010071 self.max_range_bytes = 0
Tim Halld8339a72021-05-27 18:49:40 +010072 self.encoded_ranges = OrderedDict()
73 self.hw_traversal = NpuBlockTraversal.DEPTH_FIRST
74 self.dtype = DataType.uint8
Tim Halld784af72021-06-08 21:25:57 +010075 self.scale_compression_config = None
Tim Halld8339a72021-05-27 18:49:40 +010076
77
78class CompressedWeightCache:
79 """Global tensor weight compression cache"""
80
Jonas Ohlsson845e2322022-03-01 12:39:55 +010081 cache: Dict[WeightCompressionConfig, Tensor] = {}
Tim Halld8339a72021-05-27 18:49:40 +010082
83 @staticmethod
84 def get_tensor_with_same_compression(wcc):
85 return CompressedWeightCache.cache.get(wcc)
86
87 @staticmethod
88 def add(tens):
89 # Adds the compressed weights from the tensor to the cache
90 wcc = tens.weight_compression_config
91 CompressedWeightCache.cache[wcc] = tens
92
93 @staticmethod
94 def has_tensor_with_same_compression(wcc):
95 return wcc in CompressedWeightCache.cache
96
97 @staticmethod
98 def get_unencoded_size_with_same_compression(wcc):
99 cache_obj = CompressedWeightCache.cache.get(wcc)
100 return cache_obj[1] if cache_obj else None
101
102
Tim Halld784af72021-06-08 21:25:57 +0100103def create_weight_compression_config(weight_tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Tim Halld8339a72021-05-27 18:49:40 +0100104 # Note: for an ofm block only its depth is used in weight compression.
105 # And block depth > ofm depth gives same result as block depth == ofm depth
James Peet7519d502021-07-19 16:47:58 +0100106 block_depth = min(ofm_block_depth, weight_tens.values.shape[-1])
Tim Halld784af72021-06-08 21:25:57 +0100107 return WeightCompressionConfig(npu_block_type, block_depth, ofm_depth_step, dilation, weight_tens.value_id)
Tim Halld8339a72021-05-27 18:49:40 +0100108
Louis Verhaard3c07c972020-05-07 08:12:58 +0200109
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100110def encode_weights(
111 accelerator: Accelerator,
112 weights_volume: np.ndarray,
Louis Verhaardaeae5672020-11-02 18:04:27 +0100113 dilation_xy: Tuple[int, int],
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100114 ifm_bitdepth: int,
115 ofm_block_depth: int,
116 is_depthwise: bool,
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100117 block_traversal: NpuBlockTraversal,
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100118):
119 """
Louis Verhaardaeae5672020-11-02 18:04:27 +0100120 Internal implementation of the public facing API to use weight encoding.
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100121
Tim Hallc8a73862020-10-27 12:43:14 +0000122 :param accelerator: architecture_features.Accelerator enum to pick the correct Ethos-U accelerator
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100123 :param weights_volume: numpy.ndarray in OHWI layout with a shape of four
124 :param dilation_xy: a two element tuple of dilation attributes in x,y dimension
125 :param ifm_bitdepth: the bitdepth of input feature map
Tim Hallc8a73862020-10-27 12:43:14 +0000126 :param ofm_block_depth: the depth of blocks for Ethos-U processing
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100127 :param is_depthwise: a boolean indicating these weights are used for a depthwise traversal
Louis Verhaardaeae5672020-11-02 18:04:27 +0100128 :param block_traversal: indicates how these weights are traversed on sub-kernel basis
129
Fredrik Svedbergf5c07c42021-04-23 14:36:42 +0200130 :return: a tuple with a bytearray of encoded weights and the size of the unencoded weights
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100131 """
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +0000132 # Check arg types
133 assert isinstance(accelerator, Accelerator)
134 assert isinstance(weights_volume, np.ndarray)
135 assert isinstance(dilation_xy, tuple)
136 assert isinstance(ifm_bitdepth, int)
137 assert isinstance(ofm_block_depth, int)
138 assert isinstance(is_depthwise, bool)
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100139 assert isinstance(block_traversal, NpuBlockTraversal)
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +0000140
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100141 # Checks for weight layout
142 assert len(weights_volume.shape) == 4, "weights ndarray should have a shape of 4"
143
144 # It cannot be both partkernel and depthwise
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100145 assert not (
146 is_depthwise and block_traversal == NpuBlockTraversal.PART_KERNEL_FIRST
147 ), "encode_weights :: partkernel and depthwise are mutually exclusive"
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100148
149 # Check valid values for dilation
150 assert dilation_xy[0] in (1, 2), "encode_weights :: dilation x should be 1 or 2 not {}".format(dilation_xy[0])
151 assert dilation_xy[1] in (1, 2), "encode_weights :: dilation y should be 1 or 2 not {}".format(dilation_xy[1])
152
153 ifm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ifm_ublock
154 ofm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ofm_ublock
James Peetc2449822021-07-19 17:09:16 +0100155 decomp_h = ArchitectureFeatures.SubKernelMax.height // dilation_xy[1]
156 decomp_w = ArchitectureFeatures.SubKernelMax.width // dilation_xy[0]
Mauricio Briceno67e11f72021-05-05 12:47:28 +0200157
158 return mlw_codec.reorder_encode(
159 ifm_ublock.depth,
160 ofm_ublock.depth,
161 weights_volume,
162 ofm_block_depth,
163 is_depthwise,
164 block_traversal == NpuBlockTraversal.PART_KERNEL_FIRST,
165 ifm_bitdepth,
166 decomp_h,
167 decomp_w,
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100168 )
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100169
170
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100171def encode_bias(bias: np.int64, scale: int, shift: int):
172 """
Louis Verhaardaeae5672020-11-02 18:04:27 +0100173 Internal implementation of public facing API to pack bias and scale values as required by the Ethos-U
Tim Hallc8a73862020-10-27 12:43:14 +0000174
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100175 :param bias: 64bit signed number that includes 40bit signed bias
176 :param scale: 32bit scale value
177 :param shift: 6bit shift value
178 :return: packed 80bit [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)]
179 """
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +0000180 # Check arg types
181 assert isinstance(bias, np.int64)
182 assert isinstance(scale, int)
183 assert isinstance(shift, int)
184
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100185 assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range
186 assert 0 <= scale < (1 << 32) # unsigned 32-bit range
187 assert 0 <= shift < (1 << 6) # unsigned 6-bit range
188
189 data = bytearray(10)
190 data[0] = (bias >> (0 * 8)) & 0xFF
191 data[1] = (bias >> (1 * 8)) & 0xFF
192 data[2] = (bias >> (2 * 8)) & 0xFF
193 data[3] = (bias >> (3 * 8)) & 0xFF
194 data[4] = (bias >> (4 * 8)) & 0xFF
195 data[5] = (scale >> (0 * 8)) & 0xFF
196 data[6] = (scale >> (1 * 8)) & 0xFF
197 data[7] = (scale >> (2 * 8)) & 0xFF
198 data[8] = (scale >> (3 * 8)) & 0xFF
199 data[9] = shift & 0x3F
200 return data
201
202
Tim Hallf7e810a2020-06-25 15:04:31 +0100203def core_deinterleave(hwio, core, ncores):
204 # Put weights back into OHWI
Jacob Bohline843d332020-06-23 12:12:56 +0200205 ohwi = np.transpose(hwio, (3, 0, 1, 2))
206 return ohwi[core : ohwi.shape[0] : ncores]
207
Tim Hall79d07d22020-04-27 18:20:16 +0100208
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200209def _prepare_scale_and_bias(arch, tens, rescale_for_faf, explicit_scaling):
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100210 assert tens.purpose in [TensorPurpose.FeatureMap, TensorPurpose.FSBias]
Tim Hall79d07d22020-04-27 18:20:16 +0100211 assert tens.format == TensorFormat.NHWC
212 # the connected operator should expect a bias input unless it is a FullyConnected
Louis Verhaardaee5d752020-09-30 09:01:52 +0200213 assert tens.consumer_list[0].type.needs_bias()
Tim Hall79d07d22020-04-27 18:20:16 +0100214 # the input bias tensor is the same as that connected to the operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200215 bias_tens = tens.consumer_list[0].bias
Jacob Bohlincf7da102020-05-20 09:03:40 +0200216 assert tens is bias_tens
217
Tim Hall79d07d22020-04-27 18:20:16 +0100218 # the operator should only have a single output
219 assert len(tens.consumer_list[0].outputs) == 1
James Peet7519d502021-07-19 16:47:58 +0100220 biases = tens.values
Tim Hall79d07d22020-04-27 18:20:16 +0100221
222 first_consumer_op = tens.consumer_list[0]
223 ifm_dtype = first_consumer_op.inputs[0].dtype
Dwight Lidman4f728c02020-12-17 15:14:45 +0100224 ifm_scale = first_consumer_op.get_input_quantization().scale_f32
Louis Verhaard98a34992020-09-01 10:39:04 +0200225 ofm_scale = first_consumer_op.get_output_quantization().scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100226 weight_scales = first_consumer_op.inputs[1].quantization.scale_f32
227
228 # biases can have multiple consumers for rnn cells. if so, then check that they are all the same
229 for op in tens.consumer_list[1:]:
Dwight Lidman4f728c02020-12-17 15:14:45 +0100230 assert ifm_scale == op.get_input_quantization().scale_f32
Louis Verhaard98a34992020-09-01 10:39:04 +0200231 assert ofm_scale == op.get_output_quantization().scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100232 assert weight_scales == op.inputs[1].quantization.scale_f32
233
234 if not hasattr(weight_scales, "__iter__"):
235 # If weight_scales is not already an iterable make it into a list
236 weight_scales = [weight_scales]
237
238 # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which
239 # uses double during scaling calculations
240 # TensorFlow Lite casts the scales slightly differently for uint8 and int8
241 if not rescale_for_faf:
242 if ifm_dtype == DataType.uint8:
Dwight Lidman4f728c02020-12-17 15:14:45 +0100243 # for some cases of the Mean operator, the scale must be calculated differently to match reference
244 if first_consumer_op.low_precision_scaling:
245 scales = [
246 np.double(np.single(ifm_scale) / (np.single(weight_scale) * np.single(ofm_scale)))
247 for weight_scale in weight_scales
248 ]
249 else:
250 scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200251 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100252 scales = [
253 (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale)
254 for weight_scale in weight_scales
255 ]
256 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000257 raise UnsupportedFeatureError(f"Compression of {ifm_dtype} is not implemented; Tensor: '{tens.name}'")
Tim Hall79d07d22020-04-27 18:20:16 +0100258 else:
259 if ifm_dtype == DataType.uint8:
260 scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200261 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100262 scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales]
263 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000264 raise UnsupportedFeatureError(f"Compression of {ifm_dtype} is not implemented; Tensor: '{tens.name}'")
Tim Hall79d07d22020-04-27 18:20:16 +0100265
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200266 if explicit_scaling:
267 assert len(explicit_scaling.shift) == len(explicit_scaling.multiplier)
268 quantised_scales = [(int(m), int(s)) for s, m in zip(explicit_scaling.shift, explicit_scaling.multiplier)]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200269 else:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200270 # quantise all of the weight scales into (scale_factor, shift)
271 if ifm_dtype == DataType.int16:
272 quantised_scales = [reduced_quantise_scale(scale) for scale in scales]
273 else:
274 quantised_scales = [quantise_scale(scale) for scale in scales]
Tim Hall79d07d22020-04-27 18:20:16 +0100275
Tim Halld8339a72021-05-27 18:49:40 +0100276 # If only 1 quantised scale is used, repeat that value for the length of the biases
Tim Hall79d07d22020-04-27 18:20:16 +0100277 if len(quantised_scales) == 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100278 quantised_scales = [quantised_scales[0]] * len(biases)
279
Tim Halld8339a72021-05-27 18:49:40 +0100280 return quantised_scales, biases
Tim Hall79d07d22020-04-27 18:20:16 +0100281
Jacob Bohline843d332020-06-23 12:12:56 +0200282
Tim Halld8339a72021-05-27 18:49:40 +0100283def encode_weight_and_scale_tensor(
284 arch, op, weight_tens, scale_tens, kernel, block_config, depth_offsets, rescale_for_faf=False
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100285) -> Tuple[Optional[NpuWeightTensor], Optional[NpuWeightTensor]]:
Tim Halld8339a72021-05-27 18:49:40 +0100286 npu_block_type = op.type.npu_block_type
287
Tim Halld784af72021-06-08 21:25:57 +0100288 ifm_scale = scale_tens and scale_tens.consumer_list[0].get_input_quantization().scale_f32
289 ofm_scale = scale_tens and scale_tens.consumer_list[0].get_output_quantization().scale_f32
290
Tim Halld8339a72021-05-27 18:49:40 +0100291 wcc = create_weight_compression_config(
Tim Halld784af72021-06-08 21:25:57 +0100292 weight_tens, npu_block_type, block_config.ofm_block.depth, hash(str(depth_offsets)), kernel.dilation
Tim Halld8339a72021-05-27 18:49:40 +0100293 )
294
Tim Halld784af72021-06-08 21:25:57 +0100295 scc = ScaleCompressionConfig(scale_tens and scale_tens.value_id, ifm_scale, ofm_scale)
296
Tim Halld8339a72021-05-27 18:49:40 +0100297 tens_cached = CompressedWeightCache.get_tensor_with_same_compression(wcc)
298 if tens_cached is not None:
Tim Halld784af72021-06-08 21:25:57 +0100299 if tens_cached.scale_compression_config == scc:
300 return tens_cached, None
301 npu_tensor = NpuWeightTensor(scale_tens.name)
302 do_weights = False
303 do_scales = True
304 else:
305 npu_tensor = NpuWeightTensor(weight_tens.name)
306 do_weights = True
307 do_scales = True
Tim Halld8339a72021-05-27 18:49:40 +0100308
Tim Halld8339a72021-05-27 18:49:40 +0100309 npu_tensor.weight_compression_config = wcc
Tim Halld784af72021-06-08 21:25:57 +0100310 npu_tensor.scale_compression_config = scc
Tim Halld8339a72021-05-27 18:49:40 +0100311
Tim Halld8339a72021-05-27 18:49:40 +0100312 # Ensure depth offsets are terminated at end of OFM shape
313 assert len(depth_offsets) > 1, "Require closed depth ranges"
314
315 ifm_bitdepth = op.inputs[0].dtype.size_in_bits()
Tim Halld8339a72021-05-27 18:49:40 +0100316
Tim Halld784af72021-06-08 21:25:57 +0100317 # No cache hit, need to perform the encoding
318 if do_weights:
319 assert weight_tens.quantization is not None
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200320 assert weight_tens.quantization.scale_f32 is not None or op.explicit_scaling
Tim Halld784af72021-06-08 21:25:57 +0100321 assert weight_tens.quantization.zero_point is not None
Tim Halld8339a72021-05-27 18:49:40 +0100322
Tim Halld784af72021-06-08 21:25:57 +0100323 # Early zero-point correction
James Peet7519d502021-07-19 16:47:58 +0100324 quant_buf = weight_tens.values.astype(np.int16)
Tim Hallb2798442021-06-24 19:31:38 +0100325 # the zero point can be either a native or numpy type
326 if isinstance(weight_tens.quantization.zero_point, (int, float)):
327 zero_point = np.int16(weight_tens.quantization.zero_point)
328 else:
329 zero_point = weight_tens.quantization.zero_point.astype(np.int16)
330 weights = quant_buf - zero_point
Tim Halld8339a72021-05-27 18:49:40 +0100331
Tim Halld784af72021-06-08 21:25:57 +0100332 if len(weights.shape) == 2:
333 weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0)
334
335 # Expect this (undilated) equivalence
336 assert kernel.height == weights.shape[0]
337 assert kernel.width == weights.shape[1]
338
339 ifm_depth = weights.shape[-2]
340
341 # Default HW traversal
342 npu_tensor.hw_traversal = NpuBlockTraversal.DEPTH_FIRST
343
344 if npu_block_type == NpuBlockType.ConvolutionMxN:
345 # Determine which block traversal strategy has better DPU utilization
346 kernel_size = weights.shape[0] * weights.shape[1]
347 depth_utilization = weights.shape[2] / round_up(weights.shape[2], 32 if ifm_bitdepth == 8 else 16)
348 part_kernel_utilization = (weights.shape[2] / round_up(weights.shape[2], 8)) * (
349 kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)
350 )
351 if part_kernel_utilization >= depth_utilization or ifm_depth <= 8:
352 # Part-kernel first is always better for ifm depths <= 8
353 npu_tensor.hw_traversal = NpuBlockTraversal.PART_KERNEL_FIRST
354
355 if op.type == Op.Conv2DBackpropInputSwitchedBias:
356 # Transpose Convoluion, reverse weights in H and W axes
357 weights = np.flip(weights, axis=(0, 1))
Tim Halld8339a72021-05-27 18:49:40 +0100358
359 encoded_stream = bytearray()
Tim Hallb5df7732022-05-04 16:20:43 +0100360 max_single_buffer_len = 0
Tim Halld8339a72021-05-27 18:49:40 +0100361 is_depthwise = npu_block_type == NpuBlockType.ConvolutionDepthWise
362
363 # Bias & scale
Tim Halld784af72021-06-08 21:25:57 +0100364 if do_scales:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200365 quantised_scales, biases = _prepare_scale_and_bias(arch, scale_tens, rescale_for_faf, op.explicit_scaling)
Tim Halld8339a72021-05-27 18:49:40 +0100366 scale_tens.element_size_bytes = 10
367
368 # Slice the weight stream up depth-ways into bricks and compress
James Peet7519d502021-07-19 16:47:58 +0100369 full_ofm_depth = weight_tens.values.shape[-1]
Tim Halld8339a72021-05-27 18:49:40 +0100370 ofm_block_depth = block_config.ofm_block.depth
371
372 weight_range_index = 0
373 for idx, depth_offset in enumerate(depth_offsets[:-1]):
374 # Do not generate for offsets outside the OFM
375 assert depth_offset >= 0 and depth_offset < full_ofm_depth
376 depth_length = depth_offsets[idx + 1] - depth_offset
377
378 # Get the weights necessary for this brick
Tim Halld784af72021-06-08 21:25:57 +0100379 if do_weights:
380 brick_weights = weights[:, :, :, depth_offset : depth_offset + depth_length]
Tim Halld8339a72021-05-27 18:49:40 +0100381
382 buffer_start_offset = len(encoded_stream)
383
Tim Halld784af72021-06-08 21:25:57 +0100384 # For each core, deinterleave weights/scales from the larger volume
Tim Halld8339a72021-05-27 18:49:40 +0100385 # and generate separate compressed streams.
386 for core in range(0, min(arch.ncores, full_ofm_depth)):
387
388 core_block_depth = int((ofm_block_depth + arch.ncores - 1 - core) // arch.ncores)
389
390 if core_block_depth != 0:
391 key = WeightKey(core, depth_offset)
392 weight_range = WeightRange()
393 weight_range.offset = len(encoded_stream)
394 weight_range.index = weight_range_index
395 weight_range_index += 1
396
397 # Scales & biases
Tim Halld784af72021-06-08 21:25:57 +0100398 if do_scales:
Tim Halld8339a72021-05-27 18:49:40 +0100399 scale_stream = []
400 core_scales = quantised_scales[
401 depth_offset + core : depth_offset + core + depth_length : arch.ncores
402 ]
403 core_biases = biases[depth_offset + core : depth_offset + core + depth_length : arch.ncores]
404 for j, core_bias in enumerate(core_biases):
405 scale_stream.extend(encode_bias(np.int64(core_bias), *core_scales[j]))
406
407 weight_range.scale_bytes = len(scale_stream)
408
409 encoded_stream.extend(scale_stream)
410
411 # Align to 16 for start of next substream
412 remainder = len(encoded_stream) % 16
413 if remainder > 0:
414 encoded_stream.extend(bytearray(16 - remainder))
415
416 # Weights
Tim Halld784af72021-06-08 21:25:57 +0100417 if do_weights:
418 core_weights = core_deinterleave(brick_weights, core, arch.ncores)
419 encoded_substream, _ = encode_weights(
420 accelerator=arch.accelerator_config,
421 weights_volume=core_weights,
422 dilation_xy=kernel.dilation,
423 ifm_bitdepth=ifm_bitdepth,
424 ofm_block_depth=core_block_depth,
425 is_depthwise=is_depthwise,
426 block_traversal=npu_tensor.hw_traversal,
427 )
428 weight_range.weight_offset = len(encoded_stream) - weight_range.offset
429 weight_range.weight_bytes = len(encoded_substream)
430 # Append encoded section
431 encoded_stream.extend(encoded_substream)
432 assert len(encoded_stream) % 16 == 0
Diqing Zhong66d7ec02021-02-01 19:07:04 +0100433
Tim Halld784af72021-06-08 21:25:57 +0100434 # Record encoded range in tensor
Tim Halld8339a72021-05-27 18:49:40 +0100435 npu_tensor.encoded_ranges[key] = weight_range
436
437 # Remember maximum encoded length for DoubleBuffering
Tim Hallb5df7732022-05-04 16:20:43 +0100438 max_single_buffer_len = max(max_single_buffer_len, len(encoded_stream) - buffer_start_offset)
Tim Halld8339a72021-05-27 18:49:40 +0100439
Tim Halld784af72021-06-08 21:25:57 +0100440 # Attach buffer to tensor
Tim Halld8339a72021-05-27 18:49:40 +0100441 npu_tensor.buffer = encoded_stream
Tim Hallb5df7732022-05-04 16:20:43 +0100442 npu_tensor.max_range_bytes = max_single_buffer_len
Tim Halld8339a72021-05-27 18:49:40 +0100443 npu_tensor.set_all_shapes([1, 1, 1, len(encoded_stream)])
444 npu_tensor.format = TensorFormat.WeightsCompressed
Tim Halld784af72021-06-08 21:25:57 +0100445
446 # Scale only tensor
447 if not do_weights:
448 npu_tensor.weight_compression_config = None
449 npu_tensor.purpose = TensorPurpose.FSBias
450 npu_tensor.mem_area = scale_tens.mem_area
451 npu_tensor.mem_type = scale_tens.mem_type
452 weights_tensor = tens_cached
453 scale_tensor = npu_tensor
454 else:
455 npu_tensor.purpose = TensorPurpose.Weights
456 npu_tensor.mem_area = weight_tens.mem_area
457 npu_tensor.mem_type = weight_tens.mem_type
458 weights_tensor = npu_tensor
459 scale_tensor = None
460 CompressedWeightCache.add(weights_tensor)
461
462 return weights_tensor, scale_tensor