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 | # Functions used to read from a TensorFlow Lite format file. |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 18 | import os.path |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 19 | |
| 20 | import numpy as np |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 21 | |
Louis Verhaard | 678645b | 2020-06-15 15:22:47 +0200 | [diff] [blame] | 22 | from .errors import InputFileError |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 23 | from .nn_graph import Graph |
| 24 | from .nn_graph import Subgraph |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 25 | from .operation import create_activation_function |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 26 | from .operation import Op |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 27 | from .operation import Operation |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 28 | from .tensor import QuantizationParameters |
| 29 | from .tensor import Tensor |
| 30 | from .tflite.BuiltinOperator import BuiltinOperator |
| 31 | from .tflite.Model import Model |
| 32 | from .tflite_mapping import builtin_operator_map |
| 33 | from .tflite_mapping import DataType |
| 34 | from .tflite_mapping import datatype_map |
| 35 | from .tflite_mapping import datatype_map_numpy |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 36 | |
| 37 | |
| 38 | def decode_str(s): |
| 39 | if s is None: |
| 40 | return "" |
| 41 | return s.decode("utf-8") |
| 42 | |
| 43 | |
Patrik Gustavsson | 6ae0e42 | 2020-11-04 12:43:50 +0100 | [diff] [blame] | 44 | def clone_and_reshape_tensor(src_tens, reorder, set_unique): |
| 45 | tens = src_tens.clone("_reshape", set_unique) |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 46 | tens.shape = [src_tens.shape[idx] for idx in reorder] |
| 47 | tens.bandwidth_shape = tens.shape |
| 48 | tens.storage_shape = tens.shape |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 49 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 50 | if tens.values is not None: |
| 51 | tens.values = tens.values.transpose(reorder) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 52 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 53 | if tens.quant_values is not None: |
| 54 | tens.quant_values = tens.quant_values.transpose(reorder) |
| 55 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 56 | op = Operation(Op.Const, tens.name) |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 57 | op.set_output_tensor(tens) |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 58 | return tens |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 59 | |
| 60 | |
| 61 | class TFLiteSubgraph: |
| 62 | def __init__(self, graph, subgraph): |
| 63 | self.graph = graph |
| 64 | self.name = decode_str(subgraph.Name()) |
| 65 | |
| 66 | self.tensors = [] |
| 67 | for idx in range(subgraph.TensorsLength()): |
| 68 | self.tensors.append(self.parse_tensor(subgraph.Tensors(idx))) |
| 69 | |
| 70 | for idx in range(subgraph.OperatorsLength()): |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 71 | self.parse_operator(idx, subgraph.Operators(idx)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 72 | |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 73 | self.outputs = self.get_tensors_from_indices_remove_duplicates(subgraph.OutputsAsNumpy(), "output") |
| 74 | self.inputs = self.get_tensors_from_indices_remove_duplicates(subgraph.InputsAsNumpy(), "input") |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 75 | |
| 76 | # Fix up tensors without operations. Generate either Placeholder or Constant ops |
| 77 | for tens in self.inputs: |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 78 | if tens.ops != []: |
Michael McGeagh | 528a56d | 2020-12-16 11:33:21 +0000 | [diff] [blame] | 79 | tens.error("This subgraph input tensor has unexpected driving operators.") |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 80 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 81 | op = Operation(Op.Placeholder, tens.name) |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 82 | op.set_output_tensor(tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 83 | |
| 84 | for tens in self.tensors: |
| 85 | if not tens.ops: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 86 | op = Operation(Op.Const, tens.name) |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 87 | op.set_output_tensor(tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 88 | |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 89 | def get_tensors_from_indices_remove_duplicates(self, indices, warning_str): |
| 90 | tensors = [] |
| 91 | for idx in indices: |
| 92 | tensor = self.tensors[idx] |
| 93 | if tensor not in tensors: |
| 94 | tensors.append(tensor) |
| 95 | else: |
| 96 | print( |
| 97 | "Warning: Subgraph {0} tensor ({1}) with idx = {2} already seen. Removing the duplicate.".format( |
| 98 | warning_str, tensor, idx |
| 99 | ) |
| 100 | ) |
| 101 | |
| 102 | return tensors |
| 103 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 104 | def parse_tensor(self, tens_data): |
| 105 | np_shape = tens_data.ShapeAsNumpy() |
| 106 | shape = list(np_shape) if type(np_shape) is np.ndarray else [] |
| 107 | name = decode_str(tens_data.Name()) |
Dwight Lidman | e05de45 | 2020-11-05 15:56:08 +0100 | [diff] [blame] | 108 | tens_dtype = tens_data.Type() |
| 109 | dtype = datatype_map[tens_dtype] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 110 | tens = Tensor(shape, dtype, name) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 111 | quant = tens_data.Quantization() |
| 112 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 113 | tens.quantization = QuantizationParameters() |
Tim Hall | e4e58e1 | 2020-05-08 09:50:21 +0100 | [diff] [blame] | 114 | if quant is not None: |
Diego Russo | d0eee26 | 2020-04-23 18:14:37 +0100 | [diff] [blame] | 115 | tens.quantization.min = self.len1_array_to_scalar(quant.MinAsNumpy()) |
| 116 | tens.quantization.max = self.len1_array_to_scalar(quant.MaxAsNumpy()) |
| 117 | tens.quantization.scale_f32 = self.len1_array_to_scalar(quant.ScaleAsNumpy()) |
| 118 | tens.quantization.zero_point = self.len1_array_to_scalar(quant.ZeroPointAsNumpy()) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 119 | |
| 120 | if dtype == DataType.uint8: |
| 121 | tens.quantization.quant_min = 0 |
| 122 | tens.quantization.quant_max = (1 << dtype.bits) - 1 |
Michael McGeagh | f3e3ad7 | 2020-12-02 12:39:03 +0000 | [diff] [blame] | 123 | elif dtype in (DataType.int8, DataType.int16, DataType.int32, DataType.int64): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 124 | tens.quantization.quant_min = -(1 << (dtype.bits - 1)) |
| 125 | tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 126 | |
| 127 | if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None: |
| 128 | tens.quantization = None |
| 129 | |
| 130 | tens.values = None |
| 131 | buf = self.graph.buffers[tens_data.Buffer()] |
Louis Verhaard | f4e12be | 2020-12-18 14:23:06 +0100 | [diff] [blame] | 132 | if buf is not None: |
| 133 | np_dtype = datatype_map_numpy[tens_dtype] |
| 134 | if dtype == DataType.string: |
| 135 | tens.values = np.array(buf.view(np_dtype)) |
| 136 | else: |
| 137 | tens.values = np.array(buf.view(np_dtype).reshape(shape)) |
| 138 | if tens.quantization is not None: |
| 139 | tens.quant_values = tens.values |
| 140 | tens.values = tens.quantization.dequantize(tens.quant_values) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 141 | return tens |
| 142 | |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 143 | def parse_operator(self, op_index, op_data): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 144 | op_type, opt_serializer, custom_code = self.graph.operator_codes[op_data.OpcodeIndex()] |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 145 | inputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.InputsAsNumpy()] |
| 146 | outputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.OutputsAsNumpy()] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 147 | name = "unknown_op_name" |
| 148 | if len(outputs): |
| 149 | name = outputs[0].name |
| 150 | op = Operation(op_type, name) |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 151 | op.op_index = op_index |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 152 | op.inputs = inputs |
| 153 | op.outputs = outputs |
| 154 | for out in op.outputs: |
| 155 | out.ops = [op] |
| 156 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 157 | if op.type.is_depthwise_conv2d_op() or op.type.is_conv2d_op() or op.type == Op.FullyConnected: |
Andreas Nevalainen | d8c032d | 2020-09-11 10:25:09 +0200 | [diff] [blame] | 158 | if inputs[1].values is not None: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 159 | if op.type == Op.FullyConnected: |
Patrik Gustavsson | 6ae0e42 | 2020-11-04 12:43:50 +0100 | [diff] [blame] | 160 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 161 | else: |
Patrik Gustavsson | 6ae0e42 | 2020-11-04 12:43:50 +0100 | [diff] [blame] | 162 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 163 | if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]: |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 164 | # No Bias tensor |
| 165 | inputs.append(None) |
Patrik Gustavsson | e2dbed2 | 2020-10-06 10:14:36 +0200 | [diff] [blame] | 166 | if inputs[-1] and inputs[-1].values is not None: |
Patrik Gustavsson | 3435958 | 2020-11-03 10:24:08 +0100 | [diff] [blame] | 167 | # Since bias tensor is used for both bias and scale, |
Patrik Gustavsson | 6ae0e42 | 2020-11-04 12:43:50 +0100 | [diff] [blame] | 168 | # a clone with a unique equivalence_id is needed |
| 169 | inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 170 | |
| 171 | if opt_serializer is not None: |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 172 | op.attrs = opt_serializer.deserialize(op_data) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 173 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 174 | if op_type == Op.Reshape and "new_shape" not in op.attrs: |
Michael McGeagh | 7b245fd | 2020-07-31 12:50:57 +0100 | [diff] [blame] | 175 | # Reshape should have an attrib "new_shape" but if it is missing, add it based on the output shape |
| 176 | op.attrs["new_shape"] = outputs[0].shape |
| 177 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 178 | if op_type == Op.Cast: |
Andreas Nevalainen | d8c032d | 2020-09-11 10:25:09 +0200 | [diff] [blame] | 179 | # Cast op should have "in/out_data_type" attribs add if missing |
| 180 | if "in_data_type" not in op.attrs: |
| 181 | op.attrs["in_data_type"] = inputs[0].dtype |
| 182 | if "out_data_type" not in op.attrs: |
| 183 | op.attrs["out_data_type"] = outputs[0].dtype |
| 184 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 185 | if "stride_w" in op.attrs: |
| 186 | op.attrs["strides"] = (1, op.attrs["stride_h"], op.attrs["stride_w"], 1) |
| 187 | if "filter_width" in op.attrs: |
| 188 | op.attrs["ksize"] = (1, op.attrs["filter_height"], op.attrs["filter_width"], 1) |
| 189 | if "dilation_w_factor" in op.attrs: |
| 190 | op.attrs["dilation"] = (1, op.attrs["dilation_h_factor"], op.attrs["dilation_w_factor"], 1) |
| 191 | if "depth_multiplier" in op.attrs: |
| 192 | op.attrs["channel_multiplier"] = op.attrs["depth_multiplier"] |
| 193 | |
Fredrik Svedberg | bdf09f9 | 2020-11-18 11:30:21 +0100 | [diff] [blame] | 194 | if op_type == Op.DepthwiseConv2DBias and op.attrs["depth_multiplier"] == 0: |
| 195 | # The depth multiplier is implicit and is calculated as weight channels / ifm channels |
| 196 | # Note however that the weights have been reshaped above. |
| 197 | # The original value is cached above in channel_multiplier |
| 198 | op.attrs["depth_multiplier"] = op.weights.shape[2] // op.ifm.shape[-1] |
| 199 | |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 200 | faf = op.attrs.pop("fused_activation_function", None) |
| 201 | if faf is not None: |
| 202 | op.activation = create_activation_function(faf) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 203 | if custom_code is not None: |
| 204 | op.attrs["custom_code"] = custom_code |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 205 | |
Diego Russo | d0eee26 | 2020-04-23 18:14:37 +0100 | [diff] [blame] | 206 | @staticmethod |
| 207 | def len1_array_to_scalar(arr): |
| 208 | # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in |
| 209 | # the input buffer. This is represented in Vela by using None. |
| 210 | # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays |
| 211 | # are converted to scalars |
| 212 | if isinstance(arr, int) and arr == 0: |
| 213 | return None |
| 214 | if len(arr) == 1: |
| 215 | return arr[0] |
| 216 | return arr |
| 217 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 218 | |
| 219 | class TFLiteGraph: |
Michael McGeagh | 6f72526 | 2020-12-03 15:21:36 +0000 | [diff] [blame] | 220 | def __init__(self, filename, batch_size, feed_dict, output_node_names, initialisation_nodes): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 221 | |
| 222 | self.op_times = {} |
| 223 | if batch_size is None: |
| 224 | batch_size = 1 |
| 225 | self.batch_size = batch_size |
| 226 | self.name = os.path.splitext(os.path.basename(filename))[0] |
| 227 | self.initialisation_nodes = initialisation_nodes |
| 228 | |
| 229 | with open(filename, "rb") as f: |
| 230 | buf = bytearray(f.read()) |
| 231 | |
| 232 | model = Model.GetRootAsModel(buf, 0) |
| 233 | |
| 234 | self.buffers = [] |
| 235 | for idx in range(model.BuffersLength()): |
| 236 | self.buffers.append(self.parse_buffer(model.Buffers(idx))) |
| 237 | |
| 238 | self.operator_codes = [] |
| 239 | for idx in range(model.OperatorCodesLength()): |
| 240 | self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx))) |
| 241 | |
| 242 | self.subgraphs = [] |
| 243 | for idx in range(model.SubgraphsLength()): |
| 244 | self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx))) |
| 245 | |
| 246 | self.nng = Graph(self.name, self.batch_size) |
| 247 | for tflite_sg in self.subgraphs: |
| 248 | sg = Subgraph(tflite_sg.name) |
| 249 | sg.original_inputs = tflite_sg.inputs # Preserve the original input order |
| 250 | sg.output_tensors = tflite_sg.outputs |
| 251 | self.nng.subgraphs.append(sg) |
| 252 | |
Michael McGeagh | 22f74e1 | 2020-08-07 16:21:03 +0100 | [diff] [blame] | 253 | # Preserve the original metadata |
| 254 | for idx in range(model.MetadataLength()): |
| 255 | meta = model.Metadata(idx) |
| 256 | name = meta.Name() |
| 257 | if name is not None: |
| 258 | buf_data = self.buffers[meta.Buffer()] |
| 259 | self.nng.metadata.append((name, buf_data)) |
| 260 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 261 | def parse_buffer(self, buf_data): |
| 262 | if buf_data.DataLength() == 0: |
| 263 | return None |
| 264 | data = buf_data.DataAsNumpy() |
| 265 | return data |
| 266 | |
| 267 | def parse_operator_code(self, code): |
| 268 | c = code.BuiltinCode() |
Tim Hall | 42abec1 | 2021-02-04 21:31:57 +0000 | [diff] [blame] | 269 | if c == 0: |
| 270 | c = code.DeprecatedBuiltinCode() |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 271 | if c not in builtin_operator_map: |
Michael McGeagh | 7a6f843 | 2020-12-02 15:29:22 +0000 | [diff] [blame] | 272 | raise InputFileError( |
| 273 | self.name, f"The input file contains operator code '{c}' which is currently not supported" |
| 274 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 275 | op_type, ser = builtin_operator_map[c] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 276 | custom_code = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 277 | if c == BuiltinOperator.CUSTOM: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 278 | custom_code = decode_str(code.CustomCode()) |
| 279 | return op_type, ser, custom_code |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 280 | |
| 281 | |
Michael McGeagh | 6f72526 | 2020-12-03 15:21:36 +0000 | [diff] [blame] | 282 | def read_tflite(filename, batch_size, feed_dict, output_node_names, initialisation_nodes): |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 283 | tflite_graph = TFLiteGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 284 | nng = tflite_graph.nng |
| 285 | nng.refresh_after_modification() |
| 286 | return nng |