gradient_accumulator.h 5.8 KB
Newer Older
J
Jiabin Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (c) 2019 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

#include <memory>
#include <utility>
#include <vector>
20

21
#include "paddle/fluid/eager/eager_tensor.h"
22
#include "paddle/fluid/imperative/hooks.h"
J
Jiabin Yang 已提交
23 24 25 26 27 28 29
#include "paddle/fluid/imperative/layer.h"

namespace paddle {
namespace imperative {

class GradientAccumulator {
 public:
30 31 32 33 34
  explicit GradientAccumulator(VariableWrapper* var) {
    // var may be initialized, so Synchronous VariableWrapper with Variable
    if (var && var->Var().IsInitialized()) {
      if (var->Var().IsType<framework::LoDTensor>()) {
        var->SetType(framework::proto::VarType::LOD_TENSOR);
35
      } else if (var->Var().IsType<pten::SelectedRows>()) {
36 37 38 39 40 41 42 43
        var->SetType(framework::proto::VarType::SELECTED_ROWS);
      } else {
        PADDLE_THROW(platform::errors::PermissionDenied(
            "Only support LoDTensor and SelectedRows for gradient var"));
      }
    }

    // inner_var_ record the grad of this auto-grad.
44 45
    // Only need to generate inner var for leaf-tensor.
    if (var->IsLeafGrad()) {
46 47 48
      inner_var_ = std::make_shared<VariableWrapper>(var->Name());
      inner_var_->SetType(var->Type());
      inner_var_->SetDataType(var->DataType());
49
      inner_var_->SetForwardDataType(var->ForwardDataType());
50 51 52 53 54 55 56 57 58 59 60 61 62
      inner_var_->InnerSetOverridedStopGradient(
          var->InnerOverridedStopGradient());
      VLOG(6) << " Create inner grad var for (" << var->Name()
              << ") to store result of this Graph";
    }

    // var_ is the final grad, processed by hooks and grad accumulation
    var_ = var;
  }

  // function that Sum Gradient with this Graph
  virtual void SumGrad(std::shared_ptr<VariableWrapper> var, size_t trace_id,
                       bool unchange_input = false) = 0;
J
Jiabin Yang 已提交
63 64 65

  virtual ~GradientAccumulator() = default;

66 67 68 69 70 71 72 73 74 75 76 77
  inline void IncreaseRefCnt() {
    ++ref_cnt_;
    VLOG(6) << var_->Name() << " Increase total count to " << ref_cnt_;
  }

  inline void IncreaseCurCnt() {
    ++cur_cnt_;
    VLOG(6) << var_->Name() << " Increase current count to " << cur_cnt_
            << ", total count: " << ref_cnt_;
  }

  inline size_t CurCnt() const { return cur_cnt_; }
J
Jiabin Yang 已提交
78 79 80

  inline size_t RefCnt() const { return ref_cnt_; }

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
  inline bool SumGradCompleted() const {
    return cur_cnt_ == ref_cnt_ || ref_cnt_ == 1;
  }

  std::shared_ptr<VariableWrapper>& InnerVar() { return inner_var_; }

  // return the var that will be calculated in this graph
  VariableWrapper* Var() {
    return inner_var_ != nullptr ? inner_var_.get() : var_;
  }

  inline bool HasInnerVar() const { return inner_var_ != nullptr; }

  // function that Sum Gradient with Previous Graph
  void AccumulateGrad();
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
  /** [ Hook related methods ]
   *
   *  [Why need two types of VariableWrapperHook? ]
   *
   *    There are two types of gradient accumulation:
   *    1. Gradient accumulation in same batch
   *    2. Gradient accumulation across batchs
   *    The order of execution between Hooks and gradient accumulation:

   *      [ Gradient accumulation in same batch]
   *                        |
   *            [ leaf GradVarBase hooks ]
   *                        |
   *      [ Gradient accumulation across batchs ]
   *                        |
   *          [ Gradient reduce / allreduce hooks ]

   *    Because we currently intend to accumulate these two gradient
   *    accumulation in one GradientAccumulator, We must distinguish between
   *    two types of hooks.

   *    And the InplaceVariableWrapperHook does not allow users to register
   *    directly, and is currently only used to support the reduce strategy of
   *    parallel multi-card training.
   */

  void CallGradientHooks();

  void CallReduceHooks();
126

J
Jiabin Yang 已提交
127
 protected:
128
  VariableWrapper* var_;
129 130 131
  // NOTE: only gradient accumulater of leaf tensor should hold
  // inner_var_, So not hold it by other shared pointer.
  std::shared_ptr<VariableWrapper> inner_var_;
J
Jiabin Yang 已提交
132
  size_t ref_cnt_{0};
133
  size_t cur_cnt_{0};
J
Jiabin Yang 已提交
134 135 136 137 138 139
};

class EagerGradientAccumulator : public GradientAccumulator {
 public:
  using GradientAccumulator::GradientAccumulator;

140 141
  void SumGrad(std::shared_ptr<VariableWrapper> var, size_t trace_id,
               bool unchange_input) override;
J
Jiabin Yang 已提交
142 143 144 145 146 147
};

class SortedGradientAccumulator : public GradientAccumulator {
 public:
  using GradientAccumulator::GradientAccumulator;

148 149
  void SumGrad(std::shared_ptr<VariableWrapper> var, size_t trace_id,
               bool unchange_input) override;
J
Jiabin Yang 已提交
150 151

 private:
152 153 154 155 156 157 158 159 160 161 162 163 164
  struct SavedVarInfo {
    SavedVarInfo(std::shared_ptr<VariableWrapper>&& v, size_t id,
                 bool enable_unchange_input)
        : var(std::move(v)),
          trace_id(id),
          unchange_input(enable_unchange_input) {}

    std::shared_ptr<VariableWrapper> var;
    size_t trace_id;
    bool unchange_input;
  };

  std::vector<SavedVarInfo> tmp_grad_vars_;
J
Jiabin Yang 已提交
165 166
};

167 168 169 170 171 172 173
void SelectedRowsAddToTensor(const framework::Variable& src,
                             framework::Variable* dst);

void SelectedRowsAddTensor(const framework::Variable& src_selected_rows_var,
                           const framework::Variable& src_tensor_var,
                           framework::Variable* dst_tensor_var);

174 175 176 177
template <typename VarType>
void TensorAdd(const VarType& src, VarType* dst);

void VariableAdd(const egr::EagerTensor& src, egr::EagerTensor* dst);
178

J
Jiabin Yang 已提交
179 180
}  // namespace imperative
}  // namespace paddle