Repository navigation
Expand file tree
/
Copy pathmnist_inference.cc
More file actions
219 lines (191 loc) · 8.29 KB
/
Copy pathmnist_inference.cc
File metadata and controls
219 lines (191 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// A gRPC server that classifies images into digit 0-9.
// Given each request with an image pixels encoded as floats, the server
// responds with 10 float values as probabilities for digit 0-9 respectively.
// The classification is done by running image data through a simple softmax
// regression network trained and exported by mnist_export.py.
// The intention of this example to demonstrate usage of Tensorflow
// APIs in an end-to-end scenario.
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "grpc++/security/server_credentials.h"
#include "grpc++/server.h"
#include "grpc++/server_builder.h"
#include "grpc++/server_context.h"
#include "grpc++/support/status.h"
#include "grpc++/support/status_code_enum.h"
#include "grpc/grpc.h"
#include "tensorflow/contrib/session_bundle/manifest.pb.h"
#include "tensorflow/contrib/session_bundle/session_bundle.h"
#include "tensorflow/contrib/session_bundle/signature.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow_serving/example/mnist_inference.grpc.pb.h"
#include "tensorflow_serving/example/mnist_inference.pb.h"
#include "tensorflow_serving/servables/tensorflow/session_bundle_config.pb.h"
#include "tensorflow_serving/servables/tensorflow/session_bundle_factory.h"
using grpc::InsecureServerCredentials;
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
using tensorflow::serving::ClassificationSignature;
using tensorflow::serving::MnistRequest;
using tensorflow::serving::MnistResponse;
using tensorflow::serving::MnistService;
using tensorflow::serving::BatchingParameters;
using tensorflow::serving::SessionBundle;
using tensorflow::serving::SessionBundleConfig;
using tensorflow::serving::SessionBundleFactory;
using tensorflow::string;
using tensorflow::Tensor;
using tensorflow::TensorShape;
namespace {
const int kImageSize = 28;
const int kNumChannels = 1;
const int kImageDataSize = kImageSize * kImageSize * kNumChannels;
const int kNumLabels = 10;
// Creates a gRPC Status from a TensorFlow Status.
Status ToGRPCStatus(const tensorflow::Status& status) {
return Status(static_cast<grpc::StatusCode>(status.code()),
status.error_message());
}
class MnistServiceImpl final : public MnistService::Service {
public:
explicit MnistServiceImpl(std::unique_ptr<SessionBundle> bundle)
: bundle_(std::move(bundle)) {
signature_status_ = tensorflow::serving::GetClassificationSignature(
bundle_->meta_graph_def, &signature_);
}
Status Classify(ServerContext* context, const MnistRequest* request,
MnistResponse* response) override {
// Verify protobuf input.
if (request->image_data_size() != kImageDataSize) {
return Status(StatusCode::INVALID_ARGUMENT,
tensorflow::strings::StrCat("expected image_data of size ",
kImageDataSize, ", got ",
request->image_data_size()));
}
// Transform protobuf input to inference input tensor and create
// output tensor placeholder.
// See mnist_export.py for details.
Tensor input(tensorflow::DT_FLOAT, {1, kImageDataSize});
std::copy_n(request->image_data().begin(), kImageDataSize,
input.flat<float>().data());
std::vector<Tensor> outputs;
// Run inference.
if (!signature_status_.ok()) {
return ToGRPCStatus(signature_status_);
}
// WARNING(break-tutorial-inline-code): The following code snippet is
// in-lined in tutorials, please update tutorial documents accordingly
// whenever code changes.
const tensorflow::Status status = bundle_->session->Run(
{{signature_.input().tensor_name(), input}},
{signature_.scores().tensor_name()}, {}, &outputs);
if (!status.ok()) {
return ToGRPCStatus(status);
}
// Transform inference output tensor to protobuf output.
// See mnist_export.py for details.
if (outputs.size() != 1) {
return Status(StatusCode::INTERNAL,
tensorflow::strings::StrCat(
"expected one model output, got ", outputs.size()));
}
const Tensor& score_tensor = outputs[0];
const TensorShape expected_shape({1, kNumLabels});
if (!score_tensor.shape().IsSameSize(expected_shape)) {
return Status(
StatusCode::INTERNAL,
tensorflow::strings::StrCat("expected output of size ",
expected_shape.DebugString(), ", got ",
score_tensor.shape().DebugString()));
}
const auto score_flat = outputs[0].flat<float>();
for (int i = 0; i < score_flat.size(); ++i) {
response->add_value(score_flat(i));
}
return Status::OK;
}
private:
std::unique_ptr<SessionBundle> bundle_;
tensorflow::Status signature_status_;
ClassificationSignature signature_;
};
void RunServer(int port, std::unique_ptr<SessionBundle> bundle) {
// "0.0.0.0" is the way to listen on localhost in gRPC.
const string server_address = "0.0.0.0:" + std::to_string(port);
MnistServiceImpl service(std::move(bundle));
ServerBuilder builder;
std::shared_ptr<grpc::ServerCredentials> creds = InsecureServerCredentials();
builder.AddListeningPort(server_address, creds);
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
LOG(INFO) << "Running...";
server->Wait();
}
} // namespace
int main(int argc, char** argv) {
tensorflow::int32 port = 0;
const bool parse_result =
tensorflow::ParseFlags(&argc, argv, {tensorflow::Flag("port", &port)});
if (!parse_result) {
LOG(FATAL) << "Error parsing command line flags.";
}
if (argc != 2) {
LOG(FATAL) << "Usage: mnist_inference --port=9000 /path/to/export";
}
const string bundle_path(argv[1]);
tensorflow::port::InitMain(argv[0], &argc, &argv);
// WARNING(break-tutorial-inline-code): The following code snippet is
// in-lined in tutorials, please update tutorial documents accordingly
// whenever code changes.
SessionBundleConfig session_bundle_config;
//////
// Request batching, keeping default values for the tuning parameters.
//
// (If you prefer to disable batching, simply omit the following lines of code
// such that session_bundle_config.batching_parameters remains unset.)
BatchingParameters* batching_parameters =
session_bundle_config.mutable_batching_parameters();
batching_parameters->mutable_thread_pool_name()->set_value(
"mnist_service_batch_threads");
// Use a very large queue, to avoid rejecting requests. (Note: a production
// server with load balancing may want to use the default, much smaller,
// value.)
batching_parameters->mutable_max_enqueued_batches()->set_value(1000);
//////
std::unique_ptr<SessionBundleFactory> bundle_factory;
TF_QCHECK_OK(
SessionBundleFactory::Create(session_bundle_config, &bundle_factory));
std::unique_ptr<SessionBundle> bundle(new SessionBundle);
TF_QCHECK_OK(bundle_factory->CreateSessionBundle(bundle_path, &bundle));
// END WARNING(break-tutorial-inline-code)
RunServer(port, std::move(bundle));
return 0;
}