reducer.h 7.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2020 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.

#pragma once
16
#include <ThreadPool.h>
17

18 19
#include <algorithm>
#include <iostream>
20
#include <map>
21
#include <memory>
22
#include <queue>
23 24
#include <string>
#include <unordered_map>
25
#include <unordered_set>
26 27
#include <utility>
#include <vector>
28

29
#include "paddle/fluid/framework/data_type.h"
30
#include "paddle/fluid/framework/tensor.h"
31
#include "paddle/fluid/framework/tensor_util.h"
32
#include "paddle/fluid/framework/variable.h"
33
#include "paddle/fluid/platform/for_range.h"
34
#include "paddle/phi/kernels/funcs/math_function.h"
35

36 37 38 39 40 41 42
namespace paddle {
namespace imperative {
class ParallelContext;
class VarBase;
class VariableWrapper;
}  // namespace imperative
}  // namespace paddle
43 44 45 46

namespace paddle {
namespace imperative {

K
kuizhiqing 已提交
47 48
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL) ||     \
    defined(PADDLE_WITH_XPU_BKCL) || defined(PADDLE_WITH_GLOO) || \
Z
zn 已提交
49
    defined(PADDLE_WITH_ASCEND_CL) || defined(PADDLE_WITH_CNCL)
50 51 52 53 54 55 56 57 58 59 60 61 62 63

template <typename T>
struct DivNRanksFunctor {
  DivNRanksFunctor(int64_t nranks, T* output)
      : nranks_(nranks), output_(output) {}
  HOSTDEVICE void operator()(size_t idx) const {
    output_[idx] /= static_cast<T>(nranks_);
  }
  int64_t nranks_;
  T* output_;
};

template <typename Dex>
struct DivNRanksForAllReduce {
64
  phi::DenseTensor* in_;
65 66
  int64_t nranks_;
  const platform::DeviceContext& ctx_;
67
  DivNRanksForAllReduce(phi::DenseTensor* in,
68
                        int64_t nranks,
69 70 71 72 73 74 75 76 77 78 79 80 81
                        const platform::DeviceContext& ctx)
      : in_(in), nranks_(nranks), ctx_(ctx) {}

  template <typename T>
  void apply() const {
    T* data = in_->mutable_data<T>(ctx_.GetPlace());
    platform::ForRange<Dex> for_range(static_cast<const Dex&>(ctx_),
                                      static_cast<size_t>(in_->numel()));
    DivNRanksFunctor<T> functor(nranks_, data);
    for_range(functor);
  }
};

82 83 84 85 86 87 88 89 90 91
class Group {
 public:
  // Here, we use dense_contents_ & sparse_contents_ to
  // achieve the tensor fuse. When is_sparse_ is true, sparse_contents_ work,
  // conversely, dense_contents_ works. It is mutex relationship.
  framework::Variable dense_contents_;
  framework::Variable* sparse_contents_ = nullptr;
  bool is_sparse_ = false;

  // for concat kernel
92
  std::vector<phi::DenseTensor> dense_tensors_;
93 94

  std::vector<size_t> length_;
95 96

  int64_t all_length_{0};
97 98 99 100 101 102 103 104 105 106 107
  // Global indices of participating variables in the group
  std::vector<size_t> variable_indices_;

  // Number of params that haven't been ready. When it is 0, it means
  // the group is ready.
  size_t pending_ = -1;

  // external message of group
  framework::proto::VarType::Type dtype_;

  // context is used to select the stream for concat
108
  void ConcatTensors(const platform::DeviceContext& context);
109 110

  // context is used to select the stream for split
111
  void SplitTensors(const platform::DeviceContext& context);
112

113
  // use it in CUDA
114
  void DivNRanks(phi::DenseTensor* tensor,
115
                 int64_t nranks,
116 117 118 119
                 const platform::DeviceContext& context);

  void DivNRanks(const platform::DeviceContext& context, int64_t nranks);

120
  friend std::ostream& operator<<(std::ostream&, const Group&);
121 122
};

123
struct VariableLocator {
124 125 126 127 128 129 130 131 132 133 134
  // record the index in groups_
  size_t group_index;
  size_t inside_group_index;
};

class Reducer {
 public:
  explicit Reducer(
      const std::vector<std::shared_ptr<imperative::VarBase>>& vars,
      const std::vector<std::vector<size_t>>& group_indices,
      const std::vector<bool>& is_sparse_gradient,
135
      std::shared_ptr<imperative::ParallelContext> parallel_ctx,
136 137
      const std::vector<size_t>& group_size_limits,
      bool find_unused_vars);
138 139 140 141 142

