gradient_accumulator.cc 34.6 KB
Newer Older
J
Jiabin Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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.

#include "paddle/fluid/imperative/gradient_accumulator.h"
16

J
Jiabin Yang 已提交
17 18 19
#include <algorithm>
#include <memory>
#include <utility>
20

21
#include "paddle/fluid/framework/convert_utils.h"
J
Jiabin Yang 已提交
22
#include "paddle/fluid/framework/lod_tensor.h"
23
#include "paddle/fluid/framework/selected_rows_utils.h"
J
Jiabin Yang 已提交
24 25
#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/operators/math/blas.h"
26
#include "paddle/fluid/operators/math/selected_rows_functor.h"
27
#include "paddle/fluid/platform/complex.h"
J
Jiabin Yang 已提交
28
#include "paddle/fluid/platform/device_context.h"
29
#include "paddle/fluid/platform/float16.h"
J
Jiabin Yang 已提交
30
#include "paddle/fluid/platform/profiler.h"
31
#include "paddle/pten/kernels/funcs/math_function.h"
H
hong 已提交
32 33 34
#ifdef PADDLE_WITH_XPU
#include "xpu/refactor/math.h"
#endif
35
#ifdef PADDLE_WITH_ASCEND_CL
36
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
37
#endif
J
Jiabin Yang 已提交
38 39 40 41

