aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/verbs/rdma_rendezvous_mgr.cc
blob: 74f6681af3c29f370d6cdb37d64e10a30cbb7b84 (plain)
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
/* Copyright 2017 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.
==============================================================================*/

#ifdef TENSORFLOW_USE_VERBS

#include "tensorflow/contrib/verbs/rdma_rendezvous_mgr.h"
#include <unordered_set>
#include "tensorflow/contrib/verbs/verbs_util.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#if GOOGLE_CUDA
#include "tensorflow/core/common_runtime/gpu/gpu_util.h"
#include "tensorflow/core/common_runtime/gpu/process_state.h"
#endif  // GOOGLE_CUDA
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"

namespace tensorflow {

class RdmaRemoteRendezvous : public BaseRemoteRendezvous {
 public:
  RdmaRemoteRendezvous(const WorkerEnv* env, int64 step_id, RdmaMgr* rdma_mgr)
      : BaseRemoteRendezvous(env, step_id), rdma_mgr_(rdma_mgr) {}

  void RecvPostCopyOps(const string& key, const string& key_with_step_id,
                       const Rendezvous::Args& recv_args,
                       const DoneCallback& done, const RdmaMessage& rm,
                       RdmaChannel* rc, Tensor& val, const Status& s);

 protected:
  void RecvFromRemoteAsync(const Rendezvous::ParsedKey& parsed,
                           const Rendezvous::Args& args,
                           DoneCallback done) override;

 private:
  ~RdmaRemoteRendezvous() override {}
  RdmaMgr* rdma_mgr_;

