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 |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 23 | from .errors import TensorError |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 24 | from .nn_graph import Graph |
| 25 | from .nn_graph import Subgraph |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 26 | from .operation import Operation |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 27 | from .tensor import QuantizationParameters |
| 28 | from .tensor import Tensor |
| 29 | from .tflite.BuiltinOperator import BuiltinOperator |
| 30 | from .tflite.Model import Model |
| 31 | from .tflite_mapping import builtin_operator_map |
| 32 | from .tflite_mapping import DataType |
| 33 | from .tflite_mapping import datatype_map |
| 34 | from .tflite_mapping import datatype_map_numpy |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 35 | |
| 36 | |
| 37 | def decode_str(s): |
| 38 | if s is None: |
| 39 | return "" |
| 40 | return s.decode("utf-8") |
| 41 | |
| 42 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 43 | def clone_and_reshape_tensor(src_tens, reorder): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 44 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 45 | tens = src_tens.clone("_reshape") |
| 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 | |
| 56 | op = Operation("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 != []: |
| 79 | TensorError(tens, "This subgraph input tensor has unexpected driving operators.") |
| 80 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 81 | op = Operation("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: |
| 86 | op = Operation("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()) |
| 108 | dtype = datatype_map[tens_data.Type()] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 109 | tens = Tensor(shape, dtype, name) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 110 | quant = tens_data.Quantization() |
| 111 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 112 | tens.quantization = QuantizationParameters() |
Tim Hall | e4e58e1 | 2020-05-08 09:50:21 +0100 | [diff] [blame] | 113 | if quant is not None: |
Diego Russo | d0eee26 | 2020-04-23 18:14:37 +0100 | [diff] [blame] | 114 | tens.quantization.min = self.len1_array_to_scalar(quant.MinAsNumpy()) |
| 115 | tens.quantization.max = self.len1_array_to_scalar(quant.MaxAsNumpy()) |
| 116 | tens.quantization.scale_f32 = self.len1_array_to_scalar(quant.ScaleAsNumpy()) |
| 117 | tens.quantization.zero_point = self.len1_array_to_scalar(quant.ZeroPointAsNumpy()) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 118 | |
| 119 | if dtype == DataType.uint8: |
| 120 | tens.quantization.quant_min = 0 |
| 121 | tens.quantization.quant_max = (1 << dtype.bits) - 1 |
| 122 | elif dtype in set((DataType.int8, DataType.int16, DataType.int32, DataType.int64)): |
| 123 | tens.quantization.quant_min = -(1 << (dtype.bits - 1)) |
| 124 | tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 125 | |
| 126 | if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None: |
| 127 | tens.quantization = None |
| 128 | |
| 129 | tens.values = None |
| 130 | buf = self.graph.buffers[tens_data.Buffer()] |
| 131 | if buf is not None: |
| 132 | tens.values = np.array(buf.view(datatype_map_numpy[tens_data.Type()]).reshape(shape)) |
| 133 | if tens.quantization is not None: |
| 134 | tens.quant_values = tens.values |
| 135 | tens.values = tens.quantization.dequantize(tens.quant_values) |
| 136 | return tens |
| 137 | |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 138 | def parse_operator(self, op_index, op_data): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 139 | op_type, opt_serializer = self.graph.operator_codes[op_data.OpcodeIndex()] |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 140 | inputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.InputsAsNumpy()] |
| 141 | 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] | 142 | name = "unknown_op_name" |
| 143 | if len(outputs): |
| 144 | name = outputs[0].name |
| 145 | op = Operation(op_type, name) |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 146 | op.op_index = op_index |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 147 | op.inputs = inputs |
| 148 | op.outputs = outputs |
| 149 | for out in op.outputs: |
| 150 | out.ops = [op] |
| 151 | |
| 152 | activation_function_to_split_out = None |
| 153 | |
| 154 | if op_type.startswith("DepthwiseConv2d") or op_type.startswith("Conv2D"): |
Andreas Nevalainen | d8c032d | 2020-09-11 10:25:09 +0200 | [diff] [blame^] | 155 | if inputs[1].values is not None: |
| 156 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0)) |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 157 | if len(inputs) < 3 or (len(inputs) < 4 and "Backprop" in op_type): |
| 158 | # No Bias tensor |
| 159 | inputs.append(None) |
| 160 | if inputs[-1]: |
| 161 | inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 162 | |
| 163 | if op_type.startswith("FullyConnected"): |
Andreas Nevalainen | d8c032d | 2020-09-11 10:25:09 +0200 | [diff] [blame^] | 164 | if inputs[1].values is not None: |
| 165 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0)) |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 166 | if len(inputs) < 3: |
| 167 | # No Bias tensor |
| 168 | inputs.append(None) |
| 169 | if inputs[-1]: |
| 170 | inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 171 | |
| 172 | if opt_serializer is not None: |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 173 | op.attrs = opt_serializer.deserialize(op_data) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 174 | |
Michael McGeagh | 7b245fd | 2020-07-31 12:50:57 +0100 | [diff] [blame] | 175 | if op_type == "Reshape" and "new_shape" not in op.attrs: |
| 176 | # Reshape should have an attrib "new_shape" but if it is missing, add it based on the output shape |
| 177 | op.attrs["new_shape"] = outputs[0].shape |
| 178 | |
Andreas Nevalainen | d8c032d | 2020-09-11 10:25:09 +0200 | [diff] [blame^] | 179 | if op_type == "Cast": |
| 180 | # Cast op should have "in/out_data_type" attribs add if missing |
| 181 | if "in_data_type" not in op.attrs: |
| 182 | op.attrs["in_data_type"] = inputs[0].dtype |
| 183 | if "out_data_type" not in op.attrs: |
| 184 | op.attrs["out_data_type"] = outputs[0].dtype |
| 185 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 186 | if "stride_w" in op.attrs: |
| 187 | op.attrs["strides"] = (1, op.attrs["stride_h"], op.attrs["stride_w"], 1) |
| 188 | if "filter_width" in op.attrs: |
| 189 | op.attrs["ksize"] = (1, op.attrs["filter_height"], op.attrs["filter_width"], 1) |
| 190 | if "dilation_w_factor" in op.attrs: |
| 191 | op.attrs["dilation"] = (1, op.attrs["dilation_h_factor"], op.attrs["dilation_w_factor"], 1) |
| 192 | if "depth_multiplier" in op.attrs: |
| 193 | op.attrs["channel_multiplier"] = op.attrs["depth_multiplier"] |
| 194 | |
| 195 | if "fused_activation_function" in op.attrs: |
| 196 | if op_type in set(("ConcatTFLite",)): |
| 197 | act = op.attrs["fused_activation_function"] |
| 198 | del op.attrs["fused_activation_function"] |
| 199 | if act is not None: |
| 200 | activation_function_to_split_out = act |
| 201 | |
| 202 | if activation_function_to_split_out is not None: |
| 203 | act_op = Operation(activation_function_to_split_out, name + activation_function_to_split_out) |
| 204 | out_tens = op.outputs[0] |
| 205 | intermediate_tens = out_tens.clone("_act_intermediate") |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 206 | act_op.set_output_tensor(out_tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 207 | intermediate_tens.ops = [op] |
| 208 | op.outputs[0] = intermediate_tens |
| 209 | act_op.inputs = [intermediate_tens] |
| 210 | |
Diego Russo | d0eee26 | 2020-04-23 18:14:37 +0100 | [diff] [blame] | 211 | @staticmethod |
| 212 | def len1_array_to_scalar(arr): |
| 213 | # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in |
| 214 | # the input buffer. This is represented in Vela by using None. |
| 215 | # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays |
| 216 | # are converted to scalars |
| 217 | if isinstance(arr, int) and arr == 0: |
| 218 | return None |
| 219 | if len(arr) == 1: |
| 220 | return arr[0] |
| 221 | return arr |
| 222 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 223 | |
| 224 | class TFLiteGraph: |
| 225 | def __init__( |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 226 | self, filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[], |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 227 | ): |
| 228 | |
| 229 | self.op_times = {} |
| 230 | if batch_size is None: |
| 231 | batch_size = 1 |
| 232 | self.batch_size = batch_size |
| 233 | self.name = os.path.splitext(os.path.basename(filename))[0] |
| 234 | self.initialisation_nodes = initialisation_nodes |
| 235 | |
| 236 | with open(filename, "rb") as f: |
| 237 | buf = bytearray(f.read()) |
| 238 | |
| 239 | model = Model.GetRootAsModel(buf, 0) |
| 240 | |
| 241 | self.buffers = [] |
| 242 | for idx in range(model.BuffersLength()): |
| 243 | self.buffers.append(self.parse_buffer(model.Buffers(idx))) |
| 244 | |
| 245 | self.operator_codes = [] |
| 246 | for idx in range(model.OperatorCodesLength()): |
| 247 | self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx))) |
| 248 | |
| 249 | self.subgraphs = [] |
| 250 | for idx in range(model.SubgraphsLength()): |
| 251 | self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx))) |
| 252 | |
| 253 | self.nng = Graph(self.name, self.batch_size) |
| 254 | for tflite_sg in self.subgraphs: |
| 255 | sg = Subgraph(tflite_sg.name) |
| 256 | sg.original_inputs = tflite_sg.inputs # Preserve the original input order |
| 257 | sg.output_tensors = tflite_sg.outputs |
| 258 | self.nng.subgraphs.append(sg) |
| 259 | |
Michael McGeagh | 22f74e1 | 2020-08-07 16:21:03 +0100 | [diff] [blame] | 260 | # Preserve the original metadata |
| 261 | for idx in range(model.MetadataLength()): |
| 262 | meta = model.Metadata(idx) |
| 263 | name = meta.Name() |
| 264 | if name is not None: |
| 265 | buf_data = self.buffers[meta.Buffer()] |
| 266 | self.nng.metadata.append((name, buf_data)) |
| 267 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 268 | def parse_buffer(self, buf_data): |
| 269 | if buf_data.DataLength() == 0: |
| 270 | return None |
| 271 | data = buf_data.DataAsNumpy() |
| 272 | return data |
| 273 | |
| 274 | def parse_operator_code(self, code): |
| 275 | c = code.BuiltinCode() |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 276 | if c not in builtin_operator_map: |
Louis Verhaard | 678645b | 2020-06-15 15:22:47 +0200 | [diff] [blame] | 277 | msg = "The input file contains operator code {} which is currently not supported".format(c) |
| 278 | raise InputFileError(self.name, msg) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 279 | op_type, ser = builtin_operator_map[c] |
| 280 | if c == BuiltinOperator.CUSTOM: |
| 281 | op_type += decode_str(code.CustomCode()) |
| 282 | return op_type, ser |
| 283 | |
| 284 | |
| 285 | def read_tflite( |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 286 | filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[], |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 287 | ): |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 288 | 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] | 289 | nng = tflite_graph.nng |
| 290 | nng.refresh_after_modification() |
| 291 | return nng |