Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 1 | # Copyright (C) 2021 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. |
| 16 | # Description: |
| 17 | # Functions used to read from a TOSA format file. |
| 18 | import os.path |
| 19 | import struct |
| 20 | import sys |
| 21 | |
| 22 | import numpy as np |
| 23 | |
| 24 | from .nn_graph import Graph |
| 25 | from .nn_graph import Subgraph |
| 26 | from .operation import Op |
| 27 | from .operation import Operation |
Patrik Gustavsson | 5e26eda | 2021-06-30 09:07:16 +0200 | [diff] [blame] | 28 | from .reader_util import align_tensor_indices_to_nng |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 29 | from .reader_util import clone_and_reshape_tensor |
| 30 | from .reader_util import decode_str |
| 31 | from .reader_util import fixup_tensors |
| 32 | from .tensor import QuantizationParameters |
Patrik Gustavsson | c74682c | 2021-08-17 14:26:38 +0200 | [diff] [blame] | 33 | from .tensor import shape_num_elements |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 34 | from .tensor import Tensor |
| 35 | from .tflite_mapping import DataType |
Patrik Gustavsson | df99510 | 2021-08-23 15:33:59 +0200 | [diff] [blame] | 36 | from .tosa.Op import Op as TosaOp |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 37 | from .tosa.TosaGraph import TosaGraph as TG |
| 38 | from .tosa_mapping import datatype_map |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 39 | from .tosa_mapping import datatype_map_numpy |
Patrik Gustavsson | df99510 | 2021-08-23 15:33:59 +0200 | [diff] [blame] | 40 | from .tosa_mapping import TOSA_IFM_INDICES |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 41 | from .tosa_mapping import tosa_operator_map |
| 42 | from .tosa_mapping import unsupported_tosa_operators |
| 43 | |
| 44 | |
| 45 | class TosaSubgraph: |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 46 | def __init__(self, graph, block): |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 47 | self.graph = graph |
| 48 | self.name = decode_str(block.Name()) |
| 49 | |
| 50 | self.tensors = [] |
| 51 | for idx in range(block.TensorsLength()): |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 52 | self.tensors.append(self.parse_tensor(block.Tensors(idx))) |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 53 | |
| 54 | for idx in range(block.OperatorsLength()): |
| 55 | self.parse_operator(idx, block.Operators(idx)) |
| 56 | |
| 57 | # Get the subgraph inputs and outputs |
| 58 | self.inputs = self.get_sg_inputs_remove_duplicates(block) |
| 59 | self.outputs = self.get_sg_outputs_remove_duplicates(block) |
| 60 | fixup_tensors(self.inputs, self.tensors) |
| 61 | |
| 62 | def get_sg_inputs_remove_duplicates(self, block): |
| 63 | inputs = [] |
| 64 | for idx in range(block.InputsLength()): |
| 65 | tens_data = block.Inputs(idx) |
| 66 | self.add_not_duplicate(tens_data, inputs, "input") |
| 67 | return inputs |
| 68 | |
| 69 | def get_sg_outputs_remove_duplicates(self, block): |
| 70 | outputs = [] |
| 71 | for idx in range(block.OutputsLength()): |
| 72 | tens_data = block.Outputs(idx) |
| 73 | self.add_not_duplicate(tens_data, outputs, "output") |
| 74 | return outputs |
| 75 | |
| 76 | def add_not_duplicate(self, tens_data, tensors, warning_str): |
| 77 | name = decode_str(tens_data) |
| 78 | tensor = self.get_tensor_by_name(name) |
| 79 | if tensor not in tensors: |
| 80 | tensors.append(tensor) |
| 81 | else: |
| 82 | print(f"Warning: Subgraph {warning_str} tensor ({tensor}) already seen. Removing the duplicate.") |
| 83 | |
| 84 | def get_tensor_by_name(self, name): |
| 85 | for tens in self.tensors: |
| 86 | if tens.name == name: |
| 87 | return tens |
| 88 | return None |
| 89 | |
| 90 | def parse_operator(self, op_index, op_data): |
| 91 | op_code = op_data.Op() |
| 92 | if op_code in unsupported_tosa_operators: |
| 93 | print("Unsupported Operator", op_code) |
Patrik Gustavsson | df99510 | 2021-08-23 15:33:59 +0200 | [diff] [blame] | 94 | return |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 95 | |
| 96 | op_type, attr_serializer, quant_serializer, indices = tosa_operator_map[op_code] |
| 97 | inputs = [] |
| 98 | outputs = [] |
| 99 | for idx in range(op_data.InputsLength()): |
| 100 | input_tens = self.get_tensor_by_name(decode_str(op_data.Inputs(idx))) |
| 101 | inputs.append(input_tens) |
| 102 | assert input_tens is not None |
| 103 | |
| 104 | for idx in range(op_data.OutputsLength()): |
| 105 | output_tens = self.get_tensor_by_name(decode_str(op_data.Outputs(idx))) |
| 106 | outputs.append(output_tens) |
| 107 | assert output_tens is not None |
| 108 | |
Patrik Gustavsson | df99510 | 2021-08-23 15:33:59 +0200 | [diff] [blame] | 109 | # Permutation attribute for TRANSPOSE is an input tensor in TOSA |
| 110 | # TODO In order to optimise Depthwise spawning from TFLite Support for removing |
| 111 | # Transpose of constant data. |
| 112 | # Moving permutation to an attribute, to match internal graph representation for now |
| 113 | perms = None |
| 114 | if op_code == TosaOp.TRANSPOSE: |
| 115 | perms = perms = inputs.pop(1) |
| 116 | indices = TOSA_IFM_INDICES |
| 117 | |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 118 | name = "unknown_op_name" |
| 119 | if len(outputs): |
| 120 | name = outputs[0].name |
Patrik Gustavsson | 5e26eda | 2021-06-30 09:07:16 +0200 | [diff] [blame] | 121 | inputs = align_tensor_indices_to_nng(op_type, indices, inputs) |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 122 | op = Operation(op_type, name) |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 123 | op.op_index = op_index |
| 124 | op.inputs = inputs |
| 125 | op.outputs = outputs |
| 126 | |
| 127 | for out in op.outputs: |
| 128 | out.ops = [op] |
| 129 | |
| 130 | # TODO Transpose_conv and conv3d |
| 131 | if op.type.is_depthwise_conv2d_op() or op.type.is_conv2d_op() or op.type == Op.FullyConnected: |
| 132 | if inputs[1].values is not None: |
| 133 | if op.type == Op.FullyConnected: |
| 134 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False) |
| 135 | elif op.type.is_conv2d_op(): |
| 136 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False) |
| 137 | elif op.type.is_depthwise_conv2d_op(): |
| 138 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 0, 3), False) |
| 139 | if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]: |
| 140 | # No Bias tensor |
| 141 | inputs.append(None) |
| 142 | if inputs[-1] and inputs[-1].values is not None: |
| 143 | # Since bias tensor is used for both bias and scale, |
| 144 | # a clone with a unique equivalence_id is needed |
| 145 | inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True) |
| 146 | |
| 147 | if attr_serializer is not None: |
| 148 | op.attrs = attr_serializer.deserialize(op_data) |
| 149 | |
Patrik Gustavsson | c74682c | 2021-08-17 14:26:38 +0200 | [diff] [blame] | 150 | if "padding" in op.attrs: |
| 151 | padding = op.attrs["padding"] # [top, bottom, left, right] |
| 152 | op.attrs["explicit_padding"] = ( |
| 153 | padding[0], |
| 154 | padding[2], |
| 155 | padding[1], |
| 156 | padding[3], |
| 157 | ) # [top, left, bottom, right] |
| 158 | if "stride" in op.attrs: |
| 159 | stride = op.attrs["stride"] |
| 160 | if len(stride) == 2: |
| 161 | op.attrs["strides"] = (1, stride[0], stride[1], 1) |
Patrik Gustavsson | df99510 | 2021-08-23 15:33:59 +0200 | [diff] [blame] | 162 | del op.attrs["stride"] |
Patrik Gustavsson | c74682c | 2021-08-17 14:26:38 +0200 | [diff] [blame] | 163 | else: |
| 164 | # TODO CONV3D more to be done.... |
| 165 | print("Unsupported kernel dimensions: ", len(stride)) |
| 166 | assert False |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 167 | if "dilation" in op.attrs: |
| 168 | dilation = op.attrs["dilation"] |
| 169 | if len(dilation) == 2: |
| 170 | op.attrs["dilation"] = (1, dilation[0], dilation[1], 1) |
| 171 | elif len(dilation) == 3: |
| 172 | # TODO CONV3D more to be done.... |
| 173 | op.attrs["dilation"] = (dilation[0], dilation[1], dilation[2], 1) |
| 174 | if "kernel" in op.attrs: |
| 175 | kernel = op.attrs["kernel"] |
| 176 | if len(kernel) == 2: |
| 177 | op.attrs["ksize"] = (1, kernel[0], kernel[1], 1) |
| 178 | else: |
| 179 | # TODO CONV3D more to be done.... |
| 180 | print("Unsupported kernel dimensions: ", len(kernel)) |
| 181 | assert False |
Patrik Gustavsson | b081d67 | 2021-08-25 13:49:25 +0200 | [diff] [blame^] | 182 | if "shift" in op.attrs and op.type == Op.Mul: |
| 183 | shift = op.attrs["shift"] |
| 184 | if shift != 0: |
| 185 | op.type = Op.RescaleMul |
| 186 | op.rescale = [1, shift] |
Patrik Gustavsson | df99510 | 2021-08-23 15:33:59 +0200 | [diff] [blame] | 187 | if op.type.is_depthwise_conv2d_op(): |
| 188 | op.attrs["depth_multiplier"] = op.weights.shape[3] |
| 189 | |
| 190 | elif op.type == Op.Transpose: |
| 191 | op.attrs["perms"] = perms.values |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 192 | |
| 193 | if quant_serializer is not None: |
| 194 | quant_info = quant_serializer.deserialize(op_data) |
| 195 | |
| 196 | # TODO tensor zero points currently set here |
| 197 | # zero points part of Rescale operation, handled in tosa_graph_optimizer |
| 198 | if "input_zp" in quant_info: |
| 199 | self.set_tensor_zp(op.ifm, quant_info["input_zp"]) |
| 200 | if "weight_zp" in quant_info: |
| 201 | self.set_tensor_zp(op.weights, quant_info["weight_zp"]) |
Patrik Gustavsson | c74682c | 2021-08-17 14:26:38 +0200 | [diff] [blame] | 202 | if "output_zp" in quant_info: |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 203 | self.set_tensor_zp(op.ofm, quant_info["output_zp"]) |
| 204 | if "a_zp" in quant_info: |
| 205 | self.set_tensor_zp(op.ifm, quant_info["a_zp"]) |
| 206 | if "b_zp" in quant_info: |
| 207 | self.set_tensor_zp(op.ifm2, quant_info["b_zp"]) |
| 208 | |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 209 | def parse_tensor(self, tens_data): |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 210 | name = decode_str(tens_data.Name()) |
| 211 | np_shape = tens_data.ShapeAsNumpy() |
| 212 | shape = list(np_shape) if type(np_shape) is np.ndarray else [] |
| 213 | tens_dtype = tens_data.Type() |
| 214 | dtype = datatype_map[tens_dtype] |
| 215 | |
| 216 | tens = Tensor(shape, dtype, name) |
| 217 | |
| 218 | # Initialize quantization parameters |
| 219 | tens.quantization = QuantizationParameters() |
| 220 | |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 221 | if dtype == DataType.uint8: |
| 222 | tens.quantization.quant_min = 0 |
| 223 | tens.quantization.quant_max = (1 << dtype.bits) - 1 |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 224 | elif dtype in (DataType.int8, DataType.int16, DataType.int32, DataType.int48): |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 225 | tens.quantization.quant_min = -(1 << (dtype.bits - 1)) |
| 226 | tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1 |
| 227 | |
| 228 | tens.values = None |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 229 | |
| 230 | data_length = tens_data.DataLength() |
| 231 | if data_length != 0: |
| 232 | data_as_numpy = tens_data.DataAsNumpy() |
| 233 | if tens_dtype in datatype_map_numpy: |
| 234 | np_dtype = datatype_map_numpy[tens_dtype] |
Patrik Gustavsson | c74682c | 2021-08-17 14:26:38 +0200 | [diff] [blame] | 235 | |
| 236 | # TOSA pads the tensor data |
| 237 | shape_elements = shape_num_elements(shape) |
| 238 | values = np.array(data_as_numpy.view(np_dtype)) |
| 239 | values = values[0:shape_elements] |
| 240 | tens.values = values.reshape(shape) |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 241 | else: |
| 242 | # int48 is only expected as an accumulated data/output format, int4 not supported |
| 243 | print(f"Error: unsupported/unexpected Tensor type {dtype}, with data") |
| 244 | assert False |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 245 | |
| 246 | return tens |
| 247 | |
| 248 | def set_tensor_zp(self, tens, zp): |
| 249 | if tens.quantization.zero_point is None: |
| 250 | tens.quantization.zero_point = zp |
| 251 | elif tens.quantization.zero_point != zp: |
| 252 | print(f"Error: Setting tensor zp not possible, tensor already has different zero point") |
| 253 | assert False |
| 254 | |
| 255 | |
| 256 | class TosaGraph: |
| 257 | def __init__(self, filename, batch_size, feed_dict, output_node_names, initialisation_nodes): |
| 258 | |
| 259 | self.op_times = {} |
| 260 | if batch_size is None: |
| 261 | batch_size = 1 |
| 262 | self.batch_size = batch_size |
| 263 | self.name = os.path.splitext(os.path.basename(filename))[0] |
| 264 | self.initialisation_nodes = initialisation_nodes |
| 265 | |
| 266 | with open(filename, "rb") as f: |
| 267 | buf = bytearray(f.read()) |
| 268 | |
| 269 | try: |
| 270 | parsing_step = "parsing root" |
| 271 | tosa_graph = TG.GetRootAsTosaGraph(buf, 0) |
| 272 | |
| 273 | parsing_step = "parsing version" |
| 274 | self.check_version(tosa_graph) |
| 275 | |
| 276 | parsing_step = "parsing blocks length" |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 277 | self.subgraphs = [] |
| 278 | for b_idx in range(tosa_graph.BlocksLength()): |
| 279 | parsing_step = f"parsing block {b_idx}" |
Patrik Gustavsson | d15866c | 2021-08-10 13:56:34 +0200 | [diff] [blame] | 280 | self.subgraphs.append(TosaSubgraph(self, tosa_graph.Blocks(b_idx))) |
Patrik Gustavsson | 8f1f9aa | 2021-06-28 07:41:58 +0200 | [diff] [blame] | 281 | |
| 282 | self.nng = Graph(self.name, self.batch_size) |
| 283 | for tosa_sg in self.subgraphs: |
| 284 | sg = Subgraph(tosa_sg.name) |
| 285 | sg.original_inputs = tosa_sg.inputs # Preserve the original input order |
| 286 | sg.output_tensors = tosa_sg.outputs |
| 287 | self.nng.subgraphs.append(sg) |
| 288 | |
| 289 | except (struct.error, TypeError, RuntimeError) as e: |
| 290 | print(f'Error: Invalid .tosa file. Got "{e}" while {parsing_step}.') |
| 291 | sys.exit(1) |
| 292 | |
| 293 | def check_version(self, tosa_graph): |
| 294 | version = tosa_graph.Version() |
| 295 | version_str = f"{version._major()}.{version._minor()}.{version._patch()}" |
| 296 | if version_str != "0.22.0": |
| 297 | print(f"Unsupported TOSA version: {version_str}") |
| 298 | assert False |
| 299 | |
| 300 | |
| 301 | def read_tosa(filename, batch_size, feed_dict, output_node_names, initialisation_nodes): |
| 302 | tosa_graph = TosaGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes) |
| 303 | nng = tosa_graph.nng |
| 304 | nng.refresh_after_modification() |
| 305 | return nng |