-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathROperator_LayerNormalization.hxx
More file actions
360 lines (322 loc) · 14.8 KB
/
ROperator_LayerNormalization.hxx
File metadata and controls
360 lines (322 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#ifndef TMVA_SOFIE_ROPERATOR_LAYERNORMALIZATION
#define TMVA_SOFIE_ROPERATOR_LAYERNORMALIZATION
#include "TMVA/RModel.hxx"
#include "TMVA/SOFIE_common.hxx"
#include <sstream>
#include <string>
namespace TMVA {
namespace Experimental {
namespace SOFIE {
template <typename T>
class ROperator_LayerNormalization : public ROperator {
private:
int fAttrAxis;
float fAttrEpsilon;
size_t fAttrStashType;
std::string fNX;
std::string fNScale;
std::string fNB;
std::string fNY;
std::string fNMean;
std::string fNInvStdDev;
std::string fNCastedX;
std::string fNNormalizedX;
std::string fNBroadcastedB;
std::vector<Dim> fShapeX;
std::vector<Dim> fShapeScale;
std::vector<size_t> fShapeB; // shape of input Bias (B) is assumed to be fully defined
std::vector<Dim> fShapeY;
std::vector<Dim> fShapeMean;
std::vector<Dim> fShapeInvStdDev;
size_t fAxis; // axis in [0, size)
size_t fSize; // Size of the input
// size_t fAxisDim;
std::vector<Dim> fNormalizedShape;
std::vector<Dim> fAxesShape;
// lengths in string format
std::string fLength; // Length of the input
std::string fNormalizedLength;
std::string fAxesLength;
std::string fType;
public:
ROperator_LayerNormalization() {}
ROperator_LayerNormalization(int axis, float epsilon, size_t stashType, const std::string &nameX,
const std::string &nameScale, const std::string &nameB, const std::string &nameY,
const std::string &nameMean, const std::string &nameInvStdDev)
: fAttrAxis(axis), fAttrEpsilon(epsilon), fAttrStashType(stashType), fNX(UTILITY::Clean_name(nameX)),
fNScale(UTILITY::Clean_name(nameScale)), fNB(UTILITY::Clean_name(nameB)),
fNY(UTILITY::Clean_name(nameY)), fNMean(UTILITY::Clean_name(nameMean)), fNInvStdDev(UTILITY::Clean_name(nameInvStdDev))
{
fKind = OperatorKind::LAYERNORM;
fInputTensorNames = { fNX, fNScale };
if (!fNB.empty()){
fInputTensorNames.emplace_back(fNB);
}
fOutputTensorNames = { fNY };
if (!fNMean.empty()){
fOutputTensorNames.emplace_back(fNMean);
}
if (!fNInvStdDev.empty()){
fOutputTensorNames.emplace_back(fNInvStdDev);
}
}
std::vector<std::vector<size_t>> ShapeInference(std::vector<std::vector<size_t>> input) override { return input; }
std::vector<ETensorType> TypeInference(std::vector<ETensorType> input) override { return input; }
void Initialize(RModel& model) override {
if (!model.CheckIfTensorAlreadyExist(fNX)) {
throw std::runtime_error("TMVA::SOFIE - Tensor " + fNX + " not found.");
}
bool isDynamic = model.IsDynamicTensor(fNX);
fShapeX = model.GetDimTensorShape(fNX);
fShapeY = fShapeX;
model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShapeY);
// Type of the output
fType = ConvertTypeToString(model.GetTensorType(fNX));
// Size of the input
fSize = fShapeX.size();
// Axis in [0, size)
fAxis = (fAttrAxis < 0) ? fSize + fAttrAxis : fAttrAxis;
// Shape of fShapeX[0, ..., fAxis)
fAxesShape = std::vector<Dim>(fShapeX.begin(), fShapeX.begin() + fAxis);
// Length of the axes
fAxesLength = ConvertDimShapeToLength(fAxesShape);
// Shape of fShapeX[fAxis, ..., fSize)
fNormalizedShape = std::vector<Dim>(fShapeX.begin() + fAxis, fShapeX.end());
// Length of the normalized axis
fNormalizedLength = ConvertDimShapeToLength(fNormalizedShape);
// length of the input
fLength = ConvertDimShapeToLength(fShapeX);
// Type of mean and std
ETensorType type = (fAttrStashType == 1) ? ETensorType::FLOAT : model.GetTensorType(fNX);
// Mean
if (fNMean.empty()) {
fNMean = "Mean" + fNX;
// cannot use initializer list with one element since it is ambiguous
if (isDynamic)
// add size_t(-1) to indicate that shape is an expression
model.AddIntermediateTensor(fNMean, type, std::vector<Dim>(1,Dim{fAxesLength,std::size_t(-1)}));
else
model.AddIntermediateTensor(fNMean, type, std::vector<size_t>(1,std::stoi(fAxesLength)));
}
// Inverse Standard Deviation
if (fNInvStdDev.empty()) {
fNInvStdDev = "InvStdDev" + fNX;
if (isDynamic)
model.AddIntermediateTensor(fNInvStdDev, type, std::vector<Dim>(1,Dim{fAxesLength,std::size_t(-1)}));
else
model.AddIntermediateTensor(fNInvStdDev, type, std::vector<size_t>(1,std::stoi(fAxesLength)));
}
// Cast X to float
if (fAttrStashType == 1 && model.GetTensorType(fNX) != ETensorType::FLOAT) {
fNCastedX = "Casted" + fNX;
model.AddIntermediateTensor(fNCastedX, ETensorType::FLOAT, fShapeX);
fNNormalizedX = "Normalized" + fNX;
model.AddIntermediateTensor(fNNormalizedX, ETensorType::FLOAT, fShapeX);
}
// Broadcast the bias
if (!fNB.empty()) {
fShapeB = model.GetTensorShape(fNB);
size_t lengthB = ConvertShapeToLength(fShapeB);
if (isDynamic || lengthB < static_cast<size_t>(std::stoi(fLength))) {
fNBroadcastedB = "Broadcasted" + fNB;
model.AddIntermediateTensor(fNBroadcastedB, ConvertStringToType(fType), fShapeX);
}
}
model.AddNeededStdLib("cmath");
}
std::string GenerateInitCode() override
{
std::stringstream out;
if (!fNBroadcastedB.empty()) {
out << SP << "// Broadcasting the bias of LayerNormalization op\n";
out << SP << "{\n";
out << SP << SP << "float* data = TMVA::Experimental::SOFIE::UTILITY::UnidirectionalBroadcast<float>(tensor_";
out << fNB << ", " << ConvertShapeToString(fShapeB) << ", " << ConvertShapeToString(fShapeX) << ");\n";
out << SP << "std::copy(data, data + " << fLength << ", tensor_" << fNBroadcastedB << ");\n";
out << SP << "delete[] data;\n";
out << SP << "}\n";
}
return out.str();
}
std::string Generate(std::string opName) override
{
opName = "op_" + opName;
if (fShapeX.empty()) {
throw std::runtime_error("TMVA::SOFIE LayerNormalization operator " + opName +
" called to generate without being initialized first.");
}
if (fShapeX.size() > 5) {
throw std::runtime_error("TMVA::SOFIE LayerNormalization operator not "
"implemented for input tensor of size > 5.");
}
std::stringstream out;
out << "//---- Layer Normalization operator " << opName << "\n";
// Loop over all the normalized axes i.e. [axis, ..., size)
std::vector<std::string> inputShape(fSize);
for (size_t i = 0; i < fSize; i++) {
inputShape[i] = fShapeX[i].GetVal();
}
auto strides = UTILITY::ComputeStrideFromShape(fShapeX);
std::string InputIndex = "axis_0 * " + strides[0].GetVal();
for (size_t i = 1; i < fSize; i++) {
InputIndex += " + axis_" + std::to_string(i) + " * " + strides[i].GetVal();
}
auto axesStrides = UTILITY::ComputeStrideFromShape(fAxesShape);
std::string axesIndex = "axis_" + std::to_string(0) + " * " + axesStrides[0].GetVal();
for (size_t i = 1; i < fAxis; i++) {
axesIndex += " + axis_" + std::to_string(i) + " * " + axesStrides[i].GetVal();
}
auto normalizedStrides = UTILITY::ComputeStrideFromShape(fNormalizedShape);
std::string normalizedIndex = "axis_" + std::to_string(fAxis) + " * " + normalizedStrides[0].GetVal();
for (size_t i = fAxis + 1; i < fSize; i++) {
normalizedIndex += " + axis_" + std::to_string(i) + " * " + normalizedStrides[i - fAxis].GetVal();
}
if (!fNCastedX.empty()) {
// Cast X to float
out << SP << "for (size_t i = 0; i < " << fLength << "; i++) {\n";
out << SP << SP << "tensor_" << fNCastedX << "[i] = " << "static_cast<float>(tensor_" << fNX;
out << "[i]);\n";
out << SP << "}\n";
}
out << SP << "// Compute the mean\n";
// Loop over the normalized dimensions
for (size_t i = 0; i < fAxis; i++) {
std::string iIdx = "axis_" + std::to_string(i);
out << SP << "for (size_t " << iIdx << " = 0; " << iIdx << " < " << inputShape[i]
<< "; " << iIdx << "++) {\n";
}
out << SP << SP << fType << " sum = 0.;\n";
// loop over all the dims in [0, fAxis)
for (size_t j = fAxis; j < fSize; j++) {
std::string jIdx = "axis_" + std::to_string(j);
out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j]
<< "; " << jIdx << "++) {\n";
}
out << SP << SP << SP << "sum += tensor_" << fNX << "[" << InputIndex << "];\n";
for (size_t j = fAxis; j < fSize; j++) {
out << SP << SP << "}\n";
}
out << SP << SP << "tensor_" << fNMean << "[" << axesIndex << "] = sum / " << fType << "(";
out << fNormalizedLength << ");\n";
for (size_t i = fAxis; i < fSize; i++) {
out << SP << "}\n";
}
out << SP << "// Compute the inverse Standard Deviation\n";
// Loop over the normalized dimensions
for (size_t i = 0; i < fAxis; i++) {
std::string iIdx = "axis_" + std::to_string(i);
out << SP << "for (size_t " << iIdx << " = 0; " << iIdx << " < " << inputShape[i]
<< "; " << iIdx << "++){\n";
}
// Set sum = 0
out << SP << SP << fType << " sum = 0.;\n";
// loop over all the dims in [0, fAxis)
for (size_t j = fAxis; j < fSize; j++) {
std::string jIdx = "axis_" + std::to_string(j);
out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j]
<< "; " << jIdx << "++){\n";
}
out << SP << SP << SP << "float tmp = tensor_" << fNX << "[" << InputIndex << "] - tensor_"
<< fNMean << "[" << axesIndex << "];\n";
out << SP << SP << SP << "sum += tmp*tmp;\n";
for (size_t j = fAxis; j < fSize; j++) {
out << SP << SP << "}\n";
}
out << SP << SP << "tensor_" << fNInvStdDev << "[" << axesIndex << "] = 1 / std::sqrt(";
out << "sum / " << fType << "(" << fNormalizedLength << ") + " << fAttrEpsilon << ");\n";
for (size_t i = 0; i < fAxis; i++) {
out << SP << "}\n";
}
if (!fNCastedX.empty()) {
out << "// NormalizedX = InvStdDev * (CastedX - Mean)\n";
for (size_t i = 0; i < fAxis; i++) {
std::string iIdx = "axis_" + std::to_string(i);
out << SP << "for (size_t " << iIdx << " = 0; " << iIdx << " < " << inputShape[i]
<< "; " << iIdx << "++){\n";
}
for (size_t j = fAxis; j < fSize; j++) {
std::string jIdx = "axis_" + std::to_string(j);
out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j]
<< "; " << jIdx << "++){\n";
}
out << SP << SP << SP << "tensor_" << fNNormalizedX << "[" << InputIndex << "] = tensor_";
out << fNInvStdDev << "[" << axesIndex << "] * (tensor_" << fNCastedX << "[" << InputIndex;
out << "] - tensor_" << fNMean << "[" << axesIndex << "])\n";
for (size_t j = fAxis; j < fSize; j++) {
out << SP << SP << "}\n";
}
for (size_t i = fAxis; i < fSize; i++) {
out << SP << "}\n";
}
out << "// Y = Scale o NormalizedX";
for (size_t i = 0; i < fAxis; i++) {
std::string iIdx = "axis_" + std::to_string(i);
out << SP << "for (size_t " << iIdx << " = 0; " << iIdx << " < " << inputShape[i]
<< "; " << iIdx << "++){\n";
}
for (size_t j = fAxis; j < fSize; j++) {
std::string jIdx = "axis_" + std::to_string(j);
out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j]
<< "; " << jIdx << "++){\n";
}
out << SP << SP << SP << "tensor_" << fNY << "[" << InputIndex << "] = tensor_" << fNScale;
out << "[" << axesIndex << "] * static_cast<" << fType << ">(tensor_" << fNCastedX << "[" << InputIndex;
out << "]);\n";
for (size_t j = fAxis; j < fSize; j++) {
out << SP << SP << "}\n";
}
for (size_t i = fAxis; i < fSize; i++) {
out << SP << "}\n";
}
} else {
out << SP << "// Y = Scale o InvStdDev (X - Mean)\n";
for (size_t i = 0; i < fAxis; i++) {
std::string iIdx = "axis_" + std::to_string(i);
out << SP << "for (size_t " << iIdx << " = 0; " << iIdx << " < " << inputShape[i]
<< "; " << iIdx << "++){\n";
}
for (size_t j = fAxis; j < fSize; j++) {
std::string jIdx = "axis_" + std::to_string(j);
out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j]
<< "; " << jIdx << "++){\n";
}
out << SP << SP << SP << "tensor_" << fNY << "[" << InputIndex << "] = tensor_" << fNScale;
out << "[" << normalizedIndex << "] * tensor_" << fNInvStdDev << "[" << axesIndex;
out << "] * (tensor_" << fNX << "[" << InputIndex << "] - tensor_" << fNMean << "[";
out << axesIndex << "]);\n";
for (size_t j = fAxis; j < fSize; j++) {
out << SP << SP << "}\n";
}
for (size_t i = fAxis; i < fSize; i++) {
out << SP << "}\n";
}
}
if (!fNB.empty()) {
std::string bias = "tensor_" + (fNBroadcastedB.empty() ? fNB : fNBroadcastedB);
out << SP << "// Add the bias to Y\n";
out << SP << "int " << opName << "_n = " << fLength << ";\n";
out << SP << "float " << opName << "_alpha = 1.;\n";
out << SP << "int " << opName << "_inc = 1;\n";
out << SP << "BLAS::saxpy_(&" << opName << "_n, &" << opName << "_alpha, " << bias << ", &";
out << opName << "_inc, " << "tensor_" << fNY << ", &" << opName << "_inc);\n";
}
return out.str();
}
std::vector<std::string> GetBlasRoutines() override { return { std::string("Axpy") }; }
std::vector<std::string> GetStdLibs() override { return { std::string("cmath") }; }
std::string GetFusableOutputTensorName() override {
return fNY;
}
void UpdateFusableTensorName(std::string fusable_tensor_name, const std::function<void(const std::string&)>& removal_func){
removal_func(fNX);
removal_func(fNY);
fNX = fusable_tensor_name;
fNY = fusable_tensor_name;
fInputTensorNames[0] = fNX;
fOutputTensorNames[0] = fNY;
}
};
} // namespace SOFIE
} // namespace Experimental
} // namespace TMVA
#endif