blob: 82feddd971dab092e68e2c54495a554a8c1c078a [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# 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 Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Functions used to read from a TensorFlow Lite format file.
Diego Russoea6111a2020-04-14 18:41:58 +010018import os.path
Tim Hall79d07d22020-04-27 18:20:16 +010019
20import numpy as np
Tim Hall79d07d22020-04-27 18:20:16 +010021
Louis Verhaard678645b2020-06-15 15:22:47 +020022from .errors import InputFileError
Tim Hallc8310b12020-06-17 14:53:11 +010023from .errors import TensorError
Diego Russoe8a10452020-04-21 17:39:10 +010024from .nn_graph import Graph
25from .nn_graph import Subgraph
Louis Verhaardaee5d752020-09-30 09:01:52 +020026from .operation import Op
Diego Russoea6111a2020-04-14 18:41:58 +010027from .operation import Operation
Diego Russoe8a10452020-04-21 17:39:10 +010028from .tensor import QuantizationParameters
29from .tensor import Tensor
30from .tflite.BuiltinOperator import BuiltinOperator
31from .tflite.Model import Model
32from .tflite_mapping import builtin_operator_map
33from .tflite_mapping import DataType
34from .tflite_mapping import datatype_map
35from .tflite_mapping import datatype_map_numpy
Tim Hall79d07d22020-04-27 18:20:16 +010036
37
38def decode_str(s):
39 if s is None:
40 return ""
41 return s.decode("utf-8")
42
43
Louis Verhaard3c07c972020-05-07 08:12:58 +020044def clone_and_reshape_tensor(src_tens, reorder):
Tim Hall79d07d22020-04-27 18:20:16 +010045
Louis Verhaard3c07c972020-05-07 08:12:58 +020046 tens = src_tens.clone("_reshape")
47 tens.shape = [src_tens.shape[idx] for idx in reorder]
48 tens.bandwidth_shape = tens.shape
49 tens.storage_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +010050
Louis Verhaard3c07c972020-05-07 08:12:58 +020051 if tens.values is not None:
52 tens.values = tens.values.transpose(reorder)
Tim Hall79d07d22020-04-27 18:20:16 +010053
Louis Verhaard3c07c972020-05-07 08:12:58 +020054 if tens.quant_values is not None:
55 tens.quant_values = tens.quant_values.transpose(reorder)
56
Louis Verhaardaee5d752020-09-30 09:01:52 +020057 op = Operation(Op.Const, tens.name)
Michael McGeaghc5b549b2020-08-07 11:54:28 +010058 op.set_output_tensor(tens)
Louis Verhaard3c07c972020-05-07 08:12:58 +020059 return tens
Tim Hall79d07d22020-04-27 18:20:16 +010060
61
62class 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 Hallc8310b12020-06-17 14:53:11 +010072 self.parse_operator(idx, subgraph.Operators(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010073
Tim Hallc8310b12020-06-17 14:53:11 +010074 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 Hall79d07d22020-04-27 18:20:16 +010076
77 # Fix up tensors without operations. Generate either Placeholder or Constant ops
78 for tens in self.inputs:
Tim Hallc8310b12020-06-17 14:53:11 +010079 if tens.ops != []:
80 TensorError(tens, "This subgraph input tensor has unexpected driving operators.")
81
Louis Verhaardaee5d752020-09-30 09:01:52 +020082 op = Operation(Op.Placeholder, tens.name)
Michael McGeaghc5b549b2020-08-07 11:54:28 +010083 op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +010084
85 for tens in self.tensors:
86 if not tens.ops:
Louis Verhaardaee5d752020-09-30 09:01:52 +020087 op = Operation(Op.Const, tens.name)
Michael McGeaghc5b549b2020-08-07 11:54:28 +010088 op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +010089
Tim Hallc8310b12020-06-17 14:53:11 +010090 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 Hall79d07d22020-04-27 18:20:16 +0100105 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())
109 dtype = datatype_map[tens_data.Type()]
Tim Hall79d07d22020-04-27 18:20:16 +0100110 tens = Tensor(shape, dtype, name)
Tim Hall79d07d22020-04-27 18:20:16 +0100111 quant = tens_data.Quantization()
112
Tim Hall79d07d22020-04-27 18:20:16 +0100113 tens.quantization = QuantizationParameters()
Tim Halle4e58e12020-05-08 09:50:21 +0100114 if quant is not None:
Diego Russod0eee262020-04-23 18:14:37 +0100115 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 Hall79d07d22020-04-27 18:20:16 +0100119
120 if dtype == DataType.uint8:
121 tens.quantization.quant_min = 0
122 tens.quantization.quant_max = (1 << dtype.bits) - 1
123 elif dtype in set((DataType.int8, DataType.int16, DataType.int32, DataType.int64)):
124 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
125 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
Tim Hall79d07d22020-04-27 18:20:16 +0100126
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()]
132 if buf is not None:
133 tens.values = np.array(buf.view(datatype_map_numpy[tens_data.Type()]).reshape(shape))
134 if tens.quantization is not None:
135 tens.quant_values = tens.values
136 tens.values = tens.quantization.dequantize(tens.quant_values)
137 return tens
138
Tim Hallc8310b12020-06-17 14:53:11 +0100139 def parse_operator(self, op_index, op_data):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200140 op_type, opt_serializer, custom_code = self.graph.operator_codes[op_data.OpcodeIndex()]
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200141 inputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.InputsAsNumpy()]
142 outputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.OutputsAsNumpy()]
Tim Hall79d07d22020-04-27 18:20:16 +0100143 name = "unknown_op_name"
144 if len(outputs):
145 name = outputs[0].name
146 op = Operation(op_type, name)
Tim Hallc8310b12020-06-17 14:53:11 +0100147 op.op_index = op_index
Tim Hall79d07d22020-04-27 18:20:16 +0100148 op.inputs = inputs
149 op.outputs = outputs
150 for out in op.outputs:
151 out.ops = [op]
152
Louis Verhaardaee5d752020-09-30 09:01:52 +0200153 if op.type.is_depthwise_conv2d_op() or op.type.is_conv2d_op() or op.type == Op.FullyConnected:
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200154 if inputs[1].values is not None:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200155 if op.type == Op.FullyConnected:
156 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0))
157 else:
158 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0))
159 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200160 # No Bias tensor
161 inputs.append(None)
Patrik Gustavssone2dbed22020-10-06 10:14:36 +0200162 if inputs[-1] and inputs[-1].values is not None:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200163 inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,))
Patrik Gustavsson34359582020-11-03 10:24:08 +0100164 # Since bias tensor is used for both bias and scale,
165 # set different equivalence_id for all bias tensors
166 inputs[-1].set_random_equivalence_id()
Tim Hall79d07d22020-04-27 18:20:16 +0100167
168 if opt_serializer is not None:
Tim Hallc8310b12020-06-17 14:53:11 +0100169 op.attrs = opt_serializer.deserialize(op_data)
Tim Hall79d07d22020-04-27 18:20:16 +0100170
Louis Verhaardaee5d752020-09-30 09:01:52 +0200171 if op_type == Op.Reshape and "new_shape" not in op.attrs:
Michael McGeagh7b245fd2020-07-31 12:50:57 +0100172 # 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 Verhaardaee5d752020-09-30 09:01:52 +0200175 if op_type == Op.Cast:
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200176 # 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 Hall79d07d22020-04-27 18:20:16 +0100182 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 Verhaardaee5d752020-09-30 09:01:52 +0200191 op.activation = op.attrs.pop("fused_activation_function", None)
192 if custom_code is not None:
193 op.attrs["custom_code"] = custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100194
Diego Russod0eee262020-04-23 18:14:37 +0100195 @staticmethod
196 def len1_array_to_scalar(arr):
197 # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in
198 # the input buffer. This is represented in Vela by using None.
199 # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays
200 # are converted to scalars
201 if isinstance(arr, int) and arr == 0:
202 return None
203 if len(arr) == 1:
204 return arr[0]
205 return arr
206
Tim Hall79d07d22020-04-27 18:20:16 +0100207
208class TFLiteGraph:
209 def __init__(
Diego Russoea6111a2020-04-14 18:41:58 +0100210 self, filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[],
Tim Hall79d07d22020-04-27 18:20:16 +0100211 ):
212
213 self.op_times = {}
214 if batch_size is None:
215 batch_size = 1
216 self.batch_size = batch_size
217 self.name = os.path.splitext(os.path.basename(filename))[0]
218 self.initialisation_nodes = initialisation_nodes
219
220 with open(filename, "rb") as f:
221 buf = bytearray(f.read())
222
223 model = Model.GetRootAsModel(buf, 0)
224
225 self.buffers = []
226 for idx in range(model.BuffersLength()):
227 self.buffers.append(self.parse_buffer(model.Buffers(idx)))
228
229 self.operator_codes = []
230 for idx in range(model.OperatorCodesLength()):
231 self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx)))
232
233 self.subgraphs = []
234 for idx in range(model.SubgraphsLength()):
235 self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx)))
236
237 self.nng = Graph(self.name, self.batch_size)
238 for tflite_sg in self.subgraphs:
239 sg = Subgraph(tflite_sg.name)
240 sg.original_inputs = tflite_sg.inputs # Preserve the original input order
241 sg.output_tensors = tflite_sg.outputs
242 self.nng.subgraphs.append(sg)
243
Michael McGeagh22f74e12020-08-07 16:21:03 +0100244 # Preserve the original metadata
245 for idx in range(model.MetadataLength()):
246 meta = model.Metadata(idx)
247 name = meta.Name()
248 if name is not None:
249 buf_data = self.buffers[meta.Buffer()]
250 self.nng.metadata.append((name, buf_data))
251
Tim Hall79d07d22020-04-27 18:20:16 +0100252 def parse_buffer(self, buf_data):
253 if buf_data.DataLength() == 0:
254 return None
255 data = buf_data.DataAsNumpy()
256 return data
257
258 def parse_operator_code(self, code):
259 c = code.BuiltinCode()
Tim Hallc30f4952020-06-15 20:47:35 +0100260 if c not in builtin_operator_map:
Louis Verhaard678645b2020-06-15 15:22:47 +0200261 msg = "The input file contains operator code {} which is currently not supported".format(c)
262 raise InputFileError(self.name, msg)
Tim Hall79d07d22020-04-27 18:20:16 +0100263 op_type, ser = builtin_operator_map[c]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200264 custom_code = None
Tim Hall79d07d22020-04-27 18:20:16 +0100265 if c == BuiltinOperator.CUSTOM:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200266 custom_code = decode_str(code.CustomCode())
267 return op_type, ser, custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100268
269
270def read_tflite(
Diego Russoea6111a2020-04-14 18:41:58 +0100271 filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[],
Tim Hall79d07d22020-04-27 18:20:16 +0100272):
Diego Russoea6111a2020-04-14 18:41:58 +0100273 tflite_graph = TFLiteGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
Tim Hall79d07d22020-04-27 18:20:16 +0100274 nng = tflite_graph.nng
275 nng.refresh_after_modification()
276 return nng