Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ROperator_Conv.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_ROPERATOR_CONV
2#define TMVA_SOFIE_ROPERATOR_CONV
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
15namespace TMVA {
16namespace Experimental {
17namespace SOFIE {
18
19template<typename T>
21{
22private:
23 bool fBroadcastBias = false;
24
25 std::string fAttrAutopad;
26 std::vector<size_t> fAttrDilations;
27 size_t fAttrGroup;
28 std::vector<size_t> fAttrKernelShape;
29 std::vector<size_t> fAttrPads;
30 std::vector<size_t> fAttrStrides;
31
32 std::string fNX;
33 std::string fNW;
34 std::string fNB;
35 std::string fNY;
36
37 std::string convK;
38 std::string imcol;
39
40 std::vector<Dim> fShapeX;
41 std::vector<size_t> fShapeW;
42 std::vector<size_t> fShapeB;
43 std::vector<Dim> fShapeY;
44
45 std::string fType;
46
47 size_t fDim; // dimension of the convolution
48
49
50public:
51
53
54 ROperator_Conv(std::string autopad, std::vector<size_t> dilations,
55 size_t group, std::vector<size_t> kernelShape, std::vector<size_t> pads,
56 std::vector<size_t> strides, std::string nameX, std::string nameW,
57 std::string nameB, std::string nameY):
59 fAttrPads(pads), fAttrStrides(strides),
60 fNX(UTILITY::Clean_name(nameX)), fNW(UTILITY::Clean_name(nameW)),
61 fNB(UTILITY::Clean_name(nameB)), fNY(UTILITY::Clean_name(nameY))
62 {
63 if(std::is_same<T, float>::value) {
64 fType = "float";
65 } else {
66 throw
67 std::runtime_error("TMVA SOFIE Encountered unsupported type parsing a Conv operator");
68 }
71 }
72
73 ROperator_Conv(std::string autopad, std::vector<size_t> dilations,
74 size_t group, std::vector<size_t> kernelShape, std::vector<size_t> pads,
75 std::vector<size_t> strides, std::string nameX, std::string nameW,
76 std::string nameY):
78 fAttrPads(pads), fAttrStrides(strides),
79 fNX(UTILITY::Clean_name(nameX)), fNW(UTILITY::Clean_name(nameW)), fNY(UTILITY::Clean_name(nameY))
80 {
81 if(std::is_same<T, float>::value) {
82 fType = "float";
83 } else {
84 throw
85 std::runtime_error("TMVA SOFIE Encountered unsupported type parsing a Conv operator");
86 }
89 }
90
91 // function returning output shape given input
92 std::vector<Dim> DoShapeInference(const std::vector<Dim> & input, const std::vector<size_t> & weight) {
93 // shape of convolution input has to be (according to ONNX): N x C x H x W
94 // Where N : batch size, C : input channels, H : input height, W : input width
95
96 if (input.size() -2 != fDim) {
97 throw std::runtime_error("TMVA SOFIE Conv Op Shape inference - invalid input ");
98 }
99 if (weight.size() -2 != fDim) {
100 throw std::runtime_error("TMVA SOFIE Conv Op Shape inference - invalid weights ");
101 }
102 if (fAttrGroup == 0 && input[1].isParam)
103 throw std::runtime_error("TMVA SOFIE Conv - param shapes not supported without group attr");
104 if (fAttrKernelShape.empty()) {
105 if (input[2].isParam || (fDim > 1 && input[3].isParam) || (fDim > 2 && input[4].isParam))
106 throw std::runtime_error("TMVA SOFIE Conv - param shapes not supported without kernel attr");
107 }
108
109 if (fAttrGroup == 0) {
110 fAttrGroup = input[1].dim / weight[1];
111 }
112
113 // kernel shape
114 size_t k1 = ((fAttrKernelShape.empty())? weight[2] : fAttrKernelShape[0]);
115 size_t k2 = (fDim > 1) ? ((fAttrKernelShape.empty()) ? weight[3] : fAttrKernelShape[1]) : 1;
116 size_t k3 = (fDim > 2) ? ((fAttrKernelShape.empty()) ? weight[4] : fAttrKernelShape[2]) : 1;
117
118
119 size_t i1 = (fDim > 1) ? ((fDim > 2) ? 3 : 2) : 1;
120 size_t i2 = (fDim > 2) ? 4 : 3;
121 size_t i3 = 5;
122
123 if (fAttrDilations.empty()) {
124 fAttrDilations = {1, 1, 1};
125 }
126 fAttrDilations.resize(3);
127 if (fDim < 3) {
128 fAttrDilations.resize(3, 1);
129 }
130 // Shape of the kernel
131 fAttrKernelShape = {k1 + (fAttrDilations[0] - 1) * (k1 - 1),
132 k2 + (fAttrDilations[1] - 1) * (k2 - 1),
133 k3 + (fAttrDilations[2] - 1) * (k3 - 1)};
134
135 if (fAttrStrides.empty()) {
136 fAttrStrides = {1, 1, 1};
137 }
138 if (fDim < 3)
139 fAttrStrides.resize(3, 1);
140
141 if (fAttrAutopad == "NOTSET") {
142 if (fAttrPads.empty()) {
143 fAttrPads = {1, 1, 1, 1, 1, 1};
144 }
145 } else if (fAttrAutopad == "SAME_UPPER" || fAttrAutopad == "SAME_LOWER") {
146 for (size_t d = 0; d < fDim; ++d) {
147 if (input[d + 2].isParam)
148 throw std::runtime_error(
149 "TMVA SOFIE Conv Op: SAME padding with parametric input shape is not supported");
150 }
151 // ONNX SAME padding: total_pad = max(0, (ceil(in/stride)-1)*stride + kernel - in)
152 // SAME_UPPER places extra padding at end, SAME_LOWER at beginning
153 fAttrPads.assign(6, 0);
154 for (size_t d = 0; d < fDim; ++d) {
155 size_t inSize = input[d + 2].dim;
156 size_t stride_d = fAttrStrides[d];
157 size_t outSize = (inSize + stride_d - 1) / stride_d;
158 int totalPad = std::max(0, (int)((outSize - 1) * stride_d + fAttrKernelShape[d]) - (int)inSize);
159 if (fAttrAutopad == "SAME_UPPER") {
160 fAttrPads[d] = (size_t)(totalPad / 2);
161 fAttrPads[d + fDim] = (size_t)(totalPad - totalPad / 2);
162 } else {
163 fAttrPads[d] = (size_t)(totalPad - totalPad / 2);
164 fAttrPads[d + fDim] = (size_t)(totalPad / 2);
165 }
166 }
167 } else if (fAttrAutopad != "VALID") {
168 throw
169 std::runtime_error("TMVA SOFIE Conv Op invalid fAutopad");
170 }
171 // to be sure pad is vector of size 6
172 if (fDim < 3) fAttrPads.resize(6, 0);
173
174 Dim input1 = input[2];
175 Dim input2 = (fDim > 1) ? input[3] : Dim{1};
176 Dim input3 = (fDim > 2) ? input[4] : Dim{1};
177
178 size_t pad1 = fAttrPads[0] + fAttrPads[i1];
179
180 // function to get output dimension of convolution given input
181
182 auto computeOutput = [&](Dim inputDim, size_t kernel, size_t pad, size_t stride) {
183 if (!inputDim.isParam) {
184 size_t outSize = (inputDim.dim + pad - kernel) / stride + 1;
185 return Dim{outSize};
186 } else {
187 if (stride == 1){
188 if ((pad - kernel + 1) == 0 )
189 // output is same as input
190 return inputDim;
191 else {
192 int64_t v = pad - kernel + 1;
193 std::string outStr = "(" + inputDim.param + "+" + std::to_string(v) + ")";
194 return Dim{ outStr, static_cast<size_t>(-1)};
195 }
196 } else { // general case (stride not 1)
197 int64_t v = pad - kernel;
198 std::string outStr =
199 "((" + inputDim.param + "+" + std::to_string(v) + ")/" + std::to_string(stride) + "+1)";
200 return Dim{ outStr, static_cast<size_t>(-1)};
201 }
202 }
203 throw std::runtime_error("TMVA SOFIE Conv Op - invalid values");
204 return Dim{};
205 };
206
208
209 Dim batch_size = input[0]; // first element in input tensor
210 Dim output_channels = Dim{weight[0]}; // first element in weight tensor
211
212 std::vector<Dim> ret({ batch_size, output_channels, output1 });
213
214 if (fDim == 1)
215 return ret;
216
217 size_t pad2 = fAttrPads[1] + fAttrPads[i2];
219
220 // output is N x M x OH x OW
221 ret.push_back(output2);
222 if (fDim == 2)
223 return ret;
224
225 size_t pad3 = fAttrPads[2] + fAttrPads[i3];
227
228 // output is N x M x OH x OW x OD
229 ret.push_back(output3);
230 return ret;
231 }
232
233 void Initialize(RModel& model) override {
234 if (!model.CheckIfTensorAlreadyExist(fNX)) {
235 throw
236 std::runtime_error("TMVA SOFIE Conv op Input Tensor " + fNX + " is not found in model");
237 }
238 fShapeX = model.GetDimTensorShape(fNX);
239 if (fShapeX.size() < 3 || fShapeX.size() > 5) {
240 std::cout << fNX << " : " << ConvertDimShapeToString(fShapeX) << std::endl;
241 throw
242 std::runtime_error("TMVA SOFIE Conv Op input data tensor" + fNX + " is not of 3,4 or 5 dimensions");
243 }
244 fDim = fShapeX.size() - 2;
245 if (!model.CheckIfTensorAlreadyExist(fNW)) {
246 throw
247 std::runtime_error("TMVA SOFIE Conv op Input weight Tensor " + fNW + " is not found in model");
248 }
249 fShapeW = model.GetTensorShape(fNW);
250 if (fShapeW.size() < 3 || fShapeW.size() > 5) {
251 std::cout << fNW << " : " << ConvertShapeToString(fShapeW) << std::endl;
252 throw std::runtime_error("TMVA SOFIE Conv Op input weight tensor" + fNW + " is not of 3,4 or 5 dimensions");
253 }
255 model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShapeY);
256 if (fNB != "") {
257 if (!model.CheckIfTensorAlreadyExist(fNB)) {
258 throw
259 std::runtime_error("TMVA SOFIE Conv op Input Tensor " + fNB + " is not found in model");
260 }
261 fShapeB = model.GetTensorShape(fNB);
262 if (fShapeB.size() != 1)
263 throw std::runtime_error("TMVA SOFIE Conv op " + fNY + " : invalid shape for Bias tensor " + fNB + " : " +
264 ConvertShapeToString(fShapeB) + " is not 1D");
265 std::vector<Dim> targetShape(fShapeY.begin() + 1, fShapeY.end());
266 auto shapeDimB = model.GetDimTensorShape(fNB);
268 if (broadcast_needed) {
269 // make bias shape equal to Y shape by adding 1
270 if (fShapeB.size() < 1)
271 throw std::runtime_error("TMVA SOFIE Conv op: Bias Tensor has empty shape");
272 // we assume bias tensor dimension is equal to number of filters that is the second dimension in
273 // the output tensor
274 if (!(shapeDimB[0] == fShapeY[1]))
275 throw std::runtime_error("TMVA SOFIE Conv op: Bias Tensor has wrong shape: " +
277 if (fType != "float")
278 throw std::runtime_error("TMVA SOFIE Conv op: Broadcasting for non-float type tensors is not supported");
279 // here is the actual broadcasting (done in the Session constructor via GenerateInitCode)
280 fBroadcastBias = true;
281 }
282 }
283 // output channel size can be parametric and is an expression
284 std::vector<Dim> outputDims = std::vector<Dim>(fShapeY.begin()+2, fShapeY.end());
285 //check if shape is not parametric
286 std::vector<size_t> outputInts = ConvertShapeToInt(outputDims);
288 if (outputInts.empty()) {
289 auto outputChannelSize = ConvertDimShapeToLength(outputDims); // size/channel = D * H * W
290 channelDim = Dim{ outputChannelSize, static_cast<size_t>(-1)};
291 } else {
294 }
295 size_t kernelSize = fAttrKernelShape[0];
296 for (size_t i = 1; i < fDim; i++) {
298 }
299
300 std::vector<size_t> shape1 = {fShapeW[0], fShapeW[1], kernelSize};
301 std::vector<Dim> shape2 = {Dim{fShapeW[1]}, Dim{kernelSize}, channelDim };
302
303 // private workspaces of this node, named after its output, which is unique: the reshaped
304 // kernel depends on this node's weights and the im2col buffer on its attributes
305 model.AddIntermediateTensor(fNY + "_f", ConvertStringToType(fType), shape1);
306 model.AddIntermediateTensor(fNY + "_xcol", ConvertStringToType(fType), shape2);
307 convK = fNY + "_f";
308 imcol = fNY + "_xcol";
309 fOutputTensorNames.emplace_back(convK);
310 fOutputTensorNames.emplace_back(imcol);
311 fInputTensorNames.emplace_back(convK);
312 fInputTensorNames.emplace_back(imcol);
313
314 if (model.Verbose()) {
315 std::cout << "Conv - " << fDim << " " << fNX << " : " << ConvertDimShapeToString(fShapeX)
316 << " --> " << fNY << " : " << ConvertDimShapeToString(fShapeY) << std::endl;
317 }
318
319 // register the inference helper functions used by the generated code
320 if (fDim < 3)
321 model.AddNeededHelperFunction("Im2col");
322 else
323 model.AddNeededHelperFunction("Im2col_3d");
324 model.AddNeededHelperFunction("Gemm_Call");
325 if (fBroadcastBias)
326 model.AddNeededHelperFunction("UnidirectionalBroadcast");
327 }
328
329 std::string GenerateInitCode() override {
330 std::stringstream out;
331 // Generate initialization code for broadcasting of bias tensor
332 if (fBroadcastBias) {
333 // include a separate scope to avoid defining unique operator temp variables
334 std::vector<size_t> shape(fDim + 1, 1);
335 // bias (is a 1D tensor)
336 shape[0] = fShapeB[0];
337 std::vector<Dim> targetShape(fShapeY.begin() + 1, fShapeY.end());
338 out << "//--- broadcast bias tensor " << fNB << "for Conv op if needed \n";
339 // in case of dynamic tensors check needs to be done at run time
342 if (isOutDynamic)
343 out << SP << "if (" << length << " > " << ConvertShapeToLength(shape) << ") {\n";
344 else
345 out << SP << "{\n";
346 out << SP << SP << "float * data = UTILITY::UnidirectionalBroadcast(tensor_"
347 << fNB << ", " << ConvertShapeToString(shape) << ", " << ConvertDimShapeToString(fShapeY) << ");\n";
348 out << SP << SP << "fTensor_" << fNB << ".resize(" << length << ");\n";
349 out << SP << SP << "std::copy(data, data + " << length << ", fTensor_" << fNB << ".begin());\n";
350 out << SP << SP << "tensor_" << fNB << " = fTensor_" << fNB << ".data();\n";
351 out << SP << SP << "delete[] data;\n";
352 out << SP << "}\n";
353 }
354 return out.str();
355 }
356
357 std::string Generate(std::string OpName) override {
358 OpName = "op_" + OpName;
359
360 if (fShapeX.empty() || fShapeW.empty() || (fNB != "" && fShapeB.empty()) || fShapeY.empty()) {
361 throw
362 std::runtime_error("TMVA SOFIE Conv Op called to Generate without being initialized first");
363 }
364
365 std::stringstream out;
366 auto bsize = fShapeX[0];
367 size_t kDepth = (fDim > 2) ? fShapeW[2] : 1; // kernel depth
368 size_t kHeight = (fDim > 1) ? fShapeW[fDim] : 1; // kernel height
369 size_t kWidth = fShapeW[fDim+1]; // kernel width
370 auto iDepth = (fDim > 2) ? fShapeX[2] : Dim{1}; // input depth
371 auto iHeight = (fDim > 1) ? fShapeX[fDim] : Dim{1}; // input height
372 auto iWidth = fShapeX[fDim+1]; // input width
373 auto oDepth = (fDim > 2) ? fShapeY[2] : Dim{1}; // output depth
374 auto oHeight = (fDim > 1) ? fShapeY[fDim] : Dim{1}; // ouput height
375 auto oWidth = fShapeY[fDim+1]; // output width
376 // total output size for a channel
377 auto outputChannelStride = ConvertDimShapeToLength(std::vector<Dim>{oDepth, oHeight, oWidth}); // size of channel = D * H * W
378 auto outputBatchStride = ConvertDimShapeToLength(std::vector<Dim>{fShapeY[1] , oDepth, oHeight, oWidth}); // size of C * D * H * W
379 // input size
381 auto inputBatchStride = ConvertDimShapeToLength(std::vector<Dim>{fShapeX[1] , iDepth, iHeight, iWidth}); // size of C * D * H * W
382
383 out << "\n//---- operator Conv " << OpName << "\n";
384
385 // vectorize the (dilated)convolution kernels into a matrix
386 // no need to transpose the matrix
387 // to fix for 1d and 3d
388
389 size_t id = (fDim > 2) ? fDim-3 : 2;
390 size_t ih = (fDim > 1) ? fDim-2 : 1;
391 size_t iw = fDim-1;
392
393 size_t wstrideDil = fAttrDilations[iw];
394 size_t hstride = kWidth;
395 size_t hstrideDil = fAttrDilations[ih] * fAttrKernelShape[iw]; // stride dilated in the height
396 size_t dstride = kHeight * kWidth;
398 size_t icstride = kHeight * kWidth * kDepth;
400 size_t ocstride = fShapeW[1] * icstride;
401 size_t ocstrideDil = fShapeW[1] * icstrideDil;
402
403 out << SP << "for (std::size_t oc = 0; oc < " << fShapeW[0] << "; oc++) {\n";
404 out << SP << SP << "for (std::size_t ic = 0; ic < " << fShapeW[1] << "; ic++) {\n";
405 if (fDim > 2)
406 out << SP << SP << SP << "for (std::size_t kd = 0; kd < " << kDepth << "; kd++) {\n";
407 if (fDim > 1)
408 out << SP << SP << SP << "for (std::size_t kh = 0; kh < " << kHeight << "; kh++) {\n";
409 out << SP << SP << SP << SP << "for (std::size_t kw = 0; kw < " << kWidth << "; kw++) {\n";
410
411 out << SP << SP << SP << SP << SP << "tensor_" << convK << "[oc * " << ocstrideDil << " + ic * " << icstrideDil;
412 if (fDim > 2) out << " + kd * " << dstrideDil;
413 if (fDim > 1) out << " + kh * " << hstrideDil;
414 out << " + kw * " << wstrideDil << " ] = tensor_" << fNW << "[oc * " << ocstride << " + ic * " << icstride;
415 if (fDim > 2) out << " + kd * " << dstride;
416 if (fDim > 1) out << " + kh * " << hstride;
417 out << " + kw ];\n";
418
419 out << SP << SP << SP << SP << "}\n";
420 if (fDim > 1) out << SP << SP << SP << "}\n";
421 if (fDim > 2) out << SP << SP << SP << "}\n";
422 out << SP << SP << "}\n";
423 out << SP << "}\n";
424
425 // Dilation is already folded into the expanded kernel shape and the dilated tensor_<X>_f
426 // layout above, so the dense im2col below must use dilation 1 to avoid double-counting it.
427 fAttrDilations = std::vector<size_t>(3, 1);
428
429 //out << SP << "char " << OpName << "_transA = 'T';\n";
430 out << SP << "char " << OpName << "_transA = 'N';\n";
431 out << SP << "char " << OpName << "_transB = 'N';\n";
432 out << SP << "int " << OpName << "_m = " << outputChannelStride << ";\n"; // output h*w
433 assert(fShapeY[1] == fShapeW[0]);
434 //assert(fShapeW[1] == fShapeX[1] / fAttrGroup);
435 out << SP << "int " << OpName << "_n = " << fShapeW[0] << ";\n"; // output channels
436 out << SP << "int " << OpName << "_k = " << fShapeW[1] * fAttrKernelShape[0] * fAttrKernelShape[1] * fAttrKernelShape[2] << ";\n";
437 out << SP << "float " << OpName << "_alpha = 1.0;\n";
438 if (fNB != "")
439 out << SP << "float " << OpName << "_beta = 1.0;\n";
440 else // when bias is not present beta needs to be equal to zero to avoid re-using previous results in output tensor
441 out << SP << "float " << OpName << "_beta = 0.0;\n";
442
443
444 // Loop on batch size
445 out << SP << "for (size_t n = 0; n < " << bsize << "; n++) {\n";
446
447 // IM2COL: Unroll the input tensor
448 // order input data as (e.g. kernel 2x2) and (xa,ya) is channel 1 and (xb,yb) is channel 2
449 // (xa1,..,xak,ya1,..yak)(xb1,...,xbk,yb1,..,ybk)
450 // (xa2,...xak+1,ya1,...yak)(......)
451 // trick for speed is using caffe im2col and output a matrix which contains filtered values as rows.
452 // By doing this one has consecutive memory reads and writes
453 // Resulting matrix op_xcol is (input channels * filter_h * filter_w , output_h * output_w)
454 // fAttrPads holds the begin pads in [0, fDim) and the end pads in [fDim, 2 * fDim),
455 // which is the layout Im2col expects. They may differ: ONNX allows it through the
456 // "pads" attribute, and SAME_UPPER / SAME_LOWER produce it whenever the total
457 // padding along an axis is odd (an even kernel size).
458 if (fDim == 1) {
459 // the 1d case is emitted as a 2d one of height 1, for which stride_h is 1
460 fAttrStrides[1] = 1;
461 }
462 out << SP << SP << "size_t out_offset = n * " << outputBatchStride << ";\n";
463
464 if (fAttrGroup == 1) {
465 out << SP << SP << "size_t x_offset = n * " << inputBatchStride << ";\n";
466 // when using im2col - resulting matrix is transposed, the dimension is (input_c * filter_h * filter_y, output_h *
467 // output_w)
468 if (fDim < 3) {
469 out << SP << SP << "UTILITY::Im2col<float>(tensor_" << fNX
470 << " + x_offset,"
471 // channels, height, width, kernel_h, kernel_w, pad_h_begin, pad_h_end, pad_w_begin,
472 // pad_w_end, stride_h, stride_w, dilation_h, dilation_w,
473 //
474 << fShapeW[1] << "," << iHeight << "," << iWidth << ",";
475 if (fDim == 1)
476 out << "1, " << fAttrKernelShape[0] << ",0,0," << fAttrPads[0] << "," << fAttrPads[1] << ",1,"
477 << fAttrStrides[0] << ",1," << fAttrDilations[0];
478 else // dim ==2
479 out << fAttrKernelShape[0] << "," << fAttrKernelShape[1] << "," << fAttrPads[0] << ","
480 << fAttrPads[2] << "," << fAttrPads[1] << "," << fAttrPads[3]
481 << "," << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrDilations[0] << ","
482 << fAttrDilations[1];
483 out << "," << "tensor_" << imcol << ");\n\n ";
484 } else {
485 // 3d im2col
486 out << SP << SP << "UTILITY::Im2col_3d<float>(tensor_" << fNX
487 << " + x_offset,"
488 // channels, d, h, w, k_d, k_h, k_w, pad_d_begin, pad_d_end, pad_h_begin, pad_h_end,
489 // pad_w_begin, pad_w_end, stride_d, stride_h, stride_w, dilation_d, dilation_h, dilation_w,
490 //
491 << fShapeW[1] << "," << iDepth << "," << iHeight << "," << iWidth << "," << fAttrKernelShape[0] << ","
492 << fAttrKernelShape[1] << "," << fAttrKernelShape[2] << "," << fAttrPads[0] << "," << fAttrPads[3]
493 << "," << fAttrPads[1] << "," << fAttrPads[4] << "," << fAttrPads[2] << "," << fAttrPads[5] << ","
494 << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrStrides[2] << "," << fAttrDilations[0]
495 << "," << fAttrDilations[1] << "," << fAttrDilations[2] << ","
496 << "tensor_" << imcol << ");\n\n ";
497 }
498 // BLAS
499 out << SP << "Gemm_Call("
500 << "tensor_" << fNY << " + out_offset, false, false, " << OpName << "_m, " << OpName << "_n, " << OpName
501 << "_k, " << OpName << "_alpha, " << "tensor_" << imcol << ", tensor_" << convK << ", " << OpName
502 << "_beta, ";
503 if (fNB != "")
504 out << "tensor_" << fNB;
505 else
506 out << "nullptr";
507 out << ");\n";
508
509 // out << SP << SP << "BLAS::sgemm_(&" << OpName << "_transA, &" << OpName << "_transB, &" << OpName << "_m, &"
510 // << OpName << "_n, &" << OpName << "_k, &" << OpName << "_alpha, " << "tensor_" << imcol << ", &" <<
511 // OpName << "_m,\n"; // use m if op_xcol is not transpose , otherwise k
512 // out << SP << SP << SP << "tensor_" << convK << ", &" << OpName << "_k, &" << OpName << "_beta, tensor_" <<
513 // fNY << " + out_offset, &" << OpName << "_m);\n";
514 } else {
515 // case of group convolution
516 // Unroll (IM2COL) the input tensor- make loop on groups and repeat operations (IM2COL + GEMM for each
517 // group)
518 // out << SP << SP << "size_t out_offset = n * " << fShapeY[1] * oDepth * oHeight * oWidth << ";\n";
519 out << SP << SP << "for (size_t g = 0; g < " << fAttrGroup << "; g++) {\n";
520 out << SP << SP << "size_t x_offset = n * " << inputBatchStride << " + g * "
521 << fShapeW[1] << " * " << inputChannelStride << ";\n ";
522 out << SP << SP << "size_t g_offset = g * " << fShapeW[0] << " * (" << outputChannelStride << ") / " << fAttrGroup << ";\n ";
523 out << SP << SP << "size_t out_offset = n * " << outputBatchStride << " + g_offset;\n";
524
525 if (fDim < 3) {
526 out << SP << SP << "UTILITY::Im2col<float>(tensor_" << fNX
527 << " + x_offset,"
528 // channels, height, width, kernel_h, kernel_w, pad_h_begin, pad_h_end, pad_w_begin,
529 // pad_w_end, stride_h, stride_w, dilation_h, dilation_w,
530 //
531 << fShapeW[1] << "," << iHeight << "," << iWidth << ",";
532 if (fDim == 1)
533 out << "1, " << fAttrKernelShape[0] << ",0,0," << fAttrPads[0] << "," << fAttrPads[1] << ",1,"
534 << fAttrStrides[0] << ",1," << fAttrDilations[0];
535 else // dim ==2
536 out << fAttrKernelShape[0] << "," << fAttrKernelShape[1] << "," << fAttrPads[0] << ","
537 << fAttrPads[2] << "," << fAttrPads[1] << "," << fAttrPads[3]
538 << "," << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrDilations[0] << ","
539 << fAttrDilations[1];
540 out << ", tensor_" << imcol << ");\n\n ";
541 } else {
542 // 3d im2col
543 out << SP << SP << "UTILITY::Im2col_3d<float>(tensor_" << fNX
544 << " + x_offset,"
545 // channels, d, h, w, k_d, k_h, k_w, pad_d_begin, pad_d_end, pad_h_begin, pad_h_end,
546 // pad_w_begin, pad_w_end, stride_d, stride_h, stride_w, dilation_d, dilation_h, dilation_w,
547 //
548 << fShapeW[1] << "," << iDepth << "," << iHeight << "," << iWidth << "," << fAttrKernelShape[0] << ","
549 << fAttrKernelShape[1] << "," << fAttrKernelShape[2] << "," << fAttrPads[0] << "," << fAttrPads[3]
550 << "," << fAttrPads[1] << "," << fAttrPads[4] << "," << fAttrPads[2] << "," << fAttrPads[5] << ","
551 << fAttrStrides[0] << "," << fAttrStrides[1] << "," << fAttrStrides[2] << "," << fAttrDilations[0]
552 << "," << fAttrDilations[1] << "," << fAttrDilations[2] << ",tensor_" << imcol << ");\n\n ";
553 }
554
555 // BLAS
556 // n must be divided by the number of groups
557 out << SP << SP << SP << OpName << "_n = " << fShapeW[0] / fAttrGroup << ";\n";
558 // offset g must be g * k * n
559 out << SP << SP << SP << "size_t offset_f = g * "
561 << ";\n";
562
563 out << SP << "Gemm_Call("
564 << "tensor_" << fNY << " + out_offset, false, false, " << OpName << "_m, " << OpName << "_n, " << OpName
565 << "_k, " << OpName << "_alpha, " << "tensor_" << imcol << ", tensor_" << convK << " + offset_f, "
566 << OpName << "_beta, ";
567 if (fNB != "")
568 out << "tensor_" << fNB << " + g_offset";
569 else
570 out << "nullptr";
571 out << ");\n";
572
573 // out << SP << SP << "BLAS::sgemm_(&" << OpName << "_transA, &" << OpName << "_transB, &" << OpName << "_m, &"
574 // << OpName << "_n, &" << OpName << "_k, &" << OpName << "_alpha, tensor_" << imcol << ", &" << OpName
575 // << "_m,\n"; // use m if op_xcol is not transpose , otherwise k
576 // out << SP << SP << SP << "tensor_" << convK << " + offset_f, &" << OpName << "_k, &" << OpName << "_beta,
577 // tensor_" << fNY
578 // << " + out_offset"
579 // << ", &" << OpName << "_m);\n";
580
581 out << SP << SP << "}\n"; // end of group loop
582 }
583
584 // if (fNB != "") {
585 // out << SP << "int " << OpName << "_size = " << outputBatchStride << ";\n";
586 // out << SP << "float " << OpName << "_gamma = 1.0;\n";
587 // out << SP << "int " << OpName << "_incx = 1;\n";
588 // out << SP << "int " << OpName << "_incy = 1;\n";
589
590 // out << SP << "BLAS::saxpy_(&" << OpName << "_size, &" << OpName << "_gamma, tensor_" << fNB << ", &"
591 // << OpName << "_incx, tensor_" << fNY << " + out_offset, &" << OpName << "_incy);\n";
592
593 // }
594 out << SP << "}\n"; // end of batch size loop
595
596 return out.str();
597 }
598
599 /*! \brief Returns the blas routines needed to compile the generated code
600 */
601 std::vector<std::string> GetBlasRoutines() override { return { std::string("Gemm"), std::string("Axpy") }; }
602};
603
604} // namespace SOFIE
605} // namespace Experimental
606} // namespace TMVA
607
608#endif
#define d(i)
Definition RSha256.hxx:102
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 length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize id
std::string Generate(std::string OpName) override
ROperator_Conv(std::string autopad, std::vector< size_t > dilations, size_t group, std::vector< size_t > kernelShape, std::vector< size_t > pads, std::vector< size_t > strides, std::string nameX, std::string nameW, std::string nameB, std::string nameY)
std::vector< std::string > GetBlasRoutines() override
Returns the blas routines needed to compile the generated code.
void Initialize(RModel &model) override
ROperator_Conv(std::string autopad, std::vector< size_t > dilations, size_t group, std::vector< size_t > kernelShape, std::vector< size_t > pads, std::vector< size_t > strides, std::string nameX, std::string nameW, std::string nameY)
std::vector< Dim > DoShapeInference(const std::vector< Dim > &input, const std::vector< size_t > &weight)
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
bool AreSameShape(const std::vector< size_t > &, const std::vector< size_t > &)
std::string ConvertDimShapeToString(const std::vector< Dim > &shape)
std::size_t ConvertShapeToLength(const std::vector< size_t > &shape)
std::vector< size_t > ConvertShapeToInt(const std::vector< Dim > &shape)
Convert shape based on Dim to integer format.
ETensorType ConvertStringToType(std::string type)
std::string ConvertDimShapeToLength(const std::vector< Dim > &shape)
std::string ConvertShapeToString(const std::vector< size_t > &shape)
create variable transformations