gradient_accumulator.cc 38.1 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
#include "paddle/fluid/imperative/layer.h"
25
#include "paddle/fluid/operators/math/selected_rows_functor.h"
26
#include "paddle/fluid/platform/bfloat16.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 32
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/math_function.h"
H
hong 已提交
33 34 35
#ifdef PADDLE_WITH_XPU
#include "xpu/refactor/math.h"
#endif
36
#ifdef PADDLE_WITH_ASCEND_CL
37
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
38
#endif
F
fwenguang 已提交
39 40 41
#ifdef PADDLE_WITH_MLU
#include "paddle/fluid/operators/mlu/mlu_baseop.h"
#endif
J
Jiabin Yang 已提交
42 43 44 45

namespace paddle {
namespace imperative {

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

55
  VLOG(6) << "Copy occurs when sum gradients within this graph";
56 57 58 59 60 61 62 63
  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());
64 65 66
  } else if (src->IsType<phi::SelectedRows>()) {
    auto& src_selected_rows = src->Get<phi::SelectedRows>();
    if (!dst->IsType<phi::SelectedRows>()) {
67 68
      dst->Clear();
    }
69
    auto* dst_selected_rows = dst->GetMutable<phi::SelectedRows>();
70 71 72 73 74 75 76
    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(
77
        "Only support LoDTensor and SelectedRows for sum gradient"));
78 79 80
  }
}

J
Jiabin Yang 已提交
81
template <typename T>
82 83
class TensorAddFunctor
    : public std::unary_function<const platform::Place&, void> {
J
Jiabin Yang 已提交
84 85 86 87
 public:
  TensorAddFunctor(int64_t numel, const T* x, T* y)
      : numel_(numel), x_(x), y_(y) {}

88
  void operator()(const platform::CPUPlace& place) const {
L
Leo Chen 已提交
89
    phi::CPUContext* ctx = dynamic_cast<phi::CPUContext*>(
J
Jiabin Yang 已提交
90
        platform::DeviceContextPool::Instance().Get(place));
L
Leo Chen 已提交
91
    auto blas = phi::funcs::GetBlas<phi::CPUContext, T>(*ctx);
J
Jiabin Yang 已提交
92 93 94
    blas.AXPY(numel_, 1., x_, y_);
  }

H
hong 已提交
95
#ifdef PADDLE_WITH_XPU
96
  void operator()(const platform::XPUPlace& place) const {
97
    using XPUType = typename XPUTypeTrait<T>::Type;
H
hong 已提交
98 99
    platform::XPUDeviceContext* ctx = dynamic_cast<platform::XPUDeviceContext*>(
        platform::DeviceContextPool::Instance().Get(place));
100 101 102 103 104
    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_));
105
    PADDLE_ENFORCE_EQ(
106 107 108 109
        r,
        XPU_SUCCESS,
        platform::errors::External(
            "XPU add kernel return wrong value[%d %s]", r, XPUAPIErrorMsg[r]));
H
hong 已提交
110 111
  }
