50struct DataChefRegistry final :
public Registry<DataChefFactory>
54DataChefRegistry &data_chef_registry(
const tflchef::TensorType &type)
56 static DataChefRegistry s32;
57 static DataChefRegistry s64;
58 static DataChefRegistry fp32;
59 static DataChefRegistry u8;
60 static DataChefRegistry string;
61 static DataChefRegistry boolean;
62 static DataChefRegistry s16;
63 static DataChefRegistry fp16;
64 static DataChefRegistry s8;
65 static DataChefRegistry s4;
73 case tflchef::FLOAT32:
75 case tflchef::FLOAT16:
93 throw std::runtime_error{
"Unknown tensor type"};
96struct OpChefRegistry final :
public Registry<OpChefFactory>
100OpChefRegistry &op_chef_registry(
void)
102 static OpChefRegistry registry;
107std::map<tflite::BuiltinOperator, int32_t>
108gather_builtincode_map(const ::tflchef::ModelRecipe &model_recipe)
111 std::map<tflite::BuiltinOperator, int32_t> builtin_map;
113 for (
const auto &operation : model_recipe.operation())
115 if (operation.type() ==
"Custom")
118 auto op_chef = op_chef_registry().lookup(operation.type()).create(&operation);
120 if (builtin_map.find(op_chef->code()) == builtin_map.end() ||
121 builtin_map[op_chef->code()] < operation.version())
122 builtin_map[op_chef->code()] = operation.version();
126 for (
int g = 0;
g < model_recipe.graph_size(); ++
g)
128 const auto &
graph = model_recipe.graph(g);
129 for (
const auto &operation :
graph.operation())
131 if (operation.type() ==
"Custom")
134 auto op_chef = op_chef_registry().lookup(operation.type()).create(&operation);
136 if (builtin_map.find(op_chef->code()) == builtin_map.end() ||
137 builtin_map[op_chef->code()] < operation.version())
138 builtin_map[op_chef->code()] = operation.version();
146std::set<std::string> gather_customcode_set(const ::tflchef::ModelRecipe &model_recipe)
148 std::set<std::string> customcode_set;
149 for (
const auto &operation : model_recipe.operation())
151 if (operation.type() ==
"Custom")
153 assert(not operation.custom_code().empty());
154 customcode_set.insert(operation.custom_code());
159 for (
int g = 0;
g < model_recipe.graph_size(); ++
g)
161 const auto &
graph = model_recipe.graph(g);
162 for (
const auto &operation :
graph.operation())
164 if (operation.type() ==
"Custom")
166 assert(not operation.custom_code().empty());
167 customcode_set.insert(operation.custom_code());
172 return customcode_set;
183 ModelChef() =
default;
187 void cook(const ::tflchef::ModelRecipe &model_recipe);
190 void prepare_initial_buffer(
void);
191 void gather_operator_codes(const ::tflchef::ModelRecipe &model_recipe);
192 void gather_signature_defs(const ::tflchef::ModelRecipe &model_recipe);
194 template <
typename T>
void cook_operands(
const T &graph);
196 template <
typename T>
197 void cook_operations(
const T &graph, std::map<std::string, int32_t> &symbol_table);
199 template <
typename T>
200 void cook_graph(
const T &graph, std::map<std::string, int32_t> &symbol_table);
202 bool finalize_ext_buffer(
void);
205 const char *get_buffer_pointer(
void)
const;
206 size_t get_size(
void)
const;
209 std::unique_ptr<flatbuffers::FlatBufferBuilder> _flatbuffer_builder;
211 std::vector<flatbuffers::Offset<::tflite::SignatureDef>> _signdef_vec;
212 std::vector<flatbuffers::Offset<::tflite::Buffer>> _buffer_vec;
213 std::vector<flatbuffers::Offset<::tflite::OperatorCode>> _code_vec;
214 std::vector<flatbuffers::Offset<::tflite::SubGraph>> _subgraph_vec;
215 std::map<tflite::BuiltinOperator, int32_t> _builtin_code_map;
216 std::vector<std::string> _custom_code_vec;
219 std::vector<std::map<std::string, int32_t>> _symbol_tables;
223 std::vector<flatbuffers::Offset<::tflite::Tensor>> _tensor_vec;
225 std::vector<flatbuffers::Offset<::tflite::Operator>> _operator_vec;
227 std::string _graph_name;
230 bool _ext_offset =
false;
231 std::map<int32_t, std::vector<uint8_t>> _buffer_data_map;
232 std::string _ext_data;
235void ModelChef::init(
void)
237 _flatbuffer_builder =
241std::vector<flatbuffers::Offset<tflite::DimensionMetadata>>
243 const std::vector<int> &traversal_order_vec,
244 const std::vector<sparsity::TfLiteDimensionType> &format_vec,
245 const std::vector<std::vector<int32_t>> &dim_metadata_src)
248 std::vector<flatbuffers::Offset<tflite::DimensionMetadata>> dim_metadata_vec(dims_count);
249 for (int32_t i = 0; i < dims_count; i++)
251 const int32_t metadata_idx = 2 * i;
254 auto array_segments =
255 tflite::CreateInt32Vector(*flatbuffer_builder,
256 flatbuffer_builder->
CreateVector(dim_metadata_src[metadata_idx]))
259 tflite::CreateInt32Vector(
260 *flatbuffer_builder, flatbuffer_builder->
CreateVector(dim_metadata_src[metadata_idx + 1]))
262 dim_metadata_vec[i] =
263 tflite::CreateDimensionMetadata(*flatbuffer_builder, tflite::DimensionType_SPARSE_CSR, 0,
264 tflite::SparseIndexVector_Int32Vector, array_segments,
265 tflite::SparseIndexVector_Int32Vector, array_indices);
269 dim_metadata_vec[i] = tflite::CreateDimensionMetadata(
270 *flatbuffer_builder, tflite::DimensionType_DENSE, dim_metadata_src[metadata_idx][0]);
273 return dim_metadata_vec;
276template <
typename T>
void ModelChef::cook_operands(
const T &graph)
278 int32_t buffer_start = _buffer_vec.size();
279 int32_t buffer_index = 0;
282 const auto size_input =
graph.input_size();
283 for (
int ci = 0; ci < size_input; ++ci)
285 tflite::BufferBuilder buffer_builder{*_flatbuffer_builder};
286 _buffer_vec.emplace_back(buffer_builder.Finish());
289 const auto size_output =
graph.output_size();
290 for (
int co = 0; co < size_output; ++co)
292 tflite::BufferBuilder buffer_builder{*_flatbuffer_builder};
293 _buffer_vec.emplace_back(buffer_builder.Finish());
299 for (
const auto &operand :
graph.operand())
301 assert(operand.has_name());
302 assert(operand.has_type());
307 std::vector<int32_t> dims;
308 if (operand.has_shape())
310 dims =
as_dims(operand.shape());
311 shape = _flatbuffer_builder->CreateVector(dims);
314 auto name = _flatbuffer_builder->CreateString(operand.name());
319 if (operand.has_filler())
321 const auto &filler = operand.filler();
323 assert(filler.has_tag());
326 auto chef = data_chef_registry(operand.type()).lookup(filler.tag()).create(args);
328 assert(chef !=
nullptr);
332 auto data_vec = chef->generate(count);
334 if (operand.has_make_sparse() && operand.make_sparse())
336 assert(not operand.has_sparsity());
337 assert(operand.has_shape());
338 assert(operand.type() != tflchef::TensorType::INT4);
340 const int32_t dims_count = dims.size();
341 std::vector<int> traversal_order_vec;
342 std::vector<sparsity::TfLiteDimensionType> format_vec;
343 for (int32_t o = 0; o < dims_count; ++o)
344 traversal_order_vec.push_back(o);
345 for (int32_t o = 0; o < dims_count - 1; ++o)
349 if (operand.type() == tflchef::FLOAT32)
352 converter.DenseToSparse(
reinterpret_cast<const float *
>(data_vec.data()));
353 const auto &sparse_data = converter.GetData();
355 std::vector<uint8_t> sparse_uint8;
356 for (
int c = 0; c < sparse_data.size(); ++c)
358 const float value = sparse_data.at(c);
359 const uint8_t *
arr =
reinterpret_cast<const uint8_t *
>(&value);
360 for (uint32_t b = 0;
b <
sizeof(float); ++
b)
362 sparse_uint8.emplace_back(arr[b]);
367 buffer_index = _buffer_vec.size();
368 _buffer_data_map[buffer_index] = sparse_uint8;
370 auto buffer = tflite::CreateBuffer(*_flatbuffer_builder, 0, 1, 1);
371 _buffer_vec.emplace_back(buffer);
375 auto data = _flatbuffer_builder->CreateVector(sparse_uint8);
377 tflite::BufferBuilder buffer_builder{*_flatbuffer_builder};
378 buffer_builder.add_data(data);
379 auto buffer = buffer_builder.Finish();
382 buffer_index = _buffer_vec.size();
383 _buffer_vec.emplace_back(buffer);
387 auto traversal_order = _flatbuffer_builder->CreateVector(traversal_order_vec);
390 std::vector<int> block_map_vec{};
391 auto block_map = _flatbuffer_builder->CreateVector(block_map_vec);
394 const auto &dim_metadata_src = converter.GetDimMetadata();
395 auto dim_metadata_vec =
396 make_dim_metadata_vec(_flatbuffer_builder.get(), dims_count, traversal_order_vec,
397 format_vec, dim_metadata_src);
398 auto dim_metadata = _flatbuffer_builder->CreateVector(dim_metadata_vec);
399 sparsity_index = tflite::CreateSparsityParameters(*_flatbuffer_builder, traversal_order,
400 block_map, dim_metadata);
402 else if (operand.type() == tflchef::FLOAT16)
405 converter.DenseToSparse(
reinterpret_cast<const uint16_t *
>(data_vec.data()));
406 const auto &sparse_data = converter.GetData();
408 std::vector<uint8_t> sparse_uint8;
409 for (
int c = 0; c < sparse_data.size(); ++c)
411 const uint16_t value = sparse_data.at(c);
412 const uint8_t *
arr =
reinterpret_cast<const uint8_t *
>(&value);
413 for (uint32_t b = 0;
b <
sizeof(uint16_t); ++
b)
415 sparse_uint8.emplace_back(arr[b]);
420 buffer_index = _buffer_vec.size();
421 _buffer_data_map[buffer_index] = sparse_uint8;
423 auto buffer = tflite::CreateBuffer(*_flatbuffer_builder, 0, 1, 1);
424 _buffer_vec.emplace_back(buffer);
428 auto data = _flatbuffer_builder->CreateVector(sparse_uint8);
431 tflite::BufferBuilder buffer_builder{*_flatbuffer_builder};
432 buffer_builder.add_data(data);
433 auto buffer = buffer_builder.Finish();
436 buffer_index = _buffer_vec.size();
437 _buffer_vec.emplace_back(buffer);
441 auto traversal_order = _flatbuffer_builder->CreateVector(traversal_order_vec);
444 std::vector<int> block_map_vec{};
445 auto block_map = _flatbuffer_builder->CreateVector(block_map_vec);
448 const auto &dim_metadata_src = converter.GetDimMetadata();
449 auto dim_metadata_vec =
450 make_dim_metadata_vec(_flatbuffer_builder.get(), dims_count, traversal_order_vec,
451 format_vec, dim_metadata_src);
452 auto dim_metadata = _flatbuffer_builder->CreateVector(dim_metadata_vec);
453 sparsity_index = tflite::CreateSparsityParameters(*_flatbuffer_builder, traversal_order,
454 block_map, dim_metadata);
458 throw std::runtime_error{
"NYI: unsupported operand type"};
464 if (operand.type() == tflchef::TensorType::INT4)
466 uint32_t packed = (count + 1) / 2;
467 std::vector<uint8_t> data_packed(packed);
468 for (uint32_t idx = 0; idx < packed; ++idx)
470 uint32_t sidx = idx * 2;
471 data_packed[idx] = data_vec[sidx++] & 0x0f;
473 data_packed[idx] |= data_vec[sidx] << 4;
475 data_vec = data_packed;
480 buffer_index = _buffer_vec.size();
481 _buffer_data_map[buffer_index] = data_vec;
483 auto buffer = tflite::CreateBuffer(*_flatbuffer_builder, 0, 1, 1);
484 _buffer_vec.emplace_back(buffer);
488 auto data = _flatbuffer_builder->CreateVector(data_vec);
491 tflite::BufferBuilder buffer_builder{*_flatbuffer_builder};
492 buffer_builder.add_data(data);
493 auto buffer = buffer_builder.Finish();
496 buffer_index = _buffer_vec.size();
497 _buffer_vec.emplace_back(buffer);
505 for (
auto it = input_names.begin(); it != input_names.end(); ++it, ++idx)
507 if (*it == operand.name())
509 buffer_index = buffer_start + idx;
513 if (buffer_index == 0)
516 for (
auto it = output_names.begin(); it != output_names.end(); ++it, ++idx)
518 if (*it == operand.name())
520 buffer_index = buffer_start + size_input + idx;
525 if (buffer_index == 0)
528 buffer_index = _buffer_vec.size();
530 tflite::BufferBuilder buffer_builder{*_flatbuffer_builder};
531 _buffer_vec.emplace_back(buffer_builder.Finish());
534 assert(buffer_index != 0);
539 if (operand.has_quant())
541 const auto &quant = operand.quant();
545 std::vector<float> quant_max_vec(quant.max_size());
546 std::vector<float> quant_min_vec(quant.min_size());
547 std::vector<float> quant_scale_vec(quant.scale_size());
548 std::vector<int64_t> quant_zero_point_vec(quant.zero_point_size());
550 for (uint32_t i = 0; i < quant.max_size(); ++i)
551 quant_max_vec.at(i) = quant.max(i);
552 for (uint32_t i = 0; i < quant.min_size(); ++i)
553 quant_min_vec.at(i) = quant.min(i);
554 for (uint32_t i = 0; i < quant.scale_size(); ++i)
555 quant_scale_vec.at(i) = quant.scale(i);
556 for (uint32_t i = 0; i < quant.zero_point_size(); ++i)
557 quant_zero_point_vec.at(i) = quant.zero_point(i);
559 auto quant_max = _flatbuffer_builder->CreateVector(quant_max_vec);
560 auto quant_min = _flatbuffer_builder->CreateVector(quant_min_vec);
561 auto quant_scale = _flatbuffer_builder->CreateVector(quant_scale_vec);
562 auto quant_zero_point = _flatbuffer_builder->CreateVector(quant_zero_point_vec);
565 tflite::QuantizationParametersBuilder quant_builder{*_flatbuffer_builder};
566 quant_builder.add_max(quant_max);
567 quant_builder.add_min(quant_min);
568 quant_builder.add_scale(quant_scale);
569 quant_builder.add_zero_point(quant_zero_point);
570 quant_builder.add_quantized_dimension(quant.quantized_dimension());
573 quant_index = quant_builder.Finish();
576 if (operand.has_sparsity())
578 const auto &
sparsity = operand.sparsity();
581 std::vector<int> traversal_order_vec{
sparsity.traversal_order().dim().begin(),
582 sparsity.traversal_order().dim().end()};
583 auto traversal_order = _flatbuffer_builder->CreateVector(traversal_order_vec);
586 std::vector<int> block_map_vec{
sparsity.block_map().dim().begin(),
588 auto block_map = _flatbuffer_builder->CreateVector(block_map_vec);
591 std::vector<flatbuffers::Offset<tflite::DimensionMetadata>> dim_metadata_vec;
592 auto recipe_dim_metadata =
sparsity.dim_metadata();
593 for (
const auto &dm : recipe_dim_metadata)
596 auto tflite_array_segments =
600 auto tflite_array_indices =
603 auto tflite_dim_metadata_builder = tflite::DimensionMetadataBuilder{*_flatbuffer_builder};
605 tflite_dim_metadata_builder.add_dense_size(dm.dense_size());
606 tflite_dim_metadata_builder.add_array_segments(tflite_array_segments);
607 tflite_dim_metadata_builder.add_array_segments_type(
609 tflite_dim_metadata_builder.add_array_indices(tflite_array_indices);
610 tflite_dim_metadata_builder.add_array_indices_type(
612 auto tflite_dim_metadata = tflite_dim_metadata_builder.Finish();
613 dim_metadata_vec.emplace_back(tflite_dim_metadata);
615 auto dim_metadata = _flatbuffer_builder->CreateVector(dim_metadata_vec);
617 sparsity_index = tflite::CreateSparsityParameters(*_flatbuffer_builder, traversal_order,
618 block_map, dim_metadata);
622 if (operand.has_shape_signature())
624 auto signature =
as_dims(operand.shape_signature());
625 shape_signature = _flatbuffer_builder->CreateVector(signature);
629 tflite::TensorBuilder tensor_builder{*_flatbuffer_builder};
631 tensor_builder.add_shape(shape);
633 tensor_builder.add_buffer(buffer_index);
634 tensor_builder.add_name(name);
635 tensor_builder.add_is_variable(operand.is_variable());
636 if (operand.has_quant())
637 tensor_builder.add_quantization(quant_index);
638 tensor_builder.add_sparsity(sparsity_index);
639 if (operand.has_shape_signature())
640 tensor_builder.add_shape_signature(shape_signature);
643 _tensor_vec.emplace_back(tensor_builder.Finish());
648void ModelChef::cook_operations(
const T &graph, std::map<std::string, int32_t> &symbol_table)
650 auto lookup = [&](
const std::string &name) {
651 if (symbol_table.find(name) != symbol_table.end())
652 return symbol_table.at(name);
657 std::string msg =
"tflchef : input not found in " + _graph_name +
" graph";
658 throw std::runtime_error(msg.c_str());
663 for (
const auto &operation :
graph.operation())
665 assert(operation.has_type());
667 std::string op_type = operation.type();
668 if (not operation.custom_code().empty())
669 op_type = operation.custom_code();
671 auto op_chef = op_chef_registry().lookup(op_type).create(&operation);
674 std::vector<int32_t> input_vec =
as_dataset(operation.input()).map(lookup).vectorize();
675 auto inputs = _flatbuffer_builder->CreateVector(input_vec);
678 std::vector<int32_t> output_vec =
as_dataset(operation.output()).map(lookup).vectorize();
679 auto outputs = _flatbuffer_builder->CreateVector(output_vec);
682 auto options = op_chef->value(*_flatbuffer_builder);
688 tflite::OperatorBuilder
op_builder{*_flatbuffer_builder};
692 uint32_t opcode_index = 0;
693 auto op_it = _builtin_code_map.find(op_chef->code());
695 if (op_it != _builtin_code_map.end())
697 opcode_index = std::distance(_builtin_code_map.begin(), op_it);
702 assert(not operation.custom_code().empty());
703 const auto &custom_code = operation.custom_code();
704 auto op_it = std::find(_custom_code_vec.begin(), _custom_code_vec.end(), custom_code);
705 assert(op_it != _custom_code_vec.end());
706 opcode_index = _builtin_code_map.size();
707 opcode_index += std::distance(_custom_code_vec.begin(), op_it);
713 op_builder.add_builtin_options_type(op_chef->type());
715 op_builder.add_custom_options(circle_custom_options);
716 op_builder.add_custom_options_format(tflite::CustomOptionsFormat_FLEXBUFFERS);
718 _operator_vec.emplace_back(
op_builder.Finish());
723void ModelChef::cook_graph(
const T &graph, std::map<std::string, int32_t> &symbol_table)
727 assert(symbol_table.empty());
728 assert(_tensor_vec.empty());
729 assert(_operator_vec.empty());
732 if (
graph.has_name())
733 _graph_name =
graph.name();
735 auto lookup = [&](
const std::string &name) {
736 if (symbol_table.find(name) != symbol_table.end())
737 return symbol_table.at(name);
742 std::string msg =
"tflchef : input not found in " + _graph_name +
" graph";
743 throw std::runtime_error(msg.c_str());
747 cook_operands(graph);
749 for (
const auto &operand :
graph.operand())
752 int32_t tensor_index = symbol_table.size();
755 INFO(l) <<
"Symbol [" <<
tensor_name <<
"] = Tensor " << tensor_index << std::endl;
760 cook_operations(graph, symbol_table);
763 std::vector<int32_t> input_vec =
as_dataset(
graph.input()).map(lookup).vectorize();
764 std::vector<int32_t> output_vec =
as_dataset(
graph.output()).map(lookup).vectorize();
767 auto tensors = _flatbuffer_builder->CreateVector(_tensor_vec);
768 auto inputs = _flatbuffer_builder->CreateVector(input_vec);
769 auto outputs = _flatbuffer_builder->CreateVector(output_vec);
770 auto operators = _flatbuffer_builder->CreateVector(_operator_vec);
771 auto name = _flatbuffer_builder->CreateString(_graph_name);
773 tflite::SubGraphBuilder subgraph_builder{*_flatbuffer_builder};
775 subgraph_builder.add_tensors(tensors);
776 subgraph_builder.add_inputs(inputs);
777 subgraph_builder.add_outputs(outputs);
778 subgraph_builder.add_operators(operators);
779 subgraph_builder.add_name(name);
781 _subgraph_vec.emplace_back(subgraph_builder.Finish());
784void ModelChef::gather_operator_codes(const ::tflchef::ModelRecipe &model_recipe)
787 _builtin_code_map = gather_builtincode_map(model_recipe);
788 for (
auto const &opcode : _builtin_code_map)
790 tflite::OperatorCodeBuilder code_builder{*_flatbuffer_builder};
795 if (opcode.first < 127)
797 code_builder.add_deprecated_builtin_code(opcode.first);
801 code_builder.add_deprecated_builtin_code(
802 ::tflite::BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES);
804 code_builder.add_version(opcode.second);
805 code_builder.add_builtin_code(opcode.first);
806 auto code = code_builder.Finish();
808 _code_vec.emplace_back(code);
813 std::set<std::string> custom_code_set = gather_customcode_set(model_recipe);
814 std::vector<std::string> custom_code_vec{custom_code_set.begin(), custom_code_set.end()};
815 _custom_code_vec = custom_code_vec;
818 for (
const auto &opcode : _custom_code_vec)
820 auto custom_code = _flatbuffer_builder->CreateString(opcode);
821 tflite::OperatorCodeBuilder code_builder{*_flatbuffer_builder};
822 code_builder.add_deprecated_builtin_code(tflite::BuiltinOperator_CUSTOM);
823 code_builder.add_custom_code(custom_code);
824 code_builder.add_builtin_code(tflite::BuiltinOperator_CUSTOM);
825 auto code = code_builder.Finish();
827 _code_vec.emplace_back(code);
831void ModelChef::prepare_initial_buffer(
void)
837 tflite::BufferBuilder buffer_builder{*_flatbuffer_builder};
838 _buffer_vec.emplace_back(buffer_builder.Finish());
841void ModelChef::gather_signature_defs(const ::tflchef::ModelRecipe &model_recipe)
843 for (
int s = 0;
s < model_recipe.signature_def_size(); ++
s)
846 const auto &rec_signature_def = model_recipe.signature_def(s);
848 std::vector<flatbuffers::Offset<::tflite::TensorMap>> tensormap_inputs;
849 std::vector<flatbuffers::Offset<::tflite::TensorMap>> tensormap_outputs;
852 auto subgraph_index = 0;
853 if (rec_signature_def.has_subgraph_index())
855 subgraph_index = rec_signature_def.subgraph_index();
857 assert(subgraph_index < _symbol_tables.size());
858 auto &symbol_table = _symbol_tables[subgraph_index];
861 for (
int si = 0; si < rec_signature_def.inputs_size(); ++si)
864 const auto &rec_tm_input = rec_signature_def.inputs(si);
865 auto name = _flatbuffer_builder->CreateString(rec_tm_input.name());
866 uint32_t tensor_index = 0;
868 assert(rec_tm_input.has_tensor() || rec_tm_input.has_tensor_index());
869 if (rec_tm_input.has_tensor())
872 const auto &
tensor = rec_tm_input.tensor();
873 tensor_index = symbol_table[
tensor];
878 tensor_index = rec_tm_input.tensor_index();
881 ::tflite::TensorMapBuilder tensormap_builder{*_flatbuffer_builder};
882 tensormap_builder.add_name(name);
883 tensormap_builder.add_tensor_index(tensor_index);
884 tensormap_inputs.push_back(tensormap_builder.Finish());
887 for (
int so = 0; so < rec_signature_def.outputs_size(); ++so)
889 const auto &rec_tm_output = rec_signature_def.outputs(so);
890 auto name = _flatbuffer_builder->CreateString(rec_tm_output.name());
891 uint32_t tensor_index = 0;
892 assert(rec_tm_output.has_tensor() || rec_tm_output.has_tensor_index());
893 if (rec_tm_output.has_tensor())
895 const auto &
tensor = rec_tm_output.tensor();
896 tensor_index = symbol_table[
tensor];
900 tensor_index = rec_tm_output.tensor_index();
903 ::tflite::TensorMapBuilder tensormap_builder{*_flatbuffer_builder};
904 tensormap_builder.add_name(name);
905 tensormap_builder.add_tensor_index(tensor_index);
906 tensormap_outputs.push_back(tensormap_builder.Finish());
909 auto inputs = _flatbuffer_builder->CreateVector(tensormap_inputs);
910 auto outputs = _flatbuffer_builder->CreateVector(tensormap_outputs);
911 auto signature_key = _flatbuffer_builder->CreateString(rec_signature_def.signature_key());
914 ::tflite::SignatureDefBuilder signature_def_builder{*_flatbuffer_builder};
915 signature_def_builder.add_inputs(inputs);
916 signature_def_builder.add_outputs(outputs);
917 signature_def_builder.add_signature_key(signature_key);
918 signature_def_builder.add_subgraph_index(rec_signature_def.subgraph_index());
920 _signdef_vec.emplace_back(signature_def_builder.Finish());
924bool ModelChef::finalize_ext_buffer(
void)
929 auto align16 = [](
size_t &v) {
935 size_t result_size = _flatbuffer_builder->GetSize();
936 align16(result_size);
937 for (
auto &it : _buffer_data_map)
939 std::vector<uint8_t> &buffer_data = it.second;
940 result_size += buffer_data.size();
941 align16(result_size);
943 align16(result_size);
947 auto *buff_ptr =
reinterpret_cast<const char *
>(_flatbuffer_builder->GetBufferPointer());
949 auto padalign16 = [](std::string &
str) {
950 while (
str.size() % 16 != 0)
954 result.reserve(result_size);
955 result.append(buff_ptr, _flatbuffer_builder->GetSize());
957 auto mutable_model = tflite::GetMutableModel(
result.data());
958 auto mutable_buffers = mutable_model->mutable_buffers();
962 for (
auto &it : _buffer_data_map)
964 int32_t buffer_index = it.first;
965 std::vector<uint8_t> &buffer_data = it.second;
967 uint64_t
size = buffer_data.size();
969 tflite::Buffer *mutable_buffer = mutable_buffers->GetMutableObject(buffer_index);
970 ret &= mutable_buffer->mutate_offset(
offset);
971 ret &= mutable_buffer->mutate_size(
size);
973 result.append(buffer_data.begin(), buffer_data.end());
984void ModelChef::cook(const ::tflchef::ModelRecipe &model_recipe)
987 _ext_offset = model_recipe.has_ext_offset() ? model_recipe.ext_offset() :
false;
989 prepare_initial_buffer();
991 gather_operator_codes(model_recipe);
997 _graph_name =
"main";
999 std::map<std::string, int32_t> symbol_table;
1000 cook_graph<::tflchef::ModelRecipe>(model_recipe, symbol_table);
1001 _symbol_tables.push_back(symbol_table);
1006 for (
int g = 0;
g < model_recipe.graph_size(); ++
g)
1008 const auto &
graph = model_recipe.graph(g);
1010 std::ostringstream stringStream;
1011 stringStream <<
"sub_" << (
g + 1);
1013 _graph_name = stringStream.str();
1015 symbol_table.clear();
1016 _tensor_vec.clear();
1017 _operator_vec.clear();
1018 cook_graph<::tflchef::Graph>(graph, symbol_table);
1019 _symbol_tables.push_back(symbol_table);
1022 gather_signature_defs(model_recipe);
1025 auto buffers = _flatbuffer_builder->CreateVector(_buffer_vec);
1026 auto signdefs = _flatbuffer_builder->CreateVector(_signdef_vec);
1027 auto operator_codes = _flatbuffer_builder->CreateVector(_code_vec);
1028 auto subgraphs = _flatbuffer_builder->CreateVector(_subgraph_vec);
1029 auto description = _flatbuffer_builder->CreateString(
"Generated by tflchef");
1032 tflite::ModelBuilder model_builder{*_flatbuffer_builder};
1034 model_builder.add_version(3);
1035 model_builder.add_operator_codes(operator_codes);
1036 model_builder.add_signature_defs(signdefs);
1037 model_builder.add_subgraphs(subgraphs);
1038 model_builder.add_description(description);
1039 model_builder.add_buffers(buffers);
1041 auto model = model_builder.Finish();
1044 ::tflite::FinishModelBuffer(*_flatbuffer_builder, model);
1047 finalize_ext_buffer();
1050const char *ModelChef::get_buffer_pointer(
void)
const
1053 return _ext_data.data();
1054 return reinterpret_cast<const char *
>(_flatbuffer_builder->GetBufferPointer());
1057size_t ModelChef::get_size(
void)
const
1060 return _ext_data.size();
1061 return _flatbuffer_builder->GetSize();
1072 GeneratedModelImpl()
1078 const char *
base(
void)
const override {
return _mc.get_buffer_pointer(); }
1080 size_t size(
void)
const override {
return _mc.get_size(); }
1083 ModelChef &model_chef(
void) {
return _mc; }
1097GeneratedModel
cook(const ::tflchef::ModelRecipe &model_recipe)
1100#define OP_CHEF(NAME, FACTORY_CLASS) \
1101 op_chef_registry().add(#NAME, std::unique_ptr<FACTORY_CLASS>(new FACTORY_CLASS()));
1102#include "OpChef.def"
1106#define DATA_CHEF(TYPE, NAME, FACTORY_CLASS) \
1107 data_chef_registry(::tflchef::TYPE) \
1108 .add(#NAME, std::unique_ptr<FACTORY_CLASS>(new FACTORY_CLASS()));
1109#include "DataChef.def"
1112 std::unique_ptr<GeneratedModelImpl> gen_model(
new GeneratedModelImpl());
1114 ModelChef &mc = gen_model->model_chef();
1117 mc.cook(model_recipe);
1120 return GeneratedModel{std::move(gen_model)};
OpBuilder op_builder(coco::Module *m)
Helper class to hold data needed in creation of a FlatBuffer. To serialize data, you typically call o...
Offset< Vector< T > > CreateVector(const T *v, size_t len)
Serialize an array into a FlatBuffer vector.
__global uchar * offset(const Image *img, int x, int y)
GeneratedModel cook(const ModelRecipe &model_recipe)
Code * code(const SessionID &sess)
flatbuffers::Offset< flatbuffers::Vector< uint8_t > > circle_custom_options(flatbuffers::FlatBufferBuilder &fb, const luci::CircleNode *node)
const char * tensor_name(const circle::Tensor *tensor)
This file provides string <-> number cast helpers.
Dims< int32_t > as_dims(const SHAPETYPE &shape)
Dataset< T > as_dataset(const ::google::protobuf::RepeatedPtrField< T > &field)
RangedArguments< InputIt > ranged_arguments(InputIt beg, InputIt end)
int32_t element_count(const Dims< int32_t > &dims)
GeneratedModel cook(const ModelRecipe &model_recipe)
virtual size_t size(void) const =0
virtual const char * base(void) const =0
tflite::DimensionType as_tflite_dimensiontype(const tflchef::DimensionType &value)
tflite::SparseIndexVector as_tflite_sparse_idx_vec_type(const tflchef::SparseIndexVecType &value)
flatbuffers::Offset< void > as_tflite_sparse_index_vec(flatbuffers::FlatBufferBuilder &fb, const ::tflchef::TensorSparsity_IndexVec &value)
tflite::TensorType as_tflite_tensortype(const tflchef::TensorType &value)