LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
bilstm_and_dense.h
Go to the documentation of this file.
1// Copyright 2021 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_SRC_INFERENCE_EIGEN_BILSTM_AND_DENSE_H
7#define DEEPLIMA_SRC_INFERENCE_EIGEN_BILSTM_AND_DENSE_H
8
9#include <vector>
10#include <type_traits>
11
12#include "bilstm.h"
13#include "linear.h"
14
15//#define BILSTM_AND_DENSE_PROFILE
16//#define MATMUL_WITH_FACTORIZATION
17
18#ifdef BILSTM_AND_DENSE_PROFILE
19#include <chrono>
20#endif
21
22namespace deeplima
23{
24namespace eigen_impl
25{
26
46template<typename M, // Basic matrix type
47 typename V, // Basic vector type
48 typename T, // Basic scalar type,
49 typename AuxScalar=float, // Input scalar type:
50 // - float - for normal arithmetics
51 // - int16_t - for fixed point operations where possible
52 uint8_t IFracBits=4, // Fraction bits in input data (used if AuxScalar is integer)
53 uint8_t WFracBits=4 // Fraction bits in weights_hh (used if AuxScalar is integer)
54 >
56{
57protected:
58
59 // For fixed point calculations (used only if AusScalar is integer)
60 static_assert(std::is_signed_v<AuxScalar>);
61 typedef AuxScalar fixed_point_t;
62 using MatrixWeight = typename std::conditional<std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>,
63 Eigen::Matrix<fixed_point_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
64 M>::type;
65 using MatrixInput = typename std::conditional<std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>,
66 Eigen::Matrix<fixed_point_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>,
67 M>::type;
68
69 // 2^bits as fixed_point_t. A plain `fixed_point_t(1) << bits` is ill-formed
70 // when AuxScalar is a floating-point type; GCC only rejects it on use, MSVC
71 // as soon as the class is instantiated.
72 static constexpr fixed_point_t pow2(int bits)
73 {
74 if constexpr (std::is_integral_v<fixed_point_t>)
75 return fixed_point_t(1) << bits;
76 else
77 return fixed_point_t(int64_t(1) << bits);
78 }
79 static constexpr fixed_point_t WEIGHT_FRACTION_MULT = pow2(WFracBits);
80 static constexpr fixed_point_t DATA_FRACTION_MULT = pow2(IFracBits);
81 static constexpr fixed_point_t WEIGHT_DATA_FRACTION_MULT = pow2(WFracBits + IFracBits);
82 // End of fixed point releated definitions
83
85 {
86 workbench_t(uint32_t input_size,
87 uint32_t hidden_size,
88 const std::vector<uint32_t>& output_sizes,
89 bool precomputed_input=false)
90 : temp(M::Zero(precomputed_input ? 0 : hidden_size * 8, input_size)),
91 out(M::Zero(hidden_size * 2, input_size)),
92 zero(V::Zero(hidden_size)),
93 m_precomputed_input(precomputed_input)
94 {
95 lin_out.resize(output_sizes.size());
96 for (size_t i = 0; i < output_sizes.size(); i++)
97 {
98 lin_out[i] = M::Zero(output_sizes[i], input_size);
99 }
100 }
101
102 virtual ~workbench_t() {}
103
106 std::vector<M> lin_out;
107 const V zero;
109 };
110
111public:
113 {
115 std::vector<params_linear_t<M, V>> linear;
116
117#ifdef MATMUL_WITH_FACTORIZATION
118 struct multiplier_t
119 {
120 Eigen::PartialPivLU<M> matmul_input;
121 Eigen::PartialPivLU<M> matmul_forget;
122 Eigen::PartialPivLU<M> matmul_update;
123 Eigen::PartialPivLU<M> matmul_output;
124 };
125
126 multiplier_t mul_fw;
127 multiplier_t mul_bw;
128
129 bool precompute()
130 {
131 // std::cerr << "fw weights size: " << bilstm.fw.weight_hh.rows()
132 // << " x " << bilstm.fw.weight_hh.cols() << std::endl;
133
134 size_t hidden_size = bilstm.fw.weight_hh.cols();
135 // std::cerr << "precompute(fw.input):" << std::endl;
136 // /*
137 mul_fw.matmul_input = bilstm.fw.weight_hh.block(0, 0, hidden_size, hidden_size).inverse().partialPivLu();
138 mul_fw.matmul_forget = bilstm.fw.weight_hh.block(hidden_size, 0, hidden_size, hidden_size).inverse().partialPivLu();
139 mul_fw.matmul_update = bilstm.fw.weight_hh.block(hidden_size*2, 0, hidden_size, hidden_size).inverse().partialPivLu();
140 mul_fw.matmul_output = bilstm.fw.weight_hh.block(hidden_size*3, 0, hidden_size, hidden_size).inverse().partialPivLu();
141 // */
142
143 hidden_size = bilstm.bw.weight_hh.cols();
144 // std::cerr << "precompute(bw.input):" << std::endl;
145 // /*
146 mul_bw.matmul_input = bilstm.bw.weight_hh.block(0, 0, hidden_size, hidden_size).inverse().partialPivLu();
147 mul_bw.matmul_forget = bilstm.bw.weight_hh.block(hidden_size, 0, hidden_size, hidden_size).inverse().partialPivLu();
148 mul_bw.matmul_update = bilstm.bw.weight_hh.block(hidden_size*2, 0, hidden_size, hidden_size).inverse().partialPivLu();
149 mul_bw.matmul_output = bilstm.bw.weight_hh.block(hidden_size*3, 0, hidden_size, hidden_size).inverse().partialPivLu();
150 // */
151
152 // std::cerr << "end of precomputing" << std::endl;
153 return true;
154 }
155#else
156 // These two matrices of weights are used (and filled) only if we are going
157 // to use fixed point multiplication of the recurrent state.
160
161 void convert_matrix(const M& src, MatrixWeight& dst)
162 {
163 dst = MatrixWeight::Zero(src.rows(), src.cols());
164 for (Eigen::Index row = 0; row < src.rows(); ++row)
165 for (Eigen::Index col = 0; col < src.cols(); ++col)
166 {
167 auto val = src(row, col);
168 dst(row, col) = static_cast<fixed_point_t>((val >= 0.0) ? (val * WEIGHT_FRACTION_MULT + T{0.5}) : (val * WEIGHT_FRACTION_MULT - T{0.5}));
169 }
170 }
171
173 {
174 if constexpr (std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
175 {
176 // std::cerr << "Converting hh to fixed_point" << std::endl;
177 // std::cerr << "min(fw_weight_hh) = " << bilstm.fw.weight_hh.minCoeff() << " "
178 // << "max(fw_weight_hh) = " << bilstm.fw.weight_hh.maxCoeff() << std::endl;
180 // std::cerr << "min(fw_weight_hh) = " << static_cast<T>(weight_fw_hh_fixed_point.minCoeff()) / WEIGHT_FRACTION_MULT << " "
181 // << "max(fw_weight_hh) = " << static_cast<T>(weight_fw_hh_fixed_point.maxCoeff()) / WEIGHT_FRACTION_MULT << std::endl;
182
183 // std::cerr << "min(bw_weight_hh) = " << bilstm.bw.weight_hh.minCoeff() << " "
184 // << "max(bw_weight_hh) = " << bilstm.bw.weight_hh.maxCoeff() << std::endl;
186 // std::cerr << "min(bw_weight_hh) = " << static_cast<T>(weight_bw_hh_fixed_point.minCoeff()) / /*WEIGHT_FRACTION_MULT << " "
187 // << "max(bw_weight_hh) = " << static_cast<T>(weight_bw_hh_fixed_point.maxCoeff()) / WEIGHT_FRACTION_MULT << std::endl;*/
188 }
189
190 return true;
191 }
192#endif
193};
194
196
197 virtual std::shared_ptr<Op_Base::workbench_t> create_workbench(uint32_t input_size, const std::shared_ptr<param_base_t> params, bool precomputed_input=false) const override
198 {
199 assert(input_size > 0);
200 assert(nullptr != params);
201 const auto& layer = std::dynamic_pointer_cast<const params_t>(params)->bilstm;
202 const auto& linear = std::dynamic_pointer_cast<const params_t>(params)->linear;
203
204#ifdef MATMUL_WITH_FACTORIZATION
205 const auto& mul_fw = std::dynamic_pointer_cast<const params_t>(params)->mul_fw;
206 const auto& mul_bw = std::dynamic_pointer_cast<const params_t>(params)->mul_bw;
207#endif
208
209 std::vector<uint32_t> output_sizes;
210 output_sizes.reserve(linear.size());
211 for ( const auto& p : linear )
212 {
213 output_sizes.push_back(p.weight.rows());
214 }
215 return std::make_shared<workbench_t>(input_size, layer.fw.weight_ih.rows() / 4, output_sizes, precomputed_input);
216 }
217
218 virtual bool supports_precomputing() const
219 {
220 return true;
221 }
222
223 virtual void precompute_inputs(const std::shared_ptr<param_base_t> params, const M& inputs, M& outputs, int64_t first_column)
224 {
225 assert(nullptr != params);
226 const auto& layer = std::dynamic_pointer_cast<const params_t>(params)->bilstm;
227 size_t hidden_size = layer.fw.weight_ih.rows() / 4;
228
229 auto output_block = outputs.block(0, first_column, outputs.rows(), inputs.cols());
230 // Top rows - forward pass
231 const V fw_bias = layer.fw.bias_ih + layer.fw.bias_hh;
232 output_block.topRows(hidden_size * 4).noalias() = (layer.fw.weight_ih * inputs).colwise() + fw_bias;
233
234 /*
235 std::cerr << "min(precomputed inputs) = " << output_block.topRows(hidden_size * 4).minCoeff() << " "
236 << "max(precomputed inputs) = " << output_block.topRows(hidden_size * 4).maxCoeff() << std::endl;
237 */
238
239 // Bottom rows - backward pass
240 const V bw_bias = layer.bw.bias_ih + layer.bw.bias_hh;
241 output_block.bottomRows(hidden_size * 4).noalias() = (layer.bw.weight_ih * inputs).colwise() + bw_bias;
242
243 /*
244 std::cerr << "min(precomputed inputs) = " << output_block.bottomRows(hidden_size * 4).minCoeff() << " "
245 << "max(precomputed inputs) = " << output_block.bottomRows(hidden_size * 4).maxCoeff() << std::endl;
246 */
247 }
248
249 virtual size_t execute(std::shared_ptr<Op_Base::workbench_t> pwb,
250 const M& input_matrix,
251 const std::shared_ptr<param_base_t> pparams,
252 std::vector<std::vector<uint8_t>>& final_output,
253 size_t input_begin,
254 size_t input_end,
255 size_t output_begin,
256 size_t output_end)
257 {
258 assert(pwb);
259 assert(pparams);
260 const params_t& params = *std::dynamic_pointer_cast<const params_t>(pparams);
261 const auto& layer = params.bilstm;
262 const auto& linear = params.linear;
263
264#ifdef MATMUL_WITH_FACTORIZATION
265 const auto& mul_fw = params.mul_fw;
266 const auto& mul_bw = params.mul_bw;
267#endif
268
269 auto wb = std::dynamic_pointer_cast<workbench_t>(pwb);
270 M& temp = wb->temp;
271 M& output = wb->out;
272 const V& zero = wb->zero;
273
274 size_t hidden_size = layer.fw.weight_ih.rows() / 4;
275 V c = zero;
276 V s = V::Zero(hidden_size * 4);
277
278 // Only the slot's columns [input_begin, input_end): the whole workbench
279 // width (the slot size, 16K characters for the segmenter) was processed,
280 // whatever the text length (most of the time of a short text), and the
281 // backward pass started beyond the text's end, on columns left by the
282 // previous text: the results of a text depended on the previous one
283 const Eigen::Index n = std::min<Eigen::Index>(
284 input_end > input_begin ? Eigen::Index(input_end - input_begin) : 0, temp.cols());
285 assert(n > 0);
286 assert(output_end - input_begin <= size_t(n));
287 Eigen::Ref<const M> input = input_matrix.block(0, input_begin, input_matrix.rows(), n);
288
289 if (wb->m_precomputed_input)
290 {
291#ifdef MATMUL_WITH_FACTORIZATION
292 forward_pass(hidden_size, input, layer.fw.weight_hh, mul_fw, s, c, output);
293#else
294 if constexpr (std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
295 {
296 forward_pass(hidden_size, input, params.weight_fw_hh_fixed_point, s, c, output);
297 }
298 else if constexpr (std::is_floating_point_v<AuxScalar>)
299 {
300 forward_pass(hidden_size, input, layer.fw.weight_hh, s, c, output);
301 }
302 else
303 {
304 static_assert((std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
305 || std::is_floating_point_v<AuxScalar>, "AuxScalar must be a signed integer or floating-point type");
306 }
307#endif
308
309 V c_fw = c;
310 c = V::Zero(hidden_size);
311#ifdef MATMUL_WITH_FACTORIZATION
312 backward_pass(hidden_size, input, layer.bw.weight_hh, mul_bw, s, c, output);
313#else
314 if constexpr (std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
315 {
316 backward_pass(hidden_size, input, params.weight_bw_hh_fixed_point, s, c, output);
317 }
318 else if constexpr (std::is_floating_point_v<AuxScalar>)
319 {
320 backward_pass(hidden_size, input, layer.bw.weight_hh, s, c, output);
321 }
322 else
323 {
324 static_assert((std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
325 || std::is_floating_point_v<AuxScalar>, "AuxScalar must be a signed integer or floating-point type");
326 }
327#endif
328 }
329 else
330 {
331 // Top rows - forward pass
332 temp.topRows(hidden_size * 4).leftCols(n) = (layer.fw.weight_ih * input).colwise() + layer.fw.bias_ih;
333 // Bottom rows - backward pass
334 temp.bottomRows(hidden_size * 4).leftCols(n) = (layer.bw.weight_ih * input).colwise() + layer.bw.bias_ih;
335
336#ifdef MATMUL_WITH_FACTORIZATION
337 forward_pass(hidden_size, temp.leftCols(n), layer.fw.weight_hh, mul_fw, s, c, output);
338#else
339 if constexpr (std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
340 {
341 forward_pass(hidden_size, temp.leftCols(n), params.weight_fw_hh_fixed_point, s, c, output);
342 }
343 else if constexpr (std::is_floating_point_v<AuxScalar>)
344 {
345 forward_pass(hidden_size, temp.leftCols(n), layer.fw.weight_hh, s, c, output);
346 }
347 else
348 {
349 static_assert((std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
350 || std::is_floating_point_v<AuxScalar>, "AuxScalar must be a signed integer or floating-point type");
351 }
352#endif
353
354 V c_fw = c;
355 c = V::Zero(hidden_size);
356
357#ifdef MATMUL_WITH_FACTORIZATION
358 backward_pass(hidden_size, temp.leftCols(n), layer.bw.weight_hh, mul_bw, s, c, output);
359#else
360 if constexpr (std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
361 {
362 backward_pass(hidden_size, temp.leftCols(n), params.weight_bw_hh_fixed_point, s, c, output);
363 }
364 else if constexpr (std::is_floating_point_v<AuxScalar>)
365 {
366 backward_pass(hidden_size, temp.leftCols(n), layer.bw.weight_hh, s, c, output);
367 }
368 else
369 {
370 static_assert((std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
371 || std::is_floating_point_v<AuxScalar>, "AuxScalar must be a signed integer or floating-point type");
372 }
373#endif
374 }
375
376#ifdef BILSTM_AND_DENSE_PROFILE
377 const auto before_linear = std::chrono::high_resolution_clock::now();
378#endif
379
380/*
381 M lo = linear[0].weight * output.col(0);
382 for (auto i = output_begin - input_begin; i < output_end - input_begin; i++)
383 {
384 for (size_t j = 0; j < final_output.size(); ++j)
385 {
386 //lo = (linear[j].weight * output.col(i)).colwise() + linear[j].bias;
387 Eigen::Index idx = 0;
388 // TODO scalar v value is not used but maxCoeff has side effect. It must be kept. Should we remove the
389 // return value or use it somewhat?
390 // typename M::Scalar v =
391 ((linear[j].weight * output.col(i)) + linear[j].bias).col(0).maxCoeff(&idx);
392
393 //lo.col(0).maxCoeff(&idx);
394 assert(idx >= 0);
395 assert(idx < std::numeric_limits<uint8_t>::max());
396 final_output[j][input_begin+i] = (uint8_t) idx;
397 }
398 }
399*/
400
401 // Linear layer on top of RNN outputs
402 M& linear_output = wb->lin_out[0];
403 for (size_t j = 0; j < final_output.size(); j++)
404 {
405 // A full assignment: it resizes linear_output to this output's classes
406 // (they differ between the outputs of the tagger)
407 linear_output.noalias() = (linear[j].weight * output.leftCols(n)).colwise() + linear[j].bias;
408 //linear_output.colwise() += linear[j].bias;
409
410 for (auto i = output_begin - input_begin; i < output_end - input_begin; i++)
411 {
412 Eigen::Index idx = 0;
413 // TODO scalar v value is not used but maxCoeff has side effect. It must be kept. Should we remove the
414 // return value or use it somewhat?
415 // typename M::Scalar v =
416 linear_output.col(i).maxCoeff(&idx);
417 assert(idx >= 0);
418 assert(idx < std::numeric_limits<uint8_t>::max());
419 final_output[j][input_begin+i] = (uint8_t) idx;
420 }
421 }
422
423#ifdef BILSTM_AND_DENSE_PROFILE
424 const auto after_linear = std::chrono::high_resolution_clock::now();
425 std::cerr << "output.cols()==" << output.cols() << " "
426 << "linear time: " << std::chrono::duration_cast<std::chrono::microseconds>(after_linear - before_linear).count() << " "
427 << std::endl;
428#endif
429
430
431 // Linear layer on top of RNN outputs - alternative way to calculate (not faster)
432 /*for (size_t j = 0; j < final_output.size(); j++)
433 {
434 M& linear_output = wb->lin_out[j];
435 linear_output = (linear[j].weight * output).colwise() + linear[j].bias;
436 }
437
438 for (size_t j = 0; j < final_output.size(); j++)
439 {
440 M& linear_output = wb->lin_out[j];
441
442 for (Eigen::Index i = output_begin - input_begin;
443 i < output_end - input_begin; i++)
444 {
445 Eigen::Index idx = 0;
446 typename M::Scalar v = linear_output.col(i).maxCoeff(&idx);
447 assert(idx >= 0);
448 assert(idx < std::numeric_limits<uint8_t>::max());
449 final_output[j][input_begin+i] = (uint8_t) idx;
450 }
451 }*/
452
453 return 0;
454 }
455
456protected:
457 inline void forward_pass(
458 const size_t hidden_size, // [in] the size of the hidden state
459 Eigen::Ref<const M> input, // [in] the pre-computed inputs
460 const MatrixWeight& weight_hh, // [in] the weights matrix
461#ifdef MATMUL_WITH_FACTORIZATION
462 const typename params_t::multiplier_t& mul,
463#endif
464 V& s, // [temp] preallocated space for results before gating
465 V& c, // [in/out] the cell state
466 M& output // [out] the output states
467 )
468 {
469 step_fw(hidden_size, 0, input.col(0).topRows(hidden_size * 4), c, output);
470
471#ifdef MATMUL_WITH_FACTORIZATION
472 V prev_state;
473#endif
474
475#ifdef BILSTM_AND_DENSE_PROFILE
476 std::chrono::duration<double> sum1(0), sum2(0);
477#endif
478 for (Eigen::Index t = 1; t < input.cols(); t++)
479 {
480#ifdef BILSTM_AND_DENSE_PROFILE
481 const auto before1 = std::chrono::high_resolution_clock::now();
482#endif
483
484#ifdef MATMUL_WITH_FACTORIZATION
485 /*
486 s.segment(0, hidden_size).noalias() = mul.matmul_input.permutationP() * output.block(0, t-1, hidden_size, 1);
487 mul.matmul_input.matrixLU().template triangularView<Eigen::UnitLower>().solveInPlace(s.segment(0, hidden_size));
488 mul.matmul_input.matrixLU().template triangularView<Eigen::Upper>().solveInPlace(s.segment(0, hidden_size));
489
490 s.segment(hidden_size, hidden_size) = mul.matmul_forget.permutationP() * output.block(0, t-1, hidden_size, 1);
491 mul.matmul_forget.matrixLU().template triangularView<Eigen::UnitLower>().solveInPlace(s.segment(hidden_size, hidden_size));
492 mul.matmul_forget.matrixLU().template triangularView<Eigen::Upper>().solveInPlace(s.segment(hidden_size, hidden_size));
493
494 s.segment(hidden_size*2, hidden_size) = mul.matmul_update.permutationP() * output.block(0, t-1, hidden_size, 1);
495 mul.matmul_update.matrixLU().template triangularView<Eigen::UnitLower>().solveInPlace(s.segment(hidden_size*2, hidden_size));
496 mul.matmul_update.matrixLU().template triangularView<Eigen::Upper>().solveInPlace(s.segment(hidden_size*2, hidden_size));
497
498 s.segment(hidden_size*3, hidden_size) = mul.matmul_output.permutationP() * output.block(0, t-1, hidden_size, 1);
499 mul.matmul_output.matrixLU().template triangularView<Eigen::UnitLower>().solveInPlace(s.segment(hidden_size*3, hidden_size));
500 mul.matmul_output.matrixLU().template triangularView<Eigen::Upper>().solveInPlace(s.segment(hidden_size*3, hidden_size));
501 */
502
503 prev_state = output.block(0, t-1, hidden_size, 1);
504 s.segment(0, hidden_size) = mul.matmul_input.solve(prev_state);
505 s.segment(hidden_size, hidden_size) = mul.matmul_forget.solve(prev_state);
506 s.segment(hidden_size*2, hidden_size) = mul.matmul_update.solve(prev_state);
507 s.segment(hidden_size*3, hidden_size) = mul.matmul_output.solve(prev_state);
508
509 s += input.col(t).topRows(hidden_size * 4);
510#else
511 if constexpr (std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
512 {
513 s = input.col(t).topRows(hidden_size * 4);
514 MatrixInput arg2 = (output.block(0, t-1, hidden_size, 1) * DATA_FRACTION_MULT).template cast<fixed_point_t>() ;
515 s.noalias() += ((weight_hh * arg2).template cast<T>() / WEIGHT_DATA_FRACTION_MULT);
516 }
517 else if constexpr (std::is_floating_point_v<AuxScalar>)
518 {
519 s = input.col(t).topRows(hidden_size * 4);
520 s.noalias() += weight_hh * output.block(0, t-1, hidden_size, 1);
521
522 //s = weight_hh * output.block(0, t-1, hidden_size, 1);
523 //s += input.col(t).topRows(hidden_size * 4);
524 }
525 else
526 {
527 static_assert((std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
528 || std::is_floating_point_v<AuxScalar>, "AuxScalar must be a signed integer or floating-point type");
529 }
530#endif
531
532#ifdef BILSTM_AND_DENSE_PROFILE
533 const auto after1 = std::chrono::high_resolution_clock::now();
534 sum1 += after1 - before1;
535
536 const auto before2 = std::chrono::high_resolution_clock::now();
537#endif
538 step_fw(hidden_size, t, s, c, output);
539
540#ifdef BILSTM_AND_DENSE_PROFILE
541 const auto after2 = std::chrono::high_resolution_clock::now();
542 sum2 += after2 - before2;
543#endif
544 }
545
546#ifdef BILSTM_AND_DENSE_PROFILE
547 std::cerr << "input.cols()==" << input.cols() << " "
548 << "step_fw avg time: " << std::chrono::duration_cast<std::chrono::microseconds>(sum2).count() << " "
549 << "in+recc avg time: " << std::chrono::duration_cast<std::chrono::microseconds>(sum1).count()
550 << std::endl;
551#endif
552 }
553
554 inline void backward_pass(
555 const size_t hidden_size, // [in] the size of the hidden state
556 Eigen::Ref<const M> input, // [in] the pre-computed inputs
557 const MatrixWeight& weight_hh, // [in] the weights matrix
558#ifdef MATMUL_WITH_FACTORIZATION
559 const typename params_t::multiplier_t& mul,
560#endif
561 V& s, // [temp] preallocated space for results before gating
562 V& c, // [in/out] the cell state
563 M& output // [out] the output states
564 )
565 {
566 int t = input.cols() - 1;
567 step_bw(hidden_size, t, input.col(t).bottomRows(hidden_size * 4), c, output);
568
569 for (t = input.cols() - 2; t >= 0; t--)
570 {
571 if constexpr (std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
572 {
573 s = input.col(t).bottomRows(hidden_size * 4);
574 MatrixInput arg2 = (output.block(hidden_size, t+1, hidden_size, 1) * DATA_FRACTION_MULT).template cast<fixed_point_t>() ;
575 s.noalias() += ((weight_hh * arg2).template cast<float>() / WEIGHT_DATA_FRACTION_MULT);
576 }
577 else if constexpr (std::is_floating_point_v<AuxScalar>)
578 {
579 s = input.col(t).bottomRows(hidden_size * 4);
580 s.noalias() += weight_hh * output.block(hidden_size, t+1, hidden_size, 1);
581 }
582 else
583 {
584 static_assert((std::is_integral_v<AuxScalar> && std::is_signed_v<AuxScalar>)
585 || std::is_floating_point_v<AuxScalar>, "AuxScalar must be a signed integer or floating-point type");
586 }
587 step_bw(hidden_size, t, s, c, output);
588 }
589 }
590
591 #define TANH(x) ( T(2) / ( T(1) + Eigen::exp( T(-2) * (x).array() ) ) - T(1) )
592 #define SIGMOID(x) ( T(1) / ( T(1) + Eigen::exp( - (x).array() ) ) )
593
594 inline void update_c(
595 const size_t hidden_size, // [in] the size of the hidden state
596 const V& s, // [in] the results before gating
597 V& c // [in/out] the cell state
598 )
599 {
600 // c = c * forget_gate = c * 1 / sigmoid(...)
601 c = c.array() / (1 + Eigen::exp( - s.segment(hidden_size, hidden_size).array() ) );
602
603 // c = c + input_gate * update_gate
604 c += ( SIGMOID(s.segment(0, hidden_size)).array() * TANH(s.segment(hidden_size * 2, hidden_size)).array() ).matrix();
605 }
606
607 inline void step_fw(
608 const size_t hidden_size, // [in] the size of the hidden state
609 const size_t t, // [in] step (the position in output)
610 const V& s, // [in] the results before gating
611 V& c, // [in/out] the cell state
612 M& output // [out] the matrix of output states
613 )
614 {
615 update_c(hidden_size, s, c);
616
617 // output = output_gate * tanh(c)
618 output.col(t).topRows(hidden_size).noalias() = (SIGMOID(s.segment(hidden_size * 3, hidden_size)).array() * TANH(c).array()).matrix();
619 }
620
621 inline void step_bw(
622 const size_t hidden_size, // [in] the size of the hidden state
623 const size_t t, // [in] step (the position in output)
624 const V& s, // [in] the results before gating
625 V& c, // [in/out] the cell state
626 M& output // [out] matrix of output states
627 )
628 {
629 update_c(hidden_size, s, c);
630
631 // output = output_gate * tanh(c)
632 output.col(t).bottomRows(hidden_size).noalias() = (SIGMOID(s.segment(hidden_size * 3, hidden_size)).array() * TANH(c).array()).matrix();
633 }
634};
635
636} // namespace eigen_impl
637} // namespace deeplima
638
639#endif
#define TANH(x)
#define SIGMOID(x)
Fusion of several torch modules implemented for inference in Eigen.
void step_fw(const size_t hidden_size, const size_t t, const V &s, V &c, M &output)
typename std::conditional< std::is_integral_v< AuxScalar > &&std::is_signed_v< AuxScalar >, Eigen::Matrix< fixed_point_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >, M >::type MatrixWeight
void step_bw(const size_t hidden_size, const size_t t, const V &s, V &c, M &output)
virtual void precompute_inputs(const std::shared_ptr< param_base_t > params, const M &inputs, M &outputs, int64_t first_column)
typename std::conditional< std::is_integral_v< AuxScalar > &&std::is_signed_v< AuxScalar >, Eigen::Matrix< fixed_point_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor >, M >::type MatrixInput
static constexpr fixed_point_t pow2(int bits)
void update_c(const size_t hidden_size, const V &s, V &c)
virtual size_t execute(std::shared_ptr< Op_Base::workbench_t > pwb, const M &input_matrix, const std::shared_ptr< param_base_t > pparams, std::vector< std::vector< uint8_t > > &final_output, size_t input_begin, size_t input_end, size_t output_begin, size_t output_end)
void forward_pass(const size_t hidden_size, Eigen::Ref< const M > input, const MatrixWeight &weight_hh, V &s, V &c, M &output)
virtual std::shared_ptr< Op_Base::workbench_t > create_workbench(uint32_t input_size, const std::shared_ptr< param_base_t > params, bool precomputed_input=false) const override
void backward_pass(const size_t hidden_size, Eigen::Ref< const M > input, const MatrixWeight &weight_hh, V &s, V &c, M &output)
Edit rules for lemmatizing words absent from the lemma dictionary.
workbench_t(uint32_t input_size, uint32_t hidden_size, const std::vector< uint32_t > &output_sizes, bool precomputed_input=false)
params_lstm_t< M, V > fw
Definition bilstm.h:51
params_lstm_t< M, V > bw
Definition bilstm.h:52