tesseract  4.0.0-1-g2a2b
tfnetwork.cpp
Go to the documentation of this file.
1 // File: tfnetwork.cpp
3 // Description: Encapsulation of an entire tensorflow graph as a
4 // Tesseract Network.
5 // Author: Ray Smith
6 // Created: Fri Feb 26 09:35:29 PST 2016
7 //
8 // (C) Copyright 2016, Google Inc.
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 #ifdef INCLUDE_TENSORFLOW
20 
21 #include "tfnetwork.h"
22 
23 #include "allheaders.h"
24 #include "input.h"
25 #include "networkscratch.h"
26 
27 using tensorflow::Status;
28 using tensorflow::Tensor;
29 using tensorflow::TensorShape;
30 
31 namespace tesseract {
32 
33 TFNetwork::TFNetwork(const STRING& name) : Network(NT_TENSORFLOW, name, 0, 0) {}
34 
35 int TFNetwork::InitFromProtoStr(const string& proto_str) {
36  if (!model_proto_.ParseFromString(proto_str)) return 0;
37  return InitFromProto();
38 }
39 
40 // Writes to the given file. Returns false in case of error.
41 // Should be overridden by subclasses, but called by their Serialize.
42 bool TFNetwork::Serialize(TFile* fp) const {
43  if (!Network::Serialize(fp)) return false;
44  string proto_str;
45  model_proto_.SerializeToString(&proto_str);
47  data.resize_no_init(proto_str.size());
48  memcpy(&data[0], proto_str.data(), proto_str.size());
49  if (!data.Serialize(fp)) return false;
50  return true;
51 }
52 
53 // Reads from the given file. Returns false in case of error.
54 // Should be overridden by subclasses, but NOT called by their DeSerialize.
55 bool TFNetwork::DeSerialize(TFile* fp) {
57  if (!data.DeSerialize(fp)) return false;
58  if (!model_proto_.ParseFromArray(&data[0], data.size())) {
59  return false;
60  }
61  return InitFromProto();
62 }
63 
64 // Runs forward propagation of activations on the input line.
65 // See Network for a detailed discussion of the arguments.
66 void TFNetwork::Forward(bool debug, const NetworkIO& input,
67  const TransposedArray* input_transpose,
68  NetworkScratch* scratch, NetworkIO* output) {
69  std::vector<std::pair<string, Tensor>> tf_inputs;
70  int depth = input_shape_.depth();
71  ASSERT_HOST(depth == input.NumFeatures());
72  // TODO(rays) Allow batching. For now batch_size = 1.
73  const StrideMap& stride_map = input.stride_map();
74  // TF requires a tensor of shape float[batch, height, width, depth].
75  TensorShape shape{1, stride_map.Size(FD_HEIGHT), stride_map.Size(FD_WIDTH),
76  depth};
77  Tensor input_tensor(tensorflow::DT_FLOAT, shape);
78  // The flat() member gives a 1d array, with a data() member to get the data.
79  auto eigen_tensor = input_tensor.flat<float>();
80  memcpy(eigen_tensor.data(), input.f(0),
81  input.Width() * depth * sizeof(input.f(0)[0]));
82  // Add the tensor to the vector of inputs.
83  tf_inputs.emplace_back(model_proto_.image_input(), input_tensor);
84 
85  // Provide tensors giving the width and/or height of the image if they are
86  // required. Some tf ops require a separate tensor with knowledge of the
87  // size of the input as they cannot obtain it from the input tensor. This is
88  // usually true in the case of ops that process a batch of variable-sized
89  // objects.
90  if (!model_proto_.image_widths().empty()) {
91  TensorShape size_shape{1};
92  Tensor width_tensor(tensorflow::DT_INT64, size_shape);
93  auto eigen_wtensor = width_tensor.flat<int64>();
94  *eigen_wtensor.data() = stride_map.Size(FD_WIDTH);
95  tf_inputs.emplace_back(model_proto_.image_widths(), width_tensor);
96  }
97  if (!model_proto_.image_heights().empty()) {
98  TensorShape size_shape{1};
99  Tensor height_tensor(tensorflow::DT_INT64, size_shape);
100  auto eigen_htensor = height_tensor.flat<int64>();
101  *eigen_htensor.data() = stride_map.Size(FD_HEIGHT);
102  tf_inputs.emplace_back(model_proto_.image_heights(), height_tensor);
103  }
104  std::vector<string> target_layers = {model_proto_.output_layer()};
105  std::vector<Tensor> outputs;
106  Status s = session_->Run(tf_inputs, target_layers, {}, &outputs);
107  if (!s.ok()) tprintf("session->Run failed:%s\n", s.error_message().c_str());
108  ASSERT_HOST(s.ok());
109  ASSERT_HOST(outputs.size() == 1);
110  const Tensor& output_tensor = outputs[0];
111  // Check the dimensions of the output.
112  ASSERT_HOST(output_tensor.shape().dims() == 3);
113  int output_batch = output_tensor.shape().dim_size(0);
114  int output_steps = output_tensor.shape().dim_size(1);
115  int output_depth = output_tensor.shape().dim_size(2);
116  ASSERT_HOST(output_batch == 1);
117  ASSERT_HOST(output_depth == output_shape_.depth());
118  output->Resize2d(false, output_steps, output_depth);
119  auto eigen_output = output_tensor.flat<float>();
120  memcpy(output->f(0), eigen_output.data(),
121  output_steps * output_depth * sizeof(output->f(0)[0]));
122 }
123 
124 int TFNetwork::InitFromProto() {
125  spec_ = model_proto_.spec();
126  input_shape_.SetShape(
127  model_proto_.batch_size(), std::max(0, model_proto_.y_size()),
128  std::max(0, model_proto_.x_size()), model_proto_.depth());
129  output_shape_.SetShape(model_proto_.batch_size(), 1, 0,
130  model_proto_.num_classes());
131  output_shape_.set_loss_type(model_proto_.using_ctc() ? LT_CTC : LT_SOFTMAX);
132  ni_ = input_shape_.height();
133  no_ = output_shape_.depth();
134  // Initialize the session_ with the graph. Since we can't get the graph
135  // back from the session_, we have to keep the proto as well
136  tensorflow::SessionOptions options;
137  session_.reset(NewSession(options));
138  Status s = session_->Create(model_proto_.graph());
139  if (s.ok()) return model_proto_.global_step();
140  tprintf("Session_->Create returned '%s'\n", s.error_message().c_str());
141  return 0;
142 }
143 
144 } // namespace tesseract
145 
146 #endif // ifdef INCLUDE_TENSORFLOW
void resize_no_init(int size)
Definition: genericvector.h:65
int size() const
Definition: genericvector.h:71
bool DeSerialize(bool swap, FILE *fp)
bool Serialize(FILE *fp, const char *data, size_t n)
Definition: serialis.cpp:59
bool Serialize(FILE *fp) const
virtual bool Serialize(TFile *fp) const
Definition: network.cpp:151
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
Definition: strngs.h:45
bool DeSerialize(FILE *fp, char *data, size_t n)
Definition: serialis.cpp:27
#define ASSERT_HOST(x)
Definition: errcode.h:84