PME reduction for CUDA F buffer operations
[alexxy/gromacs.git] / src / gromacs / ewald / pme_gpu.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017,2018,2019, 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 high-level PME GPU functions which do not require GPU framework-specific code.
38  *
39  * \author Aleksei Iupinov <a.yupinov@gmail.com>
40  * \ingroup module_ewald
41  */
42
43 #include "gmxpre.h"
44
45 #include "config.h"
46
47 #include <list>
48
49 #include "gromacs/ewald/ewald_utils.h"
50 #include "gromacs/ewald/pme.h"
51 #include "gromacs/fft/parallel_3dfft.h"
52 #include "gromacs/math/invertmatrix.h"
53 #include "gromacs/mdlib/gmx_omp_nthreads.h"
54 #include "gromacs/mdtypes/enerdata.h"
55 #include "gromacs/mdtypes/forceoutput.h"
56 #include "gromacs/mdtypes/inputrec.h"
57 #include "gromacs/utility/exceptions.h"
58 #include "gromacs/utility/fatalerror.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/stringutil.h"
61
62 #include "pme_gpu_internal.h"
63 #include "pme_grid.h"
64 #include "pme_internal.h"
65 #include "pme_solve.h"
66
67 void pme_gpu_reset_timings(const gmx_pme_t *pme)
68 {
69     if (pme_gpu_active(pme))
70     {
71         pme_gpu_reset_timings(pme->gpu);
72     }
73 }
74
75 void pme_gpu_get_timings(const gmx_pme_t *pme, gmx_wallclock_gpu_pme_t *timings)
76 {
77     if (pme_gpu_active(pme))
78     {
79         pme_gpu_get_timings(pme->gpu, timings);
80     }
81 }
82
83 /*! \brief
84  * A convenience wrapper for launching either the GPU or CPU FFT.
85  *
86  * \param[in] pme            The PME structure.
87  * \param[in] gridIndex      The grid index - should currently always be 0.
88  * \param[in] dir            The FFT direction enum.
89  * \param[in] wcycle         The wallclock counter.
90  */
91 void inline parallel_3dfft_execute_gpu_wrapper(gmx_pme_t              *pme,
92                                                const int               gridIndex,
93                                                enum gmx_fft_direction  dir,
94                                                gmx_wallcycle_t         wcycle)
95 {
96     GMX_ASSERT(gridIndex == 0, "Only single grid supported");
97     if (pme_gpu_performs_FFT(pme->gpu))
98     {
99         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
100         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_PME);
101         pme_gpu_3dfft(pme->gpu, dir, gridIndex);
102         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_PME);
103         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
104     }
105     else
106     {
107         wallcycle_start(wcycle, ewcPME_FFT_MIXED_MODE);
108 #pragma omp parallel for num_threads(pme->nthread) schedule(static)
109         for (int thread = 0; thread < pme->nthread; thread++)
110         {
111             gmx_parallel_3dfft_execute(pme->pfft_setup[gridIndex], dir, thread, wcycle);
112         }
113         wallcycle_stop(wcycle, ewcPME_FFT_MIXED_MODE);
114     }
115 }
116
117 /* The PME computation code split into a few separate functions. */
118
119 void pme_gpu_prepare_computation(gmx_pme_t            *pme,
120                                  bool                  needToUpdateBox,
121                                  const matrix          box,
122                                  gmx_wallcycle        *wcycle,
123                                  int                   flags)
124 {
125     GMX_ASSERT(pme_gpu_active(pme), "This should be a GPU run of PME but it is not enabled.");
126     GMX_ASSERT(pme->nnodes > 0, "");
127     GMX_ASSERT(pme->nnodes == 1 || pme->ndecompdim > 0, "");
128
129     PmeGpu *pmeGpu = pme->gpu;
130     pmeGpu->settings.currentFlags = flags;
131     // TODO these flags are only here to honor the CPU PME code, and probably should be removed
132
133     bool shouldUpdateBox = false;
134     for (int i = 0; i < DIM; ++i)
135     {
136         for (int j = 0; j <= i; ++j)
137         {
138             shouldUpdateBox                  |= (pmeGpu->common->previousBox[i][j] != box[i][j]);
139             pmeGpu->common->previousBox[i][j] = box[i][j];
140         }
141     }
142
143     if (needToUpdateBox || shouldUpdateBox) // || is to make the first computation always update
144     {
145         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
146         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_PME);
147         pme_gpu_update_input_box(pmeGpu, box);
148         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_PME);
149         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
150
151         if (!pme_gpu_performs_solve(pmeGpu))
152         {
153             // TODO remove code duplication and add test coverage
154             matrix scaledBox;
155             pmeGpu->common->boxScaler->scaleBox(box, scaledBox);
156             gmx::invertBoxMatrix(scaledBox, pme->recipbox);
157             pme->boxVolume = scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ];
158         }
159     }
160 }
161
162
163 void pme_gpu_launch_spread(gmx_pme_t            *pme,
164                            const rvec           *x,
165                            gmx_wallcycle        *wcycle)
166 {
167     GMX_ASSERT(pme_gpu_active(pme), "This should be a GPU run of PME but it is not enabled.");
168
169     PmeGpu *pmeGpu = pme->gpu;
170
171     // The only spot of PME GPU where LAUNCH_GPU counter increases call-count
172     wallcycle_start(wcycle, ewcLAUNCH_GPU);
173     // The only spot of PME GPU where ewcsLAUNCH_GPU_PME subcounter increases call-count
174     wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_PME);
175     pme_gpu_copy_input_coordinates(pmeGpu, x);
176     wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_PME);
177     wallcycle_stop(wcycle, ewcLAUNCH_GPU);
178
179     const unsigned int gridIndex  = 0;
180     real              *fftgrid    = pme->fftgrid[gridIndex];
181     if (pmeGpu->settings.currentFlags & GMX_PME_SPREAD)
182     {
183         /* Spread the coefficients on a grid */
184         const bool computeSplines = true;
185         const bool spreadCharges  = true;
186         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
187         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_PME);
188         pme_gpu_spread(pmeGpu, gridIndex, fftgrid, computeSplines, spreadCharges);
189         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_PME);
190         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
191     }
192 }
193
194 void pme_gpu_launch_complex_transforms(gmx_pme_t      *pme,
195                                        gmx_wallcycle  *wcycle)
196 {
197     PmeGpu            *pmeGpu                 = pme->gpu;
198     const bool         computeEnergyAndVirial = (pmeGpu->settings.currentFlags & GMX_PME_CALC_ENER_VIR) != 0;
199     const bool         performBackFFT         = (pmeGpu->settings.currentFlags & (GMX_PME_CALC_F | GMX_PME_CALC_POT)) != 0;
200     const unsigned int gridIndex              = 0;
201     t_complex         *cfftgrid               = pme->cfftgrid[gridIndex];
202
203     if (pmeGpu->settings.currentFlags & GMX_PME_SPREAD)
204     {
205         if (!pme_gpu_performs_FFT(pmeGpu))
206         {
207             wallcycle_start(wcycle, ewcWAIT_GPU_PME_SPREAD);
208             pme_gpu_sync_spread_grid(pme->gpu);
209             wallcycle_stop(wcycle, ewcWAIT_GPU_PME_SPREAD);
210         }
211     }
212
213     try
214     {
215         if (pmeGpu->settings.currentFlags & GMX_PME_SOLVE)
216         {
217             /* do R2C 3D-FFT */
218             parallel_3dfft_execute_gpu_wrapper(pme, gridIndex, GMX_FFT_REAL_TO_COMPLEX, wcycle);
219
220             /* solve in k-space for our local cells */
221             if (pme_gpu_performs_solve(pmeGpu))
222             {
223                 const auto gridOrdering = pme_gpu_uses_dd(pmeGpu) ? GridOrdering::YZX : GridOrdering::XYZ;
224                 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
225                 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_PME);
226                 pme_gpu_solve(pmeGpu, cfftgrid, gridOrdering, computeEnergyAndVirial);
227                 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_PME);
228                 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
229             }
230             else
231             {
232                 wallcycle_start(wcycle, ewcPME_SOLVE_MIXED_MODE);
233 #pragma omp parallel for num_threads(pme->nthread) schedule(static)
234                 for (int thread = 0; thread < pme->nthread; thread++)
235                 {
236                     solve_pme_yzx(pme, cfftgrid, pme->boxVolume,
237                                   computeEnergyAndVirial, pme->nthread, thread);
238                 }
239                 wallcycle_stop(wcycle, ewcPME_SOLVE_MIXED_MODE);
240             }
241         }
242
243         if (performBackFFT)
244         {
245             parallel_3dfft_execute_gpu_wrapper(pme, gridIndex, GMX_FFT_COMPLEX_TO_REAL, wcycle);
246         }
247     } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
248 }
249
250 void pme_gpu_launch_gather(const gmx_pme_t                 *pme,
251                            gmx_wallcycle gmx_unused        *wcycle,
252                            PmeForceOutputHandling           forceTreatment,
253                            bool                             useGpuFPmeReduction)
254 {
255     GMX_ASSERT(pme_gpu_active(pme), "This should be a GPU run of PME but it is not enabled.");
256
257     if (!pme_gpu_performs_gather(pme->gpu))
258     {
259         return;
260     }
261
262     wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
263     wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_PME);
264     const unsigned int gridIndex  = 0;
265     real              *fftgrid    = pme->fftgrid[gridIndex];
266     pme_gpu_gather(pme->gpu, forceTreatment, reinterpret_cast<float *>(fftgrid), useGpuFPmeReduction);
267     wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_PME);
268     wallcycle_stop(wcycle, ewcLAUNCH_GPU);
269 }
270
271 //! Accumulate the \c forcesToAdd to \c f, using the available threads.
272 static void sum_forces(gmx::ArrayRef<gmx::RVec>       f,
273                        gmx::ArrayRef<const gmx::RVec> forceToAdd)
274 {
275     const int      end = forceToAdd.size();
276
277     int gmx_unused nt = gmx_omp_nthreads_get(emntPME);
278 #pragma omp parallel for num_threads(nt) schedule(static)
279     for (int i = 0; i < end; i++)
280     {
281         f[i] += forceToAdd[i];
282     }
283 }
284
285 //! Reduce quantities from \c output to \c forceWithVirial and \c enerd.
286 static void pme_gpu_reduce_outputs(const int             flags,
287                                    const PmeOutput      &output,
288                                    gmx_wallcycle        *wcycle,
289                                    gmx::ForceWithVirial *forceWithVirial,
290                                    gmx_enerdata_t       *enerd,
291                                    bool                  useGpuFPmeReduction)
292 {
293     wallcycle_start(wcycle, ewcPME_GPU_F_REDUCTION);
294     GMX_ASSERT(forceWithVirial, "Invalid force pointer");
295     const bool haveComputedEnergyAndVirial = (flags & GMX_PME_CALC_ENER_VIR) != 0;
296     if (haveComputedEnergyAndVirial)
297     {
298         GMX_ASSERT(enerd, "Invalid energy output manager");
299         forceWithVirial->addVirialContribution(output.coulombVirial_);
300         enerd->term[F_COUL_RECIP] += output.coulombEnergy_;
301     }
302     if (!useGpuFPmeReduction)
303     {
304         sum_forces(forceWithVirial->force_, output.forces_);
305     }
306     wallcycle_stop(wcycle, ewcPME_GPU_F_REDUCTION);
307 }
308
309 bool pme_gpu_try_finish_task(gmx_pme_t            *pme,
310                              const int             flags,
311                              gmx_wallcycle        *wcycle,
312                              gmx::ForceWithVirial *forceWithVirial,
313                              gmx_enerdata_t       *enerd,
314                              GpuTaskCompletion     completionKind)
315 {
316     GMX_ASSERT(pme_gpu_active(pme), "This should be a GPU run of PME but it is not enabled.");
317
318     // First, if possible, check whether all tasks on the stream have
319     // completed, and return fast if not. Accumulate to wcycle the
320     // time needed for that checking, but do not yet record that the
321     // gather has occured.
322     bool           needToSynchronize      = true;
323     constexpr bool c_streamQuerySupported = (GMX_GPU == GMX_GPU_CUDA);
324     // TODO: implement c_streamQuerySupported with an additional GpuEventSynchronizer per stream (#2521)
325     if ((completionKind == GpuTaskCompletion::Check) && c_streamQuerySupported)
326     {
327         wallcycle_start_nocount(wcycle, ewcWAIT_GPU_PME_GATHER);
328         // Query the PME stream for completion of all tasks enqueued and
329         // if we're not done, stop the timer before early return.
330         const bool pmeGpuDone = pme_gpu_stream_query(pme->gpu);
331         wallcycle_stop(wcycle, ewcWAIT_GPU_PME_GATHER);
332
333         if (!pmeGpuDone)
334         {
335             return false;
336         }
337         needToSynchronize = false;
338     }
339
340     wallcycle_start(wcycle, ewcWAIT_GPU_PME_GATHER);
341     // If the above check passed, then there is no need to make an
342     // explicit synchronization call.
343     if (needToSynchronize)
344     {
345         // Synchronize the whole PME stream at once, including D2H result transfers.
346         pme_gpu_synchronize(pme->gpu);
347     }
348     pme_gpu_update_timings(pme->gpu);
349     PmeOutput output = pme_gpu_getOutput(*pme, flags);
350     wallcycle_stop(wcycle, ewcWAIT_GPU_PME_GATHER);
351
352     pme_gpu_reduce_outputs(flags, output, wcycle, forceWithVirial, enerd, false);
353
354     return true;
355 }
356
357 // This is used by PME-only ranks
358 PmeOutput pme_gpu_wait_finish_task(gmx_pme_t     *pme,
359                                    const int      flags,
360                                    gmx_wallcycle *wcycle)
361 {
362     GMX_ASSERT(pme_gpu_active(pme), "This should be a GPU run of PME but it is not enabled.");
363
364     wallcycle_start(wcycle, ewcWAIT_GPU_PME_GATHER);
365
366     // Synchronize the whole PME stream at once, including D2H result transfers.
367     // TODO: make this sync conditional with useGpuFPmeReduction to wait only for virial/energies
368     pme_gpu_synchronize(pme->gpu);
369
370     pme_gpu_update_timings(pme->gpu);
371     PmeOutput output = pme_gpu_getOutput(*pme, flags);
372     wallcycle_stop(wcycle, ewcWAIT_GPU_PME_GATHER);
373     return output;
374 }
375
376 // This is used when not using the alternate-waiting reduction
377 void pme_gpu_wait_and_reduce(gmx_pme_t            *pme,
378                              const int             flags,
379                              gmx_wallcycle        *wcycle,
380                              gmx::ForceWithVirial *forceWithVirial,
381                              gmx_enerdata_t       *enerd,
382                              bool                  useGpuFPmeReduction)
383 {
384     PmeOutput output = pme_gpu_wait_finish_task(pme, flags, wcycle);
385     pme_gpu_reduce_outputs(flags, output, wcycle, forceWithVirial, enerd, useGpuFPmeReduction);
386 }
387
388 void pme_gpu_reinit_computation(const gmx_pme_t *pme,
389                                 gmx_wallcycle   *wcycle)
390 {
391     GMX_ASSERT(pme_gpu_active(pme), "This should be a GPU run of PME but it is not enabled.");
392
393     wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
394     wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_PME);
395
396     pme_gpu_clear_grids(pme->gpu);
397     pme_gpu_clear_energy_virial(pme->gpu);
398
399     wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_PME);
400     wallcycle_stop(wcycle, ewcLAUNCH_GPU);
401 }
402
403 void *pme_gpu_get_device_x(const gmx_pme_t *pme)
404 {
405     if (!pme || !pme_gpu_active(pme))
406     {
407         return nullptr;
408     }
409     return pme_gpu_get_kernelparam_coordinates(pme->gpu);
410 }
411
412 void *pme_gpu_get_device_f(const gmx_pme_t *pme)
413 {
414     if (!pme || !pme_gpu_active(pme))
415     {
416         return nullptr;
417     }
418     return pme_gpu_get_kernelparam_forces(pme->gpu);
419 }
420
421 GpuEventSynchronizer * pme_gpu_get_f_ready_synchronizer(const gmx_pme_t *pme)
422 {
423     if (!pme || !pme_gpu_active(pme))
424     {
425         return nullptr;
426     }
427
428     return pme_gpu_get_forces_ready_synchronizer(pme->gpu);
429 }