blob: cd18adb2b757675d0fb71ebb08ea6bddc96951cd [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
Fredrik Svedberg4a434cb2022-09-27 14:13:01 +020026from .operation import ExplicitScaling
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020027from .operation import Op
28from .operation import Operation
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +020029from .reader_util import align_tensor_indices_to_nng
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020030from .reader_util import clone_and_reshape_tensor
31from .reader_util import decode_str
32from .reader_util import fixup_tensors
Patrik Gustavssonf1580f02021-09-01 12:43:02 +020033from .shape4d import Shape4D
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020034from .tensor import QuantizationParameters
Patrik Gustavssonc74682c2021-08-17 14:26:38 +020035from .tensor import shape_num_elements
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020036from .tensor import Tensor
37from .tflite_mapping import DataType
Patrik Gustavssondf995102021-08-23 15:33:59 +020038from .tosa.Op import Op as TosaOp
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020039from .tosa.TosaGraph import TosaGraph as TG
40from .tosa_mapping import datatype_map
Patrik Gustavssond15866c2021-08-10 13:56:34 +020041from .tosa_mapping import datatype_map_numpy
Patrik Gustavssondf995102021-08-23 15:33:59 +020042from .tosa_mapping import TOSA_IFM_INDICES
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020043from .tosa_mapping import tosa_operator_map
44from .tosa_mapping import unsupported_tosa_operators
45
46
47class TosaSubgraph:
Patrik Gustavssond15866c2021-08-10 13:56:34 +020048 def __init__(self, graph, block):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020049 self.graph = graph
50 self.name = decode_str(block.Name())
51
52 self.tensors = []
53 for idx in range(block.TensorsLength()):
Patrik Gustavssond15866c2021-08-10 13:56:34 +020054 self.tensors.append(self.parse_tensor(block.Tensors(idx)))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020055
56 for idx in range(block.OperatorsLength()):
57 self.parse_operator(idx, block.Operators(idx))
58
59 # Get the subgraph inputs and outputs
60 self.inputs = self.get_sg_inputs_remove_duplicates(block)
61 self.outputs = self.get_sg_outputs_remove_duplicates(block)
62 fixup_tensors(self.inputs, self.tensors)
63
64 def get_sg_inputs_remove_duplicates(self, block):
65 inputs = []
66 for idx in range(block.InputsLength()):
67 tens_data = block.Inputs(idx)
68 self.add_not_duplicate(tens_data, inputs, "input")
69 return inputs
70
71 def get_sg_outputs_remove_duplicates(self, block):
72 outputs = []
73 for idx in range(block.OutputsLength()):
74 tens_data = block.Outputs(idx)
75 self.add_not_duplicate(tens_data, outputs, "output")
76 return outputs
77
78 def add_not_duplicate(self, tens_data, tensors, warning_str):
79 name = decode_str(tens_data)
80 tensor = self.get_tensor_by_name(name)
81 if tensor not in tensors:
82 tensors.append(tensor)
83 else:
84 print(f"Warning: Subgraph {warning_str} tensor ({tensor}) already seen. Removing the duplicate.")
85
86 def get_tensor_by_name(self, name):
87 for tens in self.tensors:
88 if tens.name == name:
89 return tens
90 return None
91
92 def parse_operator(self, op_index, op_data):
93 op_code = op_data.Op()
94 if op_code in unsupported_tosa_operators:
95 print("Unsupported Operator", op_code)
Patrik Gustavssondf995102021-08-23 15:33:59 +020096 return
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020097
98 op_type, attr_serializer, quant_serializer, indices = tosa_operator_map[op_code]
99 inputs = []
100 outputs = []
101 for idx in range(op_data.InputsLength()):
102 input_tens = self.get_tensor_by_name(decode_str(op_data.Inputs(idx)))
103 inputs.append(input_tens)
104 assert input_tens is not None
105
106 for idx in range(op_data.OutputsLength()):
107 output_tens = self.get_tensor_by_name(decode_str(op_data.Outputs(idx)))
108 outputs.append(output_tens)
109 assert output_tens is not None
110
Patrik Gustavssondf995102021-08-23 15:33:59 +0200111 # Permutation attribute for TRANSPOSE is an input tensor in TOSA
112 # TODO In order to optimise Depthwise spawning from TFLite Support for removing
113 # Transpose of constant data.
114 # Moving permutation to an attribute, to match internal graph representation for now
115 perms = None
116 if op_code == TosaOp.TRANSPOSE:
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200117 perms = inputs.pop(1)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200118 indices = TOSA_IFM_INDICES
119
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200120 name = "unknown_op_name"
121 if len(outputs):
122 name = outputs[0].name
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200123 inputs = align_tensor_indices_to_nng(op_type, indices, inputs)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200124 op = Operation(op_type, name)
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200125 op.op_index = op_index
126 op.inputs = inputs
127 op.outputs = outputs
128
129 for out in op.outputs:
130 out.ops = [op]
131
132 # TODO Transpose_conv and conv3d
133 if op.type.is_depthwise_conv2d_op() or op.type.is_conv2d_op() or op.type == Op.FullyConnected:
134 if inputs[1].values is not None:
135 if op.type == Op.FullyConnected:
136 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 0), False)
137 elif op.type.is_conv2d_op():
138 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 3, 0), False)
139 elif op.type.is_depthwise_conv2d_op():
140 inputs[1] = clone_and_reshape_tensor(inputs[1], (1, 2, 0, 3), False)
141 if op.type.needs_bias() and len(inputs) <= op_type.info.indices.biases[0]:
142 # No Bias tensor
143 inputs.append(None)
144 if inputs[-1] and inputs[-1].values is not None:
145 # Since bias tensor is used for both bias and scale,
146 # a clone with a unique equivalence_id is needed
147 inputs[-1] = clone_and_reshape_tensor(inputs[-1], (0,), True)
148
149 if attr_serializer is not None:
150 op.attrs = attr_serializer.deserialize(op_data)
151
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200152 if "padding" in op.attrs:
153 padding = op.attrs["padding"] # [top, bottom, left, right]
154 op.attrs["explicit_padding"] = (
155 padding[0],
156 padding[2],
157 padding[1],
158 padding[3],
159 ) # [top, left, bottom, right]
160 if "stride" in op.attrs:
161 stride = op.attrs["stride"]
162 if len(stride) == 2:
163 op.attrs["strides"] = (1, stride[0], stride[1], 1)
Patrik Gustavssondf995102021-08-23 15:33:59 +0200164 del op.attrs["stride"]
Patrik Gustavssonc74682c2021-08-17 14:26:38 +0200165 else:
166 # TODO CONV3D more to be done....
167 print("Unsupported kernel dimensions: ", len(stride))
168 assert False
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200169 if "dilation" in op.attrs:
170 dilation = op.attrs["dilation"]
171 if len(dilation) == 2:
172 op.attrs["dilation"] = (1, dilation[0], dilation[1], 1)
173 elif len(dilation) == 3:
174 # TODO CONV3D more to be done....
175 op.attrs["dilation"] = (dilation[0], dilation[1], dilation[2], 1)
176 if "kernel" in op.attrs:
177 kernel = op.attrs["kernel"]
178 if len(kernel) == 2:
179 op.attrs["ksize"] = (1, kernel[0], kernel[1], 1)
180 else:
181 # TODO CONV3D more to be done....
182 print("Unsupported kernel dimensions: ", len(kernel))
183 assert False
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200184 if "shift" in op.attrs and op.type == Op.Mul:
185 shift = op.attrs["shift"]
186 if shift != 0:
Fredrik Svedberg4a434cb2022-09-27 14:13:01 +0200187 op.explicit_scaling = ExplicitScaling(False, [shift], [1])
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