gradient_accumulator.h 3.7 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/imperative/hooks.h"
J
Jiabin Yang 已提交
22 23 24 25 26 27 28
#include "paddle/fluid/imperative/layer.h"

namespace paddle {
namespace imperative {

class GradientAccumulator {
 public:
29
  explicit GradientAccumulator(VariableWrapper* var) : var_(var) {}
J
Jiabin Yang 已提交
30

31 32
  virtual void Add(std::shared_ptr<VariableWrapper> var, size_t trace_id,
                   bool unchange_input = false) = 0;
J
Jiabin Yang 已提交
33 34 35 36 37 38 39

  virtual ~GradientAccumulator() = default;

  inline void IncreaseRefCnt() { ++ref_cnt_; }

  inline size_t RefCnt() const { return ref_cnt_; }

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  /* Hook related methods */
  inline bool HasPostHooks() const { return !post_hooks_.expired(); }

  void SetPostHooks(const std::shared_ptr<LeafVarHookPipeline>& hooks) {
    PADDLE_ENFORCE_NOT_NULL(
        hooks, platform::errors::InvalidArgument(
                   "The hook set to GradientAccumulator is nullptr."));

    auto shared_hooks = post_hooks_.lock();
    if (shared_hooks != hooks) {
      PADDLE_ENFORCE_EQ(
          shared_hooks, nullptr,
          platform::errors::PermissionDenied(
              "Cannot set post hooks twice to GradientAccumulator."));
      post_hooks_ = hooks;
    }
  }

  // call backward post hooks, such as reduce hook
  void CallBackwardPostHooks() {
    PADDLE_ENFORCE_NE(
        post_hooks_.expired(), true,
        platform::errors::NotFound(
            "The post hooks of GradientAccumulator for Tensor `%s` expired.",
            var_->Name()));
    auto shared_hooks = post_hooks_.lock();
    for (const auto& hook : shared_hooks->backward_hooks()) {
      VLOG(3) << "call gradient accumulator backward hooks.";
      (*hook)(var_);
    }
  }

J
Jiabin Yang 已提交
72
 protected:
73
  VariableWrapper* var_;
J
Jiabin Yang 已提交
74
  size_t ref_cnt_{0};
75 76

  std::weak_ptr<LeafVarHookPipeline> post_hooks_;
J
Jiabin Yang 已提交
77 78 79 80 81 82
};

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

83 84
  void Add(std::shared_ptr<VariableWrapper> var, size_t trace_id,
           bool unchange_input) override;
J
Jiabin Yang 已提交
85

86 87 88 89 90 91 92 93 94 95 96 97 98
 private:
  inline bool AccumulateCompleted() const { return cur_cnt_ == ref_cnt_; }

  void IncreaseCurCnt() {
    ++cur_cnt_;
    VLOG(3) << "IncreaseCurCnt: cur_cnt " << cur_cnt_ << ", ref_cnt "
            << ref_cnt_;
    // After all tmp gradient being accumulated to grad var, run hooks
    if (AccumulateCompleted() && HasPostHooks()) {
      CallBackwardPostHooks();
    }
  }

J
Jiabin Yang 已提交
99 100 101 102 103 104 105 106
 private:
  size_t cur_cnt_{0};
};

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

107 108
  void Add(std::shared_ptr<VariableWrapper> var, size_t trace_id,
           bool unchange_input) override;
J
Jiabin Yang 已提交
109 110

 private:
111 112 113 114 115 116 117 118 119 120 121 122 123
  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 已提交
124 125 126 127
};

}  // namespace imperative
}  // namespace paddle