#else
112
  void operator()(const platform::XPUPlace& place) const {
113 114 115 116 117
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
H
hong 已提交
118
#endif
119

120
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
121
  void operator()(const platform::CUDAPlace& place) const {
J
Jiabin Yang 已提交
122 123 124
    platform::CUDADeviceContext* ctx =
        dynamic_cast<platform::CUDADeviceContext*>(
            platform::DeviceContextPool::Instance().Get(place));
125
    auto blas = phi::funcs::GetBlas<platform::CUDADeviceContext, T>(*ctx);
J
Jiabin Yang 已提交
126 127 128
    blas.AXPY(numel_, 1., x_, y_);
  }
#else
129
  void operator()(const platform::CUDAPlace& place) const {
130
    PADDLE_THROW(platform::errors::PermissionDenied(
131 132 133 134 135 136
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#endif

F
fwenguang 已提交
137
#ifdef PADDLE_WITH_MLU
138
  void operator()(const platform::MLUPlace& place) const {
F
fwenguang 已提交
139 140 141 142 143 144 145
    // TODO(fwg): SUPPORT it
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#else
146
  void operator()(const platform::MLUPlace& place) const {
F
fwenguang 已提交
147 148 149 150 151 152 153
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#endif

154
#ifdef PADDLE_WITH_ASCEND_CL
155
  void operator()(const platform::NPUPlace& place) const {
156 157 158 159 160 161 162
    // TODO(zhiqiu): SUPPORT it
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
#else
163
  void operator()(const platform::NPUPlace& place) const {
164
    PADDLE_THROW(platform::errors::PermissionDenied(
165 166 167
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
J
Jiabin Yang 已提交
168 169 170
  }
#endif

171
  void operator()(const platform::NPUPinnedPlace& place) const {
172 173 174 175 176
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
J
Jiabin Yang 已提交
177
  // there is NO blas in CUDAPinnedPlace
178
  void operator()(const platform::CUDAPinnedPlace& place) const {
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
  }
J
jianghaicheng 已提交
184
  // there is NO support in IPUPlace
185
  void operator()(const platform::IPUPlace& place) const {
J
jianghaicheng 已提交
186 187 188 189 190
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
191 192 193 194 195 196
  void operator()(const platform::CustomPlace& place) const {
    PADDLE_THROW(platform::errors::PermissionDenied(
        "Gradient accumulation on place (%s) "
        "is not supported in imperative mode",
        place));
  }
J
Jiabin Yang 已提交
197 198 199 200

 private:
  int64_t numel_;
  const T* x_;
201
  mutable T* y_;
J
Jiabin Yang 已提交
202 203
};

204 205 206
#ifdef PADDLE_WITH_XPU
template <typename T>
void XPUTensorAddFunctor(const platform::Place& place,
207 208
                         const framework::Tensor& src,
                         framework::Tensor* dst) {
209 210 211 212 213
  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));
214 215
  int r = xpu::add<XPUType>(
      ctx->x_context(), x, y, y, static_cast<int>(src.numel()));
216
  PADDLE_ENFORCE_EQ(
217 218 219 220
      r,
      XPU_SUCCESS,
      platform::errors::External(
          "XPU add kernel return wrong value[%d %s]", r, XPUAPIErrorMsg[r]));
221 222 223
}
#endif

224
template <typename DeviceContext, typename T>
225 226
void TensorAddImpl(const framework::Tensor& src,
                   framework::Tensor* dst,
227 228 229 230
                   const platform::Place& place) {
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
  paddle::platform::DeviceContext* ctx = pool.Get(place);
  auto dev_ctx = dynamic_cast<DeviceContext*>(ctx);
231
  phi::funcs::ElementwiseAddTo<DeviceContext, T> func;
232 233 234
  func(dev_ctx, src, dst);
}

235 236 237
template <typename TType>
TType* GetInnerMutableTensor(framework::Variable* dst) {
  auto* dst_tensor = dst->GetMutable<TType>();
238 239 240
  return dst_tensor;
}

241 242 243
template <typename TType>
TType* GetInnerMutableTensor(paddle::experimental::Tensor* dst) {
  auto* dst_tensor = static_cast<TType*>(dst->impl().get());
244 245 246
  return dst_tensor;
}

247 248 249
template <typename TType>
const TType& GetInnerTensor(const framework::Variable& src) {
  return src.Get<TType>();
250 251
}

252 253 254
template <typename TType>
TType& GetInnerTensor(const paddle::experimental::Tensor& src) {
  PADDLE_ENFORCE_EQ(
255 256
      src.initialized(),
      true,
257 258 259 260 261
      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;
262 263
}

264 265 266
template <typename TType>
TType* GetEmptyInnerTensor(paddle::experimental::Tensor* dst) {
  PADDLE_ENFORCE_EQ(
267 268
      dst->defined(),
      false,
269 270 271 272 273 274 275 276 277 278 279 280 281
      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;
}

282 283
template <typename VarType>
void TensorAdd(const VarType& src, VarType* dst) {
284 285
  phi::DenseTensor* dst_tensor = GetInnerMutableTensor<phi::DenseTensor>(dst);
  const phi::DenseTensor& src_tensor = GetInnerTensor<phi::DenseTensor>(src);
J
Jiabin Yang 已提交
286 287 288 289 290 291 292 293 294

  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;
  }

295
  PADDLE_ENFORCE_EQ(
296 297
      dst_tensor->numel(),
      numel,
298 299 300 301
      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.",
302 303
          numel,
          dst_tensor->numel()));
J
Jiabin Yang 已提交
304

305
  auto data_type = framework::TransToProtoVarType(src_tensor.dtype());
J
Jiabin Yang 已提交
306 307
  auto place = src_tensor.place();

308 309
  PADDLE_ENFORCE_EQ(framework::TransToProtoVarType(dst_tensor->dtype()),
                    data_type,
310 311 312 313 314
                    platform::errors::PreconditionNotMet(
                        "The data type of source tensor and destination tensor "
                        "should be equal, Otherwise, the calculation results "
                        "will be incorrect."));

315 316 317 318
  // 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);
  }
319
#define PADDLE_TENSOR_ADD(cpp_type)                                  \
J
Jiabin Yang 已提交
320 321
  if (data_type == framework::DataTypeTrait<cpp_type>::DataType()) { \
    TensorAddFunctor<cpp_type> func(                                 \
322 323
        numel,                                                       \
        src_tensor.data<cpp_type>(),                                 \
J
Jiabin Yang 已提交
324
        dst_tensor->mutable_data<cpp_type>(place));                  \
325
    platform::VisitPlace(place, func);                               \
J
Jiabin Yang 已提交
326 327 328
    return;                                                          \
  }

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
#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",
345 346
          framework::DataTypeToString(data_type),
          place));
347 348 349 350 351 352 353
    }
    const auto& runner = operators::NpuOpRunner(
        "Add", {*dst_tensor, src_tensor}, {*dst_tensor}, {});
    runner.Run(dev_ctx->stream());
    return;
  }
#endif
354 355 356 357 358
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  if (platform::is_custom_place(place)) {
    PADDLE_THROW(platform::errors::Unimplemented(
        "Gradient accumulation of data type (%s) on place (%s) is not "
        "supported in imperative mode",
359 360
        framework::DataTypeToString(data_type),
        place));
361 362
  }
#endif
363 364 365 366 367 368 369 370 371 372 373
#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",
374 375
          framework::DataTypeToString(data_type),
          place));
376 377 378 379 380
    }
    return;
  }
