Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ROperator_LayerNormalization.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_ROPERATOR_LAYERNORMALIZATION
2#define TMVA_SOFIE_ROPERATOR_LAYERNORMALIZATION
3
4#include "TMVA/RModel.hxx"
5#include "TMVA/ROperator.hxx"
7
8#include <sstream>
9#include <string>
10
11namespace TMVA {
12namespace Experimental {
13namespace SOFIE {
14
15template <typename T>
17private:
18 bool fCastToFloat = false; // flag to indicate if operation 1 are in floats (to be impl)
22
23 std::string fNX;
24 std::string fNScale;
25 std::string fNB;
26 std::string fNY;
27 std::string fNMean;
28 std::string fNInvStdDev;
29
30 std::string fNCastedX;
31 std::string fNNormalizedX;
32 std::string fNBroadcastedB;
33
34 std::vector<Dim> fShapeX;
35 std::vector<Dim> fShapeScale;
36 std::vector<Dim> fShapeB;
37 std::vector<Dim> fShapeY;
38 std::vector<Dim> fShapeMean;
39 std::vector<Dim> fShapeInvStdDev;
40
41 size_t fAxis; // axis in [0, size)
42 size_t fSize; // Size of the input
43 // size_t fAxisDim;
44
45 std::vector<Dim> fNormalizedShape; // shape from X[ axis,...,N-1]
46 std::vector<Dim> fAxesShape; // shape from X[0,..,axis-1]
47 // lengths in string format
48 std::string fLength; // Length of the input
49 std::string fNormalizedLength;
50 std::string fAxesLength;
51
52 std::string fType;
53
54public:
56
57 ROperator_LayerNormalization(int axis, float epsilon, size_t stashType, const std::string &nameX,
58 const std::string &nameScale, const std::string &nameB, const std::string &nameY,
59 const std::string &nameMean, const std::string &nameInvStdDev)
60 : fAttrAxis(axis), fAttrEpsilon(epsilon), fAttrStashType(stashType), fNX(UTILITY::Clean_name(nameX)),
61 fNScale(UTILITY::Clean_name(nameScale)), fNB(UTILITY::Clean_name(nameB)),
62 fNY(UTILITY::Clean_name(nameY)), fNMean(UTILITY::Clean_name(nameMean)), fNInvStdDev(UTILITY::Clean_name(nameInvStdDev))
63 {
65 if (!fNB.empty()){
66 fInputTensorNames.emplace_back(fNB);
67 }
68
70 if (!fNMean.empty()){
71 fOutputTensorNames.emplace_back(fNMean);
72 }
73 if (!fNInvStdDev.empty()){
74 fOutputTensorNames.emplace_back(fNInvStdDev);
75 }
76 }
77
78 void Initialize(RModel& model) override {
79 if (!model.CheckIfTensorAlreadyExist(fNX)) {
80 throw std::runtime_error("TMVA::SOFIE - LayerNormalization - Tensor " + fNX + " not found.");
81 }
82 bool isDynamic = model.IsDynamicTensor(fNX);
83 fShapeX = model.GetDimTensorShape(fNX);
85 // Type of the output
86 fType = ConvertTypeToString(model.GetTensorType(fNX));
87 // Size of the input
88 fSize = fShapeX.size();
89 // Axis must be in [-size, size)
90 const int rank = static_cast<int>(fSize);
91 if (fAttrAxis < -rank || fAttrAxis >= rank)
92 throw std::runtime_error("TMVA::SOFIE - LayerNormalization - axis " + std::to_string(fAttrAxis) +
93 " is out of range for input of rank " + std::to_string(fSize));
94 // Axis in [0, size)
95 fAxis = (fAttrAxis < 0) ? fAttrAxis + rank : fAttrAxis;
96 // Shape of fShapeX[0, ..., fAxis)
97 fAxesShape = std::vector<Dim>(fShapeX.begin(), fShapeX.begin() + fAxis);
98 // Length of the axes
100 // Shape of fShapeX[fAxis, ..., fSize)
101 fNormalizedShape = std::vector<Dim>(fShapeX.begin() + fAxis, fShapeX.end());
102 // Length of the normalized axis
104 // length of the input
106 // Type of mean and std
107 ETensorType type = (fAttrStashType == 1) ? ETensorType::FLOAT : model.GetTensorType(fNX);
108 // Mean
109 if (!fNMean.empty()) {
110 // cannot use initializer list with one element since it is ambiguous
111 if (isDynamic)
112 // add size_t(-1) to indicate that shape is an expression
113 model.AddIntermediateTensor(fNMean, type, std::vector<Dim>(1,Dim{fAxesLength,std::size_t(-1)}));
114 else
115 model.AddIntermediateTensor(fNMean, type, std::vector<size_t>(1,std::stoi(fAxesLength)));
116 }
117 // Inverse Standard Deviation
118 if (!fNInvStdDev.empty()) {
119 if (isDynamic)
120 model.AddIntermediateTensor(fNInvStdDev, type, std::vector<Dim>(1,Dim{fAxesLength,std::size_t(-1)}));
121 else
122 model.AddIntermediateTensor(fNInvStdDev, type, std::vector<size_t>(1,std::stoi(fAxesLength)));
123 }
124 // if mean and stdev are not empty they are not defined in the output list
125 // Cast X to float
126 if (fAttrStashType == 1 && model.GetTensorType(fNX) != ETensorType::FLOAT) {
127 fCastToFloat = true;
128 fType = "float";
129 }
130 // scale shape
131 fShapeScale = model.GetDimTensorShape(fNScale);
132 // appends 1 to scale shapes if missing
133 size_t dimScale = fShapeScale.size();
134 if (dimScale < fSize) {
135 for (size_t i = 0; i < fSize-dimScale; i++)
136 fShapeScale.insert(fShapeScale.begin(), Dim{1});
137 }
138 // check also shape if consistent now
139 for (size_t i = 0; i < fSize; i++) {
140 if (fShapeScale[i].dim != 1 && fShapeScale[i] != fShapeX[i])
141 throw std::runtime_error("TMVA::SOFIE - LayerNormalization - Scale Tensor has invalid shape " + ConvertDimShapeToString(fShapeScale));
142 }
143 if (!fNB.empty()) {
144 fShapeB = model.GetDimTensorShape(fNB);
145 // appends 1 to bias shapes if missing
146 size_t dimB = fShapeB.size();
147 if (dimB < fShapeX.size()) {
148 for (size_t i = 0; i < fSize-dimB; i++)
149 fShapeB.insert(fShapeB.begin(), Dim{1});
150 }
151 for (size_t i = 0; i < fSize; i++) {
152 if (fShapeB[i].dim != 1 && fShapeB[i] != fShapeX[i])
153 throw std::runtime_error("TMVA::SOFIE - LayerNormalization - Bias Tensor has invalid shape " + ConvertDimShapeToString(fShapeScale));
154 }
155 }
156
157 model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShapeY);
158 if (model.Verbose()){
159 std::cout << "LayerNormalization : " << fNX << " -> " << fNY << " shape " << ConvertDimShapeToString(fShapeY)
160 << " using bias and scale with shapes " << ConvertDimShapeToString(fShapeB) << " " << ConvertDimShapeToString(fShapeScale)
161 << std::endl;
162 }
163
164 model.AddNeededStdLib("cmath");
165
166 // the generated init code may broadcast the bias with UnidirectionalBroadcast
167 if (!fNBroadcastedB.empty())
168 model.AddNeededHelperFunction("UnidirectionalBroadcast");
169 }
170
171 std::string GenerateInitCode() override
172 {
173 std::stringstream out;
174 if (!fNBroadcastedB.empty()) {
175 out << SP << "// Broadcasting the bias of LayerNormalization op\n";
176 out << SP << "{\n";
177 out << SP << SP << "float* data = UTILITY::UnidirectionalBroadcast(tensor_";
178 out << fNB << ", " << ConvertDimShapeToString(fShapeB) << ", " << ConvertDimShapeToString(fShapeX) << ");\n";
179 out << SP << "std::copy(data, data + " << fLength << ", tensor_" << fNBroadcastedB << ");\n";
180 out << SP << "delete[] data;\n";
181 out << SP << "}\n";
182 }
183 return out.str();
184 }
185
186 std::string Generate(std::string opName) override
187 {
188 opName = "op_" + opName;
189 if (fShapeX.empty()) {
190 throw std::runtime_error("TMVA::SOFIE LayerNormalization operator " + opName +
191 " called to generate without being initialized first.");
192 }
193
194 std::stringstream out;
195
196 out << "//---- Layer Normalization operator " << opName << "\n";
197
198 // Loop over all the normalized axes i.e. [axis, ..., size)
199 std::vector<std::string> inputShape(fSize);
200
201 for (size_t i = 0; i < fSize; i++) {
202 inputShape[i] = fShapeX[i].GetVal();
203 }
204
206 std::string inputIndex = "axis_0 * " + strides[0].GetVal();
207 for (size_t i = 1; i < fSize; i++) {
208 inputIndex += " + axis_" + std::to_string(i);
209 if (i < fSize-1) inputIndex += " * " + strides[i].GetVal();
210 }
211 auto scaleStrides = UTILITY::ComputeStrideFromShape(fShapeScale);
212 std::string scaleIndex;
213 for (size_t i = 0; i < fSize; i++) {
214 if (fShapeScale[i].dim != 1) {
215 if (!scaleIndex.empty()) scaleIndex += " + ";
216 scaleIndex += "axis_" + std::to_string(i);
217 if ( scaleStrides[i].dim != 1) scaleIndex += " * " + scaleStrides[i].GetVal();
218 }
219 }
220 if (scaleIndex.empty()) scaleIndex = "0";
221
222 // the bias is optional: fShapeB is empty when there is no bias input
223 std::string biasIndex;
224 if (!fNB.empty()) {
225 auto biasStrides = UTILITY::ComputeStrideFromShape(fShapeB);
226 for (size_t i = 0; i < fSize; i++) {
227 if (fShapeB[i].dim != 1) {
228 if (!biasIndex.empty()) biasIndex += " + ";
229 biasIndex += "axis_" + std::to_string(i);
230 if ( biasStrides[i].dim != 1) biasIndex += " * " + biasStrides[i].GetVal();
231 }
232 }
233 }
234 if (biasIndex.empty()) biasIndex = "0";
235
236 // index in the Mean and InvStdDev tensors. If fAxis is 0 there are no outer
237 // dimensions and these tensors have a single element
238 std::string axesIndex = "0";
239 if (fAxis > 0) {
241 axesIndex = "axis_0 * " + axesStrides[0].GetVal();
242 for (size_t i = 1; i < fAxis; i++) {
243 axesIndex += " + axis_" + std::to_string(i) + " * " + axesStrides[i].GetVal();
244 }
245 }
246
247
248 // compute mean and std-dev. Save in tensors if requested
249
250 // open a scope: if fAxis is 0 there are no outer loops and the local
251 // variables below would otherwise be declared at function scope
252 out << SP << "{\n";
253
254 out << SP << "// Compute the mean\n";
255
256 // Loop over all the outer dims in [0, fAxis)
257 for (size_t i = 0; i < fAxis; i++) {
258 std::string iIdx = "axis_" + std::to_string(i);
259 out << SP << "for (size_t " << iIdx << " = 0; " << iIdx << " < " << inputShape[i]
260 << "; " << iIdx << "++) {\n";
261 }
262 out << SP << SP << fType << " mean = 0.;\n";
263 // loop over the normalized dimensions (fAxis,....,N-1)
264 for (size_t j = fAxis; j < fSize; j++) {
265 std::string jIdx = "axis_" + std::to_string(j);
266 out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j]
267 << "; " << jIdx << "++) {\n";
268 }
269 out << SP << SP << SP << "mean += tensor_" << fNX << "[" << inputIndex << "];\n";
270 for (size_t j = fAxis; j < fSize; j++) {
271 out << SP << SP << "}\n";
272 }
273 out << SP << SP << "mean /= " << fType << "(" << fNormalizedLength << ");\n";
274
275
276 out << SP << "// Compute the inverse Standard Deviation\n";
277
278 // Set sum = 0
279 out << SP << SP << fType << " sum = 0.;\n";
280 // loop over all the dims in [0, fAxis)
281 for (size_t j = fAxis; j < fSize; j++) {
282 std::string jIdx = "axis_" + std::to_string(j);
283 out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j]
284 << "; " << jIdx << "++){\n";
285 }
286 out << SP << SP << SP << "float tmp = tensor_" << fNX << "[" << inputIndex << "] - mean;\n";
287 out << SP << SP << SP << "sum += tmp*tmp;\n";
288 for (size_t j = fAxis; j < fSize; j++) {
289 out << SP << SP << "}\n";
290 }
291 out << SP << SP << fType << " invStdDev = 1 / std::sqrt(";
292 out << "sum / " << fType << "(" << fNormalizedLength << ") + " << fAttrEpsilon << ");\n";
293
294
295 // set output mean and invStdDev if requested
296 if (!fNMean.empty())
297 out << SP << SP << "tensor_" << fNMean << "[" << axesIndex << "] = mean;\n";
298 if (!fNInvStdDev.empty())
299 out << SP << SP << "tensor_" << fNInvStdDev << "[" << axesIndex << "] = invStdDev;\n";
300
301 // scale and add bias
302
303 out << SP << "// Y = Scale o InvStdDev (X - Mean)\n";
304
305 for (size_t j = fAxis; j < fSize; j++) {
306 std::string jIdx = "axis_" + std::to_string(j);
307 out << SP << SP << "for (size_t " << jIdx << " = 0; " << jIdx << " < " << inputShape[j] << "; " << jIdx
308 << "++){\n";
309 }
310 out << SP << SP << SP << "tensor_" << fNY << "[" << inputIndex << "] = tensor_" << fNScale;
311 out << "[" << scaleIndex << "] * invStdDev * (tensor_" << fNX << "[" << inputIndex << "] - mean)";
312
313 // add bias if needed
314 if (!fNB.empty())
315 // assume bias has index as scale
316 out << " + tensor_" << fNB << "[" << biasIndex << "]";
317 out << ";\n";
318
319 // close loops on normalizing dim [..,fAxis,...fSize-1]
320 for (size_t j = fAxis; j < fSize; j++) {
321 out << SP << SP << "}\n";
322 }
323 // close loops on the other dimensions [0,...,fAxis]
324 for (size_t i = 0; i < fAxis; i++) {
325 out << SP << "}\n";
326 }
327 out << SP << "}\n";
328
329 return out.str();
330 }
331
332 std::vector<std::string> GetBlasRoutines() override { return { std::string("Axpy") }; }
333
334 std::vector<std::string> GetStdLibs() override { return { std::string("cmath") }; }
335};
336
337} // namespace SOFIE
338} // namespace Experimental
339} // namespace TMVA
340
341#endif
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 Atom_t Time_t type
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)
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)
create variable transformations