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