19 std::default_delete<ROperator>()(ptr);
28const std::string
SP =
" ";
30void ReplaceAll(std::string &str,
const std::string &from,
const std::string &to)
33 while ((pos = str.find(from, pos)) != std::string::npos) {
34 str.replace(pos, from.length(), to);
39bool IsIdentifierChar(
char c)
41 return std::isalnum(
static_cast<unsigned char>(
c)) ||
c ==
'_';
47bool IsIdentifier(
const std::string &s)
49 if (s.empty() || std::isdigit(
static_cast<unsigned char>(s[0])))
52 if (!IsIdentifierChar(
c))
58std::string TensorMember(std::string
const &
name)
60 return "tensor_" +
name;
65std::string SafetensorsDType(ETensorType
type)
73 " cannot be written to a safetensors file");
79std::string JsonEscape(
const std::string &s)
82 out.reserve(s.size() + 2);
83 for (
const char c : s) {
85 case '"': out +=
"\\\"";
break;
86 case '\\': out +=
"\\\\";
break;
88 if (
static_cast<unsigned char>(
c) < 0x20) {
90 std::snprintf(buf,
sizeof(buf),
"\\u%04x",
c);
103 return static_cast<std::underlying_type_t<Options>
>(opA) |
static_cast<std::underlying_type_t<Options>
>(opB);
105std::underlying_type_t<Options>
operator|(std::underlying_type_t<Options> opA,
Options opB) {
106 return opA |
static_cast<std::underlying_type_t<Options>
>(opB);
112 return f->second.shape;
116 return f2->second.shape();
120 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] is an input tensor with unspecified dimension parameter");
124 return f4->second.shape;
130 if (f5->second.second)
131 return std::vector<size_t>{};
133 return std::vector<size_t>{f5->second.first.size()};
137 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] is a dynamic tensor. Use GetDynamicTensorShape instead of GetTensorShape");
142 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the shape is requested is not found");
147 return f->second.shape;
150 return f->second.shape;
158 return f->second.shape;
161 return f->second.shape;
165 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the shape is requested is not dynamic");
167 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the shape is requested is not found");
173 return f->second.type;
177 return f2->second.type();
181 return f3->second.type;
185 return f4->second.type;
189 return f5->second.type;
199 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the type is requested is not found, model name: " +
fName);
216 throw std::runtime_error(
"TMVA-SOFIE: input tensor with name " + input_name +
" already exists \n");
226 throw std::runtime_error(
"TMVA-SOFIE: input tensor with name " + input_name +
" already exists \n");
239 auto libs = op->GetStdLibs();
240 auto op_input_tensors = op->GetOpInputTensors();
241 for (
auto &stdlib : libs) {
245 std::unique_ptr<ROperator, ROperatorDeleter> opStored(op.release());
246 if (order_execution >= 0) {
263 std::cout <<
"adding order execution for " << op_input_tensors[
index] <<
" order " << order_execution
273 throw std::runtime_error(
"TMVA-SOFIE: initialized tensor with name " + tensor_name +
" already exists \n");
280 const std::vector<std::size_t> &shape,
void *raw_data)
284 std::shared_ptr<void>
data(malloc(
size * itemsize), free);
285 std::memcpy(
data.get(), raw_data,
size * itemsize);
293 throw std::runtime_error(
"TMVA-SOFIE: constant tensor with name " + tensor_name +
" already exists \n");
302 throw std::runtime_error(
"TMVA-SOFIE: shape tensor with name " + tensor_name +
" already exists \n");
304 fShapeTensors[tensor_name] = std::make_pair(shape_values, scalar);
316 throw std::runtime_error(
"TMVA-SOFIE: alias tensor with name " + tensor_name +
" already exists \n");
320 origin_name = it->second;
364 return itr->second.IsConstantTensor();
385 if (!int_shape.empty())
394 throw std::runtime_error(
"TMVA-SOFIE: intermediate tensor with name " + tensor_name +
" already exists \n");
403 throw std::runtime_error(
"TMVA-SOFIE: intermediate tensor with name " + tensor_name +
" already exists \n");
408 for (
auto &
d : shape) {
410 if (
d.dim !=
size_t(-1)) {
439 for(
auto& it : outputtensornames) {
445 for(
auto& it:curr_output_tensors) {
454 throw std::runtime_error(
"TMVA-SOFIE: tensor " + tensor_name +
" not found when trying to update it");
463 throw std::runtime_error(
"TMVA-SOFIE: tensor " + tensor_name +
" not found when trying to get its data");
465 return f->second.sharedptr();
472 throw std::runtime_error(
"TMVA-SOFIE: initialized tensor " + tensor_name +
" not found when trying to get its info");
474 t->second.SetNotWritable();
479 std::stringstream code;
482 std::cout <<
"Total chunks allocated\n";
484 std::cout <<
"..... chunk " << chunk->first <<
" size " << chunk->second.tensor_size <<
" " << chunk->second.tensor_name << std::endl;
488 auto declareIntermediateTensor = [
this, &code](std::string
const &
name,
size_t size,
size_t location) {
490 code <<
"\n // Allocating memory for intermediate tensor " <<
name <<
" with size " <<
size <<
" bytes";
492 << typeName <<
"* " << TensorMember(
name) <<
" = reinterpret_cast<" << typeName
493 <<
"*>(fIntermediateMemoryPool.data() + " << location <<
");\n";
496 if (
fVerbose) std::cout <<
"*** AllocateIntermediateMemory: Loop on op output tensors\n";
498 std::vector<TensorMemoryInfo> ordered_output_tensors;
500 for (
auto &it : op_output_tensors) {
501 auto name = std::string(it);
514 ordered_output_tensors.push_back(tmi);
516 std::sort(ordered_output_tensors.begin(), ordered_output_tensors.end(),
519 for (
auto &it : ordered_output_tensors) {
520 bool allocated =
false;
521 std::string
name = std::string{it.tensor_name};
522 size_t tensor_size = it.tensor_size;
524 std::cout <<
"output tensor " <<
name <<
" size " << tensor_size << std::endl;
529 if (
fVerbose) std::cout <<
".. available chunk " << chunk->first <<
" with size = " << chunk->second;
531 if (chunk->second >= tensor_size) {
535 auto new_chunk_location = chunk->first + chunk->second - tensor_size;
538 declareIntermediateTensor(
name, tensor_size, new_chunk_location);
539 chunk->second -= tensor_size;
543 if (
fVerbose) std::cout <<
" is re-used and split in a new of size " << new_chunk.tensor_size <<
" at " << new_chunk_location;
545 if (chunk->second == 0) {
546 if (
fVerbose) std::cout <<
" and deleted since size matches";
549 if (
fVerbose) std::cout << std::endl;
555 declareIntermediateTensor(
name, tensor_size, chunk->first);
558 if (
fVerbose) std::cout <<
" is extended with a bigger one of size " << tensor_size << std::endl;
562 if (
fVerbose) std::cout << std::endl;
573 declareIntermediateTensor(
name, tensor_size, chunk_idx);
575 if (
fVerbose) std::cout <<
"no chunk available - add in total stack a new chunk with size of tensor and idx : " << chunk_idx
583 if (
fVerbose) std::cout <<
"*** CheckAndFlushIntermediateMemory: Loop on input tensors for op " << op_idx <<
"\n";
585 if (
fVerbose) std::cout <<
"available chunks before freeing them : \n";
588 if (
fVerbose) std::cout <<
"-- free chunk " << chunk->first <<
" size = " << chunk->second << std::endl;
590 for (
auto &iv : op_input_tensors) {
592 if (
fVerbose) std::cout <<
".. input tensors : " << iv;
601 if (
fVerbose) std::cout <<
" flash condition is met - looping on chunks to find matching one \n";
604 if (
fVerbose) std::cout <<
"--- chunk " << chunk->first <<
" , " << chunk->second.tensor_name <<
" size " << chunk->second.tensor_size;
605 if (chunk->second.tensor_name == it) {
606 if (
fVerbose) std::cout <<
" -- Found chunk corresponding to input tensor: " << chunk->first;
612 : std::prev(first_greater);
617 last_smaller->first + last_smaller->second == chunk->first) {
619 last_smaller->second += chunk->second.tensor_size;
621 if (
fVerbose) std::cout <<
" is adjacent in memory with previous one - merge ";
623 last_smaller->first + last_smaller->second == first_greater->first) {
625 last_smaller->second += first_greater->second;
631 if (
fVerbose) std::cout <<
" merge also with following that is free ";
634 if (
fVerbose) std::cout << std::endl;
637 chunk->first + chunk->second.tensor_size == first_greater->first) {
639 if (
fVerbose) std::cout <<
" is adjacent in memory with following one - merge \n";
641 size_t new_size = chunk->second.tensor_size + first_greater->second;
642 size_t first_greater_idx = first_greater->first;
651 if (
fVerbose) std::cout <<
" insert in the available stack the chunk with size " << chunk->second.tensor_size << std::endl;
653 chunk->second.tensor_name =
"free";
658 if (
fVerbose) std::cout << std::endl;
664 std::map<std::string, size_t> inputParams;
666 inputParams[
"input_size"] = batchSize;
667 inputParams[
"batch_size"] = batchSize;
668 inputParams[
"bs"] = batchSize;
679 std::cout <<
"Model is already initialized - skip initialization " << std::endl;
694 auto found = originalInputTensorInfos.find(inputName);
695 if (found == originalInputTensorInfos.end())
697 auto &
input = *found;
698 if (verbose) std::cout <<
"looking at the tensor " <<
input.first << std::endl;
700 if (!inputParams.empty()) {
701 for (
auto &
d :
input.second.shape) {
703 std::string pname =
d.param;
704 if (pname ==
input.first +
"_size") pname =
"input_size";
705 auto itr = inputParams.find(pname);
706 if (itr != inputParams.end() ) {
707 d =
Dim{ itr->second };
709 std::cout <<
"Tensor: " <<
input.first <<
" - fix parametric shape " << itr->first <<
" to " << itr->second << std::endl;
719 if (!shape.empty()) {
731 for (
auto &
d :
input.second.shape) {
748 std::vector<size_t> temp_available_stack;
751 std::unordered_set<std::string> runtimeInitializedInputs;
752 for(
size_t op_idx = 0; op_idx <
fOperators.size(); ++op_idx){
755 std::cout <<
"Initializing operator " << i <<
" " <<
typeid(
r).
name() << std::endl;
758 for(
auto &it:
fOperators[op_idx]->GetOpOutputTensors()){
759 std::string
name = std::string{it};
769 if (!
fOperators[op_idx]->IsOutputConstant()) {
770 for (
auto &it :
fOperators[op_idx]->GetOpInputTensors()) {
771 std::string
name = std::string{it};
773 runtimeInitializedInputs.insert(
name);
786 if (it.second.IsNotWritable() && runtimeInitializedInputs.find(it.first) != runtimeInitializedInputs.end()) {
787 it.second.SetWritable();
789 std::cout <<
"Initialized tensor " << it.first <<
" is flagged as not writable but is used by non constant operators, set it as writable \n";
795 it.second.SetConstant();
801 bool modelHasWeights =
false;
803 if (it.second.IsWeightTensor()) {
804 modelHasWeights =
true;
808 if (!modelHasWeights)
830 graph->fParentGraph =
this;
831 graph->fIsSubGraph =
true;
837 bool graphHasWeights =
false;
838 for (
auto &it : graph->fInitializedTensors) {
839 if (it.second.IsWeightTensor()) {
840 graphHasWeights =
true;
846 std::vector<std::string> blasRoutines;
847 for (
auto &
e : graph->fNeededBlasRoutines)
848 blasRoutines.push_back(
e);
850 for (
auto e : graph->fNeededStdLib)
854 for (
auto const &
h : graph->GetNeededHelperFunctions())
859 graph->fInputTensorNames.emplace_back(
name);
871 std::stringstream strs;
876 bool allocateOnStack = (
length > 100 || t.second.IsWeightTensor()) ?
false :
true;
878 const T *
data = t.second.data<T>();
881 bool sameData =
false;
884 if (!allocateOnStack &&
length > 1) {
887 sameData = (
data[idx] ==
data[idx - 1]);
889 }
while (sameData && idx <
length);
891 if (allocateOnStack) {
893 strs <<
type <<
" * " << TensorMember(t.first) <<
" = fTensor_" + t.first +
";\n";
895 strs <<
"std::vector<" <<
type <<
"> fTensor_" << t.first <<
" = ";
901 strs <<
type <<
" * " << TensorMember(t.first) <<
" = fTensor_" + t.first +
".data();\n";
909 fGC +=
"// initialized (weights and constant) tensors\n";
913 if (i.second.IsNotWritable())
continue;
918 bool hasInfOrNaN =
false;
919 const float *
data = i.second.data<
float>();
920 for (
size_t idx = 0; idx <
length; idx++) {
921 if (std::is_floating_point<float>::value) {
922 if (std::isinf(
data[idx]) || std::isnan(
data[idx])) {
930 fGC += GenerateConstantTensorCode<float>(i);
933 fGC += GenerateConstantTensorCode<int64_t>(i);
936 fGC += GenerateConstantTensorCode<int32_t>(i);
939 fGC += GenerateConstantTensorCode<uint8_t>(i);
947 fGC +=
"std::vector<float> fTensor_" + i.first +
" = std::vector<float>(" + std::to_string(
length) +
");\n";
948 fGC +=
"float * " + TensorMember(i.first) +
" = fTensor_" + i.first +
".data();\n";
957 fGC +=
"\n//--- Allocating session memory pool to be used for allocating intermediate tensors\n";
962 const size_t memPoolSize = totalStack.rbegin()->first + totalStack.rbegin()->second.tensor_size;
963 fGC +=
"std::vector<char> fIntermediateMemoryPool = std::vector<char>(" + std::to_string(memPoolSize) +
");\n\n";
968 std::string tensor_declaration_block =
"";
975 tensor_declaration_block +=
"std::vector<std::uint8_t> fTensor_" + i.first +
976 " = std::vector<std::uint8_t>(" +
978 tensor_declaration_block +=
979 "std::uint8_t * " + TensorMember(i.first) +
" = fTensor_" + i.first +
".data();\n";
983 bool not_in_freq_map =
985 bool not_in_output_names =
988 if ((not_in_freq_map && not_in_output_names) || (!not_in_freq_map && !is_extended && not_in_output_names)) {
992 tensor_declaration_block +=
"std::vector<float> fTensor_" + i.first +
" = std::vector<float>(" + std::to_string(
length) +
");\n";
993 tensor_declaration_block +=
"float * " + TensorMember(i.first) +
" = fTensor_" + i.first +
".data();\n";
997 tensor_declaration_block +=
"std::vector<double> fTensor_" + i.first +
" = std::vector<double>(" + std::to_string(
length) +
");\n";
998 tensor_declaration_block +=
"double * " + TensorMember(i.first) +
" = fTensor_" + i.first +
".data();\n";
1002 tensor_declaration_block +=
"std::vector<int64_t> fTensor_" + i.first +
" = std::vector<int64_t>(" + std::to_string(
length) +
");\n";
1003 tensor_declaration_block +=
"int64_t * " + TensorMember(i.first) +
" = fTensor_" + i.first +
".data();\n";
1009 if (tensor_declaration_block.length()) {
1010 fGC +=
"\n//--- declare and allocate the intermediate tensors\n" + tensor_declaration_block;
1015 fGC +=
"//--- declare the dynamic tensors\n";
1021 fGC +=
"//--- dynamic tensors pool\n";
1022 fGC +=
"std::vector<char> fDynamicMemoryPool;\n";
1028 std::string strcode;
1030 strcode += op->GenerateDeclCode();
1032 if (strcode.empty())
return;
1033 fGC +=
"\n//---- operator declarations \n";
1045 std::cout <<
"generating code for dynamic tensor management" << std::endl;
1052 std::stringstream out;
1053 out <<
"// dynamic tensor memory management\n";
1054 out <<
SP <<
"std::vector<TensorLifeInfo> dynamicTensorInfos;\n";
1059 std::vector<std::pair<std::string, ETensorType>> tensors;
1063 for (
auto &it : op->GetOpOutputTensors()) {
1065 auto op_ptr = op.get();
1066 std::cout <<
"Looping on operator " << op_index <<
" " <<
typeid(*op_ptr).name() << std::endl;
1069 std::string
name = std::string(it);
1075 int begin = op_index;
1080 end = it_lookup->second + 1;
1085 std::cout <<
"op " << op_index <<
"tensor_" <<
name <<
" begin " << begin <<
" " <<
" end " << end << std::endl;
1086 throw std::runtime_error(
"TMVA-SOFIE: RModel::GenerateDynamicTensorInfo: tensor_" +
name +
" has end before begin");
1090 out <<
SP <<
"dynamicTensorInfos.push_back( {" << begin <<
", " << end <<
", " << type_size <<
"* (" << tensor_size <<
") });"
1091 <<
" // tensor_" <<
name << std::endl;
1097 out <<
"\n" <<
SP <<
"auto memory_result = OrganizeMemory(dynamicTensorInfos);\n\n";
1098 out <<
"// allocating now the memory\n";
1099 out <<
SP <<
"fDynamicMemoryPool = std::vector<char>(memory_result.total_bytes);\n";
1100 out <<
SP <<
"int idx = 0;\n";
1101 for (
auto & it : tensors) {
1102 out <<
SP <<
"tensor_" << it.first <<
" = reinterpret_cast<" <<
ConvertTypeToString(it.second) <<
" *>(fDynamicMemoryPool.data() + memory_result.offsets[idx++]);\n";
1105 bool missingTensor =
false;
1109 if (std::find(tensors.begin(), tensors.end(), std::pair<std::string,ETensorType>{i.first, i.second.type}) == tensors.end()) {
1110 std::cout <<
"Dynamic tensors " << i.first <<
" is not in list of operator input/output " << std::endl;
1111 missingTensor =
true;
1115 throw std::runtime_error(
"TMVA-SOFIE: RModel::GenerateDynamicTensorInfo - some tensors are not in input/output list");
1122 std::vector<std::string> params;
1129 params.push_back(dim.param);
1146 for (
auto &
d : shape) {
1147 if (
d.param == paramName)
1161 const std::string
target =
"tensor_";
1163 std::vector<std::string>
result;
1165 for (
size_t i = 0; i <
input.size();) {
1167 bool doCollect =
false;
1170 (i == 0 || !IsIdentifierChar(
input[i - 1]))) {
1174 std::size_t j = i +
target.size();
1177 while (j <
input.size() && IsIdentifierChar(
input[j]))
1180 std::string fullName =
input.substr(i, j - i);
1201 result.push_back(fullName);
1221 std::unordered_map<std::string, int> inputParams;
1227 for (
auto &
d : shape) {
1228 std::string pName =
d.param;
1230 if (
d.isParam && inputParams.count(pName) == 0) {
1231 if (isdecl) rGC +=
"size_t ";
1232 rGC +=
d.param +
",";
1233 inputParams[pName] = i_input;
1240 if (
type.rfind(
"other", 0) == 0)
1241 throw std::runtime_error(
"TMVA-SOFIE: input tensor " +
name +
1242 " is of a data type which is not yet supported.");
1243 rGC +=
type +
" const* ";
1245 rGC +=
"tensor_" +
name +
",";
1262std::string memberNameForDimShape(std::string
name)
1264 if (!
name.empty()) {
1265 name[0] = std::toupper(
static_cast<unsigned char>(
name[0]));
1278 bool sameOutputTypes =
true;
1279 std::string inferReturnType;
1282 if (outputSize == 1) {
1283 fGC +=
"std::vector<" + typeForOutput(eFirstOutputType) +
">";
1288 sameOutputTypes =
false;
1290 if (sameOutputTypes)
1291 fGC +=
"std::vector<std::vector<" + typeForOutput(eFirstOutputType) +
">>";
1293 inferReturnType =
"std::tuple<";
1294 for (
size_t i = 0; i < outputSize; i++) {
1296 if (i < outputSize - 1)
1297 inferReturnType +=
",";
1299 inferReturnType +=
">";
1300 fGC += inferReturnType;
1307 if (!doInferArgs.empty())
1310 std::unordered_set<std::string> emittedShapeParams;
1322 for (
auto &dim : dims) {
1324 dim.param = memberNameForDimShape(dim.param);
1328 std::string outputName =
"output_tensor_" +
name;
1330 doInferArgs +=
" " + outputName +
".data(),";
1334 emittedShapeParams.insert(dim.param).second) {
1335 fGC +=
SP +
"size_t " + dim.param +
" = 0;\n";
1336 doInferArgs +=
" " + dim.param +
",";
1341 if (!doInferArgs.empty())
1342 doInferArgs.back() =
' ';
1345 std::unordered_set<std::string> input_params_checked;
1346 std::string dynamic_parameters_check =
"";
1350 for (
auto &
d : shape) {
1351 std::string pName =
d.param;
1352 if (
d.isParam && input_params_checked.count(pName) == 0) {
1353 std::string memberName = memberNameForDimShape(
d.param);
1354 dynamic_parameters_check +=
d.param +
" > " + memberName +
" || ";
1355 input_params_checked.insert(pName);
1356 fGC +=
SP +
"if (" +
d.param +
" > " + memberName +
") {\n";
1357 fGC +=
SP +
SP +
"throw std::runtime_error(\"TMVA-SOFIE: dynamic input tensor shape parameter " +
1358 d.param +
" exceeds the initialized maximum allowed shape.\");\n";
1365 fGC +=
SP +
"doInfer(*this, " + doInferArgs +
");\n";
1371 std::string outputName =
"output_tensor_" +
name;
1373 fGC +=
SP + outputName +
".resize(" + tensor_size +
");\n";
1377 fGC +=
SP +
"return {";
1392 fGC +=
"struct " + sessionName +
";\n";
1396 if (!doInferSignature.empty())
1397 doInferSignature +=
", ";
1399 std::unordered_set<std::string> signatureShapeParams;
1406 signatureShapeParams.insert(dim.param).second)
1407 doInferSignature +=
" size_t &" + dim.param +
"_output,";
1411 doInferSignature.back() =
' ';
1413 doInferSignature = sessionName +
" const &session, " + doInferSignature;
1415 doInferSignature =
"inline void doInfer(" + doInferSignature +
")";
1418 fGC += doInferSignature +
";\n";
1424 std::string sessionCode = R
"(struct @SESSION@ {
1426 ~@SESSION@() = default;
1428 @SESSION@(@SESSION@ const&) = delete;
1429 @SESSION@(@SESSION@ &&) = default;
1431 @SESSION@& operator=(@SESSION@ const&) = delete;
1432 @SESSION@& operator=(@SESSION@ &&) = default;
1435 ReplaceAll(sessionCode, "@SESSION@", sessionName);
1443 std::string intermediate_memory_alloc_string =
"";
1444 intermediate_memory_alloc_string +=
"\n// --- Positioning intermediate tensor memory --";
1445 for (
size_t op_idx = 0; op_idx <
fOperators.size(); ++op_idx) {
1448 std::cout <<
"\n******************\n analyzing input/output operator " << op_idx <<
" "
1449 <<
typeid(*op).name() << std::endl;
1464 fGC += intermediate_memory_alloc_string;
1474 fGC +=
"\n// dynamic shape parameters\n";
1476 std::sort(dimShapeNames.begin(), dimShapeNames.end());
1477 for (
const auto &
p : dimShapeNames) {
1478 fGC +=
"size_t " + memberNameForDimShape(
p) +
";\n";
1485 fGC +=
"Session_" + graph->fName +
" fSession_" + graph->fName +
";\n";
1491 for (
size_t id = 0;
id <
fOperators.size();
id++) {
1492 std::string opName = std::to_string(
id);
1498 std::string dynParamDecls;
1499 std::string dynParamArgs;
1504 dynParamArgs +=
", " +
p;
1515 fGC +=
" static std::string LoadWeightsFromFile(const std::string &filename) {\n";
1516 fGC +=
" std::ifstream f(filename, std::ios::binary);\n";
1517 fGC +=
" if (!f.is_open()) {\n";
1518 fGC +=
" throw std::runtime_error(\"tmva-sofie failed to open file \" + filename + \" for input "
1521 fGC +=
" return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());\n";
1523 fGC += sessionName +
"(std::string filename =\"" +
fName +
".safetensors\"" + dynParamDecls +
")\n";
1524 fGC +=
" : " + sessionName +
"(SafetensorsBlob{LoadWeightsFromFile(filename)}" + dynParamArgs +
") {}\n\n";
1525 fGC += sessionName +
"(SafetensorsBlob weights_blob" + dynParamDecls +
") {\n";
1527 std::string fileName =
fName +
".dat";
1528 fGC += sessionName +
"(std::string filename =\"" + fileName +
"\"" + dynParamDecls +
") {\n";
1532 fGC += sessionName +
"(std::string = \"\"" + dynParamDecls +
") {\n";
1540 std::sort(dimShapeNames.begin(), dimShapeNames.end());
1541 for (
const auto &
p : dimShapeNames) {
1542 fGC +=
" " + memberNameForDimShape(
p) +
" = " +
p +
";\n";
1549 fGC +=
"\n//--- reading weights from file\n";
1559 for (
size_t id = 0;
id <
fOperators.size();
id++) {
1571 fGC += sessionName +
"(SafetensorsBlob" + dynParamDecls +
")\n";
1572 fGC +=
" : " + sessionName +
"(std::string{}" + dynParamArgs +
") {}\n\n";
1578 fGC +=
"// Set all weight and constant tensors to zero. This is useful to create\n"
1579 "// the tangent Session objects needed to differentiate the generated code\n"
1581 "void SetWeightsToZero() {\n";
1585 if (i.second.IsNotWritable() ||
1588 fGC +=
" for (auto &v : fTensor_" + i.first +
") v = 0;\n";
1591 fGC +=
" fSession_" + graph->fName +
".SetWeightsToZero();\n";
1599 fGC +=
"}; // end of Session\n\n";
1606 fGC += doInferSignature +
" {\n";
1611 std::cout <<
"Generating main inference code for " <<
fName << std::endl;
1614 throw std::runtime_error(
"TMVA-SOFIE: output size=0 are not supported");
1616 std::string allOperatorCode;
1618 for (
size_t op_idx = 0; op_idx <
fOperators.size(); ++op_idx) {
1620 std::cout <<
"Generating code for operator .... " << op_idx << std::endl;
1621 std::string operatorCode =
fOperators[op_idx]->Generate(std::to_string(op_idx));
1624 for (
auto const &outName :
fOperators[op_idx]->GetOpOutputTensors()) {
1625 std::string
name(outName);
1629 allOperatorCode += operatorCode;
1635 std::string expanded;
1636 std::istringstream lines(allOperatorCode);
1638 while (std::getline(lines,
line)) {
1640 if (pos == std::string::npos) {
1641 expanded +=
line +
"\n";
1646 expanded +=
SP +
"if (" + param +
" > session." + memberNameForDimShape(param) +
")\n" +
SP +
SP +
1647 "throw std::runtime_error(\"TMVA-SOFIE: shape parameter " + param +
1648 " exceeds the maximum allowed by the Session: pass a larger value to its constructor\");\n";
1651 allOperatorCode = expanded;
1656 ReplaceAll(allOperatorCode,
"this->",
"session.");
1660 const std::string prefix =
"tensor_";
1661 for (
auto const&
name: tensorMemberNames) {
1665 fGC +=
" auto &" +
name +
" = session." +
name +
";\n";
1675 std::string t =
"session.tensor_" +
name;
1677 fGC +=
" std::copy(" + t +
", " + t +
" + " + std::to_string(
length) +
", tensor_" +
name +
");\n";
1681 fGC += allOperatorCode;
1683 std::unordered_set<std::string> assignedShapeParams;
1689 assignedShapeParams.insert(dim.param).second)
1690 fGC +=
" " + dim.param +
"_output = " + dim.param +
";\n";
1726 std::cout <<
"generate session code for subgraph " << graph->fName << std::endl;
1727 graph->GenerateSessionCode();
1732 std::cout <<
"generate Main session code - model " <<
fName << std::endl;
1738 fGC += (
"} //TMVA_SOFIE_" +
fName +
"\n");
1739 fGC +=
"\n#endif // " + hgname +
"\n";
1753 fGC +=
" std::ifstream f;\n";
1754 fGC +=
" f.open(filename);\n";
1755 fGC +=
" if (!f.is_open()) {\n";
1756 fGC +=
" throw std::runtime_error(\"tmva-sofie failed to open file \" + filename + \" for input weights\");\n";
1765 if (!i.second.IsWeightTensor())
continue;
1766 std::string tensor_name =
"tensor_" + i.first;
1769 fGC +=
" ReadTensorFromStream(f, " + tensor_name +
", \"" + tensor_name +
"\", " +
length +
");\n";
1771 throw std::runtime_error(
"tmva-sofie tensor " + tensor_name +
" with type " +
ConvertTypeToString(i.second.type()) +
" cannot be read from a file");
1774 fGC +=
" f.close();\n";
1784 fGC +=
" SafetensorsReader sofie_weights_reader(weights_blob);\n";
1788 if (!i.second.IsWeightTensor())
1790 std::string tensor_name =
"tensor_" + i.first;
1793 dtype = SafetensorsDType(i.second.type());
1794 }
catch (
const std::runtime_error &) {
1795 throw std::runtime_error(
"tmva-sofie tensor " + tensor_name +
" with type " +
1797 " cannot be read from a safetensors payload");
1800 fGC +=
" sofie_weights_reader.Read(\"" + tensor_name +
"\", fTensor_" + i.first +
", " +
length +
", \"" +
1808 std::string fileExtension;
1811 fileExtension =
".dat";
1814 fileExtension =
".safetensors";
1817 fileExtension =
".dat";
1828 std::ofstream
f(
filename, std::ios::binary);
1830 throw std::runtime_error(
"tmva-sofie failed to open file " +
filename +
" for tensor weight data");
1834 long curr_pos =
f.tellp();
1842 std::runtime_error(
"tmva-sofie failed to open file " +
filename +
" for tensor weight data");
1845 if (!i.second.IsWeightTensor()) {
1849 std::string tensor_name =
"tensor_" + i.first;
1850 f << tensor_name <<
" " <<
length <<
"\n";
1852 const float *
data = i.second.data<
float>();
1853 for (
size_t idx = 0; idx <
length; idx++) {
1856 if (
value != 0. && std::abs(
value) < std::numeric_limits<float>::min() )
value = 0;
1858 if (std::isinf(
value))
1859 f << (
value > 0 ?
"inf" :
"-inf");
1860 else if (std::isnan(
value))
1863 f << std::setprecision(std::numeric_limits<float>::max_digits10) <<
value;
1864 f << ( (idx <
length-1) ?
" " :
"\n" );
1868 throw std::runtime_error(
"tmva-sofie tensor " + tensor_name +
" with type " +
ConvertTypeToString(i.second.type()) +
" cannot be written to a file");
1871 throw std::runtime_error(
"tmva-sofie failed to write tensor data to file for " + tensor_name);
1873 long curr_pos =
f.tellp();
1885 const std::uint16_t one = 1;
1886 if (!*
reinterpret_cast<const std::uint8_t *
>(&one))
1887 throw std::runtime_error(
"tmva-sofie: safetensors weights can only be written on a little-endian host");
1894 std::uint64_t
offset = 0;
1896 std::vector<std::string> names;
1899 if (item.second.IsWeightTensor())
1900 names.push_back(item.first);
1902 std::sort(names.begin(), names.end());
1903 std::string headerStr =
"{";
1904 for (
size_t idx = 0; idx < names.size(); ++idx) {
1909 headerStr +=
"\"" + JsonEscape(
"tensor_" + names[idx]) +
"\":{\"dtype\":\"" + SafetensorsDType(tensor.type()) +
1911 for (
size_t i = 0; i < tensor.shape().
size(); ++i) {
1914 headerStr += std::to_string(tensor.shape()[i]);
1916 headerStr +=
"],\"data_offsets\":[" + std::to_string(
offset) +
"," + std::to_string(
offset + nbytes) +
"]}";
1921 const std::uint64_t headerSize = headerStr.size();
1923 for (
int i = 0; i < 8; ++i)
1924 sizestr[i] =
static_cast<char>((headerSize >> (8 * i)) & 0xff);
1925 f.write(sizestr, 8);
1926 f.write(headerStr.data(), headerStr.size());
1927 for (
const auto &
name : names) {
1930 f.write(
reinterpret_cast<const char *
>(tensor.data<
void>()), nbytes);
1933 throw std::runtime_error(
"tmva-sofie failed to write safetensors payload");
1938 std::ostringstream buffer;
1940 return buffer.str();
1944 std::cout <<
"Summary of model " <<
GetName() << std::endl;
1945 for(
size_t op_idx = 0; op_idx <
fOperators.size(); ++op_idx){
1947 std::string raw_name =
typeid(
r).
name();
1949 std::string
name = raw_name.substr(raw_name.find(
"ROperator_")+10, raw_name.size());
1950 std::cout << op_idx <<
" " <<
name <<
" : ";
1951 for (
auto & t_in :
r.GetOpInputTensors()) std::cout << t_in <<
" ";
1952 std::cout <<
" ----> ";
1953 for (
auto & t_out :
r.GetOpOutputTensors()) std::cout << t_out <<
" ";
1954 std::cout << std::endl;
1962 fGC +=
"\n// Input tensor dimensions\n";
1965 bool hasDynamicInputTensors =
false;
1970 hasDynamicInputTensors =
true;
1973 fGC +=
"constexpr std::array<SingleDim, " + std::to_string(shape.size()) +
"> dim_" +
name +
"{";
1974 for (std::size_t iDim = 0; iDim < shape.size(); ++iDim) {
1975 auto const &dim = shape[iDim];
1977 fGC +=
"SingleDim{\"" + dim.GetVal() +
"\"}";
1979 fGC +=
"SingleDim{" + dim.GetVal() +
"}";
1981 if (iDim != shape.size() - 1) {
1987 fGC +=
"\nconstexpr std::array<TensorDims, " + std::to_string(
fInputTensorNames.size()) +
"> inputTensorDims{\n";
1990 fGC +=
SP +
"makeDims(dim_" +
name +
")";
2000 "\nconstexpr bool hasDynamicInputTensors{" + std::string{hasDynamicInputTensors ?
"true" :
"false"} +
"};\n\n";
2002 fGC +=
"\n// Output tensor dimensions\n";
2003 bool hasDynamicOutputTensors =
false;
2007 hasDynamicOutputTensors =
true;
2010 fGC +=
"constexpr std::array<SingleDim, " + std::to_string(shape.size()) +
"> dim_" +
name +
"{";
2011 for (std::size_t iDim = 0; iDim < shape.size(); ++iDim) {
2012 auto const &dim = shape[iDim];
2014 fGC +=
"SingleDim{\"" + dim.GetVal() +
"\"}";
2016 fGC +=
"SingleDim{" + dim.GetVal() +
"}";
2018 if (iDim != shape.size() - 1) {
2024 fGC +=
"\nconstexpr std::array<TensorDims, " + std::to_string(
fOutputTensorNames.size()) +
"> outputTensorDims{\n";
2027 fGC +=
SP +
"makeDims(dim_" +
name +
")";
2036 "\nconstexpr bool hasDynamicOutputTensors{" + std::string{hasDynamicOutputTensors ?
"true" :
"false"} +
"};\n\n";
2040 std::cout <<
"Model requires following inputs:\n";
2042 std::cout <<
"Parametrised Tensor name: " << inputInfo.first <<
"\t";
2044 std::cout <<
"shape: [";
2045 for (
size_t i = 0; i < inputInfo.second.shape.size(); i++) {
2046 if (inputInfo.second.shape[i].isParam) {
2047 std::cout << inputInfo.second.shape[i].param;
2049 std::cout << inputInfo.second.shape[i].dim ;
2051 if (i < inputInfo.second.shape.size() - 1) std::cout <<
",";
2053 std::cout <<
"]" << std::endl;
2057 std::cout <<
"Fully Specified Tensor name: " << inputInfo.first <<
"\t";
2059 std::cout <<
"shape: [";
2060 for (
size_t i = 0; i < inputInfo.second.shape.size(); i++) {
2061 std::cout << inputInfo.second.shape[i];
2062 if (i < inputInfo.second.shape.size() - 1) std::cout <<
",";
2064 std::cout <<
"]" << std::endl;
2070 std::cout <<
"Model initialized the following tensors:\n";
2072 std::cout <<
"Tensor name: \"" << it.first <<
"\"\t";
2074 std::cout <<
"shape: [";
2075 for (
size_t i = 0; i < it.second.shape().
size(); i++) {
2076 std::cout << it.second.shape()[i];
2077 if (i < it.second.shape().size() - 1) std::cout <<
",";
2080 if (it.second.IsConstantTensor()) std::cout <<
" (Constant)";
2081 if (it.second.IsNotWritable()) std::cout <<
" (Not Writable)";
2082 std::cout << std::endl;
2088 std::cout <<
"Model specify the following intermediate tensors:\n";
2090 std::cout <<
"Tensor name: \"" << it.first <<
"\"\t";
2092 std::cout <<
"shape: [";
2093 for (
size_t i = 0; i < it.second.shape.size(); i++) {
2094 std::cout << it.second.shape[i];
2095 if (i < it.second.shape.size() - 1) std::cout <<
",";
2097 std::cout <<
"]" << std::endl;
2103 std::cout <<
"Model specify the following dynamic tensors:\n";
2105 std::cout <<
"Tensor name: \"" << it.first <<
"\"\t";
2107 std::cout <<
"shape: [";
2108 for (
size_t i = 0; i < it.second.shape.size(); i++) {
2109 std::cout << it.second.shape[i].GetVal();
2110 if (i < it.second.shape.size() - 1) std::cout <<
",";
2112 std::cout <<
"]" << std::endl;
2118 std::cout <<
"Model specify the following output tensors:\n";
2120 std::cout <<
"Tensor name: \"" << it <<
"\"\t";
2125 std::cout <<
"with shape not yet defined" << std::endl;
2134 std::cout <<
"Tensor " <<
name <<
" not found in model's initialized tensor list" << std::endl;
2138 std::cout <<
"Tensor name: " << it->first <<
"\t";
2141 std::cout <<
"shape: [";
2142 for (
size_t i = 0; i < it->second.shape().
size(); i++) {
2143 std::cout << it->second.shape()[i];
2144 length *= it->second.shape()[i];
2145 if (i < it->second.shape().size() - 1) std::cout <<
",";
2147 std::cout <<
"]" << std::endl;
2148 bool ellipsis =
true;
2154 std::cout <<
"data: [" << std::endl;
2156 auto converted_data = it->second.data<
float>();
2157 for (
int i =0; i < n_print; i++) {
2158 std::cout << converted_data[i];
2159 if (i < n_print - 1) std::cout <<
" ,";
2162 if (ellipsis) std::cout <<
", ...";
2163 std::cout <<
"]" << std::endl;
2168 fGC += (
"//Code generated automatically by TMVA for Inference of Model file [" +
fFileName +
"] at [" +
fParseTime.substr(0,
fParseTime.length()-1) +
"] \n");
2171 std::transform(hgname.begin(), hgname.end(), hgname.begin(), [](
unsigned char c) {
2172 return std::toupper(c);
2174 hgname =
"ROOT_TMVA_SOFIE_" + hgname;
2175 fGC +=
"\n#ifndef " + hgname +
"\n";
2176 fGC +=
"#define " + hgname +
"\n\n";
2179 for (
const char *
h : {
"cstdint",
"cstring",
"string",
"vector",
"map",
"memory",
"sstream",
"iostream",
"iomanip",
2180 "limits",
"stdexcept",
"algorithm",
"cmath",
"cassert"}) {
2184 fGC +=
"#include <" + i +
">\n";
2187 fGC +=
"#include \"" + i +
"\"\n";
2193 fGC +=
"#include <fstream>\n";
2197 fGC +=
"#include <iterator>\n";
2199 fGC +=
"\nnamespace TMVA_SOFIE_" +
fName +
"{\n";
2201 fGC += (
"namespace BLAS{\n");
2203 if (routine ==
"Gemm") {
2204 fGC += (
"\textern \"C\" void sgemm_(const char * transa, const char * transb, const int * m, const int * n, const int * k,\n"
2205 "\t const float * alpha, const float * A, const int * lda, const float * B, const int * ldb,\n"
2206 "\t const float * beta, float * C, const int * ldc);\n");
2209 }
else if (routine ==
"Gemv") {
2210 fGC += (
"\textern \"C\" void sgemv_(const char * trans, const int * m, const int * n, const float * alpha, const float * A,\n"
2211 "\t const int * lda, const float * X, const int * incx, const float * beta, const float * Y, const int * incy);\n");
2212 }
else if (routine ==
"Axpy") {
2213 fGC += (
"\textern \"C\" void saxpy_(const int * n, const float * alpha, const float * x,\n"
2214 "\t const int * incx, float * y, const int * incy);\n");
2215 }
else if (routine ==
"Copy") {
2216 fGC += (
"\textern \"C\" void scopy_(const int *n, const float* x, const int *incx, float* y, const int* incy);\n");
2219 fGC += (
"}//BLAS\n");
2232 auto replaceMarker = [
this](
const std::string &marker,
const std::string &replacement) {
2233 auto pos =
fGC.find(marker);
2234 if (pos != std::string::npos) {
2235 fGC.replace(pos, marker.size(), replacement);
2245 auto pos =
fGC.rfind(
"#endif");
2246 if (pos != std::string::npos) {
2268 throw std::runtime_error(
"tmva-sofie failed to open file for output generated inference code");
2277 size_t pos =
filename.find(
".hxx");
2278 if (pos != std::string::npos)
2279 filename.replace(pos, 4, extension);
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t target
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize id
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
std::string WriteInitializedTensorsToBuffer()
void AddShapeParam(const std::string &name, size_t def_value=0)
std::vector< std::string > RuntimeBoundParams(const std::string &name) const
Shape parameters of a dynamic tensor that an operator computes at run time and that are Session const...
void AddNeededHelperFunction(std::string name)
std::vector< size_t > GetTensorShape(const std::string &name) const
void ReadInitializedTensorsFromFile()
std::set< std::string > fNeededHelperFunctions
void PrintIntermediateTensors() const
std::unordered_set< std::string > fComputedShapeParams
! shape parameters computed at run time by an operator
std::vector< Dim > GetDimTensorShape(const std::string &name) const
std::unordered_map< std::string, DynamicTensorInfo > fDynamicTensorInfos
bool IsDynamicTensor(const std::string &name) const
WeightFileType fWeightFile
void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector< Dim > dim_shape)
void GenerateIntermediateTensorInfo()
bool AddAliasTensor(const std::string &tensor_name, const std::string &orig_tensor_name)
std::string GenerateInferSignature(bool isdecl=true)
std::string fExtraCodeForDimShapes
void GenerateOperatorDeclarations()
size_t fWeightsTensorSize
std::unordered_set< std::string > fNeededBlasRoutines
bool CheckIfTensorAlreadyExist(std::string tensor_name)
void GenerateHeaderInfo(std::string &hgname)
void GenerateRequiredInputTensorInfo()
To emit the dimensions of the input tensors as a data member of a session, which is helpful when vali...
void OutputGenerated(std::string filename="", bool append=false)
std::unordered_map< std::string, std::string > fAliasTensors
void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector< Dim > shape)
static std::string SizeCheckMarker(const std::string &name)
Line for an operator's Generate(), where its size variables are declared and before it writes the out...
std::unordered_map< std::string, TensorInfo > fIntermediateTensorInfos
void AddOutputTensorNameList(std::vector< std::string > output_tensor_names)
void EmitHelperFunctionsCode()
std::unordered_map< std::string, TensorInfo > fReadyInputTensorInfos
void AddConstantTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector< Dim > shape)
std::vector< std::string > fDimShapeNames
void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
std::unordered_map< std::string_view, size_t > fIntermediateTensorFrequencyLookup
! lookup table for intermediate tensor frequency (transient)
void AddBlasRoutines(std::vector< std::string > routines)
void AddInputTensorName(std::string name)
std::vector< std::string > fOutputTensorNames
void PrintRequiredInputTensors() const
void GenerateSessionCode()
void AddNeededStdLib(std::string libname)
bool IsDimInputTensor(const std::string &name) const
void GenerateDynamicTensorInfo()
void PrintDynamicTensors() const
bool IsShapeTensor(const std::string &name) const
check if a tensor is a shape tensor
static constexpr const char * kHelperIncludesMarker
bool IsInitializedTensor(const std::string &name) const
std::unordered_set< std::string > fNeededStdLib
bool IsAliasTensor(const std::string &name) const
check if a tensor is a alias tensor
static constexpr const char * kHelperFunctionsMarker
size_t fConstantTensorSize
void CheckAndFlushIntermediateMemory(std::span< const std::string_view > op_output_tensors, const size_t &op_idx)
void AddOperator(std::unique_ptr< ROperator > op, int order_execution=-1)
void PrintOutputTensors() const
RModel()=default
Default constructor.
void HeadInitializedTensors(std::string name, int n_print=50)
bool IsConstantTensor(const std::string &name) const
void WriteInitializedTensorsToStream(std::ostream &os)
void Initialize(int batchSize=-1, bool verbose=false)
long WriteInitializedTensorsToFile(std::string filename="")
OptimizationLevel fOptimizationLevel
void PrintSummary() const
std::vector< std::string > CollectTensorMemberNames(const std::string &input)
Collects all identifiers starting with "tensor_" in the input code, provided that the occurrence is n...
std::vector< Dim > GetDynamicTensorShape(const std::string &name) const
RModel & operator=(RModel &&)
void PrintInitializedTensors() const
std::unordered_map< std::string, InputTensorInfo > fInputTensorInfos
std::shared_ptr< void > GetInitializedTensorData(std::string tensor_name)
void AddComputedShapeParam(const std::string &name)
Declare a shape parameter as computed at run time by an operator.
MemoryPoolInfo fIntermediateMemoryInfo
! intermediate memory info (transient)
void GenerateIntermediateMemoryPool()
std::string AllocateIntermediateMemory(std::span< const std::string_view > op_output_tensors)
std::unordered_map< std::string, std::pair< std::vector< Dim >, bool > > fShapeTensors
std::vector< std::unique_ptr< ROperator, ROperatorDeleter > > fOperators
void InitializeSubGraph(std::shared_ptr< RModel > graph)
std::unordered_map< std::string, std::string > fShapeParams
void SetNotWritableInitializedTensor(const std::string &tensor_name)
const std::string & GetName() const
ETensorType GetTensorType(std::string name) const
void GenerateInitializedTensorInfo()
std::vector< std::string > fInputTensorNames
std::unordered_map< std::string, InitializedTensor > fInitializedTensors
void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
void Generate(std::underlying_type_t< Options > options, int batchSize=-1, bool verbose=false)
const std::vector< Dim > & GetShapeTensorValues(const std::string &tensor_name) const
std::vector< std::shared_ptr< RModel > > fSubGraphs
! sub-graph models (transient)
bool IsReadyInputTensor(const std::string &name) const
void UpdateOutputTensorList(std::vector< std::string > curr_output_tensor, std::vector< std::string > modify_output_tensor)
void AddShapeTensor(const std::string &name, const std::vector< Dim > &shapeValues, bool scalar=false)
std::unordered_set< std::string > fCustomOpHeaders
bool IsInputTensorShapeParam(std::string const &name) const
Check if a given parameter is used for the shape of an input tensor.
std::string Clean_name(std::string input_tensor_name)
const std::string kCheckMarker
std::string ConvertDimShapeToString(const std::vector< Dim > &shape)
std::size_t ConvertShapeToLength(const std::vector< size_t > &shape)
std::string ConvertValuesToString(size_t n, const T *data, size_t maxprint=-1)
std::vector< Dim > ConvertShapeToDim(const std::vector< size_t > &shape)
Convert shape from integer format to dynamic one (based on Dim)
constexpr size_t GetTypeSize(ETensorType type)
std::string GenerateConstantTensorCode(const std::pair< std::string, InitializedTensor > &t)
std::vector< size_t > ConvertShapeToInt(const std::vector< Dim > &shape)
Convert shape based on Dim to integer format.
std::string ConvertTypeToString(ETensorType type)
HelperFunctionsCode GenerateHelperFunctionsCode(const std::set< std::string > &neededHelpers, const std::string &modelNamespace, bool sgemmAlreadyDeclared=false)
Return the standalone C++ source of the inference helper functions requested in neededHelpers (see RM...
std::underlying_type_t< Options > operator|(Options opA, Options opB)
std::string ConvertDimShapeToLength(const std::vector< Dim > &shape)
std::string ConvertShapeToString(const std::vector< size_t > &shape)
std::string ConvertValToString(T value)
if(fPos !=fText.size()) Fail("unexpected trailing content")
Source code of the inference helper functions to embed in generated code so that it is standalone and...
std::string definitions
function/type definitions to place inside the generated model namespace
std::string cladDefinitions
Clad custom-derivative definitions to place at file scope (outside the model namespace) so that Clad ...
std::string includes
#include directives to place in the header preamble
std::map< size_t, TensorMemoryInfo > total_stack
std::map< size_t, size_t > available_stack
void operator()(ROperator *ptr) const