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 |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 23 | from .errors import UnsupportedFeatureError |
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) |
| 57 | op.outputs = [tens] |
| 58 | tens.ops = [op] |
| 59 | |
| 60 | return tens |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 61 | |
| 62 | |
| 63 | class TFLiteSubgraph: |
| 64 | def __init__(self, graph, subgraph): |
| 65 | self.graph = graph |
| 66 | self.name = decode_str(subgraph.Name()) |
| 67 | |
| 68 | self.tensors = [] |
| 69 | for idx in range(subgraph.TensorsLength()): |
| 70 | self.tensors.append(self.parse_tensor(subgraph.Tensors(idx))) |
| 71 | |
| 72 | for idx in range(subgraph.OperatorsLength()): |
| 73 | self.parse_operator(subgraph.Operators(idx)) |
| 74 | |
| 75 | self.outputs = [self.tensors[idx] for idx in subgraph.OutputsAsNumpy()] |
| 76 | self.inputs = [self.tensors[idx] for idx in subgraph.InputsAsNumpy()] |
| 77 | |
| 78 | # Fix up tensors without operations. Generate either Placeholder or Constant ops |
| 79 | for tens in self.inputs: |
| 80 | assert not tens.ops |
| 81 | op = Operation("Placeholder", tens.name) |
| 82 | op.outputs = [tens] |
| 83 | tens.ops = [op] |
| 84 | |
| 85 | for tens in self.tensors: |
| 86 | if not tens.ops: |
| 87 | op = Operation("Const", tens.name) |
| 88 | op.outputs = [tens] |
| 89 | tens.ops = [op] |
| 90 | |
| 91 | def parse_tensor(self, tens_data): |
| 92 | np_shape = tens_data.ShapeAsNumpy() |
| 93 | shape = list(np_shape) if type(np_shape) is np.ndarray else [] |
| 94 | name = decode_str(tens_data.Name()) |
| 95 | dtype = datatype_map[tens_data.Type()] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 96 | tens = Tensor(shape, dtype, name) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 97 | quant = tens_data.Quantization() |
| 98 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 99 | tens.quantization = QuantizationParameters() |
Tim Hall | e4e58e1 | 2020-05-08 09:50:21 +0100 | [diff] [blame] | 100 | if quant is not None: |
Diego Russo | d0eee26 | 2020-04-23 18:14:37 +0100 | [diff] [blame] | 101 | tens.quantization.min = self.len1_array_to_scalar(quant.MinAsNumpy()) |
| 102 | tens.quantization.max = self.len1_array_to_scalar(quant.MaxAsNumpy()) |
| 103 | tens.quantization.scale_f32 = self.len1_array_to_scalar(quant.ScaleAsNumpy()) |
| 104 | tens.quantization.zero_point = self.len1_array_to_scalar(quant.ZeroPointAsNumpy()) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 105 | |
| 106 | if dtype == DataType.uint8: |
| 107 | tens.quantization.quant_min = 0 |
| 108 | tens.quantization.quant_max = (1 << dtype.bits) - 1 |
| 109 | elif dtype in set((DataType.int8, DataType.int16, DataType.int32, DataType.int64)): |
| 110 | tens.quantization.quant_min = -(1 << (dtype.bits - 1)) |
| 111 | tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 112 | |
| 113 | if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None: |
| 114 | tens.quantization = None |
| 115 | |
| 116 | tens.values = None |
| 117 | buf = self.graph.buffers[tens_data.Buffer()] |
| 118 | if buf is not None: |
| 119 | tens.values = np.array(buf.view(datatype_map_numpy[tens_data.Type()]).reshape(shape)) |
| 120 | if tens.quantization is not None: |
| 121 | tens.quant_values = tens.values |
| 122 | tens.values = tens.quantization.dequantize(tens.quant_values) |
| 123 | return tens |
| 124 | |
| 125 | def parse_operator(self, op_data): |
| 126 | op_type, opt_serializer = self.graph.operator_codes[op_data.OpcodeIndex()] |
| 127 | inputs = [self.tensors[idx] for idx in op_data.InputsAsNumpy()] |
| 128 | outputs = [self.tensors[idx] for idx in op_data.OutputsAsNumpy()] |
| 129 | name = "unknown_op_name" |
| 130 | if len(outputs): |
| 131 | name = outputs[0].name |
| 132 | op = Operation(op_type, name) |
| 133 | op.inputs = inputs |
| 134 | op.outputs = outputs |
| 135 | for out in op.outputs: |
| 136 | out.ops = [op] |
| 137 | |
| 138 | activation_function_to_split_out = None |
| 139 | |
| 140 | if op_type.startswith("DepthwiseConv2d") or op_type.startswith("Conv2D"): |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 141 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 142 | |
| 143 | if op_type.startswith("FullyConnected"): |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 144 | inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 145 | |
| 146 | if opt_serializer is not None: |
| 147 | op.attrs = opt_serializer.deserialize(op_data.BuiltinOptions(), op_data.CustomOptionsAsNumpy()) |
| 148 | |
| 149 | if "stride_w" in op.attrs: |
| 150 | op.attrs["strides"] = (1, op.attrs["stride_h"], op.attrs["stride_w"], 1) |
| 151 | if "filter_width" in op.attrs: |
| 152 | op.attrs["ksize"] = (1, op.attrs["filter_height"], op.attrs["filter_width"], 1) |
| 153 | if "dilation_w_factor" in op.attrs: |
| 154 | op.attrs["dilation"] = (1, op.attrs["dilation_h_factor"], op.attrs["dilation_w_factor"], 1) |
| 155 | if "depth_multiplier" in op.attrs: |
| 156 | op.attrs["channel_multiplier"] = op.attrs["depth_multiplier"] |
| 157 | |
| 158 | if "fused_activation_function" in op.attrs: |
| 159 | if op_type in set(("ConcatTFLite",)): |
| 160 | act = op.attrs["fused_activation_function"] |
| 161 | del op.attrs["fused_activation_function"] |
| 162 | if act is not None: |
| 163 | activation_function_to_split_out = act |
| 164 | |
| 165 | if activation_function_to_split_out is not None: |
| 166 | act_op = Operation(activation_function_to_split_out, name + activation_function_to_split_out) |
| 167 | out_tens = op.outputs[0] |
| 168 | intermediate_tens = out_tens.clone("_act_intermediate") |
| 169 | out_tens.ops = [act_op] |
| 170 | act_op.outputs = [out_tens] |
| 171 | intermediate_tens.ops = [op] |
| 172 | op.outputs[0] = intermediate_tens |
| 173 | act_op.inputs = [intermediate_tens] |
| 174 | |
Diego Russo | d0eee26 | 2020-04-23 18:14:37 +0100 | [diff] [blame] | 175 | @staticmethod |
| 176 | def len1_array_to_scalar(arr): |
| 177 | # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in |
| 178 | # the input buffer. This is represented in Vela by using None. |
| 179 | # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays |
| 180 | # are converted to scalars |
| 181 | if isinstance(arr, int) and arr == 0: |
| 182 | return None |
| 183 | if len(arr) == 1: |
| 184 | return arr[0] |
| 185 | return arr |
| 186 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 187 | |
| 188 | class TFLiteGraph: |
| 189 | def __init__( |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 190 | self, filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[], |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 191 | ): |
| 192 | |
| 193 | self.op_times = {} |
| 194 | if batch_size is None: |
| 195 | batch_size = 1 |
| 196 | self.batch_size = batch_size |
| 197 | self.name = os.path.splitext(os.path.basename(filename))[0] |
| 198 | self.initialisation_nodes = initialisation_nodes |
| 199 | |
| 200 | with open(filename, "rb") as f: |
| 201 | buf = bytearray(f.read()) |
| 202 | |
| 203 | model = Model.GetRootAsModel(buf, 0) |
| 204 | |
| 205 | self.buffers = [] |
| 206 | for idx in range(model.BuffersLength()): |
| 207 | self.buffers.append(self.parse_buffer(model.Buffers(idx))) |
| 208 | |
| 209 | self.operator_codes = [] |
| 210 | for idx in range(model.OperatorCodesLength()): |
| 211 | self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx))) |
| 212 | |
| 213 | self.subgraphs = [] |
| 214 | for idx in range(model.SubgraphsLength()): |
| 215 | self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx))) |
| 216 | |
| 217 | self.nng = Graph(self.name, self.batch_size) |
| 218 | for tflite_sg in self.subgraphs: |
| 219 | sg = Subgraph(tflite_sg.name) |
| 220 | sg.original_inputs = tflite_sg.inputs # Preserve the original input order |
| 221 | sg.output_tensors = tflite_sg.outputs |
| 222 | self.nng.subgraphs.append(sg) |
| 223 | |
| 224 | def parse_buffer(self, buf_data): |
| 225 | if buf_data.DataLength() == 0: |
| 226 | return None |
| 227 | data = buf_data.DataAsNumpy() |
| 228 | return data |
| 229 | |
| 230 | def parse_operator_code(self, code): |
| 231 | c = code.BuiltinCode() |
Louis Verhaard | 678645b | 2020-06-15 15:22:47 +0200 | [diff] [blame^] | 232 | if not c in builtin_operator_map: |
| 233 | msg = "The input file contains operator code {} which is currently not supported".format(c) |
| 234 | raise InputFileError(self.name, msg) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 235 | op_type, ser = builtin_operator_map[c] |
| 236 | if c == BuiltinOperator.CUSTOM: |
| 237 | op_type += decode_str(code.CustomCode()) |
| 238 | return op_type, ser |
| 239 | |
| 240 | |
| 241 | def read_tflite( |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 242 | filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[], |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 243 | ): |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 244 | 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] | 245 | nng = tflite_graph.nng |
| 246 | nng.refresh_after_modification() |
| 247 | return nng |