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
55 }
56 // ctor for versions < 10
57 ROperator_Slice(std::string nameData, std::vector<IType> starts, std::vector<IType> ends, std::vector<IType> axes, std::string nameOutput)
58 : fNData(UTILITY::Clean_name(nameData)),
59 fNOutput(UTILITY::Clean_name(nameOutput))
60 {
61 fAttributes.push_back(starts);
62 fAttributes.push_back(ends);
63 fAttributes.push_back(axes);
64 }
65
66 // output type is same as input
67 std::vector<ETensorType> TypeInference(std::vector<ETensorType> input) override {
68 auto ret = std::vector<ETensorType>(1, input[0]);
69 return ret;
70 }
71
72 // output shape
73 std::vector<std::vector<size_t>> ShapeInference(std::vector<std::vector<size_t>> input) override {
74 auto & input_shape = input[0];
75 // assume dimension of output shape is SAME AS INPUT !
76 std::vector<std::vector<size_t>> ret(1, input_shape);
77 auto & output_shape = ret[0];
78 for (size_t i = 0; i < input_shape.size(); i++) {
79 output_shape[i] = (fEnd[i]-fStart[i])/ fSteps[i];
80 }
81 return ret;
82 }
83
84
85 void Initialize(RModel& model) override {
86 if (model.CheckIfTensorAlreadyExist(fNData) == false){ //input must be a graph input, or already initialized intermediate tensor
87 throw std::runtime_error("TMVA Slice Op Input Tensor is not found in model");
88 }
89
90 std::vector<std::vector<size_t>> shapes;
92 fShapeInput);
93
94 std::vector<std::vector<IType>> itensors(4);
95 if (fNames.size() > 0) {
96 // loop on the extra 2 or 3 or 4 inputs
97 for (size_t i = 0; i < fNames.size(); ++i) {
98 if (!fNames[i].empty()) {
99 // std::cout << " i " << i << " getting data for tensor " << fNames[i] << std::endl;
100 auto dptr = model.GetInitializedTensorData(fNames[i]);
101 auto tensor = static_cast<IType *>(dptr.get());
102 auto vec = model.GetTensorShape(fNames[i]);
103 assert(vec.size() == 1);
104 itensors[i] = std::vector<IType>(tensor, tensor + vec[0]);
105 } else {
106 switch (i) {
107 case 2: // missing axes
108 itensors[2] = std::vector<IType>(fShapeInput.size());
109 std::iota(itensors[2].begin(), itensors[2].end(), 0);
110 break;
111 case 3: // missing steps
112 itensors[3] = std::vector<IType>(itensors[0].size(), 1);
113 default: break;
114 }
115 }
116 }
117 } else {
118 assert(fAttributes.size() > 1);
119 for (size_t i = 0; i < fAttributes.size(); i++) {
120 itensors[i] = fAttributes[i];
121 }
122 }
123 size_t dim = fShapeInput.size();
124
125 fSteps = std::vector<IType>(dim, 1);
126 fStart = std::vector<IType>(dim, 0);
127 fEnd = std::vector<IType>(dim, 0);
128 std::copy(fShapeInput.begin(), fShapeInput.end(), fEnd.begin());
129
130 auto istart = itensors[0];
131 auto iend = itensors[1];
132 auto iaxes = itensors[2];
133 auto isteps = itensors[3];
134
135 // make tensor axis
136 // if iaxes.size is =0 tensor axis is missing and use defaults
137 if (iaxes.size() > 0) {
138 for (size_t i = 0; i < iaxes.size(); i++) {
139 // negative axes - they count from the back
140 if (iaxes[i] < 0) iaxes[i] = dim + iaxes[i];
141 if (iaxes[i] < 0 || iaxes[i] >= static_cast<IType>(dim))
142 throw std::runtime_error("TMVA Slice Op : invalid axis value " + std::to_string(iaxes[i]) +
143 " for " + std::to_string(i));
144
145 size_t iAxisDim = fShapeInput[iaxes[i]];
146 // find start/end/step for given axis
147 // check step size for clamping starting/end value
148 if (istart[i] < 0) istart[i] = iAxisDim + istart[i];
149 if (iend[i] < 0) iend[i] = iAxisDim + iend[i];
150 if (istart[i] < 0) istart[i] = 0;
151 if (isteps[i] > 0) {
152 if (istart[i] > static_cast<IType>(iAxisDim)) istart[i] = static_cast<IType>(iAxisDim);
153 if (iend[i] < 0) iend[i] = 0;
154 if (iend[i] > static_cast<IType>(iAxisDim)) iend[i] = static_cast<IType>(iAxisDim);
155 } else if (isteps[i] < 0) {
156 if (istart[i] > static_cast<IType>(iAxisDim)-1) istart[i] = static_cast<IType>(iAxisDim) -1;
157 if (iend[i] < -1) iend[i] = -1;
158 if (iend[i] > static_cast<IType>(iAxisDim)-1) iend[i] = static_cast<IType>(iAxisDim) -1;
159 } else {
160 throw std::runtime_error("TMVA Slice Op : invalid step value " + std::to_string(isteps[i]) +
161 " for " + std::to_string(i));
162 }
163 fStart[iaxes[i]] = istart[i];
164 fEnd[iaxes[i]] = iend[i];
165 fSteps[iaxes[i]] = isteps[i];
166 }
167 }
168
170 // case input is a constant tensor and of int64 type
172 fIsOutputConstant = true;
173 auto inputData = static_cast<int64_t*>(model.GetInitializedTensorData(fNData).get());
174 size_t outputSize = ConvertShapeToLength(fShapeOutput);
175 std::vector<int64_t> outputData(outputSize);
177 // perform slice using a recursive function- need to use two lambda functions for this
178 auto sliceRecursive = [&](size_t iaxis, size_t & outIdx, size_t & inOffset) {
179 auto slice_impl = [&](size_t iax, size_t & outputIdx, size_t & inputOffset, auto & sliceRecImpl) {
180 // compute indices
181 std::vector<IType> indices;
182 for (IType i = fStart[iax]; (fSteps[iax] > 0) ? i < fEnd[iax] : i > fEnd[iax]; i += fSteps[iax] )
183 indices.push_back(i);
184 if (iax == dim-1) { // last axis
185 for (size_t i = 0; i < indices.size(); i++) {
186 outputData[outputIdx] = inputData[inputOffset + indices[i]];
187 outputIdx++;
188 }
189 return;
190 } else {
191 for (size_t i = 0; i < indices.size(); i++) {
192 size_t offset = inputOffset + inputStride[iax]*indices[i];
194 }
195 }
196 };
198 };
199 size_t idx = 0;
200 size_t offset = 0;
201 sliceRecursive(0, idx, offset);
202
203 model.AddConstantTensor<int64_t>(fNOutput, fShapeOutput, outputData.data());
204 if (model.Verbose()) {
205 std::cout << "Slice: output is a constant tensor " << ConvertShapeToString(fShapeOutput) << " : "
206 << ConvertValuesToString(outputData) << std::endl;
207 }
208 }
209 else {
211 if (model.Verbose()) {
212 std::cout << "Slice ---> " << fNOutput << " " << ConvertShapeToString(fShapeOutput) << std::endl;
213 }
214 }
215 }
216
217 std::string Generate(std::string OpName) override {
218 if (fIsOutputConstant) return ""; //no op for constant tensors
219
220 OpName = "op_" + OpName;
221 if (fShapeInput.empty() || fShapeOutput.empty()){
222 throw std::runtime_error("TMVA SOFIE Slice Op called to Generate without being initialized first");
223 }
224
225 std::stringstream out;
226 //std::string opName = "Slice";
227
228 out << SP << "///------- Slice operator\n" << std::endl;
229 // loop on the dimensions depending no the orders
230 size_t ndim = fShapeInput.size();
231 std::vector<size_t> strides(ndim,1);
232 for (int i = int(ndim-2); i >=0 ; i--) {
233 strides[i] = strides[i+1]*fShapeInput[i+1];
234 }
235
236 out << SP << "{\n"; // define operator scope
237 out << SP << "size_t iOut = 0;\n";
238 std::string MSP = SP;
239 for (size_t idim = 0; idim < ndim; idim++) {
240 out << MSP << "for (size_t i" << idim << " = " << fStart[idim] << "; i" << idim << " < " << fEnd[idim]
241 << "; i" << idim << "+= " << fSteps[idim] << ") {\n";
242 MSP += SP;
243 if (idim < ndim-1) out << MSP << "size_t stride" << idim << " = " << strides[idim] << "*i" << idim << ";\n";
244 }
245 out << MSP << "size_t iInput = ";
246 for (size_t idim = 0; idim < ndim-1; idim++) out << " stride" << idim << " + ";
247 // here should be step size ?
248 out << "i" << ndim-1 << ";\n";
249 out << MSP << "tensor_" << fNOutput << "[iOut++] = tensor_" <<fNData << "[iInput];\n";
250 for (size_t idim = 0; idim < ndim; idim++) {
251 MSP = MSP.replace(0,SP.length(),"");
252 out << MSP << "}\n";
253 }
254 out << SP << "}\n"; // end operator scope
255
256 return out.str();
257 }
258
259};
260
261}//SOFIE
262}//Experimental
263}//TMVA
264
265
266#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:227
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:192
bool IsInitializedTensor(const std::string &name) const
Definition RModel.cxx:202
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:288
std::vector< std::vector< IType > > fAttributes
std::vector< std::vector< size_t > > ShapeInference(std::vector< std::vector< size_t > > input) override
std::vector< ETensorType > TypeInference(std::vector< ETensorType > input) override
ROperator_Slice(std::string nameData, std::vector< IType > starts, std::vector< IType > ends, std::vector< IType > axes, std::string nameOutput)
std::string Generate(std::string OpName) override
ROperator_Slice(std::string nameData, std::vector< std::string > names, std::string nameOutput)
std::vector< std::string_view > fInputTensorNames
Definition ROperator.hxx:46
bool fIsOutputConstant
flag to identify if operator has a constant output (no need to generate code)
Definition ROperator.hxx:44
const std::string SP
space used to correctly indent the generated C++ code
Definition ROperator.hxx:42
std::vector< std::string_view > fOutputTensorNames
Definition ROperator.hxx:47
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