reduce_op_handle.cc 6.2 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//   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.

#include "paddle/fluid/framework/details/reduce_op_handle.h"
C
chengduoZH 已提交
16
#include "paddle/fluid/framework/details/container_cast.h"
C
chengduoZH 已提交
17
#include "paddle/fluid/framework/details/reduce_and_gather.h"
C
chengduoZH 已提交
18
#include "paddle/fluid/framework/details/variable_visitor.h"
C
chengduoZH 已提交
19 20 21 22 23 24

namespace paddle {
namespace framework {
namespace details {

void ReduceOpHandle::RunImpl() {
C
chengduoZH 已提交
25
  if (places_.size() == 1) return;
C
chengduoZH 已提交
26
  // the input and output may have dummy var.
C
chengduoZH 已提交
27
  auto in_var_handles = DynamicCast<VarHandle>(inputs_);
C
chengduoZH 已提交
28 29 30 31 32

  PADDLE_ENFORCE_EQ(
      in_var_handles.size(), places_.size(),
      "The number of output should equal to the number of places.");

C
chengduoZH 已提交
33 34 35 36 37 38 39 40
  VarHandle *out_var_handle;
  {
    auto out_var_handles = DynamicCast<VarHandle>(outputs_);

    PADDLE_ENFORCE_EQ(out_var_handles.size(), 1,
                      "The number of output should be one.");
    out_var_handle = out_var_handles.front();
  }
C
chengduoZH 已提交
41

C
chengduoZH 已提交
42
  auto in_0_handle = in_var_handles[0];
C
chengduoZH 已提交
43

C
chengduoZH 已提交
44 45 46 47 48 49 50 51 52 53 54
  std::vector<const Scope *> var_scopes;
  for (auto *s : local_scopes_) {
    var_scopes.emplace_back(s->FindVar(kLocalExecScopeName)->Get<Scope *>());
  }

  auto pre_in_var =
      var_scopes.at(in_0_handle->scope_idx_)->FindVar(in_0_handle->name_);
  PADDLE_ENFORCE_NOT_NULL(pre_in_var);

  // Wait input done, this Wait is asynchronous operation
  WaitInputVarGenerated(in_var_handles);
C
chengduoZH 已提交
55

C
chengduoZH 已提交
56
  // NOTE: The Places of all input tensor must be all on CPU or all on GPU.
C
chengduoZH 已提交
57
  std::vector<platform::Place> in_places;  // used to get dev_ctx
C
chengduoZH 已提交
58
  for (auto *in_handle : in_var_handles) {
C
chengduoZH 已提交
59
    in_places.emplace_back(in_handle->place_);
C
chengduoZH 已提交
60 61 62
    auto in_var =
        var_scopes.at(in_handle->scope_idx_)->FindVar(in_handle->name_);
    PADDLE_ENFORCE_NOT_NULL(in_var);
C
chengduoZH 已提交
63
    VariableVisitor::EnforceShapeAndDTypeEQ(*pre_in_var, *in_var);
C
chengduoZH 已提交
64
  }
C
chengduoZH 已提交
65

C
chengduoZH 已提交
66 67 68
  auto out_var =
      var_scopes.at(out_var_handle->scope_idx_)->FindVar(out_var_handle->name_);
  PADDLE_ENFORCE_NOT_NULL(out_var);
C
chengduoZH 已提交
69

C
chengduoZH 已提交
70 71 72 73 74 75 76 77 78 79 80
  // NOTE: The tensors' Place of input and output must be all on GPU or all on
  // CPU.
  auto in_p = VariableVisitor::GetMutableTensor(pre_in_var).place();
  platform::Place t_out_p;
  if (platform::is_gpu_place(in_p)) {
    PADDLE_ENFORCE(platform::is_gpu_place(out_var_handle->place_),
                   "Places of input and output must be all on GPU.");
    t_out_p = out_var_handle->place_;
  } else {
    t_out_p = platform::CPUPlace();
  }
C
chengduoZH 已提交
81

C
chengduoZH 已提交
82 83 84
  if (pre_in_var->IsType<framework::SelectedRows>()) {
    std::vector<const SelectedRows *> in_selected_rows =
        GetInputValues<SelectedRows>(in_var_handles, var_scopes);
C
chengduoZH 已提交
85

C
chengduoZH 已提交
86
    GatherSelectedRows(in_selected_rows, in_places, dev_ctxes_, t_out_p,
C
chengduoZH 已提交
87
                       out_var->GetMutable<framework::SelectedRows>());
C
chengduoZH 已提交
88
  } else {
C
chengduoZH 已提交
89 90
    std::vector<const LoDTensor *> lod_tensors =
        GetInputValues<LoDTensor>(in_var_handles, var_scopes);
C
chengduoZH 已提交
91

C
chengduoZH 已提交
92
    if (paddle::platform::is_cpu_place(lod_tensors[0]->place())) {
C
chengduoZH 已提交
93 94 95
      ReduceLoDTensor func(lod_tensors,
                           out_var->GetMutable<framework::LoDTensor>());
      VisitDataType(ToDataType(lod_tensors[0]->type()), func);
C
chengduoZH 已提交
96
    } else if (paddle::platform::is_gpu_place(lod_tensors[0]->place())) {
C
chengduoZH 已提交
97
#ifdef PADDLE_WITH_CUDA
C
chengduoZH 已提交
98 99 100 101
      auto pre_in = pre_in_var->Get<framework::LoDTensor>();
      VariableVisitor::ShareDimsAndLoD(*pre_in_var, out_var);
      VariableVisitor::GetMutableTensor(out_var).mutable_data(
          out_var_handle->place_, pre_in.type());
C
chengduoZH 已提交
102

C
chengduoZH 已提交
103
      auto out_p = out_var_handle->place_;
C
chengduoZH 已提交
104
      int root_id = boost::get<platform::CUDAPlace>(out_p).device;
C
chengduoZH 已提交
105
      std::vector<std::function<void()>> all_reduce_calls;
C
chengduoZH 已提交
106
      for (size_t i = 0; i < var_scopes.size(); ++i) {
C
chengduoZH 已提交
107
        auto &p = in_places[i];
C
chengduoZH 已提交
108
        auto &lod_tensor = *lod_tensors[i];
C
chengduoZH 已提交
109

C
chengduoZH 已提交
110
        int dev_id = boost::get<platform::CUDAPlace>(p).device;
C
chengduoZH 已提交
111
        auto &nccl_ctx = nccl_ctxs_->at(dev_id);
C
chengduoZH 已提交
112 113 114

        void *buffer = const_cast<void *>(lod_tensor.data<void>());
        void *recvbuffer = nullptr;
C
chengduoZH 已提交
115
        if (root_id == dev_id) {
C
chengduoZH 已提交
116 117 118
          recvbuffer =
              out_var->GetMutable<framework::LoDTensor>()->mutable_data(
                  out_var_handle->place_);
C
chengduoZH 已提交
119 120
        }

C
chengduoZH 已提交
121
        int type = platform::ToNCCLDataType(lod_tensor.type());
C
chengduoZH 已提交
122 123 124 125 126 127 128
        size_t numel = static_cast<size_t>(lod_tensor.numel());
        all_reduce_calls.emplace_back(
            [buffer, recvbuffer, type, numel, root_id, &nccl_ctx] {
              PADDLE_ENFORCE(platform::dynload::ncclReduce(
                  buffer, recvbuffer, numel, static_cast<ncclDataType_t>(type),
                  ncclSum, root_id, nccl_ctx.comm_, nccl_ctx.stream()));
            });
C
chengduoZH 已提交
129 130
      }

C
chengduoZH 已提交
131 132 133 134 135 136
      this->RunAndRecordEvent([&] {
        platform::NCCLGroupGuard guard;
        for (auto &call : all_reduce_calls) {
          call();
        }
      });
C
chengduoZH 已提交
137
#else
C
chengduoZH 已提交
138
      PADDLE_THROW("CUDA is not enabled.");
C
chengduoZH 已提交
139 140
#endif
    } else {
C
chengduoZH 已提交
141
      PADDLE_THROW("Place should be CPUPlace or CUDAPlace.");
C
chengduoZH 已提交
142 143 144
    }
  }
}
C
chengduoZH 已提交
145

C
chengduoZH 已提交
146 147 148 149 150 151 152 153 154 155
template <typename T>
std::vector<const T *> ReduceOpHandle::GetInputValues(
    const std::vector<VarHandle *> &in_var_handles,
    const std::vector<const Scope *> &var_scopes) const {
  std::vector<const T *> in_selected_rows;
  for (auto *in_handle : in_var_handles) {
    auto &in_sr = var_scopes.at(in_handle->scope_idx_)
                      ->FindVar(in_handle->name_)
                      ->Get<T>();
    in_selected_rows.emplace_back(&in_sr);
C
chengduoZH 已提交
156
  }
C
chengduoZH 已提交
157
  return in_selected_rows;
C
chengduoZH 已提交
158 159
}

C
chengduoZH 已提交
160 161 162 163 164 165 166
void ReduceOpHandle::WaitInputVarGenerated(
    const std::vector<VarHandle *> &in_var_handles) {
  for (auto *in : in_var_handles) {
    if (in->generated_op_) {
      for (auto pair : dev_ctxes_) {
        in->generated_op_->Wait(pair.second);
      }
C
chengduoZH 已提交
167 168 169
    }
  }
}
C
chengduoZH 已提交
170

C
chengduoZH 已提交
171 172 173 174
std::string ReduceOpHandle::Name() const { return "reduce"; }
}  // namespace details
}  // namespace framework
}  // namespace paddle