adam_op_xpu.cc 23.8 KB
Newer Older
Y
yinhaofeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/* Copyright (c) 2016 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.

    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. */

14
#include "gflags/gflags.h"
15
#include "paddle/fluid/framework/op_registry.h"
16
#include "paddle/fluid/memory/memcpy.h"
17
#include "paddle/fluid/operators/optimizers/adam_op_functor.h"
Y
yinhaofeng 已提交
18 19 20 21 22

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
23
using float16 = paddle::platform::float16;
Y
yinhaofeng 已提交
24 25

#ifdef PADDLE_WITH_XPU
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
template <typename T1, typename T2>
static int ConvertDataByType(const T1* x,
                             T2** y,
                             int len,
                             bool allocateFlag,
                             const framework::ExecutionContext& ctx) {
  if (nullptr == x || nullptr == y || len <= 0)
    return xpu::Error_t::INVALID_PARAM;
  int r = 0;
  if (allocateFlag) {
    r = xpu_malloc(reinterpret_cast<void**>(y), sizeof(T2) * len);

    PADDLE_ENFORCE_EQ(
        r,
        xpu::Error_t::SUCCESS,
        platform::errors::External(
            "Alloc memory in xpu for result data failed with [%d]", r));
  }

  T1* cpu_data = reinterpret_cast<T1*>(malloc(sizeof(T1) * len));

  paddle::memory::Copy(paddle::platform::CPUPlace(),
                       cpu_data,
                       ctx.GetPlace(),
                       x,
                       len * sizeof(T1));

  T2* cpu_real_data = reinterpret_cast<T2*>(malloc(sizeof(T2) * len));
  for (int i = 0; i < len; i++) cpu_real_data[i] = static_cast<T2>(cpu_data[i]);

  paddle::memory::Copy(ctx.GetPlace(),
                       *y,
                       paddle::platform::CPUPlace(),
                       cpu_real_data,
                       len * sizeof(T2));

  free(cpu_data);
  free(cpu_real_data);

  return xpu::Error_t::SUCCESS;
}

template <typename T>
static void getDataPointer(const phi::DenseTensor& tensorData,
                           T** result,
                           const framework::ExecutionContext& ctx) {
  if (tensorData.dtype() == paddle::experimental::DataType::FLOAT16) {
    const float16* real_data =
        tensorData.template data<paddle::platform::float16>();
    int len = tensorData.numel();

    int r = ConvertDataByType<float16, T>(real_data, result, len, true, ctx);
    PADDLE_ENFORCE_EQ(
        r,
        xpu::Error_t::SUCCESS,
        platform::errors::External(
            "execute function ConvertDataByType failed with [%d]", r));
  }
}

template <typename T>
static void getOutDataPointer(phi::DenseTensor* tensorData,
                              Tensor* out,
                              T** result,
                              const framework::ExecutionContext& ctx) {
  if (tensorData->dtype() == paddle::experimental::DataType::FLOAT16) {
    *result = out->template mutable_data<T>(ctx.GetPlace());
  } else {
    *result = tensorData->template mutable_data<T>(ctx.GetPlace());
  }
}

template <typename T>
static void copyOutData(const Tensor& srcTensor,
                        phi::DenseTensor* dstTensor,
                        const framework::ExecutionContext& ctx) {
  if (dstTensor->dtype() == paddle::experimental::DataType::FLOAT16) {
    const T* xpu_out_data = srcTensor.template data<T>();
    float16* out_data =
        dstTensor->template mutable_data<float16>(ctx.GetPlace());

    int len = srcTensor.numel();

    int r =
        ConvertDataByType<T, float16>(xpu_out_data, &out_data, len, false, ctx);
    PADDLE_ENFORCE_EQ(
        r,
        xpu::Error_t::SUCCESS,
        platform::errors::External(
            "execute function ConvertDataByType failed with[%d]", r));
  }
}

