tesseract  4.1.0
network.h
Go to the documentation of this file.
1 // File: network.h
3 // Description: Base class for neural network implementations.
4 // Author: Ray Smith
5 //
6 // (C) Copyright 2013, Google Inc.
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
17 
18 #ifndef TESSERACT_LSTM_NETWORK_H_
19 #define TESSERACT_LSTM_NETWORK_H_
20 
21 #include <cstdio>
22 #include <cmath>
23 
24 #include "genericvector.h"
25 #include "helpers.h"
26 #include "matrix.h"
27 #include "networkio.h"
28 #include "serialis.h"
29 #include "static_shape.h"
30 #include "tprintf.h"
31 
32 struct Pix;
33 class ScrollView;
34 class TBOX;
35 
36 namespace tesseract {
37 
38 class ImageData;
39 class NetworkScratch;
40 
41 // Enum to store the run-time type of a Network. Keep in sync with kTypeNames.
43  NT_NONE, // The naked base class.
44  NT_INPUT, // Inputs from an image.
45  // Plumbing networks combine other networks or rearrange the inputs.
46  NT_CONVOLVE, // Duplicates inputs in a sliding window neighborhood.
47  NT_MAXPOOL, // Chooses the max result from a rectangle.
48  NT_PARALLEL, // Runs networks in parallel.
49  NT_REPLICATED, // Runs identical networks in parallel.
50  NT_PAR_RL_LSTM, // Runs LTR and RTL LSTMs in parallel.
51  NT_PAR_UD_LSTM, // Runs Up and Down LSTMs in parallel.
52  NT_PAR_2D_LSTM, // Runs 4 LSTMs in parallel.
53  NT_SERIES, // Executes a sequence of layers.
54  NT_RECONFIG, // Scales the time/y size but makes the output deeper.
55  NT_XREVERSED, // Reverses the x direction of the inputs/outputs.
56  NT_YREVERSED, // Reverses the y-direction of the inputs/outputs.
57  NT_XYTRANSPOSE, // Transposes x and y (for just a single op).
58  // Functional networks actually calculate stuff.
59  NT_LSTM, // Long-Short-Term-Memory block.
60  NT_LSTM_SUMMARY, // LSTM that only keeps its last output.
61  NT_LOGISTIC, // Fully connected logistic nonlinearity.
62  NT_POSCLIP, // Fully connected rect lin version of logistic.
63  NT_SYMCLIP, // Fully connected rect lin version of tanh.
64  NT_TANH, // Fully connected with tanh nonlinearity.
65  NT_RELU, // Fully connected with rectifier nonlinearity.
66  NT_LINEAR, // Fully connected with no nonlinearity.
67  NT_SOFTMAX, // Softmax uses exponential normalization, with CTC.
68  NT_SOFTMAX_NO_CTC, // Softmax uses exponential normalization, no CTC.
69  // The SOFTMAX LSTMs both have an extra softmax layer on top, but inside, with
70  // the outputs fed back to the input of the LSTM at the next timestep.
71  // The ENCODED version binary encodes the softmax outputs, providing log2 of
72  // the number of outputs as additional inputs, and the other version just
73  // provides all the softmax outputs as additional inputs.
74  NT_LSTM_SOFTMAX, // 1-d LSTM with built-in fully connected softmax.
75  NT_LSTM_SOFTMAX_ENCODED, // 1-d LSTM with built-in binary encoded softmax.
76  // A TensorFlow graph encapsulated as a Tesseract network.
78 
79  NT_COUNT // Array size.
80 };
81 
82 // Enum of Network behavior flags. Can in theory be set for each individual
83 // network element.
85  // Network forward/backprop behavior.
86  NF_LAYER_SPECIFIC_LR = 64, // Separate learning rate for each layer.
87  NF_ADAM = 128, // Weight-specific learning rate.
88 };
89 
90 // State of training and desired state used in SetEnableTraining.
92  // Valid states of training_.
93  TS_DISABLED, // Disabled permanently.
94  TS_ENABLED, // Enabled for backprop and to write a training dump.
95  // Re-enable from ANY disabled state.
96  TS_TEMP_DISABLE, // Temporarily disabled to write a recognition dump.
97  // Valid only for SetEnableTraining.
98  TS_RE_ENABLE, // Re-Enable from TS_TEMP_DISABLE, but not TS_DISABLED.
99 };
100 
101 // Base class for network types. Not quite an abstract base class, but almost.
102 // Most of the time no isolated Network exists, except prior to
103 // deserialization.
104 class Network {
105  public:
106  Network();
107  Network(NetworkType type, const STRING& name, int ni, int no);
108  virtual ~Network() = default;
109 
110  // Accessors.
111  NetworkType type() const {
112  return type_;
113  }
114  bool IsTraining() const { return training_ == TS_ENABLED; }
115  bool needs_to_backprop() const {
116  return needs_to_backprop_;
117  }
118  int num_weights() const { return num_weights_; }
119  int NumInputs() const {
120  return ni_;
121  }
122  int NumOutputs() const {
123  return no_;
124  }
125  // Returns the required shape input to the network.
126  virtual StaticShape InputShape() const {
127  StaticShape result;
128  return result;
129  }
130  // Returns the shape output from the network given an input shape (which may
131  // be partially unknown ie zero).
132  virtual StaticShape OutputShape(const StaticShape& input_shape) const {
133  StaticShape result(input_shape);
134  result.set_depth(no_);
135  return result;
136  }
137  const STRING& name() const {
138  return name_;
139  }
140  virtual STRING spec() const {
141  return "?";
142  }
143  bool TestFlag(NetworkFlags flag) const {
144  return (network_flags_ & flag) != 0;
145  }
146 
147  // Initialization and administrative functions that are mostly provided
148  // by Plumbing.
149  // Returns true if the given type is derived from Plumbing, and thus contains
150  // multiple sub-networks that can have their own learning rate.
151  virtual bool IsPlumbingType() const { return false; }
152 
153  // Suspends/Enables/Permanently disables training by setting the training_
154  // flag. Serialize and DeSerialize only operate on the run-time data if state
155  // is TS_DISABLED or TS_TEMP_DISABLE. Specifying TS_TEMP_DISABLE will
156  // temporarily disable layers in state TS_ENABLED, allowing a trainer to
157  // serialize as if it were a recognizer.
158  // TS_RE_ENABLE will re-enable layers that were previously in any disabled
159  // state. If in TS_TEMP_DISABLE then the flag is just changed, but if in
160  // TS_DISABLED, the deltas in the weight matrices are reinitialized so that a
161  // recognizer can be converted back to a trainer.
162  virtual void SetEnableTraining(TrainingState state);
163 
164  // Sets flags that control the action of the network. See NetworkFlags enum
165  // for bit values.
166  virtual void SetNetworkFlags(uint32_t flags);
167 
168  // Sets up the network for training. Initializes weights using weights of
169  // scale `range` picked according to the random number generator `randomizer`.
170  // Note that randomizer is a borrowed pointer that should outlive the network
171  // and should not be deleted by any of the networks.
172  // Returns the number of weights initialized.
173  virtual int InitWeights(float range, TRand* randomizer);
174  // Changes the number of outputs to the outside world to the size of the given
175  // code_map. Recursively searches the entire network for Softmax layers that
176  // have exactly old_no outputs, and operates only on those, leaving all others
177  // unchanged. This enables networks with multiple output layers to get all
178  // their softmaxes updated, but if an internal layer, uses one of those
179  // softmaxes for input, then the inputs will effectively be scrambled.
180  // TODO(rays) Fix this before any such network is implemented.
181  // The softmaxes are resized by copying the old weight matrix entries for each
182  // output from code_map[output] where non-negative, and uses the mean (over
183  // all outputs) of the existing weights for all outputs with negative code_map
184  // entries. Returns the new number of weights.
185  virtual int RemapOutputs(int old_no, const std::vector<int>& code_map) {
186  return 0;
187  }
188 
189  // Converts a float network to an int network.
190  virtual void ConvertToInt() {}
191 
192  // Provides a pointer to a TRand for any networks that care to use it.
193  // Note that randomizer is a borrowed pointer that should outlive the network
194  // and should not be deleted by any of the networks.
195  virtual void SetRandomizer(TRand* randomizer);
196 
197  // Sets needs_to_backprop_ to needs_backprop and returns true if
198  // needs_backprop || any weights in this network so the next layer forward
199  // can be told to produce backprop for this layer if needed.
200  virtual bool SetupNeedsBackprop(bool needs_backprop);
201 
202  // Returns the most recent reduction factor that the network applied to the
203  // time sequence. Assumes that any 2-d is already eliminated. Used for
204  // scaling bounding boxes of truth data and calculating result bounding boxes.
205  // WARNING: if GlobalMinimax is used to vary the scale, this will return
206  // the last used scale factor. Call it before any forward, and it will return
207  // the minimum scale factor of the paths through the GlobalMinimax.
208  virtual int XScaleFactor() const {
209  return 1;
210  }
211 
212  // Provides the (minimum) x scale factor to the network (of interest only to
213  // input units) so they can determine how to scale bounding boxes.
214  virtual void CacheXScaleFactor(int factor) {}
215 
216  // Provides debug output on the weights.
217  virtual void DebugWeights() = 0;
218 
219  // Writes to the given file. Returns false in case of error.
220  // Should be overridden by subclasses, but called by their Serialize.
221  virtual bool Serialize(TFile* fp) const;
222  // Reads from the given file. Returns false in case of error.
223  // Should be overridden by subclasses, but NOT called by their DeSerialize.
224  virtual bool DeSerialize(TFile* fp) = 0;
225 
226  public:
227  // Updates the weights using the given learning rate, momentum and adam_beta.
228  // num_samples is used in the adam computation iff use_adam_ is true.
229  virtual void Update(float learning_rate, float momentum, float adam_beta,
230  int num_samples) {}
231  // Sums the products of weight updates in *this and other, splitting into
232  // positive (same direction) in *same and negative (different direction) in
233  // *changed.
234  virtual void CountAlternators(const Network& other, double* same,
235  double* changed) const {}
236 
237  // Reads from the given file. Returns nullptr in case of error.
238  // Determines the type of the serialized class and calls its DeSerialize
239  // on a new object of the appropriate type, which is returned.
240  static Network* CreateFromFile(TFile* fp);
241 
242  // Runs forward propagation of activations on the input line.
243  // Note that input and output are both 2-d arrays.
244  // The 1st index is the time element. In a 1-d network, it might be the pixel
245  // position on the textline. In a 2-d network, the linearization is defined
246  // by the stride_map. (See networkio.h).
247  // The 2nd index of input is the network inputs/outputs, and the dimension
248  // of the input must match NumInputs() of this network.
249  // The output array will be resized as needed so that its 1st dimension is
250  // always equal to the number of output values, and its second dimension is
251  // always NumOutputs(). Note that all this detail is encapsulated away inside
252  // NetworkIO, as are the internals of the scratch memory space used by the
253  // network. See networkscratch.h for that.
254  // If input_transpose is not nullptr, then it contains the transpose of input,
255  // and the caller guarantees that it will still be valid on the next call to
256  // backward. The callee is therefore at liberty to save the pointer and
257  // reference it on a call to backward. This is a bit ugly, but it makes it
258  // possible for a replicating parallel to calculate the input transpose once
259  // instead of all the replicated networks having to do it.
260  virtual void Forward(bool debug, const NetworkIO& input,
261  const TransposedArray* input_transpose,
262  NetworkScratch* scratch, NetworkIO* output) = 0;
263 
264  // Runs backward propagation of errors on fwdX_deltas.
265  // Note that fwd_deltas and back_deltas are both 2-d arrays as with Forward.
266  // Returns false if back_deltas was not set, due to there being no point in
267  // propagating further backwards. Thus most complete networks will always
268  // return false from Backward!
269  virtual bool Backward(bool debug, const NetworkIO& fwd_deltas,
270  NetworkScratch* scratch,
271  NetworkIO* back_deltas) = 0;
272 
273  // === Debug image display methods. ===
274  // Displays the image of the matrix to the forward window.
275  void DisplayForward(const NetworkIO& matrix);
276  // Displays the image of the matrix to the backward window.
277  void DisplayBackward(const NetworkIO& matrix);
278 
279  // Creates the window if needed, otherwise clears it.
280  static void ClearWindow(bool tess_coords, const char* window_name,
281  int width, int height, ScrollView** window);
282 
283  // Displays the pix in the given window. and returns the height of the pix.
284  // The pix is pixDestroyed.
285  static int DisplayImage(Pix* pix, ScrollView* window);
286 
287  protected:
288  // Returns a random number in [-range, range].
289  double Random(double range);
290 
291  protected:
292  NetworkType type_; // Type of the derived network class.
293  TrainingState training_; // Are we currently training?
294  bool needs_to_backprop_; // This network needs to output back_deltas.
295  int32_t network_flags_; // Behavior control flags in NetworkFlags.
296  int32_t ni_; // Number of input values.
297  int32_t no_; // Number of output values.
298  int32_t num_weights_; // Number of weights in this and sub-network.
299  STRING name_; // A unique name for this layer.
300 
301  // NOT-serialized debug data.
302  ScrollView* forward_win_; // Recognition debug display window.
303  ScrollView* backward_win_; // Training debug display window.
304  TRand* randomizer_; // Random number generator.
305 };
306 
307 } // namespace tesseract.
308 
309 #endif // TESSERACT_LSTM_NETWORK_H_
virtual int InitWeights(float range, TRand *randomizer)
Definition: network.cpp:130
bool needs_to_backprop_
Definition: network.h:294
virtual int RemapOutputs(int old_no, const std::vector< int > &code_map)
Definition: network.h:185
NetworkType
Definition: network.h:42
Definition: rect.h:34
bool TestFlag(NetworkFlags flag) const
Definition: network.h:143
NetworkFlags
Definition: network.h:84
void DisplayBackward(const NetworkIO &matrix)
Definition: network.cpp:299
Definition: strngs.h:45
virtual void ConvertToInt()
Definition: network.h:190
virtual void SetRandomizer(TRand *randomizer)
Definition: network.cpp:138
ScrollView * backward_win_
Definition: network.h:303
virtual bool Backward(bool debug, const NetworkIO &fwd_deltas, NetworkScratch *scratch, NetworkIO *back_deltas)=0
virtual void SetEnableTraining(TrainingState state)
Definition: network.cpp:110
void set_depth(int value)
Definition: static_shape.h:49
virtual void SetNetworkFlags(uint32_t flags)
Definition: network.cpp:124
virtual void CacheXScaleFactor(int factor)
Definition: network.h:214
TRand * randomizer_
Definition: network.h:304
NetworkType type_
Definition: network.h:292
virtual StaticShape InputShape() const
Definition: network.h:126
virtual bool IsPlumbingType() const
Definition: network.h:151
virtual void Forward(bool debug, const NetworkIO &input, const TransposedArray *input_transpose, NetworkScratch *scratch, NetworkIO *output)=0
int32_t num_weights_
Definition: network.h:298
virtual ~Network()=default
int NumInputs() const
Definition: network.h:119
TrainingState
Definition: network.h:91
ScrollView * forward_win_
Definition: network.h:302
bool IsTraining() const
Definition: network.h:114
virtual void CountAlternators(const Network &other, double *same, double *changed) const
Definition: network.h:234
static Network * CreateFromFile(TFile *fp)
Definition: network.cpp:187
virtual int XScaleFactor() const
Definition: network.h:208
virtual StaticShape OutputShape(const StaticShape &input_shape) const
Definition: network.h:132
virtual bool DeSerialize(TFile *fp)=0
const STRING & name() const
Definition: network.h:137
virtual void DebugWeights()=0
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
Definition: network.cpp:312
void DisplayForward(const NetworkIO &matrix)
Definition: network.cpp:288
NetworkType type() const
Definition: network.h:111
int NumOutputs() const
Definition: network.h:122
bool needs_to_backprop() const
Definition: network.h:115
virtual bool Serialize(TFile *fp) const
Definition: network.cpp:151
virtual bool SetupNeedsBackprop(bool needs_backprop)
Definition: network.cpp:145
int32_t network_flags_
Definition: network.h:295
static int DisplayImage(Pix *pix, ScrollView *window)
Definition: network.cpp:335
double Random(double range)
Definition: network.cpp:281
virtual STRING spec() const
Definition: network.h:140
virtual void Update(float learning_rate, float momentum, float adam_beta, int num_samples)
Definition: network.h:229
TrainingState training_
Definition: network.h:293
int num_weights() const
Definition: network.h:118