Elffuss BraidHub

kikocis/ncnn public

master · 11.1 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
4//
5// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6// in compliance with the License. You may obtain a copy of the License at
7//
8// https://opensource.org/licenses/BSD-3-Clause
9//
10// Unless required by applicable law or agreed to in writing, software distributed
11// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13// specific language governing permissions and limitations under the License.
14
15#include "fuse_constant_as_attribute.h"
16
17#include <sstream>
18#include <string>
19#include <unordered_set>
20
21#include "dead_code_elimination.h"
22
23namespace pnnx {
24
25namespace onnx2pnnx {
26
27struct constant_as_attribute
28{
29 const char* op_type;
30 int input_index;
31 const char* attribute;
32};
33
34static constant_as_attribute caas[] = {
35 {"Expand", 1, "shape"},
36 {"Gather", 1, "indices"},
37 {"If", 0, "cond"},
38 {"Pad", 1, "pads"},
39 {"Pad", 2, "value"},
40 {"ReduceMax", 1, "axes"},
41 {"ReduceMean", 1, "axes"},
42 {"ReduceMin", 1, "axes"},
43 {"ReduceProd", 1, "axes"},
44 {"ReduceSum", 1, "axes"},
45 {"Reshape", 1, "shape"},
46 {"Resize", 1, "roi"},
47 {"Resize", 2, "scales"},
48 {"Resize", 3, "sizes"},
49 {"Slice", 1, "starts"},
50 {"Slice", 2, "ends"},
51 {"Slice", 3, "axes"},
52 {"Slice", 4, "steps"},
53 {"Squeeze", 1, "axes"},
54 {"Tile", 1, "repeats"},
55 {"Unsqueeze", 1, "axes"},
56 {"Upsample", 1, "scales"},
57};
58
59static const char* get_constant_as_attribute(const std::string& op_type, int input_index)
60{
61 const int caas_count = sizeof(caas) / sizeof(caas[0]);
62 for (int i = 0; i < caas_count; i++)
63 {
64 if (op_type == caas[i].op_type && input_index == caas[i].input_index)
65 return caas[i].attribute;
66 }
67
68 return NULL;
69}
70
71void fuse_constant_as_attribute(onnx::ModelProto& model)
72{
73 // collect initializers
74 std::unordered_map<std::string, int> initializers;
75 {
76 const onnx::GraphProto& graph = model.graph();
77 for (int i = 0; i < graph.initializer_size(); i++)
78 {
79 initializers.insert(std::make_pair(graph.initializer(i).name(), i));
80 }
81 }
82
83 onnx::GraphProto* graph = model.mutable_graph();
84
85 for (int i = 0; i < graph->node_size(); i++)
86 {
87 onnx::NodeProto* node = graph->mutable_node(i);
88 if (!node->domain().empty())
89 {
90 // native onnx op
91 continue;
92 }
93
94 const std::string& op_type = node->op_type();
95
96 std::vector<int> fused_input_indexes;
97 for (int j = 0; j < node->input_size(); j++)
98 {
99 const std::string& input = node->input(j);
100 if (input.empty())
101 continue;
102
103 if (initializers.find(input) == initializers.end())
104 continue;
105
106 const char* attr_name = get_constant_as_attribute(op_type, j);
107 if (!attr_name)
108 continue;
109
110 // fprintf(stderr, "fuse_constant_as_attribute %s %d -> %s\n", op_type.c_str(), j, attr_name);
111
112 const onnx::TensorProto& tensor = graph->initializer(initializers.at(input));
113
114 int64_t numel = 1;
115 for (int k = 0; k < tensor.dims_size(); k++)
116 {
117 numel *= tensor.dims(k);
118 }
119
120 if (numel == 1)
121 {
122 // int or float scalar
123 if (tensor.data_type() == onnx::TensorProto::INT32)
124 {
125 int i32;
126 if (tensor.has_raw_data())
127 {
128 // assert tensor.raw_data().size() == 4
129 i32 = ((int*)tensor.raw_data().data())[0];
130 }
131 else
132 {
133 // assert tensor.int32_data().size() == 1
134 i32 = tensor.int32_data().at(0);
135 }
136
137 onnx::AttributeProto* attr = node->add_attribute();
138 attr->set_name(std::string(attr_name));
139 attr->set_type(onnx::AttributeProto::INT);
140 attr->set_i(i32);
141 }
142 else if (tensor.data_type() == onnx::TensorProto::INT64)
143 {
144 int64_t i64;
145 if (tensor.has_raw_data())
146 {
147 // assert tensor.raw_data().size() == 8
148 i64 = ((int64_t*)tensor.raw_data().data())[0];
149 }
150 else
151 {
152 // assert tensor.int64_data().size() == 1
153 i64 = tensor.int64_data().at(0);
154 }
155
156 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
157 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
158
159 onnx::AttributeProto* attr = node->add_attribute();
160 attr->set_name(std::string(attr_name));
161 attr->set_type(onnx::AttributeProto::INT);
162 attr->set_i((int)i64);
163 }
164 else if (tensor.data_type() == onnx::TensorProto::FLOAT)
165 {
166 float f32;
167 if (tensor.has_raw_data())
168 {
169 // assert tensor.raw_data().size() == 4
170 f32 = ((float*)tensor.raw_data().data())[0];
171 }
172 else
173 {
174 // assert tensor.float_data().size() == 1
175 f32 = tensor.float_data().at(0);
176 }
177
178 onnx::AttributeProto* attr = node->add_attribute();
179 attr->set_name(std::string(attr_name));
180 attr->set_type(onnx::AttributeProto::FLOAT);
181 attr->set_f(f32);
182 }
183 else if (tensor.data_type() == onnx::TensorProto::BOOL)
184 {
185 bool bb;
186 if (tensor.has_raw_data())
187 {
188 // assert tensor.raw_data().size() == 2
189 bb = ((uint16_t*)tensor.raw_data().data())[0] ? true : false;
190 }
191 else
192 {
193 // assert tensor.int32_data().size() == 1
194 bb = tensor.int32_data().at(0) ? true : false;
195 }
196
197 onnx::AttributeProto* attr = node->add_attribute();
198 attr->set_name(std::string(attr_name));
199 attr->set_type(onnx::AttributeProto::INT);
200 attr->set_i(bb ? 1 : 0);
201 }
202 else
203 {
204 fprintf(stderr, "unknown constant scalar type %d\n", (int)tensor.data_type());
205 continue;
206 }
207 }
208 else if (tensor.dims_size() == 1)
209 {
210 const int list_size = tensor.dims(0);
211 if (tensor.data_type() == onnx::TensorProto::INT32)
212 {
213 std::vector<int> ai(list_size);
214 if (tensor.has_raw_data())
215 {
216 // assert tensor.raw_data().size() == 4 * list_size
217 memcpy((void*)ai.data(), (int*)tensor.raw_data().data(), sizeof(int) * list_size);
218 }
219 else
220 {
221 // assert tensor.int32_data().size() == list_size
222 memcpy((void*)ai.data(), tensor.int32_data().data(), sizeof(int) * list_size);
223 }
224
225 onnx::AttributeProto* attr = node->add_attribute();
226 attr->set_name(std::string(attr_name));
227 attr->set_type(onnx::AttributeProto::INTS);
228 for (auto i32 : ai)
229 {
230 attr->add_ints(i32);
231 }
232 }
233 else if (tensor.data_type() == onnx::TensorProto::INT64)
234 {
235 std::vector<int64_t> ai(list_size);
236 if (tensor.has_raw_data())
237 {
238 // assert tensor.raw_data().size() == 8 * list_size
239 memcpy((void*)ai.data(), (int64_t*)tensor.raw_data().data(), sizeof(int64_t) * list_size);
240 }
241 else
242 {
243 // assert tensor.int64_data().size() == list_size
244 memcpy((void*)ai.data(), tensor.int64_data().data(), sizeof(int64_t) * list_size);
245 }
246
247 onnx::AttributeProto* attr = node->add_attribute();
248 attr->set_name(std::string(attr_name));
249 attr->set_type(onnx::AttributeProto::INTS);
250 for (auto i64 : ai)
251 {
252 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
253 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
254
255 attr->add_ints((int)i64);
256 }
257 }
258 else if (tensor.data_type() == onnx::TensorProto::FLOAT)
259 {
260 std::vector<float> af(list_size);
261 if (tensor.has_raw_data())
262 {
263 // assert tensor.raw_data().size() == 4 * list_size
264 memcpy((void*)af.data(), (float*)tensor.raw_data().data(), sizeof(float) * list_size);
265 }
266 else
267 {
268 // assert tensor.float_data().size() == list_size
269 memcpy((void*)af.data(), tensor.float_data().data(), sizeof(float) * list_size);
270 }
271
272 onnx::AttributeProto* attr = node->add_attribute();
273 attr->set_name(std::string(attr_name));
274 attr->set_type(onnx::AttributeProto::FLOATS);
275 for (auto f32 : af)
276 {
277 attr->add_floats(f32);
278 }
279 }
280 else
281 {
282 fprintf(stderr, "unknown constant list type %d\n", (int)tensor.data_type());
283 continue;
284 }
285 }
286
287 fused_input_indexes.push_back(j);
288 }
289
290 // drop inputs
291 for (size_t j = 0; j < fused_input_indexes.size(); j++)
292 {
293 const int fused_input_index = fused_input_indexes[j];
294
295 // ..... fii .......
296 const int node_input_size = node->input_size();
297 for (int k = fused_input_index; k < node_input_size - 1; k++)
298 {
299 node->mutable_input()->SwapElements(k, k + 1);
300 }
301
302 // ..... ....... fii
303 node->mutable_input()->RemoveLast();
304 }
305 }
306
307 onnx2pnnx::dead_code_elimination(model);
308}
309
310} // namespace onnx2pnnx
311
312} // namespace pnnx