template <typename T>
static void setBetaData(const phi::DenseTensor& beta_pow,
                        phi::DenseTensor* beta_pow_out,
                        const T& beta) {
  if (beta_pow.dtype() == paddle::experimental::DataType::FLOAT16) {
    const float16* beta_pow_p = beta_pow.template data<float16>();
    beta_pow_out->mutable_data<float16>(platform::CPUPlace())[0] =
        static_cast<float16>(beta) * beta_pow_p[0];
  } else {
    const T* beta_pow_p = beta_pow.template data<T>();
    beta_pow_out->mutable_data<T>(platform::CPUPlace())[0] =
        beta * beta_pow_p[0];
  }
}

template <typename DeviceContext, typename T>
static void scale(phi::DenseTensor* beta_pow_out,
                  const phi::DenseTensor& beta_pow,
                  T* beta_pow_ptr,
                  const T& beta,
                  const framework::ExecutionContext& ctx) {
  float16* beta_pow_out_p2 =
      beta_pow_out->mutable_data<float16>(ctx.GetPlace());

  Tensor xpu_beta_pow_out;
  const phi::DenseTensorMeta meta_beta_pow_out(
      paddle::experimental::DataType::FLOAT32, beta_pow_out->dims());
  xpu_beta_pow_out.set_meta(meta_beta_pow_out);

  T* beta_pow_out_ptr =
      xpu_beta_pow_out.template mutable_data<T>(ctx.GetPlace());

  auto& dev_ctx = ctx.template device_context<DeviceContext>();
  int r = xpu::scale(dev_ctx.x_context(),
                     beta_pow_ptr,
                     beta_pow_out_ptr,
                     beta_pow.numel(),
                     false,
                     beta,
                     0.0f);
  PADDLE_ENFORCE_EQ(r,
                    xpu::SUCCESS,
                    platform::errors::External(
                        "XPU kernel scale occur error in adam error code ",
                        r,
                        XPUAPIErrorMsg[r]));

  const float* xpu_beta_pow_out_data = xpu_beta_pow_out.template data<T>();
  int len = xpu_beta_pow_out.numel();

  r = ConvertDataByType<T, float16>(
      xpu_beta_pow_out_data, &beta_pow_out_p2, len, false, ctx);
  PADDLE_ENFORCE_EQ(
      r,
      xpu::Error_t::SUCCESS,
      platform::errors::External(
          "execute function ConvertDataByType failed with [%d]", r));
}

template <typename T>
static void freeData(const phi::DenseTensor& tensorData, T* dataPtr) {
  if (tensorData.dtype() == paddle::experimental::DataType::FLOAT16)
    xpu_free(dataPtr);
}

Y
yinhaofeng 已提交
184 185 186 187 188
template <typename DeviceContext, typename T>
class AdamOpXPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const auto* param_var = ctx.InputVar("Param");
189 190
    PADDLE_ENFORCE_EQ(param_var->IsType<framework::LoDTensor>(),
                      true,
Y
yinhaofeng 已提交
191 192 193 194 195 196 197 198
                      platform::errors::InvalidArgument(
                          "Tensor holds the wrong type,Expected Var(%s)'s "
                          "type is LoDTensor, "
                          "but the received is %s",
                          ctx.InputNames("Param").front(),
                          framework::ToTypeName(param_var->Type())));
    using paddle::framework::LoDTensor;

199 200
    auto& param = GET_DATA_SAFELY(
        ctx.Input<LoDTensor>("Param"), "Input", "Param", "Adam");
201 202 203 204

    float* param_ptr = nullptr;
    getDataPointer<float>(param, &param_ptr, ctx);

Y
yinhaofeng 已提交
205
    auto* grad_var = ctx.InputVar("Grad");
206 207
    float* grad_c = nullptr;

208 209
    auto& mom1 = GET_DATA_SAFELY(
        ctx.Input<LoDTensor>("Moment1"), "Input", "Moment1", "Adam");
210 211 212
    float* mom1_ptr = nullptr;
    getDataPointer<float>(mom1, &mom1_ptr, ctx);

213 214
    auto& mom2 = GET_DATA_SAFELY(
        ctx.Input<LoDTensor>("Moment2"), "Input", "Moment2", "Adam");
