18 std::default_delete<ROperator>()(ptr);
27const std::string
SP =
" ";
29void ReplaceAll(std::string &str,
const std::string &from,
const std::string &to)
32 while ((pos = str.find(from, pos)) != std::string::npos) {
33 str.replace(pos, from.length(), to);
40 return std::isalnum(
static_cast<unsigned char>(
c)) ||
c ==
'_';
48 if (s.empty() || std::isdigit(
static_cast<unsigned char>(s[0])))
59 return "tensor_" +
name;
72 " cannot be written to a safetensors file");
81 out.reserve(s.size() + 2);
82 for (
const char c : s) {
84 case '"': out +=
"\\\"";
break;
85 case '\\': out +=
"\\\\";
break;
87 if (
static_cast<unsigned char>(
c) < 0x20) {
89 std::snprintf(
buf,
sizeof(
buf),
"\\u%04x",
c);
102 return static_cast<std::underlying_type_t<Options>
>(
opA) |
static_cast<std::underlying_type_t<Options>
>(
opB);
105 return opA |
static_cast<std::underlying_type_t<Options>
>(
opB);
111 return f->second.shape;
115 return f2->second.shape();
119 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] is an input tensor with unspecified dimension parameter");
123 return f4->second.shape;
129 if (f5->second.second)
130 return std::vector<size_t>{};
132 return std::vector<size_t>{f5->second.first.size()};
136 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] is a dynamic tensor. Use GetDynamicTensorShape instead of GetTensorShape");
141 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the shape is requested is not found");
146 return f->second.shape;
149 return f->second.shape;
157 return f->second.shape;
160 return f->second.shape;
164 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the shape is requested is not dynamic");
166 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the shape is requested is not found");
172 return f->second.type;
176 return f2->second.type();
180 return f3->second.type;
184 return f4->second.type;
188 return f5->second.type;
198 throw std::runtime_error(
"TMVA SOFIE tensor [" +
name +
"] for which the type is requested is not found, model name: " +
fName);
215 throw std::runtime_error(
"TMVA-SOFIE: input tensor with name " +
input_name +
" already exists \n");
225 throw std::runtime_error(
"TMVA-SOFIE: input tensor with name " +
input_name +
" already exists \n");
238 auto libs =
op->GetStdLibs();
244 std::unique_ptr<ROperator, ROperatorDeleter>
opStored(
op.release());
272 throw std::runtime_error(
"TMVA-SOFIE: initialized tensor with name " + tensor_name +
" already exists \n");
279 const std::vector<std::size_t> &shape,
void *raw_data)
292 throw std::runtime_error(
"TMVA-SOFIE: constant tensor with name " + tensor_name +
" already exists \n");
301 throw std::runtime_error(
"TMVA-SOFIE: shape tensor with name " + tensor_name +
" already exists \n");
315 throw std::runtime_error(
"TMVA-SOFIE: alias tensor with name " + tensor_name +
" already exists \n");
363 return itr->second.IsConstantTensor();
393 throw std::runtime_error(
"TMVA-SOFIE: intermediate tensor with name " + tensor_name +
" already exists \n");
402 throw std::runtime_error(
"TMVA-SOFIE: intermediate tensor with name " + tensor_name +
" already exists \n");
407 for (
auto &
d : shape) {
409 if (
d.dim !=
size_t(-1)) {
453 throw std::runtime_error(
"TMVA-SOFIE: tensor " + tensor_name +
" not found when trying to update it");
462 throw std::runtime_error(
"TMVA-SOFIE: tensor " + tensor_name +
" not found when trying to get its data");
464 return f->second.sharedptr();
471 throw std::runtime_error(
"TMVA-SOFIE: initialized tensor " + tensor_name +
" not found when trying to get its info");
473 t->second.SetNotWritable();
478 std::stringstream code;
481 std::cout <<
"Total chunks allocated\n";
483 std::cout <<
"..... chunk " <<
chunk->first <<
" size " <<
chunk->second.tensor_size <<
" " <<
chunk->second.tensor_name << std::endl;
489 code <<
"\n // Allocating memory for intermediate tensor " <<
name <<
" with size " <<
size <<
" bytes";
491 << typeName <<
"* " <<
TensorMember(
name) <<
" = reinterpret_cast<" << typeName
492 <<
"*>(fIntermediateMemoryPool.data() + " << location <<
");\n";
495 if (
fVerbose) std::cout <<
"*** AllocateIntermediateMemory: Loop on op output tensors\n";
500 auto name = std::string(it);
520 std::string
name = std::string{it.tensor_name};
521 size_t tensor_size = it.tensor_size;
523 std::cout <<
"output tensor " <<
name <<
" size " << tensor_size << std::endl;
528 if (
fVerbose) std::cout <<
".. available chunk " <<
chunk->first <<
" with size = " <<
chunk->second;
530 if (
chunk->second >= tensor_size) {
538 chunk->second -= tensor_size;
544 if (
chunk->second == 0) {
545 if (
fVerbose) std::cout <<
" and deleted since size matches";
548 if (
fVerbose) std::cout << std::endl;
557 if (
fVerbose) std::cout <<
" is extended with a bigger one of size " << tensor_size << std::endl;
561 if (
fVerbose) std::cout << std::endl;
574 if (
fVerbose) std::cout <<
"no chunk available - add in total stack a new chunk with size of tensor and idx : " <<
chunk_idx
582 if (
fVerbose) std::cout <<
"*** CheckAndFlushIntermediateMemory: Loop on input tensors for op " <<
op_idx <<
"\n";
584 if (
fVerbose) std::cout <<
"available chunks before freeing them : \n";
587 if (
fVerbose) std::cout <<
"-- free chunk " <<
chunk->first <<
" size = " <<
chunk->second << std::endl;
591 if (
fVerbose) std::cout <<
".. input tensors : " <<
iv;
600 if (
fVerbose) std::cout <<
" flash condition is met - looping on chunks to find matching one \n";
603 if (
fVerbose) std::cout <<
"--- chunk " <<
chunk->first <<
" , " <<
chunk->second.tensor_name <<
" size " <<
chunk->second.tensor_size;
604 if (
chunk->second.tensor_name == it) {
605 if (
fVerbose) std::cout <<
" -- Found chunk corresponding to input tensor: " <<
chunk->first;
620 if (
fVerbose) std::cout <<
" is adjacent in memory with previous one - merge ";
630 if (
fVerbose) std::cout <<
" merge also with following that is free ";
633 if (
fVerbose) std::cout << std::endl;
638 if (
fVerbose) std::cout <<
" is adjacent in memory with following one - merge \n";
650 if (
fVerbose) std::cout <<
" insert in the available stack the chunk with size " <<
chunk->second.tensor_size << std::endl;
652 chunk->second.tensor_name =
"free";
657 if (
fVerbose) std::cout << std::endl;
678 std::cout <<
"Model is already initialized - skip initialization " << std::endl;
690 if (verbose) std::cout <<
"looking at the tensor " <<
input.first << std::endl;
693 for (
auto &
d :
input.second.shape) {
695 std::string
pname =
d.param;
701 std::cout <<
"Tensor: " <<
input.first <<
" - fix parametric shape " <<
itr->first <<
" to " <<
itr->second << std::endl;
711 if (!shape.empty()) {
723 for (
auto &
d :
input.second.shape) {
747 std::cout <<
"Initializing operator " << i <<
" " <<
typeid(
r).
name() << std::endl;
751 std::string
name = std::string{it};
763 std::string
name = std::string{it};
779 it.second.SetWritable();
781 std::cout <<
"Initialized tensor " << it.first <<
" is flagged as not writable but is used by non constant operators, set it as writable \n";
787 it.second.SetConstant();
795 if (it.second.IsWeightTensor()) {
822 graph->fParentGraph =
this;
823 graph->fIsSubGraph =
true;
831 for (
auto &
e : graph->fNeededBlasRoutines)
834 for (
auto e : graph->fNeededStdLib)
838 for (
auto const &
h : graph->GetNeededHelperFunctions())
843 graph->fInputTensorNames.emplace_back(
name);
855 std::stringstream
strs;
862 const T *
data = t.second.data<T>();
879 strs <<
"std::vector<" <<
type <<
"> fTensor_" << t.first <<
" = ";
893 fGC +=
"// initialized (weights and constant) tensors\n";
897 if (i.second.IsNotWritable())
continue;
903 const float *
data = i.second.data<
float>();
904 for (
size_t idx = 0; idx <
length; idx++) {
905 if (std::is_floating_point<float>::value) {
906 if (std::isinf(
data[idx]) || std::isnan(
data[idx])) {
931 fGC +=
"std::vector<float> fTensor_" + i.first +
" = std::vector<float>(" + std::to_string(
length) +
");\n";
932 fGC +=
"float * " +
TensorMember(i.first) +
" = fTensor_" + i.first +
".data();\n";
941 fGC +=
"\n//--- Allocating session memory pool to be used for allocating intermediate tensors\n";
947 fGC +=
"std::vector<char> fIntermediateMemoryPool = std::vector<char>(" + std::to_string(
memPoolSize) +
");\n\n";
960 " = std::vector<std::uint8_t>(" +
963 "std::uint8_t * " +
TensorMember(i.first) +
" = fTensor_" + i.first +
".data();\n";
999 fGC +=
"//--- declare the dynamic tensors\n";
1005 fGC +=
"//--- dynamic tensors pool\n";
1006 fGC +=
"std::vector<char> fDynamicMemoryPool;\n";
1017 fGC +=
"\n//---- operator declarations \n";
1029 std::cout <<
"generating code for dynamic tensor management" << std::endl;
1036 std::stringstream out;
1037 out <<
"// dynamic tensor memory management\n";
1038 out <<
SP <<
"std::vector<TensorLifeInfo> dynamicTensorInfos;\n";
1043 std::vector<std::pair<std::string, ETensorType>>
tensors;
1047 for (
auto &it :
op->GetOpOutputTensors()) {
1050 std::cout <<
"Looping on operator " <<
op_index <<
" " <<
typeid(*op_ptr).name() << std::endl;
1053 std::string
name = std::string(it);
1069 std::cout <<
"op " <<
op_index <<
"tensor_" <<
name <<
" begin " << begin <<
" " <<
" end " << end << std::endl;
1070 throw std::runtime_error(
"TMVA-SOFIE: RModel::GenerateDynamicTensorInfo: tensor_" +
name +
" has end before begin");
1074 out <<
SP <<
"dynamicTensorInfos.push_back( {" << begin <<
", " << end <<
", " <<
type_size <<
"* (" << tensor_size <<
") });"
1075 <<
" // tensor_" <<
name << std::endl;
1081 out <<
"\n" <<
SP <<
"auto memory_result = OrganizeMemory(dynamicTensorInfos);\n\n";
1082 out <<
"// allocating now the memory\n";
1083 out <<
SP <<
"fDynamicMemoryPool = std::vector<char>(memory_result.total_bytes);\n";
1084 out <<
SP <<
"int idx = 0;\n";
1086 out <<
SP <<
"tensor_" << it.first <<
" = reinterpret_cast<" <<
ConvertTypeToString(it.second) <<
" *>(fDynamicMemoryPool.data() + memory_result.offsets[idx++]);\n";
1094 std::cout <<
"Dynamic tensors " << i.first <<
" is not in list of operator input/output " << std::endl;
1099 throw std::runtime_error(
"TMVA-SOFIE: RModel::GenerateDynamicTensorInfo - some tensors are not in input/output list");
1110 for (
auto &
d : shape) {
1125 const std::string
target =
"tensor_";
1127 std::vector<std::string>
result;
1129 for (
size_t i = 0; i <
input.size();) {
1138 std::size_t
j = i +
target.size();
1191 for (
auto &
d : shape) {
1192 std::string
pName =
d.param;
1196 rGC +=
d.param +
",";
1203 if (
type ==
"other")
1204 throw std::runtime_error(
"TMVA-SOFIE: input tensor " +
name +
1205 " is of a data type which is not yet supported.");
1208 rGC +=
"tensor_" +
name +
",";
1227 if (!
name.empty()) {
1228 name[0] = std::toupper(
static_cast<unsigned char>(
name[0]));
1245 if (outputSize == 1) {
1257 for (
size_t i = 0; i < outputSize; i++) {
1259 if (i < outputSize - 1)
1299 fGC +=
SP +
"size_t " + dim.param +
" = 0;\n";
1314 for (
auto &
d : shape) {
1315 std::string
pName =
d.param;
1321 fGC +=
SP +
SP +
"throw std::runtime_error(\"TMVA-SOFIE: dynamic input tensor shape parameter " +
1322 d.param +
" exceeds the initialized maximum allowed shape.\");\n";
1341 fGC +=
SP +
"return {";
1397 std::cout <<
"\n******************\n analyzing input/output operator " <<
op_idx <<
" "
1398 <<
typeid(*op).name() << std::endl;
1423 fGC +=
"\n// dynamic shape parameters\n";
1434 fGC +=
"Session_" + graph->fName +
" fSession_" + graph->fName +
";\n";
1440 for (
size_t id = 0;
id <
fOperators.size();
id++) {
1441 std::string
opName = std::to_string(
id);
1464 fGC +=
" static std::string LoadWeightsFromFile(const std::string &filename) {\n";
1465 fGC +=
" std::ifstream f(filename, std::ios::binary);\n";
1466 fGC +=
" if (!f.is_open()) {\n";
1467 fGC +=
" throw std::runtime_error(\"tmva-sofie failed to open file \" + filename + \" for input "
1470 fGC +=
" return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());\n";
1476 std::string fileName =
fName +
".dat";
1496 fGC +=
"\n//--- reading weights from file\n";
1506 for (
size_t id = 0;
id <
fOperators.size();
id++) {
1525 fGC +=
"// Set all weight and constant tensors to zero. This is useful to create\n"
1526 "// the tangent Session objects needed to differentiate the generated code\n"
1528 "void SetWeightsToZero() {\n";
1532 if (i.second.IsNotWritable() ||
1535 fGC +=
" for (auto &v : fTensor_" + i.first +
") v = 0;\n";
1538 fGC +=
" fSession_" + graph->fName +
".SetWeightsToZero();\n";
1546 fGC +=
"}; // end of Session\n\n";
1555 std::cout <<
"Generating main inference code for " <<
fName << std::endl;
1558 throw std::runtime_error(
"TMVA-SOFIE: output size=0 are not supported");
1564 std::cout <<
"Generating code for operator .... " <<
op_idx << std::endl;
1575 const std::string prefix =
"tensor_";
1580 fGC +=
" auto &" +
name +
" = session." +
name +
";\n";
1590 std::string t =
"session.tensor_" +
name;
1592 fGC +=
" std::copy(" + t +
", " + t +
" + " + std::to_string(
length) +
", tensor_" +
name +
");\n";
1605 fGC +=
" " + dim.param +
"_output = " + dim.param +
";\n";
1641 std::cout <<
"generate session code for subgraph " << graph->fName << std::endl;
1642 graph->GenerateSessionCode();
1647 std::cout <<
"generate Main session code - model " <<
fName << std::endl;
1653 fGC += (
"} //TMVA_SOFIE_" +
fName +
"\n");
1668 fGC +=
" std::ifstream f;\n";
1669 fGC +=
" f.open(filename);\n";
1670 fGC +=
" if (!f.is_open()) {\n";
1671 fGC +=
" throw std::runtime_error(\"tmva-sofie failed to open file \" + filename + \" for input weights\");\n";
1680 if (!i.second.IsWeightTensor())
continue;
1681 std::string tensor_name =
"tensor_" + i.first;
1684 fGC +=
" ReadTensorFromStream(f, " + tensor_name +
", \"" + tensor_name +
"\", " +
length +
");\n";
1686 throw std::runtime_error(
"tmva-sofie tensor " + tensor_name +
" with type " +
ConvertTypeToString(i.second.type()) +
" cannot be read from a file");
1689 fGC +=
" f.close();\n";
1699 fGC +=
" SafetensorsReader sofie_weights_reader(weights_blob);\n";
1703 if (!i.second.IsWeightTensor())
1705 std::string tensor_name =
"tensor_" + i.first;
1709 }
catch (
const std::runtime_error &) {
1710 throw std::runtime_error(
"tmva-sofie tensor " + tensor_name +
" with type " +
1712 " cannot be read from a safetensors payload");
1715 fGC +=
" sofie_weights_reader.Read(\"" + tensor_name +
"\", fTensor_" + i.first +
", " +
length +
", \"" +
1743 std::ofstream
f(
filename, std::ios::binary);
1745 throw std::runtime_error(
"tmva-sofie failed to open file " +
filename +
" for tensor weight data");
1757 std::runtime_error(
"tmva-sofie failed to open file " +
filename +
" for tensor weight data");
1760 if (!i.second.IsWeightTensor()) {
1764 std::string tensor_name =
"tensor_" + i.first;
1765 f << tensor_name <<
" " <<
length <<
"\n";
1767 const float *
data = i.second.data<
float>();
1768 for (
size_t idx = 0; idx <
length; idx++) {
1771 if (
value != 0. && std::abs(
value) < std::numeric_limits<float>::min() )
value = 0;
1773 if (std::isinf(
value))
1774 f << (
value > 0 ?
"inf" :
"-inf");
1775 else if (std::isnan(
value))
1778 f << std::setprecision(std::numeric_limits<float>::max_digits10) <<
value;
1779 f << ( (idx <
length-1) ?
" " :
"\n" );
1783 throw std::runtime_error(
"tmva-sofie tensor " + tensor_name +
" with type " +
ConvertTypeToString(i.second.type()) +
" cannot be written to a file");
1786 throw std::runtime_error(
"tmva-sofie failed to write tensor data to file for " + tensor_name);
1800 const std::uint16_t
one = 1;
1801 if (!*
reinterpret_cast<const std::uint8_t *
>(&
one))
1802 throw std::runtime_error(
"tmva-sofie: safetensors weights can only be written on a little-endian host");
1809 std::uint64_t
offset = 0;
1811 std::vector<std::string> names;
1814 if (
item.second.IsWeightTensor())
1815 names.push_back(
item.first);
1817 std::sort(names.begin(), names.end());
1819 for (
size_t idx = 0; idx < names.size(); ++idx) {
1826 for (
size_t i = 0; i <
tensor.shape().
size(); ++i) {
1836 const std::uint64_t headerSize =
headerStr.size();
1838 for (
int i = 0; i < 8; ++i)
1839 sizestr[i] =
static_cast<char>((headerSize >> (8 * i)) & 0xff);
1842 for (
const auto &
name : names) {
1845 f.write(
reinterpret_cast<const char *
>(
tensor.data<
void>()),
nbytes);
1848 throw std::runtime_error(
"tmva-sofie failed to write safetensors payload");
1853 std::ostringstream buffer;
1855 return buffer.str();
1859 std::cout <<
"Summary of model " <<
GetName() << std::endl;
1866 for (
auto &
t_in :
r.GetOpInputTensors()) std::cout <<
t_in <<
" ";
1867 std::cout <<
" ----> ";
1868 for (
auto &
t_out :
r.GetOpOutputTensors()) std::cout <<
t_out <<
" ";
1869 std::cout << std::endl;
1877 fGC +=
"\n// Input tensor dimensions\n";
1888 fGC +=
"constexpr std::array<SingleDim, " + std::to_string(shape.size()) +
"> dim_" +
name +
"{";
1889 for (std::size_t
iDim = 0;
iDim < shape.size(); ++
iDim) {
1890 auto const &dim = shape[
iDim];
1892 fGC +=
"SingleDim{\"" + dim.GetVal() +
"\"}";
1894 fGC +=
"SingleDim{" + dim.GetVal() +
"}";
1896 if (
iDim != shape.size() - 1) {
1902 fGC +=
"\nconstexpr std::array<TensorDims, " + std::to_string(
fInputTensorNames.size()) +
"> inputTensorDims{\n";
1905 fGC +=
SP +
"makeDims(dim_" +
name +
")";
1915 "\nconstexpr bool hasDynamicInputTensors{" + std::string{
hasDynamicInputTensors ?
"true" :
"false"} +
"};\n\n";
1917 fGC +=
"\n// Output tensor dimensions\n";
1925 fGC +=
"constexpr std::array<SingleDim, " + std::to_string(shape.size()) +
"> dim_" +
name +
"{";
1926 for (std::size_t
iDim = 0;
iDim < shape.size(); ++
iDim) {
1927 auto const &dim = shape[
iDim];
1929 fGC +=
"SingleDim{\"" + dim.GetVal() +
"\"}";
1931 fGC +=
"SingleDim{" + dim.GetVal() +
"}";
1933 if (
iDim != shape.size() - 1) {
1939 fGC +=
"\nconstexpr std::array<TensorDims, " + std::to_string(
fOutputTensorNames.size()) +
"> outputTensorDims{\n";
1942 fGC +=
SP +
"makeDims(dim_" +
name +
")";
1951 "\nconstexpr bool hasDynamicOutputTensors{" + std::string{
hasDynamicOutputTensors ?
"true" :
"false"} +
"};\n\n";
1955 std::cout <<
"Model requires following inputs:\n";
1957 std::cout <<
"Parametrised Tensor name: " <<
inputInfo.first <<
"\t";
1959 std::cout <<
"shape: [";
1960 for (
size_t i = 0; i <
inputInfo.second.shape.size(); i++) {
1961 if (
inputInfo.second.shape[i].isParam) {
1962 std::cout <<
inputInfo.second.shape[i].param;
1964 std::cout <<
inputInfo.second.shape[i].dim ;
1966 if (i <
inputInfo.second.shape.size() - 1) std::cout <<
",";
1968 std::cout <<
"]" << std::endl;
1972 std::cout <<
"Fully Specified Tensor name: " <<
inputInfo.first <<
"\t";
1974 std::cout <<
"shape: [";
1975 for (
size_t i = 0; i <
inputInfo.second.shape.size(); i++) {
1977 if (i <
inputInfo.second.shape.size() - 1) std::cout <<
",";
1979 std::cout <<
"]" << std::endl;
1985 std::cout <<
"Model initialized the following tensors:\n";
1987 std::cout <<
"Tensor name: \"" << it.first <<
"\"\t";
1989 std::cout <<
"shape: [";
1990 for (
size_t i = 0; i < it.second.shape().
size(); i++) {
1991 std::cout << it.second.shape()[i];
1992 if (i < it.second.shape().size() - 1) std::cout <<
",";
1995 if (it.second.IsConstantTensor()) std::cout <<
" (Constant)";
1996 if (it.second.IsNotWritable()) std::cout <<
" (Not Writable)";
1997 std::cout << std::endl;
2003 std::cout <<
"Model specify the following intermediate tensors:\n";
2005 std::cout <<
"Tensor name: \"" << it.first <<
"\"\t";
2007 std::cout <<
"shape: [";
2008 for (
size_t i = 0; i < it.second.shape.size(); i++) {
2009 std::cout << it.second.shape[i];
2010 if (i < it.second.shape.size() - 1) std::cout <<
",";
2012 std::cout <<
"]" << std::endl;
2018 std::cout <<
"Model specify the following dynamic tensors:\n";
2020 std::cout <<
"Tensor name: \"" << it.first <<
"\"\t";
2022 std::cout <<
"shape: [";
2023 for (
size_t i = 0; i < it.second.shape.size(); i++) {
2024 std::cout << it.second.shape[i].GetVal();
2025 if (i < it.second.shape.size() - 1) std::cout <<
",";
2027 std::cout <<
"]" << std::endl;
2033 std::cout <<
"Model specify the following output tensors:\n";
2035 std::cout <<
"Tensor name: \"" << it <<
"\"\t";
2040 std::cout <<
"with shape not yet defined" << std::endl;
2049 std::cout <<
"Tensor " <<
name <<
" not found in model's initialized tensor list" << std::endl;
2053 std::cout <<
"Tensor name: " << it->first <<
"\t";
2056 std::cout <<
"shape: [";
2057 for (
size_t i = 0; i < it->second.shape().
size(); i++) {
2058 std::cout << it->second.shape()[i];
2059 length *= it->second.shape()[i];
2060 if (
i < it->second.shape().size() - 1) std::cout <<
",";
2062 std::cout <<
"]" << std::endl;
2069 std::cout <<
"data: [" << std::endl;
2072 for (
int i =0; i <
n_print; i++) {
2074 if (i <
n_print - 1) std::cout <<
" ,";
2077 if (
ellipsis) std::cout <<
", ...";
2078 std::cout <<
"]" << std::endl;
2083 fGC += (
"//Code generated automatically by TMVA for Inference of Model file [" +
fFileName +
"] at [" +
fParseTime.substr(0,
fParseTime.length()-1) +
"] \n");
2087 return std::toupper(c);
2094 for (
const char *
h : {
"cstdint",
"cstring",
"string",
"vector",
"map",
"memory",
"sstream",
"iostream",
"iomanip",
2095 "limits",
"stdexcept",
"algorithm",
"cmath",
"cassert"}) {
2099 fGC +=
"#include <" + i +
">\n";
2102 fGC +=
"#include \"" + i +
"\"\n";
2108 fGC +=
"#include <fstream>\n";
2112 fGC +=
"#include <iterator>\n";
2114 fGC +=
"\nnamespace TMVA_SOFIE_" +
fName +
"{\n";
2116 fGC += (
"namespace BLAS{\n");
2119 fGC += (
"\textern \"C\" void sgemm_(const char * transa, const char * transb, const int * m, const int * n, const int * k,\n"
2120 "\t const float * alpha, const float * A, const int * lda, const float * B, const int * ldb,\n"
2121 "\t const float * beta, float * C, const int * ldc);\n");
2124 }
else if (
routine ==
"Gemv") {
2125 fGC += (
"\textern \"C\" void sgemv_(const char * trans, const int * m, const int * n, const float * alpha, const float * A,\n"
2126 "\t const int * lda, const float * X, const int * incx, const float * beta, const float * Y, const int * incy);\n");
2127 }
else if (
routine ==
"Axpy") {
2128 fGC += (
"\textern \"C\" void saxpy_(const int * n, const float * alpha, const float * x,\n"
2129 "\t const int * incx, float * y, const int * incy);\n");
2130 }
else if (
routine ==
"Copy") {
2131 fGC += (
"\textern \"C\" void scopy_(const int *n, const float* x, const int *incx, float* y, const int* incy);\n");
2134 fGC += (
"}//BLAS\n");
2148 auto pos =
fGC.find(marker);
2149 if (pos != std::string::npos) {
2160 auto pos =
fGC.rfind(
"#endif");
2161 if (pos != std::string::npos) {
2183 throw std::runtime_error(
"tmva-sofie failed to open file for output generated inference code");
2192 size_t pos =
filename.find(
".hxx");
2193 if (pos != std::string::npos)
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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
const_iterator begin() const
const_iterator end() const
std::string WriteInitializedTensorsToBuffer()
void AddShapeParam(const std::string &name, size_t def_value=0)
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)
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 (e.g.
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)
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