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