Skip to content

Commit cec4e6e

Browse files
author
chengduo
authored
Merge pull request #9946 from chengduoZH/feature/add_reduce_op_handle
Feature/add reduce op handle
2 parents 23a21c8 + e63013a commit cec4e6e

File tree

6 files changed

+609
-30
lines changed

6 files changed

+609
-30
lines changed

paddle/fluid/framework/details/CMakeLists.txt

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,24 @@ cc_library(var_handle SRCS var_handle.cc DEPS place)
22
cc_library(op_handle_base SRCS op_handle_base.cc DEPS var_handle device_context lod_tensor)
33
cc_library(scale_loss_grad_op_handle SRCS scale_loss_grad_op_handle.cc DEPS op_handle_base scope lod_tensor ddim memory)
44
cc_library(fetch_op_handle SRCS fetch_op_handle.cc DEPS op_handle_base scope lod_tensor ddim memory)
5-
nv_library(nccl_all_reduce_op_handle SRCS nccl_all_reduce_op_handle.cc DEPS op_handle_base scope lod_tensor ddim memory
6-
dynload_cuda)
75
cc_library(computation_op_handle SRCS computation_op_handle.cc DEPS framework_proto scope place operator op_registry)
86
cc_library(send_op_handle SRCS send_op_handle.cc DEPS framework_proto scope place operator op_registry)
97

108
cc_library(ssa_graph SRCS ssa_graph.cc DEPS var_handle op_handle_base)
119
cc_library(ssa_graph_builder SRCS ssa_graph_builder.cc DEPS ssa_graph)
1210

1311
if(WITH_GPU)
12+
nv_library(nccl_all_reduce_op_handle SRCS nccl_all_reduce_op_handle.cc DEPS op_handle_base scope lod_tensor ddim memory
13+
dynload_cuda)
1414
set(multi_devices_graph_builder_deps nccl_all_reduce_op_handle)
15+
nv_library(reduce_op_handle SRCS reduce_op_handle.cc DEPS op_handle_base scope ddim dynload_cuda)
1516
else()
1617
set(multi_devices_graph_builder_deps)
18+
cc_library(reduce_op_handle SRCS reduce_op_handle.cc DEPS op_handle_base scope ddim)
1719
endif()
1820
cc_library(multi_devices_graph_builder SRCS multi_devices_graph_builder.cc DEPS ssa_graph_builder computation_op_handle
19-
scale_loss_grad_op_handle send_op_handle ${multi_devices_graph_builder_deps})
21+
scale_loss_grad_op_handle send_op_handle ${multi_devices_graph_builder_deps})
22+
2023
cc_library(ssa_graph_executor SRCS ssa_graph_executor.cc DEPS ssa_graph framework_proto)
2124
cc_library(threaded_ssa_graph_executor SRCS threaded_ssa_graph_executor.cc DEPS fetch_op_handle ssa_graph_executor scope
2225
simple_threadpool device_context)
@@ -30,3 +33,5 @@ cc_test(broadcast_op_test SRCS broadcast_op_handle_test.cc DEPS var_handle op_ha
3033
device_context broadcast_op_handle)
3134
cc_test(gather_op_test SRCS gather_op_handle_test.cc DEPS var_handle op_handle_base scope ddim memory
3235
device_context gather_op_handle)
36+
cc_test(reduce_op_handle_test SRCS reduce_op_handle_test.cc DEPS var_handle op_handle_base scope ddim memory
37+
device_context reduce_op_handle )

paddle/fluid/framework/details/nccl_all_reduce_op_handle.cc

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
// limitations under the License.
1414

1515
#include "paddle/fluid/framework/details/nccl_all_reduce_op_handle.h"
16-
1716
#include <algorithm>
17+
#include "paddle/fluid/framework/details/reduce_and_gather.h"
1818

