blob: 2925ab43572bc775e062eddd36164a7ad614b707 [file] [log] [blame]
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +02001# Copyright (C) 2021 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# Description:
17# Functions used to read from a TOSA format file.
18import os.path
19import struct
20import sys
21
22import numpy as np
23
24from .nn_graph import Graph
25from .nn_graph import Subgraph
26from .operation import Op
27from .operation import Operation
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +020028from .reader_util import align_tensor_indices_to_nng
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020029from .reader_util import clone_and_reshape_tensor
30from .reader_util import decode_str
31from .reader_util import fixup_tensors
32from .tensor import QuantizationParameters
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020033from .tensor import shape_num_elements
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020034from .tensor import Tensor
35from .tflite_mapping import DataType
Patrik Gustavssondf995102021-08-23 15:33:59 +020036from .tosa.Op import Op as TosaOp
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020037from .tosa.TosaGraph import TosaGraph as TG
38from .tosa_mapping import datatype_map
Patrik Gustavssond15866c2021-08-10 13:56:34 +020039from .tosa_mapping import datatype_map_numpy
Patrik Gustavssondf995102021-08-23 15:33:59 +020040from .tosa_mapping import TOSA_IFM_INDICES
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020041from .tosa_mapping import tosa_operator_map
42from .tosa_mapping import unsupported_tosa_operators
43
44
45class TosaSubgraph:
Patrik Gustavssond15866c2021-08-10 13:56:34 +020046 def __init__(self, graph, block):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020047 self.graph = graph
48 self.name = decode_str(block.Name())
49
50 self.tensors = []
51 for idx in range(block.TensorsLength()):
Patrik Gustavssond15866c2021-08-10 13:56:34 +020052 self.tensors.append(self.parse_tensor(block.Tensors(idx)))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020053
54 for idx in range(block.OperatorsLength()):
55 self.parse_operator(idx, block.Operators(idx))
56
57 # Get the subgraph inputs and outputs
58 self.inputs = self.get_sg_inputs_remove_duplicates(block)
59 self.outputs = self.get_sg_outputs_remove_duplicates(block)
60 fixup_tensors(self.inputs, self.tensors)
61
62 def get_sg_inputs_remove_duplicates(self, block):
63 inputs = []
64 for idx in range(block.InputsLength()):
65 tens_data = block.Inputs(idx)
66 self.add_not_duplicate(tens_data, inputs, "input")
67 return inputs
68
69 def get_sg_outputs_remove_duplicates(self, block):
70 outputs = []
71 for idx in range(block.OutputsLength()):
72 tens_data = block.Outputs(idx)
73 self.add_not_duplicate(tens_data, outputs, "output")
74 return outputs
75
76 def add_not_duplicate(self, tens_data, tensors, warning_str):
77 name = decode_str(tens_data)
78 tensor = self.get_tensor_by_name(name)
79 if tensor not in tensors:
80 tensors.append(tensor)
81 else:
82 print(f"Warning: Subgraph {warning_str} tensor ({tensor}) already seen. Removing the duplicate.")
83
84 def get_tensor_by_name(self, name):
85 for tens in self.tensors:
86 if tens.name == name:
87 return tens
88 return None
89
90 def parse_operator(self, op_index, op_data):
91 op_code = op_data.Op()
92 if op_code in unsupported_tosa_operators:
93 print("Unsupported Operator", op_code)
Patrik Gustavssondf995102021-08-23 15:33:59 +020094 return
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020095
96 op_type, attr_serializer, quant_serializer, indices = tosa_operator_map[op_code]
97 inputs = []
98 outputs = []
99 for idx in range(op_data.InputsLength()):
100 input_tens = self.get_tensor_by_name(decode_str(op_data.Inputs(idx)))
101 inputs.append(input_tens)
102 assert input_tens is not None
103
104 for idx in range(op_data.OutputsLength()):
105 output_tens = self.get_tensor_by_name(decode_str(op_data.Outputs(idx)))
106 outputs.append(output_tens)
107 assert output_tens is not None
108
Patrik Gustavssondf995102021-08-23 15:33:59 +0200109 # Permutation attribute for TRANSPOSE is an input tensor in TOSA
110 # TODO In order to optimise Depthwise spawning from TFLite Support for removing
111 # Transpose of constant data.
112 # Moving permutation to an attribute, to match internal graph representation for now
113 perms = None
114 if op_code == TosaOp.TRANSPOSE:
115 perms = perms = inputs.pop(1)
116 indices = TOSA_IFM_INDICES
117
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200118 name = "unknown_op_name"
119 if len(outputs):
120 name = outputs[0].name
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200121 inputs = align_tensor_indices_to_nng(op_type, indices, inputs)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200122 op = Operation(op_type, name)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200123 op.op_index = op_index
124 op.inputs = inputs
125 op.outputs = outputs
126
127 for out in op.outputs:
128 out.ops = [op]
129
130 # TODO Transpose_conv and conv3d
131 if op.type.is_depthwise_conv2d_op() or op.type.is_conv2d_op() or op.type == Op.FullyConnected:
132 if inputs[1].values is not None:
133 if op.type == Op.FullyConnected:
134 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False)
135 elif op.type.is_conv2d_op():
136 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False)
137 elif op.type.is_depthwise_conv2d_op():
138 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 0, 3), False)
139 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
140 # No Bias tensor
141 inputs.append(None)
142 if inputs[-1] and inputs[-1].values is not None:
143 # Since bias tensor is used for both bias and scale,
144 # a clone with a unique equivalence_id is needed
145 inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True)
146
147 if attr_serializer is not None:
148 op.attrs = attr_serializer.deserialize(op_data)
149
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200150 if "padding" in op.attrs:
151 padding = op.attrs["padding"] # [top, bottom, left, right]
152 op.attrs["explicit_padding"] = (
153 padding[0],
154 padding[2],
155 padding[1],
156 padding[3],
157 ) # [top, left, bottom, right]
158 if "stride" in op.attrs:
159 stride = op.attrs["stride"]
160 if len(stride) == 2:
161 op.attrs["strides"] = (1, stride[0], stride[1], 1)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200162 del op.attrs["stride"]
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200163 else:
164 # TODO CONV3D more to be done....
165 print("Unsupported kernel dimensions: ", len(stride))
166 assert False
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200167 if "dilation" in op.attrs:
168 dilation = op.attrs["dilation"]
169 if len(dilation) == 2:
170 op.attrs["dilation"] = (1, dilation[0], dilation[1], 1)
171 elif len(dilation) == 3:
172 # TODO CONV3D more to be done....
173 op.attrs["dilation"] = (dilation[0], dilation[1], dilation[2], 1)
174 if "kernel" in op.attrs:
175 kernel = op.attrs["kernel"]
176 if len(kernel) == 2:
177 op.attrs["ksize"] = (1, kernel[0], kernel[1], 1)
178 else:
179 # TODO CONV3D more to be done....
180 print("Unsupported kernel dimensions: ", len(kernel))
181 assert False
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200182 if "shift" in op.attrs and op.type == Op.Mul:
183 shift = op.attrs["shift"]
184 if shift != 0:
185 op.type = Op.RescaleMul
186 op.rescale = [1, shift]
Patrik Gustavssondf995102021-08-23 15:33:59 +0200187 if op.type.is_depthwise_conv2d_op():
188 op.attrs["depth_multiplier"] = op.weights.shape[3]
189
190 elif op.type == Op.Transpose:
191 op.attrs["perms"] = perms.values
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200192
193 if quant_serializer is not None:
194 quant_info = quant_serializer.deserialize(op_data)
195
196 # TODO tensor zero points currently set here
197 # zero points part of Rescale operation, handled in tosa_graph_optimizer
198 if "input_zp" in quant_info:
199 self.set_tensor_zp(op.ifm, quant_info["input_zp"])
200 if "weight_zp" in quant_info:
201 self.set_tensor_zp(op.weights, quant_info["weight_zp"])
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200202 if "output_zp" in quant_info:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200203 self.set_tensor_zp(op.ofm, quant_info["output_zp"])
204 if "a_zp" in quant_info:
205 self.set_tensor_zp(op.ifm, quant_info["a_zp"])
206 if "b_zp" in quant_info:
207 self.set_tensor_zp(op.ifm2, quant_info["b_zp"])
208
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200209 def parse_tensor(self, tens_data):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200210 name = decode_str(tens_data.Name())
211 np_shape = tens_data.ShapeAsNumpy()
212 shape = list(np_shape) if type(np_shape) is np.ndarray else []
213 tens_dtype = tens_data.Type()
214 dtype = datatype_map[tens_dtype]
215
216 tens = Tensor(shape, dtype, name)
217
218 # Initialize quantization parameters
219 tens.quantization = QuantizationParameters()
220
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200221 if dtype == DataType.uint8:
222 tens.quantization.quant_min = 0
223 tens.quantization.quant_max = (1 << dtype.bits) - 1
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200224 elif dtype in (DataType.int8, DataType.int16, DataType.int32, DataType.int48):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200225 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
226 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
227
228 tens.values = None
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200229
230 data_length = tens_data.DataLength()
231 if data_length != 0:
232 data_as_numpy = tens_data.DataAsNumpy()
233 if tens_dtype in datatype_map_numpy:
234 np_dtype = datatype_map_numpy[tens_dtype]
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200235
236 # TOSA pads the tensor data
237 shape_elements = shape_num_elements(shape)
238 values = np.array(data_as_numpy.view(np_dtype))
239 values = values[0:shape_elements]
240 tens.values = values.reshape(shape)
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200241 else:
242 # int48 is only expected as an accumulated data/output format, int4 not supported
243 print(f"Error: unsupported/unexpected Tensor type {dtype}, with data")
244 assert False
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200245
246 return tens
247
248 def set_tensor_zp(self, tens, zp):
249 if tens.quantization.zero_point is None:
250 tens.quantization.zero_point = zp
251 elif tens.quantization.zero_point != zp:
252 print(f"Error: Setting tensor zp not possible, tensor already has different zero point")
253 assert False
254
255
256class TosaGraph:
257 def __init__(self, filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
258
259 self.op_times = {}
260 if batch_size is None:
261 batch_size = 1
262 self.batch_size = batch_size
263 self.name = os.path.splitext(os.path.basename(filename))[0]
264 self.initialisation_nodes = initialisation_nodes
265
266 with open(filename, "rb") as f:
267 buf = bytearray(f.read())
268
269 try:
270 parsing_step = "parsing root"
271 tosa_graph = TG.GetRootAsTosaGraph(buf, 0)
272
273 parsing_step = "parsing version"
274 self.check_version(tosa_graph)
275
276 parsing_step = "parsing blocks length"
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200277 self.subgraphs = []
278 for b_idx in range(tosa_graph.BlocksLength()):
279 parsing_step = f"parsing block {b_idx}"
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200280 self.subgraphs.append(TosaSubgraph(self, tosa_graph.Blocks(b_idx)))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200281
282 self.nng = Graph(self.name, self.batch_size)
283 for tosa_sg in self.subgraphs:
284 sg = Subgraph(tosa_sg.name)
285 sg.original_inputs = tosa_sg.inputs # Preserve the original input order
286 sg.output_tensors = tosa_sg.outputs
287 self.nng.subgraphs.append(sg)
288
289 except (struct.error, TypeError, RuntimeError) as e:
290 print(f'Error: Invalid .tosa file. Got "{e}" while {parsing_step}.')
291 sys.exit(1)
292
293 def check_version(self, tosa_graph):
294 version = tosa_graph.Version()
295 version_str = f"{version._major()}.{version._minor()}.{version._patch()}"
296 if version_str != "0.22.0":
297 print(f"Unsupported TOSA version: {version_str}")
298 assert False
299
300
301def read_tosa(filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
302 tosa_graph = TosaGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
303 nng = tosa_graph.nng
304 nng.refresh_after_modification()
305 return nng