Move GPU 3D FFT code to fft module
[alexxy/gromacs.git] / src / gromacs / fft / gpu_3dfft_ocl.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017,2018,2019,2020,2021, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /*! \internal \file
37  *  \brief Implements GPU 3D FFT routines for OpenCL.
38  *
39  *  \author Aleksei Iupinov <a.yupinov@gmail.com>
40  *  \author Mark Abraham <mark.j.abraham@gmail.com>
41  *  \ingroup module_fft
42  */
43
44 #include "gmxpre.h"
45
46 #include "gpu_3dfft.h"
47
48 #include <array>
49 #include <vector>
50
51 #include <clFFT.h>
52
53 #include "gromacs/gpu_utils/device_context.h"
54 #include "gromacs/gpu_utils/device_stream.h"
55 #include "gromacs/gpu_utils/gmxopencl.h"
56 #include "gromacs/utility/exceptions.h"
57 #include "gromacs/utility/gmxassert.h"
58 #include "gromacs/utility/stringutil.h"
59
60 namespace gmx
61 {
62
63 class Gpu3dFft::Impl
64 {
65 public:
66     Impl(ivec                 realGridSize,
67          ivec                 realGridSizePadded,
68          ivec                 complexGridSizePadded,
69          bool                 useDecomposition,
70          bool                 performOutOfPlaceFFT,
71          const DeviceContext& context,
72          const DeviceStream&  pmeStream,
73          DeviceBuffer<float>  realGrid,
74          DeviceBuffer<float>  complexGrid);
75     ~Impl();
76
77     clfftPlanHandle               planR2C_;
78     clfftPlanHandle               planC2R_;
79     std::vector<cl_command_queue> commandStreams_;
80     cl_mem                        realGrid_;
81     cl_mem                        complexGrid_;
82 };
83
84 //! Throws the exception on clFFT error
85 static void handleClfftError(clfftStatus status, const char* msg)
86 {
87     // Supposedly it's just a superset of standard OpenCL errors
88     if (status != CLFFT_SUCCESS)
89     {
90         GMX_THROW(InternalError(formatString("%s: %d", msg, status)));
91     }
92 }
93
94 Gpu3dFft::Impl::Impl(ivec                 realGridSize,
95                      ivec                 realGridSizePadded,
96                      ivec                 complexGridSizePadded,
97                      const bool           useDecomposition,
98                      const bool           performOutOfPlaceFFT,
99                      const DeviceContext& context,
100                      const DeviceStream&  pmeStream,
101                      DeviceBuffer<float>  realGrid,
102                      DeviceBuffer<float>  complexGrid) :
103     realGrid_(realGrid), complexGrid_(complexGrid)
104 {
105     GMX_RELEASE_ASSERT(!useDecomposition, "FFT decomposition not implemented");
106
107     cl_context clContext = context.context();
108     commandStreams_.push_back(pmeStream.stream());
109
110     // clFFT expects row-major, so dimensions/strides are reversed (ZYX instead of XYZ)
111     std::array<size_t, DIM> realGridDimensions = { size_t(realGridSize[ZZ]),
112                                                    size_t(realGridSize[YY]),
113                                                    size_t(realGridSize[XX]) };
114     std::array<size_t, DIM> realGridStrides    = {
115         1, size_t(realGridSizePadded[ZZ]), size_t(realGridSizePadded[YY] * realGridSizePadded[ZZ])
116     };
117     std::array<size_t, DIM> complexGridStrides = {
118         1, size_t(complexGridSizePadded[ZZ]), size_t(complexGridSizePadded[YY] * complexGridSizePadded[ZZ])
119     };
120
121     constexpr clfftDim dims = CLFFT_3D;
122     handleClfftError(clfftCreateDefaultPlan(&planR2C_, clContext, dims, realGridDimensions.data()),
123                      "clFFT planning failure");
124     handleClfftError(clfftSetResultLocation(planR2C_, performOutOfPlaceFFT ? CLFFT_OUTOFPLACE : CLFFT_INPLACE),
125                      "clFFT planning failure");
126     handleClfftError(clfftSetPlanPrecision(planR2C_, CLFFT_SINGLE), "clFFT planning failure");
127     constexpr cl_float scale = 1.0;
128     handleClfftError(clfftSetPlanScale(planR2C_, CLFFT_FORWARD, scale),
129                      "clFFT coefficient setup failure");
130     handleClfftError(clfftSetPlanScale(planR2C_, CLFFT_BACKWARD, scale),
131                      "clFFT coefficient setup failure");
132
133     // The only difference between 2 plans is direction
134     handleClfftError(clfftCopyPlan(&planC2R_, clContext, planR2C_), "clFFT plan copying failure");
135
136     handleClfftError(clfftSetLayout(planR2C_, CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED),
137                      "clFFT R2C layout failure");
138     handleClfftError(clfftSetLayout(planC2R_, CLFFT_HERMITIAN_INTERLEAVED, CLFFT_REAL),
139                      "clFFT C2R layout failure");
140
141     handleClfftError(clfftSetPlanInStride(planR2C_, dims, realGridStrides.data()),
142                      "clFFT stride setting failure");
143     handleClfftError(clfftSetPlanOutStride(planR2C_, dims, complexGridStrides.data()),
144                      "clFFT stride setting failure");
145
146     handleClfftError(clfftSetPlanInStride(planC2R_, dims, complexGridStrides.data()),
147                      "clFFT stride setting failure");
148     handleClfftError(clfftSetPlanOutStride(planC2R_, dims, realGridStrides.data()),
149                      "clFFT stride setting failure");
150
151     handleClfftError(clfftBakePlan(planR2C_, commandStreams_.size(), commandStreams_.data(), nullptr, nullptr),
152                      "clFFT precompiling failure");
153     handleClfftError(clfftBakePlan(planC2R_, commandStreams_.size(), commandStreams_.data(), nullptr, nullptr),
154                      "clFFT precompiling failure");
155
156     // TODO: implement solve kernel as R2C FFT callback
157     // TODO: disable last transpose (clfftSetPlanTransposeResult)
158 }
159
160 Gpu3dFft::Impl::~Impl()
161 {
162     clfftDestroyPlan(&planR2C_);
163     clfftDestroyPlan(&planC2R_);
164 }
165
166 void Gpu3dFft::perform3dFft(gmx_fft_direction dir, CommandEvent* timingEvent)
167 {
168     cl_mem                            tempBuffer = nullptr;
169     constexpr std::array<cl_event, 0> waitEvents{ {} };
170
171     clfftPlanHandle plan;
172     clfftDirection  direction;
173     cl_mem *        inputGrids, *outputGrids;
174
175     switch (dir)
176     {
177         case GMX_FFT_REAL_TO_COMPLEX:
178             plan        = impl_->planR2C_;
179             direction   = CLFFT_FORWARD;
180             inputGrids  = &impl_->realGrid_;
181             outputGrids = &impl_->complexGrid_;
182             break;
183         case GMX_FFT_COMPLEX_TO_REAL:
184             plan        = impl_->planC2R_;
185             direction   = CLFFT_BACKWARD;
186             inputGrids  = &impl_->complexGrid_;
187             outputGrids = &impl_->realGrid_;
188             break;
189         default:
190             GMX_THROW(NotImplementedError("The chosen 3D-FFT case is not implemented on GPUs"));
191     }
192     handleClfftError(clfftEnqueueTransform(plan,
193                                            direction,
194                                            impl_->commandStreams_.size(),
195                                            impl_->commandStreams_.data(),
196                                            waitEvents.size(),
197                                            waitEvents.data(),
198                                            timingEvent,
199                                            inputGrids,
200                                            outputGrids,
201                                            tempBuffer),
202                      "clFFT execution failure");
203 }
204
205 Gpu3dFft::Gpu3dFft(ivec                 realGridSize,
206                    ivec                 realGridSizePadded,
207                    ivec                 complexGridSizePadded,
208                    const bool           useDecomposition,
209                    const bool           performOutOfPlaceFFT,
210                    const DeviceContext& context,
211                    const DeviceStream&  pmeStream,
212                    DeviceBuffer<float>  realGrid,
213                    DeviceBuffer<float>  complexGrid) :
214     impl_(std::make_unique<Impl>(realGridSize,
215                                  realGridSizePadded,
216                                  complexGridSizePadded,
217                                  useDecomposition,
218                                  performOutOfPlaceFFT,
219                                  context,
220                                  pmeStream,
221                                  realGrid,
222                                  complexGrid))
223 {
224 }
225
226 Gpu3dFft::~Gpu3dFft() = default;
227
228 } // namespace gmx