blob: 3a0ce43f1273c9ab42c57a9f70bb9420b0744b4f [file] [log] [blame]
Eric Kunze2364dcd2021-04-26 11:06:57 -07001
2// Copyright (c) 2020-2021, ARM Limited.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#include "tosa_serialization_handler.h"
17
18#include <iostream>
19using namespace tosa;
20
21TosaSerializationTensor::TosaSerializationTensor(const flatbuffers::String* name,
Kevin Cheng3bb1bc12021-06-17 15:57:08 -070022 const flatbuffers::Vector<int32_t>* shape,
Eric Kunze2364dcd2021-04-26 11:06:57 -070023 DType dtype,
Kevin Cheng3bb1bc12021-06-17 15:57:08 -070024 const flatbuffers::Vector<uint8_t>* data)
Eric Kunze2364dcd2021-04-26 11:06:57 -070025{
26 _dtype = dtype;
27
Kevin Cheng3bb1bc12021-06-17 15:57:08 -070028 std::copy(shape->begin(), shape->end(), std::back_inserter(_shape));
Eric Kunze2364dcd2021-04-26 11:06:57 -070029
30 assert(name);
31 _name = name->str();
32
Kevin Cheng3bb1bc12021-06-17 15:57:08 -070033 if (data)
Eric Kunze2364dcd2021-04-26 11:06:57 -070034 {
Kevin Cheng3bb1bc12021-06-17 15:57:08 -070035 std::copy(data->begin(), data->end(), std::back_inserter(_data));
Eric Kunze2364dcd2021-04-26 11:06:57 -070036 }
37}
38
Kevin Cheng545a5082021-11-11 01:36:33 +000039TosaSerializationTensor::TosaSerializationTensor(const std::string& name,
Eric Kunze2364dcd2021-04-26 11:06:57 -070040 const std::vector<int32_t>& shape,
41 DType dtype,
Kevin Cheng3bb1bc12021-06-17 15:57:08 -070042 const std::vector<uint8_t>& data)
Eric Kunze2364dcd2021-04-26 11:06:57 -070043{
Kevin Cheng3bb1bc12021-06-17 15:57:08 -070044 _dtype = dtype;
45 _shape = shape;
46 _name = name;
47 _data = data;
Eric Kunze2364dcd2021-04-26 11:06:57 -070048}
49
50TosaSerializationTensor::TosaSerializationTensor()
51{
52 _dtype = DType_UNKNOWN;
Kevin Cheng545a5082021-11-11 01:36:33 +000053 _name = "UNKNOWN";
Eric Kunze2364dcd2021-04-26 11:06:57 -070054}
55
56TosaSerializationTensor::~TosaSerializationTensor()
57{}
58
Eric Kunzebdcc3fe2022-06-07 05:17:37 +000059void TosaSerializationOperator::InitializeAttribute(Attribute attribute_type, const TosaAttributeBase* attribute)
Eric Kunze2364dcd2021-04-26 11:06:57 -070060{
Eric Kunze2364dcd2021-04-26 11:06:57 -070061 _attribute_type = attribute_type;
62
63 switch (attribute_type)
64 {
65 case Attribute_NONE:
66 _attribute = new TosaNoneAttribute();
67 break;
68#define DEF_ATTRIBUTE(NAME, ...) \
69 case Attribute_##NAME##Attribute: \
70 _attribute = new Tosa##NAME##Attribute(attribute); \
71 break;
72#include "attribute.def"
73#undef DEF_ATTRIBUTE
74 default:
75 printf("TosaSerializationOperator::TosaSerializationOperator(): Attribute %s not implemented yet\n",
76 EnumNamesAttribute()[attribute_type]);
77 assert(0);
78 }
79
Eric Kunzebdcc3fe2022-06-07 05:17:37 +000080 assert(_attribute);
Kevin Cheng545a5082021-11-11 01:36:33 +000081}
Eric Kunze2364dcd2021-04-26 11:06:57 -070082
Kevin Cheng545a5082021-11-11 01:36:33 +000083TosaSerializationOperator::TosaSerializationOperator(Op op,
84 Attribute attribute_type,
85 const TosaAttributeBase* attribute,
Kevin Cheng545a5082021-11-11 01:36:33 +000086 const std::vector<std::string>& input_tensor_names,
87 const std::vector<std::string>& output_tensor_names)
88{
89 _op = op;
Eric Kunze2364dcd2021-04-26 11:06:57 -070090 _input_tensor_names = input_tensor_names;
91 _output_tensor_names = output_tensor_names;
Kevin Cheng545a5082021-11-11 01:36:33 +000092
Eric Kunzebdcc3fe2022-06-07 05:17:37 +000093 InitializeAttribute(attribute_type, attribute);
Kevin Cheng545a5082021-11-11 01:36:33 +000094}
95
96TosaSerializationOperator::TosaSerializationOperator(Op op,
97 Attribute attribute_type,
98 const TosaAttributeBase* attribute,
Kevin Cheng545a5082021-11-11 01:36:33 +000099 std::vector<std::string>&& input_tensor_names,
100 std::vector<std::string>&& output_tensor_names)
101{
102 _op = op;
103 _input_tensor_names = std::move(input_tensor_names);
104 _output_tensor_names = std::move(output_tensor_names);
105
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000106 InitializeAttribute(attribute_type, attribute);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700107}
108
109TosaSerializationOperator::~TosaSerializationOperator()
110{
111 delete _attribute;
Eric Kunze2364dcd2021-04-26 11:06:57 -0700112}
113
Kevin Cheng545a5082021-11-11 01:36:33 +0000114TosaSerializationBasicBlock::TosaSerializationBasicBlock(const std::string& name,
115 const std::vector<TosaSerializationOperator*>& operators,
116 const std::vector<TosaSerializationTensor*>& tensors,
117 const std::vector<std::string>& inputs,
118 const std::vector<std::string>& outputs)
Eric Kunze2364dcd2021-04-26 11:06:57 -0700119{
Eric Kunze2364dcd2021-04-26 11:06:57 -0700120 _name = name;
121 _operators = operators;
122 _tensors = tensors;
123 _inputs = inputs;
124 _outputs = outputs;
125}
126
Kevin Cheng545a5082021-11-11 01:36:33 +0000127TosaSerializationBasicBlock::TosaSerializationBasicBlock(std::string&& name,
128 std::vector<TosaSerializationOperator*>&& operators,
129 std::vector<TosaSerializationTensor*>&& tensors,
130 std::vector<std::string>&& inputs,
131 std::vector<std::string>&& outputs)
132{
133 _name = std::move(name);
134 _operators = std::move(operators);
135 _tensors = std::move(tensors);
136 _inputs = std::move(inputs);
137 _outputs = std::move(outputs);
138}
139
Eric Kunze2364dcd2021-04-26 11:06:57 -0700140TosaSerializationBasicBlock::~TosaSerializationBasicBlock()
141{
142 // deallocate all operators
143 for (auto op : GetOperators())
144 {
145 delete op; // ~TosaSerializationOperator()
146 }
147
148 // deallocate all tensors
149 for (auto ts : GetTensors())
150 {
151 delete ts; // ~TosaSerializationTensor()
152 }
153}
154
155TosaSerializationHandler::TosaSerializationHandler()
156{
157 _schemaLoaded = false;
Kevin Chenge6563f52021-10-20 12:12:02 -0700158 _version = TosaVersion(TOSA_VERSION_MAJOR, TOSA_VERSION_MINOR, TOSA_VERSION_PATCH, TOSA_VERSION_DRAFT);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700159}
160
161TosaSerializationHandler::~TosaSerializationHandler()
162{
163 Clear(); // deallocate all basic blocks
164}
165
Kevin Chenga81a7a12021-11-10 14:07:34 -0800166TosaVersion TosaSerializationHandler::ParseTosaSchemaVersion(std::string schema)
167{
168 // Parse all 4 version fields in schema file
169 static const char* keywords[4] = { "major: int32 = ", "minor: int32 = ", "patch: int32 = ", "draft: bool = " };
170 string keyword_str[4];
171 size_t search_pos = 0;
172 size_t keyword_pos;
173 size_t semicolon_pos;
174 // parse integer field first
175 for (int32_t i = 0; i < 4; i++)
176 {
177 keyword_pos = schema.find(keywords[i], search_pos);
178 if (keyword_pos == std::string::npos)
179 {
180 printf("ERROR: can't find keyword \"%s\" in schema\n", keywords[i]);
181 assert(0);
182 }
183 semicolon_pos = schema.find(';', keyword_pos);
184 if (keyword_pos == std::string::npos)
185 {
186 printf("ERROR: can't find ';' in schema\n");
187 assert(0);
188 }
189 keyword_str[i] =
190 schema.substr(keyword_pos + strlen(keywords[i]), semicolon_pos - keyword_pos - strlen(keywords[i]));
191 search_pos = semicolon_pos;
192 }
193
194 int32_t schema_major = 0;
195 int32_t schema_minor = 0;
196 int32_t schema_patch = 0;
197 bool schema_draft = false;
198 try
199 {
200 schema_major = stoi(keyword_str[0]);
201 schema_minor = stoi(keyword_str[1]);
202 schema_patch = stoi(keyword_str[2]);
203 schema_draft = (keyword_str[3] == "true") ? true : false;
204 }
205 catch (std::invalid_argument& e)
206 {
207 printf("ERROR: fail at stoi(): %s\n", e.what());
208 assert(0);
209 }
210
211 TosaVersion schema_version(schema_major, schema_minor, schema_patch, schema_draft);
212
213 return schema_version;
214}
215
Eric Kunze2364dcd2021-04-26 11:06:57 -0700216tosa_err_t TosaSerializationHandler::LoadFileSchema(const char* schema_filename)
217{
218 std::string schema;
219 bool ok;
220
221 ok = flatbuffers::LoadFile(schema_filename, false, &schema);
222 if (!ok)
223 {
224 printf("Error loading schema file: %s\n", schema_filename);
225 return TOSA_FILE_ERROR;
226 }
227
228 ok = _parser.Parse(schema.c_str());
Kevin Chenga81a7a12021-11-10 14:07:34 -0800229
230 TosaVersion schema_version = ParseTosaSchemaVersion(schema);
231
232 TosaVersion::compat_t is_compat = schema_version.is_compatible(GetVersion());
233 switch (is_compat)
234 {
235 case TosaVersion::compat_t::COMPLETELY_COMPATIBLE:
236 break;
237 case TosaVersion::compat_t::PARTIALLY_COMPATIBLE:
238 printf("WARNING: Schema flatbuffer version %s is partially compatible with serializer version %s\n",
239 schema_version.to_string().c_str(), GetVersion().to_string().c_str());
240 break;
241 case TosaVersion::compat_t::NOT_COMPATIBLE:
242 printf("ERROR: Schema flatbuffer version %s is not compatible with serializer version %s\n",
243 schema_version.to_string().c_str(), GetVersion().to_string().c_str());
244 return TOSA_VERSION_MISMATCH;
245 }
246
Eric Kunze2364dcd2021-04-26 11:06:57 -0700247 if (!ok)
248 {
249 printf("Error parsing ISA schema file: %s\n", schema_filename);
250 return TOSA_FILE_ERROR;
251 }
252 _schemaLoaded = true;
253
254 return TOSA_OK;
255}
256
257tosa_err_t TosaSerializationHandler::LoadFileJson(const char* filename)
258{
259 std::string jsonfile;
260 bool ok;
261 tosa_err_t err;
262
263 if (!_schemaLoaded)
264 {
265 return TOSA_SCHEMA_MISSING;
266 }
267
268 ok = flatbuffers::LoadFile(filename, false, &jsonfile);
269 if (!ok)
270 {
271 printf("Error loading json file: %s\n", filename);
272 return TOSA_FILE_ERROR;
273 }
274
275 ok = _parser.Parse(jsonfile.c_str());
276 if (!ok)
277 {
278 printf("Error parsing json file: %s\n", filename);
279 return TOSA_FILE_ERROR;
280 }
281
282 uint8_t* buf = _parser.builder_.GetBufferPointer();
283
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700284 err = Deserialize(buf);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700285 if (err != TOSA_OK)
286 {
287 return err;
288 }
289
290 return TOSA_OK;
291}
292
293tosa_err_t TosaSerializationHandler::SaveFileJson(const char* filename)
294{
295 std::string jsongen;
296 tosa_err_t err;
297
298 if (!_schemaLoaded)
299 {
300 return TOSA_SCHEMA_MISSING;
301 }
302
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700303 err = Serialize();
Eric Kunze2364dcd2021-04-26 11:06:57 -0700304 if (err != TOSA_OK)
305 {
306 return err;
307 }
308
309 uint8_t* buf = _builder.GetBufferPointer();
310
311 if (!GenerateText(_parser, buf, &jsongen))
312 {
313 printf("Couldn't serialize parsed data to JSON!\n");
314 return TOSA_FILE_ERROR;
315 }
316
317 FILE* file = fopen(filename, "wb");
318
319 if (!file)
320 {
321 printf("Couldn't open output file: %s\n", filename);
322 return TOSA_FILE_ERROR;
323 }
324
325 if (fwrite(jsongen.c_str(), sizeof(char), jsongen.size(), file) != jsongen.size())
326 {
327 printf("Error writing to json output file: %s\n", filename);
328 fclose(file);
329 return TOSA_FILE_ERROR;
330 }
331
332 if (file)
333 fclose(file);
334
335 return TOSA_OK;
336}
337
338tosa_err_t TosaSerializationHandler::LoadFileTosaFlatbuffer(const char* filename)
339{
340 std::string read_buffer;
341 tosa_err_t err;
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800342 const uint8_t* buf;
Eric Kunze2364dcd2021-04-26 11:06:57 -0700343 bool ok;
344
345 ok = flatbuffers::LoadFile(filename, false, &read_buffer);
346 if (!ok)
347 {
348 printf("Error loading flatbuffer file: %s\n", filename);
349 return TOSA_FILE_ERROR;
350 }
351
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800352 buf = reinterpret_cast<const uint8_t*>(read_buffer.data());
Eric Kunze2364dcd2021-04-26 11:06:57 -0700353
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700354 err = Deserialize(buf);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700355 if (err != TOSA_OK)
356 {
357 return err;
358 }
359
360 return TOSA_OK;
361}
362
Aaron DeBattista8b3903a2021-11-18 16:38:11 +0000363tosa_err_t TosaSerializationHandler::LoadFileTosaFlatbuffer(const void* input, int in_size)
364{
365 tosa_err_t err;
366
367 const uint8_t* buf = (const uint8_t*)input;
368 err = Deserialize(buf);
369 if (err != TOSA_OK)
370 {
371 return err;
372 }
373
374 return TOSA_OK;
375}
376
Eric Kunze2364dcd2021-04-26 11:06:57 -0700377tosa_err_t TosaSerializationHandler::SaveFileTosaFlatbuffer(const char* filename)
378{
379 tosa_err_t err;
380
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700381 err = Serialize();
Eric Kunze2364dcd2021-04-26 11:06:57 -0700382 if (err != TOSA_OK)
383 {
384 return err;
385 }
386
387 uint8_t* buf = _builder.GetBufferPointer();
388
389 bool ok = flatbuffers::SaveFile(filename, (const char*)buf, _builder.GetSize(), false);
390 if (!ok)
391 {
392 printf("Error saving floatbuffer file: %s\n", filename);
393 return TOSA_FILE_ERROR;
394 }
395
396 return TOSA_OK;
397}
398
399tosa_err_t TosaSerializationHandler::Clear()
400{
401 // deallocate all basic blocks
402 for (auto bb : GetBlocks())
403 {
404 delete bb;
405 }
406 _blocks.clear();
407
408 return TOSA_OK;
409}
410
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700411tosa_err_t TosaSerializationHandler::Deserialize(const uint8_t* buf)
Eric Kunze2364dcd2021-04-26 11:06:57 -0700412{
Eric Kunzee6596402022-06-09 21:27:36 +0000413 if (!TosaGraphBufferHasIdentifier(buf))
414 {
415 printf("WARNING: TOSA file does not have TOSA file identifier\n");
416 }
Eric Kunze2364dcd2021-04-26 11:06:57 -0700417 auto fb_tosa_graph = GetTosaGraph(buf);
418 auto fb_tosa_version = fb_tosa_graph->version();
419 auto fb_tosa_blocks = fb_tosa_graph->blocks();
420
421 std::vector<std::string> operator_inputs_container;
422 std::vector<std::string> operator_outputs_container;
423
424 std::vector<TosaSerializationOperator*> block_operators_container;
425 std::vector<TosaSerializationTensor*> block_tensors_container;
426 std::vector<std::string> block_inputs_container;
427 std::vector<std::string> block_outputs_container;
428
429 TosaAttributeBase* typed_attribute = NULL;
Eric Kunze2364dcd2021-04-26 11:06:57 -0700430 TosaSerializationOperator* new_operator = NULL;
431 TosaSerializationBasicBlock* new_block = NULL;
432 TosaSerializationTensor* new_tensor = NULL;
433
434 // erase container
435 Clear();
436
Kevin Chenge6563f52021-10-20 12:12:02 -0700437 TosaVersion read_version(fb_tosa_version->_major(), fb_tosa_version->_minor(), fb_tosa_version->_patch(),
438 fb_tosa_version->_draft());
Eric Kunze2364dcd2021-04-26 11:06:57 -0700439
Kevin Chenge6563f52021-10-20 12:12:02 -0700440 TosaVersion::compat_t is_compat = read_version.is_compatible(GetVersion());
441 switch (is_compat)
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700442 {
Kevin Chenge6563f52021-10-20 12:12:02 -0700443 case TosaVersion::compat_t::COMPLETELY_COMPATIBLE:
444 break;
445 case TosaVersion::compat_t::PARTIALLY_COMPATIBLE:
446 printf("WARNING: Read flatbuffer version %s is partially compatible with serializer version %s\n",
447 read_version.to_string().c_str(), GetVersion().to_string().c_str());
448 break;
449 case TosaVersion::compat_t::NOT_COMPATIBLE:
450 printf("ERROR: Read flatbuffer version %s is not compatible with serializer version %s\n",
451 read_version.to_string().c_str(), GetVersion().to_string().c_str());
452 return TOSA_VERSION_MISMATCH;
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700453 }
Eric Kunze2364dcd2021-04-26 11:06:57 -0700454
455 for (size_t i = 0; i < fb_tosa_blocks->size(); i++)
456 {
457 auto curr_block = fb_tosa_blocks->Get(i);
458
459 auto block_name = curr_block->name()->str();
460
461 auto fb_tosa_operators = curr_block->operators();
462 block_operators_container.clear();
463 for (size_t j = 0; j < fb_tosa_operators->size(); j++)
464 {
465 auto curr_operator = fb_tosa_operators->Get(j);
466
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000467 auto operator_op = curr_operator->op();
468 auto attribute_type = curr_operator->attribute_type();
469 auto attribute = curr_operator->attribute();
Eric Kunze2364dcd2021-04-26 11:06:57 -0700470
471 // input tensors
472 auto operator_inputs = curr_operator->inputs();
473 operator_inputs_container.clear();
474 if (operator_inputs)
475 {
476 for (size_t k = 0; k < operator_inputs->size(); k++)
477 {
478 auto curr_input = operator_inputs->Get(k);
479 operator_inputs_container.push_back(curr_input->str());
480 }
481 }
482
483 // output tensors
484 auto operator_outputs = curr_operator->outputs();
485 operator_outputs_container.clear();
486 if (operator_outputs)
487 {
488 for (size_t k = 0; k < operator_outputs->size(); k++)
489 {
490 auto curr_output = operator_outputs->Get(k);
491 operator_outputs_container.push_back(curr_output->str());
492 }
493 }
494
495 switch (attribute_type)
496 {
497 case Attribute_NONE:
498 typed_attribute = new TosaNoneAttribute();
499 break;
500#define DEF_ATTRIBUTE(NAME, ...) \
501 case Attribute_##NAME##Attribute: \
502 typed_attribute = new Tosa##NAME##Attribute(attribute); \
503 break;
504#include "attribute.def"
505#undef DEF_ATTRIBUTE
506 default:
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700507 printf("TosaSerializationHandler::Deserialize(): Attribute %s not implemented yet\n",
Eric Kunze2364dcd2021-04-26 11:06:57 -0700508 EnumNamesAttribute()[attribute_type]);
509 return TOSA_INTERNAL_ERROR;
510 }
511
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000512 new_operator = new TosaSerializationOperator(operator_op, attribute_type, typed_attribute,
513 operator_inputs_container, operator_outputs_container);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700514 if (new_operator)
515 {
516 block_operators_container.push_back(new_operator);
517 }
518 else
519 {
520 return TOSA_MEMORY_ERROR;
521 }
522
523 if (typed_attribute)
524 delete typed_attribute;
Eric Kunze2364dcd2021-04-26 11:06:57 -0700525 }
526
527 auto fb_tosa_tensors = curr_block->tensors();
528 block_tensors_container.clear();
529 for (size_t j = 0; j < fb_tosa_tensors->size(); j++)
530 {
531 auto curr_tensor = fb_tosa_tensors->Get(j);
532
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700533 auto tensor_name = curr_tensor->name();
534 auto tensor_shape = curr_tensor->shape();
535 auto tensor_type = curr_tensor->type();
536 auto tensor_data = curr_tensor->data();
Eric Kunze2364dcd2021-04-26 11:06:57 -0700537
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700538 new_tensor = new TosaSerializationTensor(tensor_name, tensor_shape, tensor_type, tensor_data);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700539 if (new_tensor)
540 {
541 block_tensors_container.push_back(new_tensor);
542 }
543 else
544 {
545 return TOSA_MEMORY_ERROR;
546 }
547 }
548
549 auto block_inputs = curr_block->inputs();
550 auto block_outputs = curr_block->outputs();
551
552 block_inputs_container.clear();
553 block_outputs_container.clear();
554
555 for (size_t j = 0; j < block_inputs->size(); j++)
556 {
557 auto curr_block_input = block_inputs->Get(j);
558 block_inputs_container.push_back(curr_block_input->str());
559 }
560 for (size_t j = 0; j < block_outputs->size(); j++)
561 {
562 auto curr_block_output = block_outputs->Get(j);
563 block_outputs_container.push_back(curr_block_output->str());
564 }
565
566 new_block = new TosaSerializationBasicBlock(block_name, block_operators_container, block_tensors_container,
567 block_inputs_container, block_outputs_container);
568 if (new_block)
569 {
570 this->GetBlocks().push_back(new_block);
571 }
572 else
573 {
574 return TOSA_MEMORY_ERROR;
575 }
576 }
577
578 return TOSA_OK;
579}
580
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700581tosa_err_t TosaSerializationHandler::Serialize()
Eric Kunze2364dcd2021-04-26 11:06:57 -0700582{
583 std::vector<flatbuffers::Offset<TosaBasicBlock>> fboffset_blocks;
584
585 std::vector<flatbuffers::Offset<TosaOperator>> fboffset_block_operators;
586 std::vector<flatbuffers::Offset<TosaTensor>> fboffset_block_tensors;
587 std::vector<flatbuffers::Offset<flatbuffers::String>> fboffset_block_inputs;
588 std::vector<flatbuffers::Offset<flatbuffers::String>> fboffset_block_outputs;
589
590 std::vector<flatbuffers::Offset<flatbuffers::String>> fboffset_operator_inputs;
591 std::vector<flatbuffers::Offset<flatbuffers::String>> fboffset_operator_outputs;
592
593 // translate TosaFlatbufferOperator to flatbuffers::Offset<TosaOperator>
594 for (auto block : GetBlocks())
595 {
596 fboffset_block_operators.clear();
597 fboffset_block_tensors.clear();
598 fboffset_block_inputs.clear();
599 fboffset_block_outputs.clear();
600
601 auto block_name = _builder.CreateString(block->GetName().c_str());
602
603 for (auto tensor_str : block->GetInputs())
604 {
605 auto tensor_name = _builder.CreateString(tensor_str.c_str());
606 fboffset_block_inputs.push_back(tensor_name);
607 }
608
609 for (auto tensor_str : block->GetOutputs())
610 {
611 auto tensor_name = _builder.CreateString(tensor_str.c_str());
612 fboffset_block_outputs.push_back(tensor_name);
613 }
614
615 auto fb_block_inputs = _builder.CreateVector(fboffset_block_inputs);
616 auto fb_block_outputs = _builder.CreateVector(fboffset_block_outputs);
617
618 for (auto op : block->GetOperators())
619 {
620 fboffset_operator_inputs.clear();
621 fboffset_operator_outputs.clear();
622
623 auto operator_op = op->GetOp();
624 auto attribute_type = op->GetAttributeType();
625
626 for (auto tensor_str : op->GetInputTensorNames())
627 {
628 auto tensor_name = _builder.CreateString(tensor_str.c_str());
629 fboffset_operator_inputs.push_back(tensor_name);
630 }
631
632 for (auto tensor_str : op->GetOutputTensorNames())
633 {
634 auto tensor_name = _builder.CreateString(tensor_str.c_str());
635 fboffset_operator_outputs.push_back(tensor_name);
636 }
637
638 auto fb_operator_inputs = _builder.CreateVector(fboffset_operator_inputs);
639 auto fb_operator_outputs = _builder.CreateVector(fboffset_operator_outputs);
640
641 flatbuffers::Offset<void> fb_attribute;
642 switch (attribute_type)
643 {
644 case Attribute_NONE:
645 fb_attribute = 0;
646 break;
647
648#define DEF_ARGS_S_STR(NAME, V) , _builder.CreateString(reinterpret_cast<Tosa##NAME*>(op->GetAttribute())->V().c_str())
649#define DEF_ARGS_S_DEFAULT(NAME, V) , reinterpret_cast<Tosa##NAME*>(op->GetAttribute())->V()
650
651#define DEF_ARGS_S_int32_t(NAME, V) DEF_ARGS_S_DEFAULT(NAME, V)
652#define DEF_ARGS_S_float(NAME, V) DEF_ARGS_S_DEFAULT(NAME, V)
653#define DEF_ARGS_S_bool(NAME, V) DEF_ARGS_S_DEFAULT(NAME, V)
654#define DEF_ARGS_S_ResizeMode(NAME, V) DEF_ARGS_S_DEFAULT(NAME, V)
655#define DEF_ARGS_S_string(NAME, V) DEF_ARGS_S_STR(NAME, V)
656
657#define DEF_ARGS_S(NAME, T, V) DEF_ARGS_S_##T(NAME, V)
658#define DEF_ARGS_V(NAME, T, V) , _builder.CreateVector<T>(reinterpret_cast<Tosa##NAME*>(op->GetAttribute())->V())
659
660#define DEF_ARGS_1(NAME, T0, F0, V0) DEF_ARGS_##F0(NAME, T0, V0)
661#define DEF_ARGS_2(NAME, T0, F0, V0, T1, F1, V1) DEF_ARGS_##F0(NAME, T0, V0) DEF_ARGS_##F1(NAME, T1, V1)
662#define DEF_ARGS_3(NAME, T0, F0, V0, T1, F1, V1, T2, F2, V2) \
663 DEF_ARGS_##F0(NAME, T0, V0) DEF_ARGS_##F1(NAME, T1, V1) DEF_ARGS_##F2(NAME, T2, V2)
664#define DEF_ARGS_4(NAME, T0, F0, V0, T1, F1, V1, T2, F2, V2, T3, F3, V3) \
665 DEF_ARGS_##F0(NAME, T0, V0) DEF_ARGS_##F1(NAME, T1, V1) DEF_ARGS_##F2(NAME, T2, V2) DEF_ARGS_##F3(NAME, T3, V3)
666#define DEF_ARGS_5(NAME, T0, F0, V0, T1, F1, V1, T2, F2, V2, T3, F3, V3, T4, F4, V4) \
667 DEF_ARGS_##F0(NAME, T0, V0) DEF_ARGS_##F1(NAME, T1, V1) DEF_ARGS_##F2(NAME, T2, V2) DEF_ARGS_##F3(NAME, T3, V3) \
668 DEF_ARGS_##F4(NAME, T4, V4)
669#define DEF_ARGS_6(NAME, T0, F0, V0, T1, F1, V1, T2, F2, V2, T3, F3, V3, T4, F4, V4, T5, F5, V5) \
670 DEF_ARGS_##F0(NAME, T0, V0) DEF_ARGS_##F1(NAME, T1, V1) DEF_ARGS_##F2(NAME, T2, V2) DEF_ARGS_##F3(NAME, T3, V3) \
671 DEF_ARGS_##F4(NAME, T4, V4) DEF_ARGS_##F5(NAME, T5, V5)
672#define DEF_ARGS_7(NAME, T0, F0, V0, T1, F1, V1, T2, F2, V2, T3, F3, V3, T4, F4, V4, T5, F5, V5, T6, F6, V6) \
673 DEF_ARGS_##F0(NAME, T0, V0) DEF_ARGS_##F1(NAME, T1, V1) DEF_ARGS_##F2(NAME, T2, V2) DEF_ARGS_##F3(NAME, T3, V3) \
674 DEF_ARGS_##F4(NAME, T4, V4) DEF_ARGS_##F5(NAME, T5, V5) DEF_ARGS_##F6(NAME, T6, V6)
675#define DEF_ATTRIBUTE(NAME, NUM_ARGS, ...) \
676 case Attribute_##NAME##Attribute: \
677 fb_attribute = Create##NAME##Attribute(_builder DEF_ARGS_##NUM_ARGS(NAME##Attribute, __VA_ARGS__)).Union(); \
678 break;
679
680#include "attribute.def"
681#undef DEF_ATTRIBUTE
682#undef DEF_ARGS_1
683#undef DEF_ARGS_2
684#undef DEF_ARGS_3
685#undef DEF_ARGS_4
686#undef DEF_ARGS_5
687#undef DEF_ARGS_6
688#undef DEF_ARGS_7
689#undef DEF_ARGS_S
690#undef DEF_ARGS_V
691#undef DEF_ARGS_S_int32_t
692#undef DEF_ARGS_S_float
693#undef DEF_ARGS_S_bool
694#undef DEF_ARGS_S_ResizeMode
695#undef DEF_ARGS_S_string
696#undef DEF_ARGS_S_STR
697#undef DEF_ARGS_S_DEFAULT
698 default:
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700699 printf("TosaSerializationHandler::Serialize(): Attribute %s not implemented yet\n",
Eric Kunze2364dcd2021-04-26 11:06:57 -0700700 EnumNamesAttribute()[attribute_type]);
701 return TOSA_INTERNAL_ERROR;
702 }
703
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000704 auto fboffset_operator = CreateTosaOperator(_builder, operator_op, attribute_type, fb_attribute,
705 fb_operator_inputs, fb_operator_outputs);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700706 fboffset_block_operators.push_back(fboffset_operator);
707 }
708
709 auto fb_block_operators = _builder.CreateVector(fboffset_block_operators);
710
711 for (auto tensor : block->GetTensors())
712 {
713
714 auto tensor_name = _builder.CreateString(tensor->GetName().c_str());
715 auto tensor_shape = _builder.CreateVector(tensor->GetShape());
716 auto tensor_dtype = tensor->GetDtype();
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700717 auto tensor_data = _builder.CreateVector(tensor->GetData());
Eric Kunze2364dcd2021-04-26 11:06:57 -0700718
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700719 auto fboffset_tensor = CreateTosaTensor(_builder, tensor_name, tensor_shape, tensor_dtype, tensor_data);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700720 fboffset_block_tensors.push_back(fboffset_tensor);
721 }
722
723 auto fb_block_tensors = _builder.CreateVector(fboffset_block_tensors);
724
725 auto fboffset_block = CreateTosaBasicBlock(_builder, block_name, fb_block_operators, fb_block_tensors,
726 fb_block_inputs, fb_block_outputs);
727 fboffset_blocks.push_back(fboffset_block);
728 }
729
730 auto fb_blocks = _builder.CreateVector(fboffset_blocks);
731
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700732 auto fb_version =
733 CreateVersion(_builder, TOSA_VERSION_MAJOR, TOSA_VERSION_MINOR, TOSA_VERSION_PATCH, TOSA_VERSION_DRAFT);
Eric Kunze2364dcd2021-04-26 11:06:57 -0700734
735 auto fb_graph = CreateTosaGraph(_builder, fb_version, fb_blocks);
Eric Kunzee6596402022-06-09 21:27:36 +0000736 _builder.Finish(fb_graph, TosaGraphIdentifier());
Eric Kunze2364dcd2021-04-26 11:06:57 -0700737
738 return TOSA_OK;
739}
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700740
741void zero_pad(std::vector<uint8_t>& buf)
742{
743 while ((buf.size() % TENSOR_BUFFER_FORCE_ALIGNMENT) != 0)
744 {
745 buf.push_back(0);
746 }
747}
748
749tosa_err_t TosaSerializationHandler::ConvertF32toU8(const std::vector<float>& in, std::vector<uint8_t>& out)
750{
751 out.clear();
752 for (auto val : in)
753 {
754 uint32_t* val_u32 = reinterpret_cast<uint32_t*>(&val);
755 out.push_back(*val_u32 & 0xFF);
756 out.push_back((*val_u32 >> 8) & 0xFF);
757 out.push_back((*val_u32 >> 16) & 0xFF);
758 out.push_back((*val_u32 >> 24) & 0xFF);
759 }
760 zero_pad(out);
761 return TOSA_OK;
762}
763
764tosa_err_t TosaSerializationHandler::ConvertI48toU8(const std::vector<int64_t>& in, std::vector<uint8_t>& out)
765{
766 out.clear();
767 for (auto val : in)
768 {
769 uint64_t* val_u64 = reinterpret_cast<uint64_t*>(&val);
770 out.push_back(*val_u64 & 0xFF);
771 out.push_back((*val_u64 >> 8) & 0xFF);
772 out.push_back((*val_u64 >> 16) & 0xFF);
773 out.push_back((*val_u64 >> 24) & 0xFF);
774 out.push_back((*val_u64 >> 32) & 0xFF);
775 out.push_back((*val_u64 >> 40) & 0xFF);
776 }
777 zero_pad(out);
778 return TOSA_OK;
779}
780
781tosa_err_t TosaSerializationHandler::ConvertI32toU8(const std::vector<int32_t>& in, std::vector<uint8_t>& out)
782{
783 out.clear();
784 for (auto val : in)
785 {
786 uint32_t* val_u32 = reinterpret_cast<uint32_t*>(&val);
787 out.push_back(*val_u32 & 0xFF);
788 out.push_back((*val_u32 >> 8) & 0xFF);
789 out.push_back((*val_u32 >> 16) & 0xFF);
790 out.push_back((*val_u32 >> 24) & 0xFF);
791 }
792 zero_pad(out);
793 return TOSA_OK;
794}
795
796tosa_err_t TosaSerializationHandler::ConvertI16toU8(const std::vector<int16_t>& in, std::vector<uint8_t>& out)
797{
798 out.clear();
799 for (auto val : in)
800 {
801 uint16_t* val_u16 = reinterpret_cast<uint16_t*>(&val);
802 out.push_back(*val_u16 & 0xFF);
803 out.push_back((*val_u16 >> 8) & 0xFF);
804 }
805 zero_pad(out);
806 return TOSA_OK;
807}
808
809tosa_err_t TosaSerializationHandler::ConvertI8toU8(const std::vector<int8_t>& in, std::vector<uint8_t>& out)
810{
811 out.clear();
812 for (auto val : in)
813 {
814 uint8_t* val_u8 = reinterpret_cast<uint8_t*>(&val);
815 out.push_back(*val_u8);
816 }
817 zero_pad(out);
818 return TOSA_OK;
819}
820
Kevin Cheng3ce56342021-07-28 13:42:29 -0700821// Two int4 values are packed into one byte out.
822// For given input value val_0 = in[2*i], and val_1 = in[2*i+1],
823// they'll be packed as out[3:0] = val_0, and out[7:4] = val_1
824tosa_err_t TosaSerializationHandler::ConvertI4toU8(const std::vector<int8_t>& in, std::vector<uint8_t>& out)
825{
826 out.clear();
827 uint32_t in_size = in.size();
828 uint32_t out_size = (in_size % 2 == 0) ? (in_size / 2) : ((in_size + 1) / 2);
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800829 for (uint32_t i = 0; i < out_size; i++)
Kevin Cheng3ce56342021-07-28 13:42:29 -0700830 {
831 int8_t val_0 = in[2 * i];
832 int8_t val_1 = 0;
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800833 if (2u * i + 1u < in_size)
Kevin Cheng3ce56342021-07-28 13:42:29 -0700834 {
835 val_1 = in[2 * i + 1];
836 }
837 // In TOSA spec, int4 ranges [-7, 7]
838 if (val_0 < -7 || val_0 > 7 || val_1 < -7 || val_1 > 7)
839 {
840 printf("TosaSerializationHandler::ConvertI4toU8(): element in input array (%d or %d) exceeds int4 range.\n",
841 val_0, val_1);
842 return TOSA_USER_ERROR;
843 }
844 int8_t val_packed = (val_0 & 0xF) | ((val_1 & 0xF) << 4);
845 uint8_t val_u8 = static_cast<uint8_t>(val_packed);
846 out.push_back(val_u8);
847 }
848 zero_pad(out);
849 return TOSA_OK;
850}
851
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700852tosa_err_t TosaSerializationHandler::ConvertBooltoU8(const std::vector<bool>& in, std::vector<uint8_t>& out)
853{
854 out.clear();
855 for (auto val : in)
856 {
Eric Kunze4417b422022-06-20 07:27:42 -0700857 uint8_t val_u8 = val;
858 out.push_back(val_u8);
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700859 }
860 zero_pad(out);
861 return TOSA_OK;
862}
863
864tosa_err_t
865 TosaSerializationHandler::ConvertU8toF32(const std::vector<uint8_t>& in, uint32_t out_size, std::vector<float>& out)
866{
867 out.clear();
868 if (in.size() < out_size * sizeof(float))
869 {
870 printf("TosaSerializationHandler::ConvertU8toF32(): uint8 buffer size %ld must >= target size %ld\n", in.size(),
871 out_size * sizeof(float));
872 return TOSA_USER_ERROR;
873 }
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800874 for (uint32_t i = 0; i < out_size; i++)
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700875 {
876 uint32_t byte0 = in[i * sizeof(float)];
877 uint32_t byte1 = in[i * sizeof(float) + 1];
878 uint32_t byte2 = in[i * sizeof(float) + 2];
879 uint32_t byte3 = in[i * sizeof(float) + 3];
880 uint32_t val_u32 = byte0 + (byte1 << 8) + (byte2 << 16) + (byte3 << 24);
881 float* val_fp32 = reinterpret_cast<float*>(&val_u32);
882 out.push_back(*val_fp32);
883 }
884 return TOSA_OK;
885}
886
887tosa_err_t TosaSerializationHandler::ConvertU8toI48(const std::vector<uint8_t>& in,
888 uint32_t out_size,
889 std::vector<int64_t>& out)
890{
891 out.clear();
892 if (in.size() < out_size * 6 /* sizeof(int48) */)
893 {
894 printf("TosaSerializationHandler::ConvertU8toI48(): uint8 buffer size %ld must >= target size %d\n", in.size(),
895 out_size * 6);
896 return TOSA_USER_ERROR;
897 }
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800898 for (uint32_t i = 0; i < out_size; i++)
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700899 {
900 uint64_t byte0 = in[i * 6];
901 uint64_t byte1 = in[i * 6 + 1];
902 uint64_t byte2 = in[i * 6 + 2];
903 uint64_t byte3 = in[i * 6 + 3];
904 uint64_t byte4 = in[i * 6 + 4];
905 uint64_t byte5 = in[i * 6 + 5];
906 bool sign = ((byte5 >> 7) & 1) == 1 ? true : false;
907 uint64_t val_u64 = byte0 + (byte1 << 8) + (byte2 << 16) + (byte3 << 24) + (byte4 << 32) + (byte5 << 40);
908 if (sign)
909 {
910 uint64_t sext_mask = (0xFFFFUL << 48);
911 val_u64 |= sext_mask;
912 }
913 int64_t* val_i64 = reinterpret_cast<int64_t*>(&val_u64);
914 out.push_back(*val_i64);
915 }
916 return TOSA_OK;
917}
918
919tosa_err_t TosaSerializationHandler::ConvertU8toI32(const std::vector<uint8_t>& in,
920 uint32_t out_size,
921 std::vector<int32_t>& out)
922{
923 out.clear();
924 if (in.size() < out_size * sizeof(int32_t))
925 {
926 printf("TosaSerializationHandler::ConvertU8toI32(): uint8 buffer size %ld must >= target size %ld\n", in.size(),
927 out_size * sizeof(int32_t));
928 return TOSA_USER_ERROR;
929 }
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800930 for (uint32_t i = 0; i < out_size; i++)
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700931 {
932 uint32_t byte0 = in[i * sizeof(int32_t)];
933 uint32_t byte1 = in[i * sizeof(int32_t) + 1];
934 uint32_t byte2 = in[i * sizeof(int32_t) + 2];
935 uint32_t byte3 = in[i * sizeof(int32_t) + 3];
936 uint32_t val_u32 = byte0 + (byte1 << 8) + (byte2 << 16) + (byte3 << 24);
937 int32_t* val_i32 = reinterpret_cast<int32_t*>(&val_u32);
938 out.push_back(*val_i32);
939 }
940 return TOSA_OK;
941}
942
943tosa_err_t TosaSerializationHandler::ConvertU8toI16(const std::vector<uint8_t>& in,
944 uint32_t out_size,
945 std::vector<int16_t>& out)
946{
947 out.clear();
948 if (in.size() < out_size * sizeof(int16_t))
949 {
950 printf("TosaSerializationHandler::ConvertU8toI16(): uint8 buffer size %ld must >= target size %ld\n", in.size(),
951 out_size * sizeof(int16_t));
952 return TOSA_USER_ERROR;
953 }
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800954 for (uint32_t i = 0; i < out_size; i++)
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700955 {
956 uint16_t byte0 = in[i * sizeof(int16_t)];
957 uint16_t byte1 = in[i * sizeof(int16_t) + 1];
958 uint16_t val_u16 = byte0 + (byte1 << 8);
959 int16_t* val_i16 = reinterpret_cast<int16_t*>(&val_u16);
960 out.push_back(*val_i16);
961 }
962 return TOSA_OK;
963}
964
965tosa_err_t
966 TosaSerializationHandler::ConvertU8toI8(const std::vector<uint8_t>& in, uint32_t out_size, std::vector<int8_t>& out)
967{
968 out.clear();
969 if (in.size() < out_size * sizeof(int8_t))
970 {
971 printf("TosaSerializationHandler::ConvertU8toI8(): uint8 buffer size %ld must >= target size %ld\n", in.size(),
Kevin Cheng3ce56342021-07-28 13:42:29 -0700972 out_size * sizeof(int8_t));
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700973 return TOSA_USER_ERROR;
974 }
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800975 for (uint32_t i = 0; i < out_size; i++)
Kevin Cheng3bb1bc12021-06-17 15:57:08 -0700976 {
977 uint8_t val_u8 = in[i];
978 int8_t* val_i8 = reinterpret_cast<int8_t*>(&val_u8);
979 out.push_back(*val_i8);
980 }
981 return TOSA_OK;
982}
983
984tosa_err_t
Kevin Cheng3ce56342021-07-28 13:42:29 -0700985 TosaSerializationHandler::ConvertU8toI4(const std::vector<uint8_t>& in, uint32_t out_size, std::vector<int8_t>& out)
986{
987 out.clear();
988 if (out_size > in.size() * 2)
989 {
990 printf("TosaSerializationHandler::ConvertU8toI4(): output size %u must <= uint8 buffer size %ld x 2.\n",
991 out_size, in.size());
992 return TOSA_USER_ERROR;
993 }
Eric Kunzeb13fe8f2022-02-17 17:14:25 -0800994 for (size_t i = 0; i < in.size(); i++)
Kevin Cheng3ce56342021-07-28 13:42:29 -0700995 {
996 uint8_t val_u8 = in[i];
997 uint8_t val_0_u4 = val_u8 & 0xF;
998 uint8_t val_1_u4 = val_u8 >> 4;
999 uint8_t val_0_u8_sext = (val_0_u4 & 0x08) ? (val_0_u4 | 0xF0) : val_0_u4;
1000 uint8_t val_1_u8_sext = (val_1_u4 & 0x08) ? (val_1_u4 | 0xF0) : val_1_u4;
1001 int8_t val_0 = static_cast<int8_t>(val_0_u8_sext);
1002 int8_t val_1 = static_cast<int8_t>(val_1_u8_sext);
1003 // In TOSA spec, int4 ranges [-7, 7]
1004 if (val_0 < -7 || val_0 > 7 || val_1 < -7 || val_1 > 7)
1005 {
1006 printf(
1007 "TosaSerializationHandler::ConvertU8toI4(): element in output array (%d or %d) exceeds int4 range.\n",
1008 val_0, val_1);
1009 return TOSA_USER_ERROR;
1010 }
1011 out.push_back(val_0);
1012 if (2 * i + 1 < out_size)
1013 out.push_back(val_1);
1014 }
1015 return TOSA_OK;
1016}
1017
1018tosa_err_t
Kevin Cheng3bb1bc12021-06-17 15:57:08 -07001019 TosaSerializationHandler::ConvertU8toBool(const std::vector<uint8_t>& in, uint32_t out_size, std::vector<bool>& out)
1020{
1021 out.clear();
1022 if (in.size() < out_size * sizeof(bool))
1023 {
1024 printf("TosaSerializationHandler::ConvertU8toBool(): uint8 buffer size %ld must >= target size %ld\n",
1025 in.size(), out_size * sizeof(bool));
1026 return TOSA_USER_ERROR;
1027 }
Eric Kunzeb13fe8f2022-02-17 17:14:25 -08001028 for (uint32_t i = 0; i < out_size; i++)
Kevin Cheng3bb1bc12021-06-17 15:57:08 -07001029 {
1030 uint8_t val_u8 = in[i];
1031 bool* val_bool = reinterpret_cast<bool*>(&val_u8);
1032 out.push_back(*val_bool);
1033 }
1034 return TOSA_OK;
1035}