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 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 std::vector<std::unique_ptr<ROperator>> fOperators;
39
40 std::vector<std::shared_ptr<RModel>> fSubGraphs; ///<! sub-graph models (transient)
41 RModel * fParentGraph = nullptr;
42
43 // memory pool information for intermediate tensors
44 MemoryPoolInfo fIntermediateMemoryInfo; ///<! intermediate memory info (transient)
45 std::unordered_map<std::string_view, size_t> fIntermediateTensorFrequencyLookup; ///<! lookup table for intermediate tensor frequency (transient)
46
47 std::string fExtraCodeForDimShapes; // extra code needed for initialization of dynamic parameters (e.g. number of non zero elements in NonZero operator)
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 int Verbose() const { return fVerbose;}
58
59 std::vector<size_t> GetTensorShape(const std::string & name) const;
60 std::vector<Dim> GetDimTensorShape(const std::string & name) const;
61 std::vector<Dim> GetDynamicTensorShape(const std::string & name) const ;
62
63 // get the values for the tensor representing a shape
64 const std::vector<Dim> & GetShapeTensorValues(const std::string & tensor_name) const;
65
66 ETensorType GetTensorType(std::string name) const;
67
68
69 bool CheckIfTensorAlreadyExist(std::string tensor_name);
70 void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<Dim> shape);
71 void AddInputTensorInfo(std::string input_name, ETensorType type, std::vector<size_t> shape);
72 void AddOperator(std::unique_ptr<ROperator> op, int order_execution = -1);
73 void AddInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
74 std::shared_ptr<void> data);
75 void AddInitializedTensor(const std::string &tensor_name, ETensorType tensor_type,
76 const std::vector<std::size_t> &shape, void *raw_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 void AddShapeTensor(const std::string & name, const std::vector<Dim> & shapeValues, bool scalar = false);
101
102 void AddExtraCodeForDimShapes(const std::string & code) { fExtraCodeForDimShapes += code; }
103
104 // add and initialize subgraph to the model
105 void InitializeSubGraph(std::shared_ptr<RModel> graph);
106
107 // set a flag to indicate tensor does not need to be written in a weight file
108 // (e.g. shape tensors used as input to define a shape (in Reshape))
109 void SetNotWritableInitializedTensor(const std::string & tensor_name);
110
111 // Check if a tensor is initialized
112 bool IsInitializedTensor(const std::string &name) const;
113 // Check if a tensor is Constant (note a Constant tensor is also initialized)
114 bool IsConstantTensor(const std::string &name) const;
115 bool IsDynamicTensor(const std::string &name) const;
116 // Check if tensor is a input dynamic tensor (without a specified shape, based on Sim structure
117 bool IsDimInputTensor(const std::string &name) const;
118 // check if tensor is a fully specified input tensor
119 bool IsReadyInputTensor(const std::string &name) const;
120 /// check if a tensor is a shape tensor
121 bool IsShapeTensor(const std::string & name) const;
122 /// check if a tensor is a alias tensor
123 bool IsAliasTensor(const std::string & name) const;
124
125 // Add intermediate tensor
126 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<Dim> dim_shape);
127 void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape);
128 // Add an intermediate dynamic tensor
129 void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector<Dim> shape);
130 // void Add a shape parameter
131 void AddShapeParam(const std::string & name, size_t def_value = 0);
132 void AddInputTensorName(std::string name);
133 void AddOutputTensorNameList(std::vector<std::string> output_tensor_names);
134 void
135 UpdateOutputTensorList(std::vector<std::string> curr_output_tensor, std::vector<std::string> modify_output_tensor);
136 void UpdateInitializedTensor(std::string tensor_name, ETensorType type, std::vector<std::size_t> shape,
137 std::shared_ptr<void> data);
138 std::shared_ptr<void> GetInitializedTensorData(std::string tensor_name);
139
140 template<class T>
141 std::vector<T> GetTensorData(const std::string & name);
142
143 void Initialize(int batchSize = -1, bool verbose = false);
144 void Initialize(const std::map<std::string,size_t> & inputParams, bool verbose = false);
145
146 void Generate(std::underlying_type_t<Options> options, int batchSize = -1, bool verbose = false);
147 void Generate(Options options = Options::kDefault, int batchSize = -1, bool verbose = false)
148 {
149 Generate(static_cast<std::underlying_type_t<Options>>(options), batchSize, verbose);
150 }
151 // generate the infer function signature. If isdecl= false generate the calling infer function
152 // used to infer the sub-graphs
153 std::string GenerateInferSignature(bool isdecl = true);
154
155 // calculate total intermediate memory and position intermediate tensor addresses
156 std::string AllocateIntermediateMemory(std::span<const std::string_view> op_output_tensors);
157 void CheckAndFlushIntermediateMemory(std::span<const std::string_view> op_output_tensors, const size_t& op_idx);
158
160
161 // get the size in bytes of the constant tensors
163 // get the size in bytes of the weight tensors
164 size_t GetWeightsTensorSize() const { return fWeightsTensorSize; }
165 // get the size in bytes of the intermediate tensors which are not part of the memory pool
166 size_t GetOtherTensorSize() const { return fOtherTensorSize; }
167 // get the size in bytes of the intermediate tensors managed by the memory pool
169 return (!fIntermediateMemoryInfo.total_stack.empty())
170 ? fIntermediateMemoryInfo.total_stack.rbegin()->first + fIntermediateMemoryInfo.total_stack.rbegin()->second.tensor_size
171 : 0;
172 }
173
174protected:
175 // internal functions
176 // generate code for the initialized tensors
178 // generate code for the intermediate tensors
180 // generate code for the dynamic tensors
182 // generate code for declarations needed by operators
184 // generate code for inference
185 void GenerateOutput();
186 // generate code for initializing memory pool for intermediate tensors
188 // Generate all session code
189 void GenerateSessionCode();
190 bool IsInputTensorShapeParam(std::string const &name) const;
191 std::vector<std::string> CollectTensorMemberNames(const std::string &input);
193
194public:
195 const std::vector<std::string> & GetInputTensorNames() const { return fInputTensorNames; }
196 const std::vector<std::string> & GetOutputTensorNames() const { return fOutputTensorNames; }
197 const std::vector<std::string> & GetDimShapeNames() const { return fDimShapeNames; }
198
200 long WriteInitializedTensorsToFile(std::string filename = "");
201
202 void PrintSummary() const;
203 void PrintIntermediateTensors() const;
204 void PrintOutputTensors() const;
205 void OutputGenerated(std::string filename = "", bool append = false);
206 void SetFilename(std::string filename) { fName = filename; }
207
208 /*
209 template <typename T>
210 void AddInitializedTensor(std::string tensor_name, RTensor<T> new_tensor){
211 //a view only
212 T obj;
213 if (fInitializedTensors.find(tensor_name) != fInitializedTensors.end()){
214 throw std::runtime_error("TMVA-SOFIE: initialized tensor with name " + tensor_name + " already exists \n");
215 }
216 InitializedTensor new_tensor_ {GetTemplatedType(obj), new_tensor.GetShape() ,
217 static_cast<void>(new_tensor.GetData())}; fInitializedTensors[tensor_name] = new_tensor_;
218 }
219 */
220
221 void PrintRequiredInputTensors() const;
222 void PrintInitializedTensors() const;
223 void PrintDynamicTensors() const;
224 void HeadInitializedTensors(std::string name, int n_print = 50);
225
226 bool UseSession() const { return fUseSession; }
227 // flag to use vdt for fast math functions (e.g. exp in softmax)
228 void SetUseVDT(bool on) {
229 fUseVDT = on;
230 }
231 bool UseVDT() const { return fUseVDT;}
232
233 // RModel is an internal representation that doesn't support ROOT IO (if you need model IO, use ONNX directly).
235};
236
237// need to implement here templated member functions and its specialization
238
239
240template<class T>
241inline std::vector<T> RModel::GetTensorData(const std::string & name) {
242 if (!IsInitializedTensor(name)) return std::vector<T>{};
243 T * data = static_cast<T*>(GetInitializedTensorData(name).get());
245 return std::vector<T>(data, data+size);
246}
247
248template<>
249inline std::vector<Dim> RModel::GetTensorData<Dim>(const std::string & name) {
250 if (!IsShapeTensor(name)) return std::vector<Dim>{};
252}
253
254} // namespace SOFIE
255} // namespace Experimental
256} // namespace TMVA
257
258#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:142
void AddShapeParam(const std::string &name, size_t def_value=0)
Definition RModel.cxx:345
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:30
bool IsDynamicTensor(const std::string &name) const
Definition RModel.cxx:296
const std::vector< std::string > & GetOutputTensorNames() const
Definition RModel.hxx:196
void AddAliasTensor(const std::string &tensor_name, const std::string &orig_tensor_name)
Definition RModel.cxx:260
void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector< Dim > dim_shape)
Definition RModel.cxx:311
size_t GetIntermediateTensorSize() const
Definition RModel.hxx:168
std::string GenerateInferSignature(bool isdecl=true)
Definition RModel.cxx:1095
bool CheckIfTensorAlreadyExist(std::string tensor_name)
Definition RModel.cxx:157
std::vector< std::unique_ptr< ROperator > > fOperators
Definition RModel.hxx:38
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:1762
void OutputGenerated(std::string filename="", bool append=false)
Definition RModel.cxx:1969
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:168
std::unordered_map< std::string, TensorInfo > fIntermediateTensorInfos
Definition RModel.hxx:29
void SetOptimizationLevel(OptimizationLevel optim_level)
Definition RModel.hxx:159
void AddOutputTensorNameList(std::vector< std::string > output_tensor_names)
Definition RModel.cxx:353
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:242
void AddDynamicTensor(std::string tensor_name, ETensorType type, std::vector< Dim > shape)
Definition RModel.cxx:328
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:222
std::unordered_map< std::string_view, size_t > fIntermediateTensorFrequencyLookup
! lookup table for intermediate tensor frequency (transient)
Definition RModel.hxx:45
void AddExtraCodeForDimShapes(const std::string &code)
Definition RModel.hxx:102
void AddInputTensorName(std::string name)
Definition RModel.cxx:187
std::vector< std::string > fOutputTensorNames
Definition RModel.hxx:35
bool IsDimInputTensor(const std::string &name) const
Definition RModel.cxx:301
bool IsShapeTensor(const std::string &name) const
check if a tensor is a shape tensor
Definition RModel.cxx:270
size_t GetConstantTensorSize() const
Definition RModel.hxx:162
bool IsInitializedTensor(const std::string &name) const
Definition RModel.cxx:283
bool IsAliasTensor(const std::string &name) const
check if a tensor is a alias tensor
Definition RModel.cxx:274
void CheckAndFlushIntermediateMemory(std::span< const std::string_view > op_output_tensors, const size_t &op_idx)
Definition RModel.cxx:498
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:1933
bool IsConstantTensor(const std::string &name) const
Definition RModel.cxx:287
void Initialize(int batchSize=-1, bool verbose=false)
Definition RModel.cxx:577
size_t GetWeightsTensorSize() const
Definition RModel.hxx:164
long WriteInitializedTensorsToFile(std::string filename="")
Definition RModel.cxx:1635
OptimizationLevel fOptimizationLevel
Definition RModel.hxx:24
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:1037
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:92
std::unordered_map< std::string, InputTensorInfo > fInputTensorInfos
Definition RModel.hxx:26
std::shared_ptr< void > GetInitializedTensorData(std::string tensor_name)
Definition RModel.cxx:376
MemoryPoolInfo fIntermediateMemoryInfo
! intermediate memory info (transient)
Definition RModel.hxx:44
std::string AllocateIntermediateMemory(std::span< const std::string_view > op_output_tensors)
Definition RModel.cxx:393
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:241
void SetFilename(std::string filename)
Definition RModel.hxx:206
void InitializeSubGraph(std::shared_ptr< RModel > graph)
Definition RModel.cxx:735
std::unordered_map< std::string, std::string > fShapeParams
Definition RModel.hxx:32
void SetNotWritableInitializedTensor(const std::string &tensor_name)
Definition RModel.cxx:385
ETensorType GetTensorType(std::string name) const
Definition RModel.cxx:125
std::vector< std::string > fInputTensorNames
Definition RModel.hxx:36
const std::vector< std::string > & GetInputTensorNames() const
Definition RModel.hxx:195
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:367
void Generate(std::underlying_type_t< Options > options, int batchSize=-1, bool verbose=false)
Definition RModel.cxx:1502
const std::vector< Dim > & GetShapeTensorValues(const std::string &tensor_name) const
Definition RModel.cxx:278
std::vector< std::shared_ptr< RModel > > fSubGraphs
! sub-graph models (transient)
Definition RModel.hxx:40
bool IsReadyInputTensor(const std::string &name) const
Definition RModel.cxx:305
void UpdateOutputTensorList(std::vector< std::string > curr_output_tensor, std::vector< std::string > modify_output_tensor)
Definition RModel.cxx:360
const std::vector< std::string > & GetDimShapeNames() const
Definition RModel.hxx:197
void Generate(Options options=Options::kDefault, int batchSize=-1, bool verbose=false)
Definition RModel.hxx:147
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:252
void AddConstantTensor(const std::string &name, const std::vector< size_t > &shape, const T *data)
Definition RModel.hxx:84
bool IsInputTensorShapeParam(std::string const &name) const
Check if a given parameter is used for the shape of an input tensor.
Definition RModel.cxx:1019
std::size_t ConvertShapeToLength(const std::vector< size_t > &shape)
create variable transformations
std::map< size_t, TensorMemoryInfo > total_stack