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);
76 void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
77 std::shared_ptr<void> data);
78 void AddConstantTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
79 std::shared_ptr<void> data);
80
81 void AddAliasTensor(const std::string & tensor_name, const std::string & orig_tensor_name);
82
83
84 template<class T>
85 void AddConstantTensor(const std::string & name, const std::vector<size_t> & shape, const T * data) {
86 size_t length = ConvertShapeToLength(shape);
87 std::shared_ptr<void> data_ptr(malloc(length * sizeof(T)), free);
88 std::memcpy(data_ptr.get(), (void*) data, length * sizeof(T));
90 }
91 // for boolean can be more convenient passing an std::vector
92 template<class T>
93 void AddConstantTensor(const std::string & name, const std::vector<size_t> & shape, const std::vector<T> & data) {
94 size_t length = data.size();
95 std::shared_ptr<void> data_ptr(malloc(length * sizeof(T)), free);
96 std::copy(data.begin(), data.end(), (T*) data_ptr.get());
97 //std::memcpy(data_ptr.get(), (void*) data, length * sizeof(T));
99 }
100
101 template <typename T>
102 void AddInitializedTensor(const std::string & tensor_name, const std::vector<std::size_t> & shape, T *raw_data)
103 {
104 size_t size = ConvertShapeToLength(shape);
105 std::shared_ptr<void> data(malloc(size * sizeof(T)), free);
106 std::memcpy(data.get(), raw_data, size * sizeof(T));
107 AddInitializedTensor(tensor_name, GetTemplatedType(T()), shape, data);
108 }
109
110 void AddShapeTensor(const std::string & name, const std::vector<Dim> & shapeValues, bool scalar = false);
111
112
113 // add and initialize subgraph to the model
114 void InitializeSubGraph(std::shared_ptr<RModel> graph);
115
116 // set a flag to indicate tensor does not need to be written in a weight file
117 // (e.g. shape tensors used as input to define a shape (in Reshape))
118 void SetNotWritableInitializedTensor(const std::string & tensor_name);
119
120 // Check if a tensor is initialized
121 bool IsInitializedTensor(const std::string &name) const;
122 // Check if a tensor is Constant (note a Constant tensor is also initialized)
123 bool IsConstantTensor(const std::string &name) const;
124 bool IsDynamicTensor(const std::string &name) const;
125 // Check if tensor is a input dynamic tensor (without a specified shape, based on Sim structure
126 bool IsDimInputTensor(const std::string &name) const;
127 // check if tensor is a fully specified input tensor
128 bool IsReadyInputTensor(const std::string &name) const;
129 /// check if a tensor is a shape tensor
130 bool IsShapeTensor(const std::string & name) const;
131 /// check if a tensor is a alias tensor
132 bool IsAliasTensor(const std::string & name) const;
133
134 // Add intermediate tensor
135 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<Dim> dim_shape);
136 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape);
137 // Add an intermediate dynamic tensor
138 void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector<Dim> shape);
139 // void Add a shape parameter
140 void AddShapeParam(const std::string & name, size_t def_value = 0);
141 void AddInputTensorName(std::string name);
142 void AddOutputTensorNameList(std::vector<std::string> output_tensor_names);
143 void
144 UpdateOutputTensorList(std::vector<std::string> curr_output_tensor, std::vector<std::string> modify_output_tensor);
145 void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
146 std::shared_ptr<void> data);
147 std::shared_ptr<void> GetInitializedTensorData(std::string tensor_name);
148
149 template<class T>
150 std::vector<T> GetTensorData(const std::string & name);
151
152 void Initialize(int batchSize = -1, bool verbose = false);
153 void Initialize(const std::map<std::string,size_t> & inputParams, bool verbose = false);
154
155 void Generate(std::underlying_type_t<Options> options, int batchSize = -1, long pos = 0, bool verbose = false);
156 void Generate(Options options = Options::kDefault, int batchSize = -1, int pos = 0, bool verbose = false)
157 {
158 Generate(static_cast<std::underlying_type_t<Options>>(options), batchSize, pos, verbose);
159 }
160 // generate the infer function signature. If isdecl= false generate the calling infer function
161 // used to infer the sub-graphs
162 std::string GenerateInferSignature(bool isdecl = true);
163
164 // calculate total intermediate memory and position intermediate tensor addresses
165 std::string AllocateIntermediateMemory(std::span<const std::string_view> op_output_tensors);
166 void CheckAndFlushIntermediateMemory(std::span<const std::string_view> op_output_tensors, const size_t& op_idx);
167
169
170 // get the size in bytes of the constant tensors
172 // get the size in bytes of the weight tensors
173 size_t GetWeightsTensorSize() const { return fWeightsTensorSize; }
174 // get the size in bytes of the intermediate tensors which are not part of the memory pool
175 size_t GetOtherTensorSize() const { return fOtherTensorSize; }
176 // get the size in bytes of the intermediate tensors managed by the memory pool
178 return (!fIntermediateMemoryInfo.total_stack.empty())
179 ? fIntermediateMemoryInfo.total_stack.rbegin()->first + fIntermediateMemoryInfo.total_stack.rbegin()->second.tensor_size
180 : 0;
181 }
182
183protected:
184 // internal functions
185 // generate code for the initialized tensors
187 // generate code for the intermediate tensors
189 // generate code for the dynamic tensors
191 // generate code for declarations needed by operators
193 // generate code for inference
194 void GenerateOutput();
195 // generate code for initializing memory pool for intermediate tensors
197 // Generate all session code
198 void GenerateSessionCode();
199
200public:
201 const std::vector<std::string> & GetInputTensorNames() const { return fInputTensorNames; }
202 const std::vector<std::string> & GetOutputTensorNames() const { return fOutputTensorNames; }
203 const std::vector<std::string> & GetDimShapeNames() const { return fDimShapeNames; }
204
206 long WriteInitializedTensorsToFile(std::string filename = "");
207
208 void PrintSummary() const;
209 void PrintIntermediateTensors() const;
210 void PrintOutputTensors() const;
211 void OutputGenerated(std::string filename = "", bool append = false);
212 void SetFilename(std::string filename) { fName = filename; }
213
214 /*
215 template <typename T>
216 void AddInitializedTensor(std::string tensor_name, RTensor<T> new_tensor){
217 //a view only
218 T obj;
219 if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()){
220 throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n");
221 }
222 InitializedTensor new_tensor_ {GetTemplatedType(obj), new_tensor.GetShape() ,
223 static_cast<void>(new_tensor.GetData())}; fInitializedTensors[tensor_name] = new_tensor_;
224 }
225 */
226
227 void PrintRequiredInputTensors() const;
228 void PrintInitializedTensors() const;
229 void PrintDynamicTensors() const;
230 void HeadInitializedTensors(std::string name, int n_print = 50);
231
232 bool UseSession() const { return fUseSession; }
233
234 // Use the ClassDef macro to allow definition of custom streaming
236};
237
238// need to implement here templated member functions and its specialization
239
240
241template<class T>
242inline std::vector<T> RModel::GetTensorData(const std::string & name) {
243 if (!IsInitializedTensor(name)) return std::vector<T>{};
244 T * data = static_cast<T*>(GetInitializedTensorData(name).get());
246 return std::vector<T>(data, data+size);
247}
248
249template<>
250inline std::vector<Dim> RModel::GetTensorData<Dim>(const std::string & name) {
251 if (!IsShapeTensor(name)) return std::vector<Dim>{};
253}
254
255} // namespace SOFIE
256} // namespace Experimental
257} // namespace TMVA
258
259#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:202
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:177
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:1619
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 SetOptimizationLevel(OptimizationLevel optim_level)
Definition RModel.hxx:168
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:171
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:102
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:1583
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:173
long WriteInitializedTensorsToFile(std::string filename="")
Definition RModel.cxx:1364
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:1225
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:93
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:242
void SetFilename(std::string filename)
Definition RModel.hxx:212
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:201
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
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:203
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:85
void Generate(Options options=Options::kDefault, int batchSize=-1, int pos=0, bool verbose=false)
Definition RModel.hxx:156
std::size_t ConvertShapeToLength(const std::vector< size_t > &shape)
ETensorType GetTemplatedType(T)
create variable transformations
std::map< size_t, TensorMemoryInfo > total_stack