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