2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team.
6 * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7 * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
8 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9 * and including many others, as listed in the AUTHORS file in the
10 * top-level source directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
38 /*! \libinternal \file
40 * \brief This file contains function declarations necessary for
41 * computing energies and forces for the PME long-ranged part (Coulomb
44 * \author Berk Hess <hess@kth.se>
46 * \ingroup module_ewald
49 #ifndef GMX_EWALD_PME_H
50 #define GMX_EWALD_PME_H
55 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
56 #include "gromacs/gpu_utils/gpu_macros.h"
57 #include "gromacs/math/vectypes.h"
58 #include "gromacs/utility/real.h"
65 struct gmx_wallclock_gpu_pme_t;
66 struct gmx_enerdata_t;
74 enum class GpuTaskCompletion;
76 class GpuEventSynchronizer;
78 /*! \brief Hack to selectively enable some parts of PME during unit testing.
80 * Set to \c false by default. If any of the tests sets it to \c true, it will
81 * make the compatibility check consider PME to be supported in SYCL builds.
83 * Currently we don't have proper PME implementation with SYCL, but we still want
84 * to run tests for some of the kernels.
86 * \todo Remove after #3927 is done and PME is fully enabled in SYCL builds.
88 //NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
89 extern bool g_allowPmeWithSyclForTesting;
95 class ForceWithVirial;
97 enum class PinningPolicy : int;
100 /*! \libinternal \brief Class for managing usage of separate PME-only ranks
102 * Used for checking if some parts of the code could not use PME-only ranks
105 class SeparatePmeRanksPermitted
108 //! Disables PME ranks permitted flag with a reason
109 void disablePmeRanks(const std::string& reason);
110 //! Return status of PME ranks usage
111 bool permitSeparatePmeRanks() const;
112 //! Returns all reasons, for not using PME ranks
113 std::string reasonsWhyDisabled() const;
116 //! Flag that informs whether simualtion could use dedicated PME ranks
117 bool permitSeparatePmeRanks_ = true;
118 //! Storage for all reasons, why PME ranks could not be used
119 std::vector<std::string> reasons_;
122 class PmeCoordinateReceiverGpu;
127 GMX_SUM_GRID_FORWARD,
128 GMX_SUM_GRID_BACKWARD
131 /*! \brief Possible PME codepaths on a rank.
132 * \todo: make this enum class with gmx_pme_t C++ refactoring
134 enum class PmeRunMode
136 None, //!< No PME task is done
137 CPU, //!< Whole PME computation is done on CPU
138 GPU, //!< Whole PME computation is done on GPU
139 Mixed, //!< Mixed mode: only spread and gather run on GPU; FFT and solving are done on CPU.
142 /*! \brief Return the smallest allowed PME grid size for \p pmeOrder */
143 int minimalPmeGridSize(int pmeOrder);
145 //! Return whether the grid of \c pme is identical to \c grid_size.
146 bool gmx_pme_grid_matches(const gmx_pme_t& pme, const ivec grid_size);
148 /*! \brief Check restrictions on pme_order and the PME grid nkx,nky,nkz.
150 * With errorsAreFatal=true, an exception or fatal error is generated
151 * on violation of restrictions.
152 * With errorsAreFatal=false, false is returned on violation of restrictions.
153 * When all restrictions are obeyed, true is returned.
154 * Argument useThreads tells if any MPI rank doing PME uses more than 1 threads.
155 * If at calling useThreads is unknown, pass true for conservative checking.
157 * The PME GPU restrictions are checked separately during pme_gpu_init().
159 bool gmx_pme_check_restrictions(int pme_order,
163 int numPmeDomainsAlongX,
165 bool errorsAreFatal);
167 /*! \brief Construct PME data
169 * \throws gmx::InconsistentInputError if input grid sizes/PME order are inconsistent.
170 * \returns Pointer to newly allocated and initialized PME data.
172 * \todo We should evolve something like a \c GpuManager that holds \c
173 * DeviceInformation* and \c PmeGpuProgram* and perhaps other
174 * related things whose lifetime can/should exceed that of a task (or
175 * perhaps task manager). See Issue #2522.
177 gmx_pme_t* gmx_pme_init(const t_commrec* cr,
178 const NumPmeDomains& numPmeDomains,
179 const t_inputrec* ir,
180 gmx_bool bFreeEnergy_q,
181 gmx_bool bFreeEnergy_lj,
182 gmx_bool bReproducible,
188 const DeviceContext* deviceContext,
189 const DeviceStream* deviceStream,
190 const PmeGpuProgram* pmeGpuProgram,
191 const gmx::MDLogger& mdlog);
193 /*! \brief As gmx_pme_init, but takes most settings, except the grid/Ewald coefficients, from
194 * pme_src. This is only called when the PME cut-off/grid size changes.
196 void gmx_pme_reinit(gmx_pme_t** pmedata,
199 const t_inputrec* ir,
200 const ivec grid_size,
204 /*! \brief Destroys the PME data structure.*/
205 void gmx_pme_destroy(gmx_pme_t* pme);
207 /*! \brief Do a PME calculation on a CPU for the long range electrostatics and/or LJ.
209 * Computes the PME forces and the energy and viral, when requested,
210 * for all atoms in \p coordinates. Forces, when requested, are added
211 * to the buffer \p forces, which is allowed to contain more elements
212 * than the number of elements in \p coordinates.
213 * The meaning of \p flags is defined above, and determines which
214 * parts of the calculation are performed.
216 * \return 0 indicates all well, non zero is an error code.
218 int gmx_pme_do(struct gmx_pme_t* pme,
219 gmx::ArrayRef<const gmx::RVec> coordinates,
220 gmx::ArrayRef<gmx::RVec> forces,
221 gmx::ArrayRef<const real> chargeA,
222 gmx::ArrayRef<const real> chargeB,
223 gmx::ArrayRef<const real> c6A,
224 gmx::ArrayRef<const real> c6B,
225 gmx::ArrayRef<const real> sigmaA,
226 gmx::ArrayRef<const real> sigmaB,
232 gmx_wallcycle* wcycle,
241 const gmx::StepWorkload& stepWork);
243 /*! \brief Calculate the PME grid energy V for n charges.
245 * The potential (found in \p pme) must have been found already with a
246 * call to gmx_pme_do(). Note that the charges are not spread on the grid in the
247 * pme struct. Currently does not work in parallel or with free
250 real gmx_pme_calc_energy(gmx_pme_t* pme, gmx::ArrayRef<const gmx::RVec> x, gmx::ArrayRef<const real> q);
253 * This function updates the local atom data on GPU after DD (charges, coordinates, etc.).
254 * TODO: it should update the PME CPU atom data as well.
255 * (currently PME CPU call gmx_pme_do() gets passed the input pointers for each computation).
257 * \param[in,out] pme The PME structure.
258 * \param[in] numAtoms The number of particles.
259 * \param[in] chargesA The pointer to the array of particle charges in the normal state or FEP
260 * state A. Can be nullptr if PME is not performed on the GPU.
261 * \param[in] chargesB The pointer to the array of particle charges in state B. Only used if
262 * charges are perturbed and can otherwise be nullptr.
264 void gmx_pme_reinit_atoms(gmx_pme_t* pme,
266 gmx::ArrayRef<const real> chargesA,
267 gmx::ArrayRef<const real> chargesB);
269 /* A block of PME GPU functions */
271 /*! \brief Checks whether the GROMACS build allows to run PME on GPU.
272 * TODO: this partly duplicates an internal PME assert function
273 * pme_gpu_check_restrictions(), except that works with a
274 * formed gmx_pme_t structure. Should that one go away/work with inputrec?
276 * \param[out] error If non-null, the error message when PME is not supported on GPU.
278 * \returns true if PME can run on GPU on this build, false otherwise.
280 bool pme_gpu_supports_build(std::string* error);
282 /*! \brief Checks whether the detected (GPU) hardware allows to run PME on GPU.
284 * \param[in] hwinfo Information about the detected hardware
285 * \param[out] error If non-null, the error message when PME is not supported on GPU.
287 * \returns true if PME can run on GPU on this build, false otherwise.
289 bool pme_gpu_supports_hardware(const gmx_hw_info_t& hwinfo, std::string* error);
291 /*! \brief Checks whether the input system allows to run PME on GPU.
292 * TODO: this partly duplicates an internal PME assert function
293 * pme_gpu_check_restrictions(), except that works with a
294 * formed gmx_pme_t structure. Should that one go away/work with inputrec?
296 * \param[in] ir Input system.
297 * \param[out] error If non-null, the error message if the input is not supported on GPU.
299 * \returns true if PME can run on GPU with this input, false otherwise.
301 bool pme_gpu_supports_input(const t_inputrec& ir, std::string* error);
303 /*! \brief Checks whether the input system allows to run PME on GPU in Mixed mode.
304 * Assumes that the input system is compatible with GPU PME otherwise, that is,
305 * before calling this function one should check that \ref pme_gpu_supports_input returns \c true.
307 * \param[in] ir Input system.
308 * \param[out] error If non-null, the error message if the input is not supported.
310 * \returns true if PME can run on GPU in Mixed mode with this input, false otherwise.
312 bool pme_gpu_mixed_mode_supports_input(const t_inputrec& ir, std::string* error);
315 * Returns the active PME codepath (CPU, GPU, mixed).
316 * \todo This is a rather static data that should be managed by the higher level task scheduler.
318 * \param[in] pme The PME data structure.
319 * \returns active PME codepath.
321 PmeRunMode pme_run_mode(const gmx_pme_t* pme);
323 /*! \libinternal \brief
324 * Return the pinning policy appropriate for this build configuration
325 * for relevant buffers used for PME task on this rank (e.g. running
327 gmx::PinningPolicy pme_get_pinning_policy();
330 * Tells if PME is enabled to run on GPU (not necessarily active at the moment).
331 * \todo This is a rather static data that should be managed by the hardware assignment manager.
332 * For now, it is synonymous with the active PME codepath (in the absence of dynamic switching).
334 * \param[in] pme The PME data structure.
335 * \returns true if PME can run on GPU, false otherwise.
337 inline bool pme_gpu_task_enabled(const gmx_pme_t* pme)
339 return (pme != nullptr) && (pme_run_mode(pme) != PmeRunMode::CPU);
342 /*! \brief Returns the block size requirement
344 * The GPU version of PME requires that the coordinates array have a
345 * size divisible by the returned number.
347 * \param[in] pme The PME data structure.
349 GPU_FUNC_QUALIFIER int pme_gpu_get_block_size(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
350 GPU_FUNC_TERM_WITH_RETURN(0);
352 // The following functions are all the PME GPU entry points,
353 // currently inlining to nothing on non-CUDA builds.
356 * Resets the PME GPU timings. To be called at the reset step.
358 * \param[in] pme The PME structure.
360 GPU_FUNC_QUALIFIER void pme_gpu_reset_timings(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme)) GPU_FUNC_TERM;
363 * Copies the PME GPU timings to the gmx_wallclock_gpu_pme_t structure (for log output). To be called at the run end.
365 * \param[in] pme The PME structure.
366 * \param[in] timings The gmx_wallclock_gpu_pme_t structure.
368 GPU_FUNC_QUALIFIER void pme_gpu_get_timings(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
369 gmx_wallclock_gpu_pme_t* GPU_FUNC_ARGUMENT(timings)) GPU_FUNC_TERM;
371 /* The main PME GPU functions */
374 * Prepares PME on GPU computation (updating the box if needed)
375 * \param[in] pme The PME data structure.
376 * \param[in] box The unit cell box.
377 * \param[in] wcycle The wallclock counter.
378 * \param[in] stepWork The required work for this simulation step
380 GPU_FUNC_QUALIFIER void pme_gpu_prepare_computation(gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
381 const matrix GPU_FUNC_ARGUMENT(box),
382 gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
383 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork)) GPU_FUNC_TERM;
386 * Launches first stage of PME on GPU - spreading kernel.
388 * \param[in] pme The PME data structure.
389 * \param[in] xReadyOnDevice Event synchronizer indicating that the coordinates
390 * are ready in the device memory; nullptr allowed only
391 * on separate PME ranks.
392 * \param[in] wcycle The wallclock counter.
393 * \param[in] lambdaQ The Coulomb lambda of the current state of the
394 * system. Only used if FEP of Coulomb is active.
395 * \param[in] useGpuDirectComm Whether direct GPU PME-PP communication is active
396 * \param[in] pmeCoordinateReceiverGpu Coordinate receiver object, which must be valid when
397 * direct GPU PME-PP communication is active
399 GPU_FUNC_QUALIFIER void pme_gpu_launch_spread(
400 gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
401 GpuEventSynchronizer* GPU_FUNC_ARGUMENT(xReadyOnDevice),
402 gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
403 real GPU_FUNC_ARGUMENT(lambdaQ),
404 bool GPU_FUNC_ARGUMENT(useGpuDirectComm),
405 gmx::PmeCoordinateReceiverGpu* GPU_FUNC_ARGUMENT(pmeCoordinateReceiverGpu)) GPU_FUNC_TERM;
408 * Launches middle stages of PME (FFT R2C, solving, FFT C2R) either on GPU or on CPU, depending on the run mode.
410 * \param[in] pme The PME data structure.
411 * \param[in] wcycle The wallclock counter.
412 * \param[in] stepWork The required work for this simulation step
414 GPU_FUNC_QUALIFIER void
415 pme_gpu_launch_complex_transforms(gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
416 gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
417 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork)) GPU_FUNC_TERM;
420 * Launches last stage of PME on GPU - force gathering and D2H force transfer.
422 * \param[in] pme The PME data structure.
423 * \param[in] wcycle The wallclock counter.
424 * \param[in] lambdaQ The Coulomb lambda to use when calculating the results.
426 GPU_FUNC_QUALIFIER void pme_gpu_launch_gather(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
427 gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
428 real GPU_FUNC_ARGUMENT(lambdaQ)) GPU_FUNC_TERM;
431 * Attempts to complete PME GPU tasks.
433 * The \p completionKind argument controls whether the function blocks until all
434 * PME GPU tasks enqueued completed (as pme_gpu_wait_finish_task() does) or only
435 * checks and returns immediately if they did not.
436 * When blocking or the tasks have completed it also gets the output forces
437 * by assigning the ArrayRef to the \p forces pointer passed in.
438 * Virial/energy are also outputs if they were to be computed.
440 * \param[in] pme The PME data structure.
441 * \param[in] stepWork The required work for this simulation step
442 * \param[in] wcycle The wallclock counter.
443 * \param[out] forceWithVirial The output force and virial
444 * \param[out] enerd The output energies
445 * \param[in] lambdaQ The Coulomb lambda to use when calculating the results.
446 * \param[in] completionKind Indicates whether PME task completion should only be checked rather
448 * \returns True if the PME GPU tasks have completed
450 GPU_FUNC_QUALIFIER bool pme_gpu_try_finish_task(gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
451 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork),
452 gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
453 gmx::ForceWithVirial* GPU_FUNC_ARGUMENT(forceWithVirial),
454 gmx_enerdata_t* GPU_FUNC_ARGUMENT(enerd),
455 real GPU_FUNC_ARGUMENT(lambdaQ),
456 GpuTaskCompletion GPU_FUNC_ARGUMENT(completionKind))
457 GPU_FUNC_TERM_WITH_RETURN(false);
460 * Blocks until PME GPU tasks are completed, and gets the output forces and virial/energy
461 * (if they were to be computed).
463 * \param[in] pme The PME data structure.
464 * \param[in] stepWork The required work for this simulation step
465 * \param[in] wcycle The wallclock counter.
466 * \param[out] forceWithVirial The output force and virial
467 * \param[out] enerd The output energies
468 * \param[in] lambdaQ The Coulomb lambda to use when calculating the results.
470 GPU_FUNC_QUALIFIER void pme_gpu_wait_and_reduce(gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
471 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork),
472 gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
473 gmx::ForceWithVirial* GPU_FUNC_ARGUMENT(forceWithVirial),
474 gmx_enerdata_t* GPU_FUNC_ARGUMENT(enerd),
475 real GPU_FUNC_ARGUMENT(lambdaQ)) GPU_FUNC_TERM;
478 * The PME GPU reinitialization function that is called both at the end of any PME computation and on any load balancing.
480 * Clears the internal grid and energy/virial buffers; it is not safe to start
481 * the PME computation without calling this.
482 * Note that unlike in the nbnxn module, the force buffer does not need clearing.
484 * \todo Rename this function to *clear* -- it clearly only does output resetting
485 * and we should be clear about what the function does..
487 * \param[in] pme The PME data structure.
488 * \param[in] wcycle The wallclock counter.
490 GPU_FUNC_QUALIFIER void pme_gpu_reinit_computation(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
491 gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle)) GPU_FUNC_TERM;
493 /*! \brief Set pointer to device copy of coordinate data.
494 * \param[in] pme The PME data structure.
495 * \param[in] d_x The pointer to the positions buffer to be set
497 GPU_FUNC_QUALIFIER void pme_gpu_set_device_x(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
498 DeviceBuffer<gmx::RVec> GPU_FUNC_ARGUMENT(d_x)) GPU_FUNC_TERM;
500 /*! \brief Get pointer to device copy of force data.
501 * \param[in] pme The PME data structure.
502 * \returns Pointer to force data
504 GPU_FUNC_QUALIFIER DeviceBuffer<gmx::RVec> pme_gpu_get_device_f(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
505 GPU_FUNC_TERM_WITH_RETURN(DeviceBuffer<gmx::RVec>{});
507 /*! \brief Get pointer to the device synchronizer object that allows syncing on PME force calculation completion
508 * \param[in] pme The PME data structure.
509 * \returns Pointer to synchronizer
511 GPU_FUNC_QUALIFIER GpuEventSynchronizer* pme_gpu_get_f_ready_synchronizer(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
512 GPU_FUNC_TERM_WITH_RETURN(nullptr);