Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1 | # 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 16 | # Description: |
| 17 | # Compresses and pads the weigths. It also calculates the scales and packs with the biases. |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 18 | import math |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 19 | from collections import namedtuple |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 20 | |
| 21 | import numpy as np |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 22 | |
Manupa Karunaratne | d83d2e1 | 2020-07-20 12:05:32 +0100 | [diff] [blame] | 23 | from .architecture_features import Accelerator |
| 24 | from .architecture_features import ArchitectureFeatures |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 25 | from .data_type import DataType |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 26 | from .errors import UnsupportedFeatureError |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 27 | from .nn_graph import SchedulingStrategy |
| 28 | from .numeric_util import round_up |
Patrik Gustavsson | d89c09e | 2020-07-08 11:27:12 +0200 | [diff] [blame] | 29 | from .numeric_util import round_up_divide |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 30 | from .operation import NpuBlockType |
| 31 | from .scaling import quantise_scale |
| 32 | from .scaling import reduced_quantise_scale |
| 33 | from .tensor import TensorBlockTraversal |
| 34 | from .tensor import TensorFormat |
| 35 | from .tensor import TensorPurpose |
| 36 | from .tensor import TensorSubPurpose |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 37 | from ethosu import mlw_codec |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 38 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 39 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 40 | # Contains meta info for a weight compression. If two tensors have identical weight compression config, |
| 41 | # then they also will have identical compressed weights. |
| 42 | WeightCompressionConfig = namedtuple( |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 43 | "WeightCompressionConfig", ["npu_block_type", "ofm_block_depth", "ofm_depth_step", "dilation", "equivalence_id"] |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 44 | ) |
| 45 | |
| 46 | |
Manupa Karunaratne | d83d2e1 | 2020-07-20 12:05:32 +0100 | [diff] [blame] | 47 | def encode_weights( |
| 48 | accelerator: Accelerator, |
| 49 | weights_volume: np.ndarray, |
| 50 | dilation_xy: tuple, |
| 51 | ifm_bitdepth: int, |
| 52 | ofm_block_depth: int, |
| 53 | is_depthwise: bool, |
| 54 | is_partkernel: bool, |
| 55 | ): |
| 56 | """ |
| 57 | Public facing API to use the ethosu weight encoding. |
| 58 | |
| 59 | :param accelerator: architecture_features.Accelerator enum to pick the correct ethosu accelerator |
| 60 | :param weights_volume: numpy.ndarray in OHWI layout with a shape of four |
| 61 | :param dilation_xy: a two element tuple of dilation attributes in x,y dimension |
| 62 | :param ifm_bitdepth: the bitdepth of input feature map |
| 63 | :param ofm_block_depth: the depth of blocks for ethosu processing |
| 64 | :param is_depthwise: a boolean indicating these weights are used for a depthwise traversal |
| 65 | :param is_partkernel: a boolean indicating these weights are traversed on sub-kernal basis |
| 66 | :return: a bytearray of compressed weights |
| 67 | """ |
| 68 | |
Manupa Karunaratne | 8b24f2b | 2020-08-12 18:26:39 +0000 | [diff] [blame] | 69 | # Check arg types |
| 70 | assert isinstance(accelerator, Accelerator) |
| 71 | assert isinstance(weights_volume, np.ndarray) |
| 72 | assert isinstance(dilation_xy, tuple) |
| 73 | assert isinstance(ifm_bitdepth, int) |
| 74 | assert isinstance(ofm_block_depth, int) |
| 75 | assert isinstance(is_depthwise, bool) |
| 76 | assert isinstance(is_partkernel, bool) |
| 77 | |
Manupa Karunaratne | d83d2e1 | 2020-07-20 12:05:32 +0100 | [diff] [blame] | 78 | # Checks for weight layout |
| 79 | assert len(weights_volume.shape) == 4, "weights ndarray should have a shape of 4" |
| 80 | |
| 81 | # It cannot be both partkernel and depthwise |
| 82 | assert not (is_depthwise and is_partkernel), "encode_weights :: partkernel and depthwise are mutually exclusive" |
| 83 | |
| 84 | # Check valid values for dilation |
| 85 | assert dilation_xy[0] in (1, 2), "encode_weights :: dilation x should be 1 or 2 not {}".format(dilation_xy[0]) |
| 86 | assert dilation_xy[1] in (1, 2), "encode_weights :: dilation y should be 1 or 2 not {}".format(dilation_xy[1]) |
| 87 | |
| 88 | ifm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ifm_ublock |
| 89 | ofm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ofm_ublock |
| 90 | raw_stream = generate_brick( |
| 91 | ifm_ublock=ifm_ublock, |
| 92 | ofm_ublock=ofm_ublock, |
| 93 | brick_weights=weights_volume, |
| 94 | ofm_block_depth=ofm_block_depth, |
| 95 | is_depthwise=is_depthwise, |
| 96 | is_partkernel=is_partkernel, |
| 97 | ifm_bitdepth=ifm_bitdepth, |
| 98 | dilation=dilation_xy, |
| 99 | ) |
| 100 | encoded_stream = encode(raw_stream) |
| 101 | return encoded_stream |
| 102 | |
| 103 | |
Manupa Karunaratne | bef228b | 2020-07-29 18:06:28 +0100 | [diff] [blame] | 104 | def encode_bias(bias: np.int64, scale: int, shift: int): |
| 105 | """ |
| 106 | Public facing API to pack bias and scale values as required by the hardware |
| 107 | :param bias: 64bit signed number that includes 40bit signed bias |
| 108 | :param scale: 32bit scale value |
| 109 | :param shift: 6bit shift value |
| 110 | :return: packed 80bit [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)] |
| 111 | """ |
Manupa Karunaratne | 8b24f2b | 2020-08-12 18:26:39 +0000 | [diff] [blame] | 112 | # Check arg types |
| 113 | assert isinstance(bias, np.int64) |
| 114 | assert isinstance(scale, int) |
| 115 | assert isinstance(shift, int) |
| 116 | |
Manupa Karunaratne | bef228b | 2020-07-29 18:06:28 +0100 | [diff] [blame] | 117 | assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range |
| 118 | assert 0 <= scale < (1 << 32) # unsigned 32-bit range |
| 119 | assert 0 <= shift < (1 << 6) # unsigned 6-bit range |
| 120 | |
| 121 | data = bytearray(10) |
| 122 | data[0] = (bias >> (0 * 8)) & 0xFF |
| 123 | data[1] = (bias >> (1 * 8)) & 0xFF |
| 124 | data[2] = (bias >> (2 * 8)) & 0xFF |
| 125 | data[3] = (bias >> (3 * 8)) & 0xFF |
| 126 | data[4] = (bias >> (4 * 8)) & 0xFF |
| 127 | data[5] = (scale >> (0 * 8)) & 0xFF |
| 128 | data[6] = (scale >> (1 * 8)) & 0xFF |
| 129 | data[7] = (scale >> (2 * 8)) & 0xFF |
| 130 | data[8] = (scale >> (3 * 8)) & 0xFF |
| 131 | data[9] = shift & 0x3F |
| 132 | return data |
| 133 | |
| 134 | |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 135 | def create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation): |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 136 | # Note: for an ofm block only its depth is used in weight compression. |
| 137 | # And block depth > ofm depth gives same result as block depth == ofm depth |
| 138 | block_depth = min(ofm_block_depth, tens.quant_values.shape[-1]) |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 139 | return WeightCompressionConfig(npu_block_type, block_depth, ofm_depth_step, dilation, tens.equivalence_id) |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 140 | |
| 141 | |
| 142 | def set_storage_shape(tens): |
| 143 | # Sets the storage shape depending on the tensor's sub purpose |
| 144 | if tens.sub_purpose == TensorSubPurpose.DoubleBuffer and len(tens.compressed_values) > 2: |
| 145 | offset = 2 * np.amax([len(x) for x in tens.compressed_values]) |
| 146 | assert offset % 16 == 0 |
| 147 | else: |
| 148 | offset = tens.weight_compressed_offsets[-1] |
| 149 | tens.storage_shape = [1, 1, 1, offset] |
| 150 | |
| 151 | |
| 152 | class CompressedWeightCache: |
| 153 | # Contains weight compressions for all weight tensors in a graph |
| 154 | def __init__(self): |
| 155 | self.cache = {} # maps from WeightCompressionConfig to a tensor clone containing compressed weights |
| 156 | |
| 157 | def get_tensor_with_same_compression(self, wcc): |
| 158 | return self.cache.get(wcc) |
| 159 | |
| 160 | def add(self, tens): |
| 161 | # Adds the compressed weights from the tensor to the cache |
| 162 | wcc = tens.weight_compression_config |
| 163 | # Clone the tensor to make sure that nothing related to the weight compression is modified |
| 164 | tens_clone = tens.clone("_weights{}_{}".format(wcc.ofm_block_depth, wcc.ofm_depth_step)) |
| 165 | self.cache[wcc] = tens_clone |
| 166 | |
| 167 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 168 | def encode(weight_stream): |
Patrik Gustavsson | 5ff9944 | 2020-07-10 10:12:17 +0200 | [diff] [blame] | 169 | if len(weight_stream) == 0: |
| 170 | return [] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 171 | assert np.amin(weight_stream) >= -255 |
| 172 | assert np.amax(weight_stream) <= 255 |
| 173 | |
| 174 | # Encode flattened signed weight stream |
| 175 | compressed = mlw_codec.encode(weight_stream) |
| 176 | |
| 177 | # pad with 0xFF as needed so the length of the weight stream |
| 178 | # is a multiple of 16 |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 179 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 180 | while (len(compressed) % 16) != 0: |
| 181 | compressed.append(0xFF) |
| 182 | |
| 183 | return compressed |
| 184 | |
| 185 | |
Manupa Karunaratne | d83d2e1 | 2020-07-20 12:05:32 +0100 | [diff] [blame] | 186 | def generate_brick( |
| 187 | ifm_ublock, ofm_ublock, brick_weights, ofm_block_depth, is_depthwise, is_partkernel, ifm_bitdepth, dilation |
| 188 | ): |
| 189 | |
| 190 | decomp_h = ArchitectureFeatures.SubKernelMax.height // dilation[0] |
| 191 | decomp_w = ArchitectureFeatures.SubKernelMax.width // dilation[1] |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 192 | # Expect weights formatted OHWI |
| 193 | ofm_depth = brick_weights.shape[-4] |
| 194 | ifm_depth = brick_weights.shape[-1] |
| 195 | kernel_width = brick_weights.shape[-2] |
| 196 | kernel_height = brick_weights.shape[-3] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 197 | # IFM block depth |
| 198 | if is_partkernel or (ifm_bitdepth == 16): |
| 199 | # IFM block depth is always 16 for part-kernel-first |
| 200 | ifm_block_depth = 16 |
| 201 | elif ifm_bitdepth == 8: |
| 202 | ifm_block_depth = 32 |
| 203 | else: |
| 204 | assert False |
| 205 | |
| 206 | stream = [] |
| 207 | |
| 208 | # Top level striping - OFM blocks in the entire brick's depth |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 209 | for ofm_block_z in range(0, ofm_depth, ofm_block_depth): |
| 210 | clipped_ofm_block_depth = min(ofm_block_depth, ofm_depth - ofm_block_z) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 211 | # IFM blocks required for the brick |
| 212 | for ifm_block_z in range(0, (1 if is_depthwise else ifm_depth), ifm_block_depth): |
| 213 | if is_depthwise: |
| 214 | clipped_ifm_block_depth = ifm_ublock.depth |
| 215 | else: |
| 216 | clipped_ifm_block_depth = ( |
| 217 | min(ifm_block_depth, ifm_depth - ifm_block_z) if is_partkernel else ifm_block_depth |
| 218 | ) |
| 219 | # Weight decomposition |
| 220 | # Subkernel Splitting (H) |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 221 | for subkernel_y in range(0, kernel_height, decomp_h): |
| 222 | sub_height = min(kernel_height - subkernel_y, decomp_h) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 223 | # Subkernel splitting (W) |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 224 | for subkernel_x in range(0, kernel_width, decomp_w): |
| 225 | sub_width = min(kernel_width - subkernel_x, decomp_w) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 226 | subkernel_elements = sub_width * sub_height |
| 227 | # Part kernel first works across the kernel H/W and needs padding |
| 228 | if is_partkernel: |
| 229 | if ifm_bitdepth == 16 and subkernel_elements % 2 != 0: |
| 230 | subkernel_elements = int(math.ceil(subkernel_elements / 2) * 2) |
| 231 | elif ifm_bitdepth == 8 and subkernel_elements % 4 != 0: |
| 232 | subkernel_elements = int(math.ceil(subkernel_elements / 4) * 4) |
| 233 | |
| 234 | # Depthwise Conv requires multiple of 4 kernel elements in its weight block |
| 235 | # this is different from normal conv which is considered "weights depth-first" |
| 236 | elif is_depthwise: |
| 237 | subkernel_elements = int(math.ceil(subkernel_elements / 4.0) * 4) |
| 238 | |
| 239 | ifm_block_depth_outer = clipped_ifm_block_depth if is_partkernel else 1 |
| 240 | ifm_block_depth_inner = 1 if is_partkernel else clipped_ifm_block_depth |
| 241 | # IFM Ublocks in IFM-block over depth for part-kernel-first mode |
| 242 | # For depth-first IFM Ublocks are traversed after subkernel elements so this loop is ignored. |
| 243 | for ifm_ublk_outer in range(0, ifm_block_depth_outer, ifm_ublock.depth): |
| 244 | # OFM Ublocks in OFM-block over depth |
| 245 | for ofm_ublk in range(0, clipped_ofm_block_depth, ofm_ublock.depth): |
| 246 | # HW Kernel element traversal - cannot be a H/W loop due to element |
| 247 | # padding requirement on depthwise/part-kernel configurations |
| 248 | for element in range(subkernel_elements): |
| 249 | kx = element % sub_width |
| 250 | ky = element // sub_width |
| 251 | # IFM Ublocks in IFM-block over depth (only 1 ublock if depthwise) |
| 252 | # In case of part-kernel-first IFM Ublock traversal have already been handled |
| 253 | # and this loop is ignored. |
| 254 | for ifm_ublk_inner in range(0, ifm_block_depth_inner, ifm_ublock.depth): |
| 255 | # Feed OFM ublock elements |
| 256 | for ofm_ublock_z in range(ofm_ublock.depth): |
| 257 | # Source IFM ublock elements (only 1 element deep if depthwise) |
| 258 | for ifm_ublock_z in range(1 if is_depthwise else ifm_ublock.depth): |
| 259 | # Source position within the current subkernel |
| 260 | wx = subkernel_x + kx |
| 261 | wy = subkernel_y + ky |
| 262 | # Source IFM/OFM slices |
| 263 | ifm_ublk = ifm_ublk_inner + ifm_ublk_outer |
| 264 | ifm_z = ifm_block_z + ifm_ublk + ifm_ublock_z |
| 265 | ofm_z = ofm_block_z + ofm_ublk + ofm_ublock_z |
| 266 | if (ifm_z >= ifm_depth) or (ofm_z >= ofm_depth) or (ky >= sub_height): |
| 267 | stream.append(0) |
| 268 | else: |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 269 | stream.append(brick_weights[ofm_z][wy][wx][ifm_z]) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 270 | return stream |
| 271 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 272 | |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 273 | def core_deinterleave(hwio, core, ncores): |
| 274 | # Put weights back into OHWI |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 275 | ohwi = np.transpose(hwio, (3, 0, 1, 2)) |
| 276 | return ohwi[core : ohwi.shape[0] : ncores] |
| 277 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 278 | |
| 279 | # Compress the weights |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 280 | def compress_weights(arch, nng, tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 281 | assert tens.purpose == TensorPurpose.Weights |
| 282 | assert tens.format == TensorFormat.WeightsCompressed |
| 283 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 284 | # Check the weight cache |
| 285 | if nng.weight_cache is None: |
| 286 | nng.weight_cache = CompressedWeightCache() |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 287 | wcc = create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation) |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 288 | tens.weight_compression_config = wcc |
| 289 | tens_cached = nng.weight_cache.get_tensor_with_same_compression(wcc) |
| 290 | if tens_cached is not None: |
| 291 | # Cache hit, copy weights from the cache |
| 292 | tens.copy_compressed_weight_info(tens_cached) |
| 293 | set_storage_shape(tens) |
| 294 | return |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 295 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 296 | # No cache hit, perform the compression |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 297 | assert tens.quantization is not None |
| 298 | assert tens.quantization.scale_f32 is not None |
| 299 | assert tens.quantization.zero_point is not None |
| 300 | |
| 301 | zero_point = tens.quantization.zero_point |
| 302 | quant_buf = tens.quant_values.astype(np.int64) |
| 303 | |
| 304 | # Early zero-point correction |
| 305 | weights = quant_buf - zero_point |
| 306 | |
| 307 | if len(weights.shape) == 2: |
| 308 | weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 309 | |
| 310 | compression_scales = [] |
| 311 | compressed_offsets = [] |
| 312 | encoded_streams = [] |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 313 | encoded_streams_substream_offsets = [] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 314 | offset = 0 |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 315 | max_single_buffer_len = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 316 | |
| 317 | ifm_bitdepth = tens.consumer_list[0].inputs[0].dtype.size_in_bits() |
| 318 | ifm_depth = weights.shape[-2] |
| 319 | if npu_block_type == NpuBlockType.ConvolutionDepthWise: |
| 320 | tens.block_traversal = TensorBlockTraversal.DepthWise |
| 321 | if npu_block_type == NpuBlockType.ConvolutionMxN: |
| 322 | # Determine which block traversal strategy has better DPU utilization |
Jacob Bohlin | de2a57f | 2020-08-10 15:21:42 +0200 | [diff] [blame] | 323 | kernel_size = weights.shape[0] * weights.shape[1] |
| 324 | depth_utilization = weights.shape[2] / round_up(weights.shape[2], 32 if ifm_bitdepth == 8 else 16) |
| 325 | part_kernel_utilization = (weights.shape[2] / round_up(weights.shape[2], 8)) * ( |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 326 | kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2) |
| 327 | ) |
| 328 | if part_kernel_utilization >= depth_utilization or ifm_depth <= 8: |
| 329 | # Part-kernel first is always better for ifm depths <= 8 |
| 330 | tens.block_traversal = TensorBlockTraversal.PartKernelFirst |
| 331 | else: |
| 332 | tens.block_traversal = TensorBlockTraversal.DepthFirst |
| 333 | |
Manupa Karunaratne | d83d2e1 | 2020-07-20 12:05:32 +0100 | [diff] [blame] | 334 | is_depthwise = tens.block_traversal == TensorBlockTraversal.DepthWise |
| 335 | is_partkernel = tens.block_traversal == TensorBlockTraversal.PartKernelFirst |
| 336 | |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 337 | if tens.consumer_list[0].type == "Conv2DBackpropInputSwitchedBias": |
| 338 | # Transpose Convoluion, reverse weights in H and W axes |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 339 | weights = np.flip(weights, axis=(0, 1)) |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 340 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 341 | # Calculate brick size |
Jacob Bohlin | de2a57f | 2020-08-10 15:21:42 +0200 | [diff] [blame] | 342 | brick_size = (weights.shape[0], weights.shape[1], weights.shape[2], min(tens.shape[-1], ofm_depth_step)) |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 343 | elements_in_brick = np.prod(brick_size) |
| 344 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 345 | # Slice weight stream up depth-ways into bricks and compress |
| 346 | full_ofm_depth = quant_buf.shape[-1] |
| 347 | for idx in range(0, full_ofm_depth, ofm_depth_step): |
| 348 | # Get the weights necessary for this brick |
| 349 | count = min(full_ofm_depth - idx, ofm_depth_step) |
| 350 | brick_weights = weights[:, :, :, idx : idx + count] |
| 351 | |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 352 | substream_offsets = [0] |
| 353 | encoded_stream = [] |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 354 | |
| 355 | # For each core, deinterleave weights from the larger volume |
| 356 | # and generate separate compressed streams. |
| 357 | for core in range(0, min(arch.ncores, full_ofm_depth)): |
| 358 | core_weights = core_deinterleave(brick_weights, core, arch.ncores) |
Tim Hall | 6231676 | 2020-06-25 16:55:02 +0100 | [diff] [blame] | 359 | |
| 360 | block_depth = (ofm_block_depth + arch.ncores - 1 - core) // arch.ncores |
Manupa Karunaratne | d83d2e1 | 2020-07-20 12:05:32 +0100 | [diff] [blame] | 361 | encoded_substream = [] |
Tim Hall | 6231676 | 2020-06-25 16:55:02 +0100 | [diff] [blame] | 362 | if block_depth != 0: |
Manupa Karunaratne | d83d2e1 | 2020-07-20 12:05:32 +0100 | [diff] [blame] | 363 | encoded_substream = encode_weights( |
| 364 | accelerator=arch.accelerator_config, |
| 365 | weights_volume=core_weights, |
| 366 | dilation_xy=dilation, |
| 367 | ifm_bitdepth=ifm_bitdepth, |
| 368 | ofm_block_depth=block_depth, |
| 369 | is_depthwise=is_depthwise, |
| 370 | is_partkernel=is_partkernel, |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 371 | ) |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 372 | encoded_stream.extend(encoded_substream) |
| 373 | substream_offsets.append(len(encoded_stream)) |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 374 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 375 | encoded_streams.append(encoded_stream) |
| 376 | encoded_streams_substream_offsets.append(substream_offsets) |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 377 | |
| 378 | # Remember maximum encoded length for DoubleBuffering |
| 379 | max_single_buffer_len = max(max_single_buffer_len, len(encoded_stream)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 380 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 381 | # Remember where we put it for linear addressing |
| 382 | compressed_offsets.append(offset) |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 383 | offset += len(encoded_stream) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 384 | assert offset % 16 == 0 |
| 385 | |
| 386 | # Compression scale tracking |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 387 | compression_scales.append(len(encoded_stream) / elements_in_brick) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 388 | |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 389 | # Track total length as last element of the offsets array |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 390 | compressed_offsets.append(offset) |
| 391 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 392 | tens.weight_compression_scales = compression_scales |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 393 | tens.weight_compressed_offsets = compressed_offsets |
| 394 | tens.compression_scale_for_worst_weight_stream = np.amax(compression_scales) |
| 395 | tens.storage_compression_scale = tens.bandwidth_compression_scale = np.average(compression_scales) |
| 396 | tens.compressed_values = encoded_streams |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 397 | tens.compressed_values_substream_offsets = encoded_streams_substream_offsets |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 398 | tens.brick_size = brick_size |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 399 | set_storage_shape(tens) |
| 400 | nng.weight_cache.add(tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 401 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 402 | |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 403 | def calc_scales_and_pack_biases(tens, arch, ofm_depth_step, rescale_for_faf=False): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 404 | assert tens.purpose == TensorPurpose.FeatureMap |
| 405 | assert tens.format == TensorFormat.NHWC |
| 406 | # the connected operator should expect a bias input unless it is a FullyConnected |
| 407 | assert "Bias" in tens.consumer_list[0].type or tens.consumer_list[0].type.startswith("FullyConnected") |
| 408 | # the input bias tensor is the same as that connected to the operator |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 409 | _, _, bias_tens, _ = tens.consumer_list[0].get_ifm_weights_biases_ofm() |
| 410 | assert tens is bias_tens |
| 411 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 412 | # the operator should only have a single output |
| 413 | assert len(tens.consumer_list[0].outputs) == 1 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 414 | biases = tens.quant_values |
| 415 | |
| 416 | first_consumer_op = tens.consumer_list[0] |
| 417 | ifm_dtype = first_consumer_op.inputs[0].dtype |
| 418 | ifm_scale = first_consumer_op.inputs[0].quantization.scale_f32 |
| 419 | ofm_scale = first_consumer_op.outputs[0].quantization.scale_f32 |
| 420 | weight_scales = first_consumer_op.inputs[1].quantization.scale_f32 |
| 421 | |
| 422 | # biases can have multiple consumers for rnn cells. if so, then check that they are all the same |
| 423 | for op in tens.consumer_list[1:]: |
| 424 | assert ifm_scale == op.inputs[0].quantization.scale_f32 |
| 425 | assert ofm_scale == op.outputs[0].quantization.scale_f32 |
| 426 | assert weight_scales == op.inputs[1].quantization.scale_f32 |
| 427 | |
| 428 | if not hasattr(weight_scales, "__iter__"): |
| 429 | # If weight_scales is not already an iterable make it into a list |
| 430 | weight_scales = [weight_scales] |
| 431 | |
| 432 | # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which |
| 433 | # uses double during scaling calculations |
| 434 | # TensorFlow Lite casts the scales slightly differently for uint8 and int8 |
| 435 | if not rescale_for_faf: |
| 436 | if ifm_dtype == DataType.uint8: |
| 437 | scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales] |
Fredrik Svedberg | d67c0aa | 2020-03-30 13:15:28 +0200 | [diff] [blame] | 438 | elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 439 | scales = [ |
| 440 | (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale) |
| 441 | for weight_scale in weight_scales |
| 442 | ] |
| 443 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 444 | raise UnsupportedFeatureError( |
| 445 | "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name) |
| 446 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 447 | else: |
| 448 | if ifm_dtype == DataType.uint8: |
| 449 | scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales] |
Fredrik Svedberg | d67c0aa | 2020-03-30 13:15:28 +0200 | [diff] [blame] | 450 | elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 451 | scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales] |
| 452 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 453 | raise UnsupportedFeatureError( |
| 454 | "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name) |
| 455 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 456 | |
| 457 | # quantise all of the weight scales into (scale_factor, shift) |
Fredrik Svedberg | d67c0aa | 2020-03-30 13:15:28 +0200 | [diff] [blame] | 458 | if ifm_dtype == DataType.int16: |
| 459 | quantised_scales = [reduced_quantise_scale(scale) for scale in scales] |
| 460 | else: |
| 461 | quantised_scales = [quantise_scale(scale) for scale in scales] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 462 | |
| 463 | for _, shift in quantised_scales: |
| 464 | assert shift >= 16 |
| 465 | |
| 466 | # pack the biases and scales |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 467 | if len(quantised_scales) == 1: |
| 468 | # If only 1 quantised scale is used, repeat that value for the length of the biases |
| 469 | quantised_scales = [quantised_scales[0]] * len(biases) |
| 470 | |
| 471 | assert len(quantised_scales) == len(biases) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 472 | tens.element_size_bytes = 10 |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 473 | tens.compressed_values = [] |
| 474 | tens.compressed_values_substream_offsets = [] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 475 | |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 476 | total_elements = len(quantised_scales) |
Patrik Gustavsson | d89c09e | 2020-07-08 11:27:12 +0200 | [diff] [blame] | 477 | alignment_bytes = 0 |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 478 | for i in range(0, total_elements, ofm_depth_step): |
| 479 | # Extract streams from brick to generate substreams for each core |
| 480 | stream = bytearray() |
| 481 | substream_offsets = [0] |
| 482 | max_len = min(ofm_depth_step, total_elements - i) |
| 483 | for core in range(0, min(arch.ncores, max_len)): |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 484 | core_scales = quantised_scales[i + core : i + core + max_len : arch.ncores] |
| 485 | core_biases = biases[i + core : i + core + max_len : arch.ncores] |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 486 | for j, core_bias in enumerate(core_biases): |
Manupa Karunaratne | bef228b | 2020-07-29 18:06:28 +0100 | [diff] [blame] | 487 | stream.extend(encode_bias(np.int64(core_bias), *core_scales[j])) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 488 | |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 489 | # Align to 16 for start for next substream |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 490 | remainder = (len(stream)) % 16 |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 491 | if remainder > 0: |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 492 | stream.extend(bytearray(16 - remainder)) |
Patrik Gustavsson | d89c09e | 2020-07-08 11:27:12 +0200 | [diff] [blame] | 493 | alignment_bytes += 16 - remainder |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 494 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 495 | substream_offsets.append(len(stream)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 496 | |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 497 | # Add to compressed values with their substream offset lists to the tensor |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 498 | tens.compressed_values.append(stream) |
| 499 | tens.compressed_values_substream_offsets.append(substream_offsets) |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 500 | |
Patrik Gustavsson | d89c09e | 2020-07-08 11:27:12 +0200 | [diff] [blame] | 501 | tens.storage_shape = [total_elements + round_up_divide(alignment_bytes, tens.element_size_bytes)] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 502 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 503 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 504 | def update_pass_weight_and_scale_tensors(nng, arch): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 505 | for sg in nng.subgraphs: |
| 506 | for ps in sg.passes: |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 507 | tens = ps.weight_tensor |
| 508 | if tens is not None: |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 509 | op = tens.find_npu_op() |
Dwight Lidman | 940fdee | 2020-08-13 13:11:48 +0200 | [diff] [blame] | 510 | if op is None: |
| 511 | continue |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 512 | npu_usage_of_tensor = op.attrs["npu_block_type"] |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 513 | needs_dma = tens.needs_dma() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 514 | if ps.cascade.strategy == SchedulingStrategy.WeightStream and needs_dma: |
| 515 | ofm_depth_step = ps.block_config[-1] |
| 516 | else: |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 517 | ofm_depth_step = tens.shape[-1] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 518 | compress_weights( |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 519 | arch, nng, tens, npu_usage_of_tensor, ps.block_config[-1], ofm_depth_step, op.get_dilation_h_w() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 520 | ) |
| 521 | # Update source tensor |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 522 | if needs_dma: |
| 523 | src_tens = tens.get_dma_src_tensor() |
| 524 | src_tens.shape = tens.shape |
| 525 | src_tens.quant_values = tens.quant_values |
| 526 | src_tens.copy_compressed_weight_info(tens) |
| 527 | set_storage_shape(src_tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 528 | |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 529 | if ps.scale_tensor is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 530 | rescale_for_faf = False |
| 531 | activation_ops = set(("Sigmoid", "Tanh")) |
| 532 | if (ps.ops[-1].type in activation_ops) and (ps.npu_block_type != NpuBlockType.ElementWise): |
| 533 | rescale_for_faf = True |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 534 | calc_scales_and_pack_biases(ps.scale_tensor, arch, ofm_depth_step, rescale_for_faf) |