blob: 9e2021544f7cb9e66d6591d97da4fd01168eb1aa [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 Verhaarde8a5a782020-11-02 18:04:27 +010026from .operation import create_activation_function
Louis Verhaardaee5d752020-09-30 09:01:52 +020027from .operation import Op
Diego Russoea6111a2020-04-14 18:41:58 +010028from .operation import Operation
Diego Russoe8a10452020-04-21 17:39:10 +010029from .tensor import QuantizationParameters
30from .tensor import Tensor
31from .tflite.BuiltinOperator import BuiltinOperator
32from .tflite.Model import Model
33from .tflite_mapping import builtin_operator_map
34from .tflite_mapping import DataType
35from .tflite_mapping import datatype_map
36from .tflite_mapping import datatype_map_numpy
Tim Hall79d07d22020-04-27 18:20:16 +010037
38
39def decode_str(s):
40 if s is None:
41 return ""
42 return s.decode("utf-8")
43
44
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +010045def clone_and_reshape_tensor(src_tens, reorder, set_unique):
46 tens = src_tens.clone("_reshape", set_unique)
Louis Verhaard3c07c972020-05-07 08:12:58 +020047 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())
Dwight Lidmane05de452020-11-05 15:56:08 +0100109 tens_dtype = tens_data.Type()
110 dtype = datatype_map[tens_dtype]
Tim Hall79d07d22020-04-27 18:20:16 +0100111 tens = Tensor(shape, dtype, name)
Tim Hall79d07d22020-04-27 18:20:16 +0100112 quant = tens_data.Quantization()
113
Tim Hall79d07d22020-04-27 18:20:16 +0100114 tens.quantization = QuantizationParameters()
Tim Halle4e58e12020-05-08 09:50:21 +0100115 if quant is not None:
Diego Russod0eee262020-04-23 18:14:37 +0100116 tens.quantization.min = self.len1_array_to_scalar(quant.MinAsNumpy())
117 tens.quantization.max = self.len1_array_to_scalar(quant.MaxAsNumpy())
118 tens.quantization.scale_f32 = self.len1_array_to_scalar(quant.ScaleAsNumpy())
119 tens.quantization.zero_point = self.len1_array_to_scalar(quant.ZeroPointAsNumpy())
Tim Hall79d07d22020-04-27 18:20:16 +0100120
121 if dtype == DataType.uint8:
122 tens.quantization.quant_min = 0
123 tens.quantization.quant_max = (1 << dtype.bits) - 1
124 elif dtype in set((DataType.int8, DataType.int16, DataType.int32, DataType.int64)):
125 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
126 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
Tim Hall79d07d22020-04-27 18:20:16 +0100127
128 if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None:
129 tens.quantization = None
130
131 tens.values = None
132 buf = self.graph.buffers[tens_data.Buffer()]
Dwight Lidmane05de452020-11-05 15:56:08 +0100133 if buf is not None and dtype != DataType.string:
134 tens.values = np.array(buf.view(datatype_map_numpy[tens_dtype]).reshape(shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100135 if tens.quantization is not None:
136 tens.quant_values = tens.values
137 tens.values = tens.quantization.dequantize(tens.quant_values)
138 return tens
139
Tim Hallc8310b12020-06-17 14:53:11 +0100140 def parse_operator(self, op_index, op_data):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200141 op_type, opt_serializer, custom_code = self.graph.operator_codes[op_data.OpcodeIndex()]
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200142 inputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.InputsAsNumpy()]
143 outputs = [self.tensors[idx] if idx != -1 else None for idx in op_data.OutputsAsNumpy()]
Tim Hall79d07d22020-04-27 18:20:16 +0100144 name = "unknown_op_name"
145 if len(outputs):
146 name = outputs[0].name
147 op = Operation(op_type, name)
Tim Hallc8310b12020-06-17 14:53:11 +0100148 op.op_index = op_index
Tim Hall79d07d22020-04-27 18:20:16 +0100149 op.inputs = inputs
150 op.outputs = outputs
151 for out in op.outputs:
152 out.ops = [op]
153
Louis Verhaardaee5d752020-09-30 09:01:52 +0200154 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 +0200155 if inputs[1].values is not None:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200156 if op.type == Op.FullyConnected:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100157 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200158 else:
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100159 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200160 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200161 # No Bias tensor
162 inputs.append(None)
Patrik Gustavssone2dbed22020-10-06 10:14:36 +0200163 if inputs[-1] and inputs[-1].values is not None:
Patrik Gustavsson34359582020-11-03 10:24:08 +0100164 # Since bias tensor is used for both bias and scale,
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100165 # a clone with a unique equivalence_id is needed
166 inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True)
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
Fredrik Svedbergbdf09f92020-11-18 11:30:21 +0100191 if op_type == Op.DepthwiseConv2DBias and op.attrs["depth_multiplier"] == 0:
192 # The depth multiplier is implicit and is calculated as weight channels / ifm channels
193 # Note however that the weights have been reshaped above.
194 # The original value is cached above in channel_multiplier
195 op.attrs["depth_multiplier"] = op.weights.shape[2] // op.ifm.shape[-1]
196
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100197 faf = op.attrs.pop("fused_activation_function", None)
198 if faf is not None:
199 op.activation = create_activation_function(faf)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200200 if custom_code is not None:
201 op.attrs["custom_code"] = custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100202
Diego Russod0eee262020-04-23 18:14:37 +0100203 @staticmethod
204 def len1_array_to_scalar(arr):
205 # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in
206 # the input buffer. This is represented in Vela by using None.
207 # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays
208 # are converted to scalars
209 if isinstance(arr, int) and arr == 0:
210 return None
211 if len(arr) == 1:
212 return arr[0]
213 return arr
214
Tim Hall79d07d22020-04-27 18:20:16 +0100215
216class TFLiteGraph:
217 def __init__(
Diego Russoea6111a2020-04-14 18:41:58 +0100218 self, filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[],
Tim Hall79d07d22020-04-27 18:20:16 +0100219 ):
220
221 self.op_times = {}
222 if batch_size is None:
223 batch_size = 1
224 self.batch_size = batch_size
225 self.name = os.path.splitext(os.path.basename(filename))[0]
226 self.initialisation_nodes = initialisation_nodes
227
228 with open(filename, "rb") as f:
229 buf = bytearray(f.read())
230
231 model = Model.GetRootAsModel(buf, 0)
232
233 self.buffers = []
234 for idx in range(model.BuffersLength()):
235 self.buffers.append(self.parse_buffer(model.Buffers(idx)))
236
237 self.operator_codes = []
238 for idx in range(model.OperatorCodesLength()):
239 self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx)))
240
241 self.subgraphs = []
242 for idx in range(model.SubgraphsLength()):
243 self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx)))
244
245 self.nng = Graph(self.name, self.batch_size)
246 for tflite_sg in self.subgraphs:
247 sg = Subgraph(tflite_sg.name)
248 sg.original_inputs = tflite_sg.inputs # Preserve the original input order
249 sg.output_tensors = tflite_sg.outputs
250 self.nng.subgraphs.append(sg)
251
Michael McGeagh22f74e12020-08-07 16:21:03 +0100252 # Preserve the original metadata
253 for idx in range(model.MetadataLength()):
254 meta = model.Metadata(idx)
255 name = meta.Name()
256 if name is not None:
257 buf_data = self.buffers[meta.Buffer()]
258 self.nng.metadata.append((name, buf_data))
259
Tim Hall79d07d22020-04-27 18:20:16 +0100260 def parse_buffer(self, buf_data):
261 if buf_data.DataLength() == 0:
262 return None
263 data = buf_data.DataAsNumpy()
264 return data
265
266 def parse_operator_code(self, code):
267 c = code.BuiltinCode()
Tim Hallc30f4952020-06-15 20:47:35 +0100268 if c not in builtin_operator_map:
Louis Verhaard678645b2020-06-15 15:22:47 +0200269 msg = "The input file contains operator code {} which is currently not supported".format(c)
270 raise InputFileError(self.name, msg)
Tim Hall79d07d22020-04-27 18:20:16 +0100271 op_type, ser = builtin_operator_map[c]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200272 custom_code = None
Tim Hall79d07d22020-04-27 18:20:16 +0100273 if c == BuiltinOperator.CUSTOM:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200274 custom_code = decode_str(code.CustomCode())
275 return op_type, ser, custom_code
Tim Hall79d07d22020-04-27 18:20:16 +0100276
277
278def read_tflite(
Diego Russoea6111a2020-04-14 18:41:58 +0100279 filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[],
Tim Hall79d07d22020-04-27 18:20:16 +0100280):
Diego Russoea6111a2020-04-14 18:41:58 +0100281 tflite_graph = TFLiteGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
Tim Hall79d07d22020-04-27 18:20:16 +0100282 nng = tflite_graph.nng
283 nng.refresh_after_modification()
284 return nng