Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RModel.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_RMODEL
2#define TMVA_SOFIE_RMODEL
3
6#include "TMVA/ROperator.hxx"
7
8namespace TMVA {
9namespace Experimental {
10namespace SOFIE {
11
12class RModel final : public RModel_Base {
13
14private:
15 bool fIsInitialized = false;
16 bool fIsSubGraph = false;
17 int fVerbose = 0;
18 int fBatchSize = -1;
19 long fReadPos = 0; // reading file position
20 size_t fConstantTensorSize = 0; // size (in Bytes) of the allocated constant tensors
21 size_t fWeightsTensorSize = 0; // size (in Bytes) of the allocated weight tensors
22 size_t fOtherTensorSize = 0; // size (in Bytes) of intermediate tensors which are not managed by the memory pool
23
25
26 std::unordered_map<std::string, InputTensorInfo> fInputTensorInfos; // input tensors where shape may not fully defined or other graph inputs?
27 std::unordered_map<std::string, TensorInfo> fReadyInputTensorInfos; // input tensors where shape is full defined
28 std::unordered_map<std::string, InitializedTensor> fInitializedTensors;
29 std::unordered_map<std::string, TensorInfo> fIntermediateTensorInfos;
30 std::unordered_map<std::string, DynamicTensorInfo> fDynamicTensorInfos;
31 std::unordered_map<std::string, std::pair<std::vector<Dim>, bool>> fShapeTensors; // constant tensors describing a shape
32 std::unordered_map<std::string, std::string> fShapeParams; // parameters defining the dynamic shape (e.g. batch size), store also its default value
33 std::unordered_map<std::string, std::string> fAliasTensors; // list of alias tensors
34 std::vector<std::string> fDimShapeNames; // parameter names used to define the shapes
35 std::vector<std::string> fOutputTensorNames;
36 std::vector<std::string> fInputTensorNames; // input tensor names using ONNX order
37
38
39
40 std::vector<std::unique_ptr<ROperator>> fOperators;
41
42 std::vector<std::shared_ptr<RModel>> fSubGraphs; ///<! sub-graph models (transient)
43 RModel * fParentGraph = nullptr;
44
45 // memory pool information for intermediate tensors
46 MemoryPoolInfo fIntermediateMemoryInfo; ///<! intermediate memory info (transient)
47 std::unordered_map<std::string_view, size_t> fIntermediateTensorFrequencyLookup; ///<! lookup table for intermediate tensor frequency (transient)
48
49public:
50 /**
51 Default constructor. Needed to allow serialization of ROOT objects. See
52 https://root.cern/manual/io_custom_classes/#restrictions-on-types-root-io-can-handle
53 */
54 RModel() = default;
55 RModel(std::string name, std::string parsedtime) : RModel_Base(name, parsedtime) {}
56
57 // For GNN Functions usage
59
60 int Verbose() const { return fVerbose;}
61
62 std::vector<size_t> GetTensorShape(const std::string & name) const;
63 std::vector<Dim> GetDimTensorShape(const std::string & name) const;
64 std::vector<Dim> GetDynamicTensorShape(const std::string & name) const ;
65
66 // get the values for the tensor representing a shape
67 const std::vector<Dim> & GetShapeTensorValues(const std::string & tensor_name) const;
68
69 ETensorType GetTensorType(std::string name) const;
70
71
72 bool CheckIfTensorAlreadyExist(std::string tensor_name);
73 void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<Dim> shape);
74 void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<size_t> shape);
75 void AddOperator(std::unique_ptr<ROperator> op, int order_execution = -1);
77 {
78 std::unique_ptr<ROperator> tmp(op);
79 AddOperator(std::move(tmp), order_execution);
80 }
81 void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
82 std::shared_ptr<void> data);
83 void AddConstantTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
84 std::shared_ptr<void> data);
85
86 void AddAliasTensor(const std::string & tensor_name, const std::string & orig_tensor_name);
87
88
89 template<class T>
90 void AddConstantTensor(const std::string & name, const std::vector<size_t> & shape, const T * data) {
91 size_t length = ConvertShapeToLength(shape);
92 std::shared_ptr<void> data_ptr(malloc(length * sizeof(T)), free);
93 std::memcpy(data_ptr.get(), (void*) data, length * sizeof(T));
95 }
96 // for boolean can be more convenient passing an std::vector
97 template<class T>
98 void AddConstantTensor(const std::string & name, const std::vector<size_t> & shape, const std::vector<T> & data) {
99 size_t length = data.size();
100 std::shared_ptr<void> data_ptr(malloc(length * sizeof(T)), free);
101 std::copy(data.begin(), data.end(), (T*) data_ptr.get());
102 //std::memcpy(data_ptr.get(), (void*) data, length * sizeof(T));
104 }
105
106 template <typename T>
107 void AddInitializedTensor(const std::string & tensor_name, const std::vector<std::size_t> & shape, T *raw_data)
108 {
109 size_t size = ConvertShapeToLength(shape);
110 std::shared_ptr<void> data(malloc(size * sizeof(T)), free);
111 std::memcpy(data.get(), raw_data, size * sizeof(T));
112 AddInitializedTensor(tensor_name, GetTemplatedType(T()), shape, data);
113 }
114
115 void AddShapeTensor(const std::string & name, const std::vector<Dim> & shapeValues, bool scalar = false);
116
117
118 // add and initialize subgraph to the model
119 void InitializeSubGraph(std::shared_ptr<RModel> graph);
120
121 // set a flag to indicate tensor does not need to be written in a weight file
122 // (e.g. shape tensors used as input to define a shape (in Reshape))
123 void SetNotWritableInitializedTensor(const std::string & tensor_name);
124
125 // Check if a tensor is initialized
126 bool IsInitializedTensor(const std::string &name) const;
127 // Check if a tensor is Constant (note a Constant tensor is also initialized)
128 bool IsConstantTensor(const std::string &name) const;
129 bool IsDynamicTensor(const std::string &name) const;
130 // Check if tensor is a input dynamic tensor (without a specified shape, based on Sim structure
131 bool IsDimInputTensor(const std::string &name) const;
132 // check if tensor is a fully specified input tensor
133 bool IsReadyInputTensor(const std::string &name) const;
134 /// check if a tensor is a shape tensor
135 bool IsShapeTensor(const std::string & name) const;
136 /// check if a tensor is a alias tensor
137 bool IsAliasTensor(const std::string & name) const;
138
139 // Add intermediate tensor
140 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<Dim> dim_shape);
141 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape);
142 // Add an intermediate dynamic tensor
143 void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector<Dim> shape);
144 // void Add a shape parameter
145 void AddShapeParam(const std::string & name, size_t def_value = 0);
146 void AddInputTensorName(std::string name);
147 void AddOutputTensorNameList(std::vector<std::string> output_tensor_names);
148 void
149 UpdateOutputTensorList(std::vector<std::string> curr_output_tensor, std::vector<std::string> modify_output_tensor);
150 void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
151 std::shared_ptr<void> data);
152 std::shared_ptr<void> GetInitializedTensorData(std::string tensor_name);
153
154 template<class T>
155 std::vector<T> GetTensorData(const std::string & name);
156
157 void Initialize(int batchSize = -1, bool verbose = false);
158 void Initialize(const std::map<std::string,size_t> & inputParams, bool verbose = false);
159
160 void Generate(std::underlying_type_t<Options> options, int batchSize = -1, long pos = 0, bool verbose = false);
161 void Generate(Options options = Options::kDefault, int batchSize = -1, int pos = 0, bool verbose = false)
162 {
163 Generate(static_cast<std::underlying_type_t<Options>>(options), batchSize, pos, verbose);
164 }
165 // generate the infer function signature. If isdecl= false generate the calling infer function
166 // used to infer the sub-graphs
167 std::string GenerateInferSignature(bool isdecl = true);
168
169 // calculate total intermediate memory and position intermediate tensor addresses
170 std::string AllocateIntermediateMemory(std::span<const std::string_view> op_output_tensors);
171 void CheckAndFlushIntermediateMemory(std::span<const std::string_view> op_output_tensors, const size_t& op_idx);
172
174
175 // get the size in bytes of the constant tensors
177 // get the size in bytes of the weight tensors
178 size_t GetWeightsTensorSize() const { return fWeightsTensorSize; }
179 // get the size in bytes of the intermediate tensors which are not part of the memory pool
180 size_t GetOtherTensorSize() const { return fOtherTensorSize; }
181 // get the size in bytes of the intermediate tensors managed by the memory pool
183 return (!fIntermediateMemoryInfo.total_stack.empty())
184 ? fIntermediateMemoryInfo.total_stack.rbegin()->first + fIntermediateMemoryInfo.total_stack.rbegin()->second.tensor_size
185 : 0;
186 }
187
188protected:
189 // internal functions
190 // generate code for the initialized tensors
192 // generate code for the intermediate tensors
194 // generate code for the dynamic tensors
196 // generate code for declarations needed by operators
198 // generate code for inference
199 void GenerateOutput();
200 // generate code for initializing memory pool for intermediate tensors
202 // Generate all session code
203 void GenerateSessionCode();
204
205public:
206 const std::vector<std::string> & GetInputTensorNames() const { return fInputTensorNames; }
207 const std::vector<std::string> & GetOutputTensorNames() const { return fOutputTensorNames; }
208 const std::vector<std::string> & GetDimShapeNames() const { return fDimShapeNames; }
209
211 long WriteInitializedTensorsToFile(std::string filename = "");
212
213 void PrintIntermediateTensors() const;
214 void PrintOutputTensors() const;
215 void OutputGenerated(std::string filename = "", bool append = false);
216 std::vector<std::string> GetOutputTensorNames() { return fOutputTensorNames; }
217 void SetFilename(std::string filename) { fName = filename; }
218
219 /*
220 template <typename T>
221 void AddInitializedTensor(std::string tensor_name, RTensor<T> new_tensor){
222 //a view only
223 T obj;
224 if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()){
225 throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n");
226 }
227 InitializedTensor new_tensor_ {GetTemplatedType(obj), new_tensor.GetShape() ,
228 static_cast<void>(new_tensor.GetData())}; fInitializedTensors[tensor_name] = new_tensor_;
229 }
230 */
231
232 void PrintRequiredInputTensors() const;
233 void PrintInitializedTensors() const;
234 void PrintDynamicTensors() const;
235 void HeadInitializedTensors(std::string name, int n_print = 50);
236
237 bool UseSession() const { return fUseSession; }
238
239 // Use the ClassDef macro to allow definition of custom streaming
241};
242
243// need to implement here templated member functions and its specialization
244
245
246template<class T>
247inline std::vector<T> RModel::GetTensorData(const std::string & name) {
248 if (!IsInitializedTensor(name)) return std::vector<T>{};
249 T * data = static_cast<T*>(GetInitializedTensorData(name).get());
251 return std::vector<T>(data, data+size);
252}
253
254template<>
255inline std::vector<Dim> RModel::GetTensorData<Dim>(const std::string & name) {
256 if (!IsShapeTensor(name)) return std::vector<Dim>{};
258}
259
260} // namespace SOFIE
261} // namespace Experimental
262} // namespace TMVA
263
264#endif // TMVA_SOFIE_RMODEL
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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 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 length
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:110
#define malloc
Definition civetweb.c:1575
void AddShapeParam(const std::string &name, size_t def_value=0)
Definition RModel.cxx:296
std::vector< size_t > GetTensorShape(const std::string &name) const
Definition RModel.cxx:29
std::vector< Dim > GetDimTensorShape(const std::string &name) const
Definition RModel.cxx:65
std::unordered_map< std::string, DynamicTensorInfo > fDynamicTensorInfos
Definition RModel.hxx:30
bool IsDynamicTensor(const std::string &name) const
Definition RModel.cxx:247
const std::vector< std::string > & GetOutputTensorNames() const
Definition RModel.hxx:207
void AddAliasTensor(const std::string &tensor_name, const std::string &orig_tensor_name)
Definition RModel.cxx:211
void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector< Dim > dim_shape)
Definition RModel.cxx:262
size_t GetIntermediateTensorSize() const
Definition RModel.hxx:182
void AddOperatorReference(ROperator *op, int order_execution=-1)
Definition RModel.hxx:76
std::string GenerateInferSignature(bool isdecl=true)
Definition RModel.cxx:915
RModel(std::string function_name)
Definition RModel.hxx:58
bool CheckIfTensorAlreadyExist(std::string tensor_name)
Definition RModel.cxx:122
std::vector< std::unique_ptr< ROperator > > fOperators
Definition RModel.hxx:40
void OutputGenerated(std::string filename="", bool append=false)
Definition RModel.cxx:1553
std::unordered_map< std::string, std::string > fAliasTensors
Definition RModel.hxx:33
void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector< Dim > shape)
Definition RModel.cxx:133
std::unordered_map< std::string, TensorInfo > fIntermediateTensorInfos
Definition RModel.hxx:29
void AddOutputTensorNameList(std::vector< std::string > output_tensor_names)
Definition RModel.cxx:304
std::unordered_map< std::string, TensorInfo > fReadyInputTensorInfos
Definition RModel.hxx:27
void AddConstantTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:193
void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector< Dim > shape)
Definition RModel.cxx:279
std::vector< std::string > fDimShapeNames
Definition RModel.hxx:34
void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:183
std::unordered_map< std::string_view, size_t > fIntermediateTensorFrequencyLookup
! lookup table for intermediate tensor frequency (transient)
Definition RModel.hxx:47
void AddInputTensorName(std::string name)
Definition RModel.cxx:152
std::vector< std::string > fOutputTensorNames
Definition RModel.hxx:35
bool IsDimInputTensor(const std::string &name) const
Definition RModel.cxx:252
bool IsShapeTensor(const std::string &name) const
check if a tensor is a shape tensor
Definition RModel.cxx:221
size_t GetConstantTensorSize() const
Definition RModel.hxx:176
bool IsInitializedTensor(const std::string &name) const
Definition RModel.cxx:234
bool IsAliasTensor(const std::string &name) const
check if a tensor is a alias tensor
Definition RModel.cxx:225
void AddInitializedTensor(const std::string &tensor_name, const std::vector< std::size_t > &shape, T *raw_data)
Definition RModel.hxx:107
void CheckAndFlushIntermediateMemory(std::span< const std::string_view > op_output_tensors, const size_t &op_idx)
Definition RModel.cxx:449
void AddOperator(std::unique_ptr< ROperator > op, int order_execution=-1)
Definition RModel.cxx:156
RModel()=default
Default constructor.
void HeadInitializedTensors(std::string name, int n_print=50)
Definition RModel.cxx:1517
bool IsConstantTensor(const std::string &name) const
Definition RModel.cxx:238
void Initialize(int batchSize=-1, bool verbose=false)
Definition RModel.cxx:528
size_t GetWeightsTensorSize() const
Definition RModel.hxx:178
long WriteInitializedTensorsToFile(std::string filename="")
Definition RModel.cxx:1313
OptimizationLevel fOptimizationLevel
Definition RModel.hxx:24
void Generate(std::underlying_type_t< Options > options, int batchSize=-1, long pos=0, bool verbose=false)
Definition RModel.cxx:1174
std::vector< Dim > GetDynamicTensorShape(const std::string &name) const
Definition RModel.cxx:76
void AddConstantTensor(const std::string &name, const std::vector< size_t > &shape, const std::vector< T > &data)
Definition RModel.hxx:98
std::unordered_map< std::string, InputTensorInfo > fInputTensorInfos
Definition RModel.hxx:26
std::shared_ptr< void > GetInitializedTensorData(std::string tensor_name)
Definition RModel.cxx:327
MemoryPoolInfo fIntermediateMemoryInfo
! intermediate memory info (transient)
Definition RModel.hxx:46
std::string AllocateIntermediateMemory(std::span< const std::string_view > op_output_tensors)
Definition RModel.cxx:344
std::unordered_map< std::string, std::pair< std::vector< Dim >, bool > > fShapeTensors
Definition RModel.hxx:31
std::vector< T > GetTensorData(const std::string &name)
Definition RModel.hxx:247
void SetFilename(std::string filename)
Definition RModel.hxx:217
void InitializeSubGraph(std::shared_ptr< RModel > graph)
Definition RModel.cxx:663
std::unordered_map< std::string, std::string > fShapeParams
Definition RModel.hxx:32
void SetNotWritableInitializedTensor(const std::string &tensor_name)
Definition RModel.cxx:336
ETensorType GetTensorType(std::string name) const
Definition RModel.cxx:90
std::vector< std::string > fInputTensorNames
Definition RModel.hxx:36
const std::vector< std::string > & GetInputTensorNames() const
Definition RModel.hxx:206
std::unordered_map< std::string, InitializedTensor > fInitializedTensors
Definition RModel.hxx:28
void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:318
std::vector< std::string > GetOutputTensorNames()
Definition RModel.hxx:216
const std::vector< Dim > & GetShapeTensorValues(const std::string &tensor_name) const
Definition RModel.cxx:229
std::vector< std::shared_ptr< RModel > > fSubGraphs
! sub-graph models (transient)
Definition RModel.hxx:42
bool IsReadyInputTensor(const std::string &name) const
Definition RModel.cxx:256
void UpdateOutputTensorList(std::vector< std::string > curr_output_tensor, std::vector< std::string > modify_output_tensor)
Definition RModel.cxx:311
const std::vector< std::string > & GetDimShapeNames() const
Definition RModel.hxx:208
RModel(std::string name, std::string parsedtime)
Definition RModel.hxx:55
void AddShapeTensor(const std::string &name, const std::vector< Dim > &shapeValues, bool scalar=false)
Definition RModel.cxx:203
void AddConstantTensor(const std::string &name, const std::vector< size_t > &shape, const T *data)
Definition RModel.hxx:90
void SetOptimizationLevel(const OptimizationLevel &optim_level)
Definition RModel.hxx:173
void Generate(Options options=Options::kDefault, int batchSize=-1, int pos=0, bool verbose=false)
Definition RModel.hxx:161
std::size_t ConvertShapeToLength(const std::vector< size_t > &shape)
ETensorType GetTemplatedType(T)
create variable transformations
std::map< size_t, TensorMemoryInfo > total_stack