Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ROperator_RNN.hxx
Go to the documentation of this file.
1#ifndef TMVA_SOFIE_ROPERATOR_RNN
2#define TMVA_SOFIE_ROPERATOR_RNN
3
4#include "TMVA/RModel.hxx"
5#include "TMVA/ROperator.hxx"
7
8#include <memory>
9#include <sstream>
10#include <vector>
11
13
14/*! \brief Recurrent Neural Network operator
15 *
16 * Inference code generation for one-layer vanilla RNN. Supports forward, reverse and bidirectional RNNs.
17 * See the <a href="https://github.com/onnx/onnx/blob/master/docs/Operators.md#RNN">ONNX documentation</a>
18 * for details about the supported RNN architectures.
19 */
20template <typename T> class ROperator_RNN final : public ROperator {
21 private:
22 std::vector<float> fAttrActivationAlpha; ///< Scaling values used by some activation functions
23 std::vector<float> fAttrActivationBeta; ///< Scaling values used by some activation functions
24 std::vector<std::string> fAttrActivations; ///< Activation functions
25 float fAttrClip; ///< Clip threshold
26 std::string fAttrDirection; ///< Direction of processing
27 size_t fAttrHiddenSize; ///< Number of the hidden layers
28 size_t fAttrLayout; ///< Data layout
29
30 std::string fNX; ///< Name of the input
31 std::string fNW; ///< Name of the weights
32 std::string fNR; ///< Name of the recurrence
33 std::string fNB; ///< Name of the bias
34 std::string fNSequence_lens; ///< Name of the length of the sequences
35 std::string fNInitial_h; ///< Name of the initial value of the hidden states
36 std::string fNY; ///< Name of the output
37 std::string fNY_h; ///< Name of the last sequence of the output
38
39 std::vector<size_t> fShapeX; ///< Shape of the input
40 std::vector<size_t> fShapeW; ///< Shape of the weights
41 std::vector<size_t> fShapeR; ///< Shape of the recurrence
42 std::vector<size_t> fShapeB; ///< Shape of the bias
43 std::vector<size_t> fShapeSequence_lens; ///< Shape of the length of the sequences
44 std::vector<size_t> fShapeInitial_h; ///< Shape of the initial value of the hidden states
45 std::vector<size_t> fShapeY; ///< Shape of the output
46 std::vector<size_t> fShapeY_h; ///< Shape of the last sequence of the output
47
48 std::string fType; ///< Type of the tensors
49
50 public:
51 /*! Default constructor of ROperator_RNN */
53
54 /*! \brief Constructor of ROperator_RNN from the attributes
55 *
56 * \param activation_alpha scaling values used by some activation functions
57 * \param activation_beta scaling values used by some activation functions
58 * \param activations activation functions
59 * \param clip clip threshold
60 * \param direction direction of processing of the sequneces
61 * \param hidden_size number of hidden layers
62 * \param layout data layout
63 * \param nameX name of the input tensor
64 * \param nameW name of the weight tensor
65 * \param nameR name of the recurrence tensor
66 * \param nameB name of the bias tensor
67 * \param nameSequence_lens name of the length of the sequences
68 * \param nameInitial_h name of the initial value of the hidden states
69 * \param nameY name of the output
70 * \param nameY_h name of the last sequence of the output
71 */
72 ROperator_RNN(std::vector<float> activation_alpha,
73 std::vector<float> activation_beta,
74 std::vector<std::string> activations, float clip,
75 std::string direction, size_t hidden_size, size_t layout,
76 std::string nameX, std::string nameW, std::string nameR,
77 std::string nameB, std::string nameSequence_lens,
78 std::string nameInitial_h, std::string nameY,
79 std::string nameY_h)
80 : fAttrActivationAlpha(activation_alpha),
81 fAttrActivationBeta(activation_beta), fAttrActivations(activations),
82 fAttrClip(clip), fAttrDirection(direction),
83 fAttrHiddenSize(hidden_size), fAttrLayout(layout),
84 fNX(UTILITY::Clean_name(nameX)), fNW(UTILITY::Clean_name(nameW)),
85 fNR(UTILITY::Clean_name(nameR)), fNB(UTILITY::Clean_name(nameB)),
86 fNSequence_lens(UTILITY::Clean_name(nameSequence_lens)),
87 fNInitial_h(UTILITY::Clean_name(nameInitial_h)),
88 fNY(UTILITY::Clean_name(nameY)), fNY_h(UTILITY::Clean_name(nameY_h)) {
89 if (std::is_same<T, float>::value) {
90 fType = "float";
91 } else {
92 throw std::runtime_error(
93 "TMVA SOFIE Encountered unsupported type parsing a RNN operator");
94 }
95
97 if(!fNB.empty()){
98 fInputTensorNames.emplace_back(fNB);
99 }
100 if(!fNSequence_lens.empty()){
102 }
103 if(!fNInitial_h.empty()){
104 fInputTensorNames.emplace_back(fNInitial_h);
105 }
106
107 fOutputTensorNames = { };
108 if(!fNY.empty()){
109 fOutputTensorNames.emplace_back(fNY);
110 }
111 if(!fNY_h.empty()){
112 fOutputTensorNames.emplace_back(fNY_h);
113 }
114 }
115
116 /*! \brief Infers the shape of the output tensors
117 *
118 * \param input shape of the input tensors
119 */
120 std::vector<std::vector<size_t>>
121 ShapeInference(std::vector<std::vector<size_t>> input);
122
123 /*! \brief Initialize the model
124 *
125 * \param model Model
126 */
127 void Initialize(RModel &) override;
128
129 /*! \brief Generates the inference code
130 *
131 * \param OpName name of the operator
132 */
133 std::string Generate(std::string OpName) override;
134
135 // generate code for Session data members (e.g. internal vectors)
136 std::string GenerateSessionMembersCode(std::string opName) override;
137
138 /*! \brief Returns the blas routines needed to compile the generated code
139 */
140 std::vector<std::string> GetBlasRoutines() override { return { std::string("Gemm"), std::string("Axpy") }; }
141};
142
143template <typename T>
144auto ROperator_RNN<T>::ShapeInference(std::vector<std::vector<size_t>> input) -> std::vector<std::vector<size_t>>
145{
146 size_t num_directions = input[1][0];
147 size_t hidden_size = input[1][1];
148 if (fAttrLayout == 0) {
149 size_t seq_length = input[0][0];
150 size_t batch_size = input[0][1];
151 std::vector<std::vector<size_t>> ret(
152 {{seq_length, num_directions, batch_size, hidden_size}, {num_directions, batch_size, hidden_size}});
153 return ret;
154 } else {
155 size_t batch_size = input[0][0];
156 size_t seq_length = input[0][1];
157 std::vector<std::vector<size_t>> ret(
158 {{batch_size, seq_length, num_directions, hidden_size}, {batch_size, num_directions, hidden_size}});
159 return ret;
160 }
161}
162
163template <typename T>
165{
166 // Check the input and output tensors
167 if (!model.CheckIfTensorAlreadyExist(fNX)) {
168 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNX + " is not found in model.");
169 }
170 fShapeX = model.GetTensorShape(fNX);
171 if (fShapeX.size() != 3) {
172 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNX + " is not of 3 dimensions.");
173 }
174 if (!model.CheckIfTensorAlreadyExist(fNW)) {
175 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNW + " is not found in model.");
176 }
177 fShapeW = model.GetTensorShape(fNW);
178 if (fShapeW.size() != 3) {
179 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNW + " is not of 3 dimensions.");
180 }
181 if (!model.CheckIfTensorAlreadyExist(fNR)) {
182 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNR + " is not found in model.");
183 }
184 fShapeR = model.GetTensorShape(fNR);
185 if (fShapeR.size() != 3) {
186 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNR + " is not of 3 dimensions.");
187 }
188 if (!fNB.empty()) {
189 if (!model.CheckIfTensorAlreadyExist(fNB)) {
190 throw std::runtime_error("TMVA SOFIE RNN op input tensor " + fNB + " is not found in model.");
191 }
192 fShapeB = model.GetTensorShape(fNB);
193 if (fShapeB.size() != 2 && fShapeB.size() != 4) {
194 throw std::runtime_error("TMVA SOFIE RNN op input tensor " + fNB + " is not of 2 or 4 dimensions.");
195 }
196 if (fShapeB.size() == 2) {
197 // Broadcasting the bias
198 auto original_data = model.GetInitializedTensorData(fNB);
199 size_t num_directions = fShapeW[0];
200 size_t seq_length = (fAttrLayout == 0) ? fShapeX[0] : fShapeX[1];
201 size_t batch_size = (fAttrLayout == 0) ? fShapeX[1] : fShapeX[0];
202 if (fType == "float") {
203 float *original_bias = static_cast<float *>(original_data.get());
204 float *new_bias = new float[num_directions * seq_length * batch_size * fAttrHiddenSize];
205 std::vector<float> sum(fAttrHiddenSize);
206 for (size_t direction = 0; direction < num_directions; direction++) {
207 for (size_t h = 0; h < fAttrHiddenSize; h++) {
208 sum[h] = original_bias[direction * 2 * fAttrHiddenSize + h] +
209 original_bias[(2 * direction + 1) * fAttrHiddenSize + h];
210 }
211 for (size_t seq = 0; seq < seq_length; seq++) {
212 for (size_t batch = 0; batch < batch_size; batch++) {
213 size_t bias_offset = direction * seq_length * batch_size * fAttrHiddenSize +
214 seq * batch_size * fAttrHiddenSize + batch * fAttrHiddenSize;
215 std::copy(sum.begin(), sum.end(), new_bias + bias_offset);
216 }
217 }
218 }
219 std::vector<size_t> new_bias_shape = {num_directions, seq_length, batch_size, fAttrHiddenSize};
220 std::shared_ptr<void> new_bias_ptr(new_bias, std::default_delete<float[]>());
221 model.UpdateInitializedTensor(fNB, model.GetTensorType(fNB), new_bias_shape, new_bias_ptr);
222 fShapeB = model.GetTensorShape(fNB);
223 }
224 }
225 }
226 if (!fNSequence_lens.empty()) {
227 if (!model.CheckIfTensorAlreadyExist(fNSequence_lens)) {
228 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNSequence_lens + "is not found in model.");
229 }
230 fShapeSequence_lens = model.GetTensorShape(fNSequence_lens);
231 if (fShapeSequence_lens.size() != 1) {
232 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNSequence_lens + " is not of 1 dimension.");
233 }
234 }
235 if (!fNInitial_h.empty()) {
236 if (!model.CheckIfTensorAlreadyExist(fNInitial_h)) {
237 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNInitial_h + " is not found in model.");
238 }
239 fShapeInitial_h = model.GetTensorShape(fNInitial_h);
240 if (fShapeInitial_h.size() != 3) {
241 throw std::runtime_error("TMVA SOFIE RNN Op input tensor " + fNInitial_h + " is not of 3 dimensions.");
242 }
243 }
244 if (!fNY.empty()) {
245 fShapeY = ShapeInference({fShapeX, fShapeW})[0];
246 if (!model.CheckIfTensorAlreadyExist(fNY)) {
247 model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShapeY);
248 }
249 }
250 if (!fNY_h.empty()) {
251 fShapeY_h = ShapeInference({fShapeX, fShapeW})[1];
252 if (!model.CheckIfTensorAlreadyExist(fNY_h)) {
253 model.AddIntermediateTensor(fNY_h, model.GetTensorType(fNX), fShapeY_h);
254 }
255 }
256 // Check the attributes
257 for (auto &activation : fAttrActivations) {
258 if (activation != "Relu" && activation != "Tanh" && activation != "Sigmoid" && activation != "Affine" &&
259 activation != "LeakyRelu" && activation != "ThresholdRelu" && activation != "ScaledTanh" &&
260 activation != "HardSigmoid" && activation != "Elu" && activation != "Softsign" && activation != "Softplus") {
261 throw std::runtime_error("TMVA SOFIE - Activation function " + activation + " not implemented");
262 }
263 }
264 if (fAttrDirection != "forward" && fAttrDirection != "backward" && fAttrDirection != "bidirectional") {
265 throw std::runtime_error("TMVA SOFIE - Invalid RNN direction fAttrDirection = " + fAttrDirection);
266 }
267 if (fAttrHiddenSize != fShapeW[1]) {
268 throw std::runtime_error("TMVA SOFIE - fAttrHiddenSize must be equal to " + std::to_string(fShapeW[1]));
269 }
270 if (fAttrLayout > 1) {
271 throw std::runtime_error("TMVA SOFIE - Layout fAttrLayout = " + std::to_string(fAttrLayout) +
272 " must be 0 (timewise) or 1 (batchwise)");
273 }
274 if (fAttrActivations.empty()) {
275 if (fAttrDirection == "bidirectional") {
276 fAttrActivations = {"Tanh", "Tanh"};
277 } else {
278 fAttrActivations = {"Tanh"};
279 }
280 }
281 // Add needed standard library headers
282 model.AddNeededStdLib("cmath");
283}
284
285// generate code for Session data members (e.g. internal vectors)
286template <typename T>
287std::string ROperator_RNN<T>::GenerateSessionMembersCode(std::string opName)
288{
289 opName = "op_" + opName;
290 std::stringstream out;
291
292 size_t num_directions = fShapeW[0];
293 size_t seq_length = (fAttrLayout == 0) ? fShapeX[0] : fShapeX[1];
294 size_t batch_size = (fAttrLayout == 0) ? fShapeX[1] : fShapeX[0];
295 size_t input_size = fShapeX[2];
296
297 struct Block {
298 std::string name;
299 size_t size;
300 };
301
302 std::vector<Block> blocks;
303
304 if (fAttrLayout != 0) {
305 blocks.push_back({"input", seq_length * batch_size * input_size});
306 blocks.push_back({"initial_hidden_state", num_directions * batch_size * fAttrHiddenSize});
307 }
308 blocks.push_back({"feedforward", seq_length * batch_size * fAttrHiddenSize});
309 if (fAttrLayout != 0 || fNY.empty()) {
310 blocks.push_back({"hidden_state", seq_length * num_directions * batch_size * fAttrHiddenSize});
311 }
312
313 // Compute total size
314 size_t total_size = 0;
315 for (const auto &b : blocks) {
316 total_size += b.size;
317 }
318
319 // Emit backing storage
320 out << "std::vector<" << fType << "> fVec_" << opName << "_buffer = std::vector<" << fType << ">(" << total_size
321 << ");\n";
322
323 // Emit pointers
324 std::size_t offset = 0;
325 for (const auto &b : blocks) {
326 out << fType << "* fVec_" << opName << "_" << b.name << " = fVec_" << opName << "_buffer.data() + " << offset
327 << ";\n";
328 offset += b.size;
329 }
330
331 out << "\n";
332
333 return out.str();
334}
335
336//////////////////////////////////////////////////////////////////////////////////////////////////
337template <typename T>
338auto ROperator_RNN<T>::Generate(std::string OpName) -> std::string
339{
340 OpName = "op_" + OpName;
341 std::stringstream out;
342
343 size_t seq_length = (fAttrLayout == 0) ? fShapeX[0] : fShapeX[1];
344 size_t batch_size = (fAttrLayout == 0) ? fShapeX[1] : fShapeX[0];
345 size_t input_size = fShapeX[2];
346 size_t num_directions = fShapeW[0];
347
348 // set the input
349 if (fAttrLayout == 0) {
350 if (fType == "float") {
351 out << SP << "float const*" << OpName << "_input = tensor_" << fNX << ";\n";
352 }
353 } else {
354 out << SP << fType << " * " << OpName << "_input = this->fVec_" << OpName << "_input;\n";
355 out << SP << "for(size_t seq = 0; seq < " << seq_length << "; seq++) {\n";
356 out << SP << SP << "for(size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
357 out << SP << SP << SP << "for(size_t i = 0; i < " << input_size << "; i++) {\n";
358 out << SP << SP << SP << SP << OpName << "_input[seq * " << batch_size * input_size << " + batch * " << input_size
359 << " + i] = " << "tensor_" << fNX << "[batch * " << seq_length * input_size << " + seq * " << input_size
360 << " + i];\n";
361 out << SP << SP << SP << "}\n";
362 out << SP << SP << "}\n";
363 out << SP << "}\n";
364 }
365
366 // Set the initial hidden state
367 if (!fNInitial_h.empty()) {
368 if (fAttrLayout == 0) {
369 out << SP << fType << " *" << OpName << "_initial_hidden_state = " << " tensor_" << fNInitial_h << ";\n";
370 } else {
371 out << SP << fType << " * " << OpName << "_initial_hidden_state = this->fVec_" << OpName
372 << "_initial_hidden_state;\n";
373
374 for (size_t direction = 0; direction < num_directions; direction++) {
375 out << SP << "for(size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
376 out << SP << SP << "for(size_t h = 0; h < " << fAttrHiddenSize << "; h++) {\n";
377 out << SP << SP << SP << OpName << "_initial_hidden_state[" << direction * batch_size * fAttrHiddenSize
378 << " + batch * " << fAttrHiddenSize << " + h] = tensor_" << fNInitial_h << "[batch * "
379 << num_directions * fAttrHiddenSize << " + " << direction * fAttrHiddenSize << " + h];\n";
380 out << SP << SP << "}\n";
381 out << SP << "}\n";
382 }
383 }
384 }
385
386 out << SP << fType << " * " << OpName << "_feedforward = this->fVec_" << OpName << "_feedforward;\n";
387
388 // Set the hidden state
389 if (fAttrLayout == 0 && !fNY.empty()) {
390 out << SP << fType << " *" << OpName << "_hidden_state = tensor_" << fNY << ";\n";
391 } else {
392 out << SP << fType << " * " << OpName << "_hidden_state = this->fVec_" << OpName << "_hidden_state;\n";
393 }
394
395 out << SP << "char " << OpName << "_transA = 'N';\n";
396 out << SP << "char " << OpName << "_transB = 'T';\n";
397 out << SP << "int " << OpName << "_m = " << seq_length * batch_size << ";\n";
398 out << SP << "int " << OpName << "_n = " << fAttrHiddenSize << ";\n";
399 out << SP << "int " << OpName << "_k = " << input_size << ";\n";
400 if (fType == "float") {
401 out << SP << "float " << OpName << "_alpha = 1.;\n";
402 out << SP << "float " << OpName << "_beta = .0;\n";
403 }
404 if (!fNB.empty()) {
405 out << SP << "int " << OpName << "_bias_size = " << seq_length * batch_size * fAttrHiddenSize << ";\n";
406 out << SP << "int " << OpName << "_incx = 1;\n";
407 out << SP << "int " << OpName << "_incy = 1;\n";
408 }
409
410 for (size_t direction = 0; direction < num_directions; direction++) {
411 // feedforward = input * W^T + bias
412 if (fType == "float") {
413 if (direction == 0) {
414 out << SP << "BLAS::sgemm_(&" << OpName << "_transB, &" << OpName << "_transA, &" << OpName << "_n, &"
415 << OpName << "_m, &" << OpName << "_k, &" << OpName << "_alpha, tensor_" << fNW << ", &" << OpName
416 << "_k, " << OpName << "_input, &" << OpName << "_k, &" << OpName << "_beta, " << OpName
417 << "_feedforward, &" << OpName << "_n);\n";
418 } else {
419 out << SP << "size_t " << OpName << "_w_offset = " << fAttrHiddenSize * input_size << ";\n";
420 out << SP << "BLAS::sgemm_(&" << OpName << "_transB, &" << OpName << "_transA, &" << OpName << "_n, &"
421 << OpName << "_m, &" << OpName << "_k, &" << OpName << "_alpha, tensor_" << fNW << " + " << OpName
422 << "_w_offset, &" << OpName << "_k, " << OpName << "_input, &" << OpName << "_k, &" << OpName
423 << "_beta, " << OpName << "_feedforward, &" << OpName << "_n);\n";
424 }
425 }
426 // Add the bias
427 if (!fNB.empty()) {
428 if (fType == "float") {
429 if (direction == 0) {
430 out << SP << "BLAS::saxpy_(&" << OpName << "_bias_size, &" << OpName << "_alpha, tensor_" << fNB << ", &"
431 << OpName << "_incx, " << OpName << "_feedforward, &" << OpName << "_incy);\n";
432 } else {
433 out << SP << "size_t " << OpName << "_bias_offset = " << seq_length * batch_size * fAttrHiddenSize
434 << ";\n";
435 out << SP << "BLAS::saxpy_(&" << OpName << "_bias_size, &" << OpName << "_alpha, tensor_" << fNB << " + "
436 << OpName << "_bias_offset, &" << OpName << "_incx, " << OpName << "_feedforward, &" << OpName
437 << "_incy);\n";
438 }
439 }
440 }
441
442 // Copy feedforward into hidden state
443 out << SP << "for (size_t seq = 0; seq < " << seq_length << "; seq++) {\n";
444 out << SP << SP << "size_t offset = seq * " << batch_size * fAttrHiddenSize << ";\n";
445 out << SP << SP << "size_t size = " << batch_size * fAttrHiddenSize << ";\n";
446 out << SP << SP << "size_t h_offset = seq * " << num_directions * batch_size * fAttrHiddenSize << " + "
447 << direction * batch_size * fAttrHiddenSize << ";\n";
448 out << SP << SP << "std::copy(" << OpName << "_feedforward + offset, " << OpName
449 << "_feedforward + offset + size, " << OpName << "_hidden_state + h_offset);\n";
450 out << SP << "}\n";
451
452 out << SP << "for (size_t seq = 0; seq < " << seq_length << "; seq++) {\n";
453 if (fAttrDirection == "backward" || direction == 1) {
454 out << SP << SP << "size_t index = " << seq_length - 1 << " - seq;\n";
455 } else {
456 out << SP << SP << "size_t index = seq;\n";
457 }
458
459 out << SP << SP << "int m2 = " << batch_size << ";\n";
460 out << SP << SP << "size_t offset = index * " << num_directions * batch_size * fAttrHiddenSize << " + "
461 << direction * batch_size * fAttrHiddenSize << ";\n";
462 out << SP << SP << "size_t size = " << batch_size * fAttrHiddenSize << ";\n";
463 out << SP << SP << "if (seq == 0) {\n";
464 if (!fNInitial_h.empty()) {
465 // hidden_state = hidden_state + initial_hidden_state * R^T
466 out << SP << SP << SP << "size_t r_offset = " << direction * fAttrHiddenSize * fAttrHiddenSize << ";\n";
467 out << SP << SP << SP << "size_t initial_hidden_state_offset = " << direction * batch_size * fAttrHiddenSize
468 << ";\n";
469 if (fType == "float") {
470 out << SP << SP << SP << "BLAS::sgemm_(&" << OpName << "_transB, &" << OpName << "_transA, &" << OpName
471 << "_n, &m2, &" << OpName << "_n, &" << OpName << "_alpha, tensor_" << fNR << " + r_offset, &" << OpName
472 << "_n, " << OpName << "_initial_hidden_state + initial_hidden_state_offset, &" << OpName << "_n, &"
473 << OpName << "_alpha, " << OpName << "_hidden_state + offset, &" << OpName << "_n);\n";
474 }
475 }
476 out << SP << SP << "} else {\n";
477 // hidden_state = hidden_state + previous_hidden_state * R^T
478 out << SP << SP << SP << "size_t r_offset = " << direction * fAttrHiddenSize * fAttrHiddenSize << ";\n";
479 if (fAttrDirection == "backward" || direction == 1) {
480 out << SP << SP << SP << "size_t previous_offset = (index + 1) * "
481 << num_directions * batch_size * fAttrHiddenSize << " + " << direction * batch_size * fAttrHiddenSize
482 << ";\n";
483 } else {
484 out << SP << SP << SP << "size_t previous_offset = (seq - 1) * "
485 << num_directions * batch_size * fAttrHiddenSize << " + " << direction * batch_size * fAttrHiddenSize
486 << ";\n";
487 }
488 if (fType == "float") {
489 out << SP << SP << SP << "BLAS::sgemm_(&" << OpName << "_transB, &" << OpName << "_transA, &" << OpName
490 << "_n, &m2, &" << OpName << "_n, &" << OpName << "_alpha, tensor_" << fNR << " + r_offset, &" << OpName
491 << "_n, " << OpName << "_hidden_state + previous_offset, &" << OpName << "_n, &" << OpName << "_alpha, "
492 << OpName << "_hidden_state + offset, &" << OpName << "_n);\n";
493 }
494 out << SP << SP << "}\n";
495
496 // Clip the elements of the hidden state into the range [-fAttrClip, fAttrClip]
497 if (fAttrClip > .0) {
498 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
499 if (fType == "float") {
500 out << SP << SP << SP << "float x = (" << OpName << "_hidden_state[i] > " << -fAttrClip << ") ? " << OpName
501 << "_hidden_state[i] : " << -fAttrClip << ";\n";
502 }
503 out << SP << SP << SP << OpName << "_hidden_state[i] = (x < " << fAttrClip << ") ? x : " << fAttrClip << ";\n";
504 out << SP << SP << "}\n";
505 }
506
507 // Apply the activation function to the hidden state
508 if (fAttrActivations[direction] == "Relu") {
509 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
510 out << SP << SP << SP << "if (" << OpName << "_hidden_state[i] < 0.)\n";
511 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = 0.;\n";
512 out << SP << SP << "}\n";
513 } else if (fAttrActivations[direction] == "Tanh") {
514 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
515 if (fType == "float") {
516 out << SP << SP << SP << "float ex = std::exp(-2 * " << OpName << "_hidden_state[i]);\n";
517 }
518 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = (1. - ex) / (1. + ex);\n";
519 out << SP << SP << "}\n";
520 } else if (fAttrActivations[direction] == "Sigmoid") {
521 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
522 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = 1. / (1. + std::exp(-" << OpName
523 << "_hidden_state[i]));\n";
524 out << SP << SP << "}\n";
525 } else if (fAttrActivations[direction] == "Affine") {
526 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
527 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = " << fAttrActivationAlpha[direction] << " * "
528 << OpName << "_hidden_state[i] + " << fAttrActivationBeta[direction] << ";\n";
529 out << SP << SP << "}\n";
530 } else if (fAttrActivations[direction] == "ScaledTanh") {
531 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
532 if (fType == "float") {
533 out << SP << SP << SP << "float ex = std::exp(-2 * " << fAttrActivationBeta[direction] << " * " << OpName
534 << "_hidden_state[i]);\n";
535 }
536 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = " << fAttrActivationAlpha[direction]
537 << " * (1. - ex) / (1. + ex);\n";
538 out << SP << SP << "}\n";
539 } else if (fAttrActivations[direction] == "HardSigmoid") {
540 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
541 if (fType == "float") {
542 out << SP << SP << SP << "float a = " << fAttrActivationAlpha[direction] << " * " << OpName
543 << "_hidden_state[i] + " << fAttrActivationBeta[direction] << ";\n";
544 out << SP << SP << SP << "float b = (a > 0.) ? a : 0.;\n";
545 }
546 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = (b < 1.) ? b : 1.;\n";
547 out << SP << SP << "}\n";
548 } else if (fAttrActivations[direction] == "LeakyRelu") {
549 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
550 out << SP << SP << SP << "if (" << OpName << "_hidden_state[i] < 0.)\n";
551 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = " << fAttrActivationAlpha[direction] << " * "
552 << OpName << "_hidden_state[i];\n";
553 out << SP << SP << "}\n";
554 } else if (fAttrActivations[direction] == "ThresholdRelu") {
555 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
556 out << SP << SP << SP << "if (" << OpName << "_hidden_state[i] < " << fAttrActivationAlpha[direction] << ")\n";
557 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = 0.;\n";
558 out << SP << SP << "}";
559 } else if (fAttrActivations[direction] == "Elu") {
560 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
561 out << SP << SP << SP << "if (" << OpName << "_hidden_state[i] < 0.)\n";
562 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = " << fAttrActivationAlpha[direction]
563 << " * std::exp(" << OpName << "_hidden_state[i] - 1.);\n";
564 out << SP << SP << "}\n";
565 } else if (fAttrActivations[direction] == "Softsign") {
566 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
567 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = " << OpName << "_hidden_state[i] / (1. + abs("
568 << OpName << "_hidden_state[i]));\n";
569 out << SP << SP << "}\n";
570 } else { // fAttrActivations[direction] = Softplus
571 out << SP << SP << "for (size_t i = offset; i < offset + size; i++) {\n";
572 out << SP << SP << SP << SP << OpName << "_hidden_state[i] = log(1. + std::exp(" << OpName
573 << "_hidden_state[i]));\n";
574 out << SP << SP << "}\n";
575 out << SP << "}\n";
576 }
577 out << SP << "}\n";
578 }
579
580 // Padding the hidden state for RNN with different sequence lengths
581 if (!fNSequence_lens.empty()) {
582 out << SP << "for (size_t seq = 0; seq < " << seq_length << "; seq++) {\n";
583 out << SP << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
584 out << SP << SP << SP << "if (seq >= tensor_" << fNSequence_lens << "[batch]) {\n";
585 out << SP << SP << SP << SP << "for (size_t h = 0; h < " << fAttrHiddenSize << "; h++) {\n";
586 if (num_directions == 1) {
587 out << SP << SP << SP << SP << SP << OpName << "_hidden_state[seq * "
588 << num_directions * batch_size * fAttrHiddenSize << " + batch * " << fAttrHiddenSize << " + h] = 0.;\n";
589 } else {
590 out << SP << SP << SP << SP << SP << OpName << "_hidden_state[seq * "
591 << num_directions * batch_size * fAttrHiddenSize << " + batch * " << fAttrHiddenSize << " + h] = 0.;\n";
592 out << SP << SP << SP << SP << SP << OpName << "_hidden_state[seq * "
593 << num_directions * batch_size * fAttrHiddenSize << " + " << batch_size * fAttrHiddenSize << " + batch * "
594 << fAttrHiddenSize << " + h] = 0.;\n";
595 }
596 out << SP << SP << SP << SP << "}\n";
597 out << SP << SP << SP << "}\n";
598 out << SP << SP << "}\n";
599 out << SP << "}\n";
600 }
601
602 // Copy the hidden state into y and y_h
603 if (fAttrLayout == 0) {
604 if (!fNY_h.empty()) {
605 if (fNSequence_lens.empty()) {
606 size_t yh_size = batch_size * fAttrHiddenSize;
607 if (fAttrDirection == "backward") {
608 out << SP << "std::copy(" << OpName << "_hidden_state, " << OpName << "_hidden_state + " << yh_size
609 << ", tensor_" << fNY_h << ");\n";
610 } else {
611 size_t offset = (seq_length - 1) * num_directions * batch_size * fAttrHiddenSize;
612 out << SP << "std::copy(" << OpName << "_hidden_state + " << offset << ", " << OpName
613 << "_hidden_state + " << offset << " + " << yh_size << ", tensor_" << fNY_h << ");\n";
614 }
615 if (num_directions == 2) {
616 out << SP << "std::copy(" << OpName << "_hidden_state + " << yh_size << ", " << OpName
617 << "_hidden_state + " << 2 * yh_size << ", tensor_" << fNY_h << " + " << yh_size << ");\n";
618 }
619 } else { // RNN with different sequence lengths
620 if (fAttrDirection == "backward") {
621 out << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
622 out << SP << SP << "size_t offset = batch * " << fAttrHiddenSize << ";\n";
623 out << SP << SP << "std::copy(" << OpName << "_hidden_state + offset, " << OpName
624 << "_hidden_state + offset + " << fAttrHiddenSize << ", tensor_" << fNY_h << " + offset);\n";
625 out << SP << "}\n";
626 } else {
627 out << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
628 out << SP << SP << "size_t seq = " << "tensor_" << fNSequence_lens << "[batch] - 1;\n";
629 out << SP << SP << "size_t offset = seq * " << num_directions * batch_size * fAttrHiddenSize
630 << " + batch * " << fAttrHiddenSize << ";\n";
631 out << SP << SP << "size_t yh_offset = batch * " << fAttrHiddenSize << ";\n";
632 out << SP << SP << "std::copy(" << OpName << "_hidden_state + offset, " << OpName
633 << "_hidden_state + offset + " << fAttrHiddenSize << ", tensor_" << fNY_h << " + yh_offset);\n";
634 out << SP << "}\n";
635 }
636 if (num_directions == 2) {
637 out << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
638 out << SP << SP << "size_t offset = " << batch_size * fAttrHiddenSize << " + batch * " << fAttrHiddenSize
639 << ";\n";
640 out << SP << SP << "size_t yh_offset = " << batch_size * fAttrHiddenSize << " + batch * "
641 << fAttrHiddenSize << ";\n";
642 out << SP << SP << "std::copy(" << OpName << "_hidden_state + offset, " << OpName
643 << "_hidden_state + offset + " << fAttrHiddenSize << ", tensor_" << fNY_h << " + yh_offset);\n";
644 out << SP << "}\n";
645 }
646 }
647 }
648 } else { // fAttrLayout=1
649 if (!fNY.empty()) {
650 for (size_t direction = 0; direction < num_directions; direction++) {
651 out << SP << "for (size_t seq = 0; seq < " << seq_length << "; seq++) {\n";
652 out << SP << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
653 out << SP << SP << SP << "size_t offset = seq * " << num_directions * batch_size * fAttrHiddenSize << " + "
654 << direction * batch_size * fAttrHiddenSize << " + batch * " << fAttrHiddenSize << ";\n";
655 out << SP << SP << SP << "size_t y_offset = batch * " << seq_length * num_directions * fAttrHiddenSize
656 << " + seq * " << num_directions * fAttrHiddenSize << " + " << direction * fAttrHiddenSize << ";\n";
657 out << SP << SP << SP << "std::copy(" << OpName << "_hidden_state + offset, " << OpName
658 << "_hidden_state + offset + " << fAttrHiddenSize << ", tensor_" << fNY << " + y_offset);\n";
659 out << SP << SP << "}\n";
660 out << SP << "}\n";
661 }
662 }
663 if (!fNY_h.empty()) {
664 if (fAttrDirection == "backward") {
665 out << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
666 out << SP << SP << "size_t offset = batch * " << fAttrHiddenSize << ";\n";
667 out << SP << SP << "size_t yh_offset = batch * " << num_directions * fAttrHiddenSize << ";\n";
668 out << SP << SP << "std::copy(" << OpName << "_hidden_state + offset, " << OpName
669 << "_hidden_state + offset + " << fAttrHiddenSize << ", tensor_" << fNY_h << " + yh_offset);\n";
670 out << SP << "}\n";
671 } else {
672 out << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
673 if (fNSequence_lens.empty()) {
674 out << SP << SP << "size_t seq = " << seq_length - 1 << ";\n";
675 } else {
676 out << SP << SP << "size_t seq = " << "tensor_" << fNSequence_lens << "[batch] - 1;\n";
677 }
678 out << SP << SP << "size_t offset = seq * " << num_directions * batch_size * fAttrHiddenSize
679 << " + batch * " << fAttrHiddenSize << ";\n";
680 out << SP << SP << "size_t yh_offset = batch * " << num_directions * fAttrHiddenSize << ";\n";
681 out << SP << SP << "std::copy(" << OpName << "_hidden_state + offset, " << OpName
682 << "_hidden_state + offset + " << fAttrHiddenSize << ", tensor_" << fNY_h << " + yh_offset);\n";
683 out << SP << "}\n";
684 }
685 if (num_directions == 2) {
686 out << SP << "for (size_t batch = 0; batch < " << batch_size << "; batch++) {\n";
687 out << SP << SP << "size_t offset = " << batch_size * fAttrHiddenSize << " + batch * " << fAttrHiddenSize
688 << ";\n";
689 out << SP << SP << "size_t yh_offset = batch * " << num_directions * fAttrHiddenSize << " + "
690 << fAttrHiddenSize << ";\n";
691 out << SP << SP << "std::copy(" << OpName << "_hidden_state + offset, " << OpName
692 << "_hidden_state + offset + " << fAttrHiddenSize << ", tensor_" << fNY_h << " + yh_offset);\n";
693 out << SP << "}\n";
694 }
695 }
696 }
697
698 return out.str();
699}
700
701} // namespace TMVA::Experimental::SOFIE
702
703#endif
#define b(i)
Definition RSha256.hxx:100
#define h(i)
Definition RSha256.hxx:106
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
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 offset
char name[80]
Definition TGX11.cxx:142
Recurrent Neural Network operator.
std::vector< size_t > fShapeB
Shape of the bias.
std::vector< float > fAttrActivationBeta
Scaling values used by some activation functions.
std::vector< std::vector< size_t > > ShapeInference(std::vector< std::vector< size_t > > input)
Infers the shape of the output tensors.
size_t fAttrHiddenSize
Number of the hidden layers.
std::string fNInitial_h
Name of the initial value of the hidden states.
ROperator_RNN(std::vector< float > activation_alpha, std::vector< float > activation_beta, std::vector< std::string > activations, float clip, std::string direction, size_t hidden_size, size_t layout, std::string nameX, std::string nameW, std::string nameR, std::string nameB, std::string nameSequence_lens, std::string nameInitial_h, std::string nameY, std::string nameY_h)
Constructor of ROperator_RNN from the attributes.
void Initialize(RModel &) override
Initialize the model.
std::vector< size_t > fShapeR
Shape of the recurrence.
std::string fNW
Name of the weights.
std::vector< size_t > fShapeY
Shape of the output.
std::string fType
Type of the tensors.
std::string fNY
Name of the output.
std::string fNSequence_lens
Name of the length of the sequences.
std::vector< size_t > fShapeSequence_lens
Shape of the length of the sequences.
std::vector< std::string > GetBlasRoutines() override
Returns the blas routines needed to compile the generated code.
std::string fNR
Name of the recurrence.
std::string GenerateSessionMembersCode(std::string opName) override
std::vector< float > fAttrActivationAlpha
Scaling values used by some activation functions.
ROperator_RNN()
Default constructor of ROperator_RNN.
std::vector< size_t > fShapeX
Shape of the input.
std::string fAttrDirection
Direction of processing.
std::string fNX
Name of the input.
std::string Generate(std::string OpName) override
Generates the inference code.
std::string fNY_h
Name of the last sequence of the output.
std::vector< size_t > fShapeInitial_h
Shape of the initial value of the hidden states.
std::vector< size_t > fShapeW
Shape of the weights.
std::vector< std::string > fAttrActivations
Activation functions.
std::vector< size_t > fShapeY_h
Shape of the last sequence of the output.
std::vector< std::string_view > fInputTensorNames
Definition ROperator.hxx:44
std::vector< std::string_view > fOutputTensorNames
Definition ROperator.hxx:45
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335