activation_op_xpu.cc 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2020 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. */

#ifdef PADDLE_WITH_XPU

#include "paddle/fluid/operators/activation_op.h"
#include <string>
19
#include "paddle/fluid/platform/device/xpu/xpu_header.h"
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

namespace paddle {
namespace operators {

using paddle::framework::Tensor;

template <typename Functor>
class XPUActivationKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    Functor functor;

    auto attrs = functor.GetAttrs();
    for (auto &attr : attrs) {
      *attr.second = context.Attr<float>(attr.first);
    }
    functor(context);
  }
};

template <typename Functor>
class XPUActivationGradKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    Functor functor;

    auto attrs = functor.GetAttrs();
    for (auto &attr : attrs) {
      *attr.second = context.Attr<float>(attr.first);
    }
    functor(context);
  }
};

56
template <typename DeviceContext, typename T, typename XPUT>
T
TTerror 已提交
57 58
void xpu_activation_forward(
    const framework::ExecutionContext &ctx,
59
    std::function<int(xpu::Context *, const XPUT *, XPUT *, int)> func) {
60 61
  const auto *x = ctx.Input<Tensor>("X");
  auto *y = ctx.Output<Tensor>("Out");
62 63
  const XPUT *x_data = reinterpret_cast<const XPUT *>(x->data<T>());
  XPUT *y_data = reinterpret_cast<XPUT *>(y->mutable_data<T>(ctx.GetPlace()));
P
procr 已提交
64

T
TTerror 已提交
65 66 67 68 69 70
  auto xpu_context = ctx.device_context<DeviceContext>().x_context();
  int r = func(xpu_context, x_data, y_data, x->numel());
  PADDLE_ENFORCE_EQ(
      r, xpu::Error_t::SUCCESS,
      platform::errors::External("XPU activation op return wrong value[%d %s].",
                                 r, XPUAPIErrorMsg[r]));
71 72
}

73 74 75 76 77 78
template <typename DeviceContext, typename T, typename XPUT>
void xpu_activation_backward(
    const framework::ExecutionContext &ctx,
    std::function<int(xpu::Context *, const XPUT *, const XPUT *, const XPUT *,
                      XPUT *, int)>
        func) {
79 80 81 82 83
  /* TODO: relu tanh sigmoid are inplace */
  const auto *x = ctx.Input<Tensor>("X");
  auto *y = ctx.Input<Tensor>("Out");
  auto *dOut = ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
  auto *dX = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
84 85 86 87 88 89 90
  const XPUT *x_data = nullptr;
  const XPUT *y_data = nullptr;
  const XPUT *y_grad = nullptr;
  if (x != nullptr) x_data = reinterpret_cast<const XPUT *>(x->data<T>());
  if (y != nullptr) y_data = reinterpret_cast<const XPUT *>(y->data<T>());
  if (dOut != nullptr) y_grad = reinterpret_cast<const XPUT *>(dOut->data<T>());
  XPUT *x_grad = reinterpret_cast<XPUT *>(dX->mutable_data<T>(ctx.GetPlace()));
91
  auto xpu_context = ctx.device_context<DeviceContext>().x_context();
P
procr 已提交
92

T
TTerror 已提交
93 94
  int r = func(xpu_context, x_data, y_data, y_grad, x_grad, dX->numel());
  PADDLE_ENFORCE_EQ(r, xpu::Error_t::SUCCESS,
95
                    platform::errors::External(
T
TTerror 已提交
96 97
                        "XPU activation grad op return wrong value[%d %s].", r,
                        XPUAPIErrorMsg[r]));
98 99
}

T
TTerror 已提交
100
template <typename T>
101
struct XPUAbsFunctor : public BaseActivationFunctor<T> {
102
  using XPUType = typename XPUTypeTrait<T>::Type;
103
  void operator()(const framework::ExecutionContext &ctx) const {
104
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
105
        ctx, xpu::abs<XPUType>);
106 107 108
  }
};

T
TTerror 已提交
109
template <typename T>
110
struct XPUAbsGradFunctor : public BaseActivationFunctor<T> {
111
  using XPUType = typename XPUTypeTrait<T>::Type;
112
  void operator()(const framework::ExecutionContext &ctx) const {
113 114
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::abs_grad<XPUType>);
115 116 117 118
  }
};

