Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ROperator_Softmax.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_ROPERATOR_Softmax
2#define TMVA_SOFIE_ROPERATOR_Softmax
3
5#include "TMVA/ROperator.hxx"
6#include "TMVA/RModel.hxx"
7
8#include <sstream>
9
10namespace TMVA {
11namespace Experimental {
12namespace SOFIE {
13
14// implement Softmax and LogSoftmax
15class ROperator_Softmax final : public ROperator {
16
17private:
18 bool fLogSoftmax; // for the logsoftmax case
19 bool fUseVDT = false;
20 int64_t fAttrAxis;
21
22 std::string fNX;
23 std::string fNY;
24 std::vector<Dim> fShape;
25
26 std::string fType;
27
28public:
30 ROperator_Softmax(int64_t attr_axis, std::string nameX, std::string nameY, bool logSoftmax = false)
31 : fLogSoftmax(logSoftmax),
32 fAttrAxis(attr_axis), fNX(UTILITY::Clean_name(nameX)), fNY(UTILITY::Clean_name(nameY))
33
34 {
37 }
38
39 void Initialize(RModel& model) override {
40 if (model.CheckIfTensorAlreadyExist(fNX) ==
41 false) { // input must be a graph input, or already initialized intermediate tensor
42 throw std::runtime_error("TMVA SOFIE Softmax Op Input Tensor is not found in model");
43 }
44 fShape = model.GetDimTensorShape(fNX);
45 model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShape);
46 fType = ConvertTypeToString(model.GetTensorType(fNX));
47 if (model.Verbose()) {
48 std::cout << "Softmax -> " << fNY << " " << ConvertDimShapeToString(fShape) << std::endl;
49 }
50 fUseVDT = model.UseVDT();
51 if (fUseVDT) {
52 model.AddNeededCustomHeader("vdt/exp.h");
53 if (fLogSoftmax)
54 model.AddNeededCustomHeader("vdt/log.h");
55 }
56 }
57
58 std::string Generate(std::string opName) override {
59 opName = "op_" + opName;
60 if (fShape.empty()) {
61 throw std::runtime_error("TMVA SOFIE Operator Softmax called to Generate without being initialized first");
62 }
63 std::stringstream out;
64 out << "///------- Softmax " << opName << " ---> " // << fNY << " "
65 << ConvertDimShapeToString(fShape) << "\n" << std::endl;
66 size_t size = fShape.size();
67 auto length_str = ConvertDimShapeToLength(fShape);
68 size_t axis = fAttrAxis < 0 ? size + fAttrAxis : fAttrAxis;
69
70 std::string expFunction = (fUseVDT) ? "vdt::fast_expf" : "std::exp";
71 std::string logFunction = (fUseVDT) ? "vdt::fast_logf" : "std::log";
72
73 // Check if this is the special case where memory is contiguous.
74 if (axis == size - 1) {
75 std::string axis_size = fShape[axis].GetVal();
76 std::string num_rows;
77 if (IsInteger(length_str) && IsInteger(axis_size)) {
78 num_rows = std::to_string(std::stoul(length_str) / std::stoul(axis_size));
79 } else {
80 num_rows = "(" + length_str + ") / (" + axis_size + ")";
81 }
82
83 out << SP << "//----- softmax axis is last one - " << axis << "\n";
84 out << SP << "for (int i = 0; i < " << num_rows << "; ++i) {\n";
85 out << SP << SP << "size_t offset = i * " << axis_size << ";\n";
86 out << SP << SP << fType << " const * x_ptr = &tensor_" << fNX << "[offset];\n";
87 out << SP << SP << fType << " * y_ptr = &tensor_" << fNY << "[offset];\n";
88
89 out << SP << SP << fType << " vmax = x_ptr[0];\n";
90 out << SP << SP << "for (int j = 1; j < " << axis_size << "; ++j) {\n";
91 out << SP << SP << SP << "if (x_ptr[j] > vmax) vmax = x_ptr[j];\n";
92 out << SP << SP << "}\n";
93
94 out << SP << SP << fType << " sum = 0.0;\n";
95 out << SP << SP << "for (int j = 0; j < " << axis_size << "; ++j) {\n";
96 out << SP << SP << SP << "y_ptr[j] = " << expFunction << "(x_ptr[j] - vmax);\n";
97 out << SP << SP << SP << "sum += y_ptr[j];\n";
98 out << SP << SP << "}\n";
99
100 if (fLogSoftmax) {
101 // log(softmax(x)) = (x - max) - log(sum): taking the log of exp(x - max) / sum instead
102 // would give -inf wherever exp(x - max) underflows to 0
103 out << SP << SP << fType << " log_sum = " << logFunction << "(sum);\n";
104 out << SP << SP << "for (int j = 0; j < " << axis_size << "; ++j) {\n";
105 out << SP << SP << SP << "y_ptr[j] = x_ptr[j] - vmax - log_sum;\n";
106 out << SP << SP << "}\n";
107 } else {
108 out << SP << SP << fType << " inv_sum = 1.0f / sum;\n";
109 out << SP << SP << "for (int j = 0; j < " << axis_size << "; ++j) {\n";
110 out << SP << SP << SP << "y_ptr[j] *= inv_sum;\n";
111 out << SP << SP << "}\n";
112 }
113 out << SP << "}\n";
114
115 } else {
116 // generic case for any axis
118 size_t k = 0;
119 std::vector<std::string> l(size);
120 for (size_t i = 0; i < size; i++) {
121 if (i != axis) {
122 for (size_t j = 0; j < k; j++) out << SP;
123 l[i] = std::string("i") + std::to_string(i);
124 out << SP << "for (int " << l[i] << " = 0; " << l[i] << " < " << fShape[i] << "; " << l[i] << "++) {\n";
125 k++;
126 }
127 }
128 for (size_t j = 0; j < size-1; j++) out << SP;
129 out << fType << " sum = 0.;\n";
130 for (size_t j = 0; j < size-1; j++) out << SP;
131 out << "size_t index = ";
132 bool first = true;
133 for (size_t i = 0; i < size; i++) {
134 if (i == axis) continue;
135 if (!first) out << " + ";
136 if (stride[i].GetVal() != "1")
137 out << stride[i] << "*";
138 out << l[i];
139 first = false;
140 }
141 out << ";\n";
142 // find maximum looping along reduced axis
143 for (size_t j = 0; j < size-1; j++) out << SP;
144 out << fType << " vmax = tensor_" << fNX << "[index];\n";
145 for (size_t j = 0; j < size-1; j++) out << SP;
146 out << "for (int i = 1; i < " << fShape[axis] << "; i++) {\n";
147 for (size_t j = 0; j < size; j++) out << SP;
148 out << fType << " x = tensor_" << fNX << "[index + i";
149 if (stride[axis].GetVal() != "1") out << "*(" << stride[axis] << ")";
150 out << "];\n";
151 for (size_t j = 0; j < size; j++) out << SP;
152 out << "if (x > vmax) vmax = x;\n";
153 for (size_t j = 0; j < size-1; j++) out << SP;
154 out << "}\n";
155 // compute softmax
156 for (size_t j = 0; j < size-1; j++) out << SP;
157 out << "for (int i = 0; i < " << fShape[axis] << "; i++) {\n";
158 for (size_t j = 0; j < size; j++) out << SP;
159 out << "size_t id = index + i";
160 if (stride[axis].GetVal() != "1") out << "*(" << stride[axis] << ")";
161 out << ";\n";
162 for (size_t j = 0; j < size; j++) out << SP;
163 out << "tensor_" << fNY << "[id] = " << expFunction << "(tensor_" << fNX << "[id] - vmax);\n";
164 for (size_t j = 0; j < size; j++) out << SP;
165 out << "sum += tensor_" << fNY << "[id];\n";
166 for (size_t j = 0; j < size-1; j++) out << SP;
167 out << "}\n";
168 if (fLogSoftmax) {
169 // log(softmax(x)) = (x - max) - log(sum), see the last-axis case above
170 for (size_t j = 0; j < size - 1; j++)
171 out << SP;
172 out << fType << " log_sum = " << logFunction << "(sum);\n";
173 }
174 // normalize
175 for (size_t j = 0; j < size-1; j++) out << SP;
176 out << "for (int i = 0; i < " << fShape[axis] << "; i++) {\n";
177 for (size_t j = 0; j < size; j++) out << SP;
178 out << "size_t id = index + i";
179 if (stride[axis].GetVal() != "1") out << "*(" << stride[axis] << ")";
180 out << ";\n";
181 for (size_t j = 0; j < size; j++) out << SP;
182 if (fLogSoftmax)
183 out << "tensor_" << fNY << "[id] = tensor_" << fNX << "[id] - vmax - log_sum;\n";
184 else
185 out << "tensor_" << fNY << "[id] /= sum;\n";
186 for (size_t j = 0; j < size-1; j++) out << SP;
187 out << "}\n";
188 //end loops
189 for (int i = static_cast<int>(k) - 1; i >= 0; i--) {
190 for (int j = 0; j < i; j++) out << SP;
191 out << "}\n";
192 }
193 }
194 return out.str();
195 }
196 std::vector<std::string> GetStdLibs() override { return { std::string("cmath") }; }
197};
198
199} // namespace SOFIE
200} // namespace Experimental
201} // namespace TMVA
202
203#endif // TMVA_SOFIE_ROPERATOR_Softmax
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
std::vector< std::string > GetStdLibs() override
std::string Generate(std::string opName) override
ROperator_Softmax(int64_t attr_axis, std::string nameX, std::string nameY, bool logSoftmax=false)
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
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::string ConvertTypeToString(ETensorType type)
std::string ConvertDimShapeToLength(const std::vector< Dim > &shape)
bool IsInteger(const std::string &s)
create variable transformations
TLine l
Definition textangle.C:4