accumulation_node.cc 8.5 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/api/generated/eager_generated/forwards/dygraph_functions.h"
19
#include "paddle/fluid/eager/eager_tensor.h"
J
Jiabin Yang 已提交
20
#include "paddle/fluid/eager/utils.h"
21
#include "paddle/fluid/imperative/gradient_accumulator.h"
22 23 24
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"
25 26
#include "paddle/phi/api/all.h"
#include "paddle/phi/core/dense_tensor.h"
27
#include "paddle/phi/core/sparse_coo_tensor.h"
28

29 30
namespace egr {

31 32
static void CopyOrAddTensor(paddle::Tensor* tensor,
                            const paddle::Tensor& t,
J
Jiabin Yang 已提交
33 34
                            bool is_fake_empty) {
  if (is_fake_empty) {
J
Jiabin Yang 已提交
35
    VLOG(3) << "Move Tensor ptr: " << t.impl();
36 37
    *tensor = t;
  } else {
J
Jiabin Yang 已提交
38 39
    if (!tensor->defined() || !tensor->initialized()) {
      // Simply copy tensor->impl
J
Jiabin Yang 已提交
40
      VLOG(3) << "Move Tensor ptr: " << t.impl();
J
Jiabin Yang 已提交
41 42
      *tensor = t;
    } else {
J
Jiabin Yang 已提交
43 44
      VLOG(3) << "Add Tensor ptr: " << t.impl()
              << " with Tensor ptr: " << tensor->impl();
J
Jiabin Yang 已提交
45 46 47
      // Accumulation
      if (LIKELY(t.is_dense_tensor())) {
        if (LIKELY(tensor->is_dense_tensor())) {
48
          if (t.is_custom_device()) {
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
            auto* dev_ctx =
                phi::DeviceContextPool::Instance().Get(tensor->place());
            auto kernel_result =
                phi::KernelFactory::Instance().SelectKernelOrThrowError(
                    "add",
                    phi::KernelKey(phi::TransToPhiBackend(tensor->place()),
                                   phi::DataLayout::ALL_LAYOUT,
                                   tensor->dtype()));
            const auto& kernel = kernel_result.kernel;
            using kernel_signature = void (*)(const phi::DeviceContext&,
                                              const phi::DenseTensor&,
                                              const phi::DenseTensor&,
                                              phi::DenseTensor*);
            auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
            (*kernel_fn)(
                *dev_ctx,
                *reinterpret_cast<phi::DenseTensor*>(tensor->impl().get()),
                *reinterpret_cast<phi::DenseTensor*>(t.impl().get()),
                reinterpret_cast<phi::DenseTensor*>(tensor->impl().get()));
68
          } else {
69
            paddle::imperative::TensorAdd<paddle::Tensor>(t, tensor);
70
          }
J
Jiabin Yang 已提交
71 72 73 74
        } else {
          // TODO(jiabin): Support Other TensorBase later
          // TODO(zhanlve): Replace SelectedRowsAddTensor with
          // add_dygraph_function once it's supported
75 76
          paddle::Tensor new_buffer(std::make_shared<phi::DenseTensor>(),
                                    "tmp_accumulator");
J
Jiabin Yang 已提交
77 78 79
          paddle::imperative::SelectedRowsAddTensor(*tensor, t, &new_buffer);
          tensor->set_impl(new_buffer.impl());
        }
80 81 82 83 84
      } 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());
85 86
          paddle::Tensor t_values(std::make_shared<phi::DenseTensor>(
              t_sparse->non_zero_elements()));
87 88
          auto tensor_sparse =
              std::dynamic_pointer_cast<phi::SparseCooTensor>(tensor->impl());
89 90
          paddle::Tensor tensor_values(std::make_shared<phi::DenseTensor>(
              tensor_sparse->non_zero_elements()));
91
          if (t.is_custom_device()) {
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
            auto* dev_ctx =
                phi::DeviceContextPool::Instance().Get(tensor->place());
            auto kernel_result =
                phi::KernelFactory::Instance().SelectKernelOrThrowError(
                    "add_coo_coo",
                    phi::KernelKey(phi::TransToPhiBackend(tensor->place()),
                                   phi::DataLayout::ALL_LAYOUT,
                                   tensor->dtype()));
            const auto& kernel = kernel_result.kernel;
            using kernel_signature = void (*)(const phi::DeviceContext&,
                                              const phi::SparseCooTensor&,
                                              const phi::SparseCooTensor&,
                                              phi::SparseCooTensor*);
            auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
            (*kernel_fn)(
                *dev_ctx,
                *reinterpret_cast<phi::SparseCooTensor*>(tensor->impl().get()),
                *reinterpret_cast<phi::SparseCooTensor*>(t.impl().get()),
                reinterpret_cast<phi::SparseCooTensor*>(tensor->impl().get()));
111
          } else {
112 113
            paddle::imperative::TensorAdd<paddle::Tensor>(t_values,
                                                          &tensor_values);
114
          }
115
        }
116 117 118
      } else {
        // TODO(jiabin): Support Other TensorBase later
        // TODO(zhanlve): Replace SelectedRowsAddTensor with
J
Jiabin Yang 已提交
119 120 121 122 123
        // add_dygraph_function
        // once it's supported
        if (tensor->is_dense_tensor()) {
          paddle::imperative::SelectedRowsAddToTensor(t, tensor);
        } else {
124 125 126
          *tensor =
              std::move(*paddle::imperative::SelectedRowsMerge<paddle::Tensor>(
                  t, *tensor));
J
Jiabin Yang 已提交
127
        }
128 129
      }
    }
130 131 132
  }
}

133
paddle::small_vector<std::vector<paddle::Tensor>, kSlotSmallVectorSize>
134
GradNodeAccumulation::operator()(
135
    paddle::small_vector<std::vector<paddle::Tensor>,
136
                         kSlotSmallVectorSize>& grads,  // NOLINT
137 138
    bool create_graph,
    bool is_new_grad) {
J
Jiabin Yang 已提交
139
  VLOG(3) << "Running AD API Grad: GradNodeAccumulation";
140 141 142 143 144 145 146 147 148
  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 .",
149 150
                     grads[0].size(),
                     0));
151
  // Apply Gradient Hooks
152
  paddle::Tensor grad_out;
153
  if (GradientHooksRegistered()) {
154
    paddle::small_vector<std::vector<paddle::Tensor>, kSlotSmallVectorSize>
155
        hooked_grads = ApplyGradientHooks(grads);
156
    grad_out = hooked_grads[0][0];
157
  } else {
158
    grad_out = grads[0][0];
159 160
  }

161
  if (!weak_grad_.expired() && !is_new_grad) {
162
    auto grad = weak_grad_.lock();
163 164 165 166
    if (grad_out.defined() && grad_out.initialized()) {
      CopyOrAddTensor(grad.get(), grad_out, is_fake_empty_);
    }
    // else { do nothing since there is no valid value in grad out tensor }
J
Jiabin Yang 已提交
167
    is_fake_empty_ = false;
168 169 170 171 172 173
  }

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

J
Jiabin Yang 已提交
178 179 180 181 182 183 184 185 186 187 188 189
    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);
  }
190
  return {{grad_out}};
191 192
}

193
void GradNodeAccumulation::RegisterReduceHook(
194
    std::shared_ptr<VoidHook>&& hook) {
195
  reduce_hooks_.emplace_back(std::move(hook));
196 197 198 199
}

void GradNodeAccumulation::ApplyReduceHooks() {
  for (auto& hook : reduce_hooks_) {
200
    (*hook)();
201 202
  }
}
203
}  // namespace egr