template <typename T>
119
struct XPUExpFunctor : public BaseActivationFunctor<T> {
120
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
121
  void operator()(const framework::ExecutionContext &ctx) const {
122
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
123
        ctx, xpu::exp<XPUType>);
T
TTerror 已提交
124 125 126
  }
};

127
template <typename T>
T
TTerror 已提交
128
struct XPULogFunctor : public BaseActivationFunctor<T> {
129
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
130
  void operator()(const framework::ExecutionContext &ctx) const {
131 132
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::log<XPUType>);
T
TTerror 已提交
133 134 135
  }
};

136
template <typename T>
137
struct XPUReciprocalFunctor : public BaseActivationFunctor<T> {
138
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
139
  void operator()(const framework::ExecutionContext &ctx) const {
140
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
141
        ctx, xpu::reciprocal<XPUType>);
T
TTerror 已提交
142 143 144
  }
};

145
template <typename T>
146
struct XPUReciprocalGradFunctor : public BaseActivationFunctor<T> {
147
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
148
  void operator()(const framework::ExecutionContext &ctx) const {
149 150
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::reciprocal_grad<XPUType>);
T
TTerror 已提交
151 152 153
  }
};

154
template <typename T>
155
struct XPUReluFunctor : public BaseActivationFunctor<T> {
156
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
157
  void operator()(const framework::ExecutionContext &ctx) const {
158
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
159
        ctx, xpu::relu<XPUType>);
T
TTerror 已提交
160 161 162
  }
};

163
template <typename T>
164 165
struct XPUReluGradFunctor : public BaseActivationFunctor<T> {
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
166
  void operator()(const framework::ExecutionContext &ctx) const {
167 168
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::relu_grad<XPUType>);
T
TTerror 已提交
169 170 171
  }
};

P
procr 已提交
172
template <typename T>
173
struct XPUSigmoidFunctor : public BaseActivationFunctor<T> {
174
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
175
  void operator()(const framework::ExecutionContext &ctx) const {
176
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
177
        ctx, xpu::sigmoid<XPUType>);
T
TTerror 已提交
178 179 180
  }
};

181
template <typename T>
182
struct XPUSigmoidGradFunctor : public BaseActivationFunctor<T> {
183
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
184
  void operator()(const framework::ExecutionContext &ctx) const {
185
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
186
        ctx, xpu::sigmoid_grad<XPUType>);
T
TTerror 已提交
187 188 189
  }
};

190
template <typename T>
191
struct XPUSqrtFunctor : public BaseActivationFunctor<T> {
192
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
193
  void operator()(const framework::ExecutionContext &ctx) const {
194 195
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::sqrt<XPUType>);
T
TTerror 已提交
196 197 198
  }
};

199
template <typename T>
200
struct XPUSqrtGradFunctor : public BaseActivationFunctor<T> {
201
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
202
  void operator()(const framework::ExecutionContext &ctx) const {
203
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
204
        ctx, xpu::sqrt_grad<XPUType>);
T
TTerror 已提交
205 206 207
  }
};

208
template <typename T>
209
struct XPUSquareFunctor : public BaseActivationFunctor<T> {
210
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
211
  void operator()(const framework::ExecutionContext &ctx) const {
212 213
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::square<XPUType>);
T
TTerror 已提交
214 215 216
  }
};

217
template <typename T>
T
TTerror 已提交
218
struct XPUSquareGradFunctor : public BaseActivationFunctor<T> {
219
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
220
  void operator()(const framework::ExecutionContext &ctx) const {
221 222
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::square_grad<XPUType>);
T
TTerror 已提交
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 259 260 261 262 263
template <typename T>
struct XPUTanhFunctor : public BaseActivationFunctor<T> {
  using XPUType = typename XPUTypeTrait<T>::Type;
  void operator()(const framework::ExecutionContext &ctx) const {
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::tanh<XPUType>);
  }
};

template <typename T>
struct XPUTanhGradFunctor : public BaseActivationFunctor<T> {
  using XPUType = typename XPUTypeTrait<T>::Type;
  void operator()(const framework::ExecutionContext &ctx) const {
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::tanh_grad<XPUType>);
  }
};

