Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ROperator_Gemm.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_ROPERATOR_GEMM
2#define TMVA_SOFIE_ROPERATOR_GEMM
3
4
6#include "TMVA/ROperator.hxx"
7#include "TMVA/RModel.hxx"
8
9#include <sstream>
10#include <algorithm>
11#include <iterator>
12#include <iomanip>
13#include <limits>
14#include <cassert>
15
16namespace TMVA{
17namespace Experimental{
18namespace SOFIE{
19
20
21 template <typename T>
23 {
24
25 private:
26 bool fIsDynamic = false;
27 bool fBroadcastBias = false;
28 bool fCheckBiasShapeAtRuntime = false; // flag to identify the need to do a run time check of bias shape compatibility in case of dynamic shapes and uni-directional broadcasting
29 bool fBiasBroadcastAssumed = false; // Initialize assumed a broadcast: the integer shape of Y was unknown
30
31 float fAttrAlpha = 1.0;
32 float fAttrBeta = 1.0;
35
36 std::string fNA;
37 std::string fNB;
38 std::string fNC = "";
39 std::string fNY;
40 std::string fType;
42 std::vector<Dim> fShapeA;
43 std::vector<Dim> fShapeB;
44 std::vector<size_t> fShapeC;
45 std::vector<Dim> fDimShapeC;
46 std::vector<Dim> fShapeY;
47 RModel * fModel = nullptr;
48
49 public:
50
52 ROperator_Gemm(float alpha, float beta, int_t transA, int_t transB, std::string nameA, std::string nameB, std::string nameY, EActivationType activation=EActivationType::UNDEFINED):
53 fAttrAlpha(alpha), fAttrBeta(beta), fAttrTransA(transA), fAttrTransB(transB), fNA(UTILITY::Clean_name(nameA)),
54 fNB(UTILITY::Clean_name(nameB)), fNY(UTILITY::Clean_name(nameY))
55 {
57 fType = "float";
58 static_assert(std::is_same_v<T, float>,
59 "TMVA::SOFIE - Unsupported type parsing a Gemm operator");
62 }
63
64 ROperator_Gemm(float alpha, float beta, int_t transA, int_t transB, std::string nameA, std::string nameB, std::string nameC, std::string nameY, EActivationType activation=EActivationType::UNDEFINED):
65 fAttrAlpha(alpha), fAttrBeta(beta), fAttrTransA(transA), fAttrTransB(transB), fNA(UTILITY::Clean_name(nameA)),
66 fNB(UTILITY::Clean_name(nameB)), fNC(UTILITY::Clean_name(nameC)), fNY(UTILITY::Clean_name(nameY)), fActivation(activation)
67 {
69 fType = "float";
70
73 }
74
75 std::vector<ETensorType> TypeInference(std::vector<ETensorType> input) override {
76 ETensorType out = input[0];
77 return {out};
78 }
79
80 template <typename U>
81 std::vector<U> DoShapeInference(const std::vector<std::vector<U>> & input){
82 if (input.size() > 3) throw std::runtime_error("TMVA SOFIE Gemm Op Shape Inference only need 2 or 3 input tensor");
83 // accept tensor with input dimensions > 2
84 // example: A = (d1,d2,...,N1,N2) B = (d1,d2,...,N2,N3) --> Y = (d1,d2,..,N1,N3)
85 for (auto& i: input){
86 if (i.size() < 2){
87 throw std::runtime_error("TMVA SOFIE Gemm Op Shape Inference only accept input tensor with >=2 dimensions");
88 }
89 }
90
91 // when there are 3 inputs shape of Y is the one of C
92 if (input.size() == 3){
93 //shape of C is shape of Y
94 return input[2];
95 }
96 // ioffset cannot be less than 2
97 int ioffset = input[0].size()-2; // in case of tensors with dim > 2
98
99 std::vector<U> s_a(input[0].begin() + ioffset, input[0].begin() + ioffset + 2);
100 std::vector<U> s_b(input[1].begin() + ioffset, input[1].begin() + ioffset + 2);
101 // reverse in case of transpose
102 if (fAttrTransA){
103 std::reverse(s_a.begin(), s_a.end());
104 }
105 if (fAttrTransB){
106 std::reverse(s_b.begin(), s_b.end());
107 }
108 std::vector<U> s_y;
109 s_y.reserve(input[0].size());
110 if (input[0].size() > 2 && input[1].size() == input[0].size()) {
111 // in case of dim > 2 first dimensions are equal to the input ones not
112 // equal to 1 (e.g. (1,2,3) * (2,3,4) -> (2,2,4))
113 // here could probably use the Broadcasting function UTILITY::MultidirectionalBroadcastShape
114 for (size_t i = 0; i < input[0].size()-2; i++) {
115 Dim valueA = input[0][i];
116 Dim valueB = input[1][i];
117 if (valueA.GetVal() != valueB.GetVal()) {
118 if (valueB.GetVal() == "1")
119 s_y.push_back(input[0][i]);
120 else if (valueA.GetVal() == "1")
121 s_y.push_back(input[1][i]);
122 else if (!valueA.isParam && !valueB.isParam)
123 throw std::runtime_error("TMVA SOFIE Gemm Op - invalid input shapes " + valueA.GetVal() + " and "
124 + valueB.GetVal());
125 else if (valueA.isParam && valueB.isParam){
126 // check which parameter is first in RModel list
127 auto & dimNames = fModel->GetDimShapeNames();
128 auto p1 = std::find(dimNames.begin(), dimNames.end(), valueA.param);
129 auto p2 = std::find(dimNames.begin(), dimNames.end(), valueB.param);
130 if (p1 < p2) s_y.push_back(input[0][i]);
131 else s_y.push_back(input[1][i]);
132 }
133 else if (!valueA.isParam)
134 s_y.push_back(input[0][i]);
135 else if (!valueB.isParam)
136 s_y.push_back(input[1][i]);
137 else
138 throw std::runtime_error("TMVA SOFIE Gemm Op - invalid input shapes " + valueA.GetVal() + " and "
139 + valueB.GetVal());
140 }
141 else
142 s_y.push_back(input[0][i]);
143 }
144 }
145
146 s_y.push_back(s_a[0]);
147 s_y.push_back(s_b[1]);
148 return s_y;
149 }
150
151 std::vector<std::vector<size_t>> ShapeInference(std::vector<std::vector<size_t>> input) override {
152 std::vector<std::vector<size_t>> ret;
154 return ret;
155 }
156 std::vector<Dim> DynamicShapeInference(const std::vector<std::vector<Dim>> & input){
158 }
159
160
161
162 void Initialize(RModel& model) override {
163 //TODO: propagate A or B as specified by ONNX standard
164 fModel = &model;
165
166 if ((model.CheckIfTensorAlreadyExist(fNA) == false) || (model.CheckIfTensorAlreadyExist(fNB) == false) ){ //input must be a graph input, or already initialized intermediate tensor
167 throw std::runtime_error("TMVA SOFIE Gemm Op Input Tensor " + fNA + " or " + fNB + " is not found in model");
168 }
169 if (fNC != ""){
170 if (model.CheckIfTensorAlreadyExist(fNC) == false){ //input must be a graph input, or already initialized intermediate tensor
171 throw std::runtime_error("TMVA SOFIE Gemm Op Input Tensor " + fNC + " is not found in model");
172 }
173 }
174 if (model.IsDynamicTensor(fNA) || model.IsDimInputTensor(fNA) ) {
175 fShapeA = model.GetDynamicTensorShape(fNA);
176 fIsDynamic = true;
177 } else {
178 auto shapeA_int = model.GetTensorShape(fNA);
180 }
181 // case A is of dim1 we prepend a 1 but we need to remove later
182 bool prependOne = false;
183 if (fShapeA.size() == 1) {
184 fShapeA.insert(fShapeA.begin(), Dim(1));
185 prependOne = true;
186 }
187
188 if (model.IsDynamicTensor(fNB) || model.IsDimInputTensor(fNB)) {
189 fShapeB = model.GetDynamicTensorShape(fNB);
190 fIsDynamic = true;
191 }
192 else {
193 auto shapeB_int = model.GetTensorShape(fNB);
195 }
196 // case B is dim1 we append a 1 but we need to remove later
197 bool appendOne = false;
198 if (fShapeB.size() == 1) {
199 fShapeB.insert(fShapeB.end(), Dim(1));
200 appendOne = true;
201 }
202 // assume if not shape is 2 that extra values are 1.
203 // implement also MatMul case where we stack matrices (see numpy.matmul)
204 if (fShapeA.size() != fShapeB.size()) {
205 // if different dimensions we prepend 1 values
206 if (fShapeA.size() < fShapeB.size()) {
207 fShapeA.insert(fShapeA.begin(), fShapeB.size()-fShapeA.size(), Dim(1));
208 } else if (fShapeB.size() < fShapeA.size()) {
209 fShapeB.insert(fShapeB.begin(), fShapeA.size()-fShapeB.size(), Dim(1));
210 }
211 }
212
214 std::vector<size_t> shapeY = ConvertShapeToInt(fShapeY);
215
216 // bias is normally not dynamic (not support it for time being)
217 if (fNC != ""){
218 if (model.IsDynamicTensor(fNC))
219 fDimShapeC = model.GetDynamicTensorShape(fNC);
220 else {
221 fShapeC = model.GetTensorShape(fNC);
223 }
224 // for dynamic outputs broadcasting is always needed
225 bool broadcast_needed = false;
226 if (fIsDynamic && shapeY.empty()) {
227 broadcast_needed = true;
229 } else
230 // consider broadcasting also if they have different length
232
233
234 if (broadcast_needed) {
235 fBroadcastBias = true;
236 // check if broadcasting is compatible and note that prepend 1 to shapeC
238 // return flag must not have bit equal to 2 since this is a unidirectional broadcast of C->Y
239 //
240 if ((r.first & 2) == 2) {
241 throw std::runtime_error("TMVA SOFIE Gemm Op - bias tensor of shape " + ConvertDimShapeToString(fDimShapeC) + " cannot be uni-directional broadcasted to " + ConvertDimShapeToString(fShapeY));
242 } else if (r.first == 4) {
243 // we need to do a run time check of bias shape if it is compatible
245 }
247 }
248 }
249
250 // remove appended or prepended value of 1 in Y
251 if (prependOne) {
252 if (fIsDynamic)
253 fShapeY.erase(fShapeY.begin());
254 else
255 shapeY.erase(shapeY.begin());
256 }
257 if (appendOne) {
258 if (fIsDynamic)
259 fShapeY.erase(fShapeY.end()-1);
260 else
261 shapeY.erase(shapeY.end()-1);
262 }
263
264 // Constant-fold Gemm/MatMul when A, B (and C) are all initializers, following the
265 // ROperator_BasicBinary pattern (compute now, skip Generate() entirely). Only full
266 // constant folding is handled; propagating just A or B (see the TODO above) would
267 // need a different mechanism than fIsOutputConstant's all-or-nothing fold.
268 bool canFold = !fIsDynamic
269 && model.IsInitializedTensor(fNA)
270 && model.IsInitializedTensor(fNB)
271 && (fNC.empty() || model.IsInitializedTensor(fNC))
272 && fShapeA.size() <= 2 // exclude stacked/batched MatMul
273 && !fBroadcastBias // exclude bias requiring run-time broadcast
275
276 if (canFold) {
279 size_t dimA = shapeA_i.size();
280 size_t dimB = shapeB_i.size();
281 size_t m = fAttrTransA ? shapeA_i[dimA - 1] : shapeA_i[dimA - 2];
282 size_t k = fAttrTransA ? shapeA_i[dimA - 2] : shapeA_i[dimA - 1];
283 size_t n = fAttrTransB ? shapeB_i[dimB - 2] : shapeB_i[dimB - 1];
284
285 auto dataA = static_cast<T *>(model.GetInitializedTensorData(fNA).get());
286 auto dataB = static_cast<T *>(model.GetInitializedTensorData(fNB).get());
287
288 // plain host-side 2D matrix multiply: Y = alpha * op(A) * op(B)
289 std::vector<T> dataY(m * n, T(0));
290 for (size_t i = 0; i < m; i++) {
291 for (size_t j = 0; j < n; j++) {
292 T sum{};
293 for (size_t p = 0; p < k; p++) {
294 T aVal = fAttrTransA ? dataA[p * m + i] : dataA[i * k + p];
295 T bVal = fAttrTransB ? dataB[j * k + p] : dataB[p * n + j];
296 sum += aVal * bVal;
297 }
298 dataY[i * n + j] = static_cast<T>(fAttrAlpha) * sum;
299 }
300 }
301 // Y += beta * C (fBroadcastBias is false here, so C already matches Y's length)
302 if (!fNC.empty()) {
303 auto dataC = static_cast<T *>(model.GetInitializedTensorData(fNC).get());
304 for (size_t idx = 0; idx < dataY.size(); idx++)
305 dataY[idx] += static_cast<T>(fAttrBeta) * dataC[idx];
306 }
307 // fuse ReLU now since Generate() will be skipped entirely for a constant output
309 for (auto &v : dataY)
310 v = std::max(v, T(0));
311 }
312
313 model.AddConstantTensor<T>(fNY, shapeY, dataY.data());
314 // flag the operand tensors to not be written in the generated code or weight file
315 model.SetNotWritableInitializedTensor(fNA);
316 model.SetNotWritableInitializedTensor(fNB);
317 if (!fNC.empty())
318 model.SetNotWritableInitializedTensor(fNC);
319 fIsOutputConstant = true;
320
321 if (model.Verbose()) {
322 std::cout << "Gemm (or MatMul) " << fNA << " , " << fNB;
323 if (!fNC.empty())
324 std::cout << " , " << fNC;
325 std::cout << " ---> " << fNY << " (constant) " << ConvertShapeToString(shapeY) << std::endl;
326 }
327 return;
328 }
329
330 if (!fIsDynamic)
331 model.AddIntermediateTensor(fNY, model.GetTensorType(fNA), shapeY);
332 else
333 model.AddDynamicTensor(fNY, model.GetTensorType(fNA), fShapeY);
334
335 if (model.Verbose()){
336 std::cout << "Gemm (or MatMul) " << " ---> " << fNY << " shape ";
337 if (fIsDynamic)
338 std::cout << ConvertDimShapeToString(fShapeY) << std::endl;
339 else
340 std::cout << ConvertShapeToString(shapeY) << std::endl;
341 }
342
343 model.AddNeededStdLib("algorithm");
344
345 // register the inference helper functions used by the generated code
346 if (fType == "float")
347 model.AddNeededHelperFunction("Gemm_Call");
348 // bias handling emits Copy / Fill, fused activation emits Relu
349 if (fNC != "") {
350 model.AddNeededHelperFunction("Copy");
351 model.AddNeededHelperFunction("Fill");
352 }
354 model.AddNeededHelperFunction("Relu");
355 }
356
357 std::string Generate(std::string opName) override {
359 return ""; // no op for constant tensors
360
361 opName = "op_" + opName;
362
363 // if (fShapeA.empty() || fShapeB.empty() || fShapeY.empty() || (fNC != "" && fShapeC.empty())) {
364 // throw std::runtime_error("TMVA SOFIE Gemm Op called to Generate without being initialized first");
365 // }
366 std::stringstream out;
367 out << "\n//--------- Gemm " << opName << " " << ConvertDimShapeToString(fShapeA) << " * " << ConvertDimShapeToString(fShapeB)
368 << " -> " << ConvertDimShapeToString(fShapeY) << "\n";
369 // need to consider case A and B have dim > 2 (for MatMul)
370 int64_t dimA = fShapeA.size();
371 int64_t dimB = fShapeB.size();
372 int64_t dimY = fShapeY.size();
373 int64_t dimC = fDimShapeC.size();
374 if (dimA != dimB || dimA != dimY || (fBroadcastBias && dimC != dimY)) {
375 std::cout << " shape A " << ConvertDimShapeToString(fShapeA)
376 << " shape B " << ConvertDimShapeToString(fShapeB)
377 << " shape C " << ConvertDimShapeToString(fDimShapeC)
378 << " shape Y " << ConvertDimShapeToString(fShapeY) << std::endl;
379 throw std::runtime_error("TMVA SOFIE Gemm(MatMul) has invalid shape for inputs or output");
380 }
381 auto m = (fAttrTransA ? fShapeA[dimA-1].GetVal() : fShapeA[dimA-2].GetVal());
382 auto n = (fAttrTransB ? fShapeB[dimB-2].GetVal() : fShapeB[dimB-1].GetVal());
383 auto k = (fAttrTransA ? fShapeA[dimA-2].GetVal() : fShapeA[dimA-1].GetVal());
384 // size of A: if (transposeA) is m*k else k*m
385 // size of B n*k
386 std::vector<Dim> sY = {fShapeY[dimY-2], fShapeY[dimY-1]};
387 // extra dimensions in case of stacked MatMul
388 std::vector<Dim> sExtraY;
389 for (int64_t i = 0; i < dimY-2; i++) {
390 sExtraY.push_back(fShapeY[i]);
391 }
392 auto lengthGemm = ConvertDimShapeToLength(sY); // size of the Gemm operation
393 auto lengthExtra_Y = ConvertDimShapeToLength(sExtraY); // extra length in case input tensors are of dim>2 (MatMul)
394 std::string lengthExtra_C;
395 std::vector<Dim> sExtraC;
396 std::vector<Dim> sC;
397 bool haveExtraC = false;
398 if (dimC > 2) {
399 sC = {fDimShapeC[dimC-2], fDimShapeC[dimC-1]};
400 for (int64_t i = 0; i < dimC-2; i++) {
401 sExtraC.push_back(fDimShapeC[i]);
402 }
404 if (lengthExtra_C != "1") haveExtraC = true;
405 } else if (dimC > 0) {
406 for (int64_t i = 0; i < dimC; i++) {
407 sC.push_back(fDimShapeC[i]);
408 }
409 }
410
411 // case bias is present
412 if (!fNC.empty()){
413 // when the 2 last dims of bias and Y are not compatible we need to perform a run time broadcast
414 if (sC != sY)
415 fBroadcastBias = true;
417 // C has exactly the shape of Y, nothing to broadcast. Only revisit the
418 // assumption Initialize had to make while the shape of Y was still unknown:
419 // a bias it did compare and found to need broadcasting keeps it.
420 fBroadcastBias = false;
421 if (!fBroadcastBias) {
422 // add a check in case broadcasting was not needed or done outside of session
423 // C should have smaller dimension of Y
424 if (!fIsDynamic) {
425 if ((std::stoi(lengthGemm) != std::stoi(ConvertDimShapeToLength(sC))) ||
426 (haveExtraC && std::stoi(lengthExtra_Y) != std::stoi(lengthExtra_C)))
427 throw std::runtime_error("TMVA SOFIE Gemm Op " + opName + " Bias tensor " + fNC +
428 " has not correct size " + ConvertShapeToString(fShapeC) +
429 " output length " + lengthGemm);
430 } else {
431 // add a dynamic check (C should not be a dynamic tensor)
432 out << SP << "assert(" << lengthGemm << " == " << ConvertDimShapeToLength(sC) << ");\n";
433 if (haveExtraC)
434 out << SP << "assert(" << lengthExtra_Y << " == " << lengthExtra_C << ");\n";
435 }
436 }
437 } else {
438 fBroadcastBias = false;
439 //in this case fAttrBeta needs to be equal to zero otherwise second time we run we will use
440 // the previous result
441 if (fAttrBeta != 0) {
442 // some model don't have bias but Beta is not zero - force it to zero
443 fAttrBeta = 0;
444 std::cout << "WARNING: TMVA SOFIE Gemm Op " + opName + " Bias tensor is not present but beta value in Gemm is not zero - force it to zero\n";
445 }
446 }
447
448 // include MatMul case where we stack the Gemm operations
449 // exclude case where we have only 1's in the additional dims
450 bool doStackMul = dimY > 2 && ( fIsDynamic || std::stoi(lengthExtra_Y) > 1);
451 // compute input offset for stack multiplications
452 std::string lengthExtra_A;
453 std::string lengthExtra_B;
454 std::string increment_A;
455 std::string increment_B;
456
457 if (doStackMul) {
458 std::vector<Dim> sA(fShapeA.begin(), fShapeA.begin()+dimA-2);
459 std::vector<Dim> sB(fShapeB.begin(), fShapeB.begin()+dimB-2);
460 std::vector<Dim> mA = {fShapeA[dimA-2], fShapeA[dimA-1]};
461 std::vector<Dim> mB = {fShapeB[dimB-2], fShapeB[dimB-1]};
464 // if A ( b, m, k) and B (b, k, n) these are the strides of A and B ( m*k for A and n*k for B )
467 }
468 bool extraA = (doStackMul && lengthExtra_A != "1");
469 bool extraB = (doStackMul && lengthExtra_B != "1");
471 // run time check for bias broadcasting
472 std::string biasShapeType = opName + "_biasShapeType";
474 // create a flag according to bias shape:
475 // = 1 for (1,Y2)
476 // = 2 for (Y1,1)
477 // = 3 for a scalar
478 out << SP << "int " << biasShapeType << " = 0;\n";
479 // case vector of columns
480 if (sC[0].GetVal() != "1" && sC[1].GetVal() != sY[1].GetVal())
481 out << SP << "if (" << sC[0] << " == 1 && " << sC[1] << " == " << sY[1] << ")\n";
482 else if (sC[0].GetVal() == "1")
483 out << SP << "if (" << sC[1] << " == " << sY[1] << ")\n";
484 else if (sC[1].GetVal() == sY[1].GetVal())
485 out << SP << "if (" << sC[0] << " == 1)\n";
486
487 out << SP << SP << biasShapeType << " = 1;\n";
488
489 // case vector of rows
490 if (sC[1].GetVal() != "1" && sC[0].GetVal() != sY[0].GetVal())
491 out << SP << "else if (" << sC[1] << " == 1 && " << sC[0] << " == " << sY[0] << ")\n";
492 else if (sC[1].GetVal() == "1")
493 out << SP << "else if (" << sC[0] << " == " << sY[0] << ")\n";
494 else if (sC[0].GetVal() == sY[0].GetVal())
495 out << SP << "else if (" << sC[1] << " == 1)\n";
496
497 out << SP << SP << biasShapeType << " = 2;\n";
498
499 // case scalar
500 if (sC[0].GetVal() != "1" && sC[1].GetVal() != "1")
501 out << SP << "else if (" << sC[0] << " == 1 && " << sC[1] << " == 1 )\n";
502 else if (sC[0].GetVal() == "1")
503 out << SP << "else if (" << sC[1] << " == 1)\n";
504 else if (sC[1].GetVal() == "1")
505 out << SP << "else if (" << sC[0] << " == 1)\n";
506 out << SP << SP << biasShapeType << " = 3;\n";
507 out << SP << "else\n";
508 out << SP << SP << "throw std::runtime_error(\"TMVA SOFIE Gemm Op - bias tensor "
509 << ConvertDimShapeToString(fDimShapeC) << " cannot be broadcasted to "
510 << ConvertDimShapeToString(fShapeY) << "\");\n";
511 }
512 auto SP2 = SP;
513 if (doStackMul) {
514 out << SP << "size_t " << opName << "_y_offset = 0;\n"; // needed if we stack the gemm operations
515 if (extraA)
516 out << SP << "size_t " << opName << "_A_offset = 0;\n";
517 if (extraB)
518 out << SP << "size_t " << opName << "_B_offset = 0;\n";
519 if (extraC)
520 out << SP << "size_t " << opName << "_C_offset = 0;\n";
521 out << SP << "for (size_t i = 0; i < " << lengthExtra_Y << "; i++){\n";
522 SP2 += SP;
523 }
524 // do the bias broadcasting at run time by
525 // initializing output Y vector with bias values
526 if (fBroadcastBias) {
527
528 fAttrBeta = 1.;
529
530 // loop on first output dimension
531 out << SP2 << "for (size_t j = 0; j < " << sY[0] << "; j++) { \n";
532 out << SP2 << SP << "size_t y_index = ";
533 if (doStackMul) // add offset in case of stack multiplications (not sure if bias is present in these cases)
534 out << opName << "_y_offset + ";
535 if (sY[1].GetVal() != "1")
536 out << sY[1] << " * j;\n";
537 else
538 out << "j;\n";
539
540 std::string prefix = SP2 + SP;
541 std::string target = "tensor_" + fNY;
542 if (sC.size() != 2) {
543 throw std::runtime_error("TMVA SOFIE Gemm Op - invalid rank for bias tensor " + ConvertDimShapeToString(fDimShapeC) + ConvertDimShapeToString(sC));
544 } if (sC[0].GetVal() == "1" && sC[1].GetVal() == sY[1].GetVal()) {
545 out << prefix << "Copy(" << target << " + y_index, tensor_" << fNC << ", " << sY[1] << ");\n";
546 } else if (sC[1].GetVal() == "1" && sC[0].GetVal() == sY[0].GetVal()) {
547 out << prefix << "Fill(" << target << " + y_index, tensor_" << fNC << "[j], " << sY[1] << ");\n";
548 } else if (sC[0].GetVal() == "1" && sC[1].GetVal() == "1") {
549 // scalar case
550 out << prefix << "Fill(" << target << " + y_index, tensor_" << fNC << "[0], " << sY[1] << ");\n";
551 } else if (fCheckBiasShapeAtRuntime) {
552 // in the generic dynamic case we check at run time that bias is compatible
553 // we check that bias[0] = 1 or equal to SY[0] and that bias[1] = 1 or equal to SY[1]
554 // tbd: this run-time check coul;d be moved outside the loop for better run time efficiency
555 out << SP2 << SP << "if (" << biasShapeType << " == 1)\n"; // case vector of columns
556 out << SP << prefix << "Copy(" << target << " + y_index, tensor_" << fNC << ", " << sY[1] << ");\n";
557 out << SP2 << SP << "else if (" << biasShapeType << " == 2)\n"; // case vector of rows
558 out << SP << prefix << "Fill(" << target << " + y_index, tensor_" << fNC << "[j], " << sY[1] << ");\n";
559 out << SP2 << SP << "else \n"; // scalar case
560 out << SP << prefix << "Fill(" << target << " + y_index, tensor_" << fNC << "[0], " << sY[1] << ");\n";
561 } else {
562 throw std::runtime_error("TMVA SOFIE Gemm Op - invalid shape for bias tensor " + ConvertDimShapeToString(fDimShapeC));
563 }
564
565 out << SP2 << "}\n";
566 }
567
568 if (fType == "float"){
569
570 out << SP2 << "Gemm_Call(" << "tensor_" << fNY;
571 if (doStackMul) out << " + " << opName << "_y_offset";
572 out << ", "
573 << (fAttrTransB ? "true, " : "false, ")
574 << (fAttrTransA ? "true, " : "false, ")
575 << n << ", " << m << ", " << k << ", ";
576 out << std::setprecision(std::numeric_limits<float>::max_digits10) << fAttrAlpha << ", tensor_" << fNB;
577 if (extraB) out << " + " << opName << "_B_offset";
578 out << ", tensor_" << fNA;
579 if (extraA) out << " + " << opName << "_A_offset";
580 out << ", " << std::setprecision(std::numeric_limits<float>::max_digits10) << fAttrBeta << ",";
581 // in the case of bias and no broadcasting needed - I need to add bias as an extra tensor in Gemm call
582 if (!fNC.empty() && !fBroadcastBias) {
583 out << "tensor_" << fNC;
584 if (extraC) {
585 out << " + " << opName << "_C_offset";
586 }
587 } else {
588 out << "nullptr";
589 }
590 out << ");\n";
591
592 }
593
594 if (doStackMul) {
595 out << SP << SP << opName << "_y_offset += " << lengthGemm << ";\n";
596 if (lengthExtra_A != "1")
597 out << SP << SP << opName << "_A_offset += " << increment_A << ";\n";
598 if (lengthExtra_B != "1")
599 out << SP << SP << opName << "_B_offset += " << increment_B << ";\n";
600 if (extraC)
601 // increment_C is lengthGEmm
602 out << SP << SP << opName << "_C_offset += " << lengthGemm << ";\n";
603 out << SP << "}\n"; // end of loop on the stacked multiplication
604 }
605
606 // fuse with Relu
608 out << SP << "//--- applying RELU to output\n";
609 std::string tnsr = "tensor_" + fNY;
611 out << SP << "Relu(" << tnsr << ", " << tnsr << ", " << reluSize << ");\n";
612 }
613
614 return out.str();
615 }
616
617 std::vector<std::string> GetBlasRoutines() override { return {"Gemm", "Gemv"}; }
618
619 };
620
621
622}//SOFIE
623}//Experimental
624}//TMVA
625
626
627#endif //TMVA_SOFIE_ROPERATOR_GEMM
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.
winID h TVirtualViewer3D TVirtualGLPainter p
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 Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t target
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 r
const_iterator begin() const
const_iterator end() const
const std::vector< std::string > & GetDimShapeNames() const
Definition RModel.hxx:226
ROperator_Gemm(float alpha, float beta, int_t transA, int_t transB, std::string nameA, std::string nameB, std::string nameC, std::string nameY, EActivationType activation=EActivationType::UNDEFINED)
std::vector< Dim > DynamicShapeInference(const std::vector< std::vector< Dim > > &input)
std::vector< ETensorType > TypeInference(std::vector< ETensorType > input) override
ROperator_Gemm(float alpha, float beta, int_t transA, int_t transB, std::string nameA, std::string nameB, std::string nameY, EActivationType activation=EActivationType::UNDEFINED)
std::vector< std::vector< size_t > > ShapeInference(std::vector< std::vector< size_t > > input) override
std::vector< U > DoShapeInference(const std::vector< std::vector< U > > &input)
std::string Generate(std::string opName) override
void Initialize(RModel &model) override
std::vector< std::string > GetBlasRoutines() override
std::vector< std::string_view > fInputTensorNames
Definition ROperator.hxx:47
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:48
const Int_t n
Definition legend1.C:16
std::vector< size_t > MultidirectionalBroadcastShape(std::vector< std::vector< size_t > >)
std::string ConvertDimShapeToString(const std::vector< Dim > &shape)
std::vector< Dim > ConvertShapeToDim(const std::vector< size_t > &shape)
Convert shape from integer format to dynamic one (based on Dim)
std::vector< size_t > ConvertShapeToInt(const std::vector< Dim > &shape)
Convert shape based on Dim to integer format.
std::string ConvertDimShapeToLength(const std::vector< Dim > &shape)
std::string ConvertShapeToString(const std::vector< size_t > &shape)
create variable transformations
TMarker m
Definition textangle.C:8
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335