namespace paddle {
namespace imperative {

42 43 44
static void MoveOrCopyVar(framework::Variable* dst, framework::Variable* src,
                          bool force_copy) {
  if (!force_copy) {
45
    VLOG(6) << "Just Move Variable when sum gradients within this graph";
46 47 48 49
    *dst = std::move(*src);
    return;
  }

50
  VLOG(6) << "Copy occurs when sum gradients within this graph";
51 52 53 54 55 56 57 58
  if (src->IsType<framework::LoDTensor>()) {
    auto& src_tensor = src->Get<framework::LoDTensor>();
    if (!dst->IsType<framework::LoDTensor>()) {
      dst->Clear();
    }
    auto* dst_tensor = dst->GetMutable<framework::LoDTensor>();
    framework::TensorCopy(src_tensor, src_tensor.place(), dst_tensor);
    dst_tensor->set_lod(src_tensor.lod());
59 60 61
  } else if (src->IsType<pten::SelectedRows>()) {
    auto& src_selected_rows = src->Get<pten::SelectedRows>();
    if (!dst->IsType<pten::SelectedRows>()) {
62 63
      dst->Clear();
    }
64
    auto* dst_selected_rows = dst->GetMutable<pten::SelectedRows>();
65 66 67 68 69 70 71
    framework::TensorCopy(src_selected_rows.value(),
                          src_selected_rows.value().place(),
                          dst_selected_rows->mutable_value());
    dst_selected_rows->set_rows(src_selected_rows.rows());
    dst_selected_rows->set_height(src_selected_rows.height());
  } else {
    PADDLE_THROW(platform::errors::PermissionDenied(
72
        "Only support LoDTensor and SelectedRows for sum gradient"));
73 74 75
  }
}

J
Jiabin Yang 已提交
76 77 78 79 80 81
template <typename T>
class TensorAddFunctor : public boost::static_visitor<> {
 public:
  TensorAddFunctor(int64_t numel, const T* x, T* y)
      : numel_(numel), x_(x), y_(y) {}

82
  void operator()(const platform::CPUPlace& place) const {
J
Jiabin Yang 已提交
83 84 85 86 87 88
    platform::CPUDeviceContext* ctx = dynamic_cast<platform::CPUDeviceContext*>(
        platform::DeviceContextPool::Instance().Get(place));
    auto blas = operators::math::GetBlas<platform::CPUDeviceContext, T>(*ctx);
    blas.AXPY(numel_, 1., x_, y_);
  }

H
hong 已提交
89
#ifdef PADDLE_WITH_XPU
90
  void operator()(const platform::XPUPlace& place) const {
91
    using XPUType = typename XPUTypeTrait<T>::Type;
H
hong 已提交
92 93
    platform::XPUDeviceContext* ctx = dynamic_cast<platform::XPUDeviceContext*>(
        platform::DeviceContextPool::Instance().Get(place));
94 95 96 97 98 99 100 101
    int r = xpu::add<XPUType>(
        ctx->x_context(), reinterpret_cast<const XPUType*>(x_),
        reinterpret_cast<const XPUType*>(y_), reinterpret_cast<XPUType*>(y_),
        static_cast<int>(numel_));
    PADDLE_ENFORCE_EQ(
        r, XPU_SUCCESS,
        platform::errors::External("XPU add kernel return wrong value[%d %s]",
                                   r, XPUAPIErrorMsg[r]));
H
hong 已提交
102 103
  }
#else
104
  void operator()(const platform::XPUPlace& place) const {
105 106 107 108 109
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
H
hong 已提交
110
#endif
111

112
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
113
  void operator()(const platform::CUDAPlace& place) const {
J
Jiabin Yang 已提交
114 115 116 117 118 119 120
    platform::CUDADeviceContext* ctx =
        dynamic_cast<platform::CUDADeviceContext*>(
            platform::DeviceContextPool::Instance().Get(place));
    auto blas = operators::math::GetBlas<platform::CUDADeviceContext, T>(*ctx);
    blas.AXPY(numel_, 1., x_, y_);
  }
#else
121
  void operator()(const platform::CUDAPlace& place) const {
122
    PADDLE_THROW(platform::errors::PermissionDenied(
123 124 125 126 127 128
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#endif

F
fwenguang 已提交
129
#ifdef PADDLE_WITH_MLU
130
  void operator()(const platform::MLUPlace& place) const {
F
fwenguang 已提交
131 132 133 134 135 136 137
    // TODO(fwg): SUPPORT it
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#else
138
  void operator()(const platform::MLUPlace& place) const {
F
fwenguang 已提交
139 140 141 142 143 144 145
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#endif

146
#ifdef PADDLE_WITH_ASCEND_CL
147
  void operator()(const platform::NPUPlace& place) const {
148 149 150 151 152 153 154
    // TODO(zhiqiu): SUPPORT it
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#else
155
  void operator()(const platform::NPUPlace& place) const {
156
    PADDLE_THROW(platform::errors::PermissionDenied(
157 158 159
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
J
Jiabin Yang 已提交
160 161 162
  }
#endif

163
  void operator()(const platform::NPUPinnedPlace& place) const {
164 165 166 167 168
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
J
Jiabin Yang 已提交
169
  // there is NO blas in CUDAPinnedPlace
170
  void operator()(const platform::CUDAPinnedPlace& place) const {
171 172 173 174
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
J
Jiabin Yang 已提交
175
  }
J
jianghaicheng 已提交
176
  // there is NO support in IPUPlace
177
  void operator()(const platform::IPUPlace& place) const {
J
jianghaicheng 已提交
178 179 180 181 182
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
J
Jiabin Yang 已提交
183 184 185 186

 private:
  int64_t numel_;
  const T* x_;
187
  mutable T* y_;
J
Jiabin Yang 已提交
188 189
};

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
#ifdef PADDLE_WITH_XPU
template <typename T>
void XPUTensorAddFunctor(const platform::Place& place,
                         const framework::Tensor& src, framework::Tensor* dst) {
  using XPUType = typename XPUTypeTrait<T>::Type;
  platform::XPUDeviceContext* ctx = dynamic_cast<platform::XPUDeviceContext*>(
      platform::DeviceContextPool::Instance().Get(place));
  const XPUType* x = reinterpret_cast<const XPUType*>(src.data<T>());
  XPUType* y = reinterpret_cast<XPUType*>(dst->mutable_data<T>(place));
  int r = xpu::add<XPUType>(ctx->x_context(), x, y, y,
                            static_cast<int>(src.numel()));
  PADDLE_ENFORCE_EQ(
      r, XPU_SUCCESS,
      platform::errors::External("XPU add kernel return wrong value[%d %s]", r,
                                 XPUAPIErrorMsg[r]));
}
#endif

208 209 210 211 212 213
template <typename DeviceContext, typename T>
void TensorAddImpl(const framework::Tensor& src, framework::Tensor* dst,
                   const platform::Place& place) {
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
  paddle::platform::DeviceContext* ctx = pool.Get(place);
  auto dev_ctx = dynamic_cast<DeviceContext*>(ctx);
214
  pten::funcs::ElementwiseAddTo<DeviceContext, T> func;
215 216 217
  func(dev_ctx, src, dst);
}

218 219 220
template <typename TType>
TType* GetInnerMutableTensor(framework::Variable* dst) {
  auto* dst_tensor = dst->GetMutable<TType>();
221 222 223
  return dst_tensor;
}

224 225 226
template <typename TType>
TType* GetInnerMutableTensor(paddle::experimental::Tensor* dst) {
  auto* dst_tensor = static_cast<TType*>(dst->impl().get());
227 228 229
  return dst_tensor;
}

230 231 232
template <typename TType>
const TType& GetInnerTensor(const framework::Variable& src) {
  return src.Get<TType>();
233 234
}

235 236 237 238 239 240 241 242 243
template <typename TType>
TType& GetInnerTensor(const paddle::experimental::Tensor& src) {
  PADDLE_ENFORCE_EQ(
      src.initialized(), true,
      platform::errors::Fatal("We only add tensor with value if a tensor is "
                              "NOT INITILIZED, it should just move instead of "
                              "calling this method."));
  auto* src_tensor = static_cast<TType*>(src.impl().get());
  return *src_tensor;
244 245
}

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
template <typename TType>
TType* GetEmptyInnerTensor(paddle::experimental::Tensor* dst) {
  PADDLE_ENFORCE_EQ(
      dst->defined(), false,
      platform::errors::Fatal(
          "The underlying Tensor implementation should be nullptr"));
  dst->set_impl(std::make_shared<TType>());
  auto* dst_tensor = static_cast<TType*>(dst->impl().get());
  return dst_tensor;
}

template <typename TType>
TType* GetEmptyInnerTensor(paddle::imperative::VariableWrapper* dst) {
  auto* dst_tensor = dst->MutableVar()->GetMutable<TType>();
  return dst_tensor;
}

263 264
template <typename VarType>
void TensorAdd(const VarType& src, VarType* dst) {
265 266
  pten::DenseTensor* dst_tensor = GetInnerMutableTensor<pten::DenseTensor>(dst);
  const pten::DenseTensor& src_tensor = GetInnerTensor<pten::DenseTensor>(src);
J
Jiabin Yang 已提交
267 268 269 270 271 272 273 274 275

  auto numel = src_tensor.numel();

  // FIXME(minqiyang): loss_grad op will pass a zero grad of label
  // ugly fix for it
  if (numel == 0) {
    return;
  }

276 277 278 279 280 281 282
  PADDLE_ENFORCE_EQ(
      dst_tensor->numel(), numel,
      platform::errors::PreconditionNotMet(
          "The number of elements of source tensor and destination tensor "
          "should be equal, but got the number of elements of source tensor is "
          "%zu and the number of elements of destination tensor is %zu.",
          numel, dst_tensor->numel()));
J
Jiabin Yang 已提交
283

284
  auto data_type = framework::TransToProtoVarType(src_tensor.dtype());
J
Jiabin Yang 已提交
285 286
  auto place = src_tensor.place();

287 288
  PADDLE_ENFORCE_EQ(framework::TransToProtoVarType(dst_tensor->dtype()),
                    data_type,
289 290 291 292 293
                    platform::errors::PreconditionNotMet(
                        "The data type of source tensor and destination tensor "
                        "should be equal, Otherwise, the calculation results "
                        "will be incorrect."));

294 295 296 297 298 299 300
#ifdef PADDLE_WITH_XPU
  // if src and dst are in different place, copy dst to src's place
  if (dst_tensor->place() != place) {
    paddle::framework::TensorCopySync(*dst_tensor, place, dst_tensor);
  }
#endif

301
#define PADDLE_TENSOR_ADD(cpp_type)                                  \
J
Jiabin Yang 已提交
302 303 304 305
  if (data_type == framework::DataTypeTrait<cpp_type>::DataType()) { \
    TensorAddFunctor<cpp_type> func(                                 \
        numel, src_tensor.data<cpp_type>(),                          \
        dst_tensor->mutable_data<cpp_type>(place));                  \
306
    platform::VisitPlace(place, func);                               \
J
Jiabin Yang 已提交
307 308 309
    return;                                                          \
  }

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
#ifdef PADDLE_WITH_ASCEND_CL
  if (platform::is_npu_place(place)) {
    platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
    platform::DeviceContext* ctx = pool.Get(place);
    auto dev_ctx = dynamic_cast<platform::NPUDeviceContext*>(ctx);
    if (data_type == framework::DataTypeTrait<float>::DataType()) {
      dst_tensor->mutable_data<float>(place);
    } else if (data_type == framework::DataTypeTrait<double>::DataType()) {
      dst_tensor->mutable_data<double>(place);
    } else if (data_type ==
               framework::DataTypeTrait<platform::float16>::DataType()) {
      dst_tensor->mutable_data<platform::float16>(place);
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Gradient accumulation of data type (%s) on place (%s) is not "
          "supported in imperative mode",
          framework::DataTypeToString(data_type), place));
    }
    const auto& runner = operators::NpuOpRunner(
        "Add", {*dst_tensor, src_tensor}, {*dst_tensor}, {});
    runner.Run(dev_ctx->stream());
    return;
  }
#endif
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

#ifdef PADDLE_WITH_XPU
  if (platform::is_xpu_place(place)) {
    if (data_type == framework::DataTypeTrait<float>::DataType()) {
      XPUTensorAddFunctor<float>(place, src_tensor, dst_tensor);
    } else if (data_type ==
               framework::DataTypeTrait<platform::float16>::DataType()) {
      XPUTensorAddFunctor<platform::float16>(place, src_tensor, dst_tensor);
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Gradient accumulation of data type (%s) on place (%s) is not "
          "supported in imperative mode",
          framework::DataTypeToString(data_type), place));
    }
    return;
  }
#endif

352
  PADDLE_TENSOR_ADD(float);
353

H
hong 已提交
354 355
#ifndef PADDLE_WITH_XPU
  // NOTE(phlrain): xpu only support float
356
  PADDLE_TENSOR_ADD(double);
357 358
  // NOTE(chenweihang): only support complex grad tensor accumulated,
  // support selected rows if needed in the future
359 360
  PADDLE_TENSOR_ADD(platform::complex<float>);
  PADDLE_TENSOR_ADD(platform::complex<double>);
H
hong 已提交
361
#endif
J
Jiabin Yang 已提交
362

363
#undef PADDLE_TENSOR_ADD
J
Jiabin Yang 已提交
364

365 366
  if (data_type == framework::proto::VarType::FP16) {
    if (platform::is_gpu_place(place)) {
367
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
      return TensorAddImpl<platform::CUDADeviceContext, platform::float16>(
          src_tensor, dst_tensor, place);
#else
      PADDLE_THROW(platform::errors::Unimplemented(
          "Gradient accumulation of data type (%s) on place (%s) is not "
          "supported in imperative mode",
          framework::DataTypeToString(data_type), place));
#endif
    } else if (platform::is_cpu_place(place)) {
      return TensorAddImpl<platform::CPUDeviceContext, platform::float16>(
          src_tensor, dst_tensor, place);
    }
  }
  PADDLE_THROW(platform::errors::Unimplemented(
      "Gradient accumulation of data type (%s) on place (%s) is not "
      "supported in imperative mode",
      framework::DataTypeToString(data_type), place));
J
Jiabin Yang 已提交
385 386
}

387 388
template void TensorAdd<framework::Variable>(const framework::Variable& src,
                                             framework::Variable* dst);
389 390
template void TensorAdd<paddle::experimental::Tensor>(
    const paddle::experimental::Tensor& src, paddle::experimental::Tensor* dst);
391

392 393 394 395 396
template <typename VarType>
void SelectedRowsAddToTensor(const VarType& src, VarType* dst) {
  pten::DenseTensor* dst_tensor = GetInnerMutableTensor<pten::DenseTensor>(dst);
  const pten::SelectedRows& src_selected_rows =
      GetInnerTensor<pten::SelectedRows>(src);
397
  auto place = dst_tensor->place();
398 399
  auto data_type =
      framework::TransToProtoVarType(src_selected_rows.value().dtype());
400 401 402 403 404 405 406 407 408 409 410 411
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();

#define PADDLE_SELECTED_ROWS_ADD_TO_TENSOR(dev_ctx_type, cpp_type)           \
  if (data_type == framework::DataTypeTrait<cpp_type>::DataType()) {         \
    paddle::platform::DeviceContext* dev_ctx = pool.Get(place);              \
    paddle::operators::math::SelectedRowsAddToTensor<dev_ctx_type, cpp_type> \
        functor;                                                             \
    functor(*(dynamic_cast<dev_ctx_type*>(dev_ctx)), src_selected_rows,      \
            dst_tensor);                                                     \
    return;                                                                  \
  }

412
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
413 414 415 416 417 418 419
  if (paddle::platform::is_gpu_place(place)) {
    PADDLE_SELECTED_ROWS_ADD_TO_TENSOR(platform::CUDADeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD_TO_TENSOR(platform::CUDADeviceContext, double);
  } else {
#endif
    PADDLE_SELECTED_ROWS_ADD_TO_TENSOR(platform::CPUDeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD_TO_TENSOR(platform::CPUDeviceContext, double);
420
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
421 422 423 424 425 426 427 428 429 430
  }
#endif

#undef PADDLE_SELECTED_ROWS_ADD_TO_TENSOR

  PADDLE_THROW(platform::errors::InvalidArgument(
      "Not supported data type %s for SelectedRowsAddToTensor",
      framework::DataTypeToString(data_type)));
}

431 432 433 434 435 436 437 438 439 440 441 442 443
template void SelectedRowsAddToTensor(const framework::Variable& src,
                                      framework::Variable* dst);
template void SelectedRowsAddToTensor(const paddle::experimental::Tensor& src,
                                      paddle::experimental::Tensor* dst);

template <typename VarType>
void SelectedRowsAddTensor(const VarType& src_selected_rows_var,
                           const VarType& src_tensor_var,
                           VarType* dst_tensor_var) {
  const pten::SelectedRows& src_selected_rows =
      GetInnerTensor<pten::SelectedRows>(src_selected_rows_var);
  const pten::DenseTensor& src_tensor =
      GetInnerTensor<pten::DenseTensor>(src_tensor_var);
444
  const auto& place = src_tensor.place();
445
  auto data_type = framework::TransToProtoVarType(src_tensor.dtype());
446 447
  auto* dev_ctx = platform::DeviceContextPool::Instance().Get(place);

448 449
  pten::DenseTensor* dst_tensor =
      GetInnerMutableTensor<pten::DenseTensor>(dst_tensor_var);
450
  dst_tensor->Resize(src_tensor.dims());
451 452
  dst_tensor->mutable_data(place, src_tensor.dtype());

453 454 455 456 457 458 459 460 461
#define PADDLE_SELECTED_ROWS_ADD_TENSOR(dev_ctx_type, cpp_type)            \
  if (data_type == framework::DataTypeTrait<cpp_type>::DataType()) {       \
    paddle::operators::math::SelectedRowsAddTensor<dev_ctx_type, cpp_type> \
        functor;                                                           \
    functor(*(dynamic_cast<dev_ctx_type*>(dev_ctx)), src_selected_rows,    \
            src_tensor, dst_tensor);                                       \
    return;                                                                \
  }

462
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
463 464 465 466 467 468 469
  if (platform::is_gpu_place(place)) {
    PADDLE_SELECTED_ROWS_ADD_TENSOR(platform::CUDADeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD_TENSOR(platform::CUDADeviceContext, double);
  } else {
#endif
    PADDLE_SELECTED_ROWS_ADD_TENSOR(platform::CPUDeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD_TENSOR(platform::CPUDeviceContext, double);
470
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
471 472 473 474 475 476 477 478 479 480
  }
#endif

  PADDLE_THROW(platform::errors::InvalidArgument(
      "Not supported data type %s for SelectedRowsAddToTensor",
      framework::DataTypeToString(data_type)));

#undef PADDLE_SELECTED_ROWS_ADD_TENSOR
}

481 482 483 484 485 486 487 488 489 490 491 492
template void SelectedRowsAddTensor(
    const framework::Variable& src_selected_rows_var,
    const framework::Variable& src_tensor_var,
    framework::Variable* dst_tensor_var);
template void SelectedRowsAddTensor(
    const paddle::experimental::Tensor& src_selected_rows_var,
    const paddle::experimental::Tensor& src_tensor_var,
    paddle::experimental::Tensor* dst_tensor_var);

// Note(chenweihang): when two selected rows need to be added,
//   adding one to another is not equal to merging two selected rows
//   to one then add it to a empty selected rows, the after is correct
493 494 495 496 497 498 499 500
template <typename ReturnVarType, typename VarType>
std::shared_ptr<ReturnVarType> SelectedRowsMerge(const VarType& src1,
                                                 const VarType& src2) {
  const pten::SelectedRows& src_selected_rows1 =
      GetInnerTensor<pten::SelectedRows>(src1);
  const pten::SelectedRows& src_selected_rows2 =
      GetInnerTensor<pten::SelectedRows>(src2);

501
  auto place = src_selected_rows1.value().place();
502 503
  auto data_type =
      framework::TransToProtoVarType(src_selected_rows1.value().dtype());
504 505
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();

506
  std::vector<const pten::SelectedRows*> src_selected_rows;
507 508
  src_selected_rows.emplace_back(&src_selected_rows1);
  src_selected_rows.emplace_back(&src_selected_rows2);
509 510 511 512

  auto dst_var = std::make_shared<ReturnVarType>("Temp");
  pten::SelectedRows* dst_selected_rows =
      GetEmptyInnerTensor<pten::SelectedRows>(dst_var.get());
513 514 515 516 517 518 519 520 521 522 523

#define PADDLE_SELECTED_ROWS_ADD(dev_ctx_type, cpp_type)                  \
  if (data_type == framework::DataTypeTrait<cpp_type>::DataType()) {      \
    paddle::platform::DeviceContext* dev_ctx = pool.Get(place);           \
    paddle::operators::math::scatter::MergeAdd<dev_ctx_type, cpp_type>    \
        merge_add;                                                        \
    merge_add(*(dynamic_cast<dev_ctx_type*>(dev_ctx)), src_selected_rows, \
              dst_selected_rows);                                         \
    return dst_var;                                                       \
  }

524
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
525 526 527 528 529 530 531
  if (paddle::platform::is_gpu_place(place)) {
    PADDLE_SELECTED_ROWS_ADD(platform::CUDADeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD(platform::CUDADeviceContext, double);
  } else {
#endif
    PADDLE_SELECTED_ROWS_ADD(platform::CPUDeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD(platform::CPUDeviceContext, double);
532
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
533 534 535 536 537 538 539 540 541
  }
#endif

#undef PADDLE_SELECTED_ROWS_ADD
  PADDLE_THROW(platform::errors::InvalidArgument(
      "Not supported data type %s for SelectedRowsMerge",
      framework::DataTypeToString(data_type)));
}

542 543 544 545 546 547
template std::shared_ptr<paddle::experimental::Tensor> SelectedRowsMerge(
    const paddle::experimental::Tensor& src1,
    const paddle::experimental::Tensor& src2);
template std::shared_ptr<paddle::imperative::VariableWrapper> SelectedRowsMerge(
    const framework::Variable& src1, const framework::Variable& src2);

548
void VariableWrapperAdd(std::shared_ptr<VariableWrapper> var,
549
                        VariableWrapper* dst_var, bool unchange_input) {
550
  auto& src = var->Var();
551
  auto* dst = dst_var->MutableVar();
552 553
  if (dst->IsType<framework::LoDTensor>()) {
    if (src.IsType<framework::LoDTensor>()) {
554
      TensorAdd<framework::Variable>(src, dst);
555
    } else if (src.IsType<pten::SelectedRows>()) {
556 557 558 559 560 561 562 563
      SelectedRowsAddToTensor(src, dst);
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Unexpected branch, output variable type is %s",
          framework::ToTypeName(dst->Type())));
    }
  } else {
    if (src.IsType<framework::LoDTensor>()) {
564 565 566 567 568 569 570 571 572
      if (unchange_input) {
        framework::Variable new_dst;
        SelectedRowsAddTensor(*dst, src, &new_dst);
        *dst = std::move(new_dst);
      } else {
        auto* src_mutable = var->MutableVar();
        SelectedRowsAddToTensor(*dst, src_mutable);
        *dst = std::move(*(var->MutableVar()));
      }
573
    } else if (src.IsType<pten::SelectedRows>()) {
574
      auto temp = SelectedRowsMerge<VariableWrapper>(src, *dst);
575 576 577 578 579 580 581 582 583
      *dst = std::move(*(temp->MutableVar()));
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Unexpected branch, output variable type is %s",
          framework::ToTypeName(dst->Type())));
    }
  }
}

584 585
static platform::Place GetPlaceOfVar(
    const std::shared_ptr<VariableWrapper>& var) {
586 587 588
  platform::Place place;
  if (var->Var().IsType<framework::LoDTensor>()) {
    place = var->Var().Get<framework::LoDTensor>().place();
589 590
  } else if (var->Var().IsType<pten::SelectedRows>()) {
    place = var->Var().Get<pten::SelectedRows>().place();
591 592 593 594 595 596 597
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "only support LoDTensor and SelectedRows in dygraph"));
  }
  return place;
}

598 599
void GradientAccumulator::AccumulateGrad() {
  /**
600 601
   * If the leaf gradient has been calculated done, the inner_var_
   * should be added to the var_.
602 603 604 605 606 607 608 609 610 611
   */
  if (!var_->IsLeafGrad() || !SumGradCompleted() || !HasInnerVar()) {
    return;
  }
  PADDLE_ENFORCE_EQ(HasInnerVar(), true,
                    platform::errors::InvalidArgument(
                        "Leaf tensor should have inner var to store results of "
                        "this auto-grad"));
  PADDLE_ENFORCE_EQ(inner_var_->Var().IsInitialized(), true,
                    platform::errors::InvalidArgument(
612
                        "Interior var of Leaf tensor should be initialized."));
613 614 615
  auto* src = inner_var_->MutableVar();
  auto* dst = var_->MutableVar();
  if (!var_->IsEmpty()) {
616 617 618
    VLOG(6) << "Leaf Var(" << var_->Name()
            << ")'s Gradient has been initizlized, will accumulate on "
               "previous gradient.";
619 620
    if (dst->IsType<framework::LoDTensor>()) {
      if (src->IsType<framework::LoDTensor>()) {
621
        TensorAdd<framework::Variable>(*src, dst);
622
      } else if (src->IsType<pten::SelectedRows>()) {
623 624
        SelectedRowsAddToTensor(*src, dst);
      }
625
    } else if (dst->IsType<pten::SelectedRows>()) {
626 627 628
      if (src->IsType<framework::LoDTensor>()) {
        SelectedRowsAddToTensor(*dst, src);
        *dst = std::move(*src);
629
      } else if (src->IsType<pten::SelectedRows>()) {
630
        auto temp = SelectedRowsMerge<VariableWrapper>(*src, *dst);
631 632 633 634 635 636 637
        *dst = std::move(*(temp->MutableVar()));
      }
    } else {
      PADDLE_THROW(platform::errors::PermissionDenied(
          "Only support LoDTensor and SelectedRows for gradient var"));
    }
  } else {
638 639 640
    VLOG(6)
        << "Leaf Var(" << var_->Name()
        << ")'s Gradient has not been initialized, not accumulate. Just move";
641 642 643
    *(dst) = std::move(*src);
    var_->SetType(inner_var_->Type());
    var_->SetDataType(inner_var_->DataType());
644
    var_->SetIsEmpty(false);
645 646 647 648
  }
  inner_var_.reset();
}

649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
void GradientAccumulator::CallGradientHooks() {
  PADDLE_ENFORCE_EQ(var_->IsLeafGrad(), true,
                    platform::errors::Unavailable(
                        "Only leaf gradient Tensor can deal with by gradient "
                        "hook in gradient accumulator."));
  PADDLE_ENFORCE_EQ(
      SumGradCompleted(), true,
      platform::errors::PreconditionNotMet(
          "Only can call gradient hooks after sum gradient completed."));
  PADDLE_ENFORCE_EQ(
      HasInnerVar(), true,
      platform::errors::PreconditionNotMet(
          "Leaf Tensor's inner var is nullptr when call gradient hook."));
  PADDLE_ENFORCE_EQ(
      inner_var_->Var().IsInitialized(), true,
      platform::errors::PreconditionNotMet("Leaf Tensor's inner var "
                                           "is not initialized when "
                                           "call gradient hook."));
667 668
  if (var_->HasVariableWrapperHook()) {
    VLOG(3) << "Call " << var_->GetVariableWrapperHooks().size()
669 670 671 672
            << " hooks of leaf gradient accumulator's inner var `"
            << var_->Name() << "`.";
    auto tmp_var = inner_var_;
    VLOG(3) << "Input var " << var_->Name() << "'s hook size - "
673 674
            << var_->GetVariableWrapperHooks().size();
    for (const auto& hook_pair : var_->GetVariableWrapperHooks()) {
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
      tmp_var = (*hook_pair.second)(tmp_var);
    }
    inner_var_ = tmp_var;
  }
}

void GradientAccumulator::CallReduceHooks() {
  PADDLE_ENFORCE_EQ(
      var_->IsLeafGrad(), true,
      platform::errors::Unavailable("Only leaf gradient Tensor can deal with "
                                    "by reduce hook in gradient accumulator."));
  PADDLE_ENFORCE_EQ(SumGradCompleted(), true,
                    platform::errors::PreconditionNotMet(
                        "Only can call reduce hooks after the gradient "
                        "summation is completed in current batch."));
  PADDLE_ENFORCE_EQ(HasInnerVar(), false,
                    platform::errors::PreconditionNotMet(
                        "Only can call reduce hooks after the "
                        "gradient accumulation is completed in "
                        "current batch or across batchs."));
695 696
  if (var_->HasVoidHook()) {
    for (const auto& hook : var_->GetVoidHooks()) {
697
      VLOG(3) << "call gradient accumulator backward hooks.";
698
      (*hook)();
699 700 701 702
    }
  }
}

703 704
void EagerGradientAccumulator::SumGrad(std::shared_ptr<VariableWrapper> var,
                                       size_t trace_id, bool unchange_input) {
705 706 707 708 709 710 711 712
  /**
   * If var has grad node, it indicates that this var would be an input
   * of a grad op. Therefore, it should not be changed.
   */
  if (var->HasGradNode()) {
    unchange_input = true;
  }

713
  auto* dst_var = Var();
714
  platform::Place place = GetPlaceOfVar(var);
715 716 717
  if (!dst_var->OverridedStopGradient()) {
    if (CurCnt() == 0) {
      MoveOrCopyVar(dst_var->MutableVar(), var->MutableVar(), unchange_input);
718
    } else {
719 720 721
      VLOG(6) << "Sum Gradient for: " << dst_var->Name()
              << " within this graph.";
      VariableWrapperAdd(var, dst_var, unchange_input);
722
    }
J
Jiabin Yang 已提交
723
  } else {
724 725 726
    if (!dst_var->Var().IsInitialized() ||
        !dst_var->Var().Get<framework::LoDTensor>().IsInitialized()) {
      VLOG(6) << "Set StopGradient Grad: " << dst_var->Name() << " as zero ";
727
      auto* dev_ctx = platform::DeviceContextPool::Instance().Get(place);
728 729 730 731
      if (!dst_var->Var().IsInitialized()) {
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
        VLOG(6) << "Dims of " << dst_var->Name() << " is set as: "
732 733
                << var->Var().Get<framework::LoDTensor>().dims();
        tensor->Resize(var->Var().Get<framework::LoDTensor>().dims());
734 735
        tensor->mutable_data(place,
                             framework::TransToPtenDataType(var->DataType()));
736
        pten::funcs::set_constant(*dev_ctx, tensor, 0.0);
737
      } else {
738 739
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
740 741
        tensor->mutable_data(place,
                             framework::TransToPtenDataType(var->DataType()));
742
        pten::funcs::set_constant(*dev_ctx, tensor, 0.0);
743
      }
744
    }
J
Jiabin Yang 已提交
745
  }
746

747 748 749 750
  // Type may be changed after OP run, such as VarTypeInference
  // so synchronous VariableWrapper with Variable.
  if (dst_var->Var().IsType<framework::LoDTensor>()) {
    dst_var->SetType(framework::proto::VarType::LOD_TENSOR);
751
  } else if (dst_var->Var().IsType<pten::SelectedRows>()) {
752
    dst_var->SetType(framework::proto::VarType::SELECTED_ROWS);
753
  }
754

755
  // Increase curent count
756
  IncreaseCurCnt();
J
Jiabin Yang 已提交
757 758
}

759 760 761
void SortedGradientAccumulator::SumGrad(std::shared_ptr<VariableWrapper> var,
                                        size_t trace_id, bool unchange_input) {
  auto* dst_var = Var();
762
  platform::Place place = GetPlaceOfVar(var);
763
  if (!dst_var->OverridedStopGradient()) {
764
    if (ref_cnt_ == 1) {
765
      MoveOrCopyVar(dst_var->MutableVar(), var->MutableVar(),
766
                    unchange_input || var->HasGradNode());
767 768 769 770 771
    } else {
      if (tmp_grad_vars_.empty()) {
        tmp_grad_vars_.reserve(ref_cnt_);
      }

772
      tmp_grad_vars_.emplace_back(std::move(var), trace_id, unchange_input);
773 774 775 776 777

      if (tmp_grad_vars_.size() != ref_cnt_) {
        return;
      }

778 779
      VLOG(6) << "Sum Gradient for: " << dst_var->Name()
              << " within this graph.";
780 781 782 783 784 785 786 787 788 789
      std::sort(tmp_grad_vars_.begin(), tmp_grad_vars_.end(),
                [](const SavedVarInfo& info1, const SavedVarInfo& info2) {
                  return info1.trace_id > info2.trace_id;
                });

      for (auto& var_info : tmp_grad_vars_) {
        if (var_info.var->HasGradNode()) {
          var_info.unchange_input = true;
        }
      }
790

791
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
792
      if (paddle::platform::is_gpu_place(place)) {
793
        // sum selected rows firstly
794
        for (auto& var_info : tmp_grad_vars_) {
795
          if (!var_info.var->Var().IsType<pten::SelectedRows>()) {
796
            continue;
797
          }
798

799 800
          if (CurCnt() == 0) {
            MoveOrCopyVar(dst_var->MutableVar(), var_info.var->MutableVar(),
801 802
                          var_info.unchange_input);
          } else {
803
            VariableWrapperAdd(var_info.var, dst_var, var_info.unchange_input);
804
          }
805 806

          var_info.var = nullptr;
807 808
          // Increase count
          IncreaseCurCnt();
809 810 811 812 813 814 815 816 817 818
        }

        for (auto& var_info : tmp_grad_vars_) {
          if (!var_info.var) {
            continue;
          }

          PADDLE_ENFORCE_EQ(var_info.var->Var().IsType<framework::LoDTensor>(),
                            true, platform::errors::PermissionDenied(
                                      "Gradient var must be LoDTensor"));
819 820
          if (CurCnt() == 0) {
            MoveOrCopyVar(dst_var->MutableVar(), var_info.var->MutableVar(),
821 822
                          var_info.unchange_input);
          } else {
823
            VariableWrapperAdd(var_info.var, dst_var, var_info.unchange_input);
824
          }
825 826

          var_info.var = nullptr;
827 828
          // Increase count
          IncreaseCurCnt();
829 830 831
        }
      } else {
#endif
832 833 834 835 836 837
        for (auto& var_info : tmp_grad_vars_) {
          if (!var_info.var) {
            continue;
          }
          PADDLE_ENFORCE_EQ(
              var_info.var->Var().IsType<framework::LoDTensor>() ||
838
                  var_info.var->Var().IsType<pten::SelectedRows>(),
839 840 841 842 843 844 845 846 847 848 849 850
              true, platform::errors::PermissionDenied("The type of Gradient "
                                                       "var must be LoDTensor "
                                                       "or SelectedRows"));
          if (CurCnt() == 0) {
            MoveOrCopyVar(dst_var->MutableVar(), var_info.var->MutableVar(),
                          var_info.unchange_input);
          } else {
            VariableWrapperAdd(var_info.var, dst_var, var_info.unchange_input);
          }
          var_info.var = nullptr;
          // Increase count
          IncreaseCurCnt();
851
        }
852
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
853
      }
854
#endif
855
      tmp_grad_vars_.clear();
J
Jiabin Yang 已提交
856
    }
857
  } else {
858 859
    if (!dst_var->Var().IsInitialized() ||
        !dst_var->Var().Get<framework::LoDTensor>().IsInitialized()) {
860 861
      VLOG(6) << "Set StopGradient Grad: " << var->Name() << " as zero";
      auto* dev_ctx = platform::DeviceContextPool::Instance().Get(place);
862 863 864 865
      if (!dst_var->Var().IsInitialized()) {
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
        VLOG(6) << "Dims of " << dst_var->Name() << " is set as: "
866 867
                << var->Var().Get<framework::LoDTensor>().dims();
        tensor->Resize(var->Var().Get<framework::LoDTensor>().dims());
868 869
        tensor->mutable_data(place,
                             framework::TransToPtenDataType(var->DataType()));
870
        pten::funcs::set_constant(*dev_ctx, tensor, 0.0);
871
      } else {
872 873
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
874 875
        tensor->mutable_data(place,
                             framework::TransToPtenDataType(var->DataType()));
876
        pten::funcs::set_constant(*dev_ctx, tensor, 0.0);
877
      }
J
Jiabin Yang 已提交
878
    }
879
    // looks like tmp_grad_vars will not have any member but just in case
J
Jiabin Yang 已提交
880 881
    tmp_grad_vars_.clear();
  }
882

883 884
  if (dst_var->Var().IsType<framework::LoDTensor>()) {
    dst_var->SetType(framework::proto::VarType::LOD_TENSOR);
885
  } else if (dst_var->Var().IsType<pten::SelectedRows>()) {
886
    dst_var->SetType(framework::proto::VarType::SELECTED_ROWS);
887
  }
J
Jiabin Yang 已提交
888 889 890 891
}

}  // namespace imperative
}  // namespace paddle