#endif

F
fwenguang 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394
#ifdef PADDLE_WITH_MLU
  if (platform::is_mlu_place(place)) {
    platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
    platform::DeviceContext* ctx = pool.Get(place);
    auto dev_ctx = dynamic_cast<platform::MLUDeviceContext*>(ctx);
    if (data_type == framework::DataTypeTrait<float>::DataType()) {
      dst_tensor->mutable_data<float>(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",
395 396
          framework::DataTypeToString(data_type),
          place));
F
fwenguang 已提交
397 398 399 400 401
    }
    static const float alpha = 1.f;
    static const float beta = 1.f;
    operators::MLUCnnlTensorDesc src_tensor_desc(src_tensor);
    operators::MLUCnnlTensorDesc dst_tensor_desc(*dst_tensor);
402 403 404 405 406 407 408 409 410 411
    PADDLE_ENFORCE_MLU_SUCCESS(
        cnnlAssignAdd(dev_ctx->cnnl_handle(),
                      static_cast<const void*>(&alpha),
                      src_tensor_desc.get(),
                      operators::GetBasePtr(&src_tensor),
                      nullptr,
                      0,
                      static_cast<const void*>(&beta),
                      dst_tensor_desc.get(),
                      operators::GetBasePtr(dst_tensor)));
F
fwenguang 已提交
412 413 414 415
    return;
  }
#endif

416
  PADDLE_TENSOR_ADD(float);
417

H
hong 已提交
418 419
#ifndef PADDLE_WITH_XPU
  // NOTE(phlrain): xpu only support float
420
  PADDLE_TENSOR_ADD(double);
421 422
  // NOTE(chenweihang): only support complex grad tensor accumulated,
  // support selected rows if needed in the future
423 424
  PADDLE_TENSOR_ADD(platform::complex<float>);
  PADDLE_TENSOR_ADD(platform::complex<double>);
H
hong 已提交
425
#endif
J
Jiabin Yang 已提交
426

427
#undef PADDLE_TENSOR_ADD
J
Jiabin Yang 已提交
428

