blob: 476b70aa0756cf3fce5aaad2c58c7638eca1cb1f [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# Utlity function for reading .tosa and .tflite files
18from .operation import Op
19from .operation import Operation
20
21
22def decode_str(s):
23 if s is None:
24 return ""
25 return s.decode("utf-8")
26
27
28def clone_and_reshape_tensor(src_tens, reorder, set_unique):
29 tens = src_tens.clone("_reshape", set_unique)
30 tens.shape = [src_tens.shape[idx] for idx in reorder]
31 tens.bandwidth_shape = tens.shape
32 tens.storage_shape = tens.shape
33
34 if tens.values is not None:
35 tens.values = tens.values.transpose(reorder)
36
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020037 op = Operation(Op.Const, tens.name)
38 op.set_output_tensor(tens)
39 return tens
40
41
42# Fix up tensors without operations. Generate either Placeholder or Constant ops
43def fixup_tensors(input_tensors, tensors):
44 for tens in input_tensors:
45 if len(tens.ops) and tens.ops[0].type == Op.Const:
46 break
47
48 if tens.ops != []:
49 tens.error("This subgraph input tensor has unexpected driving operators.")
50
51 op = Operation(Op.Placeholder, tens.name)
52 op.set_output_tensor(tens)
53
54 for tens in tensors:
55 if not tens.ops:
56 op = Operation(Op.Const, tens.name)
57 op.set_output_tensor(tens)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +020058
59
60def align_inputs_indices(from_indices, to_indices, inputs):
61 to_list = to_indices.ifms + to_indices.weights + to_indices.biases
62 from_list = from_indices.ifms + from_indices.weights + from_indices.biases
63
64 assert len(to_list) == len(from_list)
65 if to_list != from_list:
66 for idx, t_idx in enumerate(to_list):
67 if t_idx >= len(inputs):
68 # Biases are allowed to be left out
69 assert t_idx in from_indices.biases and t_idx in to_indices.biases
70 continue
71 if to_list[idx] != from_list[idx]:
72 # find t_idx in from list and swap.
73 for jdx in from_list[idx:]:
74 if from_list[jdx] == t_idx:
75 inputs[idx], inputs[jdx] = inputs[jdx], inputs[idx]
76 from_list[idx], from_list[jdx] = from_list[jdx], from_list[idx]
77 break
78 assert from_list == to_list
79 return inputs
80
81
82def align_tensor_indices_to_nng(op_type, indices, inputs):
83 nng_op = Op(op_type)
84 return align_inputs_indices(indices, nng_op.info.indices, inputs)