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
48 std::string fExtraCodeForDimShapes; // extra code needed for initialization of dynamic parameters (e.g. number of non zero elements in NonZero operator)
49
50public:
51 /**
52 Default constructor. Needed to allow serialization of ROOT objects. See
53 https://root.cern/manual/io_custom_classes/#restrictions-on-types-root-io-can-handle
54 */
55 RModel() = default;
56 RModel(std::string name, std::string parsedtime) : RModel_Base(name, parsedtime) {}
57
58 // For GNN Functions usage
60
61 int Verbose() const { return fVerbose;}
62
63 std::vector<size_t> GetTensorShape(const std::string & name) const;
64 std::vector<Dim> GetDimTensorShape(const std::string & name) const;
65 std::vector<Dim> GetDynamicTensorShape(const std::string & name) const ;
66
67 // get the values for the tensor representing a shape
68 const std::vector<Dim> & GetShapeTensorValues(const std::string & tensor_name) const;
69
70 ETensorType GetTensorType(std::string name) const;
71
72
73 bool CheckIfTensorAlreadyExist(std::string tensor_name);
74 void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<Dim> shape);
75 void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<size_t> shape);
76 void AddOperator(std::unique_ptr<ROperator> op, int order_execution = -1);
77 void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
78 std::shared_ptr<void> data);
79 void AddConstantTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
80 std::shared_ptr<void> data);
81
82 void AddAliasTensor(const std::string & tensor_name, const std::string & orig_tensor_name);
83
84
85 template<class T>
86 void AddConstantTensor(const std::string & name, const std::vector<size_t> & shape, const T * data) {
87 size_t length = ConvertShapeToLength(shape);
88 std::shared_ptr<void> data_ptr(malloc(length * sizeof(T)), free);
89 std::memcpy(data_ptr.get(), (void*) data, length * sizeof(T));
91 }
92 // for boolean can be more convenient passing an std::vector
93 template<class T>
94 void AddConstantTensor(const std::string & name, const std::vector<size_t> & shape, const std::vector<T> & data) {
95 size_t length = data.size();
96 std::shared_ptr<void> data_ptr(malloc(length * sizeof(T)), free);
97 std::copy(data.begin(), data.end(), (T*) data_ptr.get());
98 //std::memcpy(data_ptr.get(), (void*) data, length * sizeof(T));
100 }
101
102 template <typename T>
103 void AddInitializedTensor(const std::string & tensor_name, const std::vector<std::size_t> & shape, T *raw_data)
104 {
105 size_t size = ConvertShapeToLength(shape);
106 std::shared_ptr<void> data(malloc(size * sizeof(T)), free);
107 std::memcpy(data.get(), raw_data, size * sizeof(T));
108 AddInitializedTensor(tensor_name, GetTemplatedType(T()), shape, data);
109 }
110
111 void AddShapeTensor(const std::string & name, const std::vector<Dim> & shapeValues, bool scalar = false);
112
113 void AddExtraCodeForDimShapes(const std::string & code) { fExtraCodeForDimShapes += code; }
114
115 // add and initialize subgraph to the model
116 void InitializeSubGraph(std::shared_ptr<RModel> graph);
117
118 // set a flag to indicate tensor does not need to be written in a weight file
119 // (e.g. shape tensors used as input to define a shape (in Reshape))
120 void SetNotWritableInitializedTensor(const std::string & tensor_name);
121
122 // Check if a tensor is initialized
123 bool IsInitializedTensor(const std::string &name) const;
124 // Check if a tensor is Constant (note a Constant tensor is also initialized)
125 bool IsConstantTensor(const std::string &name) const;
126 bool IsDynamicTensor(const std::string &name) const;
127 // Check if tensor is a input dynamic tensor (without a specified shape, based on Sim structure
128 bool IsDimInputTensor(const std::string &name) const;
129 // check if tensor is a fully specified input tensor
130 bool IsReadyInputTensor(const std::string &name) const;
131 /// check if a tensor is a shape tensor
132 bool IsShapeTensor(const std::string & name) const;
133 /// check if a tensor is a alias tensor
134 bool IsAliasTensor(const std::string & name) const;
135
136 // Add intermediate tensor
137 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<Dim> dim_shape);
138 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape);
139 // Add an intermediate dynamic tensor
140 void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector<Dim> shape);
141 // void Add a shape parameter
142 void AddShapeParam(const std::string & name, size_t def_value = 0);
143 void AddInputTensorName(std::string name);
144 void AddOutputTensorNameList(std::vector<std::string> output_tensor_names);
145 void
146 UpdateOutputTensorList(std::vector<std::string> curr_output_tensor, std::vector<std::string> modify_output_tensor);
147 void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
148 std::shared_ptr<void> data);
149 std::shared_ptr<void> GetInitializedTensorData(std::string tensor_name);
150
151 template<class T>
152 std::vector<T> GetTensorData(const std::string & name);
153
154 void Initialize(int batchSize = -1, bool verbose = false);
155 void Initialize(const std::map<std::string,size_t> & inputParams, bool verbose = false);
156
157 void Generate(std::underlying_type_t<Options> options, int batchSize = -1, long pos = 0, bool verbose = false);
158 void Generate(Options options = Options::kDefault, int batchSize = -1, int pos = 0, bool verbose = false)
159 {
160 Generate(static_cast<std::underlying_type_t<Options>>(options), batchSize, pos, verbose);
161 }
162 // generate the infer function signature. If isdecl= false generate the calling infer function
163 // used to infer the sub-graphs
164 std::string GenerateInferSignature(bool isdecl = true);
165
166 // calculate total intermediate memory and position intermediate tensor addresses
167 std::string AllocateIntermediateMemory(std::span<const std::string_view> op_output_tensors);
168 void CheckAndFlushIntermediateMemory(std::span<const std::string_view> op_output_tensors, const size_t& op_idx);
169
171
172 // get the size in bytes of the constant tensors
174 // get the size in bytes of the weight tensors
175 size_t GetWeightsTensorSize() const { return fWeightsTensorSize; }
176 // get the size in bytes of the intermediate tensors which are not part of the memory pool
177 size_t GetOtherTensorSize() const { return fOtherTensorSize; }
178 // get the size in bytes of the intermediate tensors managed by the memory pool
180 return (!fIntermediateMemoryInfo.total_stack.empty())
181 ? fIntermediateMemoryInfo.total_stack.rbegin()->first + fIntermediateMemoryInfo.total_stack.rbegin()->second.tensor_size
182 : 0;
183 }
184
185protected:
186 // internal functions
187 // generate code for the initialized tensors
189 // generate code for the intermediate tensors
191 // generate code for the dynamic tensors
193 // generate code for declarations needed by operators
195 // generate code for inference
196 void GenerateOutput();
197 // generate code for initializing memory pool for intermediate tensors
199 // Generate all session code
200 void GenerateSessionCode();
201 bool IsInputTensorShapeParam(std::string const &name) const;
202 std::vector<std::string> CollectTensorMemberNames(const std::string &input);
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 PrintSummary() const;
214 void PrintIntermediateTensors() const;
215 void PrintOutputTensors() const;
216 void OutputGenerated(std::string filename = "", bool append = false);
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 // flag to use vdt for fast math functions (e.g. exp in softmax)
239 void SetUseVDT(bool on) {
240 fUseVDT = on;
241 }
242 bool UseVDT() const { return fUseVDT;}
243
244 // Use the ClassDef macro to allow definition of custom streaming
246};
247
248// need to implement here templated member functions and its specialization
249
250
251template<class T>
252inline std::vector<T> RModel::GetTensorData(const std::string & name) {
253 if (!IsInitializedTensor(name)) return std::vector<T>{};
254 T * data = static_cast<T*>(GetInitializedTensorData(name).get());
256 return std::vector<T>(data, data+size);
257}
258
259template<>
260inline std::vector<Dim> RModel::GetTensorData<Dim>(const std::string & name) {
261 if (!IsShapeTensor(name)) return std::vector<Dim>{};
263}
264
265} // namespace SOFIE
266} // namespace Experimental
267} // namespace TMVA
268
269#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:148
#define malloc
Definition civetweb.c:1575
void AddShapeParam(const std::string &name, size_t def_value=0)
Definition RModel.cxx:335
std::vector< size_t > GetTensorShape(const std::string &name) const
Definition RModel.cxx:64
std::vector< Dim > GetDimTensorShape(const std::string &name) const
Definition RModel.cxx:100
std::unordered_map< std::string, DynamicTensorInfo > fDynamicTensorInfos
Definition RModel.hxx:31
bool IsDynamicTensor(const std::string &name) const
Definition RModel.cxx:286
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:250
void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector< Dim > dim_shape)
Definition RModel.cxx:301
size_t GetIntermediateTensorSize() const
Definition RModel.hxx:179
std::string GenerateInferSignature(bool isdecl=true)
Definition RModel.cxx:1078
RModel(std::string function_name)
Definition RModel.hxx:59
bool CheckIfTensorAlreadyExist(std::string tensor_name)
Definition RModel.cxx:157
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:1741
void OutputGenerated(std::string filename="", bool append=false)
Definition RModel.cxx:1949
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:168
std::unordered_map< std::string, TensorInfo > fIntermediateTensorInfos
Definition RModel.hxx:30
void SetOptimizationLevel(OptimizationLevel optim_level)
Definition RModel.hxx:170
void AddOutputTensorNameList(std::vector< std::string > output_tensor_names)
Definition RModel.cxx:343
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:232
void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector< Dim > shape)
Definition RModel.cxx:318
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:222
std::unordered_map< std::string_view, size_t > fIntermediateTensorFrequencyLookup
! lookup table for intermediate tensor frequency (transient)
Definition RModel.hxx:46
void AddExtraCodeForDimShapes(const std::string &code)
Definition RModel.hxx:113
void AddInputTensorName(std::string name)
Definition RModel.cxx:187
std::vector< std::string > fOutputTensorNames
Definition RModel.hxx:36
bool IsDimInputTensor(const std::string &name) const
Definition RModel.cxx:291
bool IsShapeTensor(const std::string &name) const
check if a tensor is a shape tensor
Definition RModel.cxx:260
size_t GetConstantTensorSize() const
Definition RModel.hxx:173
bool IsInitializedTensor(const std::string &name) const
Definition RModel.cxx:273
bool IsAliasTensor(const std::string &name) const
check if a tensor is a alias tensor
Definition RModel.cxx:264
void AddInitializedTensor(const std::string &tensor_name, const std::vector< std::size_t > &shape, T *raw_data)
Definition RModel.hxx:103
void CheckAndFlushIntermediateMemory(std::span< const std::string_view > op_output_tensors, const size_t &op_idx)
Definition RModel.cxx:488
void AddOperator(std::unique_ptr< ROperator > op, int order_execution=-1)
Definition RModel.cxx:191
RModel()=default
Default constructor.
void HeadInitializedTensors(std::string name, int n_print=50)
Definition RModel.cxx:1913
bool IsConstantTensor(const std::string &name) const
Definition RModel.cxx:277
void Initialize(int batchSize=-1, bool verbose=false)
Definition RModel.cxx:567
size_t GetWeightsTensorSize() const
Definition RModel.hxx:175
long WriteInitializedTensorsToFile(std::string filename="")
Definition RModel.cxx:1606
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:1467
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:1020
std::vector< Dim > GetDynamicTensorShape(const std::string &name) const
Definition RModel.cxx:111
void AddConstantTensor(const std::string &name, const std::vector< size_t > &shape, const std::vector< T > &data)
Definition RModel.hxx:94
std::unordered_map< std::string, InputTensorInfo > fInputTensorInfos
Definition RModel.hxx:27
std::shared_ptr< void > GetInitializedTensorData(std::string tensor_name)
Definition RModel.cxx:366
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:383
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:252
void SetFilename(std::string filename)
Definition RModel.hxx:217
void InitializeSubGraph(std::shared_ptr< RModel > graph)
Definition RModel.cxx:725
std::unordered_map< std::string, std::string > fShapeParams
Definition RModel.hxx:33
void SetNotWritableInitializedTensor(const std::string &tensor_name)
Definition RModel.cxx:375
ETensorType GetTensorType(std::string name) const
Definition RModel.cxx:125
std::vector< std::string > fInputTensorNames
Definition RModel.hxx:37
const std::vector< std::string > & GetInputTensorNames() const
Definition RModel.hxx:206
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:357
const std::vector< Dim > & GetShapeTensorValues(const std::string &tensor_name) const
Definition RModel.cxx:268
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:295
void UpdateOutputTensorList(std::vector< std::string > curr_output_tensor, std::vector< std::string > modify_output_tensor)
Definition RModel.cxx:350
const std::vector< std::string > & GetDimShapeNames() const
Definition RModel.hxx:208
RModel(std::string name, std::string parsedtime)
Definition RModel.hxx:56
void AddShapeTensor(const std::string &name, const std::vector< Dim > &shapeValues, bool scalar=false)
Definition RModel.cxx:242
void AddConstantTensor(const std::string &name, const std::vector< size_t > &shape, const T *data)
Definition RModel.hxx:86
void Generate(Options options=Options::kDefault, int batchSize=-1, int pos=0, bool verbose=false)
Definition RModel.hxx:158
bool IsInputTensorShapeParam(std::string const &name) const
Check if a given parameter is used for the shape of an input tensor.
Definition RModel.cxx:1002
std::size_t ConvertShapeToLength(const std::vector< size_t > &shape)
ETensorType GetTemplatedType(T)
create variable transformations
std::map< size_t, TensorMemoryInfo > total_stack