blob: 80f36457b367da77843c7cd2ec4a247c8ad1390f [file] [log] [blame]
Rickard Bolinbc6ee582022-11-04 08:24:29 +00001# SPDX-FileCopyrightText: Copyright 2020-2022 Arm Limited and/or its affiliates <open-source-office@arm.com>
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.
Rickard Bolinbc6ee582022-11-04 08:24:29 +000016#
Tim Hall79d07d22020-04-27 18:20:16 +010017# Description:
18# Functions used to read from a TensorFlow Lite format file.
Diego Russoea6111a2020-04-14 18:41:58 +010019import os.path
Henrik G Olssonea9b23c2021-03-23 17:34:49 +010020import struct
21import sys
Tim Hall79d07d22020-04-27 18:20:16 +010022
23import numpy as np
Tim Hall79d07d22020-04-27 18:20:16 +010024
Louis Verhaard678645b2020-06-15 15:22:47 +020025from .errors import InputFileError
Diego Russoe8a10452020-04-21 17:39:10 +010026from .nn_graph import Graph
27from .nn_graph import Subgraph
Louis Verhaarde8a5a782020-11-02 18:04:27 +010028from .operation import create_activation_function
Louis Verhaardaee5d752020-09-30 09:01:52 +020029from .operation import Op
Diego Russoea6111a2020-04-14 18:41:58 +010030from .operation import Operation
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +020031from .reader_util import align_tensor_indices_to_nng
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020032from .reader_util import clone_and_reshape_tensor
33from .reader_util import decode_str
34from .reader_util import fixup_tensors
Diego Russoe8a10452020-04-21 17:39:10 +010035from .tensor import QuantizationParameters
36from .tensor import Tensor
37from .tflite.BuiltinOperator import BuiltinOperator
38from .tflite.Model import Model
39from .tflite_mapping import builtin_operator_map
40from .tflite_mapping import DataType
41from .tflite_mapping import datatype_map
42from .tflite_mapping import datatype_map_numpy
Tim Hall79d07d22020-04-27 18:20:16 +010043
44
Tim Hall79d07d22020-04-27 18:20:16 +010045class TFLiteSubgraph:
46 def __init__(self, graph, subgraph):
47 self.graph = graph
48 self.name = decode_str(subgraph.Name())
49
50 self.tensors = []
51 for idx in range(subgraph.TensorsLength()):
52 self.tensors.append(self.parse_tensor(subgraph.Tensors(idx)))
53
54 for idx in range(subgraph.OperatorsLength()):
Tim Hallc8310b12020-06-17 14:53:11 +010055 self.parse_operator(idx, subgraph.Operators(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010056
Tim Hallc8310b12020-06-17 14:53:11 +010057 self.outputs = self.get_tensors_from_indices_remove_duplicates(subgraph.OutputsAsNumpy(), "output")
58 self.inputs = self.get_tensors_from_indices_remove_duplicates(subgraph.InputsAsNumpy(), "input")
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020059 fixup_tensors(self.inputs, self.tensors)
Tim Hall79d07d22020-04-27 18:20:16 +010060
Tim Hallc8310b12020-06-17 14:53:11 +010061 def get_tensors_from_indices_remove_duplicates(self, indices, warning_str):
62 tensors = []
63 for idx in indices:
64 tensor = self.tensors[idx]
65 if tensor not in tensors:
66 tensors.append(tensor)
67 else:
68 print(
69 "Warning: Subgraph {0} tensor ({1}) with idx = {2} already seen. Removing the duplicate.".format(
70 warning_str, tensor, idx
71 )
72 )
73
74 return tensors
75
Tim Hall79d07d22020-04-27 18:20:16 +010076 def parse_tensor(self, tens_data):
77 np_shape = tens_data.ShapeAsNumpy()
78 shape = list(np_shape) if type(np_shape) is np.ndarray else []
79 name = decode_str(tens_data.Name())
Dwight Lidmane05de452020-11-05 15:56:08 +010080 tens_dtype = tens_data.Type()
81 dtype = datatype_map[tens_dtype]
Tim Hall79d07d22020-04-27 18:20:16 +010082 tens = Tensor(shape, dtype, name)
Tim Hall79d07d22020-04-27 18:20:16 +010083 quant = tens_data.Quantization()
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +010084 tens.is_variable = tens_data.IsVariable()
Tim Hall79d07d22020-04-27 18:20:16 +010085
Tim Hall79d07d22020-04-27 18:20:16 +010086 tens.quantization = QuantizationParameters()
Tim Halle4e58e12020-05-08 09:50:21 +010087 if quant is not None:
Diego Russod0eee262020-04-23 18:14:37 +010088 tens.quantization.min = self.len1_array_to_scalar(quant.MinAsNumpy())
89 tens.quantization.max = self.len1_array_to_scalar(quant.MaxAsNumpy())
90 tens.quantization.scale_f32 = self.len1_array_to_scalar(quant.ScaleAsNumpy())
91 tens.quantization.zero_point = self.len1_array_to_scalar(quant.ZeroPointAsNumpy())
Fredrik Svedbergcc8569f2021-11-01 14:25:29 +010092 tens.quantization.quant_dim = quant.QuantizedDimension()
Tim Hall79d07d22020-04-27 18:20:16 +010093
94 if dtype == DataType.uint8:
95 tens.quantization.quant_min = 0
96 tens.quantization.quant_max = (1 << dtype.bits) - 1
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000097 elif dtype in (DataType.int8, DataType.int16, DataType.int32, DataType.int64):
Tim Hall79d07d22020-04-27 18:20:16 +010098 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
99 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
Tim Hall79d07d22020-04-27 18:20:16 +0100100
101 if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None:
102 tens.quantization = None
103
104 tens.values = None
105 buf = self.graph.buffers[tens_data.Buffer()]
Louis Verhaardf4e12be2020-12-18 14:23:06 +0100106 if buf is not None:
107 np_dtype = datatype_map_numpy[tens_dtype]
108 if dtype == DataType.string:
109 tens.values = np.array(buf.view(np_dtype))
110 else:
111 tens.values = np.array(buf.view(np_dtype).reshape(shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100112 return tens
113
Tim Hallc8310b12020-06-17 14:53:11 +0100114 def parse_operator(self, op_index, op_data):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200115 op_type, opt_serializer, custom_code, indices = self.graph.operator_codes[op_data.OpcodeIndex()]
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200116 inputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.InputsAsNumpy()]
117 outputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.OutputsAsNumpy()]
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100118 intermediates = []
119 if op_data.IntermediatesLength():
120 intermediates = [self.tensors[idx] if idx != -1 else None for idx in op_data.IntermediatesAsNumpy()]
121
Tim Hall79d07d22020-04-27 18:20:16 +0100122 name = "unknown_op_name"
123 if len(outputs):
124 name = outputs[0].name
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200125 inputs = align_tensor_indices_to_nng(op_type, indices, inputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100126 op = Operation(op_type, name)
Tim Hallc8310b12020-06-17 14:53:11 +0100127 op.op_index = op_index
Tim Hall79d07d22020-04-27 18:20:16 +0100128 op.inputs = inputs
129 op.outputs = outputs
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100130 op.intermediates = intermediates
Tim Hall79d07d22020-04-27 18:20:16 +0100131 for out in op.outputs:
132 out.ops = [op]
133
Louis Verhaardaee5d752020-09-30 09:01:52 +0200134 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 +0200135 if inputs[1].values is not None:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200136 if op.type == Op.FullyConnected:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100137 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200138 else:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100139 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200140 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200141 # No Bias tensor
142 inputs.append(None)
Patrik Gustavssone2dbed22020-10-06 10:14:36 +0200143 if inputs[-1] and inputs[-1].values is not None:
Patrik Gustavsson34359582020-11-03 10:24:08 +0100144 # Since bias tensor is used for both bias and scale,
Johan Alfvén53605be2022-10-26 12:52:17 +0200145 # a clone with a unique equivalence_id is needed.
146 inputs[-1] = clone_and_reshape_tensor(inputs[-1], None, True)
Tim Hall79d07d22020-04-27 18:20:16 +0100147
148 if opt_serializer is not None:
Tim Hallc8310b12020-06-17 14:53:11 +0100149 op.attrs = opt_serializer.deserialize(op_data)
Tim Hall79d07d22020-04-27 18:20:16 +0100150
Johan Alfvén673683b2022-09-05 09:39:47 +0200151 if op_type == Op.While:
152 # Attach the actual nng subgraphs to the op
153 cond_subgraph_index = op.attrs["cond_subgraph_index"]
154 body_subgraph_index = op.attrs["body_subgraph_index"]
155 op.attrs["subgraph"] = (
156 self.graph.nng.subgraphs[cond_subgraph_index],
157 self.graph.nng.subgraphs[body_subgraph_index],
158 )
159
Louis Verhaardaee5d752020-09-30 09:01:52 +0200160 if op_type == Op.Reshape and "new_shape" not in op.attrs:
Michael McGeagh7b245fd2020-07-31 12:50:57 +0100161 # Reshape should have an attrib "new_shape" but if it is missing, add it based on the output shape
162 op.attrs["new_shape"] = outputs[0].shape
163
Louis Verhaardaee5d752020-09-30 09:01:52 +0200164 if op_type == Op.Cast:
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200165 # Cast op should have "in/out_data_type" attribs add if missing
166 if "in_data_type" not in op.attrs:
167 op.attrs["in_data_type"] = inputs[0].dtype
168 if "out_data_type" not in op.attrs:
169 op.attrs["out_data_type"] = outputs[0].dtype
170
Tim Hall79d07d22020-04-27 18:20:16 +0100171 if "stride_w" in op.attrs:
172 op.attrs["strides"] = (1, op.attrs["stride_h"], op.attrs["stride_w"], 1)
173 if "filter_width" in op.attrs:
174 op.attrs["ksize"] = (1, op.attrs["filter_height"], op.attrs["filter_width"], 1)
175 if "dilation_w_factor" in op.attrs:
176 op.attrs["dilation"] = (1, op.attrs["dilation_h_factor"], op.attrs["dilation_w_factor"], 1)
177 if "depth_multiplier" in op.attrs:
178 op.attrs["channel_multiplier"] = op.attrs["depth_multiplier"]
179
Fredrik Svedbergbdf09f92020-11-18 11:30:21 +0100180 if op_type == Op.DepthwiseConv2DBias and op.attrs["depth_multiplier"] == 0:
181 # The depth multiplier is implicit and is calculated as weight channels / ifm channels
182 # Note however that the weights have been reshaped above.
183 # The original value is cached above in channel_multiplier
184 op.attrs["depth_multiplier"] = op.weights.shape[2] // op.ifm.shape[-1]
185
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100186 faf = op.attrs.pop("fused_activation_function", None)
187 if faf is not None:
188 op.activation = create_activation_function(faf)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200189 if custom_code is not None:
190 op.attrs["custom_code"] = custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100191
Diego Russod0eee262020-04-23 18:14:37 +0100192 @staticmethod
193 def len1_array_to_scalar(arr):
194 # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in
195 # the input buffer. This is represented in Vela by using None.
196 # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays
197 # are converted to scalars
198 if isinstance(arr, int) and arr == 0:
199 return None
200 if len(arr) == 1:
201 return arr[0]
202 return arr
203
Tim Hall79d07d22020-04-27 18:20:16 +0100204
205class TFLiteGraph:
Michael McGeagh6f725262020-12-03 15:21:36 +0000206 def __init__(self, filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
Tim Hall79d07d22020-04-27 18:20:16 +0100207
208 self.op_times = {}
209 if batch_size is None:
210 batch_size = 1
211 self.batch_size = batch_size
212 self.name = os.path.splitext(os.path.basename(filename))[0]
213 self.initialisation_nodes = initialisation_nodes
214
215 with open(filename, "rb") as f:
216 buf = bytearray(f.read())
217
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100218 try:
219 parsing_step = "parsing root"
220 model = Model.GetRootAsModel(buf, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100221
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100222 parsing_step = "parsing buffers length"
223 self.buffers = []
224 for idx in range(model.BuffersLength()):
225 parsing_step = f"parsing buffer {idx}"
226 self.buffers.append(self.parse_buffer(model.Buffers(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100227
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100228 parsing_step = "parsing operator codes length"
229 self.operator_codes = []
230 for idx in range(model.OperatorCodesLength()):
231 parsing_step = f"parsing operator code {idx}"
232 self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100233
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100234 parsing_step = "parsing subgraphs length"
235 self.subgraphs = []
Johan Alfvén673683b2022-09-05 09:39:47 +0200236
237 # Pre-allocate nng subgraphs - needed when parsing an operator and the operator
238 # has subgraph attributes.
239 self.nng = Graph(self.name, self.batch_size)
240 for idx in range(model.SubgraphsLength()):
241 sg = Subgraph()
242 self.nng.subgraphs.append(sg)
243
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100244 for idx in range(model.SubgraphsLength()):
245 parsing_step = f"parsing subgraph {idx}"
246 self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx)))
Tim Hall79d07d22020-04-27 18:20:16 +0100247
Johan Alfvén673683b2022-09-05 09:39:47 +0200248 for idx, tflite_sg in enumerate(self.subgraphs):
249 sg = self.nng.subgraphs[idx]
250 sg.name = tflite_sg.name
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100251 sg.original_inputs = tflite_sg.inputs # Preserve the original input order
252 sg.output_tensors = tflite_sg.outputs
Tim Hall79d07d22020-04-27 18:20:16 +0100253
Henrik G Olssonea9b23c2021-03-23 17:34:49 +0100254 parsing_step = "parsing metadata length"
255 # Preserve the original metadata
256 for idx in range(model.MetadataLength()):
257 parsing_step = f"parsing metadata {idx}"
258 meta = model.Metadata(idx)
259 parsing_step = f"parsing metadata name of metadata {idx}"
260 name = meta.Name()
261 if name is not None:
262 parsing_step = f"parsing metadata {idx} ({name})"
263 buf_data = self.buffers[meta.Buffer()]
264 self.nng.metadata.append((name, buf_data))
265 except (struct.error, TypeError, RuntimeError) as e:
266 print(f'Error: Invalid tflite file. Got "{e}" while {parsing_step}.')
267 sys.exit(1)
Michael McGeagh22f74e12020-08-07 16:21:03 +0100268
Tim Hall79d07d22020-04-27 18:20:16 +0100269 def parse_buffer(self, buf_data):
270 if buf_data.DataLength() == 0:
271 return None
272 data = buf_data.DataAsNumpy()
273 return data
274
275 def parse_operator_code(self, code):
276 c = code.BuiltinCode()
Tim Hall42abec12021-02-04 21:31:57 +0000277 if c == 0:
278 c = code.DeprecatedBuiltinCode()
Tim Hallc30f4952020-06-15 20:47:35 +0100279 if c not in builtin_operator_map:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000280 raise InputFileError(
281 self.name, f"The input file contains operator code '{c}' which is currently not supported"
282 )
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200283 op_type, ser, indices = builtin_operator_map[c]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200284 custom_code = None
Tim Hall79d07d22020-04-27 18:20:16 +0100285 if c == BuiltinOperator.CUSTOM:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200286 custom_code = decode_str(code.CustomCode())
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200287 return op_type, ser, custom_code, indices
Tim Hall79d07d22020-04-27 18:20:16 +0100288
289
Michael McGeagh6f725262020-12-03 15:21:36 +0000290def read_tflite(filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
Diego Russoea6111a2020-04-14 18:41:58 +0100291 tflite_graph = TFLiteGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
Tim Hall79d07d22020-04-27 18:20:16 +0100292 nng = tflite_graph.nng
293 nng.refresh_after_modification()
294 return nng