tesseract  4.0.0-1-g2a2b
network.cpp
Go to the documentation of this file.
1 // File: network.cpp
3 // Description: Base class for neural network implementations.
4 // Author: Ray Smith
5 // Created: Wed May 01 17:25: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 automatically generated configuration file if running autoconf.
20 #ifdef HAVE_CONFIG_H
21 #include "config_auto.h"
22 #endif
23 
24 #include "network.h"
25 
26 #include <cstdlib>
27 
28 // This base class needs to know about all its sub-classes because of the
29 // factory deserializing method: CreateFromFile.
30 #include "allheaders.h"
31 #include "convolve.h"
32 #include "fullyconnected.h"
33 #include "input.h"
34 #include "lstm.h"
35 #include "maxpool.h"
36 #include "parallel.h"
37 #include "reconfig.h"
38 #include "reversed.h"
39 #include "scrollview.h"
40 #include "series.h"
41 #include "statistc.h"
42 #ifdef INCLUDE_TENSORFLOW
43 #include "tfnetwork.h"
44 #endif
45 #include "tprintf.h"
46 
47 namespace tesseract {
48 
49 // Min and max window sizes.
50 const int kMinWinSize = 500;
51 const int kMaxWinSize = 2000;
52 // Window frame sizes need adding on to make the content fit.
53 const int kXWinFrameSize = 30;
54 const int kYWinFrameSize = 80;
55 
56 // String names corresponding to the NetworkType enum. Keep in sync.
57 // Names used in Serialization to allow re-ordering/addition/deletion of
58 // layer types in NetworkType without invalidating existing network files.
59 char const* const Network::kTypeNames[NT_COUNT] = {
60  "Invalid", "Input",
61  "Convolve", "Maxpool",
62  "Parallel", "Replicated",
63  "ParBidiLSTM", "DepParUDLSTM",
64  "Par2dLSTM", "Series",
65  "Reconfig", "RTLReversed",
66  "TTBReversed", "XYTranspose",
67  "LSTM", "SummLSTM",
68  "Logistic", "LinLogistic",
69  "LinTanh", "Tanh",
70  "Relu", "Linear",
71  "Softmax", "SoftmaxNoCTC",
72  "LSTMSoftmax", "LSTMBinarySoftmax",
73  "TensorFlow",
74 };
75 
77  : type_(NT_NONE),
78  training_(TS_ENABLED),
79  needs_to_backprop_(true),
80  network_flags_(0),
81  ni_(0),
82  no_(0),
83  num_weights_(0),
84  forward_win_(nullptr),
85  backward_win_(nullptr),
86  randomizer_(nullptr) {}
87 Network::Network(NetworkType type, const STRING& name, int ni, int no)
88  : type_(type),
89  training_(TS_ENABLED),
90  needs_to_backprop_(true),
91  network_flags_(0),
92  ni_(ni),
93  no_(no),
94  num_weights_(0),
95  name_(name),
96  forward_win_(nullptr),
97  backward_win_(nullptr),
98  randomizer_(nullptr) {}
99 
100 
101 // Suspends/Enables/Permanently disables training by setting the training_
102 // flag. Serialize and DeSerialize only operate on the run-time data if state
103 // is TS_DISABLED or TS_TEMP_DISABLE. Specifying TS_TEMP_DISABLE will
104 // temporarily disable layers in state TS_ENABLED, allowing a trainer to
105 // serialize as if it were a recognizer.
106 // TS_RE_ENABLE will re-enable layers that were previously in any disabled
107 // state. If in TS_TEMP_DISABLE then the flag is just changed, but if in
108 // TS_DISABLED, the deltas in the weight matrices are reinitialized so that a
109 // recognizer can be converted back to a trainer.
111  if (state == TS_RE_ENABLE) {
112  // Enable only from temp disabled.
114  } else if (state == TS_TEMP_DISABLE) {
115  // Temp disable only from enabled.
116  if (training_ == TS_ENABLED) training_ = state;
117  } else {
118  training_ = state;
119  }
120 }
121 
122 // Sets flags that control the action of the network. See NetworkFlags enum
123 // for bit values.
124 void Network::SetNetworkFlags(uint32_t flags) {
125  network_flags_ = flags;
126 }
127 
128 // Sets up the network for training. Initializes weights using weights of
129 // scale `range` picked according to the random number generator `randomizer`.
130 int Network::InitWeights(float range, TRand* randomizer) {
131  randomizer_ = randomizer;
132  return 0;
133 }
134 
135 // Provides a pointer to a TRand for any networks that care to use it.
136 // Note that randomizer is a borrowed pointer that should outlive the network
137 // and should not be deleted by any of the networks.
138 void Network::SetRandomizer(TRand* randomizer) {
139  randomizer_ = randomizer;
140 }
141 
142 // Sets needs_to_backprop_ to needs_backprop and returns true if
143 // needs_backprop || any weights in this network so the next layer forward
144 // can be told to produce backprop for this layer if needed.
145 bool Network::SetupNeedsBackprop(bool needs_backprop) {
146  needs_to_backprop_ = needs_backprop;
147  return needs_backprop || num_weights_ > 0;
148 }
149 
150 // Writes to the given file. Returns false in case of error.
151 bool Network::Serialize(TFile* fp) const {
152  int8_t data = NT_NONE;
153  if (!fp->Serialize(&data)) return false;
154  STRING type_name = kTypeNames[type_];
155  if (!type_name.Serialize(fp)) return false;
156  data = training_;
157  if (!fp->Serialize(&data)) return false;
158  data = needs_to_backprop_;
159  if (!fp->Serialize(&data)) return false;
160  if (!fp->Serialize(&network_flags_)) return false;
161  if (!fp->Serialize(&ni_)) return false;
162  if (!fp->Serialize(&no_)) return false;
163  if (!fp->Serialize(&num_weights_)) return false;
164  if (!name_.Serialize(fp)) return false;
165  return true;
166 }
167 
168 // Reads from the given file. Returns false in case of error.
169 // Should be overridden by subclasses, but NOT called by their DeSerialize.
171  int8_t data;
172  if (!fp->DeSerialize(&data)) return false;
173  if (data == NT_NONE) {
174  STRING type_name;
175  if (!type_name.DeSerialize(fp)) return false;
176  for (data = 0; data < NT_COUNT && type_name != kTypeNames[data]; ++data) {
177  }
178  if (data == NT_COUNT) {
179  tprintf("Invalid network layer type:%s\n", type_name.string());
180  return false;
181  }
182  }
183  type_ = static_cast<NetworkType>(data);
184  if (!fp->DeSerialize(&data)) return false;
186  if (!fp->DeSerialize(&data)) return false;
187  needs_to_backprop_ = data != 0;
188  if (!fp->DeSerialize(&network_flags_)) return false;
189  if (!fp->DeSerialize(&ni_)) return false;
190  if (!fp->DeSerialize(&no_)) return false;
191  if (!fp->DeSerialize(&num_weights_)) return false;
192  if (!name_.DeSerialize(fp)) return false;
193  return true;
194 }
195 
196 // Reads from the given file. Returns nullptr in case of error.
197 // Determines the type of the serialized class and calls its DeSerialize
198 // on a new object of the appropriate type, which is returned.
200  Network stub;
201  if (!stub.DeSerialize(fp)) return nullptr;
202  Network* network = nullptr;
203  switch (stub.type_) {
204  case NT_CONVOLVE:
205  network = new Convolve(stub.name_, stub.ni_, 0, 0);
206  break;
207  case NT_INPUT:
208  network = new Input(stub.name_, stub.ni_, stub.no_);
209  break;
210  case NT_LSTM:
211  case NT_LSTM_SOFTMAX:
213  case NT_LSTM_SUMMARY:
214  network =
215  new LSTM(stub.name_, stub.ni_, stub.no_, stub.no_, false, stub.type_);
216  break;
217  case NT_MAXPOOL:
218  network = new Maxpool(stub.name_, stub.ni_, 0, 0);
219  break;
220  // All variants of Parallel.
221  case NT_PARALLEL:
222  case NT_REPLICATED:
223  case NT_PAR_RL_LSTM:
224  case NT_PAR_UD_LSTM:
225  case NT_PAR_2D_LSTM:
226  network = new Parallel(stub.name_, stub.type_);
227  break;
228  case NT_RECONFIG:
229  network = new Reconfig(stub.name_, stub.ni_, 0, 0);
230  break;
231  // All variants of reversed.
232  case NT_XREVERSED:
233  case NT_YREVERSED:
234  case NT_XYTRANSPOSE:
235  network = new Reversed(stub.name_, stub.type_);
236  break;
237  case NT_SERIES:
238  network = new Series(stub.name_);
239  break;
240  case NT_TENSORFLOW:
241 #ifdef INCLUDE_TENSORFLOW
242  network = new TFNetwork(stub.name_);
243 #else
244  tprintf("TensorFlow not compiled in! -DINCLUDE_TENSORFLOW\n");
245 #endif
246  break;
247  // All variants of FullyConnected.
248  case NT_SOFTMAX:
249  case NT_SOFTMAX_NO_CTC:
250  case NT_RELU:
251  case NT_TANH:
252  case NT_LINEAR:
253  case NT_LOGISTIC:
254  case NT_POSCLIP:
255  case NT_SYMCLIP:
256  network = new FullyConnected(stub.name_, stub.ni_, stub.no_, stub.type_);
257  break;
258  default:
259  break;
260  }
261  if (network) {
262  network->training_ = stub.training_;
263  network->needs_to_backprop_ = stub.needs_to_backprop_;
264  network->network_flags_ = stub.network_flags_;
265  network->num_weights_ = stub.num_weights_;
266  if (!network->DeSerialize(fp)) {
267  delete network;
268  network = nullptr;
269  }
270  }
271  return network;
272 }
273 
274 // Returns a random number in [-range, range].
275 double Network::Random(double range) {
276  ASSERT_HOST(randomizer_ != nullptr);
277  return randomizer_->SignedRand(range);
278 }
279 
280 // === Debug image display methods. ===
281 // Displays the image of the matrix to the forward window.
282 void Network::DisplayForward(const NetworkIO& matrix) {
283 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics
284  Pix* image = matrix.ToPix();
285  ClearWindow(false, name_.string(), pixGetWidth(image),
286  pixGetHeight(image), &forward_win_);
287  DisplayImage(image, forward_win_);
288  forward_win_->Update();
289 #endif // GRAPHICS_DISABLED
290 }
291 
292 // Displays the image of the matrix to the backward window.
293 void Network::DisplayBackward(const NetworkIO& matrix) {
294 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics
295  Pix* image = matrix.ToPix();
296  STRING window_name = name_ + "-back";
297  ClearWindow(false, window_name.string(), pixGetWidth(image),
298  pixGetHeight(image), &backward_win_);
299  DisplayImage(image, backward_win_);
301 #endif // GRAPHICS_DISABLED
302 }
303 
304 #ifndef GRAPHICS_DISABLED
305 // Creates the window if needed, otherwise clears it.
306 void Network::ClearWindow(bool tess_coords, const char* window_name,
307  int width, int height, ScrollView** window) {
308  if (*window == nullptr) {
309  int min_size = std::min(width, height);
310  if (min_size < kMinWinSize) {
311  if (min_size < 1) min_size = 1;
312  width = width * kMinWinSize / min_size;
313  height = height * kMinWinSize / min_size;
314  }
315  width += kXWinFrameSize;
316  height += kYWinFrameSize;
317  if (width > kMaxWinSize) width = kMaxWinSize;
318  if (height > kMaxWinSize) height = kMaxWinSize;
319  *window = new ScrollView(window_name, 80, 100, width, height, width, height,
320  tess_coords);
321  tprintf("Created window %s of size %d, %d\n", window_name, width, height);
322  } else {
323  (*window)->Clear();
324  }
325 }
326 
327 // Displays the pix in the given window. and returns the height of the pix.
328 // The pix is pixDestroyed.
329 int Network::DisplayImage(Pix* pix, ScrollView* window) {
330  int height = pixGetHeight(pix);
331  window->Image(pix, 0, 0);
332  pixDestroy(&pix);
333  return height;
334 }
335 #endif // GRAPHICS_DISABLED
336 
337 } // namespace tesseract.
bool Serialize(FILE *fp) const
Definition: strngs.cpp:148
const int kMaxWinSize
Definition: network.cpp:51
double Random(double range)
Definition: network.cpp:275
static Network * CreateFromFile(TFile *fp)
Definition: network.cpp:199
int32_t num_weights_
Definition: network.h:305
bool DeSerialize(bool swap, FILE *fp)
Definition: strngs.cpp:161
const char * string() const
Definition: strngs.cpp:196
ScrollView * forward_win_
Definition: network.h:309
const int kMinWinSize
Definition: network.cpp:50
bool DeSerialize(char *data, size_t count=1)
Definition: serialis.cpp:103
NetworkType
Definition: network.h:43
void DisplayBackward(const NetworkIO &matrix)
Definition: network.cpp:293
virtual bool DeSerialize(TFile *fp)
Definition: network.cpp:170
virtual void SetRandomizer(TRand *randomizer)
Definition: network.cpp:138
TrainingState training_
Definition: network.h:300
static void Update()
Definition: scrollview.cpp:711
virtual int InitWeights(float range, TRand *randomizer)
Definition: network.cpp:130
NetworkType type_
Definition: network.h:299
virtual void SetEnableTraining(TrainingState state)
Definition: network.cpp:110
virtual bool SetupNeedsBackprop(bool needs_backprop)
Definition: network.cpp:145
TrainingState
Definition: network.h:92
virtual bool Serialize(TFile *fp) const
Definition: network.cpp:151
const int kXWinFrameSize
Definition: network.cpp:53
bool needs_to_backprop_
Definition: network.h:301
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
Definition: network.cpp:306
TRand * randomizer_
Definition: network.h:311
void DisplayForward(const NetworkIO &matrix)
Definition: network.cpp:282
Pix * ToPix() const
Definition: networkio.cpp:291
void Image(struct Pix *image, int x_pos, int y_pos)
Definition: scrollview.cpp:768
static char const *const kTypeNames[NT_COUNT]
Definition: network.h:314
bool Serialize(const char *data, size_t count=1)
Definition: serialis.cpp:147
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
static int DisplayImage(Pix *pix, ScrollView *window)
Definition: network.cpp:329
ScrollView * backward_win_
Definition: network.h:310
Definition: strngs.h:45
double SignedRand(double range)
Definition: helpers.h:61
const int kYWinFrameSize
Definition: network.cpp:54
virtual void SetNetworkFlags(uint32_t flags)
Definition: network.cpp:124
int32_t network_flags_
Definition: network.h:302
#define ASSERT_HOST(x)
Definition: errcode.h:84