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