accumulation_node.cc 5.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2021 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/eager/accumulation/accumulation_node.h"
16 17

#include "glog/logging.h"
18
#include "paddle/fluid/eager/eager_tensor.h"
J
Jiabin Yang 已提交
19
#include "paddle/fluid/eager/utils.h"
20
#include "paddle/fluid/imperative/gradient_accumulator.h"
21 22 23
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"
24 25
#include "paddle/phi/api/all.h"
#include "paddle/phi/core/dense_tensor.h"
26
#include "paddle/phi/core/sparse_coo_tensor.h"
27

28 29
namespace egr {

30
static void CopyOrAddTensor(paddle::experimental::Tensor* tensor,
J
Jiabin Yang 已提交
31 32 33
                            const paddle::experimental::Tensor& t,
                            bool is_fake_empty) {
  if (is_fake_empty) {
34 35
    *tensor = t;
  } else {
J
Jiabin Yang 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
    if (!tensor->defined() || !tensor->initialized()) {
      // Simply copy tensor->impl
      *tensor = t;
    } else {
      // Accumulation
      if (LIKELY(t.is_dense_tensor())) {
        if (LIKELY(tensor->is_dense_tensor())) {
          paddle::imperative::TensorAdd<paddle::experimental::Tensor>(t,
                                                                      tensor);
        } else {
          // TODO(jiabin): Support Other TensorBase later
          // TODO(zhanlve): Replace SelectedRowsAddTensor with
          // add_dygraph_function once it's supported
          paddle::experimental::Tensor new_buffer(
              std::make_shared<phi::DenseTensor>(), "tmp_accumulator");
          paddle::imperative::SelectedRowsAddTensor(*tensor, t, &new_buffer);
          tensor->set_impl(new_buffer.impl());
        }
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
      } else if (LIKELY(t.is_sparse_coo_tensor())) {
        // In fact, the gradient of SparseTensor is still a SparseTensor
        if (LIKELY(tensor->is_sparse_coo_tensor())) {
          auto t_sparse =
              std::dynamic_pointer_cast<phi::SparseCooTensor>(t.impl());
          paddle::experimental::Tensor t_values(
              std::make_shared<phi::DenseTensor>(
                  t_sparse->non_zero_elements()));
          auto tensor_sparse =
              std::dynamic_pointer_cast<phi::SparseCooTensor>(tensor->impl());
          paddle::experimental::Tensor tensor_values(
              std::make_shared<phi::DenseTensor>(
                  tensor_sparse->non_zero_elements()));
          paddle::imperative::TensorAdd<paddle::experimental::Tensor>(
              t_values, &tensor_values);
        }
70 71 72
      } else {
        // TODO(jiabin): Support Other TensorBase later
        // TODO(zhanlve): Replace SelectedRowsAddTensor with
J
Jiabin Yang 已提交
73 74 75 76 77 78 79 80
        // add_dygraph_function
        // once it's supported
        if (tensor->is_dense_tensor()) {
          paddle::imperative::SelectedRowsAddToTensor(t, tensor);
        } else {
          *tensor = std::move(*paddle::imperative::SelectedRowsMerge<
                              paddle::experimental::Tensor>(t, *tensor));
        }
81 82
      }
    }
83 84 85
  }
}

86 87 88 89 90
paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                     kSlotSmallVectorSize>
GradNodeAccumulation::operator()(
    paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                         kSlotSmallVectorSize>& grads,  // NOLINT
91 92
    bool create_graph,
    bool is_new_grad) {
J
Jiabin Yang 已提交
93
  VLOG(3) << "Running AD API Grad: GradNodeAccumulation";
94 95 96 97 98 99 100 101 102
  PADDLE_ENFORCE(grads.size() == 1,
                 paddle::platform::errors::Fatal(
                     "GradNodeAccumulation should take exactly 1 grad tensor"
                     "However received: %d slot.",
                     grads.size()));
  PADDLE_ENFORCE(grads[0].size() == 1,
                 paddle::platform::errors::Fatal(
                     "GradNodeAccumulation should take exactly 1 grad tensor"
                     "However received: %d in slot %d .",
103 104
                     grads[0].size(),
                     0));
105
  // Apply Gradient Hooks
106
  paddle::experimental::Tensor grad_out;
107
  if (GradientHooksRegistered()) {
108 109 110
    paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                         kSlotSmallVectorSize>
        hooked_grads = ApplyGradientHooks(grads);
111
    grad_out = hooked_grads[0][0];
112
  } else {
113
    grad_out = grads[0][0];
114 115
  }

116
  if (!weak_grad_.expired() && !is_new_grad) {
117
    auto grad = weak_grad_.lock();
J
Jiabin Yang 已提交
118 119
    CopyOrAddTensor(grad.get(), grad_out, is_fake_empty_);
    is_fake_empty_ = false;
120 121 122 123 124 125
  }

  // Apply Reduce Hooks
  if (ReduceHooksRegistered()) {
    ApplyReduceHooks();
  }
J
Jiabin Yang 已提交
126 127 128
  VLOG(3) << "Finish AD API Grad: GradNodeAccumulation";
  if (VLOG_IS_ON(4)) {
    const char* INPUT_PRINT_TEMPLATE = "{ Input: [%s], Output: [%s] } ";
129

J
Jiabin Yang 已提交
130 131 132 133 134 135 136 137 138 139 140 141
    std::string input_str = "";
    std::string output_str = "";
    const char* TENSOR_OUT_GRAD_TEMPLATE = "(grads[0][0], [%s]), ";
    std::string input_out_grad_str = paddle::string::Sprintf(
        TENSOR_OUT_GRAD_TEMPLATE, egr::EagerUtils::TensorStr(grads[0][0]));
    const char* TENSOR_X_GRAD_TEMPLATE = "(grad_out, [%s]), ";
    std::string output_x_grad_str = paddle::string::Sprintf(
        TENSOR_X_GRAD_TEMPLATE, egr::EagerUtils::TensorStr(grad_out));
    output_str += output_x_grad_str;
    VLOG(4) << paddle::string::Sprintf(
        INPUT_PRINT_TEMPLATE, input_str, output_str);
  }
142
  return {{grad_out}};
143 144
}

145
void GradNodeAccumulation::RegisterReduceHook(
146
    std::shared_ptr<VoidHook>&& hook) {
147
  reduce_hooks_.emplace_back(std::move(hook));
148 149 150 151
}

void GradNodeAccumulation::ApplyReduceHooks() {
  for (auto& hook : reduce_hooks_) {
152
    (*hook)();
153 154
  }
}
155
}  // namespace egr