blob: 2bec9cf18954eb55b2b418d53cefe7ff4aeab741 [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
Patrik Gustavssonf1580f02021-09-01 12:43:02 +020032from .shape4d import Shape4D
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020033from .tensor import QuantizationParameters
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020034from .tensor import shape_num_elements
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020035from .tensor import Tensor
36from .tflite_mapping import DataType
Patrik Gustavssondf995102021-08-23 15:33:59 +020037from .tosa.Op import Op as TosaOp
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020038from .tosa.TosaGraph import TosaGraph as TG
39from .tosa_mapping import datatype_map
Patrik Gustavssond15866c2021-08-10 13:56:34 +020040from .tosa_mapping import datatype_map_numpy
Patrik Gustavssondf995102021-08-23 15:33:59 +020041from .tosa_mapping import TOSA_IFM_INDICES
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020042from .tosa_mapping import tosa_operator_map
43from .tosa_mapping import unsupported_tosa_operators
44
45
46class TosaSubgraph:
Patrik Gustavssond15866c2021-08-10 13:56:34 +020047 def __init__(self, graph, block):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020048 self.graph = graph
49 self.name = decode_str(block.Name())
50
51 self.tensors = []
52 for idx in range(block.TensorsLength()):
Patrik Gustavssond15866c2021-08-10 13:56:34 +020053 self.tensors.append(self.parse_tensor(block.Tensors(idx)))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020054
55 for idx in range(block.OperatorsLength()):
56 self.parse_operator(idx, block.Operators(idx))
57
58 # Get the subgraph inputs and outputs
59 self.inputs = self.get_sg_inputs_remove_duplicates(block)
60 self.outputs = self.get_sg_outputs_remove_duplicates(block)
61 fixup_tensors(self.inputs, self.tensors)
62
63 def get_sg_inputs_remove_duplicates(self, block):
64 inputs = []
65 for idx in range(block.InputsLength()):
66 tens_data = block.Inputs(idx)
67 self.add_not_duplicate(tens_data, inputs, "input")
68 return inputs
69
70 def get_sg_outputs_remove_duplicates(self, block):
71 outputs = []
72 for idx in range(block.OutputsLength()):
73 tens_data = block.Outputs(idx)
74 self.add_not_duplicate(tens_data, outputs, "output")
75 return outputs
76
77 def add_not_duplicate(self, tens_data, tensors, warning_str):
78 name = decode_str(tens_data)
79 tensor = self.get_tensor_by_name(name)
80 if tensor not in tensors:
81 tensors.append(tensor)
82 else:
83 print(f"Warning: Subgraph {warning_str} tensor ({tensor}) already seen. Removing the duplicate.")
84
85 def get_tensor_by_name(self, name):
86 for tens in self.tensors:
87 if tens.name == name:
88 return tens
89 return None
90
91 def parse_operator(self, op_index, op_data):
92 op_code = op_data.Op()
93 if op_code in unsupported_tosa_operators:
94 print("Unsupported Operator", op_code)
Patrik Gustavssondf995102021-08-23 15:33:59 +020095 return
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020096
97 op_type, attr_serializer, quant_serializer, indices = tosa_operator_map[op_code]
98 inputs = []
99 outputs = []
100 for idx in range(op_data.InputsLength()):
101 input_tens = self.get_tensor_by_name(decode_str(op_data.Inputs(idx)))
102 inputs.append(input_tens)
103 assert input_tens is not None
104
105 for idx in range(op_data.OutputsLength()):
106 output_tens = self.get_tensor_by_name(decode_str(op_data.Outputs(idx)))
107 outputs.append(output_tens)
108 assert output_tens is not None
109
Patrik Gustavssondf995102021-08-23 15:33:59 +0200110 # Permutation attribute for TRANSPOSE is an input tensor in TOSA
111 # TODO In order to optimise Depthwise spawning from TFLite Support for removing
112 # Transpose of constant data.
113 # Moving permutation to an attribute, to match internal graph representation for now
114 perms = None
115 if op_code == TosaOp.TRANSPOSE:
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200116 perms = inputs.pop(1)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200117 indices = TOSA_IFM_INDICES
118
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200119 name = "unknown_op_name"
120 if len(outputs):
121 name = outputs[0].name
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200122 inputs = align_tensor_indices_to_nng(op_type, indices, inputs)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200123 op = Operation(op_type, name)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200124 op.op_index = op_index
125 op.inputs = inputs
126 op.outputs = outputs
127
128 for out in op.outputs:
129 out.ops = [op]
130
131 # TODO Transpose_conv and conv3d
132 if op.type.is_depthwise_conv2d_op() or op.type.is_conv2d_op() or op.type == Op.FullyConnected:
133 if inputs[1].values is not None:
134 if op.type == Op.FullyConnected:
135 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False)
136 elif op.type.is_conv2d_op():
137 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False)
138 elif op.type.is_depthwise_conv2d_op():
139 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 0, 3), False)
140 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
141 # No Bias tensor
142 inputs.append(None)
143 if inputs[-1] and inputs[-1].values is not None:
144 # Since bias tensor is used for both bias and scale,
145 # a clone with a unique equivalence_id is needed
146 inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True)
147
148 if attr_serializer is not None:
149 op.attrs = attr_serializer.deserialize(op_data)
150
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200151 if "padding" in op.attrs:
152 padding = op.attrs["padding"] # [top, bottom, left, right]
153 op.attrs["explicit_padding"] = (
154 padding[0],
155 padding[2],
156 padding[1],
157 padding[3],
158 ) # [top, left, bottom, right]
159 if "stride" in op.attrs:
160 stride = op.attrs["stride"]
161 if len(stride) == 2:
162 op.attrs["strides"] = (1, stride[0], stride[1], 1)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200163 del op.attrs["stride"]
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200164 else:
165 # TODO CONV3D more to be done....
166 print("Unsupported kernel dimensions: ", len(stride))
167 assert False
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200168 if "dilation" in op.attrs:
169 dilation = op.attrs["dilation"]
170 if len(dilation) == 2:
171 op.attrs["dilation"] = (1, dilation[0], dilation[1], 1)
172 elif len(dilation) == 3:
173 # TODO CONV3D more to be done....
174 op.attrs["dilation"] = (dilation[0], dilation[1], dilation[2], 1)
175 if "kernel" in op.attrs:
176 kernel = op.attrs["kernel"]
177 if len(kernel) == 2:
178 op.attrs["ksize"] = (1, kernel[0], kernel[1], 1)
179 else:
180 # TODO CONV3D more to be done....
181 print("Unsupported kernel dimensions: ", len(kernel))
182 assert False
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200183 if "shift" in op.attrs and op.type == Op.Mul:
184 shift = op.attrs["shift"]
185 if shift != 0:
186 op.type = Op.RescaleMul
187 op.rescale = [1, shift]
Patrik Gustavssondf995102021-08-23 15:33:59 +0200188 if op.type.is_depthwise_conv2d_op():
189 op.attrs["depth_multiplier"] = op.weights.shape[3]
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200190 if op.type == Op.SplitSliceRead:
191 op.read_offsets[0] = Shape4D.from_list(list(op.attrs["begin"]), 0)
192 op.read_shapes[0] = op.attrs["size"]
Patrik Gustavssondf995102021-08-23 15:33:59 +0200193
194 elif op.type == Op.Transpose:
195 op.attrs["perms"] = perms.values
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200196
197 if quant_serializer is not None:
198 quant_info = quant_serializer.deserialize(op_data)
199
200 # TODO tensor zero points currently set here
201 # zero points part of Rescale operation, handled in tosa_graph_optimizer
202 if "input_zp" in quant_info:
203 self.set_tensor_zp(op.ifm, quant_info["input_zp"])
204 if "weight_zp" in quant_info:
205 self.set_tensor_zp(op.weights, quant_info["weight_zp"])
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200206 if "output_zp" in quant_info:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200207 self.set_tensor_zp(op.ofm, quant_info["output_zp"])
208 if "a_zp" in quant_info:
209 self.set_tensor_zp(op.ifm, quant_info["a_zp"])
210 if "b_zp" in quant_info:
211 self.set_tensor_zp(op.ifm2, quant_info["b_zp"])
212
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200213 def parse_tensor(self, tens_data):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200214 name = decode_str(tens_data.Name())
215 np_shape = tens_data.ShapeAsNumpy()
216 shape = list(np_shape) if type(np_shape) is np.ndarray else []
217 tens_dtype = tens_data.Type()
218 dtype = datatype_map[tens_dtype]
219
220 tens = Tensor(shape, dtype, name)
221
222 # Initialize quantization parameters
223 tens.quantization = QuantizationParameters()
224
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200225 if dtype == DataType.uint8:
226 tens.quantization.quant_min = 0
227 tens.quantization.quant_max = (1 << dtype.bits) - 1
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200228 elif dtype in (DataType.int8, DataType.int16, DataType.int32, DataType.int48):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200229 tens.quantization.quant_min = -(1 << (dtype.bits - 1))
230 tens.quantization.quant_max = (1 << (dtype.bits - 1)) - 1
231
232 tens.values = None
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200233
234 data_length = tens_data.DataLength()
235 if data_length != 0:
236 data_as_numpy = tens_data.DataAsNumpy()
237 if tens_dtype in datatype_map_numpy:
238 np_dtype = datatype_map_numpy[tens_dtype]
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200239
240 # TOSA pads the tensor data
241 shape_elements = shape_num_elements(shape)
242 values = np.array(data_as_numpy.view(np_dtype))
243 values = values[0:shape_elements]
244 tens.values = values.reshape(shape)
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200245 else:
246 # int48 is only expected as an accumulated data/output format, int4 not supported
247 print(f"Error: unsupported/unexpected Tensor type {dtype}, with data")
248 assert False
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200249
250 return tens
251
252 def set_tensor_zp(self, tens, zp):
253 if tens.quantization.zero_point is None:
254 tens.quantization.zero_point = zp
255 elif tens.quantization.zero_point != zp:
Jonas Ohlsson25e700c2022-03-04 14:58:56 +0100256 print("Error: Setting tensor zp not possible, tensor already has different zero point")
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200257 assert False
258
259
260class TosaGraph:
261 def __init__(self, filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
262
263 self.op_times = {}
264 if batch_size is None:
265 batch_size = 1
266 self.batch_size = batch_size
267 self.name = os.path.splitext(os.path.basename(filename))[0]
268 self.initialisation_nodes = initialisation_nodes
269
270 with open(filename, "rb") as f:
271 buf = bytearray(f.read())
272
273 try:
274 parsing_step = "parsing root"
275 tosa_graph = TG.GetRootAsTosaGraph(buf, 0)
276
277 parsing_step = "parsing version"
278 self.check_version(tosa_graph)
279
280 parsing_step = "parsing blocks length"
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200281 self.subgraphs = []
282 for b_idx in range(tosa_graph.BlocksLength()):
283 parsing_step = f"parsing block {b_idx}"
Patrik Gustavssond15866c2021-08-10 13:56:34 +0200284 self.subgraphs.append(TosaSubgraph(self, tosa_graph.Blocks(b_idx)))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200285
286 self.nng = Graph(self.name, self.batch_size)
287 for tosa_sg in self.subgraphs:
288 sg = Subgraph(tosa_sg.name)
289 sg.original_inputs = tosa_sg.inputs # Preserve the original input order
290 sg.output_tensors = tosa_sg.outputs
291 self.nng.subgraphs.append(sg)
292
293 except (struct.error, TypeError, RuntimeError) as e:
294 print(f'Error: Invalid .tosa file. Got "{e}" while {parsing_step}.')
295 sys.exit(1)
296
297 def check_version(self, tosa_graph):
298 version = tosa_graph.Version()
299 version_str = f"{version._major()}.{version._minor()}.{version._patch()}"
300 if version_str != "0.22.0":
301 print(f"Unsupported TOSA version: {version_str}")
302 assert False
303
304
305def read_tosa(filename, batch_size, feed_dict, output_node_names, initialisation_nodes):
306 tosa_graph = TosaGraph(filename, batch_size, feed_dict, output_node_names, initialisation_nodes)
307 nng = tosa_graph.nng
308 nng.refresh_after_modification()
309 return nng