adam_op_xpu.cc 14.5 KB
Newer Older
Y
yinhaofeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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.
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/operators/optimizers/adam_op.h"
16
#include "gflags/gflags.h"
17
#include "paddle/fluid/operators/math/selected_rows_functor.h"
Y
yinhaofeng 已提交
18 19 20 21 22 23 24 25 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

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

#ifdef PADDLE_WITH_XPU
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");
    PADDLE_ENFORCE_EQ(param_var->IsType<framework::LoDTensor>(), true,
                      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;

    auto& param = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Param"), "Input",
                                  "Param", "Adam");
    // auto& grad = Ref(ctx.Input<LoDTensor>("Grad"), "Must set Grad");
    auto* grad_var = ctx.InputVar("Grad");
    auto& mom1 = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Moment1"), "Input",
                                 "Moment1", "Adam");
    auto& mom2 = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Moment2"), "Input",
                                 "Moment2", "Adam");
    auto& lr = GET_DATA_SAFELY(ctx.Input<LoDTensor>("LearningRate"), "Input",
                               "LearningRate", "Adam");
    auto& beta1_pow = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Beta1Pow"), "Input",
                                      "Beta1Pow", "Adam");
    auto& beta2_pow = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Beta2Pow"), "Input",
                                      "Beta2Pow", "Adam");

    auto& param_out = GET_DATA_SAFELY(ctx.Output<LoDTensor>("ParamOut"),
                                      "Output", "ParamOut", "Adam");
    auto& mom1_out = GET_DATA_SAFELY(ctx.Output<LoDTensor>("Moment1Out"),
                                     "Output", "Moment1Out", "Adam");
    auto& mom2_out = GET_DATA_SAFELY(ctx.Output<LoDTensor>("Moment2Out"),
                                     "Output", "Moment2Out", "Adam");

    auto* beta1_pow_out = ctx.Output<LoDTensor>("Beta1PowOut");
    auto* beta2_pow_out = ctx.Output<LoDTensor>("Beta2PowOut");
63 64 65 66 67 68 69 70 71

    bool skip_update = false;
    if (ctx.HasInput("SkipUpdate")) {
      auto* skip_update_tensor = ctx.Input<framework::Tensor>("SkipUpdate");
      PADDLE_ENFORCE_EQ(skip_update_tensor->numel(), 1,
                        platform::errors::InvalidArgument(
                            "Input(SkipUpdate) size must be 1, but get %d",
                            skip_update_tensor->numel()));
      std::vector<bool> skip_update_vec;
72 73
      paddle::framework::TensorToVector(*skip_update_tensor,
                                        ctx.device_context(), &skip_update_vec);
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
      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(
          param, ctx.GetPlace(),
          ctx.template device_context<platform::DeviceContext>(), &param_out);
      framework::TensorCopy(
          mom1, ctx.GetPlace(),
          ctx.template device_context<platform::DeviceContext>(), &mom1_out);
      framework::TensorCopy(
          mom2, ctx.GetPlace(),
          ctx.template device_context<platform::DeviceContext>(), &mom2_out);
      framework::TensorCopy(
90
          beta1_pow, beta1_pow.place(),
91 92 93
          ctx.template device_context<platform::DeviceContext>(),
          beta1_pow_out);
      framework::TensorCopy(
94
          beta2_pow, beta2_pow.place(),
95 96 97 98 99
          ctx.template device_context<platform::DeviceContext>(),
          beta2_pow_out);
      return;
    }

Y
yinhaofeng 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112
    PADDLE_ENFORCE_EQ(beta1_pow_out->numel(), 1,
                      platform::errors::InvalidArgument(
                          "Tensor holds the wrong size, Expected beta1 pow "
                          "output size is 1, but received "
                          "value is:%d.",
                          beta1_pow_out->numel()));

    PADDLE_ENFORCE_EQ(beta2_pow_out->numel(), 1,
                      platform::errors::InvalidArgument(
                          "Tensor holds the wrong size, Expected beta2 pow "
                          "output size is 1, but received "
                          "value is:%d.",
                          beta2_pow_out->numel()));
113

114 115 116
    bool use_global_beta_pow = ctx.Attr<bool>("use_global_beta_pow");
    VLOG(4) << "use_global_beta_pow:" << use_global_beta_pow;

117
    float beta1 = static_cast<float>(ctx.Attr<float>("beta1"));
Y
yinhaofeng 已提交
118 119
    if (ctx.HasInput("Beta1Tensor")) {
      auto* beta1_tensor = ctx.Input<framework::Tensor>("Beta1Tensor");
120
      beta1 = static_cast<float>(GetAttrFromTensor(beta1_tensor));
Y
yinhaofeng 已提交
121
    }
122
    float beta2 = static_cast<float>(ctx.Attr<float>("beta2"));