429 430
  if (data_type == framework::proto::VarType::FP16) {
    if (platform::is_gpu_place(place)) {
431
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
432 433 434 435 436 437
      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",
438 439
          framework::DataTypeToString(data_type),
          place));
440 441
#endif
    } else if (platform::is_cpu_place(place)) {
L
Leo Chen 已提交
442
      return TensorAddImpl<phi::CPUContext, platform::float16>(
443 444 445
          src_tensor, dst_tensor, place);
    }
  }
446 447
  if (data_type == framework::proto::VarType::BF16) {
    if (platform::is_gpu_place(place)) {
448
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
449 450 451 452 453 454
      return TensorAddImpl<platform::CUDADeviceContext, platform::bfloat16>(
          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",
455 456
          framework::DataTypeToString(data_type),
          place));
457 458
#endif
    } else if (platform::is_cpu_place(place)) {
L
Leo Chen 已提交
459
      return TensorAddImpl<phi::CPUContext, platform::bfloat16>(
460 461 462
          src_tensor, dst_tensor, place);
    }
  }
463 464 465
  PADDLE_THROW(platform::errors::Unimplemented(
      "Gradient accumulation of data type (%s) on place (%s) is not "
      "supported in imperative mode",
466 467
      framework::DataTypeToString(data_type),
      place));
J
Jiabin Yang 已提交
468 469
}

470 471
template void TensorAdd<framework::Variable>(const framework::Variable& src,
                                             framework::Variable* dst);
472 473
template void TensorAdd<paddle::experimental::Tensor>(
    const paddle::experimental::Tensor& src, paddle::experimental::Tensor* dst);
474

475 476
template <typename VarType>
void SelectedRowsAddToTensor(const VarType& src, VarType* dst) {
477 478 479
  phi::DenseTensor* dst_tensor = GetInnerMutableTensor<phi::DenseTensor>(dst);
  const phi::SelectedRows& src_selected_rows =
      GetInnerTensor<phi::SelectedRows>(src);
480
  auto place = dst_tensor->place();
481 482
  auto data_type =
      framework::TransToProtoVarType(src_selected_rows.value().dtype());
483 484 485 486 487 488 489
  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;                                                             \
490 491
    functor(*(dynamic_cast<dev_ctx_type*>(dev_ctx)),                         \
            src_selected_rows,                                               \
492 493 494 495
            dst_tensor);                                                     \
    return;                                                                  \
  }

496
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
497 498 499 500 501
  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
L
Leo Chen 已提交
502 503
    PADDLE_SELECTED_ROWS_ADD_TO_TENSOR(phi::CPUContext, float);
    PADDLE_SELECTED_ROWS_ADD_TO_TENSOR(phi::CPUContext, double);
504
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
505 506 507 508 509 510 511 512 513 514
  }
#endif

#undef PADDLE_SELECTED_ROWS_ADD_TO_TENSOR

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

515 516 517 518 519 520 521 522 523
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) {
524 525 526 527
  const phi::SelectedRows& src_selected_rows =
      GetInnerTensor<phi::SelectedRows>(src_selected_rows_var);
  const phi::DenseTensor& src_tensor =
      GetInnerTensor<phi::DenseTensor>(src_tensor_var);
528
  const auto& place = src_tensor.place();
529
  auto data_type = framework::TransToProtoVarType(src_tensor.dtype());
530 531
  auto* dev_ctx = platform::DeviceContextPool::Instance().Get(place);

532 533
  phi::DenseTensor* dst_tensor =
      GetInnerMutableTensor<phi::DenseTensor>(dst_tensor_var);
534
  dst_tensor->Resize(src_tensor.dims());
535 536
  dst_tensor->mutable_data(place, src_tensor.dtype());

537 538 539 540
#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;                                                           \
541 542 543 544
    functor(*(dynamic_cast<dev_ctx_type*>(dev_ctx)),                       \
            src_selected_rows,                                             \
            src_tensor,                                                    \
            dst_tensor);                                                   \
545 546 547
    return;                                                                \
  }

