broadcast_op_handle.cc 9.4 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//   Copyright (c) 2018 PaddlePaddle 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.

C
chengduoZH 已提交
15
#include "paddle/fluid/framework/details/broadcast_op_handle.h"
16

17
#include "paddle/fluid/framework/convert_utils.h"
Y
Yu Yang 已提交
18 19
#include "paddle/fluid/framework/details/container_cast.h"
#include "paddle/fluid/framework/details/variable_visitor.h"
20
#include "paddle/fluid/platform/place.h"
21
#include "paddle/fluid/platform/profiler/event_tracing.h"
C
chengduoZH 已提交
22 23 24 25 26

namespace paddle {
namespace framework {
namespace details {

C
chengduoZH 已提交
27
void BroadcastOpHandle::RunImpl() {
28 29
  platform::RecordEvent record_event(
      Name(), platform::TracerEventType::Communication, 1);
C
chengduoZH 已提交
30
  if (places_.size() == 1) return;
Y
Yu Yang 已提交
31

C
chengduoZH 已提交
32
  // The input and output may have dummy vars.
C
chengduo 已提交
33
  auto in_var_handles = DynamicCast<VarHandle>(inputs_);
Y
Yu Yang 已提交
34
  auto out_var_handles = DynamicCast<VarHandle>(outputs_);
C
chengduoZH 已提交
35

C
chengduo 已提交
36
  PADDLE_ENFORCE_EQ(in_var_handles.size(), 1UL,
37 38 39 40 41 42 43 44 45
                    platform::errors::PreconditionNotMet(
                        "The number of inputs should be 1, but got %d.",
                        in_var_handles.size()));
  PADDLE_ENFORCE_EQ(out_var_handles.size(), places_.size(),
                    platform::errors::PreconditionNotMet(
                        "The number of outputs and the number of places should "
                        "be equal, but got the number of outputs is %d and the "
                        "number of places is %d.",
                        out_var_handles.size(), places_.size()));
C
chengduoZH 已提交
46

C
chengduo 已提交
47 48
  VarHandle *in_var_handle = in_var_handles[0];

49
  BroadcastOneVar(*in_var_handle, out_var_handles, local_exec_scopes_);
50 51 52 53 54
}

void BroadcastOpHandle::BroadcastOneVar(
    const VarHandle &in_var_handle,
    const std::vector<VarHandle *> &out_var_handles,
55
    const std::vector<Scope *> &var_scopes) {
C
chengduoZH 已提交
56
  auto *in_var =
G
gongweibao 已提交
57
      var_scopes.at(in_var_handle.scope_idx())->FindVar(in_var_handle.name());
58 59 60
  PADDLE_ENFORCE_NOT_NULL(
      in_var, platform::errors::NotFound("Variable %s is not found in scopes.",
                                         in_var_handle.name()));
Y
Yu Yang 已提交
61
  Tensor &in_tensor = VariableVisitor::GetMutableTensor(in_var);
62
  if (UNLIKELY(!in_tensor.IsInitialized())) {
G
gongweibao 已提交
63
    VLOG(3) << "in var " << in_var_handle.name() << "not inited, return!";
64 65
    return;
  }
C
chengduoZH 已提交
66

67
  InitOutputValue(in_var_handle, out_var_handles);
C
chengduoZH 已提交
68

C
chengduoZH 已提交
69
  if (platform::is_cpu_place(in_tensor.place())) {
70
    WaitInputVarGenerated();
C
chengduoZH 已提交
71
    for (auto *out_var_handle : out_var_handles) {
72
      if (out_var_handle->IsTheSameVar(in_var_handle)) {
C
chengduoZH 已提交
73 74
        continue;
      }
G
gongweibao 已提交
75 76 77
      auto &out_p = out_var_handle->place();
      auto *out_var = var_scopes.at(out_var_handle->scope_idx())
                          ->FindVar(out_var_handle->name());
C
chengduoZH 已提交
78

C
chengduoZH 已提交
79
      RunAndRecordEvent(out_p, [in_tensor, out_var] {
C
chengduoZH 已提交
80
        paddle::framework::TensorCopy(
C
chengduoZH 已提交
81
            in_tensor, platform::CPUPlace(),
C
chengduoZH 已提交
82 83 84
            &VariableVisitor::GetMutableTensor(out_var));
      });
    }
85
  } else if (platform::is_gpu_place(in_tensor.place())) {
86
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
C
chengduoZH 已提交
87
    VarHandle *out_handle = nullptr;
88
    int root_id = in_tensor.place().device;
C
chengduoZH 已提交
89 90
    std::vector<std::function<void()>> broadcast_calls;

91 92
    int type = platform::ToNCCLDataType(
        framework::TransToProtoVarType(in_tensor.dtype()));
C
chengduoZH 已提交
93 94
    size_t numel = static_cast<size_t>(in_tensor.numel());

C
chengduoZH 已提交
95
    for (auto out_var_handle : out_var_handles) {
G
gongweibao 已提交
96 97
      Variable *out_var = var_scopes.at(out_var_handle->scope_idx())
                              ->FindVar(out_var_handle->name());
C
chengduoZH 已提交
98

99
      int dst_id = out_var_handle->place().device;
C
chengduoZH 已提交
100

C
chengduoZH 已提交
101
      auto &nccl_ctx = nccl_ctxs_->at(dst_id);
C
chengduoZH 已提交
102 103

      void *send_recv_buffer = nullptr;
C
chengduoZH 已提交
104
      if (root_id == dst_id) {
105
        send_recv_buffer = const_cast<void *>(in_tensor.data());
C
chengduoZH 已提交
106 107
        out_handle = out_var_handle;
      } else {
C
chengduoZH 已提交
108 109
        send_recv_buffer = VariableVisitor::GetMutableTensor(out_var)
                               .Resize(in_tensor.dims())
G
gongweibao 已提交
110
                               .mutable_data(out_var_handle->place());
C
chengduoZH 已提交
111 112
      }

C
chengduoZH 已提交
113 114
      broadcast_calls.emplace_back(
          [send_recv_buffer, numel, type, root_id, &nccl_ctx] {
115
            PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclBcast(
C
chengduoZH 已提交
116 117 118
                send_recv_buffer, numel, static_cast<ncclDataType_t>(type),
                root_id, nccl_ctx.comm_, nccl_ctx.stream()));
          });
Y
Yu Yang 已提交
119 120
    }

121
    WaitInputVarGenerated();
122 123 124 125 126
    this->RunAndRecordEvent([&] {
      {
        platform::NCCLGroupGuard guard;
        for (auto &call : broadcast_calls) {
          call();
C
chengduoZH 已提交
127
        }
128
      }
C
chengduoZH 已提交
129

130
      if (!out_handle->IsTheSameVar(in_var_handle)) {
G
gongweibao 已提交
131 132
        auto out_var = var_scopes.at(in_var_handle.scope_idx())
                           ->FindVar(out_var_handles[0]->name());
133
        paddle::framework::TensorCopy(
G
gongweibao 已提交
134 135
            in_tensor, in_var_handle.place(),
            *(dev_ctxes_.at(in_var_handle.place())),
136 137 138
            &VariableVisitor::GetMutableTensor(out_var));
      }
    });
C
chengduo 已提交
139 140 141
    for (auto &p : places_) {
      nccl_ctxs_->DevCtx(p)->Wait();
    }
C
chengduoZH 已提交
142
#else
143 144
    PADDLE_THROW(
        platform::errors::PreconditionNotMet("Not compiled with NCLL."));
145 146 147 148
#endif
  } else {
#if defined(PADDLE_WITH_XPU_BKCL)
    VarHandle *out_handle = nullptr;
149
    int root_id = in_tensor.place().device;
150 151
    std::vector<std::function<void()>> broadcast_calls;

152 153
    int type = platform::ToBKCLDataType(
        framework::TransToProtoVarType(in_tensor.dtype()));
154 155 156 157 158 159
    size_t numel = static_cast<size_t>(in_tensor.numel());

    for (auto out_var_handle : out_var_handles) {
      Variable *out_var = var_scopes.at(out_var_handle->scope_idx())
                              ->FindVar(out_var_handle->name());

160
      int dst_id = out_var_handle->place().device;
161 162 163 164 165

      auto &bkcl_ctx = bkcl_ctxs_->at(dst_id);

      void *send_recv_buffer = nullptr;
      if (root_id == dst_id) {
166
        send_recv_buffer = const_cast<void *>(in_tensor.data());
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
        out_handle = out_var_handle;
      } else {
        send_recv_buffer = VariableVisitor::GetMutableTensor(out_var)
                               .Resize(in_tensor.dims())
                               .mutable_data(out_var_handle->place());
      }

      broadcast_calls.emplace_back([send_recv_buffer, numel, type, root_id,
                                    &bkcl_ctx] {
        PADDLE_ENFORCE_EQ(
            bkcl_broadcast(bkcl_ctx.comm(), send_recv_buffer, send_recv_buffer,
                           numel, static_cast<BKCLDataType>(type), root_id,
                           nullptr),
            BKCL_SUCCESS,
            platform::errors::Unavailable("bkcl_broadcast failed"));
      });
    }

    WaitInputVarGenerated();
    this->RunAndRecordEvent([&] {
      {
        PADDLE_ENFORCE_EQ(
            bkcl_group_start(), BKCL_SUCCESS,
            platform::errors::Unavailable("bkcl_group_start failed"));
        for (auto &call : broadcast_calls) {
          call();
        }
        PADDLE_ENFORCE_EQ(
            bkcl_group_end(), BKCL_SUCCESS,
            platform::errors::Unavailable("bkcl_group_end failed"));
      }

      if (!out_handle->IsTheSameVar(in_var_handle)) {
        auto out_var = var_scopes.at(in_var_handle.scope_idx())
                           ->FindVar(out_var_handles[0]->name());
        paddle::framework::TensorCopy(
            in_tensor, in_var_handle.place(),
            *(dev_ctxes_.at(in_var_handle.place())),
            &VariableVisitor::GetMutableTensor(out_var));
      }
    });
#else
    PADDLE_THROW(
        platform::errors::PreconditionNotMet("Not compiled with BKCL."));
C
chengduoZH 已提交
211
#endif
C
chengduoZH 已提交
212 213 214
  }
}

215 216 217
void BroadcastOpHandle::InitOutputValue(
    const VarHandle &in_var_handle,
    const std::vector<VarHandle *> &out_var_handles) const {
218
  auto &var_scopes = local_exec_scopes_;
219
  auto *in_var =
G
gongweibao 已提交
220
      var_scopes.at(in_var_handle.scope_idx())->FindVar(in_var_handle.name());
221 222 223 224 225 226 227 228 229

  Tensor &in_tensor = VariableVisitor::GetMutableTensor(in_var);

  // NOTE: The tensors' Place of input and output must be all on GPU or all on
  // CPU.
  for (auto *out_var_handle : out_var_handles) {
    if (out_var_handle->IsTheSameVar(in_var_handle)) {
      continue;
    }
G
gongweibao 已提交
230 231 232
    auto t_out_p = out_var_handle->place();
    auto *out_var = var_scopes.at(out_var_handle->scope_idx())
                        ->FindVar(out_var_handle->name());
233 234 235
    PADDLE_ENFORCE_NOT_NULL(out_var, platform::errors::NotFound(
                                         "Variable %s is not found in scopes.",
                                         out_var_handle->name()));
236
    if (platform::is_gpu_place(in_tensor.place())) {
237 238 239
      PADDLE_ENFORCE_EQ(platform::is_gpu_place(t_out_p), true,
                        platform::errors::PreconditionNotMet(
                            "Places of input and output must be all on GPU."));
240 241 242 243 244
    } else {
      t_out_p = platform::CPUPlace();
    }
    VariableVisitor::ShareDimsAndLoD(*in_var, out_var);
    VariableVisitor::GetMutableTensor(out_var).mutable_data(t_out_p,
245
                                                            in_tensor.dtype());
246 247 248
  }
}

C
chengduoZH 已提交
249
std::string BroadcastOpHandle::Name() const { return "broadcast"; }
C
chengduoZH 已提交
250 251 252
}  // namespace details
}  // namespace framework
}  // namespace paddle