215 216 217
    float* mom2_ptr = nullptr;
    getDataPointer<float>(mom2, &mom2_ptr, ctx);

218 219
    auto& lr = GET_DATA_SAFELY(
        ctx.Input<LoDTensor>("LearningRate"), "Input", "LearningRate", "Adam");
220 221 222
    float* lr_ptr = nullptr;
    getDataPointer<float>(lr, &lr_ptr, ctx);

223 224
    auto& beta1_pow = GET_DATA_SAFELY(
        ctx.Input<LoDTensor>("Beta1Pow"), "Input", "Beta1Pow", "Adam");
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    float* beta1_pow_ptr = nullptr;
    const float* beta1_const_pow_ptr = nullptr;
    if (beta1_pow.place() == platform::CPUPlace()) {
      Tensor xpu_beta1_pow;
      paddle::framework::TensorCopy(
          beta1_pow, ctx.GetPlace(), dev_ctx, &xpu_beta1_pow);
      if (xpu_beta1_pow.dtype() == paddle::experimental::DataType::FLOAT16)
        getDataPointer<float>(xpu_beta1_pow, &beta1_pow_ptr, ctx);
      else
        beta1_const_pow_ptr = xpu_beta1_pow.template data<float>();
    } else {
      if (beta1_pow.dtype() == paddle::experimental::DataType::FLOAT16)
        getDataPointer<float>(beta1_pow, &beta1_pow_ptr, ctx);
      else
        beta1_const_pow_ptr = beta1_pow.template data<float>();
    }

243 244
    auto& beta2_pow = GET_DATA_SAFELY(
        ctx.Input<LoDTensor>("Beta2Pow"), "Input", "Beta2Pow", "Adam");
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    float* beta2_pow_ptr = nullptr;
    const float* beta2_const_pow_ptr = nullptr;
    if (beta2_pow.place() == platform::CPUPlace()) {
      Tensor xpu_beta2_pow;
      paddle::framework::TensorCopy(
          beta2_pow, ctx.GetPlace(), dev_ctx, &xpu_beta2_pow);
      if (xpu_beta2_pow.dtype() == paddle::experimental::DataType::FLOAT16)
        getDataPointer<float>(xpu_beta2_pow, &beta2_pow_ptr, ctx);
      else
        beta2_const_pow_ptr = xpu_beta2_pow.template data<float>();
    } else {
      if (beta2_pow.dtype() == paddle::experimental::DataType::FLOAT16)
        getDataPointer<float>(beta2_pow, &beta2_pow_ptr, ctx);
      else
        beta2_const_pow_ptr = beta2_pow.template data<float>();
    }
Y
yinhaofeng 已提交
261

262 263
    auto& param_out = GET_DATA_SAFELY(
        ctx.Output<LoDTensor>("ParamOut"), "Output", "ParamOut", "Adam");
264 265 266 267 268 269 270
    Tensor xpu_param_out;
    float* param_out_ptr = nullptr;
    const phi::DenseTensorMeta meta_param(
        paddle::experimental::DataType::FLOAT32, param_out.dims());
    xpu_param_out.set_meta(meta_param);
    getOutDataPointer(&param_out, &xpu_param_out, &param_out_ptr, ctx);

271 272
    auto& mom1_out = GET_DATA_SAFELY(
        ctx.Output<LoDTensor>("Moment1Out"), "Output", "Moment1Out", "Adam");
273 274 275 276 277 278 279
    Tensor xpu_mom1_out;
    float* mom1_out_ptr = nullptr;
    const phi::DenseTensorMeta meta_mom1(
        paddle::experimental::DataType::FLOAT32, mom1_out.dims());
    xpu_mom1_out.set_meta(meta_mom1);
    getOutDataPointer(&mom1_out, &xpu_mom1_out, &mom1_out_ptr, ctx);

280 281
    auto& mom2_out = GET_DATA_SAFELY(
        ctx.Output<LoDTensor>("Moment2Out"), "Output", "Moment2Out", "Adam");
