Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ROperator_Slice.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_ROPERATOR_SLICE
2#define TMVA_SOFIE_ROPERATOR_SLICE
3
5#include "TMVA/ROperator.hxx"
6#include "TMVA/RModel.hxx"
7
8#include <cassert>
9#include <sstream>
10#include <numeric>
11
12namespace TMVA{
13namespace Experimental{
14namespace SOFIE{
15
16// slice operator
17
18template <typename IType>
20{
21
22private:
23
24 std::string fNData; // input data tensor name
25 std::string fNOutput; // output data name
26 std::vector<std::string> fNames; // tensor names for meta(axis) information
27 std::vector<size_t> fShapeInput; // input shape data
28 std::vector<size_t> fShapeOutput; // output shape data
29 // saved Start/End.Steps are corrected from initial ONNX for negative/default values
30 // and are available for each axis
31 std::vector<IType> fStart; // starting values of slices
32 std::vector<IType> fEnd; // End values of slices
33 std::vector<IType> fSteps; // step values of slices
34
35 std::vector<std::vector<IType>> fAttributes; // attributes for the version <=10 case
36
37
38public:
39
41
42 // ctor for versions >= 10
43 ROperator_Slice(std::string nameData, std::vector<std::string> names, std::string nameOutput)
44 : fNData(UTILITY::Clean_name(nameData)),
45 fNOutput(UTILITY::Clean_name(nameOutput))
46 {
47 fNames.resize(4);
48 // axes and steps can be optional
49 for (size_t i = 0; i < names.size(); ++i) {
50 fNames[i] = UTILITY::Clean_name(names[i]);
51 }
52
53 }
54 // ctor for versions < 10
55 ROperator_Slice(std::string nameData, std::vector<IType> starts, std::vector<IType> ends, std::vector<IType> axes, std::string nameOutput)
56 : fNData(UTILITY::Clean_name(nameData)),
57 fNOutput(UTILITY::Clean_name(nameOutput))
58 {
59 fAttributes.push_back(starts);
60 fAttributes.push_back(ends);
61 fAttributes.push_back(axes);
62 }
63
64 // output type is same as input
65 std::vector<ETensorType> TypeInference(std::vector<ETensorType> input){
66 auto ret = std::vector<ETensorType>(1, input[0]);
67 return ret;
68 }
69
70 // output shape
71 std::vector<std::vector<size_t>> ShapeInference(std::vector<std::vector<size_t>> input){
72 auto & input_shape = input[0];
73 // assume dimension of output shape is SAME AS INPUT !
74 std::vector<std::vector<size_t>> ret(1, input_shape);
75 auto & output_shape = ret[0];
76 for (size_t i = 0; i < input_shape.size(); i++) {
77 output_shape[i] = (fEnd[i]-fStart[i])/ fSteps[i];
78 }
79 return ret;
80 }
81
82
83 void Initialize(RModel& model){
84 if (model.CheckIfTensorAlreadyExist(fNData) == false){ //input must be a graph input, or already initialized intermediate tensor
85 throw std::runtime_error("TMVA Slice Op Input Tensor is not found in model");
86 }
87
88 std::vector<std::vector<size_t>> shapes;
90 shapes.push_back(fShapeInput);
91
92 std::vector<std::vector<IType>> itensors(4);
93 if (fNames.size() > 0) {
94 // loop on the extra 2 or 3 or 4 inputs
95 for (size_t i = 0; i < fNames.size(); ++i) {
96 if (!fNames[i].empty()) {
97 // std::cout << " i " << i << " getting data for tensor " << fNames[i] << std::endl;
98 auto dptr = model.GetInitializedTensorData(fNames[i]);
99 auto tensor = static_cast<IType *>(dptr.get());
100 auto vec = model.GetTensorShape(fNames[i]);
101 assert(vec.size() == 1);
102 itensors[i] = std::vector<IType>(tensor, tensor + vec[0]);
103 } else {
104 switch (i) {
105 case 2: // missing axes
106 itensors[2] = std::vector<IType>(fShapeInput.size());
107 std::iota(itensors[2].begin(), itensors[2].end(), 0);
108 break;
109 case 3: // missing steps
110 itensors[3] = std::vector<IType>(itensors[0].size(), 1);
111 default: break;
112 }
113 }
114 }
115 } else {
116 assert(fAttributes.size() > 1);
117 for (size_t i = 0; i < fAttributes.size(); i++) {
118 itensors[i] = fAttributes[i];
119 }
120 }
121 size_t dim = fShapeInput.size();
122
123 fSteps = std::vector<IType>(dim, 1);
124 fStart = std::vector<IType>(dim, 0);
125 fEnd = std::vector<IType>(dim, 0);
126 std::copy(fShapeInput.begin(), fShapeInput.end(), fEnd.begin());
127
128 auto istart = itensors[0];
129 auto iend = itensors[1];
130 auto iaxes = itensors[2];
131 auto isteps = itensors[3];
132
133 // make tensor axis
134 // if iaxes.size is =0 tensor axis is missing and use defaults
135 if (iaxes.size() > 0) {
136 for (size_t i = 0; i < iaxes.size(); i++) {
137 // negative axes - they count from the back
138 if (iaxes[i] < 0) iaxes[i] = dim + iaxes[i];
139 if (iaxes[i] < 0 || iaxes[i] >= static_cast<IType>(dim))
140 throw std::runtime_error("TMVA Slice Op : invalid axis value " + std::to_string(iaxes[i]) +
141 " for " + std::to_string(i));
142
143 size_t iAxisDim = fShapeInput[iaxes[i]];
144 // find start/end/step for given axis
145 // check step size for clamping starting/end value
146 if (istart[i] < 0) istart[i] = iAxisDim + istart[i];
147 if (iend[i] < 0) iend[i] = iAxisDim + iend[i];
148 if (istart[i] < 0) istart[i] = 0;
149 if (isteps[i] > 0) {
150 if (istart[i] > static_cast<IType>(iAxisDim)) istart[i] = static_cast<IType>(iAxisDim);
151 if (iend[i] < 0) iend[i] = 0;
152 if (iend[i] > static_cast<IType>(iAxisDim)) iend[i] = static_cast<IType>(iAxisDim);
153 } else if (isteps[i] < 0) {
154 if (istart[i] > static_cast<IType>(iAxisDim)-1) istart[i] = static_cast<IType>(iAxisDim) -1;
155 if (iend[i] < -1) iend[i] = -1;
156 if (iend[i] > static_cast<IType>(iAxisDim)-1) iend[i] = static_cast<IType>(iAxisDim) -1;
157 } else {
158 throw std::runtime_error("TMVA Slice Op : invalid step value " + std::to_string(isteps[i]) +
159 " for " + std::to_string(i));
160 }
161 fStart[iaxes[i]] = istart[i];
162 fEnd[iaxes[i]] = iend[i];
163 fSteps[iaxes[i]] = isteps[i];
164 }
165 }
166
168 // case input is a constant tensor and of int64 type
170 fIsOutputConstant = true;
171 auto inputData = static_cast<int64_t*>(model.GetInitializedTensorData(fNData).get());
172 size_t outputSize = ConvertShapeToLength(fShapeOutput);
173 std::vector<int64_t> outputData(outputSize);
175 // perform slice using a recursive function- need to use two lambda functions for this
176 auto sliceRecursive = [&](size_t iaxis, size_t & outIdx, size_t & inOffset) {
177 auto slice_impl = [&](size_t iax, size_t & outputIdx, size_t & inputOffset, auto & sliceRecImpl) {
178 // compute indices
179 std::vector<IType> indices;
180 for (IType i = fStart[iax]; (fSteps[iax] > 0) ? i < fEnd[iax] : i > fEnd[iax]; i += fSteps[iax] )
181 indices.push_back(i);
182 if (iax == dim-1) { // last axis
183 for (size_t i = 0; i < indices.size(); i++) {
184 outputData[outputIdx] = inputData[inputOffset + indices[i]];
185 outputIdx++;
186 }
187 return;
188 } else {
189 for (size_t i = 0; i < indices.size(); i++) {
190 size_t offset = inputOffset + inputStride[iax]*indices[i];
192 }
193 }
194 };
196 };
197 size_t idx = 0;
198 size_t offset = 0;
199 sliceRecursive(0, idx, offset);
200
201 model.AddConstantTensor<int64_t>(fNOutput, fShapeOutput, outputData.data());
202 if (model.Verbose()) {
203 std::cout << "Slice: output is a constant tensor " << ConvertShapeToString(fShapeOutput) << " : "
204 << ConvertValuesToString(outputData) << std::endl;
205 }
206 }
207 else {
209 if (model.Verbose()) {
210 std::cout << "Slice ---> " << fNOutput << " " << ConvertShapeToString(fShapeOutput) << std::endl;
211 }
212 }
213 }
214
215 std::string Generate(std::string OpName){
216 if (fIsOutputConstant) return ""; //no op for constant tensors
217
218 OpName = "op_" + OpName;
219 if (fShapeInput.empty() || fShapeOutput.empty()){
220 throw std::runtime_error("TMVA SOFIE Slice Op called to Generate without being initialized first");
221 }
222
223 std::stringstream out;
224 //std::string opName = "Slice";
225
226 out << SP << "///------- Slice operator\n" << std::endl;
227 // loop on the dimensions depending no the orders
228 size_t ndim = fShapeInput.size();
229 std::vector<size_t> strides(ndim,1);
230 for (int i = int(ndim-2); i >=0 ; i--) {
231 strides[i] = strides[i+1]*fShapeInput[i+1];
232 }
233
234 out << SP << "{\n"; // define operator scope
235 out << SP << "size_t iOut = 0;\n";
236 std::string MSP = SP;
237 for (size_t idim = 0; idim < ndim; idim++) {
238 out << MSP << "for (size_t i" << idim << " = " << fStart[idim] << "; i" << idim << " < " << fEnd[idim]
239 << "; i" << idim << "+= " << fSteps[idim] << ") {\n";
240 MSP += SP;
241 if (idim < ndim-1) out << MSP << "size_t stride" << idim << " = " << strides[idim] << "*i" << idim << ";\n";
242 }
243 out << MSP << "size_t iInput = ";
244 for (size_t idim = 0; idim < ndim-1; idim++) out << " stride" << idim << " + ";
245 // here should be step size ?
246 out << "i" << ndim-1 << ";\n";
247 out << MSP << "tensor_" << fNOutput << "[iOut++] = tensor_" <<fNData << "[iInput];\n";
248 for (size_t idim = 0; idim < ndim; idim++) {
249 MSP = MSP.replace(0,SP.length(),"");
250 out << MSP << "}\n";
251 }
252 out << SP << "}\n"; // end operator scope
253
254 return out.str();
255 }
256
257};
258
259}//SOFIE
260}//Experimental
261}//TMVA
262
263
264#endif //TMVA_SOFIE_ROPERATOR_SLICE
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 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 Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
const ETensorType & GetTensorType(std::string name)
Definition RModel.cxx:94
void AddIntermediateTensor(std::string tensor_name, ETensorType type, std::vector< Dim > dim_shape)
Definition RModel.cxx:213
bool CheckIfTensorAlreadyExist(std::string tensor_name)
Definition RModel.cxx:122
void AddConstantTensor(std::string tensor_name, ETensorType type, std::vector< std::size_t > shape, std::shared_ptr< void > data)
Definition RModel.cxx:178
bool IsInitializedTensor(const std::string &name) const
Definition RModel.cxx:188
const std::vector< size_t > & GetTensorShape(std::string name)
Definition RModel.cxx:56
std::shared_ptr< void > GetInitializedTensorData(std::string tensor_name)
Definition RModel.cxx:274
std::vector< std::vector< IType > > fAttributes
std::vector< std::vector< size_t > > ShapeInference(std::vector< std::vector< size_t > > input)
std::vector< ETensorType > TypeInference(std::vector< ETensorType > input)
ROperator_Slice(std::string nameData, std::vector< IType > starts, std::vector< IType > ends, std::vector< IType > axes, std::string nameOutput)
ROperator_Slice(std::string nameData, std::vector< std::string > names, std::string nameOutput)
std::string Generate(std::string OpName)
bool fIsOutputConstant
flag to identify if operator has a constant output (no need to generate code)
Definition ROperator.hxx:45
const std::string SP
space used to correctly indent the generated C++ code
Definition ROperator.hxx:43
std::string Clean_name(std::string input_tensor_name)
std::vector< size_t > ComputeStrideFromShape(const std::vector< size_t > &shape)
compute stride of a tensor given its shape (assume layout is row-major)
std::string ConvertValuesToString(size_t n, const T *data)
std::string ConvertShapeToString(std::vector< size_t > shape)
std::size_t ConvertShapeToLength(std::vector< size_t > shape)
create variable transformations