forked from tensorflow/tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaster.cc
More file actions
486 lines (446 loc) · 15.5 KB
/
Copy pathmaster.cc
File metadata and controls
486 lines (446 loc) · 15.5 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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/* Copyright 2016 The TensorFlow Authors. 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.
==============================================================================*/
// Master implements the service MasterSerivce.
//
// A Master maintains the state of live graph computation
// sessions, each session orchestrates both local and remote devices
// to carry out the graph computation.
//
// A Master knows ahead of time local devices available as
// client devices.
//
// A Master discovers remote devices on-demand and keeps track of
// statistics of those remote devices.
//
// Each session analyses the graph, places nodes across available
// devices, and ultimately drives the graph computation by initiating
// RunGraph on the workers.
#include "tensorflow/core/distributed_runtime/master.h"
#include <unordered_set>
#include <vector>
#include "tensorflow/core/common_runtime/process_util.h"
#include "tensorflow/core/distributed_runtime/remote_device.h"
#include "tensorflow/core/distributed_runtime/worker_cache.h"
#include "tensorflow/core/distributed_runtime/worker_interface.h"
#include "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/master.pb.h"
#include "tensorflow/core/protobuf/worker.pb.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
Master::Master(MasterEnv* env, double session_gc_seconds)
: env_(env),
last_1000_steps_(1000),
step_count_(0),
session_gc_seconds_(session_gc_seconds) {
// Right now, a master service must be co-located with a device.
// Otherwise, fetches do not work.
CHECK(!env->local_devices.empty());
if (session_gc_seconds_ > 0.0) {
gc_thread_ = env_->env->StartThread(ThreadOptions(), "TF_master_GC",
[this]() { GC(); });
} else {
gc_thread_ = nullptr;
}
}
Master::~Master() {
if (gc_thread_) {
mutex_lock l(mu_);
shutdown_ = true;
shutdown_cv_.notify_all();
delete gc_thread_;
}
}
void Master::GC() {
Env* env = Env::Default();
while (true) {
mutex_lock l(mu_);
const int kTimeoutMilliseconds = 10 * 1000; // 10 seconds.
WaitForMilliseconds(&l, &shutdown_cv_, kTimeoutMilliseconds);
if (shutdown_) {
break;
}
std::vector<string> handles;
const int64 num_micros = static_cast<int64>(session_gc_seconds_ * 1000000);
for (const auto& entry : sessions_) {
int64 lat = entry.second->last_access_time_usec();
if (static_cast<int64>(env->NowMicros()) - lat > num_micros) {
handles.push_back(entry.first);
auto* sess = entry.second;
SchedClosure([this, sess]() {
LOG(WARNING) << "GC session " << sess->handle() << " after "
<< session_gc_seconds_ << " seconds. "
<< "Note that if you are starting multiple replicas "
<< "on a staggered delay, session_gc_seconds may need "
<< "to be raised.";
sess->GarbageCollect();
});
}
}
for (const auto& handle : handles) sessions_.erase(handle);
}
}
class DeviceFinder {
public:
static Status GetRemoteDevices(
const protobuf::RepeatedPtrField<string>& device_filters, MasterEnv* env,
std::vector<Device*>* out_remote) {
DeviceFinder finder(device_filters, env);
finder.Start();
TF_RETURN_IF_ERROR(finder.Wait());
finder.GetRemoteDevices(env->local_devices, out_remote);
return Status::OK();
}
private:
explicit DeviceFinder(
const protobuf::RepeatedPtrField<string>& device_filters, MasterEnv* env)
: env_(env) {
auto process_filter = [this](const string& filter) {
DeviceNameUtils::ParsedName parsed;
if (DeviceNameUtils::ParseFullName(filter, &parsed)) {
filters_.push_back(parsed);
} else {
LOG(FATAL) << "Skipping invalid filter: " << filter;
}
};
for (const string& filter : device_filters) {
process_filter(filter);
}
// Enumerates all known workers' target. A target name is a
// prefix of a device name. E.g., /job:mnist/replica:0/task:10.
std::vector<string> workers;
env_->worker_cache->ListWorkers(&workers);
if (filters_.empty()) {
std::swap(workers, targets_);
} else {
for (const string& name : workers) {
if (MatchFilters(name)) {
targets_.push_back(name);
}
}
}
seen_targets_.assign(targets_.size(), false);
}
~DeviceFinder() {
for (Device* dev : found_) delete dev;
}
void Start() {
{
mutex_lock l(mu_);
num_pending_ = targets_.size();
if (num_pending_ == 0) {
pending_zero_.notify_all();
}
}
// Talk to all workers to get the list of available devices.
using std::placeholders::_1;
using std::placeholders::_2;
for (size_t i = 0; i < targets_.size(); ++i) {
// TODO(mrry): Propagate a timeout here, since `this->WhenFound()` may
// never be called.
NewRemoteDevices(env_->env, env_->worker_cache, targets_[i],
std::bind(&ME::WhenFound, this, i, _1, _2));
}
}
// Every `kLoggingPeriodMs`, while the DeviceFinder is still waiting
// to hear from workers, log a list of the workers who have not
// responded.
const int32 kLoggingPeriodMs = 10 * 1000;
Status Wait() {
mutex_lock l(mu_);
// TODO(mrry): Propagate a timeout here, since `num_pending_` may
// never become zero.
while (num_pending_ != 0) {
pending_zero_.wait_for(l, std::chrono::milliseconds(kLoggingPeriodMs));
if (num_pending_ != 0) {
for (int i = 0; i < targets_.size(); ++i) {
if (!seen_targets_[i]) {
LOG(INFO)
<< "CreateSession still waiting for response from worker: "
<< targets_[i];
}
}
}
}
return status_;
}
// The caller takes the ownership of returned remote devices.
void GetRemoteDevices(const std::vector<Device*>& local,
std::vector<Device*>* remote) {
std::unordered_set<string> names(local.size());
for (Device* dev : local) names.insert(dev->name());
mutex_lock l(mu_);
for (Device* dev : found_) {
const string& name = dev->name();
if (names.insert(name).second && MatchFilters(name)) {
remote->push_back(dev);
} else {
delete dev;
}
}
found_.clear();
}
typedef DeviceFinder ME;
const MasterEnv* env_;
std::vector<DeviceNameUtils::ParsedName> filters_;
mutex mu_;
int num_pending_ GUARDED_BY(mu_);
condition_variable pending_zero_;
std::vector<Device*> found_ GUARDED_BY(mu_);
// List of targets to be contacted by this DeviceFinder. The
// respective `bool` in `seen_targets_` indicates whether we have
// heard from this target or not.
std::vector<string> targets_;
std::vector<bool> seen_targets_ GUARDED_BY(mu_);
Status status_;
void WhenFound(int target_index, const Status& s,
std::vector<Device*>* devices) {
mutex_lock l(mu_);
seen_targets_[target_index] = true;
if (!s.ok()) {
LOG(ERROR) << "Master init: " << s;
status_.Update(s);
} else {
found_.insert(found_.end(), devices->begin(), devices->end());
devices->clear();
}
--num_pending_;
if (num_pending_ == 0) {
pending_zero_.notify_all();
}
}
// Returns true iff the set of devices allowed by 'x' intersects
// with the set of devices allowed by 'y'.
bool Intersects(const DeviceNameUtils::ParsedName& x,
const DeviceNameUtils::ParsedName& y) {
return (!x.has_job || !y.has_job || x.job == y.job) &&
(!x.has_replica || !y.has_replica || x.replica == y.replica) &&
(!x.has_task || !y.has_task || x.task == y.task) &&
(!x.has_type || !y.has_type || x.type == y.type) &&
(!x.has_id || !y.has_id || x.id == y.id);
}
// Returns true iff 'name' matches one of the filters_.
bool MatchFilters(const string& name) {
if (filters_.empty()) return true;
DeviceNameUtils::ParsedName x;
if (DeviceNameUtils::ParseFullName(name, &x)) {
for (const auto& filter : filters_) {
if (Intersects(x, filter)) return true;
}
}
return false;
}
TF_DISALLOW_COPY_AND_ASSIGN(DeviceFinder);
};
void Master::CreateSession(const CreateSessionRequest* req,
CreateSessionResponse* resp, MyClosure done) {
SchedClosure([this, req, resp, done]() {
Status status = ValidateExternalGraphDefSyntax(req->graph_def());
if (status.ok()) {
// Ping all the workers and build the list of devices that the
// session will use.
std::vector<Device*> remote_devices;
status = DeviceFinder::GetRemoteDevices(req->config().device_filters(),
env_, &remote_devices);
if (!status.ok()) {
done(status);
return;
}
SessionOptions options;
options.config = req->config();
MasterSession* session =
env_->master_session_factory(options, env_, &remote_devices);
GraphDef* gdef =
const_cast<CreateSessionRequest*>(req)->mutable_graph_def();
Status create_status = session->Create(gdef);
if (!create_status.ok()) {
session->Close().IgnoreError();
session->Unref();
done(create_status);
return;
}
resp->set_session_handle(session->handle());
// Insert into the session map, which takes ownership of the session.
{
mutex_lock l(mu_);
CHECK(sessions_.insert({session->handle(), session}).second);
}
}
done(status);
});
}
void Master::ExtendSession(const ExtendSessionRequest* req,
ExtendSessionResponse* resp, MyClosure done) {
mu_.lock();
MasterSession* session = nullptr;
session = gtl::FindPtrOrNull(sessions_, req->session_handle());
if (session == nullptr) {
mu_.unlock();
done(errors::Aborted("Session ", req->session_handle(), " is not found."));
return;
}
session->Ref();
mu_.unlock();
SchedClosure([session, req, resp, done]() {
Status status = ValidateExternalGraphDefSyntax(req->graph_def());
if (status.ok()) {
status = session->Extend(req, resp);
}
session->Unref();
done(status);
});
}
void Master::PartialRunSetup(const PartialRunSetupRequest* req,
PartialRunSetupResponse* resp, MyClosure done) {
mu_.lock();
MasterSession* session = gtl::FindPtrOrNull(sessions_, req->session_handle());
if (session == nullptr) {
mu_.unlock();
done(errors::Aborted("Session ", req->session_handle(), " is not found."));
return;
}
session->Ref();
mu_.unlock();
SchedClosure([this, session, req, resp, done]() {
Status s = session->PartialRunSetup(req, resp);
session->Unref();
done(s);
});
}
void Master::RunStep(CallOptions* opts, const RunStepRequestWrapper* req,
MutableRunStepResponseWrapper* resp, MyClosure done) {
mu_.lock();
uint64 start_time = env_->env->NowMicros();
MasterSession* session = gtl::FindPtrOrNull(sessions_, req->session_handle());
if (session == nullptr) {
mu_.unlock();
done(errors::Aborted("Session ", req->session_handle(), " is not found."));
return;
}
session->Ref();
mu_.unlock();
SchedClosure([this, start_time, session, opts, req, resp, done]() {
Status status = session->Run(opts, *req, resp);
session->Unref();
uint64 done_time = env_->env->NowMicros();
done(status);
mutex_lock l(mu_);
last_1000_steps_.AddValue((done_time - start_time) / 1e9);
++step_count_;
});
}
void Master::CloseSession(const CloseSessionRequest* req,
CloseSessionResponse* resp, MyClosure done) {
MasterSession* session = nullptr;
{
mu_.lock();
auto iter = sessions_.find(req->session_handle());
if (iter == sessions_.end()) {
mu_.unlock();
done(errors::Aborted(
"Session ", req->session_handle(),
" is not found. Possibly, this master has restarted."));
return;
}
// NOTE(mrry): One reference to the session is transferred from
// `sessions_[req->session_handle()]` to `session`.
session = iter->second;
sessions_.erase(iter);
mu_.unlock();
}
// Session Close() blocks on thread shutdown. Therefore, we need to
// delete it in non-critical thread.
SchedClosure([session, done]() {
Status s = session->Close();
session->Unref();
done(s);
});
}
void Master::ListDevices(const ListDevicesRequest* req,
ListDevicesResponse* resp, MyClosure done) {
SchedClosure([this, req, resp, done]() {
std::vector<Device*> remote_devices;
Status s = DeviceFinder::GetRemoteDevices({}, env_, &remote_devices);
if (s.ok()) {
for (Device* dev : env_->local_devices) {
*(resp->add_local_device()) = dev->attributes();
}
for (Device* dev : remote_devices) {
*(resp->add_remote_device()) = dev->attributes();
delete dev;
}
}
done(s);
});
}
void Master::CleanupWorkers(const ResetRequest& reset) {
std::vector<string> worker_names;
env_->worker_cache->ListWorkers(&worker_names);
if (!worker_names.empty()) {
const int num_workers = worker_names.size();
std::vector<Notification> n(num_workers);
CleanupAllRequest req;
(*req.mutable_container()) = reset.container();
std::vector<CleanupAllResponse> resp(num_workers);
int c = 0;
for (int i = 0; i < num_workers; ++i) {
const string& worker_name = worker_names[i];
auto worker = env_->worker_cache->CreateWorker(worker_name);
if (worker) {
worker->CleanupAllAsync(
&req, &resp[i], [this, &n, worker_name, worker, c](Status s) {
TF_CHECK_OK(s);
env_->worker_cache->ReleaseWorker(worker_name, worker);
n[c].Notify();
});
} else {
n[c].Notify();
}
++c;
}
for (size_t i = 0; i < n.size(); ++i) {
n[i].WaitForNotification();
}
}
}
void Master::Reset(const ResetRequest* req, ResetResponse* resp,
MyClosure done) {
// Vector to hold the session pointers present in the sessions_
// (string->Session*) map.
std::vector<MasterSession*> sessions_to_close;
{
mutex_lock l(mu_);
// NOTE(mrry): Transfer one reference to each session from the
// `sessions_` map to the `sessions_to_close` vector.
for (const auto& entry : sessions_) {
sessions_to_close.push_back(entry.second);
}
sessions_.clear();
}
CleanupWorkers(*req);
SchedClosure([sessions_to_close, done]() {
Status s;
for (MasterSession* session : sessions_to_close) {
s.Update(session->Close());
session->Unref();
}
done(s);
});
}
} // end namespace tensorflow