282 283 284 285 286 287
    Tensor xpu_mom2_out;
    float* mom2_out_ptr = nullptr;
    const phi::DenseTensorMeta meta_mom2(
        paddle::experimental::DataType::FLOAT32, mom2_out.dims());
    xpu_mom2_out.set_meta(meta_mom2);
    getOutDataPointer(&mom2_out, &xpu_mom2_out, &mom2_out_ptr, ctx);
Y
yinhaofeng 已提交
288 289 290

    auto* beta1_pow_out = ctx.Output<LoDTensor>("Beta1PowOut");
    auto* beta2_pow_out = ctx.Output<LoDTensor>("Beta2PowOut");
291 292 293 294

    bool skip_update = false;
    if (ctx.HasInput("SkipUpdate")) {
      auto* skip_update_tensor = ctx.Input<framework::Tensor>("SkipUpdate");
295 296
      PADDLE_ENFORCE_EQ(skip_update_tensor->numel(),
                        1,
297 298 299 300
                        platform::errors::InvalidArgument(
                            "Input(SkipUpdate) size must be 1, but get %d",
                            skip_update_tensor->numel()));
      std::vector<bool> skip_update_vec;
301 302
      paddle::framework::TensorToVector(
          *skip_update_tensor, ctx.device_context(), &skip_update_vec);
303 304 305 306 307 308 309
      skip_update = skip_update_vec[0];
    }
    // skip_update=true, just copy input to output, and TensorCopy will call
    // mutable_data
    if (skip_update) {
      VLOG(4) << "Adam skip update";
      framework::TensorCopy(
310 311 312 313
          param,
          ctx.GetPlace(),
          ctx.template device_context<platform::DeviceContext>(),
          &param_out);
314
      framework::TensorCopy(
315 316 317 318
          mom1,
          ctx.GetPlace(),
          ctx.template device_context<platform::DeviceContext>(),
          &mom1_out);
319
      framework::TensorCopy(
320 321 322 323
          mom2,
          ctx.GetPlace(),
          ctx.template device_context<platform::DeviceContext>(),
          &mom2_out);
324
      framework::TensorCopy(
325 326
          beta1_pow,
          beta1_pow.place(),
327 328 329
          ctx.template device_context<platform::DeviceContext>(),
          beta1_pow_out);
      framework::TensorCopy(
330 331
          beta2_pow,
          beta2_pow.place(),
332 333 334 335 336
          ctx.template device_context<platform::DeviceContext>(),
          beta2_pow_out);
      return;
    }

337 338
    PADDLE_ENFORCE_EQ(beta1_pow_out->numel(),
                      1,
Y
yinhaofeng 已提交
339 340 341 342 343 344
                      platform::errors::InvalidArgument(
                          "Tensor holds the wrong size, Expected beta1 pow "
                          "output size is 1, but received "
                          "value is:%d.",
                          beta1_pow_out->numel()));

345 346
    PADDLE_ENFORCE_EQ(beta2_pow_out->numel(),
                      1,
Y
yinhaofeng 已提交
347 348 349 350 351
                      platform::errors::InvalidArgument(
                          "Tensor holds the wrong size, Expected beta2 pow "
                          "output size is 1, but received "
                          "value is:%d.",
                          beta2_pow_out->numel()));
352

353 354 355
    bool use_global_beta_pow = ctx.Attr<bool>("use_global_beta_pow");
    VLOG(4) << "use_global_beta_pow:" << use_global_beta_pow;

356
    float beta1 = static_cast<float>(ctx.Attr<float>("beta1"));
Y
yinhaofeng 已提交
357 358
    if (ctx.HasInput("Beta1Tensor")) {
      auto* beta1_tensor = ctx.Input<framework::Tensor>("Beta1Tensor");
359
      beta1 = static_cast<float>(GetAttrFromTensor(beta1_tensor));
Y
yinhaofeng 已提交
360
    }
361
    float beta2 = static_cast<float>(ctx.Attr<float>("beta2"));
Y
yinhaofeng 已提交
362 363
    if (ctx.HasInput("Beta2Tensor")) {
      auto* beta2_tensor = ctx.Input<framework::Tensor>("Beta2Tensor");
364
      beta2 = static_cast<float>(GetAttrFromTensor(beta2_tensor));
Y
yinhaofeng 已提交
365
    }
