/* Copyright (c) 2021 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/trunc_op.h" #include "paddle/fluid/platform/device/gpu/gpu_info.h" #include "paddle/fluid/platform/device/gpu/gpu_primitives.h" namespace paddle { namespace operators { using platform::PADDLE_CUDA_NUM_THREADS; template class TruncFunctor { public: __device__ TruncFunctor(const T x) : x_(x) {} __device__ T operator()() { return trunc(x_); } public: const T x_; }; template <> class TruncFunctor { public: __device__ TruncFunctor(const int x) : x_(x) {} __device__ int operator()() { return x_; } public: const int x_; }; template <> class TruncFunctor { public: __device__ TruncFunctor(const int64_t x) : x_(x) {} __device__ int64_t operator()() { return x_; } public: const int64_t x_; }; template __global__ void Trunc(const T* x, T* out, int64_t N) { CUDA_KERNEL_LOOP(index, N) { TruncFunctor functor(x[index]); out[index] = functor(); } } template __global__ void TruncGrad(T* dx, int64_t N) { CUDA_KERNEL_LOOP(index, N) { dx[index] = static_cast(0.0); } } template class TruncCUDAKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& context) const override { auto* x = context.Input("X"); auto* out = context.Output("Out"); const auto* x_data = x->data(); auto* out_data = out->mutable_data(context.GetPlace()); int64_t numel = x->numel(); int theads = PADDLE_CUDA_NUM_THREADS; int blocks = (numel + theads - 1) / theads; Trunc<<>>(x_data, out_data, numel); } }; template class TruncCUDAGradKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& context) const override { auto* dout = context.Input(framework::GradVarName("Out")); auto* dx = context.Output(framework::GradVarName("X")); const auto* dout_data = dout->data(); auto* dx_data = dx->mutable_data(context.GetPlace()); int64_t numel = dout->numel(); int theads = PADDLE_CUDA_NUM_THREADS; int blocks = (numel + theads - 1) / theads; TruncGrad<<>>(dx_data, numel); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_CUDA_KERNEL(trunc, ops::TruncCUDAKernel, ops::TruncCUDAKernel, ops::TruncCUDAKernel, ops::TruncCUDAKernel); REGISTER_OP_CUDA_KERNEL(trunc_grad, ops::TruncCUDAGradKernel, ops::TruncCUDAGradKernel, ops::TruncCUDAGradKernel, ops::TruncCUDAGradKernel);