  virtual ~Reducer() {}

  void InitializeGroups(const std::vector<std::vector<size_t>>& group_indices);

143 144
  void InitializeDenseGroups(const std::vector<size_t>& variable_indices_,
                             Group* p_group);
145

146
  void PrepareDeps(const std::unordered_set<GradOpNode*>& init_nodes);
147

148
  void PrepareForBackward(
149 150
      const std::vector<std::shared_ptr<imperative::VarBase>>& outputs,
      const bool is_sync);
151

152
  void AddDistHook(size_t var_index);
153

154
  void MarkVarReady(const size_t var_index, const bool is_used_var);
155 156 157

  void MarkGroupReady(size_t group_index);

158 159
  void FusedAllReduceSchedule(const int run_order,
                              Group& group,  // NOLINT
160
                              const int curr_group_index);
161

162 163
  void FinalizeBackward();

164 165
  std::vector<std::vector<size_t>> RebuildGruops();

166
  inline bool NeedRebuildGroup() {
167
    return !has_rebuilt_group_ && !find_unused_vars_each_step_;
168 169 170 171 172
  }

  void ProcessUnusedDenseVars();

  bool HasGrad(size_t var_index);
173

174 175 176
  void TraverseBackwardGraph(
      const std::vector<std::shared_ptr<imperative::VarBase>>& outputs);

177 178 179 180 181 182 183 184 185
 private:
  std::vector<std::shared_ptr<imperative::VarBase>> vars_;
  std::vector<std::vector<size_t>> group_indices_;
  std::vector<Group> groups_;
  size_t next_group_ = 0;
  platform::Place place_;
  std::once_flag once_flag_;
  std::vector<bool> is_sparse_gradient_;
  std::shared_ptr<imperative::ParallelContext> parallel_ctx_;
186
  std::vector<VariableLocator> variable_locators_;
187

188
  int nrings_ = 1;
189
  int64_t nranks_ = -1;
190 191

  // Following variables are to help rebuild group
192 193
  // TODO(shenliang03): Support rebuild in the future.
  bool has_rebuilt_group_{true};
194 195 196
  std::vector<std::shared_ptr<imperative::VarBase>> rebuild_vars_;
  std::vector<int64_t> rebuild_var_indices_;
  const std::vector<size_t> group_size_limits_;
197 198 199 200 201 202

  // Following variables are to help unused vars
  std::unordered_map<GradOpNode*, size_t> node_deps_;
  std::unordered_map<VariableWrapper*, size_t> var_index_map_;
  std::vector<size_t> unused_vars_;
  bool has_marked_unused_vars_{false};
203 204
  bool find_unused_vars_each_step_{false};
  bool find_unused_vars_once_{true};
205
  bool groups_need_finalize_{false};
206 207 208 209 210 211 212
#ifdef PADDLE_WITH_XPU_BKCL
  // comm_pool_ is used for scheduling allreduce in multi Kunlun cards training.
  std::unique_ptr<::ThreadPool> comm_pool_{nullptr};
  uint32_t comm_op_count_;
  std::mutex mutex_;
  std::condition_variable cv_;
#endif
213

214 215 216 217 218 219
  // grad_need_hooks_ is used to mark whether gradient synchronization is
  // required across process. The default value is false. When backward()
  // is called, grad_need_hooks_ will be assigned to true during preparation
  // of backward and revert to false while finalizing backward.
  bool grad_need_hooks_{false};

220 221 222 223 224 225 226 227 228 229 230 231
  // it just for checking hook, each parameter can only trigger one hook
  std::vector<bool> vars_marked_ready_;

  // Following variables are to help control flow.
  // local_used_vars_ uses 0/1 to indicate whether the
  // var is used in iteration. After the end of the
  // iteration, global_used_vars_ is obtained synchronously
  // globally. Choose whether to update the local
  // gradient according to the global_used_vars_.
  std::vector<int> local_used_vars_;
  // global_used_vars_ is used in comm stream to avoid wait
  framework::Variable global_used_vars_;
232 233 234 235 236
};

std::vector<std::vector<size_t>> AssignGroupBySize(
    const std::vector<std::shared_ptr<imperative::VarBase>>& tensors,
    const std::vector<bool>& is_sparse_gradient,
237 238
    const std::vector<size_t>& group_size_limits,
    const std::vector<int64_t>& tensor_indices = {});
239 240 241 242
#endif

}  // namespace imperative
}  // namespace paddle