366
    float epsilon = static_cast<float>(ctx.Attr<float>("epsilon"));
367 368
    if (ctx.HasInput("EpsilonTensor")) {
      auto* epsilon_tensor = ctx.Input<framework::Tensor>("EpsilonTensor");
369
      epsilon = static_cast<float>(GetAttrFromTensor(epsilon_tensor));
370
    }
371

Y
yinhaofeng 已提交
372
    if (grad_var->IsType<framework::LoDTensor>()) {
373 374
      auto& grad = GET_DATA_SAFELY(
          ctx.Input<LoDTensor>("Grad"), "Input", "Grad", "Adam");
375
      getDataPointer<float>(grad, &grad_c, ctx);
376

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
      int r = xpu::adam(
          dev_ctx.x_context(),
          grad_c != nullptr ? grad_c : grad.template data<float>(),
          mom1_ptr != nullptr ? mom1_ptr : mom1.template data<float>(),
          mom2_ptr != nullptr ? mom2_ptr : mom2.template data<float>(),
          param_ptr != nullptr ? param_ptr : param.template data<float>(),
          beta1_pow_ptr != nullptr ? beta1_pow_ptr : beta1_const_pow_ptr,
          beta2_pow_ptr != nullptr ? beta2_pow_ptr : beta2_const_pow_ptr,
          lr_ptr != nullptr ? lr_ptr : lr.template data<float>(),
          mom1_out_ptr,
          mom2_out_ptr,
          param_out_ptr,
          beta1,
          beta2,
          epsilon,
          param.numel());
393 394 395

      xpu_wait(dev_ctx.x_context()->xpu_stream);
      PADDLE_ENFORCE_EQ(
396 397
          r == xpu::Error_t::SUCCESS,
          true,
398
          platform::errors::External("XPU API return wrong value[%d],", r));
399 400 401 402 403 404 405

      freeData<float>(grad, grad_c);

      copyOutData<float>(xpu_mom1_out, &mom1_out, ctx);
      copyOutData<float>(xpu_mom2_out, &mom2_out, ctx);
      copyOutData<float>(xpu_param_out, &param_out, ctx);

406 407 408 409
      if (!use_global_beta_pow) {
        // update in cpu and then copy to xpu
        if (beta1_pow.place() == platform::CPUPlace() &&
            beta2_pow.place() == platform::CPUPlace()) {
410 411 412
          setBetaData(beta1_pow, beta1_pow_out, beta1);

          setBetaData(beta2_pow, beta2_pow_out, beta2);
413
        } else {
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
          float* beta1_pow_out_p1 = nullptr;

          if (beta1_pow_out->dtype() ==
              paddle::experimental::DataType::FLOAT16) {
            scale<DeviceContext, float>(
                beta1_pow_out, beta1_pow, beta1_pow_ptr, beta1, ctx);
          } else {
            const float* beta1_pow_data = beta1_pow.template data<float>();
            beta1_pow_out_p1 =
                beta1_pow_out->mutable_data<float>(ctx.GetPlace());
            r = xpu::scale(dev_ctx.x_context(),
                           beta1_pow_data,
                           beta1_pow_out_p1,
                           beta1_pow.numel(),
                           false,
                           beta1,
                           0.0f);
            xpu_wait(dev_ctx.x_context()->xpu_stream);
            PADDLE_ENFORCE_EQ(
                r,
                xpu::SUCCESS,
                platform::errors::External(
                    "XPU kernel scale occur error in adam error code ",
                    r,
                    XPUAPIErrorMsg[r]));
          }

          float* beta2_pow_out_p1 = nullptr;
          if (beta2_pow_out->dtype() ==
              paddle::experimental::DataType::FLOAT16) {
            scale<DeviceContext, float>(
                beta2_pow_out, beta2_pow, beta2_pow_ptr, beta2, ctx);
          } else {
            const float* beta2_pow_data = beta2_pow.template data<float>();
            beta2_pow_out_p1 =
                beta2_pow_out->mutable_data<float>(ctx.GetPlace());
            r = xpu::scale(dev_ctx.x_context(),
                           beta2_pow_data,
                           beta2_pow_out_p1,
                           beta2_pow.numel(),
                           false,
                           beta2,
                           0.0f);
            xpu_wait(dev_ctx.x_context()->xpu_stream);
            PADDLE_ENFORCE_EQ(
                r,
                xpu::SUCCESS,
                platform::errors::External(
                    "XPU kernel scale occur error in adam error code ",
                    r,
                    XPUAPIErrorMsg[r]));
          }
466 467
        }
      }
468 469
    } else if (grad_var->IsType<phi::SelectedRows>()) {
      auto* grad = ctx.Input<phi::SelectedRows>("Grad");
470 471 472 473 474 475 476 477 478 479 480 481

      if (grad->rows().size() == 0) {
        VLOG(3) << "grad row size is 0!!";
        return;
      }

      std::vector<int64_t> cpu_rows(grad->rows().begin(), grad->rows().end());
      bool is_strict_sorted = true;
      for (size_t i = 1; i < cpu_rows.size(); ++i) {
        if (cpu_rows[i - 1] >= cpu_rows[i]) {
          is_strict_sorted = false;
          break;
482
        }
483 484
      }

485 486
      phi::SelectedRows tmp_grad_merge;
      const phi::SelectedRows* grad_merge_ptr;
487 488 489
      if (is_strict_sorted) {
        grad_merge_ptr = grad;
      } else {
490
        scatter::MergeAdd<platform::XPUDeviceContext, float> merge_func;
491
        merge_func(ctx.template device_context<platform::XPUDeviceContext>(),
492 493 494
                   *grad,
                   &tmp_grad_merge,
                   true);
495 496 497 498

        xpu_wait(dev_ctx.x_context()->xpu_stream);
        grad_merge_ptr = &tmp_grad_merge;
      }
499

500 501
      auto& grad_merge = *grad_merge_ptr;
      auto& grad_tensor = grad_merge.value();
502 503 504

      getDataPointer<float>(grad_tensor, &grad_c, ctx);

505 506 507 508 509 510 511 512 513 514
      int row_count = grad_merge.rows().size();
      std::vector<int> rows(row_count);
      xpu::ctx_guard RAII_GUARD(dev_ctx.x_context());
      int* xpu_rows = RAII_GUARD.alloc_l3_or_gm<int>(row_count);
      std::vector<int64_t> merge_rows(grad_merge.rows().begin(),
                                      grad_merge.rows().end());
      for (size_t i = 0; i < grad_merge.rows().size(); ++i) {
        rows[i] = static_cast<int>(merge_rows[i]);
      }
      xpu_wait(dev_ctx.x_context()->xpu_stream);
515 516 517 518
      memory::Copy(ctx.GetPlace(),
                   xpu_rows,
                   platform::CPUPlace(),
                   rows.data(),
519 520 521
                   row_count * sizeof(int));
      auto row_numel = grad_tensor.numel() / grad_merge.rows().size();
      auto ori_rows = param.numel() / row_numel;
522

523
      int lazy_mode = static_cast<int>(ctx.Attr<bool>("lazy_mode"));
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
      int r = xpu::sparse_adam(
          dev_ctx.x_context(),
          grad_c != nullptr ? grad_c : grad_tensor.template data<float>(),
          mom1_ptr != nullptr ? mom1_ptr : mom1.template data<float>(),
          mom2_ptr != nullptr ? mom2_ptr : mom2.template data<float>(),
          param_ptr != nullptr ? param_ptr : param.template data<float>(),
          beta1_pow_ptr != nullptr ? beta1_pow_ptr : beta1_const_pow_ptr,
          beta2_pow_ptr != nullptr ? beta2_pow_ptr : beta2_const_pow_ptr,
          lr_ptr != nullptr ? lr_ptr : lr.template data<float>(),
          mom1_out_ptr,
          mom2_out_ptr,
          param_out_ptr,
          beta1,
          beta2,
          epsilon,
          ori_rows,
          xpu_rows,
          row_numel,
          grad_merge.rows().size(),
          lazy_mode);
544 545

      PADDLE_ENFORCE_EQ(
546 547
          r == xpu::Error_t::SUCCESS,
          true,
548 549
          platform::errors::External("XPU API return wrong value[%d],", r));

550 551 552 553 554 555
      freeData<float>(grad_tensor, grad_c);

      copyOutData<float>(xpu_mom1_out, &mom1_out, ctx);
      copyOutData<float>(xpu_mom2_out, &mom2_out, ctx);
      copyOutData<float>(xpu_param_out, &param_out, ctx);

556 557 558 559
      if (!use_global_beta_pow) {
        // update in cpu and then copy to xpu
        if (beta1_pow.place() == platform::CPUPlace() &&
            beta2_pow.place() == platform::CPUPlace()) {
560 561 562
          setBetaData(beta1_pow, beta1_pow_out, beta1);

          setBetaData(beta2_pow, beta2_pow_out, beta2);
563
        } else {
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
          float* beta1_pow_out_p1 = nullptr;

          if (beta1_pow_out->dtype() ==
              paddle::experimental::DataType::FLOAT16) {
            scale<DeviceContext, float>(
                beta1_pow_out, beta1_pow, beta1_pow_ptr, beta1, ctx);
          } else {
            const float* beta1_pow_data = beta1_pow.template data<float>();
            beta1_pow_out_p1 =
                beta1_pow_out->mutable_data<float>(ctx.GetPlace());
            r = xpu::scale(dev_ctx.x_context(),
                           beta1_pow_data,
                           beta1_pow_out_p1,
                           beta1_pow.numel(),
                           false,
                           beta1,
                           0.0f);
            xpu_wait(dev_ctx.x_context()->xpu_stream);
            PADDLE_ENFORCE_EQ(
                r,
                xpu::SUCCESS,
                platform::errors::External(
                    "XPU kernel scale occur error in adam error code ",
                    r,
                    XPUAPIErrorMsg[r]));
          }

          float* beta2_pow_out_p1 = nullptr;
          if (beta2_pow_out->dtype() ==
              paddle::experimental::DataType::FLOAT16) {
            scale<DeviceContext, float>(
                beta2_pow_out, beta2_pow, beta2_pow_ptr, beta2, ctx);
          } else {
            const float* beta2_pow_data = beta2_pow.template data<float>();
            beta2_pow_out_p1 =
                beta2_pow_out->mutable_data<float>(ctx.GetPlace());
            r = xpu::scale(dev_ctx.x_context(),
                           beta2_pow_data,
                           beta2_pow_out_p1,
                           beta2_pow.numel(),
                           false,
                           beta2,
                           0.0f);
            xpu_wait(dev_ctx.x_context()->xpu_stream);
            PADDLE_ENFORCE_EQ(
                r,
                xpu::SUCCESS,
                platform::errors::External(
                    "XPU kernel scale occur error in adam error code ",
                    r,
                    XPUAPIErrorMsg[r]));
          }
616
        }
617
      }
Y
yinhaofeng 已提交
618
    } else {
619 620
      PADDLE_ENFORCE_EQ(1,
                        2,
621 622
                        platform::errors::InvalidArgument(
                            "Variable type not supported by adam_op"));
Y
yinhaofeng 已提交
623
    }
624 625 626 627 628

    freeData<float>(param, param_ptr);
    freeData<float>(mom1, mom1_ptr);
    freeData<float>(mom2, mom2_ptr);
    freeData<float>(lr, lr_ptr);
Y
yinhaofeng 已提交
629 630 631 632 633 634 635 636 637 638
  }
};
#endif

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
#ifdef PADDLE_WITH_XPU
REGISTER_OP_XPU_KERNEL(
639 640 641 642
    adam,
    ops::AdamOpXPUKernel<paddle::platform::XPUDeviceContext, float>,
    ops::AdamOpXPUKernel<paddle::platform::XPUDeviceContext,
                         paddle::platform::float16>);
Y
yinhaofeng 已提交
643
#endif