blob: b47177f79f3a65abbfa1f31f67aad67a56e62543 [file] [log] [blame]
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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
Henrik G Olssonea9b23c2021-03-23 17:34:49 +010019import struct
20import sys
Tim Hall79d07d22020-04-27 18:20:16 +010021
22import numpy as np
Tim Hall79d07d22020-04-27 18:20:16 +010023
Louis Verhaard678645b2020-06-15 15:22:47 +020024from .errors import InputFileError
Diego Russoe8a10452020-04-21 17:39:10 +010025from .nn_graph import Graph
26from .nn_graph import Subgraph
Louis Verhaarde8a5a782020-11-02 18:04:27 +010027from .operation import create_activation_function
Louis Verhaardaee5d752020-09-30 09:01:52 +020028from .operation import Op
Diego Russoea6111a2020-04-14 18:41:58 +010029from .operation import Operation
Diego Russoe8a10452020-04-21 17:39:10 +010030from .tensor import QuantizationParameters
31from .tensor import Tensor
32from .tflite.BuiltinOperator import BuiltinOperator
33from .tflite.Model import Model
34from .tflite_mapping import builtin_operator_map
35from .tflite_mapping import DataType
36from .tflite_mapping import datatype_map
37from .tflite_mapping import datatype_map_numpy
Tim Hall79d07d22020-04-27 18:20:16 +010038
39
40def decode_str(s):
41 if s is None:
42 return ""
43 return s.decode("utf-8")
44
45
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +010046def clone_and_reshape_tensor(src_tens, reorder, set_unique):
47 tens = src_tens.clone("_reshape", set_unique)
Louis Verhaard3c07c972020-05-07 08:12:58 +020048 tens.shape = [src_tens.shape[idx] for idx in reorder]
49 tens.bandwidth_shape = tens.shape
50 tens.storage_shape = tens.shape
Tim Hall79d07d22020-04-27 18:20:16 +010051
Louis Verhaard3c07c972020-05-07 08:12:58 +020052 if tens.values is not None:
53 tens.values = tens.values.transpose(reorder)
Tim Hall79d07d22020-04-27 18:20:16 +010054
Louis Verhaard3c07c972020-05-07 08:12:58 +020055 if tens.quant_values is not None:
56 tens.quant_values = tens.quant_values.transpose(reorder)
57
Louis Verhaardaee5d752020-09-30 09:01:52 +020058 op = Operation(Op.Const, tens.name)
Michael McGeaghc5b549b2020-08-07 11:54:28 +010059 op.set_output_tensor(tens)
Louis Verhaard3c07c972020-05-07 08:12:58 +020060 return tens
Tim Hall79d07d22020-04-27 18:20:16 +010061
62
63class 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()):
Tim Hallc8310b12020-06-17 14:53:11 +010073 self.parse_operator(idx, subgraph.Operators(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010074
Tim Hallc8310b12020-06-17 14:53:11 +010075 self.outputs = self.get_tensors_from_indices_remove_duplicates(subgraph.OutputsAsNumpy(), "output")
76 self.inputs = self.get_tensors_from_indices_remove_duplicates(subgraph.InputsAsNumpy(), "input")
Tim Hall79d07d22020-04-27 18:20:16 +010077
78 # Fix up tensors without operations. Generate either Placeholder or Constant ops
79 for tens in self.inputs:
Tim Hallc8310b12020-06-17 14:53:11 +010080 if tens.ops != []:
Michael McGeagh528a56d2020-12-16 11:33:21 +000081 tens.error("This subgraph input tensor has unexpected driving operators.")
Tim Hallc8310b12020-06-17 14:53:11 +010082
Louis Verhaardaee5d752020-09-30 09:01:52 +020083 op = Operation(Op.Placeholder, tens.name)
Michael McGeaghc5b549b2020-08-07 11:54:28 +010084 op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +010085
86 for tens in self.tensors:
87 if not tens.ops:
Louis Verhaardaee5d752020-09-30 09:01:52 +020088 op = Operation(Op.Const, tens.name)
Michael McGeaghc5b549b2020-08-07 11:54:28 +010089 op.set_output_tensor(tens)
Tim Hall79d07d22020-04-27 18:20:16 +010090
Tim Hallc8310b12020-06-17 14:53:11 +010091 def get_tensors_from_indices_remove_duplicates(self, indices, warning_str):
92 tensors = []
93 for idx in indices:
94 tensor = self.tensors[idx]
95 if tensor not in tensors:
96 tensors.append(tensor)
97 else:
98 print(
99 "Warning: Subgraph {0} tensor ({1}) with idx = {2} already seen. Removing the duplicate.".format(
100 warning_str, tensor, idx
101 )
102 )
103
104 return tensors
105
Tim Hall79d07d22020-04-27 18:20:16 +0100106 def parse_tensor(self, tens_data):
107 np_shape = tens_data.ShapeAsNumpy()
108 shape = list(np_shape) if type(np_shape) is np.ndarray else []
109 name = decode_str(tens_data.Name())
Dwight Lidmane05de452020-11-05 15:56:08 +0100110 tens_dtype = tens_data.Type()
111 dtype = datatype_map[tens_dtype]
Tim Hall79d07d22020-04-27 18:20:16 +0100112 tens = Tensor(shape, dtype, name)
Tim Hall79d07d22020-04-27 18:20:16 +0100113 quant = tens_data.Quantization()
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100114 tens.is_variable = tens_data.IsVariable()
Tim Hall79d07d22020-04-27 18:20:16 +0100115
Tim Hall79d07d22020-04-27 18:20:16 +0100116 tens.quantization = QuantizationParameters()
Tim Halle4e58e12020-05-08 09:50:21 +0100117 if quant is not None:
Diego Russod0eee262020-04-23 18:14:37 +0100118 tens.quantization.min = self.len1_array_to_scalar(quant.MinAsNumpy())
119 tens.quantization.max = self.len1_array_to_scalar(quant.MaxAsNumpy())
120 tens.quantization.scale_f32 = self.len1_array_to_scalar(quant.ScaleAsNumpy())
121 tens.quantization.zero_point = self.len1_array_to_scalar(quant.ZeroPointAsNumpy())
Tim Hall79d07d22020-04-27 18:20:16 +0100122
123 if dtype == DataType.uint8:
124 tens.quantization.quant_min = 0
125 tens.quantization.quant_max = (1 << dtype.bits) - 1
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000126 elif dtype in (DataType.int8, DataType.int16, DataType.int32, DataType.int64):
Tim Hall79d07d22020-04-27 18:20:16 +0100127 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
128 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
Tim Hall79d07d22020-04-27 18:20:16 +0100129
130 if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None:
131 tens.quantization = None
132
133 tens.values = None
134 buf = self.graph.buffers[tens_data.Buffer()]
Louis Verhaardf4e12be2020-12-18 14:23:06 +0100135 if buf is not None:
136 np_dtype = datatype_map_numpy[tens_dtype]
137 if dtype == DataType.string:
138 tens.values = np.array(buf.view(np_dtype))
139 else:
140 tens.values = np.array(buf.view(np_dtype).reshape(shape))
141 if tens.quantization is not None:
142 tens.quant_values = tens.values
143 tens.values = tens.quantization.dequantize(tens.quant_values)
Tim Hall79d07d22020-04-27 18:20:16 +0100144 return tens
145
Tim Hallc8310b12020-06-17 14:53:11 +0100146 def parse_operator(self, op_index, op_data):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200147 op_type, opt_serializer, custom_code = self.graph.operator_codes[op_data.OpcodeIndex()]
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200148 inputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.InputsAsNumpy()]
149 outputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.OutputsAsNumpy()]
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100150 intermediates = []
151 if op_data.IntermediatesLength():
152 intermediates = [self.tensors[idx] if idx != -1 else None for idx in op_data.IntermediatesAsNumpy()]
153
Tim Hall79d07d22020-04-27 18:20:16 +0100154 name = "unknown_op_name"
155 if len(outputs):
156 name = outputs[0].name
157 op = Operation(op_type, name)
Tim Hallc8310b12020-06-17 14:53:11 +0100158 op.op_index = op_index
Tim Hall79d07d22020-04-27 18:20:16 +0100159 op.inputs = inputs
160 op.outputs = outputs
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100161 op.intermediates = intermediates
Tim Hall79d07d22020-04-27 18:20:16 +0100162 for out in op.outputs:
163 out.ops = [op]
164
Louis Verhaardaee5d752020-09-30 09:01:52 +0200165 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 +0200166 if inputs[1].values is not None:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200167 if op.type == Op.FullyConnected:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100168 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200169 else:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100170 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200171 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200172 # No Bias tensor
173 inputs.append(None)
Patrik Gustavssone2dbed22020-10-06 10:14:36 +0200174 if inputs[-1] and inputs[-1].values is not None:
Patrik Gustavsson34359582020-11-03 10:24:08 +0100175 # Since bias tensor is used for both bias and scale,
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100176 # a clone with a unique equivalence_id is needed
177 inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True)
Tim Hall79d07d22020-04-27 18:20:16 +0100178
179 if opt_serializer is not None:
Tim Hallc8310b12020-06-17 14:53:11 +0100180 op.attrs = opt_serializer.deserialize(op_data)
Tim Hall79d07d22020-04-27 18:20:16 +0100181
Louis Verhaardaee5d752020-09-30 09:01:52 +0200182 if op_type == Op.Reshape and "new_shape" not in op.attrs:
Michael McGeagh7b245fd2020-07-31 12:50:57 +0100183 # Reshape should have an attrib "new_shape" but if it is missing, add it based on the output shape
184 op.attrs["new_shape"] = outputs[0].shape
185
Louis Verhaardaee5d752020-09-30 09:01:52 +0200186 if op_type == Op.Cast:
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200187 # Cast op should have "in/out_data_type" attribs add if missing
188 if "in_data_type" not in op.attrs:
189 op.attrs["in_data_type"] = inputs[0].dtype
190 if "out_data_type" not in op.attrs:
191 op.attrs["out_data_type"] = outputs[0].dtype
192
Tim Hall79d07d22020-04-27 18:20:16 +0100193 if "stride_w" in op.attrs:
194 op.attrs["strides"] = (1, op.attrs["stride_h"], op.attrs["stride_w"], 1)
195 if "filter_width" in op.attrs:
196 op.attrs["ksize"] = (1, op.attrs["filter_height"], op.attrs["filter_width"], 1)
197 if "dilation_w_factor" in op.attrs:
198 op.attrs["dilation"] = (1, op.attrs["dilation_h_factor"], op.attrs["dilation_w_factor"], 1)
199 if "depth_multiplier" in op.attrs:
200 op.attrs["channel_multiplier"] = op.attrs["depth_multiplier"]
201
Fredrik Svedbergbdf09f92020-11-18 11:30:21 +0100202 if op_type == Op.DepthwiseConv2DBias and op.attrs["depth_multiplier"] == 0:
203 # The depth multiplier is implicit and is calculated as weight channels / ifm channels
204 # Note however that the weights have been reshaped above.
205 # The original value is cached above in channel_multiplier
206 op.attrs["depth_multiplier"] = op.weights.shape[2] // op.ifm.shape[-1]
207
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100208 faf = op.attrs.pop("fused_activation_function", None)
209 if faf is not None:
210 op.activation = create_activation_function(faf)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200211 if custom_code is not None:
212 op.attrs["custom_code"] = custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100213
Diego Russod0eee262020-04-23 18:14:37 +0100214 @staticmethod
215 def len1_array_to_scalar(arr):
216 # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in
217 # the input buffer. This is represented in Vela by using None.
218 # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays
219 # are converted to scalars
220 if isinstance(arr, int) and arr == 0:
221 return None
222 if len(arr) == 1:
223 return arr[0]
224 return arr
225
Tim Hall79d07d22020-04-27 18:20:16 +0100226
227class TFLiteGraph:
Michael McGeagh6f725262020-12-03 15:21:36 +0000228 def __init__(self, filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
Tim Hall79d07d22020-04-27 18:20:16 +0100229
230 self.op_times = {}
231 if batch_size is None:
232 batch_size = 1
233 self.batch_size = batch_size
234 self.name = os.path.splitext(os.path.basename(filename))[0]
235 self.initialisation_nodes = initialisation_nodes
236
237 with open(filename, "rb") as f:
238 buf = bytearray(f.read())
239
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100240 try:
241 parsing_step = "parsing root"
242 model = Model.GetRootAsModel(buf, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100243
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100244 parsing_step = "parsing buffers length"
245 self.buffers = []
246 for idx in range(model.BuffersLength()):
247 parsing_step = f"parsing buffer {idx}"
248 self.buffers.append(self.parse_buffer(model.Buffers(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100249
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100250 parsing_step = "parsing operator codes length"
251 self.operator_codes = []
252 for idx in range(model.OperatorCodesLength()):
253 parsing_step = f"parsing operator code {idx}"
254 self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100255
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100256 parsing_step = "parsing subgraphs length"
257 self.subgraphs = []
258 for idx in range(model.SubgraphsLength()):
259 parsing_step = f"parsing subgraph {idx}"
260 self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100261
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100262 self.nng = Graph(self.name, self.batch_size)
263 for tflite_sg in self.subgraphs:
264 sg = Subgraph(tflite_sg.name)
265 sg.original_inputs = tflite_sg.inputs # Preserve the original input order
266 sg.output_tensors = tflite_sg.outputs
267 self.nng.subgraphs.append(sg)
Tim Hall79d07d22020-04-27 18:20:16 +0100268
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100269 parsing_step = "parsing metadata length"
270 # Preserve the original metadata
271 for idx in range(model.MetadataLength()):
272 parsing_step = f"parsing metadata {idx}"
273 meta = model.Metadata(idx)
274 parsing_step = f"parsing metadata name of metadata {idx}"
275 name = meta.Name()
276 if name is not None:
277 parsing_step = f"parsing metadata {idx} ({name})"
278 buf_data = self.buffers[meta.Buffer()]
279 self.nng.metadata.append((name, buf_data))
280 except (struct.error, TypeError, RuntimeError) as e:
281 print(f'Error: Invalid tflite file. Got "{e}" while {parsing_step}.')
282 sys.exit(1)
Michael McGeagh22f74e12020-08-07 16:21:03 +0100283
Tim Hall79d07d22020-04-27 18:20:16 +0100284 def parse_buffer(self, buf_data):
285 if buf_data.DataLength() == 0:
286 return None
287 data = buf_data.DataAsNumpy()
288 return data
289
290 def parse_operator_code(self, code):
291 c = code.BuiltinCode()
Tim Hall42abec12021-02-04 21:31:57 +0000292 if c == 0:
293 c = code.DeprecatedBuiltinCode()
Tim Hallc30f4952020-06-15 20:47:35 +0100294 if c not in builtin_operator_map:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000295 raise InputFileError(
296 self.name, f"The input file contains operator code '{c}' which is currently not supported"
297 )
Tim Hall79d07d22020-04-27 18:20:16 +0100298 op_type, ser = builtin_operator_map[c]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200299 custom_code = None
Tim Hall79d07d22020-04-27 18:20:16 +0100300 if c == BuiltinOperator.CUSTOM:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200301 custom_code = decode_str(code.CustomCode())
302 return op_type, ser, custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100303
304
Michael McGeagh6f725262020-12-03 15:21:36 +0000305def read_tflite(filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
Diego Russoea6111a2020-04-14 18:41:58 +0100306 tflite_graph = TFLiteGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
Tim Hall79d07d22020-04-27 18:20:16 +0100307 nng = tflite_graph.nng
308 nng.refresh_after_modification()
309 return nng