template <typename T>
struct XPUHardSwishFunctor : public BaseActivationFunctor<T> {
  using XPUType = typename XPUTypeTrait<T>::Type;
  void operator()(const framework::ExecutionContext &ctx) const {
    float threshold = ctx.Attr<float>("threshold");
    float scale = ctx.Attr<float>("scale");
    float offset = ctx.Attr<float>("offset");
    PADDLE_ENFORCE_EQ(threshold, 6.0f,
                      platform::errors::External(
                          "Not support threshold [%f] in XPU", threshold));
    PADDLE_ENFORCE_EQ(scale, 6.0f, platform::errors::External(
                                       "Not support scale [%f] in XPU", scale));
    PADDLE_ENFORCE_EQ(
        offset, 3.0f,
        platform::errors::External("Not support offset [%f] in XPU", offset));
    xpu_activation_forward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::hard_swish<XPUType>);
  }
};

264
template <typename T>
T
TTerror 已提交
265
struct XPUHardSwishGradFunctor : public BaseActivationFunctor<T> {
266
  using XPUType = typename XPUTypeTrait<T>::Type;
T
TTerror 已提交
267 268 269 270 271 272 273 274 275 276 277 278
  void operator()(const framework::ExecutionContext &ctx) const {
    float threshold = ctx.Attr<float>("threshold");
    float scale = ctx.Attr<float>("scale");
    float offset = ctx.Attr<float>("offset");
    PADDLE_ENFORCE_EQ(threshold, 6.0f,
                      platform::errors::External(
                          "Not support threshold [%f] in XPU", threshold));
    PADDLE_ENFORCE_EQ(scale, 6.0f, platform::errors::External(
                                       "Not support scale [%f] in XPU", scale));
    PADDLE_ENFORCE_EQ(
        offset, 3.0f,
        platform::errors::External("Not support offset [%f] in XPU", offset));
279 280
    xpu_activation_backward<paddle::platform::XPUDeviceContext, T, XPUType>(
        ctx, xpu::hard_swish_grad<XPUType>);
T
TTerror 已提交
281 282 283
  }
};

P
procr 已提交
284
template <typename T>
T
TTerror 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
struct XPULeakyReluFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const auto *x = ctx.Input<Tensor>("X");
    auto *y = ctx.Output<Tensor>("Out");
    float alpha = ctx.Attr<float>("alpha");
    const T *x_data = x->data<T>();
    T *y_data = y->mutable_data<T>(ctx.GetPlace());

    auto xpu_context =
        ctx.device_context<paddle::platform::XPUDeviceContext>().x_context();
    int r = xpu::leaky_relu(xpu_context, x_data, y_data, x->numel(), alpha);
    PADDLE_ENFORCE_EQ(
        r, xpu::Error_t::SUCCESS,
        platform::errors::External("XPU leaky_relu return wrong value[%d %s].",
                                   r, XPUAPIErrorMsg[r]));
  }
};

