custom_relu_op.cu 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // reference https://github.com/PaddlePaddle/Paddle-Inference-Demo/blob/master/python/custom-operator/custom_relu_op.cu
  15. #include "paddle/extension.h"
  16. template <typename data_t>
  17. __global__ void relu_cuda_forward_kernel(const data_t* x,
  18. data_t* y,
  19. const int num) {
  20. int gid = blockIdx.x * blockDim.x + threadIdx.x;
  21. for (int i = gid; i < num; i += blockDim.x * gridDim.x) {
  22. y[i] = max(x[i], static_cast<data_t>(0.));
  23. }
  24. }
  25. template <typename data_t>
  26. __global__ void relu_cuda_backward_kernel(const data_t* dy,
  27. const data_t* y,
  28. data_t* dx,
  29. const int num) {
  30. int gid = blockIdx.x * blockDim.x + threadIdx.x;
  31. for (int i = gid; i < num; i += blockDim.x * gridDim.x) {
  32. dx[i] = dy[i] * (y[i] > 0 ? 1. : 0.);
  33. }
  34. }
  35. std::vector<paddle::Tensor> relu_cuda_forward(const paddle::Tensor& x) {
  36. auto out = paddle::Tensor(paddle::PlaceType::kGPU);
  37. out.reshape(x.shape());
  38. int numel = x.size();
  39. int block = 512;
  40. int grid = (numel + block - 1) / block;
  41. PD_DISPATCH_FLOATING_TYPES(
  42. x.type(), "relu_cuda_forward_kernel", ([&] {
  43. relu_cuda_forward_kernel<data_t><<<grid, block, 0, x.stream()>>>(
  44. x.data<data_t>(), out.mutable_data<data_t>(x.place()), numel);
  45. }));
  46. return {out};
  47. }
  48. std::vector<paddle::Tensor> relu_cuda_backward(const paddle::Tensor& x,
  49. const paddle::Tensor& out,
  50. const paddle::Tensor& grad_out) {
  51. auto grad_x = paddle::Tensor(paddle::PlaceType::kGPU);
  52. grad_x.reshape(x.shape());
  53. int numel = out.size();
  54. int block = 512;
  55. int grid = (numel + block - 1) / block;
  56. PD_DISPATCH_FLOATING_TYPES(
  57. out.type(), "relu_cuda_backward_kernel", ([&] {
  58. relu_cuda_backward_kernel<data_t><<<grid, block, 0, x.stream()>>>(
  59. grad_out.data<data_t>(),
  60. out.data<data_t>(),
  61. grad_x.mutable_data<data_t>(x.place()),
  62. numel);
  63. }));
  64. return {grad_x};
  65. }