548
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
549 550 551 552 553
  if (platform::is_gpu_place(place)) {
    PADDLE_SELECTED_ROWS_ADD_TENSOR(platform::CUDADeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD_TENSOR(platform::CUDADeviceContext, double);
  } else {
#endif
L
Leo Chen 已提交
554 555
    PADDLE_SELECTED_ROWS_ADD_TENSOR(phi::CPUContext, float);
    PADDLE_SELECTED_ROWS_ADD_TENSOR(phi::CPUContext, double);
556
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
557 558 559 560 561 562 563 564 565 566
  }
#endif

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

#undef PADDLE_SELECTED_ROWS_ADD_TENSOR
}

567 568 569 570 571 572 573 574 575 576 577 578
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
579 580 581
template <typename ReturnVarType, typename VarType>
std::shared_ptr<ReturnVarType> SelectedRowsMerge(const VarType& src1,
                                                 const VarType& src2) {
582 583 584 585
  const phi::SelectedRows& src_selected_rows1 =
      GetInnerTensor<phi::SelectedRows>(src1);
  const phi::SelectedRows& src_selected_rows2 =
      GetInnerTensor<phi::SelectedRows>(src2);
586

587
  auto place = src_selected_rows1.value().place();
588 589
  auto data_type =
      framework::TransToProtoVarType(src_selected_rows1.value().dtype());
590 591
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();

592
  std::vector<const phi::SelectedRows*> src_selected_rows;
593 594
  src_selected_rows.emplace_back(&src_selected_rows1);
  src_selected_rows.emplace_back(&src_selected_rows2);
595 596

  auto dst_var = std::make_shared<ReturnVarType>("Temp");
597 598
  phi::SelectedRows* dst_selected_rows =
      GetEmptyInnerTensor<phi::SelectedRows>(dst_var.get());
599

600 601 602 603 604 605 606 607 608
#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;                                                    \
609 610
  }

611
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
612 613 614 615 616
  if (paddle::platform::is_gpu_place(place)) {
    PADDLE_SELECTED_ROWS_ADD(platform::CUDADeviceContext, float);
    PADDLE_SELECTED_ROWS_ADD(platform::CUDADeviceContext, double);
  } else {
#endif
L
Leo Chen 已提交
617 618
    PADDLE_SELECTED_ROWS_ADD(phi::CPUContext, float);
    PADDLE_SELECTED_ROWS_ADD(phi::CPUContext, double);
619
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
620 621 622 623 624 625 626 627 628
  }
#endif

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

629 630 631 632 633 634
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);

635
void VariableWrapperAdd(std::shared_ptr<VariableWrapper> var,
636 637
                        VariableWrapper* dst_var,
                        bool unchange_input) {
638
  auto& src = var->Var();
639
  auto* dst = dst_var->MutableVar();
640 641
  if (dst->IsType<framework::LoDTensor>()) {
    if (src.IsType<framework::LoDTensor>()) {
642
      TensorAdd<framework::Variable>(src, dst);
643
    } else if (src.IsType<phi::SelectedRows>()) {
644 645 646 647 648 649 650 651
      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>()) {
652 653 654 655 656 657 658 659 660
      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()));
      }
661
    } else if (src.IsType<phi::SelectedRows>()) {
662
      auto temp = SelectedRowsMerge<VariableWrapper>(src, *dst);
663 664 665 666 667 668 669 670 671
      *dst = std::move(*(temp->MutableVar()));
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Unexpected branch, output variable type is %s",
          framework::ToTypeName(dst->Type())));
    }
  }
}

672 673
static platform::Place GetPlaceOfVar(
    const std::shared_ptr<VariableWrapper>& var) {
674 675 676
  platform::Place place;
  if (var->Var().IsType<framework::LoDTensor>()) {
    place = var->Var().Get<framework::LoDTensor>().place();
677 678
  } else if (var->Var().IsType<phi::SelectedRows>()) {
    place = var->Var().Get<phi::SelectedRows>().place();
679 680 681 682 683 684 685
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "only support LoDTensor and SelectedRows in dygraph"));
  }
  return place;
}

