Redesign GPU FFT abstraction
[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_ocl.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 //! Throws the exception on clFFT error
63 static void handleClfftError(clfftStatus status, const char* msg)
64 {
65     // Supposedly it's just a superset of standard OpenCL errors
66     if (status != CLFFT_SUCCESS)
67     {
68         GMX_THROW(InternalError(formatString("%s: %d", msg, status)));
69     }
70 }
71
72 Gpu3dFft::ImplOcl::ImplOcl(bool allocateGrids,
73                            MPI_Comm /*comm*/,
74                            ArrayRef<const int> gridSizesInXForEachRank,
75                            ArrayRef<const int> gridSizesInYForEachRank,
76                            const int /*nz*/,
77                            bool                 performOutOfPlaceFFT,
78                            const DeviceContext& context,
79                            const DeviceStream&  pmeStream,
80                            ivec                 realGridSize,
81                            ivec                 realGridSizePadded,
82                            ivec                 complexGridSizePadded,
83                            DeviceBuffer<float>* realGrid,
84                            DeviceBuffer<float>* complexGrid) :
85     realGrid_(*realGrid), complexGrid_(*complexGrid)
86 {
87     GMX_RELEASE_ASSERT(allocateGrids == false, "Grids needs to be pre-allocated");
88     GMX_RELEASE_ASSERT(gridSizesInXForEachRank.size() == 1 && gridSizesInYForEachRank.size() == 1,
89                        "FFT decomposition not implemented with OpenCL backend");
90
91     cl_context clContext = context.context();
92     commandStreams_.push_back(pmeStream.stream());
93
94     // clFFT expects row-major, so dimensions/strides are reversed (ZYX instead of XYZ)
95     std::array<size_t, DIM> realGridDimensions = { size_t(realGridSize[ZZ]),
96                                                    size_t(realGridSize[YY]),
97                                                    size_t(realGridSize[XX]) };
98     std::array<size_t, DIM> realGridStrides    = {
99         1, size_t(realGridSizePadded[ZZ]), size_t(realGridSizePadded[YY] * realGridSizePadded[ZZ])
100     };
101     std::array<size_t, DIM> complexGridStrides = {
102         1, size_t(complexGridSizePadded[ZZ]), size_t(complexGridSizePadded[YY] * complexGridSizePadded[ZZ])
103     };
104
105     constexpr clfftDim dims = CLFFT_3D;
106     handleClfftError(clfftCreateDefaultPlan(&planR2C_, clContext, dims, realGridDimensions.data()),
107                      "clFFT planning failure");
108     handleClfftError(clfftSetResultLocation(planR2C_, performOutOfPlaceFFT ? CLFFT_OUTOFPLACE : CLFFT_INPLACE),
109                      "clFFT planning failure");
110     handleClfftError(clfftSetPlanPrecision(planR2C_, CLFFT_SINGLE), "clFFT planning failure");
111     constexpr cl_float scale = 1.0;
112     handleClfftError(clfftSetPlanScale(planR2C_, CLFFT_FORWARD, scale),
113                      "clFFT coefficient setup failure");
114     handleClfftError(clfftSetPlanScale(planR2C_, CLFFT_BACKWARD, scale),
115                      "clFFT coefficient setup failure");
116
117     // The only difference between 2 plans is direction
118     handleClfftError(clfftCopyPlan(&planC2R_, clContext, planR2C_), "clFFT plan copying failure");
119
120     handleClfftError(clfftSetLayout(planR2C_, CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED),
121                      "clFFT R2C layout failure");
122     handleClfftError(clfftSetLayout(planC2R_, CLFFT_HERMITIAN_INTERLEAVED, CLFFT_REAL),
123                      "clFFT C2R layout failure");
124
125     handleClfftError(clfftSetPlanInStride(planR2C_, dims, realGridStrides.data()),
126                      "clFFT stride setting failure");
127     handleClfftError(clfftSetPlanOutStride(planR2C_, dims, complexGridStrides.data()),
128                      "clFFT stride setting failure");
129
130     handleClfftError(clfftSetPlanInStride(planC2R_, dims, complexGridStrides.data()),
131                      "clFFT stride setting failure");
132     handleClfftError(clfftSetPlanOutStride(planC2R_, dims, realGridStrides.data()),
133                      "clFFT stride setting failure");
134
135     handleClfftError(clfftBakePlan(planR2C_, commandStreams_.size(), commandStreams_.data(), nullptr, nullptr),
136                      "clFFT precompiling failure");
137     handleClfftError(clfftBakePlan(planC2R_, commandStreams_.size(), commandStreams_.data(), nullptr, nullptr),
138                      "clFFT precompiling failure");
139
140     // TODO: implement solve kernel as R2C FFT callback
141     // TODO: disable last transpose (clfftSetPlanTransposeResult)
142 }
143
144 Gpu3dFft::ImplOcl::~ImplOcl()
145 {
146     clfftDestroyPlan(&planR2C_);
147     clfftDestroyPlan(&planC2R_);
148 }
149
150 void Gpu3dFft::ImplOcl::perform3dFft(gmx_fft_direction dir, CommandEvent* timingEvent)
151 {
152     cl_mem                            tempBuffer = nullptr;
153     constexpr std::array<cl_event, 0> waitEvents{ {} };
154
155     clfftPlanHandle plan;
156     clfftDirection  direction;
157     cl_mem *        inputGrids, *outputGrids;
158
159     switch (dir)
160     {
161         case GMX_FFT_REAL_TO_COMPLEX:
162             plan        = planR2C_;
163             direction   = CLFFT_FORWARD;
164             inputGrids  = &realGrid_;
165             outputGrids = &complexGrid_;
166             break;
167         case GMX_FFT_COMPLEX_TO_REAL:
168             plan        = planC2R_;
169             direction   = CLFFT_BACKWARD;
170             inputGrids  = &complexGrid_;
171             outputGrids = &realGrid_;
172             break;
173         default:
174             GMX_THROW(NotImplementedError("The chosen 3D-FFT case is not implemented on GPUs"));
175     }
176     handleClfftError(clfftEnqueueTransform(plan,
177                                            direction,
178                                            commandStreams_.size(),
179                                            commandStreams_.data(),
180                                            waitEvents.size(),
181                                            waitEvents.data(),
182                                            timingEvent,
183                                            inputGrids,
184                                            outputGrids,
185                                            tempBuffer),
186                      "clFFT execution failure");
187 }
188
189 } // namespace gmx