tesseract  4.00.00dev
weightmatrix.h
Go to the documentation of this file.
1 // File: weightmatrix.h
3 // Description: Hides distinction between float/int implementations.
4 // Author: Ray Smith
5 // Created: Tue Jun 17 09:05:39 PST 2014
6 //
7 // (C) Copyright 2014, 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 #ifndef TESSERACT_LSTM_WEIGHTMATRIX_H_
20 #define TESSERACT_LSTM_WEIGHTMATRIX_H_
21 
22 #include "genericvector.h"
23 #include "matrix.h"
24 #include "tprintf.h"
25 
26 namespace tesseract {
27 
28 // Convenience instantiation of GENERIC_2D_ARRAY<double> with additional
29 // operations to write a strided vector, so the transposed form of the input
30 // is memory-contiguous.
31 class TransposedArray : public GENERIC_2D_ARRAY<double> {
32  public:
33  // Copies the whole input transposed, converted to double, into *this.
34  void Transpose(const GENERIC_2D_ARRAY<double>& input);
35  // Writes a vector of data representing a timestep (gradients or sources).
36  // The data is assumed to be of size1 in size (the strided dimension).
37  void WriteStrided(int t, const float* data) {
38  int size1 = dim1();
39  for (int i = 0; i < size1; ++i) put(i, t, data[i]);
40  }
41  void WriteStrided(int t, const double* data) {
42  int size1 = dim1();
43  for (int i = 0; i < size1; ++i) put(i, t, data[i]);
44  }
45  // Prints the first and last num elements of the un-transposed array.
46  void PrintUnTransposed(int num) {
47  int num_features = dim1();
48  int width = dim2();
49  for (int y = 0; y < num_features; ++y) {
50  for (int t = 0; t < width; ++t) {
51  if (num == 0 || t < num || t + num >= width) {
52  tprintf(" %g", (*this)(y, t));
53  }
54  }
55  tprintf("\n");
56  }
57  }
58 }; // class TransposedArray
59 
60 // Generic weight matrix for network layers. Can store the matrix as either
61 // an array of floats or inT8. Provides functions to compute the forward and
62 // backward steps with the matrix and updates to the weights.
63 class WeightMatrix {
64  public:
65  WeightMatrix() : int_mode_(false), use_ada_grad_(false) {}
66  // Sets up the network for training. Initializes weights using weights of
67  // scale `range` picked according to the random number generator `randomizer`.
68  // Note the order is outputs, inputs, as this is the order of indices to
69  // the matrix, so the adjacent elements are multiplied by the input during
70  // a forward operation.
71  int InitWeightsFloat(int no, int ni, bool ada_grad, float weight_range,
72  TRand* randomizer);
73 
74  // Converts a float network to an int network. Each set of input weights that
75  // corresponds to a single output weight is converted independently:
76  // Compute the max absolute value of the weight set.
77  // Scale so the max absolute value becomes MAX_INT8.
78  // Round to integer.
79  // Store a multiplicative scale factor (as a float) that will reproduce
80  // the original value, subject to rounding errors.
81  void ConvertToInt();
82 
83  // Accessors.
84  bool is_int_mode() const {
85  return int_mode_;
86  }
87  int NumOutputs() const { return int_mode_ ? wi_.dim1() : wf_.dim1(); }
88  // Provides one set of weights. Only used by peep weight maxpool.
89  const double* GetWeights(int index) const { return wf_[index]; }
90  // Provides access to the deltas (dw_).
91  double GetDW(int i, int j) const { return dw_(i, j); }
92 
93  // Allocates any needed memory for running Backward, and zeroes the deltas,
94  // thus eliminating any existing momentum.
95  void InitBackward();
96 
97  // Writes to the given file. Returns false in case of error.
98  bool Serialize(bool training, TFile* fp) const;
99  // Reads from the given file. Returns false in case of error.
100  bool DeSerialize(bool training, TFile* fp);
101  // As DeSerialize, but reads an old (float) format WeightMatrix for
102  // backward compatibility.
103  bool DeSerializeOld(bool training, TFile* fp);
104 
105  // Computes matrix.vector v = Wu.
106  // u is of size W.dim2() - 1 and the output v is of size W.dim1().
107  // u is imagined to have an extra element at the end with value 1, to
108  // implement the bias, but it doesn't actually have it.
109  // Asserts that the call matches what we have.
110  void MatrixDotVector(const double* u, double* v) const;
111  void MatrixDotVector(const inT8* u, double* v) const;
112  // MatrixDotVector for peep weights, MultiplyAccumulate adds the
113  // component-wise products of *this[0] and v to inout.
114  void MultiplyAccumulate(const double* v, double* inout);
115  // Computes vector.matrix v = uW.
116  // u is of size W.dim1() and the output v is of size W.dim2() - 1.
117  // The last result is discarded, as v is assumed to have an imaginary
118  // last value of 1, as with MatrixDotVector.
119  void VectorDotMatrix(const double* u, double* v) const;
120  // Fills dw_[i][j] with the dot product u[i][] . v[j][], using elements
121  // from u and v, starting with u[i][offset] and v[j][offset].
122  // Note that (matching MatrixDotVector) v[last][] is missing, presumed 1.0.
123  // Runs parallel if requested. Note that inputs must be transposed.
124  void SumOuterTransposed(const TransposedArray& u, const TransposedArray& v,
125  bool parallel);
126  // Updates the weights using the given learning rate and momentum.
127  // num_samples is the quotient to be used in the adagrad computation iff
128  // use_ada_grad_ is true.
129  void Update(double learning_rate, double momentum, int num_samples);
130  // Adds the dw_ in other to the dw_ is *this.
131  void AddDeltas(const WeightMatrix& other);
132  // Sums the products of weight updates in *this and other, splitting into
133  // positive (same direction) in *same and negative (different direction) in
134  // *changed.
135  void CountAlternators(const WeightMatrix& other, double* same,
136  double* changed) const;
137 
138  void Debug2D(const char* msg);
139 
140  // Computes and returns the dot product of the two n-vectors u and v.
141  static double DotProduct(const double* u, const double* v, int n);
142  // Utility function converts an array of float to the corresponding array
143  // of double.
144  static void FloatToDouble(const GENERIC_2D_ARRAY<float>& wf,
146 
147  private:
148  // Computes matrix.vector v = Wu.
149  // u is of size starts.back()+extents.back() and the output v is of size
150  // starts.size().
151  // The weight matrix w, is of size starts.size()xMAX(extents)+add_bias_fwd.
152  // If add_bias_fwd, an extra element at the end of w[i] is the bias weight
153  // and is added to v[i].
154  static void MatrixDotVectorInternal(const GENERIC_2D_ARRAY<double>& w,
155  bool add_bias_fwd, bool skip_bias_back,
156  const double* u, double* v);
157 
158  private:
159  // Choice between float and 8 bit int implementations.
162  // Transposed copy of wf_, used only for Backward, and set with each Update.
163  TransposedArray wf_t_;
164  // Which of wf_ and wi_ are we actually using.
165  bool int_mode_;
166  // True if we are running adagrad in this weight matrix.
167  bool use_ada_grad_;
168  // If we are using wi_, then scales_ is a factor to restore the row product
169  // with a vector to the correct range.
170  GenericVector<double> scales_;
171  // Weight deltas. dw_ is the new delta, and updates_ the momentum-decaying
172  // amount to be added to wf_/wi_.
174  GENERIC_2D_ARRAY<double> updates_;
175  // Iff use_ada_grad_, the sum of squares of dw_. The number of samples is
176  // given to Update(). Serialized iff use_ada_grad_.
177  GENERIC_2D_ARRAY<double> dw_sq_sum_;
178 };
179 
180 } // namespace tesseract.
181 
182 #endif // TESSERACT_LSTM_WEIGHTMATRIX_H_
double u[max]
double GetDW(int i, int j) const
Definition: weightmatrix.h:91
void MultiplyAccumulate(int n, const double *u, const double *v, double *out)
Definition: functions.h:201
#define tprintf(...)
Definition: tprintf.h:31
void Transpose(const GENERIC_2D_ARRAY< double > &input)
void WriteStrided(int t, const float *data)
Definition: weightmatrix.h:37
void WriteStrided(int t, const double *data)
Definition: weightmatrix.h:41
const double * GetWeights(int index) const
Definition: weightmatrix.h:89
bool is_int_mode() const
Definition: weightmatrix.h:84
bool Serialize(FILE *fp) const
Definition: matrix.h:137
bool DeSerialize(bool swap, FILE *fp)
Definition: matrix.h:155
virtual int index(int column, int row) const
Definition: matrix.h:210
int8_t inT8
Definition: host.h:34
void put(ICOORD pos, const double &thing)
Definition: matrix.h:215
double DotProduct(const double *u, const double *v, int n)
double v[max]
void PrintUnTransposed(int num)
Definition: weightmatrix.h:46