blob: 8dc5efe13bb3e87e82a7b181fcd1dbad0dd264ce [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
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +020030from .reader_util import align_tensor_indices_to_nng
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020031from .reader_util import clone_and_reshape_tensor
32from .reader_util import decode_str
33from .reader_util import fixup_tensors
Diego Russoe8a10452020-04-21 17:39:10 +010034from .tensor import QuantizationParameters
35from .tensor import Tensor
36from .tflite.BuiltinOperator import BuiltinOperator
37from .tflite.Model import Model
38from .tflite_mapping import builtin_operator_map
39from .tflite_mapping import DataType
40from .tflite_mapping import datatype_map
41from .tflite_mapping import datatype_map_numpy
Tim Hall79d07d22020-04-27 18:20:16 +010042
43
Tim Hall79d07d22020-04-27 18:20:16 +010044class TFLiteSubgraph:
45 def __init__(self, graph, subgraph):
46 self.graph = graph
47 self.name = decode_str(subgraph.Name())
48
49 self.tensors = []
50 for idx in range(subgraph.TensorsLength()):
51 self.tensors.append(self.parse_tensor(subgraph.Tensors(idx)))
52
53 for idx in range(subgraph.OperatorsLength()):
Tim Hallc8310b12020-06-17 14:53:11 +010054 self.parse_operator(idx, subgraph.Operators(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010055
Tim Hallc8310b12020-06-17 14:53:11 +010056 self.outputs = self.get_tensors_from_indices_remove_duplicates(subgraph.OutputsAsNumpy(), "output")
57 self.inputs = self.get_tensors_from_indices_remove_duplicates(subgraph.InputsAsNumpy(), "input")
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020058 fixup_tensors(self.inputs, self.tensors)
Tim Hall79d07d22020-04-27 18:20:16 +010059
Tim Hallc8310b12020-06-17 14:53:11 +010060 def get_tensors_from_indices_remove_duplicates(self, indices, warning_str):
61 tensors = []
62 for idx in indices:
63 tensor = self.tensors[idx]
64 if tensor not in tensors:
65 tensors.append(tensor)
66 else:
67 print(
68 "Warning: Subgraph {0} tensor ({1}) with idx = {2} already seen. Removing the duplicate.".format(
69 warning_str, tensor, idx
70 )
71 )
72
73 return tensors
74
Tim Hall79d07d22020-04-27 18:20:16 +010075 def parse_tensor(self, tens_data):
76 np_shape = tens_data.ShapeAsNumpy()
77 shape = list(np_shape) if type(np_shape) is np.ndarray else []
78 name = decode_str(tens_data.Name())
Dwight Lidmane05de452020-11-05 15:56:08 +010079 tens_dtype = tens_data.Type()
80 dtype = datatype_map[tens_dtype]
Tim Hall79d07d22020-04-27 18:20:16 +010081 tens = Tensor(shape, dtype, name)
Tim Hall79d07d22020-04-27 18:20:16 +010082 quant = tens_data.Quantization()
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +010083 tens.is_variable = tens_data.IsVariable()
Tim Hall79d07d22020-04-27 18:20:16 +010084
Tim Hall79d07d22020-04-27 18:20:16 +010085 tens.quantization = QuantizationParameters()
Tim Halle4e58e12020-05-08 09:50:21 +010086 if quant is not None:
Diego Russod0eee262020-04-23 18:14:37 +010087 tens.quantization.min = self.len1_array_to_scalar(quant.MinAsNumpy())
88 tens.quantization.max = self.len1_array_to_scalar(quant.MaxAsNumpy())
89 tens.quantization.scale_f32 = self.len1_array_to_scalar(quant.ScaleAsNumpy())
90 tens.quantization.zero_point = self.len1_array_to_scalar(quant.ZeroPointAsNumpy())
Fredrik Svedbergcc8569f2021-11-01 14:25:29 +010091 tens.quantization.quant_dim = quant.QuantizedDimension()
Tim Hall79d07d22020-04-27 18:20:16 +010092
93 if dtype == DataType.uint8:
94 tens.quantization.quant_min = 0
95 tens.quantization.quant_max = (1 << dtype.bits) - 1
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000096 elif dtype in (DataType.int8, DataType.int16, DataType.int32, DataType.int64):
Tim Hall79d07d22020-04-27 18:20:16 +010097 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
98 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
Tim Hall79d07d22020-04-27 18:20:16 +010099
100 if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None:
101 tens.quantization = None
102
103 tens.values = None
104 buf = self.graph.buffers[tens_data.Buffer()]
Louis Verhaardf4e12be2020-12-18 14:23:06 +0100105 if buf is not None:
106 np_dtype = datatype_map_numpy[tens_dtype]
107 if dtype == DataType.string:
108 tens.values = np.array(buf.view(np_dtype))
109 else:
110 tens.values = np.array(buf.view(np_dtype).reshape(shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100111 return tens
112
Tim Hallc8310b12020-06-17 14:53:11 +0100113 def parse_operator(self, op_index, op_data):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200114 op_type, opt_serializer, custom_code, indices = self.graph.operator_codes[op_data.OpcodeIndex()]
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200115 inputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.InputsAsNumpy()]
116 outputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.OutputsAsNumpy()]
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100117 intermediates = []
118 if op_data.IntermediatesLength():
119 intermediates = [self.tensors[idx] if idx != -1 else None for idx in op_data.IntermediatesAsNumpy()]
120
Tim Hall79d07d22020-04-27 18:20:16 +0100121 name = "unknown_op_name"
122 if len(outputs):
123 name = outputs[0].name
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200124 inputs = align_tensor_indices_to_nng(op_type, indices, inputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100125 op = Operation(op_type, name)
Tim Hallc8310b12020-06-17 14:53:11 +0100126 op.op_index = op_index
Tim Hall79d07d22020-04-27 18:20:16 +0100127 op.inputs = inputs
128 op.outputs = outputs
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100129 op.intermediates = intermediates
Tim Hall79d07d22020-04-27 18:20:16 +0100130 for out in op.outputs:
131 out.ops = [op]
132
Louis Verhaardaee5d752020-09-30 09:01:52 +0200133 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 +0200134 if inputs[1].values is not None:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200135 if op.type == Op.FullyConnected:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100136 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200137 else:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100138 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200139 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200140 # No Bias tensor
141 inputs.append(None)
Patrik Gustavssone2dbed22020-10-06 10:14:36 +0200142 if inputs[-1] and inputs[-1].values is not None:
Patrik Gustavsson34359582020-11-03 10:24:08 +0100143 # Since bias tensor is used for both bias and scale,
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100144 # a clone with a unique equivalence_id is needed
145 inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True)
Tim Hall79d07d22020-04-27 18:20:16 +0100146
147 if opt_serializer is not None:
Tim Hallc8310b12020-06-17 14:53:11 +0100148 op.attrs = opt_serializer.deserialize(op_data)
Tim Hall79d07d22020-04-27 18:20:16 +0100149
Louis Verhaardaee5d752020-09-30 09:01:52 +0200150 if op_type == Op.Reshape and "new_shape" not in op.attrs:
Michael McGeagh7b245fd2020-07-31 12:50:57 +0100151 # Reshape should have an attrib "new_shape" but if it is missing, add it based on the output shape
152 op.attrs["new_shape"] = outputs[0].shape
153
Louis Verhaardaee5d752020-09-30 09:01:52 +0200154 if op_type == Op.Cast:
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200155 # Cast op should have "in/out_data_type" attribs add if missing
156 if "in_data_type" not in op.attrs:
157 op.attrs["in_data_type"] = inputs[0].dtype
158 if "out_data_type" not in op.attrs:
159 op.attrs["out_data_type"] = outputs[0].dtype
160
Tim Hall79d07d22020-04-27 18:20:16 +0100161 if "stride_w" in op.attrs:
162 op.attrs["strides"] = (1, op.attrs["stride_h"], op.attrs["stride_w"], 1)
163 if "filter_width" in op.attrs:
164 op.attrs["ksize"] = (1, op.attrs["filter_height"], op.attrs["filter_width"], 1)
165 if "dilation_w_factor" in op.attrs:
166 op.attrs["dilation"] = (1, op.attrs["dilation_h_factor"], op.attrs["dilation_w_factor"], 1)
167 if "depth_multiplier" in op.attrs:
168 op.attrs["channel_multiplier"] = op.attrs["depth_multiplier"]
169
Fredrik Svedbergbdf09f92020-11-18 11:30:21 +0100170 if op_type == Op.DepthwiseConv2DBias and op.attrs["depth_multiplier"] == 0:
171 # The depth multiplier is implicit and is calculated as weight channels / ifm channels
172 # Note however that the weights have been reshaped above.
173 # The original value is cached above in channel_multiplier
174 op.attrs["depth_multiplier"] = op.weights.shape[2] // op.ifm.shape[-1]
175
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100176 faf = op.attrs.pop("fused_activation_function", None)
177 if faf is not None:
178 op.activation = create_activation_function(faf)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200179 if custom_code is not None:
180 op.attrs["custom_code"] = custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100181
Diego Russod0eee262020-04-23 18:14:37 +0100182 @staticmethod
183 def len1_array_to_scalar(arr):
184 # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in
185 # the input buffer. This is represented in Vela by using None.
186 # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays
187 # are converted to scalars
188 if isinstance(arr, int) and arr == 0:
189 return None
190 if len(arr) == 1:
191 return arr[0]
192 return arr
193
Tim Hall79d07d22020-04-27 18:20:16 +0100194
195class TFLiteGraph:
Michael McGeagh6f725262020-12-03 15:21:36 +0000196 def __init__(self, filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
Tim Hall79d07d22020-04-27 18:20:16 +0100197
198 self.op_times = {}
199 if batch_size is None:
200 batch_size = 1
201 self.batch_size = batch_size
202 self.name = os.path.splitext(os.path.basename(filename))[0]
203 self.initialisation_nodes = initialisation_nodes
204
205 with open(filename, "rb") as f:
206 buf = bytearray(f.read())
207
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100208 try:
209 parsing_step = "parsing root"
210 model = Model.GetRootAsModel(buf, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100211
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100212 parsing_step = "parsing buffers length"
213 self.buffers = []
214 for idx in range(model.BuffersLength()):
215 parsing_step = f"parsing buffer {idx}"
216 self.buffers.append(self.parse_buffer(model.Buffers(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100217
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100218 parsing_step = "parsing operator codes length"
219 self.operator_codes = []
220 for idx in range(model.OperatorCodesLength()):
221 parsing_step = f"parsing operator code {idx}"
222 self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100223
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100224 parsing_step = "parsing subgraphs length"
225 self.subgraphs = []
226 for idx in range(model.SubgraphsLength()):
227 parsing_step = f"parsing subgraph {idx}"
228 self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100229
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100230 self.nng = Graph(self.name, self.batch_size)
231 for tflite_sg in self.subgraphs:
232 sg = Subgraph(tflite_sg.name)
233 sg.original_inputs = tflite_sg.inputs # Preserve the original input order
234 sg.output_tensors = tflite_sg.outputs
235 self.nng.subgraphs.append(sg)
Tim Hall79d07d22020-04-27 18:20:16 +0100236
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100237 parsing_step = "parsing metadata length"
238 # Preserve the original metadata
239 for idx in range(model.MetadataLength()):
240 parsing_step = f"parsing metadata {idx}"
241 meta = model.Metadata(idx)
242 parsing_step = f"parsing metadata name of metadata {idx}"
243 name = meta.Name()
244 if name is not None:
245 parsing_step = f"parsing metadata {idx} ({name})"
246 buf_data = self.buffers[meta.Buffer()]
247 self.nng.metadata.append((name, buf_data))
248 except (struct.error, TypeError, RuntimeError) as e:
249 print(f'Error: Invalid tflite file. Got "{e}" while {parsing_step}.')
250 sys.exit(1)
Michael McGeagh22f74e12020-08-07 16:21:03 +0100251
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 Hall42abec12021-02-04 21:31:57 +0000260 if c == 0:
261 c = code.DeprecatedBuiltinCode()
Tim Hallc30f4952020-06-15 20:47:35 +0100262 if c not in builtin_operator_map:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000263 raise InputFileError(
264 self.name, f"The input file contains operator code '{c}' which is currently not supported"
265 )
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200266 op_type, ser, indices = builtin_operator_map[c]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200267 custom_code = None
Tim Hall79d07d22020-04-27 18:20:16 +0100268 if c == BuiltinOperator.CUSTOM:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200269 custom_code = decode_str(code.CustomCode())
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200270 return op_type, ser, custom_code, indices
Tim Hall79d07d22020-04-27 18:20:16 +0100271
272
Michael McGeagh6f725262020-12-03 15:21:36 +0000273def read_tflite(filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
Diego Russoea6111a2020-04-14 18:41:58 +0100274 tflite_graph = TFLiteGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
Tim Hall79d07d22020-04-27 18:20:16 +0100275 nng = tflite_graph.nng
276 nng.refresh_after_modification()
277 return nng