Y
yinhaofeng 已提交
123 124
    if (ctx.HasInput("Beta2Tensor")) {
      auto* beta2_tensor = ctx.Input<framework::Tensor>("Beta2Tensor");
125
      beta2 = static_cast<float>(GetAttrFromTensor(beta2_tensor));
Y
yinhaofeng 已提交
126
    }
127
    float epsilon = static_cast<T>(ctx.Attr<float>("epsilon"));
128 129
    if (ctx.HasInput("EpsilonTensor")) {
      auto* epsilon_tensor = ctx.Input<framework::Tensor>("EpsilonTensor");
130
      epsilon = static_cast<float>(GetAttrFromTensor(epsilon_tensor));
131
    }
Y
yinhaofeng 已提交
132 133 134 135
    if (grad_var->IsType<framework::LoDTensor>()) {
      auto& grad = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Grad"), "Input",
                                   "Grad", "Adam");
      auto& dev_ctx = ctx.template device_context<DeviceContext>();
136 137
      const float* beta1_pow_ptr = beta1_pow.template data<float>();
      const float* beta2_pow_ptr = beta2_pow.template data<float>();
138 139 140 141
      Tensor xpu_beta1_pow;
      Tensor xpu_beta2_pow;
      if (beta1_pow.place() == platform::CPUPlace() &&
          beta2_pow.place() == platform::CPUPlace()) {
142 143 144 145
        paddle::framework::TensorCopy(beta1_pow, ctx.GetPlace(), dev_ctx,
                                      &xpu_beta1_pow);
        paddle::framework::TensorCopy(beta2_pow, ctx.GetPlace(), dev_ctx,
                                      &xpu_beta2_pow);
146
        dev_ctx.Wait();
147 148
        beta1_pow_ptr = xpu_beta1_pow.template data<float>();
        beta2_pow_ptr = xpu_beta2_pow.template data<float>();
149
      }
150 151 152 153 154 155 156 157 158

      int r = xpu::adam(dev_ctx.x_context(), grad.template data<T>(),
                        mom1.template data<T>(), mom2.template data<T>(),
                        param.template data<float>(), beta1_pow_ptr,
                        beta2_pow_ptr, lr.template data<float>(),
                        mom1_out.template mutable_data<float>(ctx.GetPlace()),
                        mom2_out.template mutable_data<float>(ctx.GetPlace()),
                        param_out.template mutable_data<float>(ctx.GetPlace()),
                        beta1, beta2, epsilon, param.numel());
159 160 161 162 163

      xpu_wait(dev_ctx.x_context()->xpu_stream);
      PADDLE_ENFORCE_EQ(
          r == xpu::Error_t::SUCCESS, true,
          platform::errors::External("XPU API return wrong value[%d],", r));