1919
namespace paddle {
2020
namespace framework {
@@ -29,32 +29,6 @@ NCCLAllReduceOpHandle::NCCLAllReduceOpHandle(
2929
}
3030
}
3131

32-
struct ReduceLoDTensor {
33-
const std::vector<LoDTensor> &src_tensors_;
34-
LoDTensor &dst_tensor_;
35-
36-
ReduceLoDTensor(const std::vector<LoDTensor> &src, LoDTensor *dst)
37-
: src_tensors_(src), dst_tensor_(*dst) {}
38-
39-
template <typename T>
40-
void operator()() const {
41-
PADDLE_ENFORCE(!src_tensors_.empty());
42-
auto &t0 = src_tensors_[0];
43-
PADDLE_ENFORCE_NE(t0.numel(), 0);
44-
dst_tensor_.Resize(t0.dims());
45-
T *dst = dst_tensor_.mutable_data<T>(platform::CPUPlace());
46-
std::copy(t0.data<T>(), t0.data<T>() + t0.numel(), dst);
47-
48-
for (size_t i = 1; i < src_tensors_.size(); ++i) {
49-
auto &t = src_tensors_[i];
50-
PADDLE_ENFORCE_EQ(t.dims(), t0.dims());
51-
PADDLE_ENFORCE_EQ(t.type(), t0.type());
52-
std::transform(t.data<T>(), t.data<T>() + t.numel(), dst, dst,
53-
[](T a, T b) -> T { return a + b; });
54-
}
55-
}
56-
};
57-
5832
void NCCLAllReduceOpHandle::RunImpl() {
5933
if (inputs_.size() == 1) {
6034
return; // No need to all reduce when GPU count = 1;
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
#pragma once
16+
#include <algorithm>
17+
#include <map>
18+
#include <vector>
19+
#include "paddle/fluid/framework/details/reduce_and_gather.h"
20+
#include "paddle/fluid/framework/lod_tensor.h"
21+
#include "paddle/fluid/framework/selected_rows.h"
22+
namespace paddle {
23+
namespace framework {
24+
namespace details {
25+
26+
struct ReduceLoDTensor {
27+
const std::vector<LoDTensor> &src_tensors_;
28+
LoDTensor &dst_tensor_;
29+
30+
ReduceLoDTensor(const std::vector<LoDTensor> &src, LoDTensor *dst)
31+
: src_tensors_(src), dst_tensor_(*dst) {}
32+
33+
template <typename T>
34+
void operator()() const {
35+
PADDLE_ENFORCE(!src_tensors_.empty());
36+
auto &t0 = src_tensors_[0];
37+
PADDLE_ENFORCE_NE(t0.numel(), 0);
38+
dst_tensor_.Resize(t0.dims());
39+
T *dst = dst_tensor_.mutable_data<T>(platform::CPUPlace());
40+
std::copy(t0.data<T>(), t0.data<T>() + t0.numel(), dst);
41+
42+
for (size_t i = 1; i < src_tensors_.size(); ++i) {
43+
auto &t = src_tensors_[i];
44+
PADDLE_ENFORCE_EQ(t.dims(), t0.dims());
45+
PADDLE_ENFORCE_EQ(t.type(), t0.type());
46+
std::transform(t.data<T>(), t.data<T>() + t.numel(), dst, dst,
47+
[](T a, T b) -> T { return a + b; });
48+
}
49+
}
50+
};
51+
52+
inline void GatherSelectedRows(
53+
const std::vector<const SelectedRows *> &src_selecte_rows_,
54+
const std::vector<platform::Place> &in_places,
55+
const std::unordered_map<platform::Place, platform::DeviceContext *,
56+
platform::PlaceHash> &dev_ctxes,
57+
const platform::Place &out_place, SelectedRows *dst_selecte_rows) {
58+
PADDLE_ENFORCE(!src_selecte_rows_.empty());
59+
60+
std::vector<Tensor> in_tensors;
61+
std::vector<int64_t> out_rows;
62+
63+
for (auto in_sr_ptr : src_selecte_rows_) {
64+
auto &in_sr = *in_sr_ptr;
65+
in_tensors.emplace_back(in_sr.value());
66+
out_rows.insert(out_rows.end(), in_sr.rows().begin(), in_sr.rows().end());
67+
}
68+
69+
auto &pre_in = src_selecte_rows_[0];
70+
71+
auto &dst_tensor = *dst_selecte_rows;
72+
dst_tensor.set_height(pre_in->height());
73+
dst_tensor.set_rows(out_rows);
74+
size_t rows = out_rows.size();
75+
DDim out_dim = pre_in->GetCompleteDims();
76+
out_dim[0] = static_cast<int64_t>(rows);
77+
dst_tensor.mutable_value()->Resize(out_dim);
78+
dst_tensor.mutable_value()->mutable_data(out_place, pre_in->value().type());
79+
Tensor *out_tensor = dst_tensor.mutable_value();
80+
81+
// copy
82+
int s = 0, e = 0;
83+
for (size_t j = 0; j < in_tensors.size(); ++j) {
84+
e += in_tensors[j].dims()[0];
85+
auto sub_out = out_tensor->Slice(s, e);
86+
paddle::framework::TensorCopy(in_tensors[j], out_place,
87+
*(dev_ctxes.at(in_places[j])), &sub_out);
88+
s = e;
89+
}
90+
}
91+
92+
} // namespace details
93+
} // namespace framework
94+
} // namespace paddle
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
#include "paddle/fluid/framework/details/reduce_op_handle.h"
16+
#include "paddle/fluid/framework/details/reduce_and_gather.h"
17+
18+
namespace paddle {
19+
namespace framework {
20+
namespace details {
21+
22+
void ReduceOpHandle::RunImpl() {
23+
// the input and output may have dummy var.
24+
std::vector<VarHandle *> in_var_handles = GetValidVarHandles(inputs_);
25+
std::vector<VarHandle *> out_var_handles = GetValidVarHandles(outputs_);
26+
27+
PADDLE_ENFORCE_EQ(
28+
in_var_handles.size(), places_.size(),
29+
"The number of output should equal to the number of places.");
30+
PADDLE_ENFORCE_EQ(out_var_handles.size(), 1,
31+
"The number of output should be one.");
32+
33+
// Wait input done, this Wait is asynchronous operation
34+
WaitEvents(in_var_handles);
35+
36+
// check in the same place
37+
auto in_0_handle = in_var_handles[0];
38+
auto pre_place = in_0_handle->place_;
39+
40+
std::vector<platform::Place> in_places;
41+
for (auto *in_handle : in_var_handles) {
42+
auto in_p = in_handle->place_;
43+
PADDLE_ENFORCE_EQ(in_p.which(), pre_place.which(),
44+
"Places must be all on CPU or all on CUDA.");
45+
in_places.emplace_back(in_p);
46+
}
47+
48+
auto out_var = local_scopes_[out_var_handles[0]->scope_idx_]->FindVar(
49+
out_var_handles[0]->name_);
50+
51+
auto pre_in_var =
52+
local_scopes_[in_0_handle->scope_idx_]->FindVar(in_0_handle->name_);
53+
54+
if (pre_in_var->IsType<framework::SelectedRows>()) {
55+
auto &pre_in = pre_in_var->Get<framework::SelectedRows>();
56+
std::vector<const SelectedRows *> in_selected_rows;
57+
58+
for (auto *in_handle : in_var_handles) {
59+
auto in_var =
60+
local_scopes_.at(in_handle->scope_idx_)->FindVar(in_handle->name_);
61+
auto &in_sr = in_var->Get<framework::SelectedRows>();
62+
63+
PADDLE_ENFORCE_EQ(in_sr.value().type(), pre_in.value().type(),
64+
"The type of input is not consistent.");
65+
66+
in_selected_rows.emplace_back(&in_sr);
67+
}
68+
auto trg = out_var->GetMutable<framework::SelectedRows>();
69+
GatherSelectedRows(in_selected_rows, in_places, dev_ctxes_,
70+
out_var_handles[0]->place_, trg);
71+
} else {
72+
auto pre_in = pre_in_var->Get<framework::LoDTensor>();
73+
std::vector<LoDTensor> lod_tensors;
74+
75+
// can be refined
76+
for (auto *in_handle : in_var_handles) {
77+
auto in_var =
78+
local_scopes_.at(in_handle->scope_idx_)->FindVar(in_handle->name_);
79+
auto &in_sr = in_var->Get<framework::LoDTensor>();
80+
81+
PADDLE_ENFORCE_EQ(in_sr.type(), pre_in.type(),
82+
"The type of input is not consistent.");
83+
84+
lod_tensors.emplace_back(in_sr);
85+
}
86+
87+
auto trg = out_var->GetMutable<framework::LoDTensor>();
88+
trg->Resize(pre_in.dims());
89+
trg->mutable_data(out_var_handles[0]->place_, pre_in.type());
90+
91+
if (paddle::platform::is_cpu_place(pre_place)) {
92+
ReduceLoDTensor func(lod_tensors, trg);
93+
VisitDataType(ToDataType(lod_tensors[0].type()), func);
94+
} else if (paddle::platform::is_gpu_place(pre_place)) {
95+
#ifdef PADDLE_WITH_CUDA
96+
auto out_p = out_var_handles[0]->place_;
97+
int root = boost::get<platform::CUDAPlace>(out_p).device;
98+
99+
std::vector<std::function<void()>> all_reduce_calls;
100+
for (size_t i = 0; i < local_scopes_.size(); ++i) {
101+
auto &p = in_places[i];
102+
auto &lod_tensor = lod_tensors[i];
103+
104+
int dev_id = boost::get<platform::CUDAPlace>(p).device;
105+
auto &nccl_ctx = nccl_ctxs_->at(dev_id);
106+
auto stream = nccl_ctx.stream();
107+
auto comm = nccl_ctx.comm_;
108+
109+
void *buffer = const_cast<void *>(lod_tensor.data<void>());
110+
void *recvbuffer = nullptr;
111+
if (root == dev_id) {
112+
recvbuffer = trg->mutable_data(out_var_handles[0]->place_);
113+
}
114+
115+
all_reduce_calls.emplace_back([=] {
116+
PADDLE_ENFORCE(platform::dynload::ncclReduce(
117+
buffer, recvbuffer, static_cast<size_t>(lod_tensor.numel()),
118+
platform::ToNCCLDataType(lod_tensor.type()), ncclSum, root, comm,
119+
stream));
120+
});
121+
}
122+
123+
this->RunAndRecordEvent([&] {
124+
platform::NCCLGroupGuard guard;
125+
for (auto &call : all_reduce_calls) {
126+
call();
127+
}
128+
});
129+
#else
130+
PADDLE_THROW("CUDA is not support.");
131+
#endif
132+
} else {
133+
PADDLE_THROW("Place should be CPUPlace or CUDAPlace.");
134+
}
135+
}
136+
}
137+
138+
void ReduceOpHandle::WaitEvents(
139+
const std::vector<VarHandle *> &in_var_handles) {
140+
if (in_var_handles[0]->generated_op_) {
141+
for (auto *in : in_var_handles) {
142+
in_var_handles[0]->generated_op_->Wait(dev_ctxes_[in->place_]);
143+
}
144+
}
145+
}
146+
147+
std::vector<VarHandle *> ReduceOpHandle::GetValidVarHandles(
148+
const std::vector<VarHandleBase *> &inputs) {
149+
std::vector<VarHandle *> in_var_handles;
150+
for (auto *in : inputs) {
151+
auto *in_handle = dynamic_cast<VarHandle *>(in);
152+
if (in_handle) {
153+
in_var_handles.push_back(in_handle);
154+
}
155+
}
156+
return in_var_handles;
157+
}
158+
std::string ReduceOpHandle::Name() const { return "reduce"; }
159+
} // namespace details
160+
} // namespace framework
161+
} // namespace paddle

0 commit comments

Comments
 (0)