  TF_DISALLOW_COPY_AND_ASSIGN(RdmaRemoteRendezvous);
};

void RdmaRemoteRendezvous::RecvFromRemoteAsync(
    const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& recv_args,
    DoneCallback done) {
  Status s;
  // parse src_name and dst_name
  string src_name, dst_name, unused;
  if (!DeviceNameUtils::SplitDeviceName(parsed.src_device, &src_name,
                                        &unused) ||
      !DeviceNameUtils::SplitDeviceName(parsed.dst_device, &dst_name,
                                        &unused)) {
    s = errors::Internal("Could not parse src or dst name.");
  }
  if (!s.ok()) {
    LOG(ERROR) << "s is not ok, error code " << s.error_message();
    done(s, Args(), recv_args, Tensor{}, false);
    return;
  }
  CHECK(dst_name.compare(rdma_mgr_->local_worker()) == 0);
  RdmaChannel* rc = rdma_mgr_->FindChannel(src_name);
  string key(std::move(parsed.FullKey().ToString()));
  string key_with_step_id = VerbsUtil::AppendStepidToKey(key, step_id_);
  // insert callback
  rc->InsertRecvCallback(key_with_step_id, [this, key, key_with_step_id, rc,
                                            recv_args, parsed, done]() {
    Status src_s, dst_s, s;
    Device* src_dev, *dst_dev;
    src_s = env_->device_mgr->LookupDevice("CPU:0", &src_dev);
    dst_s = env_->device_mgr->LookupDevice(parsed.dst_device, &dst_dev);
    if (!src_s.ok() || !dst_s.ok()) {
      s = src_s.ok() ? dst_s : src_s;
      LOG(ERROR) << "s is not ok, error code " << s.error_message();
      done(s, Args(), recv_args, Tensor(), true);
      return;
    }
    RdmaBuffer* rb = rc->FindBuffer(key);
    RdmaMessage rm;
    CHECK(rb->size_ >= RdmaMessage::kMessageTotalBytes);
    RdmaMessage::ParseMessage(rm, rb->buffer_);
    CHECK(rm.type_ == RDMA_MESSAGE_TENSOR_WRITE);
    Tensor val;
    if (!rm.is_dead_) {
      void* input = static_cast<char*>(rb->buffer_) +
                    RdmaMessage::kTensorBufferStartIndex;
      bool can_memcpy = DataTypeCanUseMemcpy(rm.data_type_);
      if (can_memcpy) {
        if (dst_dev->tensorflow_gpu_device_info() &&
            (!recv_args.alloc_attrs.on_host())) {
#if GOOGLE_CUDA
          CHECK(recv_args.device_context)
              << "send dev name: " << src_dev->name()
              << " gpu_info: " << src_dev->tensorflow_gpu_device_info();
          Allocator* alloc = ProcessState::singleton()->GetCUDAHostAllocator(0);
          Tensor copy(alloc, rm.data_type_, rm.tensor_shape_);
          memcpy(DMAHelper::base(&copy), input, rm.tensor_bytes_);

          Allocator* dst_alloc = dst_dev->GetAllocator(recv_args.alloc_attrs);
          Tensor gpu_copy(dst_alloc, rm.data_type_, rm.tensor_shape_);

          GPUUtil::CopyCPUTensorToGPU(
              &copy, recv_args.device_context, dst_dev, &gpu_copy,
              [this, gpu_copy, key, key_with_step_id, recv_args, done, rm, rc](
                  const Status& s) {
                CHECK(s.ok()) << "copy tensor to gpu sync";
                Tensor val;
                val = std::move(gpu_copy);
                RecvPostCopyOps(key, key_with_step_id, recv_args, done, rm, rc,
                                val, s);
              });
#endif  // GOOGLE_CUDA
          return;
        } else {
          AllocatorAttributes host_alloc_attrs;
          host_alloc_attrs.set_gpu_compatible(true);
          host_alloc_attrs.set_on_host(true);
          Allocator* alloc = dst_dev->GetAllocator(host_alloc_attrs);
          Tensor copy(alloc, rm.data_type_, rm.tensor_shape_);
          memcpy(DMAHelper::base(&copy), input, rm.tensor_bytes_);
          val = std::move(copy);
        }
      } else {
        TensorProto proto;
        CHECK(rm.tensor_bytes_ + RdmaMessage::kTensorBufferStartIndex <=
              rb->size_);
        CHECK(ParseProtoUnlimited(&proto, input, rm.tensor_bytes_))
            << "fail to parse proto from array";
        s = dst_dev->MakeTensorFromProto(proto, recv_args.alloc_attrs, &val);
      }
    }
    RecvPostCopyOps(key, key_with_step_id, recv_args, done, rm, rc, val, s);
  });
  // append key to message queue
  RdmaBuffer* rb = rc->tx_message_buffer_;
  RdmaMessage rm;
  rm.type_ = RDMA_MESSAGE_TENSOR_REQUEST;
  rm.name_size_ = key.size();
  rm.name_ = key;
  rm.step_id_ = step_id_;
  string message = RdmaMessage::CreateMessage(rm);
  rb->EnqueueItem(message);
  rb->SendNextItem();
}

void RdmaRemoteRendezvous::RecvPostCopyOps(
    const string& key, const string& key_with_step_id,
    const Rendezvous::Args& recv_args, const DoneCallback& done,
    const RdmaMessage& rm, RdmaChannel* rc, Tensor& val, const Status& s) {
  rc->RemoveRecvCallback(key_with_step_id);
  RdmaMessage br;
  br.type_ = RDMA_MESSAGE_BUFFER_IDLE;
  br.name_size_ = key.size();
  br.name_ = key;
  string message = RdmaMessage::CreateMessage(br);
  RdmaBuffer* tb = rc->tx_message_buffer_;
  tb->EnqueueItem(message);
  tb->SendNextItem();
  done(s, Args(), recv_args, val, rm.is_dead_);
}

RdmaRendezvousMgr::RdmaRendezvousMgr(const WorkerEnv* env)
    : BaseRendezvousMgr(env) {}

BaseRemoteRendezvous* RdmaRendezvousMgr::Create(int64 step_id,
                                                const WorkerEnv* worker_env) {
  return new RdmaRemoteRendezvous(worker_env, step_id, rdma_mgr_);
}

}  // end namespace tensorflow

#endif