303
template <typename T>
T
TTerror 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
struct XPULeakyReluGradFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const auto *x = ctx.Input<Tensor>("X");
    auto *dOut = ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
    auto *dX = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
    float alpha = ctx.Attr<float>("alpha");
    const T *x_data = nullptr;
    const T *y_grad = nullptr;
    if (x != nullptr) x_data = x->data<T>();
    if (dOut != nullptr) y_grad = dOut->data<T>();
    T *x_grad = dX->mutable_data<T>(ctx.GetPlace());
    auto xpu_context =
        ctx.device_context<paddle::platform::XPUDeviceContext>().x_context();

    // The signs of x and y are the same,
    // y == nullptr here,
    // so we give 2 x to the api
    int r = xpu::leaky_relu_grad(
        xpu_context, reinterpret_cast<const float *>(x_data),
        reinterpret_cast<const float *>(x_data),
        reinterpret_cast<const float *>(y_grad),
        reinterpret_cast<float *>(x_grad), dX->numel(), alpha);
    PADDLE_ENFORCE_EQ(r, xpu::Error_t::SUCCESS,
                      platform::errors::External(
                          "XPU leaky_relu_grad return wrong value[%d %s].", r,
                          XPUAPIErrorMsg[r]));
  }
};

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
template <typename T>
struct XPUPowFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const auto *x = ctx.Input<Tensor>("X");
    auto *y = ctx.Output<Tensor>("Out");
    auto pow_factor = ctx.Attr<float>("factor");
    const T *x_data = x->data<T>();
    T *y_data = y->mutable_data<T>(ctx.GetPlace());
    T *factor_data = nullptr;

    auto xpu_context =
        ctx.device_context<paddle::platform::XPUDeviceContext>().x_context();
    PADDLE_ENFORCE_EQ(xpu_malloc(reinterpret_cast<void **>(&factor_data),
                                 x->numel() * sizeof(T)),
                      XPU_SUCCESS, platform::errors::ResourceExhausted(
                                       "XPU has no enough memory"));
    int r = xpu::constant<T>(xpu_context, factor_data, x->numel(), pow_factor);
    PADDLE_ENFORCE_EQ(
        r, xpu::Error_t::SUCCESS,
        platform::errors::External("XPU constant op return"
                                   " wrong value[%d %s] in pow op.",
                                   r, XPUAPIErrorMsg[r]));
    r = xpu::pow(xpu_context, x_data, factor_data, y_data, x->numel());
    PADDLE_ENFORCE_EQ(
        r, xpu::Error_t::SUCCESS,
        platform::errors::External("XPU pow op return wrong value[%d %s].", r,
                                   XPUAPIErrorMsg[r]));
    if (xpu_context->xpu_stream != nullptr) {
      xpu_wait(xpu_context->xpu_stream);
    }
    xpu_free(factor_data);
  }
};

367 368 369 370 371 372 373 374 375 376 377 378
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

#define REGISTER_ACTIVATION_XPU_KERNEL(act_type, functor, grad_functor)  \
  REGISTER_OP_XPU_KERNEL(act_type,                                       \
                         ops::XPUActivationKernel<ops::functor<float>>); \
  REGISTER_OP_XPU_KERNEL(                                                \
      act_type##_grad,                                                   \
      ops::XPUActivationGradKernel<ops::grad_functor<float>>);

379 380 381 382 383 384 385
REGISTER_ACTIVATION_XPU_KERNEL(abs, XPUAbsFunctor, XPUAbsGradFunctor)
REGISTER_ACTIVATION_XPU_KERNEL(hard_swish, XPUHardSwishFunctor,
                               XPUHardSwishGradFunctor)
REGISTER_ACTIVATION_XPU_KERNEL(leaky_relu, XPULeakyReluFunctor,
                               XPULeakyReluGradFunctor)
REGISTER_ACTIVATION_XPU_KERNEL(reciprocal, XPUReciprocalFunctor,
                               XPUReciprocalGradFunctor)
386 387 388 389
REGISTER_ACTIVATION_XPU_KERNEL(relu, XPUReluFunctor, XPUReluGradFunctor)
REGISTER_ACTIVATION_XPU_KERNEL(sigmoid, XPUSigmoidFunctor,
                               XPUSigmoidGradFunctor)
REGISTER_ACTIVATION_XPU_KERNEL(sqrt, XPUSqrtFunctor, XPUSqrtGradFunctor)
T
TTerror 已提交
390
REGISTER_ACTIVATION_XPU_KERNEL(square, XPUSquareFunctor, XPUSquareGradFunctor)
391 392 393 394 395 396 397 398 399

REGISTER_OP_XPU_KERNEL(
    tanh, ops::XPUActivationKernel<ops::XPUTanhFunctor<float>>,
    ops::XPUActivationKernel<ops::XPUTanhFunctor<paddle::platform::float16>>);
REGISTER_OP_XPU_KERNEL(
    tanh_grad, ops::XPUActivationGradKernel<ops::XPUTanhGradFunctor<float>>,
    ops::XPUActivationGradKernel<
        ops::XPUTanhGradFunctor<paddle::platform::float16>>);

400 401
REGISTER_OP_XPU_KERNEL(exp,
                       ops::XPUActivationKernel<ops::XPUExpFunctor<float>>);
402 403 404
REGISTER_OP_XPU_KERNEL(log,
                       ops::XPUActivationKernel<ops::XPULogFunctor<float>>);
REGISTER_OP_XPU_KERNEL(pow,
T
TTerror 已提交
405
                       ops::XPUActivationKernel<ops::XPUPowFunctor<float>>);
406 407

#endif  // PADDLE_WITH_XPU