686 687
void GradientAccumulator::AccumulateGrad() {
  /**
688 689
   * If the leaf gradient has been calculated done, the inner_var_
   * should be added to the var_.
690 691 692 693
   */
  if (!var_->IsLeafGrad() || !SumGradCompleted() || !HasInnerVar()) {
    return;
  }
694 695
  PADDLE_ENFORCE_EQ(HasInnerVar(),
                    true,
696 697 698
                    platform::errors::InvalidArgument(
                        "Leaf tensor should have inner var to store results of "
                        "this auto-grad"));
699 700
  PADDLE_ENFORCE_EQ(inner_var_->Var().IsInitialized(),
                    true,
701
                    platform::errors::InvalidArgument(
702
                        "Interior var of Leaf tensor should be initialized."));
703 704 705
  auto* src = inner_var_->MutableVar();
  auto* dst = var_->MutableVar();
  if (!var_->IsEmpty()) {
706 707 708
    VLOG(6) << "Leaf Var(" << var_->Name()
            << ")'s Gradient has been initizlized, will accumulate on "
               "previous gradient.";
709 710
    if (dst->IsType<framework::LoDTensor>()) {
      if (src->IsType<framework::LoDTensor>()) {
711
        TensorAdd<framework::Variable>(*src, dst);
712
      } else if (src->IsType<phi::SelectedRows>()) {
713 714
        SelectedRowsAddToTensor(*src, dst);
      }
715
    } else if (dst->IsType<phi::SelectedRows>()) {
716 717 718
      if (src->IsType<framework::LoDTensor>()) {
        SelectedRowsAddToTensor(*dst, src);
        *dst = std::move(*src);
719
      } else if (src->IsType<phi::SelectedRows>()) {
720
        auto temp = SelectedRowsMerge<VariableWrapper>(*src, *dst);
721 722 723 724 725 726 727
        *dst = std::move(*(temp->MutableVar()));
      }
    } else {
      PADDLE_THROW(platform::errors::PermissionDenied(
          "Only support LoDTensor and SelectedRows for gradient var"));
    }
  } else {
728 729 730
    VLOG(6)
        << "Leaf Var(" << var_->Name()
        << ")'s Gradient has not been initialized, not accumulate. Just move";
731 732 733
    *(dst) = std::move(*src);
    var_->SetType(inner_var_->Type());
    var_->SetDataType(inner_var_->DataType());
734
    var_->SetIsEmpty(false);
735 736 737 738
  }
  inner_var_.reset();
}

739
void GradientAccumulator::CallGradientHooks() {
740 741
  PADDLE_ENFORCE_EQ(var_->IsLeafGrad(),
                    true,
742 743 744 745
                    platform::errors::Unavailable(
                        "Only leaf gradient Tensor can deal with by gradient "
                        "hook in gradient accumulator."));
  PADDLE_ENFORCE_EQ(
746 747
      SumGradCompleted(),
      true,
748 749 750
      platform::errors::PreconditionNotMet(
          "Only can call gradient hooks after sum gradient completed."));
  PADDLE_ENFORCE_EQ(
751 752
      HasInnerVar(),
      true,
753 754 755
      platform::errors::PreconditionNotMet(
          "Leaf Tensor's inner var is nullptr when call gradient hook."));
  PADDLE_ENFORCE_EQ(
756 757
      inner_var_->Var().IsInitialized(),
      true,
758 759 760
      platform::errors::PreconditionNotMet("Leaf Tensor's inner var "
                                           "is not initialized when "
                                           "call gradient hook."));
761 762
  if (var_->HasVariableWrapperHook()) {
    VLOG(3) << "Call " << var_->GetVariableWrapperHooks().size()
763 764 765 766
            << " hooks of leaf gradient accumulator's inner var `"
            << var_->Name() << "`.";
    auto tmp_var = inner_var_;
    VLOG(3) << "Input var " << var_->Name() << "'s hook size - "
767 768
            << var_->GetVariableWrapperHooks().size();
    for (const auto& hook_pair : var_->GetVariableWrapperHooks()) {
769
      tmp_var = (*hook_pair.second)(tmp_var);
L
Leo Chen 已提交
770
      CheckVar(inner_var_, tmp_var);
771 772 773 774 775 776 777
    }
    inner_var_ = tmp_var;
  }
}

