blob: 4456d5a0da1a25057a06b889c477942e173eea70 [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.
16
17
18# Description:
19# Functions used to read from a TensorFlow Lite format file.
20
Diego Russoea6111a2020-04-14 18:41:58 +010021import os.path
Tim Hall79d07d22020-04-27 18:20:16 +010022
23import numpy as np
Tim Hall79d07d22020-04-27 18:20:16 +010024
Diego Russoea6111a2020-04-14 18:41:58 +010025from .tflite.Model import Model
26from .tflite.BuiltinOperator import BuiltinOperator
27from .nn_graph import Graph, Subgraph
28from .operation import Operation
29from .tensor import Tensor, QuantizationParameters
Tim Hall79d07d22020-04-27 18:20:16 +010030from .tflite_mapping import builtin_operator_map, datatype_map, datatype_map_numpy, DataType
31
32
33def decode_str(s):
34 if s is None:
35 return ""
36 return s.decode("utf-8")
37
38
39def reshape_tensor_add_const_op(tens, reorder):
40 if not tens.reshaped:
41 original_shape = tens.shape
42 tens.name = tens.name + "_reshape"
43 tens.shape = [original_shape[idx] for idx in reorder]
44 tens.bandwidth_shape = tens.shape
45 tens.storage_shape = tens.shape
46
47 if tens.values is not None:
48 tens.values = tens.values.transpose(reorder)
49
50 if tens.quant_values is not None:
51 tens.quant_values = tens.quant_values.transpose(reorder)
52
53 op = Operation("Const", tens.name)
54 op.outputs = [tens]
55 tens.ops = [op]
56 tens.reshaped = True
57
58
59class TFLiteSubgraph:
60 def __init__(self, graph, subgraph):
61 self.graph = graph
62 self.name = decode_str(subgraph.Name())
63
64 self.tensors = []
65 for idx in range(subgraph.TensorsLength()):
66 self.tensors.append(self.parse_tensor(subgraph.Tensors(idx)))
67
68 for idx in range(subgraph.OperatorsLength()):
69 self.parse_operator(subgraph.Operators(idx))
70
71 self.outputs = [self.tensors[idx] for idx in subgraph.OutputsAsNumpy()]
72 self.inputs = [self.tensors[idx] for idx in subgraph.InputsAsNumpy()]
73
74 # Fix up tensors without operations. Generate either Placeholder or Constant ops
75 for tens in self.inputs:
76 assert not tens.ops
77 op = Operation("Placeholder", tens.name)
78 op.outputs = [tens]
79 tens.ops = [op]
80
81 for tens in self.tensors:
82 if not tens.ops:
83 op = Operation("Const", tens.name)
84 op.outputs = [tens]
85 tens.ops = [op]
86
87 def parse_tensor(self, tens_data):
88 np_shape = tens_data.ShapeAsNumpy()
89 shape = list(np_shape) if type(np_shape) is np.ndarray else []
90 name = decode_str(tens_data.Name())
91 dtype = datatype_map[tens_data.Type()]
92
93 tens = Tensor(shape, dtype, name)
94
95 quant = tens_data.Quantization()
96
97 def len1_array_to_scalar(arr):
98 # The following flatbuffer quantisation fields all return a scalar value of 0 if they are not definied in
99 # the input buffer. This is represented in Vela by using None.
100 # Otherwise, the fields returned are a single or multi-element array. In which case, single element arrays
101 # are converted to scalars
102 if isinstance(arr, int) and arr == 0:
103 return None
104 if len(arr) == 1:
105 return arr[0]
106 return arr
107
108 tens.quantization = QuantizationParameters()
109 tens.quantization.min = len1_array_to_scalar(quant.MinAsNumpy())
110 tens.quantization.max = len1_array_to_scalar(quant.MaxAsNumpy())
111 tens.quantization.scale_f32 = len1_array_to_scalar(quant.ScaleAsNumpy())
112 tens.quantization.zero_point = len1_array_to_scalar(quant.ZeroPointAsNumpy())
113
114 if dtype == DataType.uint8:
115 tens.quantization.quant_min = 0
116 tens.quantization.quant_max = (1 << dtype.bits) - 1
117 elif dtype in set((DataType.int8, DataType.int16, DataType.int32, DataType.int64)):
118 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
119 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
120 else:
121 raise Exception("DataType '" + str(dtype) + "' is not supported for quantization.")
122
123 if tens.quantization.scale_f32 is None and tens.quantization.zero_point is None:
124 tens.quantization = None
125
126 tens.values = None
127 buf = self.graph.buffers[tens_data.Buffer()]
128 if buf is not None:
129 tens.values = np.array(buf.view(datatype_map_numpy[tens_data.Type()]).reshape(shape))
130 if tens.quantization is not None:
131 tens.quant_values = tens.values
132 tens.values = tens.quantization.dequantize(tens.quant_values)
133 return tens
134
135 def parse_operator(self, op_data):
136 op_type, opt_serializer = self.graph.operator_codes[op_data.OpcodeIndex()]
137 inputs = [self.tensors[idx] for idx in op_data.InputsAsNumpy()]
138 outputs = [self.tensors[idx] for idx in op_data.OutputsAsNumpy()]
139 name = "unknown_op_name"
140 if len(outputs):
141 name = outputs[0].name
142 op = Operation(op_type, name)
143 op.inputs = inputs
144 op.outputs = outputs
145 for out in op.outputs:
146 out.ops = [op]
147
148 activation_function_to_split_out = None
149
150 if op_type.startswith("DepthwiseConv2d") or op_type.startswith("Conv2D"):
151 reshape_tensor_add_const_op(inputs[1], (1, 2, 3, 0))
152
153 if op_type.startswith("FullyConnected"):
154 reshape_tensor_add_const_op(inputs[1], (1, 0))
155
156 if opt_serializer is not None:
157 op.attrs = opt_serializer.deserialize(op_data.BuiltinOptions(), op_data.CustomOptionsAsNumpy())
158
159 if "stride_w" in op.attrs:
160 op.attrs["strides"] = (1, op.attrs["stride_h"], op.attrs["stride_w"], 1)
161 if "filter_width" in op.attrs:
162 op.attrs["ksize"] = (1, op.attrs["filter_height"], op.attrs["filter_width"], 1)
163 if "dilation_w_factor" in op.attrs:
164 op.attrs["dilation"] = (1, op.attrs["dilation_h_factor"], op.attrs["dilation_w_factor"], 1)
165 if "depth_multiplier" in op.attrs:
166 op.attrs["channel_multiplier"] = op.attrs["depth_multiplier"]
167
168 if "fused_activation_function" in op.attrs:
169 if op_type in set(("ConcatTFLite",)):
170 act = op.attrs["fused_activation_function"]
171 del op.attrs["fused_activation_function"]
172 if act is not None:
173 activation_function_to_split_out = act
174
175 if activation_function_to_split_out is not None:
176 act_op = Operation(activation_function_to_split_out, name + activation_function_to_split_out)
177 out_tens = op.outputs[0]
178 intermediate_tens = out_tens.clone("_act_intermediate")
179 out_tens.ops = [act_op]
180 act_op.outputs = [out_tens]
181 intermediate_tens.ops = [op]
182 op.outputs[0] = intermediate_tens
183 act_op.inputs = [intermediate_tens]
184
185
186class TFLiteGraph:
187 def __init__(
Diego Russoea6111a2020-04-14 18:41:58 +0100188 self, filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[],
Tim Hall79d07d22020-04-27 18:20:16 +0100189 ):
190
191 self.op_times = {}
192 if batch_size is None:
193 batch_size = 1
194 self.batch_size = batch_size
195 self.name = os.path.splitext(os.path.basename(filename))[0]
196 self.initialisation_nodes = initialisation_nodes
197
198 with open(filename, "rb") as f:
199 buf = bytearray(f.read())
200
201 model = Model.GetRootAsModel(buf, 0)
202
203 self.buffers = []
204 for idx in range(model.BuffersLength()):
205 self.buffers.append(self.parse_buffer(model.Buffers(idx)))
206
207 self.operator_codes = []
208 for idx in range(model.OperatorCodesLength()):
209 self.operator_codes.append(self.parse_operator_code(model.OperatorCodes(idx)))
210
211 self.subgraphs = []
212 for idx in range(model.SubgraphsLength()):
213 self.subgraphs.append(TFLiteSubgraph(self, model.Subgraphs(idx)))
214
215 self.nng = Graph(self.name, self.batch_size)
216 for tflite_sg in self.subgraphs:
217 sg = Subgraph(tflite_sg.name)
218 sg.original_inputs = tflite_sg.inputs # Preserve the original input order
219 sg.output_tensors = tflite_sg.outputs
220 self.nng.subgraphs.append(sg)
221
222 def parse_buffer(self, buf_data):
223 if buf_data.DataLength() == 0:
224 return None
225 data = buf_data.DataAsNumpy()
226 return data
227
228 def parse_operator_code(self, code):
229 c = code.BuiltinCode()
230 op_type, ser = builtin_operator_map[c]
231 if c == BuiltinOperator.CUSTOM:
232 op_type += decode_str(code.CustomCode())
233 return op_type, ser
234
235
236def read_tflite(
Diego Russoea6111a2020-04-14 18:41:58 +0100237 filename, batch_size=1, feed_dict={}, output_node_names=[], initialisation_nodes=[],
Tim Hall79d07d22020-04-27 18:20:16 +0100238):
Diego Russoea6111a2020-04-14 18:41:58 +0100239 tflite_graph = TFLiteGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
Tim Hall79d07d22020-04-27 18:20:16 +0100240 nng = tflite_graph.nng
241 nng.refresh_after_modification()
242 return nng