Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ROperator_Reduce.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_ROPERATOR_Reduce
2#define TMVA_SOFIE_ROPERATOR_Reduce
3
5#include "TMVA/ROperator.hxx"
6#include "TMVA/RModel.hxx"
7
8#include <memory>
9#include <sstream>
10#include <algorithm>
11#include <stdexcept>
12#include <vector>
13#include <cassert>
14#include <limits>
15
16namespace TMVA{
17namespace Experimental{
18namespace SOFIE{
19
29
30template <EReduceOpMode Op>
31class ROperator_Reduce final : public ROperator
32{
33private:
34 /* Attributes*/
35 bool fInputDimShape = false;
36 int fkeepdims = 1; //default value
37 std::vector<int64_t> fAttrAxes;
39 std::string fNX;
40 std::string fNAxes;
41 std::string fNY;
42 std::vector<Dim> fShapeX;
43 std::vector<Dim> fShapeY;
44 std::vector<Dim> fShapeYNotPruned; // needed for fKeepdims=0
45 std::string fType; // type of the tensors (needed by ReduceMax/ReduceMin)
46
47 public:
48 std::string Name()
49 {
51 return "ReduceMean";
53 return "ReduceSumSquare";
54 else if (fReduceOpMode == ReduceProd)
55 return "ReduceProd";
56 else if (fReduceOpMode == ReduceSum)
57 return "ReduceSum";
58 else if (fReduceOpMode == ReduceMax)
59 return "ReduceMax";
60 else if (fReduceOpMode == ReduceMin)
61 return "ReduceMin";
62 return "Invalid";
63 }
64
66 ROperator_Reduce(int keepdims, std::vector<int64_t> attrAxes, std::string nameX, std::string nameAxes, std::string nameY):
67 fkeepdims(keepdims), fAttrAxes(attrAxes), fNX(UTILITY::Clean_name(nameX)), fNAxes(UTILITY::Clean_name(nameAxes)), fNY(UTILITY::Clean_name(nameY)) {
68 fReduceOpMode = Op;
69
71 if(!fNAxes.empty()){
72 fInputTensorNames.emplace_back(fNAxes);
73 }
74
76 }
77
78 // shape of output tensors given input tensors
79 std::vector<Dim> DoShapeInference(const std::vector<Dim> & input) {
80 auto ret = input; //suggest copy to compiler
81 auto & outputShape = ret;
82 for (size_t j = 0; j < fAttrAxes.size(); j++) {
83 if (fAttrAxes[j] < 0) fAttrAxes[j] += outputShape.size();
84 if (fAttrAxes[j] < 0 || (size_t) fAttrAxes[j] >= outputShape.size() )
85 throw std::runtime_error("TMVA SOFIE Reduce Op - invalid axes values " + std::to_string(fAttrAxes[j]));
86 // set to 1 the reduced dims
87 outputShape[fAttrAxes[j]] = Dim{1};
88 }
89 fShapeYNotPruned = outputShape;
90 // in case of pruning dimension we need to sort axes attributes
91 if (fkeepdims == 0) {
92 auto ax = fAttrAxes;
93 std::sort(ax.begin(), ax.end());
94 for (size_t j = 0; j < ax.size(); j++) {
95 // erase reduced dimensions, but keep last one
96 if (outputShape.size() > 0) {
97 outputShape.erase(outputShape.begin() + ax[j]);
98 for (size_t k = j+1; k < ax.size(); k++)
99 ax[k] -= 1; // decrease by one since we have removed a value
100 }
101 }
102 }
103 return ret;
104 }
105 void Initialize(RModel& model) override {
106
107 if (!model.CheckIfTensorAlreadyExist(fNX)) {
108 // input must be a graph input, or already initialized intermediate tensor
109 throw std::runtime_error("TMVA SOFIE Reduce Op Input Tensor " + fNX + " is not found in model");
110 }
111 fShapeX = model.GetDimTensorShape(fNX);
112 if (model.IsDynamicTensor(fNX))
113 fInputDimShape = true;
114 // check if tensor with axes is provided
115 if (!fNAxes.empty()) {
116 auto ax_shptr = model.GetInitializedTensorData(fNAxes);
117 auto ax_ptr = static_cast<int64_t *>(ax_shptr.get());
118 auto ax_shape = model.GetTensorShape(fNAxes);
119 size_t ax_length = ConvertShapeToLength(ax_shape);
120 fAttrAxes = std::vector<int64_t>(ax_ptr, ax_ptr+ax_length);
121 } else if (fAttrAxes.empty()) {
122 // in case no axes is passed assume full reduction
123 fAttrAxes.resize(fShapeX.size());
124 for (size_t i = 0; i < fAttrAxes.size(); i++)
125 fAttrAxes[i] = i;
126 }
127 // find shape of Y and add it in the list of intermediate tensors
129 model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShapeY);
130 if (model.Verbose()){
131 std::cout << Name() << " : " << fNX << " -> " << fNY << " shape " << ConvertDimShapeToString(fShapeY) << std::endl;
132 }
133 fType = ConvertTypeToString(model.GetTensorType(fNX));
134 model.AddNeededStdLib("algorithm");
136 model.AddNeededStdLib("limits");
137 }
138
139 std::string Generate(std::string opName) override {
140 opName = "op_" + opName;
141
144
145 // output stride (or not pruned vector)
147
148 // write here according to size of shape
149 // in generation code can be done automatically
150 // i0 = i / stride0 % shape0; i1 = i / stride1 % shape1 and so on
151 // and we have for the inverse
152 // i = i0 * s0 + i1 * s1 + i2 * s2 + i3 * s3 ....
153
154 // don't need to divide by last stride s[n-1] since it is 1 by definition
155
156 std::stringstream out;
157 out << "\n//---- operator " << Name() << " " << opName << "\n";
158 // check where is reduced axes are first or last one. In these case we can do a faster implementation
159 enum EReduceDim {kFirst, kLast, kMiddle};
160 EReduceDim reduceDims = kLast;
161 int kmin = fShapeX.size()-fAttrAxes.size();
162 for (int k = fShapeX.size()-1; k >= kmin; k--) {
163 // if k is not a reduced axis is not last ones
164 if (std::find(fAttrAxes.begin(), fAttrAxes.end(), k) == fAttrAxes.end()) {
165 reduceDims = kMiddle;
166 break;
167 }
168 }
169 if (reduceDims == kMiddle) {
170 reduceDims = kFirst;
171 // check if at the beginning
172 for (size_t k = 0; k < fAttrAxes.size(); k++) {
173 // if k is not a reduced axis is not first ones
174 if (std::find(fAttrAxes.begin(), fAttrAxes.end(), k) == fAttrAxes.end()) {
175 reduceDims = kMiddle;
176 break;
177 }
178 }
179 }
180 // neutral element used to initialize the accumulator
181 std::string initValue = "0";
183 initValue = "1";
184 else if (fReduceOpMode == ReduceMax)
185 initValue = "std::numeric_limits<" + fType + ">::lowest()";
186 else if (fReduceOpMode == ReduceMin)
187 initValue = "std::numeric_limits<" + fType + ">::max()";
188
189 std::string reducedLength;
190 if (fInputDimShape) {
191 reducedLength = "reducedLength_" + opName;
192 out << SP << "size_t " << reducedLength << " = (" << inputLength << ") / (" << outputLength << ");\n";
193 } else {
194 int rLength = std::stoi(inputLength) / std::stoi(outputLength);
195 reducedLength = std::to_string(rLength);
196 }
197 if (reduceDims == kLast) {
198 //std::cout << "reduction for operator " << opName << " is last" << std::endl;
199 // new faster implementation using a single loop
200 // faster to loop first on reduced dimension and then output
201 // reset output tensors
202
203 // loop on output dimensions
204 out << SP << "for (size_t i = 0; i < " << outputLength << "; i++) {\n";
205 // loop on reduce dimensions
206 out << SP << SP << "tensor_" << fNY << "[i] = " << initValue << ";\n";
207 out << SP << SP << "for (size_t j = 0; j < " << reducedLength << "; j++) {\n";
208
210 out << SP << SP << SP << "tensor_" << fNY << "[i] = std::max(tensor_" << fNY << "[i], tensor_" << fNX
211 << "[i * " << reducedLength << " + j]);\n";
212 else if (fReduceOpMode == ReduceMin)
213 out << SP << SP << SP << "tensor_" << fNY << "[i] = std::min(tensor_" << fNY << "[i], tensor_" << fNX
214 << "[i * " << reducedLength << " + j]);\n";
215 else if (fReduceOpMode == ReduceProd)
216 out << SP << SP << SP << "tensor_" << fNY << "[i] *= tensor_" << fNX << "[i * " << reducedLength << " + j];\n";
218 out << SP << SP << SP << "tensor_" << fNY << "[i] += tensor_" << fNX << "[i * " << reducedLength << " + j];\n";
220 out << SP << SP << SP << "tensor_" << fNY << "[i] += tensor_" << fNX << "[i * " << reducedLength << " + j] * tensor_"
221 << fNX << "[i * " << reducedLength << " + j];\n";
222 out << SP << SP << "}\n"; // end j loop
224 out << SP << SP << "tensor_" << fNY << "[i] /= static_cast<float>(" << reducedLength << ");\n";
225
226 out << SP << "}\n"; // end i loop
227 } else if (reduceDims == kFirst) {
228 //std::cout << "reduction for operator " << opName << " is first" << std::endl;
229 // case reduction is at beginning
230 // reset output tensors
231 out << SP << "std::fill(tensor_" << fNY << ", tensor_" << fNY << " + " << outputLength << ", " << initValue
232 << ");\n";
233
234 out << SP << "for (size_t i = 0; i < " << reducedLength << "; i++) {\n";
235 out << SP << SP << "for (size_t j = 0; j < " << outputLength << "; j++) {\n";
236
238 out << SP << SP << SP << "tensor_" << fNY << "[j] = std::max(tensor_" << fNY << "[j], tensor_" << fNX
239 << "[i * " << outputLength << " + j]);\n";
240 else if (fReduceOpMode == ReduceMin)
241 out << SP << SP << SP << "tensor_" << fNY << "[j] = std::min(tensor_" << fNY << "[j], tensor_" << fNX
242 << "[i * " << outputLength << " + j]);\n";
243 else if (fReduceOpMode == ReduceProd)
244 out << SP << SP << SP << "tensor_" << fNY << "[j] *= tensor_" << fNX << "[i * " << outputLength << " + j];\n";
246 out << SP << SP << SP << "tensor_" << fNY << "[j] += tensor_" << fNX << "[i * " << outputLength << " + j];\n";
248 out << SP << SP << SP << "tensor_" << fNY << "[j] += tensor_" << fNX << "[i * " << outputLength << " + j] * tensor_"
249 << fNX << "[i * " << outputLength << " + j];\n";
250 out << SP << SP << "}\n"; // end j loop
251 out << SP << "}\n"; // end i loop
253 out << SP << "for (size_t j = 0; j < " << outputLength << "; j++) {\n";
254 out << SP << SP << "tensor_" << fNY << "[j] /= static_cast<float>(" << reducedLength << ");\n";
255 out << SP << "}\n"; // end j loop
256 }
257 }
258 else
259 { // standard case
260 //std::cout << "reduction for operator " << opName << " is middle" << std::endl;
261 // reset output tensors
262 out << SP << "std::fill(tensor_" << fNY << ", tensor_" << fNY << " + " << outputLength << ", " << initValue
263 << ");\n";
264
265 size_t dim = fShapeX.size(); // this is the input dimension (e.g. 2, 3 or 4 or more)
266
267 // Loop over the input in memory order with one nested loop per axis. Recovering the
268 // indices instead from a single flat loop would need a division and a modulo per
269 // element, and with dynamic shapes those are real integer divisions (the divisors are
270 // not known at compile time). Here the input index is just a running counter and the
271 // output index is accumulated one axis at a time, so the inner loop is division-free.
272 auto indent = [&](size_t n) {
273 for (size_t q = 0; q < n; q++)
274 out << SP;
275 };
276 // scope the loop counters, they are declared outside of the loop nest
277 out << SP << "{\n";
278 out << SP << SP << "size_t inputIndex = 0;\n";
279 std::string outputIndex = "0"; // output index accumulated so far
280 for (size_t k = 0; k < dim; k++) {
281 indent(k + 2);
282 out << "for (size_t i_" << k << " = 0; i_" << k << " < (" << fShapeX[k] << "); i_" << k << "++) {\n";
283 if (std::find(fAttrAxes.begin(), fAttrAxes.end(), k) == fAttrAxes.end()) {
284 // not a reduced axis: it contributes to the output index
285 std::string next = "outputIndex_" + std::to_string(k);
286 indent(k + 3);
287 out << "size_t " << next << " = " << outputIndex << " + i_" << k << " * (" << outputStrides[k] << ");\n";
288 outputIndex = next;
289 }
290 }
291 // now compute reduction
292 indent(dim + 2);
293 out << "// compute reduction....\n";
294 std::string y = "tensor_" + fNY + "[" + outputIndex + "]";
295 std::string x = "tensor_" + fNX + "[inputIndex]";
296 indent(dim + 2);
298 out << y << " = std::max(" << y << ", " << x << ");\n";
299 else if (fReduceOpMode == ReduceMin)
300 out << y << " = std::min(" << y << ", " << x << ");\n";
301 else if (fReduceOpMode == ReduceProd)
302 out << y << " *= " << x << ";\n";
304 out << y << " += " << x << ";\n";
305 else if (fReduceOpMode == ReduceSumSquare)
306 out << y << " += " << x << " * " << x << ";\n";
307 indent(dim + 2);
308 out << "inputIndex++;\n";
309 for (size_t k = dim; k > 0; k--) {
310 indent(k + 1);
311 out << "}\n";
312 }
313 out << SP << "}\n"; // end loop on input elements
314 // normalize for reduced mean
315 if (fReduceOpMode == ReduceMean) {
316 out << SP << "for (size_t i = 0; i < " << outputLength << "; i++) {\n";
317 out << SP << SP << "tensor_" << fNY << "[i] /= static_cast<float>(" << reducedLength << ");\n";
318 out << SP << "}\n";
319 }
320 }
321
322 return out.str();
323 }
324
325};
326
327}//SOFIE
328}//Experimental
329}//TMVA
330
331
332#endif //TMVA_SOFIE_ROPERATOR_Reduce
333
static void indent(ostringstream &buf, int indent_level)
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
float * q
std::string Generate(std::string opName) override
ROperator_Reduce(int keepdims, std::vector< int64_t > attrAxes, std::string nameX, std::string nameAxes, std::string nameY)
std::vector< Dim > DoShapeInference(const std::vector< Dim > &input)
std::vector< std::string_view > fInputTensorNames
Definition ROperator.hxx:44
const std::string SP
space used to correctly indent the generated C++ code
Definition ROperator.hxx:40
std::vector< std::string_view > fOutputTensorNames
Definition ROperator.hxx:45
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
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 ConvertDimShapeToString(const std::vector< Dim > &shape)
std::size_t ConvertShapeToLength(const std::vector< size_t > &shape)
std::string ConvertTypeToString(ETensorType type)
std::string ConvertDimShapeToLength(const std::vector< Dim > &shape)
create variable transformations