Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RModel.cxx
Go to the documentation of this file.
1#include <limits>
2#include <algorithm>
3#include <sstream>
4#include <cctype>
5#include <cstdint>
6#include <cstdio>
7#include <memory>
8#include <string>
9#include <cstdlib>
10
11#include "TMVA/RModel.hxx"
12#include "TMVA/ROperator.hxx"
13
15
16// Out-of-line because ROperator is forward-declared in the public header.
18{
19 std::default_delete<ROperator>()(ptr);
20}
21
22RModel::~RModel() = default;
23RModel::RModel(RModel &&) = default;
24RModel &RModel::operator=(RModel &&) = default;
25
26namespace {
27
28const std::string SP = " ";
29
30void ReplaceAll(std::string &str, const std::string &from, const std::string &to)
31{
32 size_t pos = 0;
33 while ((pos = str.find(from, pos)) != std::string::npos) {
34 str.replace(pos, from.length(), to);
35 pos += to.length();
36 }
37}
38
39bool IsIdentifierChar(char c)
40{
41 return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
42}
43
44// Returns true if s is a valid C++ identifier (can be used as a variable name).
45// Dim::param can be either a plain name (e.g. "W") or a computed expression
46// (e.g. "((W+-3)/2+1)"); only the former can be used as a C++ variable name.
47bool IsIdentifier(const std::string &s)
48{
49 if (s.empty() || std::isdigit(static_cast<unsigned char>(s[0])))
50 return false;
51 for (char c : s)
52 if (!IsIdentifierChar(c))
53 return false;
54 return true;
55}
56
57// Get the data member name corresponding to a tensor with a given name.
58std::string TensorMember(std::string const &name)
59{
60 return "tensor_" + name;
61}
62
63// Safetensors dtype token (https://huggingface.co/docs/safetensors) for a
64// tensor type.
65std::string SafetensorsDType(ETensorType type)
66{
67 switch (type) {
68 case ETensorType::FLOAT: return "F32";
69 case ETensorType::DOUBLE: return "F64";
70 case ETensorType::INT64: return "I64";
71 default:
72 throw std::runtime_error("tmva-sofie tensor with type " + ConvertTypeToString(type) +
73 " cannot be written to a safetensors file");
74 }
75}
76
77// Escape a string for inclusion in the safetensors JSON header. Only what
78// JSON requires: quotation marks, backslashes and control characters.
79std::string JsonEscape(const std::string &s)
80{
81 std::string out;
82 out.reserve(s.size() + 2);
83 for (const char c : s) {
84 switch (c) {
85 case '"': out += "\\\""; break;
86 case '\\': out += "\\\\"; break;
87 default:
88 if (static_cast<unsigned char>(c) < 0x20) {
89 char buf[8];
90 std::snprintf(buf, sizeof(buf), "\\u%04x", c);
91 out += buf;
92 } else {
93 out.push_back(c);
94 }
95 }
96 }
97 return out;
98}
99
100} // namespace
101
102std::underlying_type_t<Options> operator|(Options opA, Options opB) {
103 return static_cast<std::underlying_type_t<Options>>(opA) | static_cast<std::underlying_type_t<Options>>(opB);
104}
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);
107}
108
109std::vector<size_t> RModel::GetTensorShape(const std::string & name) const {
110 auto f = fReadyInputTensorInfos.find(name);
111 if (f != fReadyInputTensorInfos.end()) {
112 return f->second.shape;
113 }
114 auto f2 = fInitializedTensors.find(name);
115 if (f2 != fInitializedTensors.end()) {
116 return f2->second.shape();
117 }
118 auto f3 = fInputTensorInfos.find(name);
119 if (f3 != fInputTensorInfos.end()) {
120 throw std::runtime_error("TMVA SOFIE tensor [" + name + "] is an input tensor with unspecified dimension parameter");
121 }
122 auto f4 = fIntermediateTensorInfos.find(name);
123 if (f4 != fIntermediateTensorInfos.end()) {
124 return f4->second.shape;
125 }
126 // case of shape tensors
127 auto f5 = fShapeTensors.find(name);
128 if (f5 != fShapeTensors.end()) {
129 // shape is vector of size 1 with size of shape values or just a scalar
130 if (f5->second.second) // check scalar flag
131 return std::vector<size_t>{};
132 else
133 return std::vector<size_t>{f5->second.first.size()};
134 }
135
137 throw std::runtime_error("TMVA SOFIE tensor [" + name + "] is a dynamic tensor. Use GetDynamicTensorShape instead of GetTensorShape");
138
141
142 throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the shape is requested is not found");
143}
144
145std::vector<Dim> RModel::GetDimTensorShape(const std::string & name) const {
146 if (auto f = fDynamicTensorInfos.find(name); f != fDynamicTensorInfos.end()) {
147 return f->second.shape;
148 }
149 if (auto f = fInputTensorInfos.find(name); f != fInputTensorInfos.end()) {
150 return f->second.shape;
151 }
152 // in case is not a dynamic tensor convert normal shape to Dim one
153 // for this we need to return the vector by value
155}
156std::vector<Dim> RModel::GetDynamicTensorShape(const std::string & name) const {
157 if (auto f = fDynamicTensorInfos.find(name); f != fDynamicTensorInfos.end()) {
158 return f->second.shape;
159 }
160 if (auto f = fInputTensorInfos.find(name); f != fInputTensorInfos.end()) {
161 return f->second.shape;
162 }
163 // throw error if shape is not dynamic
164 if (!IsDynamicTensor(name))
165 throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the shape is requested is not dynamic");
166
167 throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the shape is requested is not found");
168}
169
171 auto f = fReadyInputTensorInfos.find(name);
172 if (f != fReadyInputTensorInfos.end()) {
173 return f->second.type;
174 }
175 auto f2 = fInitializedTensors.find(name);
176 if (f2 != fInitializedTensors.end()) {
177 return f2->second.type();
178 }
179 auto f3 = fInputTensorInfos.find(name);
180 if (f3 != fInputTensorInfos.end()) {
181 return f3->second.type;
182 }
183 auto f4 = fIntermediateTensorInfos.find(name);
184 if (f4 != fIntermediateTensorInfos.end()) {
185 return f4->second.type;
186 }
187 auto f5 = fDynamicTensorInfos.find(name);
188 if (f5 != fDynamicTensorInfos.end()){
189 return f5->second.type;
190 }
191 // case of shape tensor type is INT64
192 if (fShapeTensors.find(name) != fShapeTensors.end()){
193 return ETensorType::INT64;
194 }
195
198
199 throw std::runtime_error("TMVA SOFIE tensor [" + name + "] for which the type is requested is not found, model name: " + fName);
200}
201
202bool RModel::CheckIfTensorAlreadyExist(std::string tensor_name) {
203 if (fReadyInputTensorInfos.find(tensor_name) != fReadyInputTensorInfos.end()) return true;
204 if (fInputTensorInfos.find(tensor_name) != fInputTensorInfos.end()) return true;
205 if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()) return true;
206 if (fIntermediateTensorInfos.find(tensor_name) != fIntermediateTensorInfos.end()) return true;
207 if (fDynamicTensorInfos.find(tensor_name) != fDynamicTensorInfos.end()) return true;
208 if (fShapeTensors.find(tensor_name) != fShapeTensors.end()) return true;
210 return false;
211}
212
213void RModel::AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<Dim> shape) {
214 input_name = UTILITY::Clean_name(input_name);
215 if (CheckIfTensorAlreadyExist(input_name)) {
216 throw std::runtime_error("TMVA-SOFIE: input tensor with name " + input_name + " already exists \n");
217 }
218
219 InputTensorInfo inputInfo { type, shape };
220 fInputTensorInfos[input_name] = inputInfo;
221}
222
223void RModel::AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<size_t> shape) {
224 input_name = UTILITY::Clean_name(input_name);
225 if (CheckIfTensorAlreadyExist(input_name)) {
226 throw std::runtime_error("TMVA-SOFIE: input tensor with name " + input_name + " already exists \n");
227 }
228 TensorInfo inputInfo { type, shape };
229 fReadyInputTensorInfos[input_name] = inputInfo;
230}
231
232void RModel::AddInputTensorName(std::string input_name) {
233 fInputTensorNames.emplace_back(UTILITY::Clean_name(input_name));
234}
235
236void RModel::AddOperator(std::unique_ptr<ROperator> op, int order_execution)
237{
238 AddBlasRoutines(op->GetBlasRoutines());
239 auto libs = op->GetStdLibs();
240 auto op_input_tensors = op->GetOpInputTensors();
241 for (auto &stdlib : libs) {
242 AddNeededStdLib(stdlib);
243 }
244 // Convert to the deleter used for storage (see ROperatorDeleter in the header)
245 std::unique_ptr<ROperator, ROperatorDeleter> opStored(op.release());
246 if (order_execution >= 0) {
247 fOperators.insert(fOperators.begin() + order_execution, std::move(opStored));
248 } else {
249 fOperators.push_back(std::move(opStored));
250 order_execution = fOperators.size() - 1;
251 }
252
253 // storing the last usage of tensors which are input to the operator
254 // (excluding tensors which are inputs to the model or the initialized (weights) tensors)
255 // We call this function during parsing so we don't have yet initialized the operators
256 for (size_t index = 0; index < op_input_tensors.size(); index++) {
257 if (!IsInitializedTensor(UTILITY::Clean_name(std::string(op_input_tensors[index]))) &&
258 std::find(fInputTensorNames.begin(), fInputTensorNames.end(),
259 UTILITY::Clean_name(std::string(op_input_tensors[index]))) == fInputTensorNames.end()) {
260
261 fIntermediateTensorFrequencyLookup[op_input_tensors[index]] = order_execution;
262 if (Verbose())
263 std::cout << "adding order execution for " << op_input_tensors[index] << " order " << order_execution
264 << std::endl;
265 }
266 }
267}
268
269void RModel::AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape, std::shared_ptr<void> data) {
270 tensor_name = UTILITY::Clean_name(tensor_name);
271 //NB: own data
272 if (CheckIfTensorAlreadyExist(tensor_name)) {
273 throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n");
274 }
275 InitializedTensor new_tensor {type, shape, data};
276 fInitializedTensors[tensor_name] = new_tensor;
277}
278
279void RModel::AddInitializedTensor(const std::string &tensor_name, ETensorType tensor_type,
280 const std::vector<std::size_t> &shape, void *raw_data)
281{
282 size_t size = ConvertShapeToLength(shape);
283 auto itemsize = GetTypeSize(tensor_type);
284 std::shared_ptr<void> data(malloc(size * itemsize), free);
285 std::memcpy(data.get(), raw_data, size * itemsize);
286 AddInitializedTensor(tensor_name, tensor_type, shape, data);
287}
288
289void RModel::AddConstantTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape, std::shared_ptr<void> data) {
290 tensor_name = UTILITY::Clean_name(tensor_name);
291 //NB: own data
292 if (CheckIfTensorAlreadyExist(tensor_name)) {
293 throw std::runtime_error("TMVA-SOFIE: constant tensor with name " + tensor_name + " already exists \n");
294 }
295 InitializedTensor new_tensor {type, shape, data, true}; // add here flag to specify is a constant tensor
296 fInitializedTensors[tensor_name] = new_tensor;
297}
298
299void RModel::AddShapeTensor(const std::string & name, const std::vector<Dim> & shape_values, bool scalar){
300 auto tensor_name = UTILITY::Clean_name(name);
301 if (fShapeTensors.count(tensor_name) != 0) {
302 throw std::runtime_error("TMVA-SOFIE: shape tensor with name " + tensor_name + " already exists \n");
303 }
304 fShapeTensors[tensor_name] = std::make_pair(shape_values, scalar);
305}
306
307bool RModel::AddAliasTensor(const std::string &name, const std::string &origin)
308{
309 // add an alias tensor to origin: the generated code points it to the memory of origin.
310 // The tensor must already be registered as an intermediate tensor.
311 auto tensor_name = UTILITY::Clean_name(name);
312 auto origin_name = UTILITY::Clean_name(origin);
313 // two operators writing the same tensor is a malformed graph rather than a case to refuse,
314 // so this comes before the checks below and the error does not depend on the optimization level
315 if (fAliasTensors.count(tensor_name) != 0) {
316 throw std::runtime_error("TMVA-SOFIE: alias tensor with name " + tensor_name + " already exists \n");
317 }
318 // an alias of an alias refers directly to the tensor owning the memory
319 if (auto it = fAliasTensors.find(origin_name); it != fAliasTensors.end())
320 origin_name = it->second;
321
322 // with kBasic every tensor keeps its own buffer, as the automatic differentiation of the
323 // generated code requires
325 return false;
326 // graph outputs are written into the buffers provided by the caller
327 if (std::find(fOutputTensorNames.begin(), fOutputTensorNames.end(), tensor_name) != fOutputTensorNames.end())
328 return false;
329 // only intermediate tensors can be shared: graph inputs are read-only and initialized tensors
330 // are managed by the session
331 if (fIntermediateTensorInfos.count(origin_name) == 0 && fDynamicTensorInfos.count(origin_name) == 0)
332 return false;
333 // boolean tensors are std::vector<uint8_t> members accessed directly: ROperator_SubGraph
334 // reads fTensor_<cond>[0] and writes fTensor_<out>.begin(), which an alias does not have
335 if (GetTensorType(origin_name) == ETensorType::BOOL || GetTensorType(tensor_name) != GetTensorType(origin_name))
336 return false;
337
338 fAliasTensors[tensor_name] = origin_name;
339 return true;
340}
341
342bool RModel::IsShapeTensor(const std::string & tensor_name) const {
343 return fShapeTensors.count(tensor_name) != 0;
344}
345
346bool RModel::IsAliasTensor(const std::string & tensor_name) const {
347 return fAliasTensors.count(tensor_name) != 0;
348}
349
350const std::vector<Dim> & RModel::GetShapeTensorValues(const std::string & tensor_name) const {
351 //if (!IsShapeTensor(tensor_name) ) return std::vector<Dim>{};
352 return fShapeTensors.at(tensor_name).first;
353}
354
355bool RModel::IsInitializedTensor(const std::string& tensorName) const {
356 std::string name = UTILITY::Clean_name(tensorName);
357 return fInitializedTensors.find(name) != fInitializedTensors.end();
358}
359bool RModel::IsConstantTensor(const std::string& tensorName) const {
360 // a constant tensor is an initialized tensor but has the constant flag set
361 std::string name = UTILITY::Clean_name(tensorName);
362 auto itr = fInitializedTensors.find(name);
363 if (itr == fInitializedTensors.end()) return false;
364 return itr->second.IsConstantTensor();
365}
366
367// dynamic tensors include also Dim input tensors
368bool RModel::IsDynamicTensor(const std::string& tensorName) const {
369 std::string name = UTILITY::Clean_name(tensorName);
370 bool ret = fDynamicTensorInfos.find(name) != fDynamicTensorInfos.end();
371 return (ret) ? true : IsDimInputTensor(tensorName);
372}
373bool RModel::IsDimInputTensor(const std::string& tensorName) const {
374 std::string name = UTILITY::Clean_name(tensorName);
375 return fInputTensorInfos.find(name) != fInputTensorInfos.end();
376}
377bool RModel::IsReadyInputTensor(const std::string& tensorName) const {
378 std::string name = UTILITY::Clean_name(tensorName);
380}
381
382// generic addition of a tensor
383void RModel::AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<Dim> dim_shape) {
384 auto int_shape = ConvertShapeToInt(dim_shape);
385 if (!int_shape.empty())
386 AddIntermediateTensor(tensor_name, type, int_shape);
387 else
388 AddDynamicTensor(tensor_name, type, dim_shape);
389}
390
391void RModel::AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape) {
392 tensor_name = UTILITY::Clean_name(tensor_name);
393 if (CheckIfTensorAlreadyExist(tensor_name)) {
394 throw std::runtime_error("TMVA-SOFIE: intermediate tensor with name " + tensor_name + " already exists \n");
395 }
396 TensorInfo new_tensor {type, shape};
397 fIntermediateTensorInfos[tensor_name] = new_tensor;
398}
399
400void RModel::AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector<Dim> shape){
401 tensor_name = UTILITY::Clean_name(tensor_name);
402 if (CheckIfTensorAlreadyExist(tensor_name)){
403 throw std::runtime_error("TMVA-SOFIE: intermediate tensor with name " + tensor_name + " already exists \n");
404 }
405 DynamicTensorInfo new_tensor {type, shape};
406 fDynamicTensorInfos[tensor_name] = new_tensor;
407 // store shape parameter if not existing
408 for (auto &d : shape) {
409 if (d.isParam) {
410 if (d.dim != size_t(-1)) {
411 AddShapeParam(d.param, d.dim);
412 }
413 }
414 }
415}
416
417void RModel::AddShapeParam(const std::string & param, size_t default_value) {
418 // a parameter computed at run time by an operator is never a Session constructor argument
419 if (fComputedShapeParams.count(param) != 0)
420 return;
421 if (fShapeParams.count(param) == 0) {
422 fShapeParams[param] = std::to_string(default_value);
423 // add also in the vector list (used to keep the order)
424 fDimShapeNames.push_back(param);
425 }
426}
427
428void RModel::AddComputedShapeParam(const std::string &param)
429{
430 fComputedShapeParams.insert(param);
431 // it may already be registered as an argument, reached through a shape that broadcasting
432 // rebuilt from a string; the operator's own declaration is the only one that should remain
433 fShapeParams.erase(param);
434 fDimShapeNames.erase(std::remove(fDimShapeNames.begin(), fDimShapeNames.end(), param), fDimShapeNames.end());
435}
436
437void RModel::AddOutputTensorNameList(std::vector<std::string> outputtensornames) {
438 fOutputTensorNames.clear();
439 for(auto& it : outputtensornames) {
440 fOutputTensorNames.emplace_back(UTILITY::Clean_name(it));
441 }
442}
443
444void RModel::UpdateOutputTensorList(std::vector<std::string> curr_output_tensors, std::vector<std::string> new_output_tensors) {
445 for(auto& it:curr_output_tensors) {
446 fOutputTensorNames.erase(std::remove(fOutputTensorNames.begin(), fOutputTensorNames.end(), it), fOutputTensorNames.end());
447 }
448 fOutputTensorNames.insert(fOutputTensorNames.end(), new_output_tensors.begin(), new_output_tensors.end());
449}
450
451void RModel::UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape, std::shared_ptr<void> data) {
452 tensor_name = UTILITY::Clean_name(tensor_name);
453 if (!CheckIfTensorAlreadyExist(tensor_name)) {
454 throw std::runtime_error("TMVA-SOFIE: tensor " + tensor_name + " not found when trying to update it");
455 }
456 InitializedTensor new_tensor {type, shape, data};
457 fInitializedTensors[tensor_name] = new_tensor;
458}
459
460std::shared_ptr<void> RModel::GetInitializedTensorData(std::string tensor_name) {
461 auto f = fInitializedTensors.find(tensor_name);
462 if (f == fInitializedTensors.end()) {
463 throw std::runtime_error("TMVA-SOFIE: tensor " + tensor_name + " not found when trying to get its data");
464 } else {
465 return f->second.sharedptr();
466 }
467}
468
469void RModel::SetNotWritableInitializedTensor(const std::string & tensor_name) {
470 auto t = fInitializedTensors.find(tensor_name);
471 if (t == fInitializedTensors.end()) {
472 throw std::runtime_error("TMVA-SOFIE: initialized tensor " + tensor_name + " not found when trying to get its info");
473 }
474 t->second.SetNotWritable();
475 }
476
477std::string RModel::AllocateIntermediateMemory(std::span<const std::string_view> op_output_tensors)
478{
479 std::stringstream code;
480
481 if (fVerbose) {
482 std::cout << "Total chunks allocated\n";
483 for (auto chunk = fIntermediateMemoryInfo.total_stack.begin(); chunk != fIntermediateMemoryInfo.total_stack.end(); ++chunk) {
484 std::cout << "..... chunk " << chunk->first << " size " << chunk->second.tensor_size << " " << chunk->second.tensor_name << std::endl;
485 }
486 }
487
488 auto declareIntermediateTensor = [this, &code](std::string const &name, size_t size, size_t location) {
489 std::string typeName = ConvertTypeToString(GetTensorType(name));
490 code << "\n // Allocating memory for intermediate tensor " << name << " with size " << size << " bytes";
491 code << "\n"
492 << typeName << "* " << TensorMember(name) << " = reinterpret_cast<" << typeName
493 << "*>(fIntermediateMemoryPool.data() + " << location << ");\n";
494 };
495
496 if (fVerbose) std::cout << "*** AllocateIntermediateMemory: Loop on op output tensors\n";
497 // order output tensors by size
498 std::vector<TensorMemoryInfo> ordered_output_tensors;
499
500 for (auto &it : op_output_tensors) {
501 auto name = std::string(it);
504 continue;
505
506 // case of alias tensor
507 if (IsAliasTensor(name)) {
508 continue;
509 }
510
512 // important fill the pair in the ordered output tensors with the string view and not the string
513 TensorMemoryInfo tmi = {it, tensor_size};
514 ordered_output_tensors.push_back(tmi);
515 }
516 std::sort(ordered_output_tensors.begin(), ordered_output_tensors.end(),
517 [](const TensorMemoryInfo &a, const TensorMemoryInfo &b) { return a.tensor_size > b.tensor_size; });
518
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;
523 if (fVerbose)
524 std::cout << "output tensor " << name << " size " << tensor_size << std::endl;
525
526 for (auto chunk = fIntermediateMemoryInfo.available_stack.begin();
528
529 if (fVerbose) std::cout << ".. available chunk " << chunk->first << " with size = " << chunk->second;
530 // check if available memory chunks can accommodate the tensor
531 if (chunk->second >= tensor_size) {
532 // need to use here string_view (i.e it.tensor_name)
533 // split returns the new chunk with size of new tensor. The free chunk is before the used one
534 auto new_chunk = fIntermediateMemoryInfo.total_stack[chunk->first].split(it.tensor_name, tensor_size);
535 auto new_chunk_location = chunk->first + chunk->second - tensor_size;
536 fIntermediateMemoryInfo.total_stack[new_chunk_location] = new_chunk;
537
538 declareIntermediateTensor(name, tensor_size, new_chunk_location);
539 chunk->second -= tensor_size;
540
541 allocated = true;
542
543 if (fVerbose) std::cout << " is re-used and split in a new of size " << new_chunk.tensor_size << " at " << new_chunk_location;
544
545 if (chunk->second == 0) {
546 if (fVerbose) std::cout << " and deleted since size matches";
548 }
549 if (fVerbose) std::cout << std::endl;
550 break;
551 } else if (chunk->first == fIntermediateMemoryInfo.available_stack.rbegin()->first &&
552 fIntermediateMemoryInfo.total_stack.rbegin()->first == chunk->first) {
553 // case last available chunk is the last in the memory, we can increase that one
554 fIntermediateMemoryInfo.total_stack[chunk->first] = {it.tensor_name, tensor_size};
555 declareIntermediateTensor(name, tensor_size, chunk->first);
557 allocated = true;
558 if (fVerbose) std::cout << " is extended with a bigger one of size " << tensor_size << std::endl;
559 break;
560 }
561 ++chunk;
562 if (fVerbose) std::cout << std::endl;
563 }
564
565 if (!allocated) {
566 size_t chunk_idx = fIntermediateMemoryInfo.total_stack.empty()
567 ? 0
568 : fIntermediateMemoryInfo.total_stack.rbegin()->first +
569 fIntermediateMemoryInfo.total_stack.rbegin()->second.tensor_size;
570
571 fIntermediateMemoryInfo.total_stack[chunk_idx] = it;
572
573 declareIntermediateTensor(name, tensor_size, chunk_idx);
574
575 if (fVerbose) std::cout << "no chunk available - add in total stack a new chunk with size of tensor and idx : " << chunk_idx
576 << std::endl;
577 }
578 }
579 return code.str();
580}
581
582void RModel::CheckAndFlushIntermediateMemory(std::span<const std::string_view> op_input_tensors, const size_t& op_idx){
583 if (fVerbose) std::cout << "*** CheckAndFlushIntermediateMemory: Loop on input tensors for op " << op_idx << "\n";
584 //print available chunks
585 if (fVerbose) std::cout << "available chunks before freeing them : \n";
586 for (auto chunk = fIntermediateMemoryInfo.available_stack.begin();
587 chunk != fIntermediateMemoryInfo.available_stack.end(); chunk++) {
588 if (fVerbose) std::cout << "-- free chunk " << chunk->first << " size = " << chunk->second << std::endl;
589 }
590 for (auto &iv : op_input_tensors) {
591 // last occurrence of the tensor is reached => flush it from memory
592 if (fVerbose) std::cout << ".. input tensors : " << iv;
593
594 // for alias tensors the memory to flush is the one of the tensor they refer to
595 std::string it{iv}; // convert view to string
596 if (IsAliasTensor(it))
597 it = fAliasTensors[it];
598 // find(): operator[] would insert a key viewing the local string
599 auto lastUse = fIntermediateTensorFrequencyLookup.find(it);
600 if (lastUse != fIntermediateTensorFrequencyLookup.end() && lastUse->second == op_idx) {
601 if (fVerbose) std::cout << " flash condition is met - looping on chunks to find matching one \n";
602 for (auto chunk = fIntermediateMemoryInfo.total_stack.begin();
603 chunk != fIntermediateMemoryInfo.total_stack.end(); ++chunk) {
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;
607 // check if nearby chunks in available memory can coalesce
608 auto first_greater = fIntermediateMemoryInfo.available_stack.upper_bound(
609 chunk->first); // smallest element greater than the flushed chunk idx
610 auto last_smaller = (first_greater == fIntermediateMemoryInfo.available_stack.begin())
612 : std::prev(first_greater); // largest element smaller than the flushed chunk idx
613
614 // check if the next stack entry is actually adjacent in memory
615
616 if (last_smaller != fIntermediateMemoryInfo.available_stack.end() &&
617 last_smaller->first + last_smaller->second == chunk->first) {
618 // merge chunk with previous one
619 last_smaller->second += chunk->second.tensor_size;
620 fIntermediateMemoryInfo.total_stack[last_smaller->first].merge(chunk->second);
621 if (fVerbose) std::cout << " is adjacent in memory with previous one - merge ";
622 if (first_greater != fIntermediateMemoryInfo.available_stack.end() &&
623 last_smaller->first + last_smaller->second == first_greater->first) {
624 // merge also with following one
625 last_smaller->second += first_greater->second;
626 fIntermediateMemoryInfo.total_stack[last_smaller->first].merge(
627 fIntermediateMemoryInfo.total_stack[first_greater->first]);
628 // delete merged one in available stack and in total stack
629 fIntermediateMemoryInfo.total_stack.erase(first_greater->first);
630 fIntermediateMemoryInfo.available_stack.erase(first_greater);
631 if (fVerbose) std::cout << " merge also with following that is free ";
632 }
633 fIntermediateMemoryInfo.total_stack.erase(chunk->first);
634 if (fVerbose) std::cout << std::endl;
635 break;
636 } else if (first_greater != fIntermediateMemoryInfo.available_stack.end() &&
637 chunk->first + chunk->second.tensor_size == first_greater->first) {
638 // merge with first greater
639 if (fVerbose) std::cout << " is adjacent in memory with following one - merge \n";
640 // cannot modify idx of first_greter. Insert a new one and delete previous one
641 size_t new_size = chunk->second.tensor_size + first_greater->second;
642 size_t first_greater_idx = first_greater->first;
643 fIntermediateMemoryInfo.available_stack.erase(first_greater);
644 // cannot use anymore first_greater
645 fIntermediateMemoryInfo.available_stack.insert({chunk->first, new_size});
646 fIntermediateMemoryInfo.total_stack[chunk->first].merge(
647 fIntermediateMemoryInfo.total_stack[first_greater_idx]);
648 fIntermediateMemoryInfo.total_stack.erase(first_greater_idx);
649 } else {
650 fIntermediateMemoryInfo.available_stack.insert({chunk->first, chunk->second.tensor_size});
651 if (fVerbose) std::cout << " insert in the available stack the chunk with size " << chunk->second.tensor_size << std::endl;
652 }
653 chunk->second.tensor_name = "free";
654 break;
655 }
656 }
657 } else {
658 if (fVerbose) std::cout << std::endl;
659 }
660 }
661}
662
663void RModel::Initialize(int batchSize, bool verbose) {
664 std::map<std::string, size_t> inputParams;
665 if (batchSize > 0) {
666 inputParams["input_size"] = batchSize;
667 inputParams["batch_size"] = batchSize;
668 inputParams["bs"] = batchSize;
669 }
670 Initialize(inputParams, verbose);
672}
673void RModel::Initialize(const std::map<std::string, size_t> & inputParams, bool verbose) {
674
675 fVerbose = int(verbose);
676
677 if (fIsInitialized) {
678 if (verbose)
679 std::cout << "Model is already initialized - skip initialization " << std::endl;
680 return;
681 }
683 fDynamicTensorInfos.clear();
684
685
686 // loop on inputs and see if shape can be full specified
687 // if the batch size is provided it can be used to specify the full shape
688 // Add the full specified tensors in fReadyInputTensors collection
689 auto originalInputTensorInfos = fInputTensorInfos; // need to copy because we may delete elements
690 // Visit the inputs in their model order, not in the platform-dependent
691 // iteration order of the unordered map: this loop registers the shape
692 // parameters, which defines the order of the Session constructor arguments.
693 for (auto const &inputName : fInputTensorNames) {
694 auto found = originalInputTensorInfos.find(inputName);
695 if (found == originalInputTensorInfos.end())
696 continue; // the shape of this input is already fully defined
697 auto &input = *found;
698 if (verbose) std::cout << "looking at the tensor " << input.first << std::endl;
699 // if a parameter (e.g. batch_size) is specified use for converting parametric shape in defined one
700 if (!inputParams.empty()) {
701 for (auto &d : input.second.shape) {
702 if (d.isParam) {
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 };
708 if (verbose)
709 std::cout << "Tensor: " << input.first << " - fix parametric shape " << itr->first << " to " << itr->second << std::endl;
710 }
711 }
712 }
713 }
714 // see if shape now is fully defined
715 auto shape = ConvertShapeToInt(input.second.shape);
716 if (verbose)
717 std::cout << "converting input shape for " << input.first << " " << ConvertShapeToString(shape) << " from "
718 << ConvertDimShapeToString(input.second.shape) << std::endl;
719 if (!shape.empty()) {
720 // case shape is defined (not parametric) we add the tensor in the fReadyInputTensorInfos map and
721 // we remove the tensor from the fInputTensorInfo where th eold parametric shape was stored
722 fInputTensorInfos.erase(input.first);
723 // add to the ready input tensor information the new fixed shape
724 AddInputTensorInfo(input.first, input.second.type, shape);
725 // check consistency
726 assert( fReadyInputTensorInfos.size() + fInputTensorInfos.size() == fInputTensorNames.size());
727 }
728 // store the parameters of the input tensors
729 else {
730 // store the found parametric shape parameters
731 for (auto &d : input.second.shape) {
732 if (d.isParam) {
733 // through AddShapeParam, which keeps out the parameters computed at run time
734 AddShapeParam(d.param, d.dim);
735 }
736 }
737 }
738 }
739
740 if (verbose) {
743 }
744
745 // Go through model and initialize each operator
746 int i = 0;
747
748 std::vector<size_t> temp_available_stack; // vector stores individual chunks of available memory that maybe reused
749
750 // Build set of initialized tensors consumed by at least one runtime operator (need for later)
751 std::unordered_set<std::string> runtimeInitializedInputs;
752 for(size_t op_idx = 0; op_idx < fOperators.size(); ++op_idx){
753 if (verbose) {
754 auto& r = *fOperators[op_idx].get();
755 std::cout << "Initializing operator " << i << " " << typeid(r).name() << std::endl;
756 }
757 fOperators[op_idx]->Initialize(*this);
758 for(auto &it:fOperators[op_idx]->GetOpOutputTensors()){
759 std::string name = std::string{it};
760 // check if tensor is not an initialized or output tensor and it is not already in the list
762 std::find(fOutputTensorNames.begin(), fOutputTensorNames.end(), name) == fOutputTensorNames.end() &&
764 {
766 }
767 }
768 // loop for non-constant operators and flag the inputs which are initialized tensors to make sure they are writable
769 if (!fOperators[op_idx]->IsOutputConstant()) {
770 for (auto &it : fOperators[op_idx]->GetOpInputTensors()) {
771 std::string name = std::string{it};
772 if (fInitializedTensors.find(name) != fInitializedTensors.end()) {
773 runtimeInitializedInputs.insert(name);
774 }
775 }
776 }
777
778 i++;
779 }
780
781 // loop on initialized tensors and make the integers as constant to be
782 // not written in a weight file and check if the tensors flagged as not writable are really not writable,
783 // i.e. are not used by non constant operators
784 for (auto &it : fInitializedTensors) {
785 // check if not-writable tensors are really not writable, i.e. are not used by non constant operators
786 if (it.second.IsNotWritable() && runtimeInitializedInputs.find(it.first) != runtimeInitializedInputs.end()) {
787 it.second.SetWritable();
788 if (verbose) {
789 std::cout << "Initialized tensor " << it.first << " is flagged as not writable but is used by non constant operators, set it as writable \n";
790 }
791 }
792 // if the tensor is an integer we can flag it as constant since it will not be written in a weight file and it is considered equivalent as being created from a Constant operator
793 // only FLOAT tensors are written in a weight file
794 if (it.second.type() != ETensorType::FLOAT) {
795 it.second.SetConstant();
796 }
797 }
798
799 // check if there are initialized tensors to write in a weight file
800 if (fUseWeightFile) {
801 bool modelHasWeights = false;
802 for (auto &it : fInitializedTensors) {
803 if (it.second.IsWeightTensor()) {
804 modelHasWeights = true;
805 break;
806 }
807 }
808 if (!modelHasWeights)
809 fUseWeightFile = false;
810 }
811
812 // update fIntermediateTensorFrequencyLookup for alias tensors
813 for (auto & it : fAliasTensors) {
817 else {
818 // take the largest one
820 }
821 }
822
823 fIsInitialized = true;
824}
825
826void RModel::InitializeSubGraph(std::shared_ptr<RModel> graph) {
827 // add the subgraph to the list
828 fSubGraphs.push_back(graph);
829 //this needs to be done before initializing
830 graph->fParentGraph = this;
831 graph->fIsSubGraph = true;
832
833 graph->Initialize(fBatchSize, fVerbose);
834 // set the same options as parent model
835 graph->fWeightFile = fWeightFile;
836 // a subgraph without weights has no weight file to read, as in Initialize()
837 bool graphHasWeights = false;
838 for (auto &it : graph->fInitializedTensors) {
839 if (it.second.IsWeightTensor()) {
840 graphHasWeights = true;
841 break;
842 }
843 }
844 graph->fUseWeightFile = fUseWeightFile && graphHasWeights;
845 // add needed blas routines and libs
846 std::vector<std::string> blasRoutines;
847 for (auto & e : graph->fNeededBlasRoutines)
848 blasRoutines.push_back(e);
849 AddBlasRoutines(blasRoutines);
850 for (auto e : graph->fNeededStdLib)
852 // helper functions used by the subgraph must be emitted in the top-level
853 // header, so propagate them to the parent model
854 for (auto const &h : graph->GetNeededHelperFunctions())
856
857 // add parent input tensors to current graph
858 for (auto & name : fInputTensorNames)
859 graph->fInputTensorNames.emplace_back(name);
860
861 // clean graph name
862 graph->fName = UTILITY::Clean_name(graph->fName);
863
864}
865
866// Function to generate the code for declaring and initializing constant tensors
867// This is for tensors which are not part of weight files and can be created from the Constant operator
868template <typename T>
869std::string GenerateConstantTensorCode(const std::pair<std::string, InitializedTensor> &t)
870{
871 std::stringstream strs;
872 std::string type = ConvertTypeToString(t.second.type());
873 size_t length = ConvertShapeToLength(t.second.shape());
874 // avoid using stack sizes for constant tensors to reduce compilation time
875 // also for weights which can be broadcasted do not use stack but allocate as a std::vector
876 bool allocateOnStack = (length > 100 || t.second.IsWeightTensor()) ? false : true;
877
878 const T *data = t.second.data<T>();
879
880 // and check if all values are the same
881 bool sameData = false;
882
883 // for non stack allocation check if data are the same
884 if (!allocateOnStack && length > 1) {
885 size_t idx = 1;
886 do {
887 sameData = (data[idx] == data[idx - 1]);
888 idx++;
889 } while (sameData && idx < length);
890 }
891 if (allocateOnStack) {
892 strs << type << " fTensor_" << t.first << "[" << length << "] = " << ConvertValuesToString(length, data) << ";\n";
893 strs << type << " * " << TensorMember(t.first) << " = fTensor_" + t.first + ";\n";
894 } else {
895 strs << "std::vector<" << type << "> fTensor_" << t.first << " = ";
896 if (sameData)
897 strs << "std::vector<" << type << ">(" << length << ", " << ConvertValToString(data[0]) << ");\n";
898 else {
899 strs << ConvertValuesToString(length, data) << ";\n";
900 }
901 strs << type << " * " << TensorMember(t.first) << " = fTensor_" + t.first + ".data();\n";
902 }
903 return strs.str();
904}
905
907{
908 if (!fInitializedTensors.empty())
909 fGC += "// initialized (weights and constant) tensors\n";
910
911 // here are constant tensor or initialized ones which are not weights (e.g. int64_t tensors )
912 for (auto &i : fInitializedTensors) {
913 if (i.second.IsNotWritable()) continue;
914 size_t length = ConvertShapeToLength(i.second.shape());
915 if (!fUseWeightFile || i.second.IsConstantTensor() || !i.second.IsWeightTensor() || i.second.type() != ETensorType::FLOAT ) {
916 if (i.second.type() == ETensorType::FLOAT) {
917 // check if NaN of Inf are inside tensor data
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])) {
923 hasInfOrNaN = true;
924 break;
925 }
926 }
927 }
928 if (hasInfOrNaN)
929 AddNeededStdLib("limits");
930 fGC += GenerateConstantTensorCode<float>(i);
931 fConstantTensorSize += length * sizeof(float);
932 } else if (i.second.type() == ETensorType::INT64) {
933 fGC += GenerateConstantTensorCode<int64_t>(i);
934 fConstantTensorSize += length * sizeof(int64_t);
935 } else if (i.second.type() == ETensorType::INT32) {
936 fGC += GenerateConstantTensorCode<int32_t>(i);
937 fConstantTensorSize += length * sizeof(int32_t);
938 } else if (i.second.type() == ETensorType::BOOL || i.second.type() == ETensorType::UINT8 ) {
939 fGC += GenerateConstantTensorCode<uint8_t>(i);
940 fConstantTensorSize += length * sizeof(uint8_t);
941 }
942
943
944 } else {
945 // case of tensors which are read from a file
946 if (i.second.type() == ETensorType::FLOAT) {
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";
949 fWeightsTensorSize += length * sizeof(float);
950 }
951 }
952 }
953}
954
956 if (fIntermediateMemoryInfo.total_stack.empty()) return;
957 fGC += "\n//--- Allocating session memory pool to be used for allocating intermediate tensors\n";
958
959 // char memory block is allocated since char takes 1 byte, thus easier to allocate tensors
960 // of other data types
961 auto const &totalStack = fIntermediateMemoryInfo.total_stack;
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";
964}
965
967 if (!fIntermediateTensorInfos.empty()) {
968 std::string tensor_declaration_block = "";
969 for (auto &i : fIntermediateTensorInfos) {
970 // alias tensors have no storage: the operator creating them declares a pointer to the
971 // memory of the tensor they refer to
972 if (IsAliasTensor(i.first))
973 continue;
974 if (i.second.type == ETensorType::BOOL) {
975 tensor_declaration_block += "std::vector<std::uint8_t> fTensor_" + i.first +
976 " = std::vector<std::uint8_t>(" +
977 std::to_string(ConvertShapeToLength(i.second.shape)) + ");\n";
978 tensor_declaration_block +=
979 "std::uint8_t * " + TensorMember(i.first) + " = fTensor_" + i.first + ".data();\n";
980 continue;
981 }
982 bool is_extended = (fOptimizationLevel == OptimizationLevel::kExtended);
983 bool not_in_freq_map =
985 bool not_in_output_names =
986 (std::find(fOutputTensorNames.begin(), fOutputTensorNames.end(), i.first) == fOutputTensorNames.end());
987
988 if ((not_in_freq_map && not_in_output_names) || (!not_in_freq_map && !is_extended && not_in_output_names)) {
989 size_t length = ConvertShapeToLength(i.second.shape);
990
991 if (i.second.type == ETensorType::FLOAT) {
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";
995 }
996 else if (i.second.type == ETensorType::DOUBLE) {
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";
1000 }
1001 else if (i.second.type == ETensorType::INT64) {
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";
1004 fOtherTensorSize += 8 * length;
1005 }
1006 }
1007 }
1008
1009 if (tensor_declaration_block.length()) {
1010 fGC += "\n//--- declare and allocate the intermediate tensors\n" + tensor_declaration_block;
1011 }
1012 }
1013 // add also the dynamic tensors (only declarations, allocation will be done later)
1014 if (!fDynamicTensorInfos.empty()) {
1015 fGC += "//--- declare the dynamic tensors\n";
1016 for (auto &i : fDynamicTensorInfos) {
1017 if (IsAliasTensor(i.first))
1018 continue;
1019 fGC += ConvertTypeToString(i.second.type) + " * " + TensorMember(i.first) + " = nullptr;\n";
1020 }
1021 fGC += "//--- dynamic tensors pool\n";
1022 fGC += "std::vector<char> fDynamicMemoryPool;\n";
1023 }
1024}
1025
1026// generate code for specific operator declarations to be defined in the Session class
1028 std::string strcode;
1029 for (auto & op : fOperators) {
1030 strcode += op->GenerateDeclCode();
1031 }
1032 if (strcode.empty()) return;
1033 fGC += "\n//---- operator declarations \n";
1034 fGC += strcode;
1035 fGC += "\n";
1036}
1037
1039{
1040 // generate code for allocating dynamic tensors using the greedy memory allocations
1041 if (fDynamicTensorInfos.empty())
1042 return;
1043
1044 if (fVerbose) {
1045 std::cout << "generating code for dynamic tensor management" << std::endl;
1047 }
1048
1049 // the generated code uses the TensorLifeInfo / OrganizeMemory inference helpers
1050 AddNeededHelperFunction("DynamicMemory");
1051
1052 std::stringstream out;
1053 out << "// dynamic tensor memory management\n";
1054 out << SP << "std::vector<TensorLifeInfo> dynamicTensorInfos;\n";
1055 out << SP << "dynamicTensorInfos.reserve(" << fDynamicTensorInfos.size() << ");\n";
1056
1057 // loop on all the operators to find begin/end life of the tensors
1058 int op_index = 0;
1059 std::vector<std::pair<std::string, ETensorType>> tensors;
1060 tensors.reserve(fDynamicTensorInfos.size());
1061 for (auto & op : fOperators) {
1062 // loop on output tensors -
1063 for (auto &it : op->GetOpOutputTensors()) {
1064 if (fVerbose) {
1065 auto op_ptr = op.get();
1066 std::cout << "Looping on operator " << op_index << " " << typeid(*op_ptr).name() << std::endl;
1067 }
1068 // check if is a dynamic tensor and not an alias tensor or output tensor
1069 std::string name = std::string(it);
1071 && std::find(fOutputTensorNames.begin(), fOutputTensorNames.end(), name) == fOutputTensorNames.end()) {
1072 auto tensor_size = ConvertDimShapeToLength(GetDimTensorShape(name));
1073 auto type = GetTensorType(name);
1074 size_t type_size = GetTypeSize(type);
1075 int begin = op_index;
1076 int end = fOperators.size();
1077 // look for end
1078 auto it_lookup = fIntermediateTensorFrequencyLookup.find(name);
1079 if (it_lookup != fIntermediateTensorFrequencyLookup.end())
1080 end = it_lookup->second + 1; // end is last time used + 1
1081 // // some tensors (like xcol in convolutions) are just used within the operators
1082 // if (end == 0 && begin > 0) end = begin+1;
1083
1084 if (begin> end) {
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");
1087 }
1088
1089 // write in code
1090 out << SP << "dynamicTensorInfos.push_back( {" << begin << ", " << end << ", " << type_size << "* (" << tensor_size << ") });"
1091 << " // tensor_" << name << std::endl;
1092 tensors.push_back({name,type});
1093 }
1094 }
1095 op_index++; // increment operator index
1096 }
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";
1103 }
1104 // check that all dynamic tensors are covered
1105 bool missingTensor = false;
1106 for (auto &i : fDynamicTensorInfos) {
1107 if (IsAliasTensor(i.first)) continue;
1108 if (std::find(fOutputTensorNames.begin(), fOutputTensorNames.end(), i.first) != fOutputTensorNames.end()) continue;
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;
1112 }
1113 }
1114 if (missingTensor)
1115 throw std::runtime_error("TMVA-SOFIE: RModel::GenerateDynamicTensorInfo - some tensors are not in input/output list");
1116
1117 fGC += out.str();
1118}
1119
1120std::vector<std::string> RModel::RuntimeBoundParams(const std::string &name) const
1121{
1122 std::vector<std::string> params;
1123 // an alias has no memory of its own
1124 if (fDynamicTensorInfos.count(name) == 0 || IsAliasTensor(name))
1125 return params;
1126 for (auto const &dim : GetDynamicTensorShape(name)) {
1127 // only a parameter the user gives to the Session has a maximum to check
1128 if (dim.isParam && IsIdentifier(dim.param) && fShapeParams.count(dim.param) && !IsInputTensorShapeParam(dim.param))
1129 params.push_back(dim.param);
1130 }
1131 return params;
1132}
1133
1134const std::string kCheckMarker = "//@check ";
1135std::string RModel::SizeCheckMarker(const std::string &name)
1136{
1137 return "\n " + kCheckMarker + name + "\n";
1138}
1139
1140/// Check if a given parameter is used for the shape of an input tensor.
1141bool RModel::IsInputTensorShapeParam(std::string const &paramName) const
1142{
1143 for (auto &name : fInputTensorNames) {
1144 if (IsDimInputTensor(name)) {
1145 auto shape = GetDynamicTensorShape(name);
1146 for (auto &d : shape) {
1147 if (d.param == paramName)
1148 return true;
1149 }
1150 }
1151 }
1152 return false;
1153}
1154
1155/// Collects all identifiers starting with "tensor_" in the input code,
1156/// provided that the occurrence is not immediately preceded by a
1157/// character that is valid in a C++ identifier. Excludes input and output tensor names.
1158/// Returns a deduplicated std::vector<std::string>.
1159std::vector<std::string> RModel::CollectTensorMemberNames(const std::string &input)
1160{
1161 const std::string target = "tensor_";
1162
1163 std::vector<std::string> result;
1164
1165 for (size_t i = 0; i < input.size();) {
1166
1167 bool doCollect = false;
1168
1169 if (i + target.size() <= input.size() && input.compare(i, target.size(), target) == 0 &&
1170 (i == 0 || !IsIdentifierChar(input[i - 1]))) {
1171
1172 doCollect = true;
1173
1174 std::size_t j = i + target.size();
1175
1176 // Extend to full identifier
1177 while (j < input.size() && IsIdentifierChar(input[j]))
1178 ++j;
1179
1180 std::string fullName = input.substr(i, j - i);
1181
1182 // Exclude input tensor names
1183 for (std::string const &name : fInputTensorNames) {
1184 if (fullName == target + name) {
1185 doCollect = false;
1186 break;
1187 }
1188 }
1189
1190 // Exclude output tensor names
1191 if (doCollect) {
1192 for (std::string const &name : fOutputTensorNames) {
1193 if (fullName == target + name) {
1194 doCollect = false;
1195 break;
1196 }
1197 }
1198 }
1199
1200 if (doCollect) {
1201 result.push_back(fullName);
1202 }
1203
1204 i = j; // advance past the identifier
1205 } else {
1206 ++i;
1207 }
1208 }
1209
1210 // Deduplicate (order not preserved)
1211 std::sort(result.begin(), result.end());
1212 result.erase(std::unique(result.begin(), result.end()), result.end());
1213
1214 return result;
1215}
1216
1217std::string RModel::GenerateInferSignature(bool isdecl) {
1218 // generate the infer signature given the inputs: eg. "float * tensor1, float * tensor2"
1219 // if (decl = false) generate only calling signature (tensor1,tensor2,....)
1220 std::string rGC;
1221 std::unordered_map<std::string, int> inputParams;
1222 int i_input = 0;
1223 for (auto &name : fInputTensorNames) {
1224 // if is a dynamic tensor pass initial parameters
1225 if (IsDimInputTensor(name)) {
1226 auto shape = GetDynamicTensorShape(name);
1227 for (auto &d : shape) {
1228 std::string pName = d.param;
1229 // need to check if the input parameters is already existing in another input tensor
1230 if (d.isParam && inputParams.count(pName) == 0) {
1231 if (isdecl) rGC += "size_t ";
1232 rGC += d.param + ",";
1233 inputParams[pName] = i_input;
1234 }
1235 }
1236 }
1237 if (isdecl) {
1239 // ConvertTypeToString returns "other_<type number>" for the types it does not know
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* ";
1244 }
1245 rGC += "tensor_" + name + ",";
1246 i_input++;
1247 }
1248
1249 if (fInputTensorNames.size() > 0) rGC.pop_back();// remove last ","
1250 return rGC;
1251}
1252
1253namespace {
1254
1255std::string typeForOutput(ETensorType t) {
1256 // The std::vector<bool> is a special type that is not wrapping continuous memory.
1257 // We don't want to use it as a return type.
1259 return ConvertTypeToString(t);
1260}
1261
1262std::string memberNameForDimShape(std::string name)
1263{
1264 if (!name.empty()) {
1265 name[0] = std::toupper(static_cast<unsigned char>(name[0]));
1266 }
1267 name = "f" + name;
1268 return name;
1269}
1270
1271}
1272
1274{
1275 size_t outputSize = fOutputTensorNames.size();
1276 // assume output types are all the same
1277
1278 bool sameOutputTypes = true;
1279 std::string inferReturnType; // type return by infer function
1280 ETensorType eFirstOutputType = GetTensorType(*fOutputTensorNames.begin());
1281 fGC += "\n\n";
1282 if (outputSize == 1) {
1283 fGC += "std::vector<" + typeForOutput(eFirstOutputType) + ">";
1284 } else {
1285 // if all output types are the same we return an std::vector - otherwise a tuple
1286 for (std::string const &name : fOutputTensorNames) {
1287 if (GetTensorType(name) != eFirstOutputType)
1288 sameOutputTypes = false;
1289 }
1290 if (sameOutputTypes)
1291 fGC += "std::vector<std::vector<" + typeForOutput(eFirstOutputType) + ">>";
1292 else {
1293 inferReturnType = "std::tuple<";
1294 for (size_t i = 0; i < outputSize; i++) {
1295 inferReturnType += "std::vector<" + typeForOutput(GetTensorType(fOutputTensorNames[i])) + ">";
1296 if (i < outputSize - 1)
1297 inferReturnType += ",";
1298 }
1299 inferReturnType += ">";
1300 fGC += inferReturnType;
1301 }
1302 }
1303
1304 fGC += " infer(" + GenerateInferSignature() + "){\n";
1305
1306 std::string doInferArgs = GenerateInferSignature(false);
1307 if (!doInferArgs.empty())
1308 doInferArgs += ",";
1309 // several outputs can share one run-time shape parameter: declare and pass it once
1310 std::unordered_set<std::string> emittedShapeParams;
1311 for (std::string const &name : fOutputTensorNames) {
1312 bool isDynamic = fDynamicTensorInfos.count(name) > 0;
1313 std::string n;
1314 if(!isDynamic) {
1315 n = std::to_string(ConvertShapeToLength(GetTensorShape(name)));
1316 } else {
1317 // Use the session members, the maximum sizes, when any dim depends on a run-time computed
1318 // parameter. For expression-type dims derived from input shapes, use the expression directly.
1319 // for input shape parameters we don't need to use the session member since it is passed as
1320 // argument to the infer function and it is not a runtime computed value
1321 auto dims = GetDynamicTensorShape(name);
1322 for (auto &dim : dims) {
1323 if (dim.isParam && IsIdentifier(dim.param) && !IsInputTensorShapeParam(dim.param))
1324 dim.param = memberNameForDimShape(dim.param);
1325 }
1326 n = ConvertDimShapeToLength(dims);
1327 }
1328 std::string outputName = "output_tensor_" + name;
1329 fGC += SP + "std::vector<" + typeForOutput(GetTensorType(name)) + " > " + outputName + "(" + n + ");\n";
1330 doInferArgs += " " + outputName + ".data(),";
1331 if(isDynamic) {
1332 for (auto const &dim : GetDynamicTensorShape(name)) {
1333 if (dim.isParam && !IsInputTensorShapeParam(dim.param) && IsIdentifier(dim.param) &&
1334 emittedShapeParams.insert(dim.param).second) {
1335 fGC += SP + "size_t " + dim.param + " = 0;\n";
1336 doInferArgs += " " + dim.param + ",";
1337 }
1338 }
1339 }
1340 }
1341 if (!doInferArgs.empty())
1342 doInferArgs.back() = ' ';
1343
1344 // verifying if the dynamic parameters are within allowed range
1345 std::unordered_set<std::string> input_params_checked;
1346 std::string dynamic_parameters_check = "";
1347 for (auto &name : fInputTensorNames) {
1348 if (IsDimInputTensor(name)) {
1349 auto shape = GetDynamicTensorShape(name);
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";
1359 fGC += SP + "}\n";
1360 }
1361 }
1362 }
1363 }
1364
1365 fGC += SP + "doInfer(*this, " + doInferArgs + ");\n";
1366
1367 // If the output tensors have dynamic sizes, now is the time to set them
1368 for (std::string const &name : fOutputTensorNames) {
1369 bool isDynamic = fDynamicTensorInfos.count(name) > 0;
1370 if (isDynamic) {
1371 std::string outputName = "output_tensor_" + name;
1372 auto tensor_size = ConvertDimShapeToLength(GetDimTensorShape(name));
1373 fGC += SP + outputName + ".resize(" + tensor_size + ");\n";
1374 }
1375 }
1376
1377 fGC += SP + "return {";
1378 for (size_t i = 0; i < fOutputTensorNames.size(); i++) {
1379 fGC += "output_tensor_" + fOutputTensorNames[i];
1380 if (i < fOutputTensorNames.size() - 1)
1381 fGC += ",";
1382 }
1383 fGC += "};\n";
1384 fGC += "}\n"; // end of infer function scope
1385}
1386
1388{
1389 std::string sessionName = !fIsSubGraph ? "Session" : "Session_" + fName;
1390
1391 // forward declare session struct
1392 fGC += "struct " + sessionName + ";\n";
1393
1394 // Determine the signature of the actual inference function
1395 std::string doInferSignature = GenerateInferSignature();
1396 if (!doInferSignature.empty())
1397 doInferSignature += ", ";
1398 // one argument per shape parameter, even when several outputs share it
1399 std::unordered_set<std::string> signatureShapeParams;
1400 for (auto const &name : fOutputTensorNames) {
1401 bool isDynamic = fDynamicTensorInfos.count(name) > 0;
1402 doInferSignature += typeForOutput(GetTensorType(name)) + " *tensor_" + name + ",";
1403 if(isDynamic) {
1404 for (auto const &dim : GetDynamicTensorShape(name)) {
1405 if (dim.isParam && !IsInputTensorShapeParam(dim.param) && IsIdentifier(dim.param) &&
1406 signatureShapeParams.insert(dim.param).second)
1407 doInferSignature += " size_t &" + dim.param + "_output,";
1408 }
1409 }
1410 }
1411 doInferSignature.back() = ' ';
1412
1413 doInferSignature = sessionName + " const &session, " + doInferSignature;
1414
1415 doInferSignature = "inline void doInfer(" + doInferSignature + ")";
1416
1417 // forward declare inference implementation
1418 fGC += doInferSignature + ";\n";
1419
1420 // define the Session struct: copying is not allowed because some members
1421 // are pointers to memory owned by the std::vector members of the session
1422 // struct. Since the std::vector-owned memory is not relocated when moving,
1423 // move contruction and assignment is allowed.
1424 std::string sessionCode = R"(struct @SESSION@ {
1425
1426 ~@SESSION@() = default;
1427
1428 @SESSION@(@SESSION@ const&) = delete;
1429 @SESSION@(@SESSION@ &&) = default;
1430
1431 @SESSION@& operator=(@SESSION@ const&) = delete;
1432 @SESSION@& operator=(@SESSION@ &&) = default;
1433
1434 )";
1435 ReplaceAll(sessionCode, "@SESSION@", sessionName);
1436 fGC += sessionCode;
1437
1438 // generate code for declaring the initialized tensors
1440
1442 // evaluate total intermediate memory and position intermediate tensor addresses
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) {
1446 if (fVerbose) {
1447 auto op = fOperators[op_idx].get();
1448 std::cout << "\n******************\n analyzing input/output operator " << op_idx << " "
1449 << typeid(*op).name() << std::endl;
1450 }
1451 intermediate_memory_alloc_string += AllocateIntermediateMemory(fOperators[op_idx]->GetOpOutputTensors());
1452 CheckAndFlushIntermediateMemory(fOperators[op_idx]->GetOpInputTensors(), op_idx);
1453 }
1454
1455 // to check remaining unused fragments after memory allocation (lesser the better)
1456 // for (const auto &it: fIntermediateMemoryInfo.available_stack){
1457 // std::cout<<"chunk_idx: "<<it.first<<", chunk_size: "<<it.second<<"\n";
1458 // }
1459
1460 // generate the memory pool to be used by intermediate tensors
1462
1463 // position intermediate tensors
1464 fGC += intermediate_memory_alloc_string;
1465 }
1466
1467 // generate the declaring the intermediate tensors
1469 // generate code for declarations of some specific operators
1471
1472 // storing the parameters for future checking to avoid mismatches
1473 if (!fDimShapeNames.empty()) {
1474 fGC += "\n// dynamic shape parameters\n";
1475 auto dimShapeNames = fDimShapeNames;
1476 std::sort(dimShapeNames.begin(), dimShapeNames.end());
1477 for (const auto &p : dimShapeNames) {
1478 fGC += "size_t " + memberNameForDimShape(p) + ";\n";
1479 }
1480 }
1481
1482 // add subgraph session
1483 if (!fSubGraphs.empty()) fGC += "// subgraph sessions\n";
1484 for (auto & graph : fSubGraphs) {
1485 fGC += "Session_" + graph->fName + " fSession_" + graph->fName + ";\n";
1486 }
1487
1488 // Generate code for Session constructor
1489 // add here specific operator code that needs to define session data members
1490 fGC += "\n";
1491 for (size_t id = 0; id < fOperators.size(); id++) {
1492 std::string opName = std::to_string(id);
1493 fGC += fOperators[id]->GenerateSessionMembersCode(opName);
1494 }
1495 fGC += "\n";
1496 // collect declaration of shape parameters (default values) and argument
1497 // forwarding for delegating constructors
1498 std::string dynParamDecls;
1499 std::string dynParamArgs;
1500 if (!fDimShapeNames.empty()) {
1501 // need to use same order as in infer function not alphabetical one
1502 for (auto &p : fDimShapeNames) {
1503 dynParamDecls += ",\n size_t " + p + " = " + fShapeParams[p];
1504 dynParamArgs += ", " + p;
1505 }
1506 }
1507 // here add initialization and reading of weight tensors
1509 // A Session is constructed from an in-memory safetensors blob; the
1510 // file-based constructor loads the payload fully into memory and
1511 // delegates. The temporary buffer is alive for the duration of the
1512 // delegated constructor call, and the blob constructor copies the
1513 // weights out of it.
1514 AddNeededHelperFunction("SafetensorsBlob");
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 "
1519 "weights\");\n";
1520 fGC += " }\n";
1521 fGC += " return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());\n";
1522 fGC += " }\n\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";
1526 } else if (fUseWeightFile) {
1527 std::string fileName = fName + ".dat";
1528 fGC += sessionName + "(std::string filename =\"" + fileName + "\"" + dynParamDecls + ") {\n";
1529 } else {
1530 // no need to pass weight file since it is not used
1531 // keep passing a string for compatibility
1532 fGC += sessionName + "(std::string = \"\"" + dynParamDecls + ") {\n";
1533 }
1534
1535 // initializing dynamic parameters
1536 if (!fDimShapeNames.empty()) {
1537 fGC += "\n\n";
1538 // sort a copy: fDimShapeNames defines the constructor argument order
1539 auto dimShapeNames = fDimShapeNames;
1540 std::sort(dimShapeNames.begin(), dimShapeNames.end());
1541 for (const auto &p : dimShapeNames) {
1542 fGC += " " + memberNameForDimShape(p) + " = " + p + ";\n";
1543 }
1544 }
1545 // add some extra code needed for initialization of dynamic parameters
1547
1548 if (fUseWeightFile) {
1549 fGC += "\n//--- reading weights from file\n";
1551 fGC += "\n";
1552 // fUseWeightFile = fUseWeightFile;
1553 }
1554
1555 // now we have passed the parameters we can allocate the dynamic tensors
1557
1558 // add here initialization code for operator
1559 for (size_t id = 0; id < fOperators.size(); id++) {
1560 fGC += fOperators[id]->GenerateInitCode();
1561 }
1562
1563 fGC += "}\n\n";
1564
1566 // Models requested with a safetensors weight file but without weight
1567 // tensors also expose the blob constructor, which ignores the blob, so
1568 // that both construction modes exist (from a file and from an in-memory
1569 // blob) whatever the model.
1570 AddNeededHelperFunction("SafetensorsBlob");
1571 fGC += sessionName + "(SafetensorsBlob" + dynParamDecls + ")\n";
1572 fGC += " : " + sessionName + "(std::string{}" + dynParamArgs + ") {}\n\n";
1573 }
1574
1575 // Used to build the tangent Session objects needed to differentiate the
1576 // generated code with Clad: the derivatives of the (constant) weights
1577 // are zero, but a default-constructed Session holds the actual values.
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"
1580 "// with Clad.\n"
1581 "void SetWeightsToZero() {\n";
1582 for (auto &i : fInitializedTensors) {
1583 // IsNotWritable tensors have no emitted fTensor_ member, and integer
1584 // tensors are structural (indices, shapes) that carry no tangent.
1585 if (i.second.IsNotWritable() ||
1586 (i.second.type() != ETensorType::FLOAT && i.second.type() != ETensorType::DOUBLE))
1587 continue;
1588 fGC += " for (auto &v : fTensor_" + i.first + ") v = 0;\n";
1589 }
1590 for (auto &graph : fSubGraphs) {
1591 fGC += " fSession_" + graph->fName + ".SetWeightsToZero();\n";
1592 }
1593 fGC += "}\n\n";
1594
1595 // generate the inference overload that returns an output struct
1597
1598 // end of session
1599 fGC += "}; // end of Session\n\n";
1600
1601 // the input/output tensor info is emitted at namespace scope under fixed names,
1602 // so it must be emitted only once, for the main model and not for its subgraphs
1603 if (!fIsSubGraph)
1605
1606 fGC += doInferSignature + " {\n";
1607 fGC += "\n";
1608
1609 // generate the inference code
1610 if (fVerbose)
1611 std::cout << "Generating main inference code for " << fName << std::endl;
1612
1613 if (fOutputTensorNames.size() == 0)
1614 throw std::runtime_error("TMVA-SOFIE: output size=0 are not supported");
1615
1616 std::string allOperatorCode;
1617
1618 for (size_t op_idx = 0; op_idx < fOperators.size(); ++op_idx) {
1619 if (fVerbose)
1620 std::cout << "Generating code for operator .... " << op_idx << std::endl;
1621 std::string operatorCode = fOperators[op_idx]->Generate(std::to_string(op_idx));
1622 // a tensor whose size depends on parameters computed at run time is checked before the operator
1623 // writes it, unless the operator asked for the check where it knows the size
1624 for (auto const &outName : fOperators[op_idx]->GetOpOutputTensors()) {
1625 std::string name(outName);
1626 if (!RuntimeBoundParams(name).empty() && operatorCode.find(kCheckMarker + name + "\n") == std::string::npos)
1627 operatorCode = SizeCheckMarker(name) + operatorCode;
1628 }
1629 allOperatorCode += operatorCode;
1630 }
1631
1632 // expand the markers: the tensor memory (output buffer or pool) was sized in the Session from the
1633 // maximum values of the parameters, so refuse a larger size before anything is written
1634 {
1635 std::string expanded;
1636 std::istringstream lines(allOperatorCode);
1637 std::string line;
1638 while (std::getline(lines, line)) {
1639 auto pos = line.find(kCheckMarker);
1640 if (pos == std::string::npos) {
1641 expanded += line + "\n";
1642 continue;
1643 }
1644 // like the shape parameters of the input tensors, each one is compared with its maximum
1645 for (auto const &param : RuntimeBoundParams(line.substr(pos + kCheckMarker.size()))) {
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";
1649 }
1650 }
1651 allOperatorCode = expanded;
1652 }
1653
1654 // If the generated code users members of the session struct, use the
1655 // local variable name that we're using for the session:
1656 ReplaceAll(allOperatorCode, "this->", "session.");
1657
1658 // Collect all "tensor_*" data members that are not input or output tensors
1659 std::vector<std::string> tensorMemberNames = CollectTensorMemberNames(allOperatorCode);
1660 const std::string prefix = "tensor_";
1661 for (auto const& name: tensorMemberNames) {
1662 // alias tensors are not session members: the operator creating them declares a local pointer
1663 if (IsAliasTensor(name.substr(prefix.size())))
1664 continue;
1665 fGC += " auto &" + name + " = session." + name + ";\n";
1666 }
1667 fGC += "\n";
1668
1669 // an initialized tensor (constant, or a weight reached e.g. through an Identity) that is a
1670 // model output is not written by any operator: copy it into the output buffer before the
1671 // operator code, so that operators reading the weight also see its value (the output
1672 // parameter shadows the session member in doInfer)
1673 for (auto const &name : fOutputTensorNames) {
1675 std::string t = "session.tensor_" + name;
1677 fGC += " std::copy(" + t + ", " + t + " + " + std::to_string(length) + ", tensor_" + name + ");\n";
1678 }
1679 }
1680
1681 fGC += allOperatorCode;
1682
1683 std::unordered_set<std::string> assignedShapeParams;
1684 for (auto const& name: fOutputTensorNames) {
1685 bool isDynamic = fDynamicTensorInfos.count(name) > 0;
1686 if(isDynamic) {
1687 for (auto const &dim : GetDynamicTensorShape(name)) {
1688 if (dim.isParam && !IsInputTensorShapeParam(dim.param) && IsIdentifier(dim.param) &&
1689 assignedShapeParams.insert(dim.param).second)
1690 fGC += " " + dim.param + "_output = " + dim.param + ";\n";
1691 }
1692 }
1693 }
1694 fGC += "\n";
1695
1696 fGC += "}\n";
1697}
1698
1699void RModel::Generate(std::underlying_type_t<Options> options, int batchSize, bool verbose)
1700{
1701 fVerbose = verbose;
1702 fBatchSize = batchSize;
1703
1704 // weights are contained in the generated header when kNoWeightFile is used
1705 if (static_cast<std::underlying_type_t<Options>>(Options::kNoWeightFile) & options) {
1706 fUseWeightFile = false;
1708 }
1709 if (static_cast<std::underlying_type_t<Options>>(Options::kSafetensorsWeightFile) & options) {
1710 fUseWeightFile = true;
1712 }
1713
1714 // initialize the model including all operators and sub-graphs
1715 Initialize(batchSize, verbose);
1716
1717 std::string hgname;
1718 if (!fIsSubGraph) {
1719 fGC.clear();
1720 GenerateHeaderInfo(hgname);
1721 }
1722
1723 // generate first code for the subgraphs
1724 for (auto &graph : fSubGraphs) {
1725 if (fVerbose)
1726 std::cout << "generate session code for subgraph " << graph->fName << std::endl;
1727 graph->GenerateSessionCode();
1728 fGC += graph->fGC;
1729 }
1730
1731 if (fVerbose)
1732 std::cout << "generate Main session code - model " << fName << std::endl;
1733
1734 // generate main session code
1736
1737 if (!fIsSubGraph) {
1738 fGC += ("} //TMVA_SOFIE_" + fName + "\n");
1739 fGC += "\n#endif // " + hgname + "\n";
1740 // dump the standalone definitions of the helper functions this model uses
1741 // so that the generated header does not depend on TMVA/SOFIE_common.hxx
1743 }
1744}
1745
1747 // generate the code to read initialized tensors from a text data file
1749 // check if there are tensors to write
1750
1751 if (!fUseWeightFile) return;
1752
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";
1757 fGC += " }\n";
1758
1759 // ReadTensorFromStream is emitted as a standalone helper in the header
1760 AddNeededHelperFunction("ReadTensorFromStream");
1761
1762 // loop on tensors and parse the file
1763 for (auto& i: fInitializedTensors) {
1764 // skip Constant and shape tensors (not written in a file)
1765 if (!i.second.IsWeightTensor()) continue;
1766 std::string tensor_name = "tensor_" + i.first;
1767 if (i.second.type() == ETensorType::FLOAT) {
1768 std::string length = std::to_string(ConvertShapeToLength(i.second.shape()));
1769 fGC += " ReadTensorFromStream(f, " + tensor_name + ", \"" + tensor_name + "\", " + length + ");\n";
1770 } else {
1771 throw std::runtime_error("tmva-sofie tensor " + tensor_name + " with type " + ConvertTypeToString(i.second.type()) + " cannot be read from a file");
1772 }
1773 }
1774 fGC += " f.close();\n";
1775 }
1776
1777 // generate the code to read initialized tensors from a safetensors blob
1778 // in memory (the blob comes from a file or directly from the caller)
1780 // the SafetensorsBlob/SafetensorsReader helpers are emitted as
1781 // standalone helpers in the generated header
1782 AddNeededHelperFunction("SafetensorsReader");
1783
1784 fGC += " SafetensorsReader sofie_weights_reader(weights_blob);\n";
1785
1786 for (auto &i : fInitializedTensors) {
1787 // skip Constant and shape tensors (not written in a file)
1788 if (!i.second.IsWeightTensor())
1789 continue;
1790 std::string tensor_name = "tensor_" + i.first;
1791 std::string dtype;
1792 try {
1793 dtype = SafetensorsDType(i.second.type());
1794 } catch (const std::runtime_error &) {
1795 throw std::runtime_error("tmva-sofie tensor " + tensor_name + " with type " +
1796 ConvertTypeToString(i.second.type()) +
1797 " cannot be read from a safetensors payload");
1798 }
1799 std::string length = std::to_string(ConvertShapeToLength(i.second.shape()));
1800 fGC += " sofie_weights_reader.Read(\"" + tensor_name + "\", fTensor_" + i.first + ", " + length + ", \"" +
1801 dtype + "\");\n";
1802 }
1803 }
1804}
1805
1807 // Determine the file extension based on the weight file type
1808 std::string fileExtension;
1809 switch (fWeightFile) {
1811 fileExtension = ".dat";
1812 break;
1814 fileExtension = ".safetensors";
1815 break;
1817 fileExtension = ".dat";
1818 break;
1819 }
1820
1821 // If filename is empty, use the model name as the base filename
1822 if (filename.empty()) {
1823 filename = fFileName + fileExtension;
1824 }
1825
1826 // Write the initialized tensors to the file
1828 std::ofstream f(filename, std::ios::binary);
1829 if (!f.is_open())
1830 throw std::runtime_error("tmva-sofie failed to open file " + filename + " for tensor weight data");
1831
1833
1834 long curr_pos = f.tellp();
1835 f.close();
1836 return curr_pos;
1837 } else if (fWeightFile == WeightFileType::Text) {
1838 std::ofstream f;
1839 f.open(filename);
1840 if (!f.is_open())
1841 throw
1842 std::runtime_error("tmva-sofie failed to open file " + filename + " for tensor weight data");
1843 for (auto& i: fInitializedTensors) {
1844 // skip Constant tensors and not writable tensors (e.g. shape tensors)
1845 if (!i.second.IsWeightTensor()) {
1846 continue;
1847 }
1848 size_t length = ConvertShapeToLength(i.second.shape());
1849 std::string tensor_name = "tensor_" + i.first;
1850 f << tensor_name << " " << length << "\n";
1851 if (i.second.type() == ETensorType::FLOAT) {
1852 const float * data = i.second.data<float>();
1853 for (size_t idx = 0; idx < length; idx++) {
1854 // round to zero sub-normal values
1855 float value = data[idx];
1856 if (value != 0. && std::abs(value) < std::numeric_limits<float>::min() ) value = 0;
1857 // handle non-finite values explicitly
1858 if (std::isinf(value))
1859 f << (value > 0 ? "inf" : "-inf");
1860 else if (std::isnan(value))
1861 f << "nan";
1862 else
1863 f << std::setprecision(std::numeric_limits<float>::max_digits10) << value;
1864 f << ( (idx < length-1) ? " " : "\n" );
1865 }
1866 }
1867 else {
1868 throw std::runtime_error("tmva-sofie tensor " + tensor_name + " with type " + ConvertTypeToString(i.second.type()) + " cannot be written to a file");
1869 }
1870 if (f.fail())
1871 throw std::runtime_error("tmva-sofie failed to write tensor data to file for " + tensor_name);
1872 }
1873 long curr_pos = f.tellp();
1874 f.close();
1875 return curr_pos;
1876 } else {
1877 return -1;
1878 }
1879}
1880
1882{
1883 // safetensors payloads are little-endian by specification; refuse to
1884 // write silently corrupted output on a big-endian host
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");
1888
1889 // The safetensors layout (https://huggingface.co/docs/safetensors):
1890 // 8 bytes: little-endian unsigned size N of the JSON header
1891 // N bytes: JSON header {name: {"dtype", "shape", "data_offsets"}}
1892 // rest: the raw little-endian tensor payloads, concatenated;
1893 // data_offsets are relative to the start of this region
1894 std::uint64_t offset = 0;
1895 // sort the tensor names for a reproducible output
1896 std::vector<std::string> names;
1897 for (const auto &item : fInitializedTensors) {
1898 // skip Constant tensors and not writable tensors (e.g. shape tensors)
1899 if (item.second.IsWeightTensor())
1900 names.push_back(item.first);
1901 }
1902 std::sort(names.begin(), names.end());
1903 std::string headerStr = "{";
1904 for (size_t idx = 0; idx < names.size(); ++idx) {
1905 const auto &tensor = fInitializedTensors.at(names[idx]);
1906 const std::uint64_t nbytes = ConvertShapeToLength(tensor.shape()) * GetTypeSize(tensor.type());
1907 if (idx > 0)
1908 headerStr += ",";
1909 headerStr += "\"" + JsonEscape("tensor_" + names[idx]) + "\":{\"dtype\":\"" + SafetensorsDType(tensor.type()) +
1910 "\",\"shape\":[";
1911 for (size_t i = 0; i < tensor.shape().size(); ++i) {
1912 if (i > 0)
1913 headerStr += ",";
1914 headerStr += std::to_string(tensor.shape()[i]);
1915 }
1916 headerStr += "],\"data_offsets\":[" + std::to_string(offset) + "," + std::to_string(offset + nbytes) + "]}";
1917 offset += nbytes;
1918 }
1919 headerStr += "}";
1920 // 8-byte little-endian header length
1921 const std::uint64_t headerSize = headerStr.size();
1922 char sizestr[8];
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) {
1928 const auto &tensor = fInitializedTensors.at(name);
1929 const std::uint64_t nbytes = ConvertShapeToLength(tensor.shape()) * GetTypeSize(tensor.type());
1930 f.write(reinterpret_cast<const char *>(tensor.data<void>()), nbytes);
1931 }
1932 if (f.fail())
1933 throw std::runtime_error("tmva-sofie failed to write safetensors payload");
1934}
1935
1937{
1938 std::ostringstream buffer;
1940 return buffer.str();
1941}
1942
1944 std::cout << "Summary of model " << GetName() << std::endl;
1945 for(size_t op_idx = 0; op_idx < fOperators.size(); ++op_idx){
1946 auto& r = *fOperators[op_idx].get();
1947 std::string raw_name = typeid(r).name();
1948 // look for ROperator_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;
1955 }
1956}
1957
1958/// To emit the dimensions of the input tensors as a data member of a session,
1959/// which is helpful when validating the inference inputs.
1961{
1962 fGC += "\n// Input tensor dimensions\n";
1963 // SingleDim / TensorDims / makeDims are emitted as standalone helpers
1964 AddNeededHelperFunction("InputTensorDims");
1965 bool hasDynamicInputTensors = false;
1966
1967 for (std::size_t iInput = 0; iInput < fInputTensorNames.size(); ++iInput) {
1968 auto const &name = fInputTensorNames[iInput];
1969 if (IsDimInputTensor(name)) {
1970 hasDynamicInputTensors = true;
1971 }
1972 std::vector<Dim> shape = GetDimTensorShape(name);
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];
1976 if (dim.isParam) {
1977 fGC += "SingleDim{\"" + dim.GetVal() + "\"}";
1978 } else {
1979 fGC += "SingleDim{" + dim.GetVal() + "}";
1980 }
1981 if (iDim != shape.size() - 1) {
1982 fGC += ", ";
1983 }
1984 }
1985 fGC += "};\n";
1986 }
1987 fGC += "\nconstexpr std::array<TensorDims, " + std::to_string(fInputTensorNames.size()) + "> inputTensorDims{\n";
1988 for (std::size_t iInput = 0; iInput < fInputTensorNames.size(); ++iInput) {
1989 auto const &name = fInputTensorNames[iInput];
1990 fGC += SP + "makeDims(dim_" + name + ")";
1991 if (iInput == fInputTensorNames.size() - 1) {
1992 fGC += "\n";
1993 } else {
1994 fGC += ",\n";
1995 }
1996 }
1997 fGC += "};\n";
1998
1999 fGC +=
2000 "\nconstexpr bool hasDynamicInputTensors{" + std::string{hasDynamicInputTensors ? "true" : "false"} + "};\n\n";
2001
2002 fGC += "\n// Output tensor dimensions\n";
2003 bool hasDynamicOutputTensors = false;
2004 for (std::size_t iOutput = 0; iOutput < fOutputTensorNames.size(); ++iOutput) {
2005 auto const &name = fOutputTensorNames[iOutput];
2006 if (IsDynamicTensor(name)) {
2007 hasDynamicOutputTensors = true;
2008 }
2009 std::vector<Dim> shape = GetDimTensorShape(name);
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];
2013 if (dim.isParam) {
2014 fGC += "SingleDim{\"" + dim.GetVal() + "\"}";
2015 } else {
2016 fGC += "SingleDim{" + dim.GetVal() + "}";
2017 }
2018 if (iDim != shape.size() - 1) {
2019 fGC += ", ";
2020 }
2021 }
2022 fGC += "};\n";
2023 }
2024 fGC += "\nconstexpr std::array<TensorDims, " + std::to_string(fOutputTensorNames.size()) + "> outputTensorDims{\n";
2025 for (std::size_t iOutput = 0; iOutput < fOutputTensorNames.size(); ++iOutput) {
2026 auto const &name = fOutputTensorNames[iOutput];
2027 fGC += SP + "makeDims(dim_" + name + ")";
2028 if (iOutput == fOutputTensorNames.size() - 1) {
2029 fGC += "\n";
2030 } else {
2031 fGC += ",\n";
2032 }
2033 }
2034 fGC += "};\n";
2035 fGC +=
2036 "\nconstexpr bool hasDynamicOutputTensors{" + std::string{hasDynamicOutputTensors ? "true" : "false"} + "};\n\n";
2037}
2038
2040 std::cout << "Model requires following inputs:\n";
2041 for (auto& inputInfo: fInputTensorInfos) {
2042 std::cout << "Parametrised Tensor name: " << inputInfo.first << "\t";
2043 std::cout << "type: " << ConvertTypeToString(inputInfo.second.type) << "\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;
2048 } else {
2049 std::cout << inputInfo.second.shape[i].dim ;
2050 }
2051 if (i < inputInfo.second.shape.size() - 1) std::cout << ",";
2052 }
2053 std::cout << "]" << std::endl;
2054 }
2055
2056 for (auto& inputInfo: fReadyInputTensorInfos) {
2057 std::cout << "Fully Specified Tensor name: " << inputInfo.first << "\t";
2058 std::cout << "type: " << ConvertTypeToString(inputInfo.second.type) << "\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 << ",";
2063 }
2064 std::cout << "]" << std::endl;
2065 }
2066 std::cout << "\n";
2067}
2068
2070 std::cout << "Model initialized the following tensors:\n";
2071 for (auto& it: fInitializedTensors) {
2072 std::cout << "Tensor name: \"" << it.first << "\"\t";
2073 std::cout << "type: " << ConvertTypeToString(it.second.type()) << "\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 << ",";
2078 }
2079 std::cout << "]";
2080 if (it.second.IsConstantTensor()) std::cout << " (Constant)";
2081 if (it.second.IsNotWritable()) std::cout << " (Not Writable)";
2082 std::cout << std::endl;
2083 }
2084 std::cout << "\n";
2085}
2086
2088 std::cout << "Model specify the following intermediate tensors:\n";
2089 for (auto& it: fIntermediateTensorInfos) {
2090 std::cout << "Tensor name: \"" << it.first << "\"\t";
2091 std::cout << "type: " << ConvertTypeToString(it.second.type) << "\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 << ",";
2096 }
2097 std::cout << "]" << std::endl;
2098 }
2099 std::cout << "\n";
2100}
2101
2103 std::cout << "Model specify the following dynamic tensors:\n";
2104 for (auto& it: fDynamicTensorInfos) {
2105 std::cout << "Tensor name: \"" << it.first << "\"\t";
2106 std::cout << "type: " << ConvertTypeToString(it.second.type) << "\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 << ",";
2111 }
2112 std::cout << "]" << std::endl;
2113 }
2114 std::cout << "\n";
2115}
2116
2118 std::cout << "Model specify the following output tensors:\n";
2119 for (auto& it: fOutputTensorNames) {
2120 std::cout << "Tensor name: \"" << it << "\"\t";
2121 try {
2122 auto shape = GetDimTensorShape(it);
2123 std::cout << "with shape: " << ConvertDimShapeToString(shape) << std::endl;
2124 } catch (...) {
2125 std::cout << "with shape not yet defined" << std::endl;
2126 }
2127 }
2128 std::cout << "\n";
2129}
2130
2131void RModel::HeadInitializedTensors(std::string name, int n_print) {
2132 auto it = fInitializedTensors.find(name);
2133 if (it == fInitializedTensors.end()) {
2134 std::cout << "Tensor " << name << " not found in model's initialized tensor list" << std::endl;
2135 return;
2136 }
2137
2138 std::cout << "Tensor name: " << it->first << "\t";
2139 std::cout << "type: " << ConvertTypeToString(it->second.type()) << "\t";
2140 int length =1;
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 << ",";
2146 }
2147 std::cout << "]" << std::endl;
2148 bool ellipsis = true;
2149 if (n_print > length) {
2150 n_print = length;
2151 ellipsis = false;
2152 }
2153
2154 std::cout << "data: [" << std::endl;
2155 if (it->second.type() == ETensorType::FLOAT) {
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 << " ,";
2160 }
2161 }
2162 if (ellipsis) std::cout << ", ...";
2163 std::cout << "]" << std::endl;
2164
2165}
2166
2167void RModel::GenerateHeaderInfo(std::string& hgname) {
2168 fGC += ("//Code generated automatically by TMVA for Inference of Model file [" + fFileName + "] at [" + fParseTime.substr(0, fParseTime.length()-1) +"] \n");
2169 // add header guards
2170 hgname = fName;
2171 std::transform(hgname.begin(), hgname.end(), hgname.begin(), [](unsigned char c) {
2172 return std::toupper(c);
2173 } );
2174 hgname = "ROOT_TMVA_SOFIE_" + hgname;
2175 fGC += "\n#ifndef " + hgname + "\n";
2176 fGC += "#define " + hgname + "\n\n";
2177 // Standard library headers the generated code relies on. Listed explicitly
2178 // now that they are no longer pulled in transitively via SOFIE_common.hxx.
2179 for (const char *h : {"cstdint", "cstring", "string", "vector", "map", "memory", "sstream", "iostream", "iomanip",
2180 "limits", "stdexcept", "algorithm", "cmath", "cassert"}) {
2181 fNeededStdLib.insert(h);
2182 }
2183 for (auto& i: fNeededStdLib) {
2184 fGC += "#include <" + i + ">\n";
2185 }
2186 for (auto& i: fCustomOpHeaders) {
2187 fGC += "#include \"" + i + "\"\n";
2188 }
2189 // Placeholder for the #include directives needed by the embedded helper
2190 // functions (filled in by EmitHelperFunctionsCode).
2192 if (fUseWeightFile)
2193 fGC += "#include <fstream>\n";
2194 // the safetensors file constructor buffers the payload with
2195 // std::istreambuf_iterator
2197 fGC += "#include <iterator>\n";
2198
2199 fGC += "\nnamespace TMVA_SOFIE_" + fName + "{\n";
2200 if (!fNeededBlasRoutines.empty()) {
2201 fGC += ("namespace BLAS{\n");
2202 for (auto &routine : fNeededBlasRoutines) {
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");
2207 // sgemm_ now declared; the standalone Gemm_Call helper will skip its copy.
2208 fBlasSgemmDeclared = true;
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");
2217 }
2218 }
2219 fGC += ("}//BLAS\n");
2220 }
2221 // Placeholder for the standalone definitions of the inference helper
2222 // functions used by this model (filled in by EmitHelperFunctionsCode). It
2223 // sits inside the generated model namespace, right before the session code.
2225}
2226
2228{
2229 HelperFunctionsCode code =
2231
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);
2236 }
2237 };
2238
2239 replaceMarker(kHelperIncludesMarker, code.includes);
2240 replaceMarker(kHelperFunctionsMarker, code.definitions);
2241
2242 // Clad derivatives live at file scope and reference the model's helpers, so
2243 // insert them after the whole model namespace, just before the include guard.
2244 if (!code.cladDefinitions.empty()) {
2245 auto pos = fGC.rfind("#endif");
2246 if (pos != std::string::npos) {
2247 fGC.insert(pos, code.cladDefinitions + "\n");
2248 } else {
2249 fGC += code.cladDefinitions;
2250 }
2251 }
2252}
2253
2254void RModel::OutputGenerated(std::string filename, bool append) {
2255
2256 // the model can be appended only if a file name is provided
2257 if (filename.empty()) {
2258 // if a file is pr
2259 filename = fName + ".hxx";
2260 append = false;
2261 }
2262 std::ofstream f;
2263 if (append)
2264 f.open(filename, std::ios_base::app);
2265 else
2266 f.open(filename);
2267 if (!f.is_open()) {
2268 throw std::runtime_error("tmva-sofie failed to open file for output generated inference code");
2269 }
2270 f << fGC;
2271 f.close();
2272
2273 // write weights in a separate weight file
2274 if (fUseWeightFile) {
2275 const std::string extension = fWeightFile == WeightFileType::Safetensors ? ".safetensors" : ".dat";
2276 if (!filename.empty()) {
2277 size_t pos = filename.find(".hxx");
2278 if (pos != std::string::npos)
2279 filename.replace(pos, 4, extension);
2280 else
2281 filename += extension;
2282 } else {
2283 filename = fName + extension;
2284 }
2286 }
2287}
2288
2289} // namespace SOFIE::Experimental::TMVA
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
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
char name[80]
Definition TGX11.cxx:142
std::string WriteInitializedTensorsToBuffer()
Definition RModel.cxx:1936
void AddShapeParam(const std::string &name, size_t def_value=0)
Definition RModel.cxx:417
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...
Definition RModel.cxx:1120
void AddNeededHelperFunction(std::string name)
Definition RModel.hxx:333
std::vector< size_t > GetTensorShape(const std::string &name) const
Definition RModel.cxx:109
std::set< std::string > fNeededHelperFunctions
Definition RModel.hxx:70
std::unordered_set< std::string > fComputedShapeParams
! shape parameters computed at run time by an operator
Definition RModel.hxx:101
std::vector< Dim > GetDimTensorShape(const std::string &name) const
Definition RModel.cxx:145
std::unordered_map< std::string, DynamicTensorInfo > fDynamicTensorInfos
Definition RModel.hxx:98
bool IsDynamicTensor(const std::string &name) const
Definition RModel.cxx:368
void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector< Dim > dim_shape)
Definition RModel.cxx:383
bool AddAliasTensor(const std::string &tensor_name, const std::string &orig_tensor_name)
Definition RModel.cxx:307
std::string GenerateInferSignature(bool isdecl=true)
Definition RModel.cxx:1217
std::unordered_set< std::string > fNeededBlasRoutines
Definition RModel.hxx:58
bool CheckIfTensorAlreadyExist(std::string tensor_name)
Definition RModel.cxx:202
void GenerateHeaderInfo(std::string &hgname)
Definition RModel.cxx:2167
void GenerateRequiredInputTensorInfo()
To emit the dimensions of the input tensors as a data member of a session, which is helpful when vali...
Definition RModel.cxx:1960
void OutputGenerated(std::string filename="", bool append=false)
Definition RModel.cxx:2254
std::unordered_map< std::string, std::string > fAliasTensors
Definition RModel.hxx:102
void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector< Dim > shape)
Definition RModel.cxx:213
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...
Definition RModel.cxx:1135
std::unordered_map< std::string, TensorInfo > fIntermediateTensorInfos
Definition RModel.hxx:97
void AddOutputTensorNameList(std::vector< std::string > output_tensor_names)
Definition RModel.cxx:437
std::unordered_map< std::string, TensorInfo > fReadyInputTensorInfos
Definition RModel.hxx:95
void AddConstantTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:289
void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector< Dim > shape)
Definition RModel.cxx:400
std::vector< std::string > fDimShapeNames
Definition RModel.hxx:103
void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:269
std::unordered_map< std::string_view, size_t > fIntermediateTensorFrequencyLookup
! lookup table for intermediate tensor frequency (transient)
Definition RModel.hxx:122
void AddBlasRoutines(std::vector< std::string > routines)
Definition RModel.hxx:316
void AddInputTensorName(std::string name)
Definition RModel.cxx:232
std::vector< std::string > fOutputTensorNames
Definition RModel.hxx:104
void AddNeededStdLib(std::string libname)
Definition RModel.hxx:322
bool IsDimInputTensor(const std::string &name) const
Definition RModel.cxx:373
bool IsShapeTensor(const std::string &name) const
check if a tensor is a shape tensor
Definition RModel.cxx:342
static constexpr const char * kHelperIncludesMarker
Definition RModel.hxx:80
bool IsInitializedTensor(const std::string &name) const
Definition RModel.cxx:355
std::unordered_set< std::string > fNeededStdLib
Definition RModel.hxx:64
bool IsAliasTensor(const std::string &name) const
check if a tensor is a alias tensor
Definition RModel.cxx:346
static constexpr const char * kHelperFunctionsMarker
Definition RModel.hxx:81
void CheckAndFlushIntermediateMemory(std::span< const std::string_view > op_output_tensors, const size_t &op_idx)
Definition RModel.cxx:582
void AddOperator(std::unique_ptr< ROperator > op, int order_execution=-1)
Definition RModel.cxx:236
RModel()=default
Default constructor.
void HeadInitializedTensors(std::string name, int n_print=50)
Definition RModel.cxx:2131
bool IsConstantTensor(const std::string &name) const
Definition RModel.cxx:359
void WriteInitializedTensorsToStream(std::ostream &os)
Definition RModel.cxx:1881
void Initialize(int batchSize=-1, bool verbose=false)
Definition RModel.cxx:663
long WriteInitializedTensorsToFile(std::string filename="")
Definition RModel.cxx:1806
OptimizationLevel fOptimizationLevel
Definition RModel.hxx:92
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...
Definition RModel.cxx:1159
std::vector< Dim > GetDynamicTensorShape(const std::string &name) const
Definition RModel.cxx:156
std::unordered_map< std::string, InputTensorInfo > fInputTensorInfos
Definition RModel.hxx:94
std::shared_ptr< void > GetInitializedTensorData(std::string tensor_name)
Definition RModel.cxx:460
void AddComputedShapeParam(const std::string &name)
Declare a shape parameter as computed at run time by an operator.
Definition RModel.cxx:428
MemoryPoolInfo fIntermediateMemoryInfo
! intermediate memory info (transient)
Definition RModel.hxx:121
std::string AllocateIntermediateMemory(std::span< const std::string_view > op_output_tensors)
Definition RModel.cxx:477
std::unordered_map< std::string, std::pair< std::vector< Dim >, bool > > fShapeTensors
Definition RModel.hxx:99
std::vector< std::unique_ptr< ROperator, ROperatorDeleter > > fOperators
Definition RModel.hxx:115
void InitializeSubGraph(std::shared_ptr< RModel > graph)
Definition RModel.cxx:826
std::unordered_map< std::string, std::string > fShapeParams
Definition RModel.hxx:100
void SetNotWritableInitializedTensor(const std::string &tensor_name)
Definition RModel.cxx:469
const std::string & GetName() const
Definition RModel.hxx:314
ETensorType GetTensorType(std::string name) const
Definition RModel.cxx:170
std::vector< std::string > fInputTensorNames
Definition RModel.hxx:105
std::unordered_map< std::string, InitializedTensor > fInitializedTensors
Definition RModel.hxx:96
void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:451
void Generate(std::underlying_type_t< Options > options, int batchSize=-1, bool verbose=false)
Definition RModel.cxx:1699
const std::vector< Dim > & GetShapeTensorValues(const std::string &tensor_name) const
Definition RModel.cxx:350
std::vector< std::shared_ptr< RModel > > fSubGraphs
! sub-graph models (transient)
Definition RModel.hxx:117
bool IsReadyInputTensor(const std::string &name) const
Definition RModel.cxx:377
void UpdateOutputTensorList(std::vector< std::string > curr_output_tensor, std::vector< std::string > modify_output_tensor)
Definition RModel.cxx:444
void AddShapeTensor(const std::string &name, const std::vector< Dim > &shapeValues, bool scalar=false)
Definition RModel.cxx:299
std::unordered_set< std::string > fCustomOpHeaders
Definition RModel.hxx:65
bool IsInputTensorShapeParam(std::string const &name) const
Check if a given parameter is used for the shape of an input tensor.
Definition RModel.cxx:1141
TLine * line
const Int_t n
Definition legend1.C:16
std::string Clean_name(std::string input_tensor_name)
const std::string kCheckMarker
Definition RModel.cxx:1134
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)
Definition RModel.cxx:869
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)
Definition RModel.cxx:102
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