void GradientAccumulator::CallReduceHooks() {
  PADDLE_ENFORCE_EQ(
778 779
      var_->IsLeafGrad(),
      true,
780 781
      platform::errors::Unavailable("Only leaf gradient Tensor can deal with "
                                    "by reduce hook in gradient accumulator."));
782 783
  PADDLE_ENFORCE_EQ(SumGradCompleted(),
                    true,
784 785 786
                    platform::errors::PreconditionNotMet(
                        "Only can call reduce hooks after the gradient "
                        "summation is completed in current batch."));
787 788
  PADDLE_ENFORCE_EQ(HasInnerVar(),
                    false,
789 790 791 792
                    platform::errors::PreconditionNotMet(
                        "Only can call reduce hooks after the "
                        "gradient accumulation is completed in "
                        "current batch or across batchs."));
793 794
  if (var_->HasVoidHook()) {
    for (const auto& hook : var_->GetVoidHooks()) {
795
      VLOG(3) << "call gradient accumulator backward hooks.";
796
      (*hook)();
797 798 799 800
    }
  }
}

801
void EagerGradientAccumulator::SumGrad(std::shared_ptr<VariableWrapper> var,
802 803
                                       size_t trace_id,
                                       bool unchange_input) {
804 805 806 807 808 809 810 811
  /**
   * 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;
  }

812
  auto* dst_var = Var();
813
  platform::Place place = GetPlaceOfVar(var);
814 815 816
  if (!dst_var->OverridedStopGradient()) {
    if (CurCnt() == 0) {
      MoveOrCopyVar(dst_var->MutableVar(), var->MutableVar(), unchange_input);
817
    } else {
818 819 820
      VLOG(6) << "Sum Gradient for: " << dst_var->Name()
              << " within this graph.";
      VariableWrapperAdd(var, dst_var, unchange_input);
821
    }
J
Jiabin Yang 已提交
822
  } else {
823 824 825
    if (!dst_var->Var().IsInitialized() ||
        !dst_var->Var().Get<framework::LoDTensor>().IsInitialized()) {
      VLOG(6) << "Set StopGradient Grad: " << dst_var->Name() << " as zero ";
826
      auto* dev_ctx = platform::DeviceContextPool::Instance().Get(place);
827 828 829 830
      if (!dst_var->Var().IsInitialized()) {
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
        VLOG(6) << "Dims of " << dst_var->Name() << " is set as: "
831 832
                << var->Var().Get<framework::LoDTensor>().dims();
        tensor->Resize(var->Var().Get<framework::LoDTensor>().dims());
833
        tensor->mutable_data(place,
834
                             framework::TransToPhiDataType(var->DataType()));
835
        phi::funcs::set_constant(*dev_ctx, tensor, 0.0);
836
      } else {
837 838
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
839
        tensor->mutable_data(place,
840
                             framework::TransToPhiDataType(var->DataType()));
841
        phi::funcs::set_constant(*dev_ctx, tensor, 0.0);
842
      }
843
    }
J
Jiabin Yang 已提交
844
  }
845

846 847 848 849
  // 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);
850
  } else if (dst_var->Var().IsType<phi::SelectedRows>()) {
851
    dst_var->SetType(framework::proto::VarType::SELECTED_ROWS);
852
  }
853

854
  // Increase curent count
855
  IncreaseCurCnt();
J
Jiabin Yang 已提交
856 857
}

858
void SortedGradientAccumulator::SumGrad(std::shared_ptr<VariableWrapper> var,
859 860
                                        size_t trace_id,
                                        bool unchange_input) {
861
  auto* dst_var = Var();
862
  platform::Place place = GetPlaceOfVar(var);
863
  if (!dst_var->OverridedStopGradient()) {
864
    if (ref_cnt_ == 1) {
865 866
      MoveOrCopyVar(dst_var->MutableVar(),
                    var->MutableVar(),
867
                    unchange_input || var->HasGradNode());
868 869 870 871 872
    } else {
      if (tmp_grad_vars_.empty()) {
        tmp_grad_vars_.reserve(ref_cnt_);
      }

873
      tmp_grad_vars_.emplace_back(std::move(var), trace_id, unchange_input);
874 875 876 877 878

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

879 880
      VLOG(6) << "Sum Gradient for: " << dst_var->Name()
              << " within this graph.";
881 882
      std::sort(tmp_grad_vars_.begin(),
                tmp_grad_vars_.end(),
883 884 885 886 887 888 889 890 891
                [](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;
        }
      }
892

893
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
894
      if (paddle::platform::is_gpu_place(place)) {
895
        // sum selected rows firstly
896
        for (auto& var_info : tmp_grad_vars_) {
897
          if (!var_info.var->Var().IsType<phi::SelectedRows>()) {
898
            continue;
899
          }
900

901
          if (CurCnt() == 0) {
902 903
            MoveOrCopyVar(dst_var->MutableVar(),
                          var_info.var->MutableVar(),
904 905
                          var_info.unchange_input);
          } else {
906
            VariableWrapperAdd(var_info.var, dst_var, var_info.unchange_input);
907
          }
908 909

          var_info.var = nullptr;
910 911
          // Increase count
          IncreaseCurCnt();
912 913 914 915 916 917 918 919
        }

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

          PADDLE_ENFORCE_EQ(var_info.var->Var().IsType<framework::LoDTensor>(),
920 921 922
                            true,
                            platform::errors::PermissionDenied(
                                "Gradient var must be LoDTensor"));
923
          if (CurCnt() == 0) {
924 925
            MoveOrCopyVar(dst_var->MutableVar(),
                          var_info.var->MutableVar(),
926 927
                          var_info.unchange_input);
          } else {
928
            VariableWrapperAdd(var_info.var, dst_var, var_info.unchange_input);
929
          }
930 931

          var_info.var = nullptr;
932 933
          // Increase count
          IncreaseCurCnt();
934 935 936
        }
      } else {
#endif
937 938 939 940 941 942
        for (auto& var_info : tmp_grad_vars_) {
          if (!var_info.var) {
            continue;
          }
          PADDLE_ENFORCE_EQ(
              var_info.var->Var().IsType<framework::LoDTensor>() ||
943
                  var_info.var->Var().IsType<phi::SelectedRows>(),
944 945 946 947
              true,
              platform::errors::PermissionDenied("The type of Gradient "
                                                 "var must be LoDTensor "
                                                 "or SelectedRows"));
948
          if (CurCnt() == 0) {
949 950
            MoveOrCopyVar(dst_var->MutableVar(),
                          var_info.var->MutableVar(),
951 952 953 954 955 956 957
                          var_info.unchange_input);
          } else {
            VariableWrapperAdd(var_info.var, dst_var, var_info.unchange_input);
          }
          var_info.var = nullptr;
          // Increase count
          IncreaseCurCnt();
958
        }
959
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
960
      }
961
#endif
962
      tmp_grad_vars_.clear();
J
Jiabin Yang 已提交
963
    }
964
  } else {
965 966
    if (!dst_var->Var().IsInitialized() ||
        !dst_var->Var().Get<framework::LoDTensor>().IsInitialized()) {
967 968
      VLOG(6) << "Set StopGradient Grad: " << var->Name() << " as zero";
      auto* dev_ctx = platform::DeviceContextPool::Instance().Get(place);
969 970 971 972
      if (!dst_var->Var().IsInitialized()) {
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
        VLOG(6) << "Dims of " << dst_var->Name() << " is set as: "
973 974
                << var->Var().Get<framework::LoDTensor>().dims();
        tensor->Resize(var->Var().Get<framework::LoDTensor>().dims());
975
        tensor->mutable_data(place,
976
                             framework::TransToPhiDataType(var->DataType()));
977
        phi::funcs::set_constant(*dev_ctx, tensor, 0.0);
978
      } else {
979 980
        auto* tensor =
            dst_var->MutableVar()->GetMutable<framework::LoDTensor>();
981
        tensor->mutable_data(place,
982
                             framework::TransToPhiDataType(var->DataType()));
983
        phi::funcs::set_constant(*dev_ctx, tensor, 0.0);
984
      }
J
Jiabin Yang 已提交
985
    }
986
    // looks like tmp_grad_vars will not have any member but just in case
J
Jiabin Yang 已提交
987 988
    tmp_grad_vars_.clear();
  }
989

990 991
  if (dst_var->Var().IsType<framework::LoDTensor>()) {
    dst_var->SetType(framework::proto::VarType::LOD_TENSOR);
992
  } else if (dst_var->Var().IsType<phi::SelectedRows>()) {
993
    dst_var->SetType(framework::proto::VarType::SELECTED_ROWS);
994
  }
J
Jiabin Yang 已提交
995 996 997 998
}

}  // namespace imperative
}  // namespace paddle