forked from tensorflow/neural-structured-learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknowledge_bank_grpc_service.cc
411 lines (380 loc) · 15.5 KB
/
knowledge_bank_grpc_service.cc
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*Copyright 2020 Google LLC
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
https://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.
==============================================================================*/
#include "research/carls/knowledge_bank_grpc_service.h"
#include <cstddef>
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "research/carls/base/status_helper.h"
namespace carls {
namespace {
using grpc::Status;
using grpc::StatusCode;
} // namespace
KnowledgeBankGrpcServiceImpl::KnowledgeBankGrpcServiceImpl() {}
KnowledgeBankGrpcServiceImpl::~KnowledgeBankGrpcServiceImpl() {}
Status KnowledgeBankGrpcServiceImpl::StartSession(
grpc::ServerContext* context, const StartSessionRequest* request,
StartSessionResponse* response) {
if (request->name().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "Name is empty.");
}
const std::string session_handle = request->SerializeAsString();
const auto status = StartSessionIfNecessary(
session_handle, /*require_candidate_sampler=*/false,
/*require_memory_store=*/false);
if (!status.ok()) {
return status;
}
response->set_session_handle(session_handle);
return Status::OK;
}
Status KnowledgeBankGrpcServiceImpl::Lookup(grpc::ServerContext* context,
const LookupRequest* request,
LookupResponse* response) {
if (request->session_handle().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "session_handle is empty.");
}
if (request->key().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "Empty input keys.");
}
const auto status = StartSessionIfNecessary(
request->session_handle(), /*require_candidate_sampler=*/false,
/*require_memory_store=*/false);
if (!status.ok()) {
return status;
}
std::vector<absl::string_view> keys(request->key().begin(),
request->key().end());
absl::ReaderMutexLock lock(&map_mu_);
std::vector<absl::variant<EmbeddingVectorProto, std::string>> value_or_errors;
if (request->update()) {
kb_map_[request->session_handle()]->BatchLookupWithUpdate(keys,
&value_or_errors);
} else {
kb_map_[request->session_handle()]->BatchLookup(keys, &value_or_errors);
}
if (value_or_errors.size() != keys.size()) {
return Status(StatusCode::INTERNAL,
"Inconsistent result returned by BatchLookup()");
}
auto& embedding_table = *response->mutable_embedding_table();
for (size_t i = 0; i < keys.size(); ++i) {
if (!absl::holds_alternative<EmbeddingVectorProto>(value_or_errors[i])) {
continue;
}
embedding_table[request->key(i)] =
std::move(absl::get<EmbeddingVectorProto>(value_or_errors[i]));
}
return Status::OK;
}
Status KnowledgeBankGrpcServiceImpl::Update(grpc::ServerContext* context,
const UpdateRequest* request,
UpdateResponse* response) {
if (request->session_handle().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "session_handle is empty.");
}
if (request->values().empty() && request->gradients().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "input is empty.");
}
const auto status = StartSessionIfNecessary(
request->session_handle(), /*require_candidate_sampler=*/false,
/*require_memory_store=*/false);
if (!status.ok()) {
return status;
}
if (!request->values().empty()) {
std::vector<absl::string_view> keys;
std::vector<EmbeddingVectorProto> values;
keys.reserve(request->values_size());
values.reserve(request->values_size());
for (const auto& iter : request->values()) {
keys.push_back(iter.first);
values.push_back(iter.second);
}
absl::WriterMutexLock lock(&map_mu_);
kb_map_[request->session_handle()]->BatchUpdate(keys, values);
}
if (!request->gradients().empty()) {
// Collect variables and gradients.
std::vector<absl::string_view> keys;
std::vector<absl::string_view> valid_keys;
std::vector<EmbeddingVectorProto> embeddings;
std::vector<const EmbeddingVectorProto*> gradients;
keys.reserve(request->gradients().size());
valid_keys.reserve(request->gradients().size());
embeddings.reserve(request->gradients().size());
gradients.reserve(request->gradients().size());
for (auto& pair : request->gradients()) {
keys.push_back(pair.first);
gradients.push_back(&pair.second);
}
absl::WriterMutexLock lock(&map_mu_);
if (!gd_map_.contains(request->session_handle())) {
return Status(StatusCode::INTERNAL,
"Optimizer is not created, did you forget to add "
"gradient_descent_config in DynamicEmbeddingConfig?");
}
// Step One: find the embeddings of given keys.
std::vector<absl::variant<EmbeddingVectorProto, std::string>>
value_or_errors;
kb_map_[request->session_handle()]->BatchLookup(keys, &value_or_errors);
if (value_or_errors.size() != keys.size()) {
return Status(StatusCode::INTERNAL,
"Inconsistent result returned by BatchLookup()");
}
for (size_t i = 0; i < keys.size(); ++i) {
if (!absl::holds_alternative<EmbeddingVectorProto>(value_or_errors[i])) {
continue;
}
valid_keys.push_back(keys[i]);
embeddings.push_back(
std::move(absl::get<EmbeddingVectorProto>(value_or_errors[i])));
}
if (valid_keys.empty()) {
return Status(StatusCode::INTERNAL, "No valid keys for gradient update.");
}
// Step Two: apply gradient update.
std::string error_msg;
auto updated_embeddings = gd_map_[request->session_handle()]->Apply(
embeddings, gradients, &error_msg);
if (updated_embeddings.empty()) {
return Status(
StatusCode::INTERNAL,
absl::StrCat("Applying gradient update returned error: ", error_msg));
}
// Step Three: update the embeddings.
kb_map_[request->session_handle()]->BatchUpdate(valid_keys,
updated_embeddings);
}
return Status::OK;
}
grpc::Status KnowledgeBankGrpcServiceImpl::Sample(grpc::ServerContext* context,
const SampleRequest* request,
SampleResponse* response) {
if (request->session_handle().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "session_handle is empty.");
}
if (request->sample_context().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "No sample context.");
}
const auto status = StartSessionIfNecessary(
request->session_handle(), /*require_candidate_sampler=*/true,
/*require_memory_store=*/false);
if (!status.ok()) {
return status;
}
absl::MutexLock lock(&map_mu_);
auto& knowledge_bank = *kb_map_[request->session_handle()];
// Add new keys into the knowledge bank if necessary.
if (request->update()) {
absl::flat_hash_set<absl::string_view> keys;
for (const auto& context : request->sample_context()) {
for (const auto& key : context.positive_key()) {
if (!knowledge_bank.Contains(key)) {
keys.insert(key);
}
}
}
if (!keys.empty()) {
std::vector<absl::variant<EmbeddingVectorProto, std::string>> results;
std::vector<absl::string_view> positive_keys(keys.begin(), keys.end());
knowledge_bank.BatchLookupWithUpdate(positive_keys, &results);
}
}
for (const auto& sample_context : request->sample_context()) {
std::vector<std::pair<absl::string_view, candidate_sampling::SampledResult>>
results;
auto status = cs_map_[request->session_handle()]->Sample(
knowledge_bank, sample_context, request->num_samples(), &results);
if (!status.ok()) {
return ToGrpcStatus(status);
}
auto* samples = response->add_samples();
for (auto& pair : results) {
*samples->add_sampled_result() = std::move(pair.second);
}
}
return Status::OK;
}
grpc::Status KnowledgeBankGrpcServiceImpl::MemoryLookup(
grpc::ServerContext* context, const MemoryLookupRequest* request,
MemoryLookupResponse* response) {
if (request->session_handle().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "session_handle is empty.");
}
if (request->input().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "input is empty.");
}
const auto status = StartSessionIfNecessary(
request->session_handle(), /*require_candidate_sampler=*/false,
/*require_memory_store=*/true);
if (!status.ok()) {
return status;
}
std::vector<memory_store::MemoryLookupResult> results;
absl::Status absl_status;
switch (request->mode()) {
case MemoryLookupRequest::LOOKUP_WITHOUT_UPDATE:
absl_status = ms_map_[request->session_handle()]->BatchLookup(
request->input(), &results);
if (!absl_status.ok()) {
return ToGrpcStatus(absl_status);
}
break;
case MemoryLookupRequest::LOOKUP_WITH_UPDATE:
absl_status = ms_map_[request->session_handle()]->BatchLookupWithUpdate(
request->input(), &results);
if (!absl_status.ok()) {
return ToGrpcStatus(absl_status);
}
break;
case MemoryLookupRequest::LOOKUP_WITH_GROW:
absl_status = ms_map_[request->session_handle()]->BatchLookupWithGrow(
request->input(), &results);
if (!absl_status.ok()) {
return ToGrpcStatus(absl_status);
}
break;
default:
return Status(StatusCode::INVALID_ARGUMENT, "Unknown lookup mode.");
}
for (auto& result : results) {
*response->add_memory_lookup_result() = std::move(result);
}
return Status::OK;
}
Status KnowledgeBankGrpcServiceImpl::Export(grpc::ServerContext* context,
const ExportRequest* request,
ExportResponse* response) {
if (request->session_handle().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "session_handle is empty.");
}
if (request->export_directory().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "export_directory is empty.");
}
const auto status = StartSessionIfNecessary(
request->session_handle(), /*require_candidate_sampler=*/false,
/*require_memory_store=*/false);
if (!status.ok()) {
return status;
}
StartSessionRequest start_request;
start_request.ParseFromString(request->session_handle());
absl::MutexLock lock(&map_mu_);
if (kb_map_.contains(request->session_handle())) {
return ToGrpcStatus(kb_map_[request->session_handle()]->Export(
request->export_directory(), start_request.name(),
response->mutable_knowledge_bank_saved_path()));
} else if (ms_map_.contains(request->session_handle())) {
return ToGrpcStatus(ms_map_[request->session_handle()]->Export(
request->export_directory(), start_request.name(),
response->mutable_memory_store_saved_path()));
} else {
return Status(StatusCode::INVALID_ARGUMENT,
"Neither KnowledgeStore nor MemoryStore is initialized.");
}
}
Status KnowledgeBankGrpcServiceImpl::Import(grpc::ServerContext* context,
const ImportRequest* request,
ImportResponse* response) {
if (request->session_handle().empty()) {
return Status(StatusCode::INVALID_ARGUMENT, "session_handle is empty.");
}
const auto status = StartSessionIfNecessary(
request->session_handle(), /*require_candidate_sampler=*/false,
/*require_memory_store=*/false);
if (!status.ok()) {
return status;
}
absl::MutexLock lock(&map_mu_);
if (kb_map_.contains(request->session_handle())) {
if (request->knowledge_bank_saved_path().empty()) {
return Status(StatusCode::INVALID_ARGUMENT,
"knowledge_bank_saved_path is empty.");
}
return ToGrpcStatus(kb_map_[request->session_handle()]->Import(
request->knowledge_bank_saved_path()));
} else if (ms_map_.contains(request->session_handle())) {
if (request->memory_store_saved_path().empty()) {
return Status(StatusCode::INVALID_ARGUMENT,
"memory_store_saved_path is empty.");
}
return ToGrpcStatus(ms_map_[request->session_handle()]->Import(
request->memory_store_saved_path()));
}
return Status(StatusCode::INVALID_ARGUMENT,
"Neither KnowledgeStore nor MemoryStore is initialized.");
}
size_t KnowledgeBankGrpcServiceImpl::KnowledgeBankSize() {
absl::ReaderMutexLock lock(&map_mu_);
return kb_map_.size();
}
Status KnowledgeBankGrpcServiceImpl::StartSessionIfNecessary(
const std::string& session_handle, const bool require_candidate_sampler,
const bool require_memory_store) {
StartSessionRequest request;
request.ParseFromString(session_handle);
if (require_candidate_sampler &&
!request.config().has_candidate_sampler_config()) {
return Status(StatusCode::FAILED_PRECONDITION,
"candidate_sampler_config is required but is empty.");
}
if (require_memory_store && !request.config().has_memory_store_config()) {
return Status(StatusCode::FAILED_PRECONDITION,
"memory_store_config is required but is empty.");
}
absl::MutexLock lock(&map_mu_);
if (request.config().has_knowledge_bank_config() &&
!kb_map_.contains(session_handle)) {
// Creates a new KnowledgeBank.
auto knowledge_bank =
KnowledgeBankFactory::Make(request.config().knowledge_bank_config(),
request.config().embedding_dimension());
if (knowledge_bank == nullptr) {
return Status(StatusCode::INTERNAL, "Creating KnowledgeBank failed.");
}
kb_map_[session_handle] = std::move(knowledge_bank);
}
if (request.config().has_gradient_descent_config() &&
!gd_map_.contains(session_handle)) {
auto optimizer = GradientDescentOptimizer::Create(
request.config().embedding_dimension(),
request.config().gradient_descent_config());
if (optimizer == nullptr) {
return Status(StatusCode::INTERNAL,
"Creating GradientDescentOptimizer failed.");
}
gd_map_[session_handle] = std::move(optimizer);
}
if (request.config().has_candidate_sampler_config() &&
!cs_map_.contains(session_handle)) {
auto sampler = candidate_sampling::SamplerFactory::Make(
request.config().candidate_sampler_config());
if (sampler == nullptr) {
return Status(StatusCode::INTERNAL, "Creating CandidateSampler failed.");
}
cs_map_[session_handle] = std::move(sampler);
}
if (request.config().has_memory_store_config() &&
!ms_map_.contains(session_handle)) {
auto memory_store = memory_store::MemoryStoreFactory::Make(
request.config().memory_store_config());
if (memory_store == nullptr) {
return Status(StatusCode::INTERNAL, "Creating MemoryStore failed.");
}
ms_map_[session_handle] = std::move(memory_store);
}
return Status::OK;
}
} // namespace carls