tesseract  4.00.00dev
lstm.cpp
Go to the documentation of this file.
1 // File: lstm.cpp
3 // Description: Long-term-short-term-memory Recurrent neural network.
4 // Author: Ray Smith
5 // Created: Wed May 01 17:43:06 PST 2013
6 //
7 // (C) Copyright 2013, Google Inc.
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
18 
19 #include "lstm.h"
20 
21 #ifdef _OPENMP
22 #include <omp.h>
23 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 
27 #include "fullyconnected.h"
28 #include "functions.h"
29 #include "networkscratch.h"
30 #include "tprintf.h"
31 
32 // Macros for openmp code if it is available, otherwise empty macros.
33 #ifdef _OPENMP
34 #define PARALLEL_IF_OPENMP(__num_threads) \
35  PRAGMA(omp parallel if (__num_threads > 1) num_threads(__num_threads)) { \
36  PRAGMA(omp sections nowait) { \
37  PRAGMA(omp section) {
38 #define SECTION_IF_OPENMP \
39  } \
40  PRAGMA(omp section) \
41  {
42 
43 #define END_PARALLEL_IF_OPENMP \
44  } \
45  } /* end of sections */ \
46  } /* end of parallel section */
47 
48 // Define the portable PRAGMA macro.
49 #ifdef _MSC_VER // Different _Pragma
50 #define PRAGMA(x) __pragma(x)
51 #else
52 #define PRAGMA(x) _Pragma(#x)
53 #endif // _MSC_VER
54 
55 #else // _OPENMP
56 #define PARALLEL_IF_OPENMP(__num_threads)
57 #define SECTION_IF_OPENMP
58 #define END_PARALLEL_IF_OPENMP
59 #endif // _OPENMP
60 
61 
62 namespace tesseract {
63 
64 // Max absolute value of state_. It is reasonably high to enable the state
65 // to count things.
66 const double kStateClip = 100.0;
67 // Max absolute value of gate_errors (the gradients).
68 const double kErrClip = 1.0f;
69 
70 LSTM::LSTM(const STRING& name, int ni, int ns, int no, bool two_dimensional,
71  NetworkType type)
72  : Network(type, name, ni, no),
73  na_(ni + ns),
74  ns_(ns),
75  nf_(0),
76  is_2d_(two_dimensional),
77  softmax_(NULL),
78  input_width_(0) {
79  if (two_dimensional) na_ += ns_;
80  if (type_ == NT_LSTM || type_ == NT_LSTM_SUMMARY) {
81  nf_ = 0;
82  // networkbuilder ensures this is always true.
83  ASSERT_HOST(no == ns);
84  } else if (type_ == NT_LSTM_SOFTMAX || type_ == NT_LSTM_SOFTMAX_ENCODED) {
85  nf_ = type_ == NT_LSTM_SOFTMAX ? no_ : IntCastRounded(ceil(log2(no_)));
86  softmax_ = new FullyConnected("LSTM Softmax", ns_, no_, NT_SOFTMAX);
87  } else {
88  tprintf("%d is invalid type of LSTM!\n", type);
89  ASSERT_HOST(false);
90  }
91  na_ += nf_;
92 }
93 
94 LSTM::~LSTM() { delete softmax_; }
95 
96 // Returns the shape output from the network given an input shape (which may
97 // be partially unknown ie zero).
98 StaticShape LSTM::OutputShape(const StaticShape& input_shape) const {
99  StaticShape result = input_shape;
100  result.set_depth(no_);
101  if (type_ == NT_LSTM_SUMMARY) result.set_width(1);
102  if (softmax_ != NULL) return softmax_->OutputShape(result);
103  return result;
104 }
105 
106 // Suspends/Enables training by setting the training_ flag. Serialize and
107 // DeSerialize only operate on the run-time data if state is false.
109  if (state == TS_RE_ENABLE) {
110  // Enable only from temp disabled.
112  } else if (state == TS_TEMP_DISABLE) {
113  // Temp disable only from enabled.
114  if (training_ == TS_ENABLED) training_ = state;
115  } else {
116  if (state == TS_ENABLED && training_ != TS_ENABLED) {
117  for (int w = 0; w < WT_COUNT; ++w) {
118  if (w == GFS && !Is2D()) continue;
119  gate_weights_[w].InitBackward();
120  }
121  }
122  training_ = state;
123  }
124  if (softmax_ != NULL) softmax_->SetEnableTraining(state);
125 }
126 
127 // Sets up the network for training. Initializes weights using weights of
128 // scale `range` picked according to the random number generator `randomizer`.
129 int LSTM::InitWeights(float range, TRand* randomizer) {
130  Network::SetRandomizer(randomizer);
131  num_weights_ = 0;
132  for (int w = 0; w < WT_COUNT; ++w) {
133  if (w == GFS && !Is2D()) continue;
134  num_weights_ += gate_weights_[w].InitWeightsFloat(
135  ns_, na_ + 1, TestFlag(NF_ADA_GRAD), range, randomizer);
136  }
137  if (softmax_ != NULL) {
138  num_weights_ += softmax_->InitWeights(range, randomizer);
139  }
140  return num_weights_;
141 }
142 
143 // Converts a float network to an int network.
145  for (int w = 0; w < WT_COUNT; ++w) {
146  if (w == GFS && !Is2D()) continue;
147  gate_weights_[w].ConvertToInt();
148  }
149  if (softmax_ != NULL) {
150  softmax_->ConvertToInt();
151  }
152 }
153 
154 // Sets up the network for training using the given weight_range.
156  for (int w = 0; w < WT_COUNT; ++w) {
157  if (w == GFS && !Is2D()) continue;
158  STRING msg = name_;
159  msg.add_str_int(" Gate weights ", w);
160  gate_weights_[w].Debug2D(msg.string());
161  }
162  if (softmax_ != NULL) {
163  softmax_->DebugWeights();
164  }
165 }
166 
167 // Writes to the given file. Returns false in case of error.
168 bool LSTM::Serialize(TFile* fp) const {
169  if (!Network::Serialize(fp)) return false;
170  if (fp->FWrite(&na_, sizeof(na_), 1) != 1) return false;
171  for (int w = 0; w < WT_COUNT; ++w) {
172  if (w == GFS && !Is2D()) continue;
173  if (!gate_weights_[w].Serialize(IsTraining(), fp)) return false;
174  }
175  if (softmax_ != NULL && !softmax_->Serialize(fp)) return false;
176  return true;
177 }
178 
179 // Reads from the given file. Returns false in case of error.
180 
182  if (fp->FReadEndian(&na_, sizeof(na_), 1) != 1) return false;
183  if (type_ == NT_LSTM_SOFTMAX) {
184  nf_ = no_;
185  } else if (type_ == NT_LSTM_SOFTMAX_ENCODED) {
186  nf_ = IntCastRounded(ceil(log2(no_)));
187  } else {
188  nf_ = 0;
189  }
190  is_2d_ = false;
191  for (int w = 0; w < WT_COUNT; ++w) {
192  if (w == GFS && !Is2D()) continue;
193  if (!gate_weights_[w].DeSerialize(IsTraining(), fp)) return false;
194  if (w == CI) {
195  ns_ = gate_weights_[CI].NumOutputs();
196  is_2d_ = na_ - nf_ == ni_ + 2 * ns_;
197  }
198  }
199  delete softmax_;
201  softmax_ = static_cast<FullyConnected*>(Network::CreateFromFile(fp));
202  if (softmax_ == nullptr) return false;
203  } else {
204  softmax_ = nullptr;
205  }
206  return true;
207 }
208 
209 // Runs forward propagation of activations on the input line.
210 // See NetworkCpp for a detailed discussion of the arguments.
211 void LSTM::Forward(bool debug, const NetworkIO& input,
212  const TransposedArray* input_transpose,
213  NetworkScratch* scratch, NetworkIO* output) {
214  input_map_ = input.stride_map();
215  input_width_ = input.Width();
216  if (softmax_ != NULL)
217  output->ResizeFloat(input, no_);
218  else if (type_ == NT_LSTM_SUMMARY)
219  output->ResizeXTo1(input, no_);
220  else
221  output->Resize(input, no_);
222  ResizeForward(input);
223  // Temporary storage of forward computation for each gate.
225  for (int i = 0; i < WT_COUNT; ++i) temp_lines[i].Init(ns_, scratch);
226  // Single timestep buffers for the current/recurrent output and state.
227  NetworkScratch::FloatVec curr_state, curr_output;
228  curr_state.Init(ns_, scratch);
229  ZeroVector<double>(ns_, curr_state);
230  curr_output.Init(ns_, scratch);
231  ZeroVector<double>(ns_, curr_output);
232  // Rotating buffers of width buf_width allow storage of the state and output
233  // for the other dimension, used only when working in true 2D mode. The width
234  // is enough to hold an entire strip of the major direction.
235  int buf_width = Is2D() ? input_map_.Size(FD_WIDTH) : 1;
237  if (Is2D()) {
238  states.init_to_size(buf_width, NetworkScratch::FloatVec());
239  outputs.init_to_size(buf_width, NetworkScratch::FloatVec());
240  for (int i = 0; i < buf_width; ++i) {
241  states[i].Init(ns_, scratch);
242  ZeroVector<double>(ns_, states[i]);
243  outputs[i].Init(ns_, scratch);
244  ZeroVector<double>(ns_, outputs[i]);
245  }
246  }
247  // Used only if a softmax LSTM.
248  NetworkScratch::FloatVec softmax_output;
249  NetworkScratch::IO int_output;
250  if (softmax_ != NULL) {
251  softmax_output.Init(no_, scratch);
252  ZeroVector<double>(no_, softmax_output);
253  if (input.int_mode()) int_output.Resize2d(true, 1, ns_, scratch);
254  softmax_->SetupForward(input, NULL);
255  }
256  NetworkScratch::FloatVec curr_input;
257  curr_input.Init(na_, scratch);
258  StrideMap::Index src_index(input_map_);
259  // Used only by NT_LSTM_SUMMARY.
260  StrideMap::Index dest_index(output->stride_map());
261  do {
262  int t = src_index.t();
263  // True if there is a valid old state for the 2nd dimension.
264  bool valid_2d = Is2D();
265  if (valid_2d) {
266  StrideMap::Index dim_index(src_index);
267  if (!dim_index.AddOffset(-1, FD_HEIGHT)) valid_2d = false;
268  }
269  // Index of the 2-D revolving buffers (outputs, states).
270  int mod_t = Modulo(t, buf_width); // Current timestep.
271  // Setup the padded input in source.
272  source_.CopyTimeStepGeneral(t, 0, ni_, input, t, 0);
273  if (softmax_ != NULL) {
274  source_.WriteTimeStepPart(t, ni_, nf_, softmax_output);
275  }
276  source_.WriteTimeStepPart(t, ni_ + nf_, ns_, curr_output);
277  if (Is2D())
278  source_.WriteTimeStepPart(t, ni_ + nf_ + ns_, ns_, outputs[mod_t]);
279  if (!source_.int_mode()) source_.ReadTimeStep(t, curr_input);
280  // Matrix multiply the inputs with the source.
282  // It looks inefficient to create the threads on each t iteration, but the
283  // alternative of putting the parallel outside the t loop, a single around
284  // the t-loop and then tasks in place of the sections is a *lot* slower.
285  // Cell inputs.
286  if (source_.int_mode())
287  gate_weights_[CI].MatrixDotVector(source_.i(t), temp_lines[CI]);
288  else
289  gate_weights_[CI].MatrixDotVector(curr_input, temp_lines[CI]);
290  FuncInplace<GFunc>(ns_, temp_lines[CI]);
291 
293  // Input Gates.
294  if (source_.int_mode())
295  gate_weights_[GI].MatrixDotVector(source_.i(t), temp_lines[GI]);
296  else
297  gate_weights_[GI].MatrixDotVector(curr_input, temp_lines[GI]);
298  FuncInplace<FFunc>(ns_, temp_lines[GI]);
299 
301  // 1-D forget gates.
302  if (source_.int_mode())
303  gate_weights_[GF1].MatrixDotVector(source_.i(t), temp_lines[GF1]);
304  else
305  gate_weights_[GF1].MatrixDotVector(curr_input, temp_lines[GF1]);
306  FuncInplace<FFunc>(ns_, temp_lines[GF1]);
307 
308  // 2-D forget gates.
309  if (Is2D()) {
310  if (source_.int_mode())
311  gate_weights_[GFS].MatrixDotVector(source_.i(t), temp_lines[GFS]);
312  else
313  gate_weights_[GFS].MatrixDotVector(curr_input, temp_lines[GFS]);
314  FuncInplace<FFunc>(ns_, temp_lines[GFS]);
315  }
316 
318  // Output gates.
319  if (source_.int_mode())
320  gate_weights_[GO].MatrixDotVector(source_.i(t), temp_lines[GO]);
321  else
322  gate_weights_[GO].MatrixDotVector(curr_input, temp_lines[GO]);
323  FuncInplace<FFunc>(ns_, temp_lines[GO]);
325 
326  // Apply forget gate to state.
327  MultiplyVectorsInPlace(ns_, temp_lines[GF1], curr_state);
328  if (Is2D()) {
329  // Max-pool the forget gates (in 2-d) instead of blindly adding.
330  inT8* which_fg_col = which_fg_[t];
331  memset(which_fg_col, 1, ns_ * sizeof(which_fg_col[0]));
332  if (valid_2d) {
333  const double* stepped_state = states[mod_t];
334  for (int i = 0; i < ns_; ++i) {
335  if (temp_lines[GF1][i] < temp_lines[GFS][i]) {
336  curr_state[i] = temp_lines[GFS][i] * stepped_state[i];
337  which_fg_col[i] = 2;
338  }
339  }
340  }
341  }
342  MultiplyAccumulate(ns_, temp_lines[CI], temp_lines[GI], curr_state);
343  // Clip curr_state to a sane range.
344  ClipVector<double>(ns_, -kStateClip, kStateClip, curr_state);
345  if (IsTraining()) {
346  // Save the gate node values.
347  node_values_[CI].WriteTimeStep(t, temp_lines[CI]);
348  node_values_[GI].WriteTimeStep(t, temp_lines[GI]);
349  node_values_[GF1].WriteTimeStep(t, temp_lines[GF1]);
350  node_values_[GO].WriteTimeStep(t, temp_lines[GO]);
351  if (Is2D()) node_values_[GFS].WriteTimeStep(t, temp_lines[GFS]);
352  }
353  FuncMultiply<HFunc>(curr_state, temp_lines[GO], ns_, curr_output);
354  if (IsTraining()) state_.WriteTimeStep(t, curr_state);
355  if (softmax_ != NULL) {
356  if (input.int_mode()) {
357  int_output->WriteTimeStep(0, curr_output);
358  softmax_->ForwardTimeStep(NULL, int_output->i(0), t, softmax_output);
359  } else {
360  softmax_->ForwardTimeStep(curr_output, NULL, t, softmax_output);
361  }
362  output->WriteTimeStep(t, softmax_output);
364  CodeInBinary(no_, nf_, softmax_output);
365  }
366  } else if (type_ == NT_LSTM_SUMMARY) {
367  // Output only at the end of a row.
368  if (src_index.IsLast(FD_WIDTH)) {
369  output->WriteTimeStep(dest_index.t(), curr_output);
370  dest_index.Increment();
371  }
372  } else {
373  output->WriteTimeStep(t, curr_output);
374  }
375  // Save states for use by the 2nd dimension only if needed.
376  if (Is2D()) {
377  CopyVector(ns_, curr_state, states[mod_t]);
378  CopyVector(ns_, curr_output, outputs[mod_t]);
379  }
380  // Always zero the states at the end of every row, but only for the major
381  // direction. The 2-D state remains intact.
382  if (src_index.IsLast(FD_WIDTH)) {
383  ZeroVector<double>(ns_, curr_state);
384  ZeroVector<double>(ns_, curr_output);
385  }
386  } while (src_index.Increment());
387 #if DEBUG_DETAIL > 0
388  tprintf("Source:%s\n", name_.string());
389  source_.Print(10);
390  tprintf("State:%s\n", name_.string());
391  state_.Print(10);
392  tprintf("Output:%s\n", name_.string());
393  output->Print(10);
394 #endif
395  if (debug) DisplayForward(*output);
396 }
397 
398 // Runs backward propagation of errors on the deltas line.
399 // See NetworkCpp for a detailed discussion of the arguments.
400 bool LSTM::Backward(bool debug, const NetworkIO& fwd_deltas,
401  NetworkScratch* scratch,
402  NetworkIO* back_deltas) {
403  if (debug) DisplayBackward(fwd_deltas);
404  back_deltas->ResizeToMap(fwd_deltas.int_mode(), input_map_, ni_);
405  // ======Scratch space.======
406  // Output errors from deltas with recurrence from sourceerr.
407  NetworkScratch::FloatVec outputerr;
408  outputerr.Init(ns_, scratch);
409  // Recurrent error in the state/source.
410  NetworkScratch::FloatVec curr_stateerr, curr_sourceerr;
411  curr_stateerr.Init(ns_, scratch);
412  curr_sourceerr.Init(na_, scratch);
413  ZeroVector<double>(ns_, curr_stateerr);
414  ZeroVector<double>(na_, curr_sourceerr);
415  // Errors in the gates.
416  NetworkScratch::FloatVec gate_errors[WT_COUNT];
417  for (int g = 0; g < WT_COUNT; ++g) gate_errors[g].Init(ns_, scratch);
418  // Rotating buffers of width buf_width allow storage of the recurrent time-
419  // steps used only for true 2-D. Stores one full strip of the major direction.
420  int buf_width = Is2D() ? input_map_.Size(FD_WIDTH) : 1;
421  GenericVector<NetworkScratch::FloatVec> stateerr, sourceerr;
422  if (Is2D()) {
423  stateerr.init_to_size(buf_width, NetworkScratch::FloatVec());
424  sourceerr.init_to_size(buf_width, NetworkScratch::FloatVec());
425  for (int t = 0; t < buf_width; ++t) {
426  stateerr[t].Init(ns_, scratch);
427  sourceerr[t].Init(na_, scratch);
428  ZeroVector<double>(ns_, stateerr[t]);
429  ZeroVector<double>(na_, sourceerr[t]);
430  }
431  }
432  // Parallel-generated sourceerr from each of the gates.
433  NetworkScratch::FloatVec sourceerr_temps[WT_COUNT];
434  for (int w = 0; w < WT_COUNT; ++w)
435  sourceerr_temps[w].Init(na_, scratch);
436  int width = input_width_;
437  // Transposed gate errors stored over all timesteps for sum outer.
439  for (int w = 0; w < WT_COUNT; ++w) {
440  gate_errors_t[w].Init(ns_, width, scratch);
441  }
442  // Used only if softmax_ != NULL.
443  NetworkScratch::FloatVec softmax_errors;
444  NetworkScratch::GradientStore softmax_errors_t;
445  if (softmax_ != NULL) {
446  softmax_errors.Init(no_, scratch);
447  softmax_errors_t.Init(no_, width, scratch);
448  }
449  double state_clip = Is2D() ? 9.0 : 4.0;
450 #if DEBUG_DETAIL > 1
451  tprintf("fwd_deltas:%s\n", name_.string());
452  fwd_deltas.Print(10);
453 #endif
454  StrideMap::Index dest_index(input_map_);
455  dest_index.InitToLast();
456  // Used only by NT_LSTM_SUMMARY.
457  StrideMap::Index src_index(fwd_deltas.stride_map());
458  src_index.InitToLast();
459  do {
460  int t = dest_index.t();
461  bool at_last_x = dest_index.IsLast(FD_WIDTH);
462  // up_pos is the 2-D back step, down_pos is the 2-D fwd step, and are only
463  // valid if >= 0, which is true if 2d and not on the top/bottom.
464  int up_pos = -1;
465  int down_pos = -1;
466  if (Is2D()) {
467  if (dest_index.index(FD_HEIGHT) > 0) {
468  StrideMap::Index up_index(dest_index);
469  if (up_index.AddOffset(-1, FD_HEIGHT)) up_pos = up_index.t();
470  }
471  if (!dest_index.IsLast(FD_HEIGHT)) {
472  StrideMap::Index down_index(dest_index);
473  if (down_index.AddOffset(1, FD_HEIGHT)) down_pos = down_index.t();
474  }
475  }
476  // Index of the 2-D revolving buffers (sourceerr, stateerr).
477  int mod_t = Modulo(t, buf_width); // Current timestep.
478  // Zero the state in the major direction only at the end of every row.
479  if (at_last_x) {
480  ZeroVector<double>(na_, curr_sourceerr);
481  ZeroVector<double>(ns_, curr_stateerr);
482  }
483  // Setup the outputerr.
484  if (type_ == NT_LSTM_SUMMARY) {
485  if (dest_index.IsLast(FD_WIDTH)) {
486  fwd_deltas.ReadTimeStep(src_index.t(), outputerr);
487  src_index.Decrement();
488  } else {
489  ZeroVector<double>(ns_, outputerr);
490  }
491  } else if (softmax_ == NULL) {
492  fwd_deltas.ReadTimeStep(t, outputerr);
493  } else {
494  softmax_->BackwardTimeStep(fwd_deltas, t, softmax_errors,
495  softmax_errors_t.get(), outputerr);
496  }
497  if (!at_last_x)
498  AccumulateVector(ns_, curr_sourceerr + ni_ + nf_, outputerr);
499  if (down_pos >= 0)
500  AccumulateVector(ns_, sourceerr[mod_t] + ni_ + nf_ + ns_, outputerr);
501  // Apply the 1-d forget gates.
502  if (!at_last_x) {
503  const float* next_node_gf1 = node_values_[GF1].f(t + 1);
504  for (int i = 0; i < ns_; ++i) {
505  curr_stateerr[i] *= next_node_gf1[i];
506  }
507  }
508  if (Is2D() && t + 1 < width) {
509  for (int i = 0; i < ns_; ++i) {
510  if (which_fg_[t + 1][i] != 1) curr_stateerr[i] = 0.0;
511  }
512  if (down_pos >= 0) {
513  const float* right_node_gfs = node_values_[GFS].f(down_pos);
514  const double* right_stateerr = stateerr[mod_t];
515  for (int i = 0; i < ns_; ++i) {
516  if (which_fg_[down_pos][i] == 2) {
517  curr_stateerr[i] += right_stateerr[i] * right_node_gfs[i];
518  }
519  }
520  }
521  }
522  state_.FuncMultiply3Add<HPrime>(node_values_[GO], t, outputerr,
523  curr_stateerr);
524  // Clip stateerr_ to a sane range.
525  ClipVector<double>(ns_, -state_clip, state_clip, curr_stateerr);
526 #if DEBUG_DETAIL > 1
527  if (t + 10 > width) {
528  tprintf("t=%d, stateerr=", t);
529  for (int i = 0; i < ns_; ++i)
530  tprintf(" %g,%g,%g", curr_stateerr[i], outputerr[i],
531  curr_sourceerr[ni_ + nf_ + i]);
532  tprintf("\n");
533  }
534 #endif
535  // Matrix multiply to get the source errors.
537 
538  // Cell inputs.
539  node_values_[CI].FuncMultiply3<GPrime>(t, node_values_[GI], t,
540  curr_stateerr, gate_errors[CI]);
541  ClipVector(ns_, -kErrClip, kErrClip, gate_errors[CI].get());
542  gate_weights_[CI].VectorDotMatrix(gate_errors[CI], sourceerr_temps[CI]);
543  gate_errors_t[CI].get()->WriteStrided(t, gate_errors[CI]);
544 
546  // Input Gates.
547  node_values_[GI].FuncMultiply3<FPrime>(t, node_values_[CI], t,
548  curr_stateerr, gate_errors[GI]);
549  ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GI].get());
550  gate_weights_[GI].VectorDotMatrix(gate_errors[GI], sourceerr_temps[GI]);
551  gate_errors_t[GI].get()->WriteStrided(t, gate_errors[GI]);
552 
554  // 1-D forget Gates.
555  if (t > 0) {
556  node_values_[GF1].FuncMultiply3<FPrime>(t, state_, t - 1, curr_stateerr,
557  gate_errors[GF1]);
558  ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GF1].get());
559  gate_weights_[GF1].VectorDotMatrix(gate_errors[GF1],
560  sourceerr_temps[GF1]);
561  } else {
562  memset(gate_errors[GF1], 0, ns_ * sizeof(gate_errors[GF1][0]));
563  memset(sourceerr_temps[GF1], 0, na_ * sizeof(*sourceerr_temps[GF1]));
564  }
565  gate_errors_t[GF1].get()->WriteStrided(t, gate_errors[GF1]);
566 
567  // 2-D forget Gates.
568  if (up_pos >= 0) {
569  node_values_[GFS].FuncMultiply3<FPrime>(t, state_, up_pos, curr_stateerr,
570  gate_errors[GFS]);
571  ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GFS].get());
572  gate_weights_[GFS].VectorDotMatrix(gate_errors[GFS],
573  sourceerr_temps[GFS]);
574  } else {
575  memset(gate_errors[GFS], 0, ns_ * sizeof(gate_errors[GFS][0]));
576  memset(sourceerr_temps[GFS], 0, na_ * sizeof(*sourceerr_temps[GFS]));
577  }
578  if (Is2D()) gate_errors_t[GFS].get()->WriteStrided(t, gate_errors[GFS]);
579 
581  // Output gates.
582  state_.Func2Multiply3<HFunc, FPrime>(node_values_[GO], t, outputerr,
583  gate_errors[GO]);
584  ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GO].get());
585  gate_weights_[GO].VectorDotMatrix(gate_errors[GO], sourceerr_temps[GO]);
586  gate_errors_t[GO].get()->WriteStrided(t, gate_errors[GO]);
588 
589  SumVectors(na_, sourceerr_temps[CI], sourceerr_temps[GI],
590  sourceerr_temps[GF1], sourceerr_temps[GO], sourceerr_temps[GFS],
591  curr_sourceerr);
592  back_deltas->WriteTimeStep(t, curr_sourceerr);
593  // Save states for use by the 2nd dimension only if needed.
594  if (Is2D()) {
595  CopyVector(ns_, curr_stateerr, stateerr[mod_t]);
596  CopyVector(na_, curr_sourceerr, sourceerr[mod_t]);
597  }
598  } while (dest_index.Decrement());
599 #if DEBUG_DETAIL > 2
600  for (int w = 0; w < WT_COUNT; ++w) {
601  tprintf("%s gate errors[%d]\n", name_.string(), w);
602  gate_errors_t[w].get()->PrintUnTransposed(10);
603  }
604 #endif
605  // Transposed source_ used to speed-up SumOuter.
606  NetworkScratch::GradientStore source_t, state_t;
607  source_t.Init(na_, width, scratch);
608  source_.Transpose(source_t.get());
609  state_t.Init(ns_, width, scratch);
610  state_.Transpose(state_t.get());
611 #ifdef _OPENMP
612 #pragma omp parallel for num_threads(GFS) if (!Is2D())
613 #endif
614  for (int w = 0; w < WT_COUNT; ++w) {
615  if (w == GFS && !Is2D()) continue;
616  gate_weights_[w].SumOuterTransposed(*gate_errors_t[w], *source_t, false);
617  }
618  if (softmax_ != NULL) {
619  softmax_->FinishBackward(*softmax_errors_t);
620  }
621  if (needs_to_backprop_) {
622  // Normalize the inputerr in back_deltas.
623  back_deltas->CopyWithNormalization(*back_deltas, fwd_deltas);
624  return true;
625  }
626  return false;
627 }
628 
629 // Updates the weights using the given learning rate and momentum.
630 // num_samples is the quotient to be used in the adagrad computation iff
631 // use_ada_grad_ is true.
632 void LSTM::Update(float learning_rate, float momentum, int num_samples) {
633 #if DEBUG_DETAIL > 3
634  PrintW();
635 #endif
636  for (int w = 0; w < WT_COUNT; ++w) {
637  if (w == GFS && !Is2D()) continue;
638  gate_weights_[w].Update(learning_rate, momentum, num_samples);
639  }
640  if (softmax_ != NULL) {
641  softmax_->Update(learning_rate, momentum, num_samples);
642  }
643 #if DEBUG_DETAIL > 3
644  PrintDW();
645 #endif
646 }
647 
648 // Sums the products of weight updates in *this and other, splitting into
649 // positive (same direction) in *same and negative (different direction) in
650 // *changed.
651 void LSTM::CountAlternators(const Network& other, double* same,
652  double* changed) const {
653  ASSERT_HOST(other.type() == type_);
654  const LSTM* lstm = static_cast<const LSTM*>(&other);
655  for (int w = 0; w < WT_COUNT; ++w) {
656  if (w == GFS && !Is2D()) continue;
657  gate_weights_[w].CountAlternators(lstm->gate_weights_[w], same, changed);
658  }
659  if (softmax_ != NULL) {
660  softmax_->CountAlternators(*lstm->softmax_, same, changed);
661  }
662 }
663 
664 // Prints the weights for debug purposes.
665 void LSTM::PrintW() {
666  tprintf("Weight state:%s\n", name_.string());
667  for (int w = 0; w < WT_COUNT; ++w) {
668  if (w == GFS && !Is2D()) continue;
669  tprintf("Gate %d, inputs\n", w);
670  for (int i = 0; i < ni_; ++i) {
671  tprintf("Row %d:", i);
672  for (int s = 0; s < ns_; ++s)
673  tprintf(" %g", gate_weights_[w].GetWeights(s)[i]);
674  tprintf("\n");
675  }
676  tprintf("Gate %d, outputs\n", w);
677  for (int i = ni_; i < ni_ + ns_; ++i) {
678  tprintf("Row %d:", i - ni_);
679  for (int s = 0; s < ns_; ++s)
680  tprintf(" %g", gate_weights_[w].GetWeights(s)[i]);
681  tprintf("\n");
682  }
683  tprintf("Gate %d, bias\n", w);
684  for (int s = 0; s < ns_; ++s)
685  tprintf(" %g", gate_weights_[w].GetWeights(s)[na_]);
686  tprintf("\n");
687  }
688 }
689 
690 // Prints the weight deltas for debug purposes.
692  tprintf("Delta state:%s\n", name_.string());
693  for (int w = 0; w < WT_COUNT; ++w) {
694  if (w == GFS && !Is2D()) continue;
695  tprintf("Gate %d, inputs\n", w);
696  for (int i = 0; i < ni_; ++i) {
697  tprintf("Row %d:", i);
698  for (int s = 0; s < ns_; ++s)
699  tprintf(" %g", gate_weights_[w].GetDW(s, i));
700  tprintf("\n");
701  }
702  tprintf("Gate %d, outputs\n", w);
703  for (int i = ni_; i < ni_ + ns_; ++i) {
704  tprintf("Row %d:", i - ni_);
705  for (int s = 0; s < ns_; ++s)
706  tprintf(" %g", gate_weights_[w].GetDW(s, i));
707  tprintf("\n");
708  }
709  tprintf("Gate %d, bias\n", w);
710  for (int s = 0; s < ns_; ++s)
711  tprintf(" %g", gate_weights_[w].GetDW(s, na_));
712  tprintf("\n");
713  }
714 }
715 
716 // Resizes forward data to cope with an input image of the given width.
717 void LSTM::ResizeForward(const NetworkIO& input) {
718  source_.Resize(input, na_);
719  which_fg_.ResizeNoInit(input.Width(), ns_);
720  if (IsTraining()) {
721  state_.ResizeFloat(input, ns_);
722  for (int w = 0; w < WT_COUNT; ++w) {
723  if (w == GFS && !Is2D()) continue;
724  node_values_[w].ResizeFloat(input, ns_);
725  }
726  }
727 }
728 
729 
730 } // namespace tesseract.
virtual void CountAlternators(const Network &other, double *same, double *changed) const
Definition: lstm.cpp:651
const double kStateClip
Definition: lstm.cpp:66
void add_str_int(const char *str, int number)
Definition: strngs.cpp:381
bool AddOffset(int offset, FlexDimensions dimension)
Definition: stridemap.cpp:62
void ReadTimeStep(int t, double *output) const
Definition: networkio.cpp:598
bool needs_to_backprop_
Definition: network.h:287
bool Is2D() const
Definition: lstm.h:117
void Debug2D(const char *msg)
int Width() const
Definition: networkio.h:107
void AccumulateVector(int n, const double *src, double *dest)
Definition: functions.h:191
virtual void Update(float learning_rate, float momentum, int num_samples)
int index(FlexDimensions dimension) const
Definition: stridemap.h:60
float * f(int t)
Definition: networkio.h:115
virtual void SetRandomizer(TRand *randomizer)
Definition: network.cpp:140
void init_to_size(int size, T t)
void MatrixDotVector(const double *u, double *v) const
void DisplayForward(const NetworkIO &matrix)
Definition: network.cpp:285
void MultiplyAccumulate(int n, const double *u, const double *v, double *out)
Definition: functions.h:201
void CopyVector(int n, const double *src, double *dest)
Definition: functions.h:186
NetworkType type() const
Definition: network.h:112
#define tprintf(...)
Definition: tprintf.h:31
static Network * CreateFromFile(TFile *fp)
Definition: network.cpp:203
const char * string() const
Definition: strngs.cpp:198
void Resize(const NetworkIO &src, int num_features)
Definition: networkio.h:45
void VectorDotMatrix(const double *u, double *v) const
void WriteStrided(int t, const float *data)
Definition: weightmatrix.h:37
void CountAlternators(const WeightMatrix &other, double *same, double *changed) const
bool IsTraining() const
Definition: network.h:115
int FReadEndian(void *buffer, int size, int count)
Definition: serialis.cpp:97
#define SECTION_IF_OPENMP
Definition: lstm.cpp:57
int IntCastRounded(double x)
Definition: helpers.h:179
bool int_mode() const
Definition: networkio.h:127
TrainingState
Definition: network.h:92
virtual void ConvertToInt()
Definition: lstm.cpp:144
#define ASSERT_HOST(x)
Definition: errcode.h:84
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)
Definition: lstm.cpp:400
int Size(FlexDimensions dimension) const
Definition: stridemap.h:116
void SumVectors(int n, const double *v1, const double *v2, const double *v3, const double *v4, const double *v5, double *sum)
Definition: functions.h:209
virtual void Update(float learning_rate, float momentum, int num_samples)
Definition: lstm.cpp:632
void CodeInBinary(int n, int nf, double *vec)
Definition: functions.h:231
TrainingState training_
Definition: network.h:286
virtual bool DeSerialize(TFile *fp)
Definition: lstm.cpp:181
#define PARALLEL_IF_OPENMP(__num_threads)
Definition: lstm.cpp:56
Definition: strngs.h:45
void Init(int size, NetworkScratch *scratch)
bool TestFlag(NetworkFlags flag) const
Definition: network.h:144
bool IsLast(FlexDimensions dimension) const
Definition: stridemap.cpp:37
LSTM(const STRING &name, int num_inputs, int num_states, int num_outputs, bool two_dimensional, NetworkType type)
Definition: lstm.cpp:70
virtual void SetEnableTraining(TrainingState state)
void CopyTimeStepGeneral(int dest_t, int dest_offset, int num_features, const NetworkIO &src, int src_t, int src_offset)
Definition: networkio.cpp:393
int FWrite(const void *buffer, int size, int count)
Definition: serialis.cpp:148
void SetupForward(const NetworkIO &input, const TransposedArray *input_transpose)
void CopyWithNormalization(const NetworkIO &src, const NetworkIO &scale)
Definition: networkio.cpp:831
void Update(double learning_rate, double momentum, int num_samples)
void PrintDW()
Definition: lstm.cpp:691
const double kErrClip
Definition: lstm.cpp:68
void ResizeNoInit(int size1, int size2)
Definition: matrix.h:86
void ResizeFloat(const NetworkIO &src, int num_features)
Definition: networkio.h:52
virtual int InitWeights(float range, TRand *randomizer)
Definition: lstm.cpp:129
NetworkType
Definition: network.h:43
int8_t inT8
Definition: host.h:34
NetworkType type_
Definition: network.h:285
void MultiplyVectorsInPlace(int n, const double *src, double *inout)
Definition: functions.h:196
int InitWeightsFloat(int no, int ni, bool ada_grad, float weight_range, TRand *randomizer)
void ForwardTimeStep(const double *d_input, const inT8 *i_input, int t, double *output_line)
void ResizeXTo1(const NetworkIO &src, int num_features)
Definition: networkio.cpp:70
void Print(int num) const
Definition: networkio.cpp:366
virtual ~LSTM()
Definition: lstm.cpp:94
virtual void SetEnableTraining(TrainingState state)
Definition: lstm.cpp:108
const inT8 * i(int t) const
Definition: networkio.h:123
const StrideMap & stride_map() const
Definition: networkio.h:133
virtual void DebugWeights()
Definition: lstm.cpp:155
virtual void Forward(bool debug, const NetworkIO &input, const TransposedArray *input_transpose, NetworkScratch *scratch, NetworkIO *output)
Definition: lstm.cpp:211
void Init(int size1, int size2, NetworkScratch *scratch)
virtual StaticShape OutputShape(const StaticShape &input_shape) const
void Resize2d(bool int_mode, int width, int num_features, NetworkScratch *scratch)
void WriteTimeStep(int t, const double *input)
Definition: networkio.cpp:645
void PrintW()
Definition: lstm.cpp:665
void Transpose(TransposedArray *dest) const
Definition: networkio.cpp:964
void Func2Multiply3(const NetworkIO &v_io, int t, const double *w, double *product) const
Definition: networkio.h:315
virtual bool Serialize(TFile *fp) const
Definition: lstm.cpp:168
void ClipVector(int n, T lower, T upper, T *vec)
Definition: functions.h:225
virtual bool Serialize(TFile *fp) const
Definition: network.cpp:153
#define END_PARALLEL_IF_OPENMP
Definition: lstm.cpp:58
void ResizeToMap(bool int_mode, const StrideMap &stride_map, int num_features)
Definition: networkio.cpp:45
void WriteTimeStepPart(int t, int offset, int num_features, const double *input)
Definition: networkio.cpp:651
void DisplayBackward(const NetworkIO &matrix)
Definition: network.cpp:296
virtual bool Serialize(TFile *fp) const
inT32 num_weights_
Definition: network.h:291
void SumOuterTransposed(const TransposedArray &u, const TransposedArray &v, bool parallel)
virtual void CountAlternators(const Network &other, double *same, double *changed) const
void set_width(int value)
Definition: static_shape.h:45
void FuncMultiply3Add(const NetworkIO &v_io, int t, const double *w, double *product) const
Definition: networkio.h:299
void FinishBackward(const TransposedArray &errors_t)
virtual int InitWeights(float range, TRand *randomizer)
void PrintUnTransposed(int num)
Definition: weightmatrix.h:46
int Modulo(int a, int b)
Definition: helpers.h:164
virtual StaticShape OutputShape(const StaticShape &input_shape) const
Definition: lstm.cpp:98
void BackwardTimeStep(const NetworkIO &fwd_deltas, int t, double *curr_errors, TransposedArray *errors_t, double *backprop)
void set_depth(int value)
Definition: static_shape.h:47