164 165 166 167
      if (!use_global_beta_pow) {
        // update in cpu and then copy to xpu
        if (beta1_pow.place() == platform::CPUPlace() &&
            beta2_pow.place() == platform::CPUPlace()) {
168 169
          const float* beta1_pow_p = beta1_pow.template data<float>();
          beta1_pow_out->mutable_data<float>(platform::CPUPlace())[0] =
170
              beta1 * beta1_pow_p[0];
171 172
          const float* beta2_pow_p = beta2_pow.template data<float>();
          beta2_pow_out->mutable_data<float>(platform::CPUPlace())[0] =
173 174
              beta2 * beta2_pow_p[0];
        } else {
175 176 177 178 179 180 181 182 183 184
          float* beta1_pow_out_p =
              beta1_pow_out->mutable_data<float>(ctx.GetPlace());
          float* beta2_pow_out_p =
              beta2_pow_out->mutable_data<float>(ctx.GetPlace());
          int r =
              xpu::scale(dev_ctx.x_context(), beta1_pow_ptr, beta1_pow_out_p,
                         beta1_pow.numel(), false, beta1, 0.0f);
          PADDLE_ENFORCE_EQ(
              r, xpu::SUCCESS,
              platform::errors::External(
185
                  "XPU kernel scale occur error in adam error code ", r,
186 187 188 189 190 191
                  XPUAPIErrorMsg[r]));
          r = xpu::scale(dev_ctx.x_context(), beta2_pow_ptr, beta2_pow_out_p,
                         beta2_pow.numel(), false, beta2, 0.0f);
          PADDLE_ENFORCE_EQ(
              r, xpu::SUCCESS,
              platform::errors::External(
192
                  "XPU kernel scale occur error in adam error code ", r,
193
                  XPUAPIErrorMsg[r]));
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

          xpu_wait(dev_ctx.x_context()->xpu_stream);
        }
      }
    } else if (grad_var->IsType<framework::SelectedRows>()) {
      auto* grad = ctx.Input<framework::SelectedRows>("Grad");
      auto& dev_ctx = ctx.template device_context<DeviceContext>();

      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;
213
        }
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
      }

      framework::SelectedRows tmp_grad_merge;
      const framework::SelectedRows* grad_merge_ptr;
      if (is_strict_sorted) {
        grad_merge_ptr = grad;
      } else {
        scatter::MergeAdd<platform::XPUDeviceContext, T> merge_func;
        merge_func(ctx.template device_context<platform::XPUDeviceContext>(),
                   *grad, &tmp_grad_merge, true);

        xpu_wait(dev_ctx.x_context()->xpu_stream);
        grad_merge_ptr = &tmp_grad_merge;
      }
      const T* beta1_pow_ptr = beta1_pow.template data<T>();
      const T* beta2_pow_ptr = beta2_pow.template data<T>();
      Tensor xpu_beta1_pow;
      Tensor xpu_beta2_pow;
      if (beta1_pow.place() == platform::CPUPlace() &&
          beta2_pow.place() == platform::CPUPlace()) {
        paddle::framework::TensorCopy(beta1_pow, ctx.GetPlace(), dev_ctx,
                                      &xpu_beta1_pow);
        paddle::framework::TensorCopy(beta2_pow, ctx.GetPlace(), dev_ctx,
                                      &xpu_beta2_pow);
        dev_ctx.Wait();
        beta1_pow_ptr = xpu_beta1_pow.template data<T>();
        beta2_pow_ptr = xpu_beta2_pow.template data<T>();
      }
      auto& grad_merge = *grad_merge_ptr;
      auto& grad_tensor = grad_merge.value();
      const T* grad_data = grad_tensor.template data<T>();
      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);
      memory::Copy(ctx.GetPlace(), xpu_rows, platform::CPUPlace(), rows.data(),
                   row_count * sizeof(int));
      auto row_numel = grad_tensor.numel() / grad_merge.rows().size();
      auto ori_rows = param.numel() / row_numel;
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
      int lazy_mode = static_cast<int>(ctx.Attr<bool>("lazy_mode"));
      int r = xpu::sparse_adam(
          dev_ctx.x_context(), grad_data, mom1.template data<T>(),
          mom2.template data<T>(), param.template data<T>(), beta1_pow_ptr,
          beta2_pow_ptr, lr.template data<T>(),
          mom1_out.template mutable_data<T>(ctx.GetPlace()),
          mom2_out.template mutable_data<T>(ctx.GetPlace()),
          param_out.template mutable_data<T>(ctx.GetPlace()), beta1, beta2,
          epsilon, ori_rows, xpu_rows, row_numel, grad_merge.rows().size(),
          lazy_mode);

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

      if (!use_global_beta_pow) {
        // update in cpu and then copy to xpu
        if (beta1_pow.place() == platform::CPUPlace() &&
            beta2_pow.place() == platform::CPUPlace()) {
          const float* beta1_pow_p = beta1_pow.template data<float>();
          beta1_pow_out->mutable_data<float>(platform::CPUPlace())[0] =
              beta1 * beta1_pow_p[0];
          const float* beta2_pow_p = beta2_pow.template data<float>();
          beta2_pow_out->mutable_data<float>(platform::CPUPlace())[0] =
              beta2 * beta2_pow_p[0];
        } else {
          float* beta1_pow_out_p =
              beta1_pow_out->mutable_data<float>(ctx.GetPlace());
          float* beta2_pow_out_p =
              beta2_pow_out->mutable_data<float>(ctx.GetPlace());
          int r =
              xpu::scale(dev_ctx.x_context(), beta1_pow_ptr, beta1_pow_out_p,
                         beta1_pow.numel(), false, beta1, 0.0f);
          PADDLE_ENFORCE_EQ(
              r, xpu::SUCCESS,
              platform::errors::External(
                  "XPU kernel scale occur error in adam error code ", r,
                  XPUAPIErrorMsg[r]));
          r = xpu::scale(dev_ctx.x_context(), beta2_pow_ptr, beta2_pow_out_p,
                         beta2_pow.numel(), false, beta2, 0.0f);
          PADDLE_ENFORCE_EQ(
              r, xpu::SUCCESS,
              platform::errors::External(
                  "XPU kernel scale occur error in adam error code ", r,
                  XPUAPIErrorMsg[r]));
        }
306
      }
307
      xpu_wait(dev_ctx.x_context()->xpu_stream);
Y
yinhaofeng 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    } else {
      PADDLE_ENFORCE_EQ(1, 2, platform::errors::InvalidArgument(
                                  "Variable type not supported by adam_op"));
    }
  }
};
#endif

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
#ifdef PADDLE_WITH_XPU
REGISTER_OP_XPU_KERNEL(
    adam, ops::AdamOpXPUKernel<paddle::platform::XPUDeviceContext, float>);
#endif