Use DeviceBuffer<RVec> in GPU force reduction and PME code
[alexxy/gromacs.git] / src / gromacs / mdlib / sim_util.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013-2019,2020,2021, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "config.h"
40
41 #include <cmath>
42 #include <cstdint>
43 #include <cstdio>
44 #include <cstring>
45
46 #include <array>
47 #include <optional>
48
49 #include "gromacs/applied_forces/awh/awh.h"
50 #include "gromacs/domdec/dlbtiming.h"
51 #include "gromacs/domdec/domdec.h"
52 #include "gromacs/domdec/domdec_struct.h"
53 #include "gromacs/domdec/gpuhaloexchange.h"
54 #include "gromacs/domdec/partition.h"
55 #include "gromacs/essentialdynamics/edsam.h"
56 #include "gromacs/ewald/pme.h"
57 #include "gromacs/ewald/pme_pp.h"
58 #include "gromacs/ewald/pme_pp_comm_gpu.h"
59 #include "gromacs/gmxlib/network.h"
60 #include "gromacs/gmxlib/nonbonded/nb_free_energy.h"
61 #include "gromacs/gmxlib/nonbonded/nb_kernel.h"
62 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
63 #include "gromacs/gpu_utils/gpu_utils.h"
64 #include "gromacs/imd/imd.h"
65 #include "gromacs/listed_forces/disre.h"
66 #include "gromacs/listed_forces/gpubonded.h"
67 #include "gromacs/listed_forces/listed_forces.h"
68 #include "gromacs/listed_forces/orires.h"
69 #include "gromacs/math/arrayrefwithpadding.h"
70 #include "gromacs/math/functions.h"
71 #include "gromacs/math/units.h"
72 #include "gromacs/math/vec.h"
73 #include "gromacs/math/vecdump.h"
74 #include "gromacs/mdlib/calcmu.h"
75 #include "gromacs/mdlib/calcvir.h"
76 #include "gromacs/mdlib/constr.h"
77 #include "gromacs/mdlib/dispersioncorrection.h"
78 #include "gromacs/mdlib/enerdata_utils.h"
79 #include "gromacs/mdlib/force.h"
80 #include "gromacs/mdlib/force_flags.h"
81 #include "gromacs/mdlib/forcerec.h"
82 #include "gromacs/mdlib/gmx_omp_nthreads.h"
83 #include "gromacs/mdlib/update.h"
84 #include "gromacs/mdlib/vsite.h"
85 #include "gromacs/mdlib/wall.h"
86 #include "gromacs/mdlib/wholemoleculetransform.h"
87 #include "gromacs/mdtypes/commrec.h"
88 #include "gromacs/mdtypes/enerdata.h"
89 #include "gromacs/mdtypes/forcebuffers.h"
90 #include "gromacs/mdtypes/forceoutput.h"
91 #include "gromacs/mdtypes/forcerec.h"
92 #include "gromacs/mdtypes/iforceprovider.h"
93 #include "gromacs/mdtypes/inputrec.h"
94 #include "gromacs/mdtypes/md_enums.h"
95 #include "gromacs/mdtypes/mdatom.h"
96 #include "gromacs/mdtypes/multipletimestepping.h"
97 #include "gromacs/mdtypes/simulation_workload.h"
98 #include "gromacs/mdtypes/state.h"
99 #include "gromacs/mdtypes/state_propagator_data_gpu.h"
100 #include "gromacs/nbnxm/gpu_data_mgmt.h"
101 #include "gromacs/nbnxm/nbnxm.h"
102 #include "gromacs/nbnxm/nbnxm_gpu.h"
103 #include "gromacs/pbcutil/ishift.h"
104 #include "gromacs/pbcutil/pbc.h"
105 #include "gromacs/pulling/pull.h"
106 #include "gromacs/pulling/pull_rotation.h"
107 #include "gromacs/timing/cyclecounter.h"
108 #include "gromacs/timing/gpu_timing.h"
109 #include "gromacs/timing/wallcycle.h"
110 #include "gromacs/timing/wallcyclereporting.h"
111 #include "gromacs/timing/walltime_accounting.h"
112 #include "gromacs/topology/topology.h"
113 #include "gromacs/utility/arrayref.h"
114 #include "gromacs/utility/basedefinitions.h"
115 #include "gromacs/utility/cstringutil.h"
116 #include "gromacs/utility/exceptions.h"
117 #include "gromacs/utility/fatalerror.h"
118 #include "gromacs/utility/fixedcapacityvector.h"
119 #include "gromacs/utility/gmxassert.h"
120 #include "gromacs/utility/gmxmpi.h"
121 #include "gromacs/utility/logger.h"
122 #include "gromacs/utility/smalloc.h"
123 #include "gromacs/utility/strconvert.h"
124 #include "gromacs/utility/sysinfo.h"
125
126 #include "gpuforcereduction.h"
127
128 using gmx::ArrayRef;
129 using gmx::AtomLocality;
130 using gmx::DomainLifetimeWorkload;
131 using gmx::ForceOutputs;
132 using gmx::ForceWithShiftForces;
133 using gmx::InteractionLocality;
134 using gmx::RVec;
135 using gmx::SimulationWorkload;
136 using gmx::StepWorkload;
137
138 // TODO: this environment variable allows us to verify before release
139 // that on less common architectures the total cost of polling is not larger than
140 // a blocking wait (so polling does not introduce overhead when the static
141 // PME-first ordering would suffice).
142 static const bool c_disableAlternatingWait = (getenv("GMX_DISABLE_ALTERNATING_GPU_WAIT") != nullptr);
143
144 static void sum_forces(ArrayRef<RVec> f, ArrayRef<const RVec> forceToAdd)
145 {
146     GMX_ASSERT(f.size() >= forceToAdd.size(), "Accumulation buffer should be sufficiently large");
147     const int end = forceToAdd.size();
148
149     int gmx_unused nt = gmx_omp_nthreads_get(emntDefault);
150 #pragma omp parallel for num_threads(nt) schedule(static)
151     for (int i = 0; i < end; i++)
152     {
153         rvec_inc(f[i], forceToAdd[i]);
154     }
155 }
156
157 static void calc_virial(int                              start,
158                         int                              homenr,
159                         const rvec                       x[],
160                         const gmx::ForceWithShiftForces& forceWithShiftForces,
161                         tensor                           vir_part,
162                         const matrix                     box,
163                         t_nrnb*                          nrnb,
164                         const t_forcerec*                fr,
165                         PbcType                          pbcType)
166 {
167     /* The short-range virial from surrounding boxes */
168     const rvec* fshift = as_rvec_array(forceWithShiftForces.shiftForces().data());
169     calc_vir(SHIFTS, fr->shift_vec, fshift, vir_part, pbcType == PbcType::Screw, box);
170     inc_nrnb(nrnb, eNR_VIRIAL, SHIFTS);
171
172     /* Calculate partial virial, for local atoms only, based on short range.
173      * Total virial is computed in global_stat, called from do_md
174      */
175     const rvec* f = as_rvec_array(forceWithShiftForces.force().data());
176     f_calc_vir(start, start + homenr, x, f, vir_part, box);
177     inc_nrnb(nrnb, eNR_VIRIAL, homenr);
178
179     if (debug)
180     {
181         pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
182     }
183 }
184
185 static void pull_potential_wrapper(const t_commrec*               cr,
186                                    const t_inputrec&              ir,
187                                    const matrix                   box,
188                                    gmx::ArrayRef<const gmx::RVec> x,
189                                    gmx::ForceWithVirial*          force,
190                                    const t_mdatoms*               mdatoms,
191                                    gmx_enerdata_t*                enerd,
192                                    pull_t*                        pull_work,
193                                    const real*                    lambda,
194                                    double                         t,
195                                    gmx_wallcycle_t                wcycle)
196 {
197     t_pbc pbc;
198     real  dvdl;
199
200     /* Calculate the center of mass forces, this requires communication,
201      * which is why pull_potential is called close to other communication.
202      */
203     wallcycle_start(wcycle, ewcPULLPOT);
204     set_pbc(&pbc, ir.pbcType, box);
205     dvdl = 0;
206     enerd->term[F_COM_PULL] +=
207             pull_potential(pull_work,
208                            mdatoms->massT,
209                            &pbc,
210                            cr,
211                            t,
212                            lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Restraint)],
213                            as_rvec_array(x.data()),
214                            force,
215                            &dvdl);
216     enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Restraint] += dvdl;
217     wallcycle_stop(wcycle, ewcPULLPOT);
218 }
219
220 static void pme_receive_force_ener(t_forcerec*           fr,
221                                    const t_commrec*      cr,
222                                    gmx::ForceWithVirial* forceWithVirial,
223                                    gmx_enerdata_t*       enerd,
224                                    bool                  useGpuPmePpComms,
225                                    bool                  receivePmeForceToGpu,
226                                    gmx_wallcycle_t       wcycle)
227 {
228     real  e_q, e_lj, dvdl_q, dvdl_lj;
229     float cycles_ppdpme, cycles_seppme;
230
231     cycles_ppdpme = wallcycle_stop(wcycle, ewcPPDURINGPME);
232     dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
233
234     /* In case of node-splitting, the PP nodes receive the long-range
235      * forces, virial and energy from the PME nodes here.
236      */
237     wallcycle_start(wcycle, ewcPP_PMEWAITRECVF);
238     dvdl_q  = 0;
239     dvdl_lj = 0;
240     gmx_pme_receive_f(fr->pmePpCommGpu.get(),
241                       cr,
242                       forceWithVirial,
243                       &e_q,
244                       &e_lj,
245                       &dvdl_q,
246                       &dvdl_lj,
247                       useGpuPmePpComms,
248                       receivePmeForceToGpu,
249                       &cycles_seppme);
250     enerd->term[F_COUL_RECIP] += e_q;
251     enerd->term[F_LJ_RECIP] += e_lj;
252     enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Coul] += dvdl_q;
253     enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Vdw] += dvdl_lj;
254
255     if (wcycle)
256     {
257         dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
258     }
259     wallcycle_stop(wcycle, ewcPP_PMEWAITRECVF);
260 }
261
262 static void print_large_forces(FILE*                fp,
263                                const t_mdatoms*     md,
264                                const t_commrec*     cr,
265                                int64_t              step,
266                                real                 forceTolerance,
267                                ArrayRef<const RVec> x,
268                                ArrayRef<const RVec> f)
269 {
270     real       force2Tolerance = gmx::square(forceTolerance);
271     gmx::index numNonFinite    = 0;
272     for (int i = 0; i < md->homenr; i++)
273     {
274         real force2    = norm2(f[i]);
275         bool nonFinite = !std::isfinite(force2);
276         if (force2 >= force2Tolerance || nonFinite)
277         {
278             fprintf(fp,
279                     "step %" PRId64 " atom %6d  x %8.3f %8.3f %8.3f  force %12.5e\n",
280                     step,
281                     ddglatnr(cr->dd, i),
282                     x[i][XX],
283                     x[i][YY],
284                     x[i][ZZ],
285                     std::sqrt(force2));
286         }
287         if (nonFinite)
288         {
289             numNonFinite++;
290         }
291     }
292     if (numNonFinite > 0)
293     {
294         /* Note that with MPI this fatal call on one rank might interrupt
295          * the printing on other ranks. But we can only avoid that with
296          * an expensive MPI barrier that we would need at each step.
297          */
298         gmx_fatal(FARGS, "At step %" PRId64 " detected non-finite forces on %td atoms", step, numNonFinite);
299     }
300 }
301
302 //! When necessary, spreads forces on vsites and computes the virial for \p forceOutputs->forceWithShiftForces()
303 static void postProcessForceWithShiftForces(t_nrnb*                   nrnb,
304                                             gmx_wallcycle_t           wcycle,
305                                             const matrix              box,
306                                             ArrayRef<const RVec>      x,
307                                             ForceOutputs*             forceOutputs,
308                                             tensor                    vir_force,
309                                             const t_mdatoms&          mdatoms,
310                                             const t_forcerec&         fr,
311                                             gmx::VirtualSitesHandler* vsite,
312                                             const StepWorkload&       stepWork)
313 {
314     ForceWithShiftForces& forceWithShiftForces = forceOutputs->forceWithShiftForces();
315
316     /* If we have NoVirSum forces, but we do not calculate the virial,
317      * we later sum the forceWithShiftForces buffer together with
318      * the noVirSum buffer and spread the combined vsite forces at once.
319      */
320     if (vsite && (!forceOutputs->haveForceWithVirial() || stepWork.computeVirial))
321     {
322         using VirialHandling = gmx::VirtualSitesHandler::VirialHandling;
323
324         auto                 f      = forceWithShiftForces.force();
325         auto                 fshift = forceWithShiftForces.shiftForces();
326         const VirialHandling virialHandling =
327                 (stepWork.computeVirial ? VirialHandling::Pbc : VirialHandling::None);
328         vsite->spreadForces(x, f, virialHandling, fshift, nullptr, nrnb, box, wcycle);
329         forceWithShiftForces.haveSpreadVsiteForces() = true;
330     }
331
332     if (stepWork.computeVirial)
333     {
334         /* Calculation of the virial must be done after vsites! */
335         calc_virial(
336                 0, mdatoms.homenr, as_rvec_array(x.data()), forceWithShiftForces, vir_force, box, nrnb, &fr, fr.pbcType);
337     }
338 }
339
340 //! Spread, compute virial for and sum forces, when necessary
341 static void postProcessForces(const t_commrec*          cr,
342                               int64_t                   step,
343                               t_nrnb*                   nrnb,
344                               gmx_wallcycle_t           wcycle,
345                               const matrix              box,
346                               ArrayRef<const RVec>      x,
347                               ForceOutputs*             forceOutputs,
348                               tensor                    vir_force,
349                               const t_mdatoms*          mdatoms,
350                               const t_forcerec*         fr,
351                               gmx::VirtualSitesHandler* vsite,
352                               const StepWorkload&       stepWork)
353 {
354     // Extract the final output force buffer, which is also the buffer for forces with shift forces
355     ArrayRef<RVec> f = forceOutputs->forceWithShiftForces().force();
356
357     if (forceOutputs->haveForceWithVirial())
358     {
359         auto& forceWithVirial = forceOutputs->forceWithVirial();
360
361         if (vsite)
362         {
363             /* Spread the mesh force on virtual sites to the other particles...
364              * This is parallellized. MPI communication is performed
365              * if the constructing atoms aren't local.
366              */
367             GMX_ASSERT(!stepWork.computeVirial || f.data() != forceWithVirial.force_.data(),
368                        "We need separate force buffers for shift and virial forces when "
369                        "computing the virial");
370             GMX_ASSERT(!stepWork.computeVirial
371                                || forceOutputs->forceWithShiftForces().haveSpreadVsiteForces(),
372                        "We should spread the force with shift forces separately when computing "
373                        "the virial");
374             const gmx::VirtualSitesHandler::VirialHandling virialHandling =
375                     (stepWork.computeVirial ? gmx::VirtualSitesHandler::VirialHandling::NonLinear
376                                             : gmx::VirtualSitesHandler::VirialHandling::None);
377             matrix virial = { { 0 } };
378             vsite->spreadForces(x, forceWithVirial.force_, virialHandling, {}, virial, nrnb, box, wcycle);
379             forceWithVirial.addVirialContribution(virial);
380         }
381
382         if (stepWork.computeVirial)
383         {
384             /* Now add the forces, this is local */
385             sum_forces(f, forceWithVirial.force_);
386
387             /* Add the direct virial contributions */
388             GMX_ASSERT(
389                     forceWithVirial.computeVirial_,
390                     "forceWithVirial should request virial computation when we request the virial");
391             m_add(vir_force, forceWithVirial.getVirial(), vir_force);
392
393             if (debug)
394             {
395                 pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
396             }
397         }
398     }
399     else
400     {
401         GMX_ASSERT(vsite == nullptr || forceOutputs->forceWithShiftForces().haveSpreadVsiteForces(),
402                    "We should have spread the vsite forces (earlier)");
403     }
404
405     if (fr->print_force >= 0)
406     {
407         print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
408     }
409 }
410
411 static void do_nb_verlet(t_forcerec*                fr,
412                          const interaction_const_t* ic,
413                          gmx_enerdata_t*            enerd,
414                          const StepWorkload&        stepWork,
415                          const InteractionLocality  ilocality,
416                          const int                  clearF,
417                          const int64_t              step,
418                          t_nrnb*                    nrnb,
419                          gmx_wallcycle_t            wcycle)
420 {
421     if (!stepWork.computeNonbondedForces)
422     {
423         /* skip non-bonded calculation */
424         return;
425     }
426
427     nonbonded_verlet_t* nbv = fr->nbv.get();
428
429     /* GPU kernel launch overhead is already timed separately */
430     if (!nbv->useGpu())
431     {
432         /* When dynamic pair-list  pruning is requested, we need to prune
433          * at nstlistPrune steps.
434          */
435         if (nbv->isDynamicPruningStepCpu(step))
436         {
437             /* Prune the pair-list beyond fr->ic->rlistPrune using
438              * the current coordinates of the atoms.
439              */
440             wallcycle_sub_start(wcycle, ewcsNONBONDED_PRUNING);
441             nbv->dispatchPruneKernelCpu(ilocality, fr->shift_vec);
442             wallcycle_sub_stop(wcycle, ewcsNONBONDED_PRUNING);
443         }
444     }
445
446     nbv->dispatchNonbondedKernel(ilocality, *ic, stepWork, clearF, *fr, enerd, nrnb);
447 }
448
449 static inline void clearRVecs(ArrayRef<RVec> v, const bool useOpenmpThreading)
450 {
451     int nth = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, v.ssize());
452
453     /* Note that we would like to avoid this conditional by putting it
454      * into the omp pragma instead, but then we still take the full
455      * omp parallel for overhead (at least with gcc5).
456      */
457     if (!useOpenmpThreading || nth == 1)
458     {
459         for (RVec& elem : v)
460         {
461             clear_rvec(elem);
462         }
463     }
464     else
465     {
466 #pragma omp parallel for num_threads(nth) schedule(static)
467         for (gmx::index i = 0; i < v.ssize(); i++)
468         {
469             clear_rvec(v[i]);
470         }
471     }
472 }
473
474 /*! \brief Return an estimate of the average kinetic energy or 0 when unreliable
475  *
476  * \param groupOptions  Group options, containing T-coupling options
477  */
478 static real averageKineticEnergyEstimate(const t_grpopts& groupOptions)
479 {
480     real nrdfCoupled   = 0;
481     real nrdfUncoupled = 0;
482     real kineticEnergy = 0;
483     for (int g = 0; g < groupOptions.ngtc; g++)
484     {
485         if (groupOptions.tau_t[g] >= 0)
486         {
487             nrdfCoupled += groupOptions.nrdf[g];
488             kineticEnergy += groupOptions.nrdf[g] * 0.5 * groupOptions.ref_t[g] * gmx::c_boltz;
489         }
490         else
491         {
492             nrdfUncoupled += groupOptions.nrdf[g];
493         }
494     }
495
496     /* This conditional with > also catches nrdf=0 */
497     if (nrdfCoupled > nrdfUncoupled)
498     {
499         return kineticEnergy * (nrdfCoupled + nrdfUncoupled) / nrdfCoupled;
500     }
501     else
502     {
503         return 0;
504     }
505 }
506
507 /*! \brief This routine checks that the potential energy is finite.
508  *
509  * Always checks that the potential energy is finite. If step equals
510  * inputrec.init_step also checks that the magnitude of the potential energy
511  * is reasonable. Terminates with a fatal error when a check fails.
512  * Note that passing this check does not guarantee finite forces,
513  * since those use slightly different arithmetics. But in most cases
514  * there is just a narrow coordinate range where forces are not finite
515  * and energies are finite.
516  *
517  * \param[in] step      The step number, used for checking and printing
518  * \param[in] enerd     The energy data; the non-bonded group energies need to be added to
519  * enerd.term[F_EPOT] before calling this routine \param[in] inputrec  The input record
520  */
521 static void checkPotentialEnergyValidity(int64_t step, const gmx_enerdata_t& enerd, const t_inputrec& inputrec)
522 {
523     /* Threshold valid for comparing absolute potential energy against
524      * the kinetic energy. Normally one should not consider absolute
525      * potential energy values, but with a factor of one million
526      * we should never get false positives.
527      */
528     constexpr real c_thresholdFactor = 1e6;
529
530     bool energyIsNotFinite    = !std::isfinite(enerd.term[F_EPOT]);
531     real averageKineticEnergy = 0;
532     /* We only check for large potential energy at the initial step,
533      * because that is by far the most likely step for this too occur
534      * and because computing the average kinetic energy is not free.
535      * Note: nstcalcenergy >> 1 often does not allow to catch large energies
536      * before they become NaN.
537      */
538     if (step == inputrec.init_step && EI_DYNAMICS(inputrec.eI))
539     {
540         averageKineticEnergy = averageKineticEnergyEstimate(inputrec.opts);
541     }
542
543     if (energyIsNotFinite
544         || (averageKineticEnergy > 0 && enerd.term[F_EPOT] > c_thresholdFactor * averageKineticEnergy))
545     {
546         gmx_fatal(
547                 FARGS,
548                 "Step %" PRId64
549                 ": The total potential energy is %g, which is %s. The LJ and electrostatic "
550                 "contributions to the energy are %g and %g, respectively. A %s potential energy "
551                 "can be caused by overlapping interactions in bonded interactions or very large%s "
552                 "coordinate values. Usually this is caused by a badly- or non-equilibrated initial "
553                 "configuration, incorrect interactions or parameters in the topology.",
554                 step,
555                 enerd.term[F_EPOT],
556                 energyIsNotFinite ? "not finite" : "extremely high",
557                 enerd.term[F_LJ],
558                 enerd.term[F_COUL_SR],
559                 energyIsNotFinite ? "non-finite" : "very high",
560                 energyIsNotFinite ? " or Nan" : "");
561     }
562 }
563
564 /*! \brief Return true if there are special forces computed this step.
565  *
566  * The conditionals exactly correspond to those in computeSpecialForces().
567  */
568 static bool haveSpecialForces(const t_inputrec&          inputrec,
569                               const gmx::ForceProviders& forceProviders,
570                               const pull_t*              pull_work,
571                               const bool                 computeForces,
572                               const gmx_edsam*           ed)
573 {
574
575     return ((computeForces && forceProviders.hasForceProvider()) || // forceProviders
576             (inputrec.bPull && pull_have_potential(*pull_work)) ||  // pull
577             inputrec.bRot ||                                        // enforced rotation
578             (ed != nullptr) ||                                      // flooding
579             (inputrec.bIMD && computeForces));                      // IMD
580 }
581
582 /*! \brief Compute forces and/or energies for special algorithms
583  *
584  * The intention is to collect all calls to algorithms that compute
585  * forces on local atoms only and that do not contribute to the local
586  * virial sum (but add their virial contribution separately).
587  * Eventually these should likely all become ForceProviders.
588  * Within this function the intention is to have algorithms that do
589  * global communication at the end, so global barriers within the MD loop
590  * are as close together as possible.
591  *
592  * \param[in]     fplog            The log file
593  * \param[in]     cr               The communication record
594  * \param[in]     inputrec         The input record
595  * \param[in]     awh              The Awh module (nullptr if none in use).
596  * \param[in]     enforcedRotation Enforced rotation module.
597  * \param[in]     imdSession       The IMD session
598  * \param[in]     pull_work        The pull work structure.
599  * \param[in]     step             The current MD step
600  * \param[in]     t                The current time
601  * \param[in,out] wcycle           Wallcycle accounting struct
602  * \param[in,out] forceProviders   Pointer to a list of force providers
603  * \param[in]     box              The unit cell
604  * \param[in]     x                The coordinates
605  * \param[in]     mdatoms          Per atom properties
606  * \param[in]     lambda           Array of free-energy lambda values
607  * \param[in]     stepWork         Step schedule flags
608  * \param[in,out] forceWithVirialMtsLevel0  Force and virial for MTS level0 forces
609  * \param[in,out] forceWithVirialMtsLevel1  Force and virial for MTS level1 forces, can be nullptr
610  * \param[in,out] enerd            Energy buffer
611  * \param[in,out] ed               Essential dynamics pointer
612  * \param[in]     didNeighborSearch Tells if we did neighbor searching this step, used for ED sampling
613  *
614  * \todo Remove didNeighborSearch, which is used incorrectly.
615  * \todo Convert all other algorithms called here to ForceProviders.
616  */
617 static void computeSpecialForces(FILE*                          fplog,
618                                  const t_commrec*               cr,
619                                  const t_inputrec&              inputrec,
620                                  gmx::Awh*                      awh,
621                                  gmx_enfrot*                    enforcedRotation,
622                                  gmx::ImdSession*               imdSession,
623                                  pull_t*                        pull_work,
624                                  int64_t                        step,
625                                  double                         t,
626                                  gmx_wallcycle_t                wcycle,
627                                  gmx::ForceProviders*           forceProviders,
628                                  const matrix                   box,
629                                  gmx::ArrayRef<const gmx::RVec> x,
630                                  const t_mdatoms*               mdatoms,
631                                  gmx::ArrayRef<const real>      lambda,
632                                  const StepWorkload&            stepWork,
633                                  gmx::ForceWithVirial*          forceWithVirialMtsLevel0,
634                                  gmx::ForceWithVirial*          forceWithVirialMtsLevel1,
635                                  gmx_enerdata_t*                enerd,
636                                  gmx_edsam*                     ed,
637                                  bool                           didNeighborSearch)
638 {
639     /* NOTE: Currently all ForceProviders only provide forces.
640      *       When they also provide energies, remove this conditional.
641      */
642     if (stepWork.computeForces)
643     {
644         gmx::ForceProviderInput forceProviderInput(
645                 x,
646                 mdatoms->homenr,
647                 gmx::arrayRefFromArray(mdatoms->chargeA, mdatoms->homenr),
648                 gmx::arrayRefFromArray(mdatoms->massT, mdatoms->homenr),
649                 t,
650                 box,
651                 *cr);
652         gmx::ForceProviderOutput forceProviderOutput(forceWithVirialMtsLevel0, enerd);
653
654         /* Collect forces from modules */
655         forceProviders->calculateForces(forceProviderInput, &forceProviderOutput);
656     }
657
658     if (inputrec.bPull && pull_have_potential(*pull_work))
659     {
660         const int mtsLevel = forceGroupMtsLevel(inputrec.mtsLevels, gmx::MtsForceGroups::Pull);
661         if (mtsLevel == 0 || stepWork.computeSlowForces)
662         {
663             auto& forceWithVirial = (mtsLevel == 0) ? forceWithVirialMtsLevel0 : forceWithVirialMtsLevel1;
664             pull_potential_wrapper(
665                     cr, inputrec, box, x, forceWithVirial, mdatoms, enerd, pull_work, lambda.data(), t, wcycle);
666         }
667     }
668     if (awh)
669     {
670         const int mtsLevel = forceGroupMtsLevel(inputrec.mtsLevels, gmx::MtsForceGroups::Pull);
671         if (mtsLevel == 0 || stepWork.computeSlowForces)
672         {
673             const bool needForeignEnergyDifferences = awh->needForeignEnergyDifferences(step);
674             std::vector<double> foreignLambdaDeltaH, foreignLambdaDhDl;
675             if (needForeignEnergyDifferences)
676             {
677                 enerd->foreignLambdaTerms.finalizePotentialContributions(
678                         enerd->dvdl_lin, lambda, *inputrec.fepvals);
679                 std::tie(foreignLambdaDeltaH, foreignLambdaDhDl) = enerd->foreignLambdaTerms.getTerms(cr);
680             }
681
682             auto& forceWithVirial = (mtsLevel == 0) ? forceWithVirialMtsLevel0 : forceWithVirialMtsLevel1;
683             enerd->term[F_COM_PULL] += awh->applyBiasForcesAndUpdateBias(inputrec.pbcType,
684                                                                          mdatoms->massT,
685                                                                          foreignLambdaDeltaH,
686                                                                          foreignLambdaDhDl,
687                                                                          box,
688                                                                          forceWithVirial,
689                                                                          t,
690                                                                          step,
691                                                                          wcycle,
692                                                                          fplog);
693         }
694     }
695
696     rvec* f = as_rvec_array(forceWithVirialMtsLevel0->force_.data());
697
698     /* Add the forces from enforced rotation potentials (if any) */
699     if (inputrec.bRot)
700     {
701         wallcycle_start(wcycle, ewcROTadd);
702         enerd->term[F_COM_PULL] += add_rot_forces(enforcedRotation, f, cr, step, t);
703         wallcycle_stop(wcycle, ewcROTadd);
704     }
705
706     if (ed)
707     {
708         /* Note that since init_edsam() is called after the initialization
709          * of forcerec, edsam doesn't request the noVirSum force buffer.
710          * Thus if no other algorithm (e.g. PME) requires it, the forces
711          * here will contribute to the virial.
712          */
713         do_flood(cr, inputrec, as_rvec_array(x.data()), f, ed, box, step, didNeighborSearch);
714     }
715
716     /* Add forces from interactive molecular dynamics (IMD), if any */
717     if (inputrec.bIMD && stepWork.computeForces)
718     {
719         imdSession->applyForces(f);
720     }
721 }
722
723 /*! \brief Launch the prepare_step and spread stages of PME GPU.
724  *
725  * \param[in]  pmedata              The PME structure
726  * \param[in]  box                  The box matrix
727  * \param[in]  stepWork             Step schedule flags
728  * \param[in]  xReadyOnDevice       Event synchronizer indicating that the coordinates are ready in the device memory.
729  * \param[in]  lambdaQ              The Coulomb lambda of the current state.
730  * \param[in]  wcycle               The wallcycle structure
731  */
732 static inline void launchPmeGpuSpread(gmx_pme_t*            pmedata,
733                                       const matrix          box,
734                                       const StepWorkload&   stepWork,
735                                       GpuEventSynchronizer* xReadyOnDevice,
736                                       const real            lambdaQ,
737                                       gmx_wallcycle_t       wcycle)
738 {
739     pme_gpu_prepare_computation(pmedata, box, wcycle, stepWork);
740     pme_gpu_launch_spread(pmedata, xReadyOnDevice, wcycle, lambdaQ);
741 }
742
743 /*! \brief Launch the FFT and gather stages of PME GPU
744  *
745  * This function only implements setting the output forces (no accumulation).
746  *
747  * \param[in]  pmedata        The PME structure
748  * \param[in]  lambdaQ        The Coulomb lambda of the current system state.
749  * \param[in]  wcycle         The wallcycle structure
750  * \param[in]  stepWork       Step schedule flags
751  */
752 static void launchPmeGpuFftAndGather(gmx_pme_t*               pmedata,
753                                      const real               lambdaQ,
754                                      gmx_wallcycle_t          wcycle,
755                                      const gmx::StepWorkload& stepWork)
756 {
757     pme_gpu_launch_complex_transforms(pmedata, wcycle, stepWork);
758     pme_gpu_launch_gather(pmedata, wcycle, lambdaQ);
759 }
760
761 /*! \brief
762  *  Polling wait for either of the PME or nonbonded GPU tasks.
763  *
764  * Instead of a static order in waiting for GPU tasks, this function
765  * polls checking which of the two tasks completes first, and does the
766  * associated force buffer reduction overlapped with the other task.
767  * By doing that, unlike static scheduling order, it can always overlap
768  * one of the reductions, regardless of the GPU task completion order.
769  *
770  * \param[in]     nbv              Nonbonded verlet structure
771  * \param[in,out] pmedata          PME module data
772  * \param[in,out] forceOutputsNonbonded  Force outputs for the non-bonded forces and shift forces
773  * \param[in,out] forceOutputsPme  Force outputs for the PME forces and virial
774  * \param[in,out] enerd            Energy data structure results are reduced into
775  * \param[in]     lambdaQ          The Coulomb lambda of the current system state.
776  * \param[in]     stepWork         Step schedule flags
777  * \param[in]     wcycle           The wallcycle structure
778  */
779 static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t* nbv,
780                                         gmx_pme_t*          pmedata,
781                                         gmx::ForceOutputs*  forceOutputsNonbonded,
782                                         gmx::ForceOutputs*  forceOutputsPme,
783                                         gmx_enerdata_t*     enerd,
784                                         const real          lambdaQ,
785                                         const StepWorkload& stepWork,
786                                         gmx_wallcycle_t     wcycle)
787 {
788     bool isPmeGpuDone = false;
789     bool isNbGpuDone  = false;
790
791     gmx::ArrayRef<const gmx::RVec> pmeGpuForces;
792
793     while (!isPmeGpuDone || !isNbGpuDone)
794     {
795         if (!isPmeGpuDone)
796         {
797             GpuTaskCompletion completionType =
798                     (isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
799             isPmeGpuDone = pme_gpu_try_finish_task(
800                     pmedata, stepWork, wcycle, &forceOutputsPme->forceWithVirial(), enerd, lambdaQ, completionType);
801         }
802
803         if (!isNbGpuDone)
804         {
805             auto&             forceBuffersNonbonded = forceOutputsNonbonded->forceWithShiftForces();
806             GpuTaskCompletion completionType =
807                     (isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
808             isNbGpuDone = Nbnxm::gpu_try_finish_task(
809                     nbv->gpu_nbv,
810                     stepWork,
811                     AtomLocality::Local,
812                     enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::LJSR].data(),
813                     enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::CoulombSR].data(),
814                     forceBuffersNonbonded.shiftForces(),
815                     completionType,
816                     wcycle);
817
818             if (isNbGpuDone)
819             {
820                 nbv->atomdata_add_nbat_f_to_f(AtomLocality::Local, forceBuffersNonbonded.force());
821             }
822         }
823     }
824 }
825
826 /*! \brief Set up the different force buffers; also does clearing.
827  *
828  * \param[in] forceHelperBuffers  Helper force buffers
829  * \param[in] force     force array
830  * \param[in] stepWork  Step schedule flags
831  * \param[out] wcycle   wallcycle recording structure
832  *
833  * \returns             Cleared force output structure
834  */
835 static ForceOutputs setupForceOutputs(ForceHelperBuffers*                 forceHelperBuffers,
836                                       gmx::ArrayRefWithPadding<gmx::RVec> force,
837                                       const StepWorkload&                 stepWork,
838                                       gmx_wallcycle_t                     wcycle)
839 {
840     wallcycle_sub_start(wcycle, ewcsCLEAR_FORCE_BUFFER);
841
842     /* NOTE: We assume fr->shiftForces is all zeros here */
843     gmx::ForceWithShiftForces forceWithShiftForces(
844             force, stepWork.computeVirial, forceHelperBuffers->shiftForces());
845
846     if (stepWork.computeForces)
847     {
848         /* Clear the short- and long-range forces */
849         clearRVecs(forceWithShiftForces.force(), true);
850
851         /* Clear the shift forces */
852         clearRVecs(forceWithShiftForces.shiftForces(), false);
853     }
854
855     /* If we need to compute the virial, we might need a separate
856      * force buffer for algorithms for which the virial is calculated
857      * directly, such as PME. Otherwise, forceWithVirial uses the
858      * the same force (f in legacy calls) buffer as other algorithms.
859      */
860     const bool useSeparateForceWithVirialBuffer =
861             (stepWork.computeForces
862              && (stepWork.computeVirial && forceHelperBuffers->haveDirectVirialContributions()));
863     /* forceWithVirial uses the local atom range only */
864     gmx::ForceWithVirial forceWithVirial(
865             useSeparateForceWithVirialBuffer ? forceHelperBuffers->forceBufferForDirectVirialContributions()
866                                              : force.unpaddedArrayRef(),
867             stepWork.computeVirial);
868
869     if (useSeparateForceWithVirialBuffer)
870     {
871         /* TODO: update comment
872          * We only compute forces on local atoms. Note that vsites can
873          * spread to non-local atoms, but that part of the buffer is
874          * cleared separately in the vsite spreading code.
875          */
876         clearRVecs(forceWithVirial.force_, true);
877     }
878
879     wallcycle_sub_stop(wcycle, ewcsCLEAR_FORCE_BUFFER);
880
881     return ForceOutputs(
882             forceWithShiftForces, forceHelperBuffers->haveDirectVirialContributions(), forceWithVirial);
883 }
884
885
886 /*! \brief Set up flags that have the lifetime of the domain indicating what type of work is there to compute.
887  */
888 static DomainLifetimeWorkload setupDomainLifetimeWorkload(const t_inputrec&         inputrec,
889                                                           const t_forcerec&         fr,
890                                                           const pull_t*             pull_work,
891                                                           const gmx_edsam*          ed,
892                                                           const t_mdatoms&          mdatoms,
893                                                           const SimulationWorkload& simulationWork,
894                                                           const StepWorkload&       stepWork)
895 {
896     DomainLifetimeWorkload domainWork;
897     // Note that haveSpecialForces is constant over the whole run
898     domainWork.haveSpecialForces =
899             haveSpecialForces(inputrec, *fr.forceProviders, pull_work, stepWork.computeForces, ed);
900     domainWork.haveCpuListedForceWork = false;
901     domainWork.haveCpuBondedWork      = false;
902     for (const auto& listedForces : fr.listedForces)
903     {
904         if (listedForces.haveCpuListedForces(*fr.fcdata))
905         {
906             domainWork.haveCpuListedForceWork = true;
907         }
908         if (listedForces.haveCpuBondeds())
909         {
910             domainWork.haveCpuBondedWork = true;
911         }
912     }
913     domainWork.haveGpuBondedWork = ((fr.gpuBonded != nullptr) && fr.gpuBonded->haveInteractions());
914     // Note that haveFreeEnergyWork is constant over the whole run
915     domainWork.haveFreeEnergyWork =
916             (fr.efep != FreeEnergyPerturbationType::No && mdatoms.nPerturbed != 0);
917     // We assume we have local force work if there are CPU
918     // force tasks including PME or nonbondeds.
919     domainWork.haveCpuLocalForceWork =
920             domainWork.haveSpecialForces || domainWork.haveCpuListedForceWork
921             || domainWork.haveFreeEnergyWork || simulationWork.useCpuNonbonded || simulationWork.useCpuPme
922             || simulationWork.haveEwaldSurfaceContribution || inputrec.nwall > 0;
923
924     return domainWork;
925 }
926
927 /*! \brief Set up force flag stuct from the force bitmask.
928  *
929  * \param[in]      legacyFlags          Force bitmask flags used to construct the new flags
930  * \param[in]      mtsLevels            The multiple time-stepping levels, either empty or 2 levels
931  * \param[in]      step                 The current MD step
932  * \param[in]      simulationWork       Simulation workload description.
933  * \param[in]      rankHasPmeDuty       If this rank computes PME.
934  *
935  * \returns New Stepworkload description.
936  */
937 static StepWorkload setupStepWorkload(const int                     legacyFlags,
938                                       ArrayRef<const gmx::MtsLevel> mtsLevels,
939                                       const int64_t                 step,
940                                       const SimulationWorkload&     simulationWork,
941                                       const bool                    rankHasPmeDuty)
942 {
943     GMX_ASSERT(mtsLevels.empty() || mtsLevels.size() == 2, "Expect 0 or 2 MTS levels");
944     const bool computeSlowForces = (mtsLevels.empty() || step % mtsLevels[1].stepFactor == 0);
945
946     StepWorkload flags;
947     flags.stateChanged        = ((legacyFlags & GMX_FORCE_STATECHANGED) != 0);
948     flags.haveDynamicBox      = ((legacyFlags & GMX_FORCE_DYNAMICBOX) != 0);
949     flags.doNeighborSearch    = ((legacyFlags & GMX_FORCE_NS) != 0);
950     flags.computeSlowForces   = computeSlowForces;
951     flags.computeVirial       = ((legacyFlags & GMX_FORCE_VIRIAL) != 0);
952     flags.computeEnergy       = ((legacyFlags & GMX_FORCE_ENERGY) != 0);
953     flags.computeForces       = ((legacyFlags & GMX_FORCE_FORCES) != 0);
954     flags.computeListedForces = ((legacyFlags & GMX_FORCE_LISTED) != 0);
955     flags.computeNonbondedForces =
956             ((legacyFlags & GMX_FORCE_NONBONDED) != 0) && simulationWork.computeNonbonded
957             && !(simulationWork.computeNonbondedAtMtsLevel1 && !computeSlowForces);
958     flags.computeDhdl = ((legacyFlags & GMX_FORCE_DHDL) != 0);
959
960     if (simulationWork.useGpuBufferOps)
961     {
962         GMX_ASSERT(simulationWork.useGpuNonbonded,
963                    "Can only offload buffer ops if nonbonded computation is also offloaded");
964     }
965     flags.useGpuXBufferOps = simulationWork.useGpuBufferOps;
966     // on virial steps the CPU reduction path is taken
967     flags.useGpuFBufferOps = simulationWork.useGpuBufferOps && !flags.computeVirial;
968     flags.useGpuPmeFReduction = flags.computeSlowForces && flags.useGpuFBufferOps && simulationWork.useGpuPme
969                                 && (rankHasPmeDuty || simulationWork.useGpuPmePpCommunication);
970     flags.useGpuXHalo = simulationWork.useGpuHaloExchange;
971     flags.useGpuFHalo = simulationWork.useGpuHaloExchange && flags.useGpuFBufferOps;
972
973     return flags;
974 }
975
976
977 /* \brief Launch end-of-step GPU tasks: buffer clearing and rolling pruning.
978  *
979  * TODO: eliminate \p useGpuPmeOnThisRank when this is
980  * incorporated in DomainLifetimeWorkload.
981  */
982 static void launchGpuEndOfStepTasks(nonbonded_verlet_t*               nbv,
983                                     gmx::GpuBonded*                   gpuBonded,
984                                     gmx_pme_t*                        pmedata,
985                                     gmx_enerdata_t*                   enerd,
986                                     const gmx::MdrunScheduleWorkload& runScheduleWork,
987                                     bool                              useGpuPmeOnThisRank,
988                                     int64_t                           step,
989                                     gmx_wallcycle_t                   wcycle)
990 {
991     if (runScheduleWork.simulationWork.useGpuNonbonded && runScheduleWork.stepWork.computeNonbondedForces)
992     {
993         /* Launch pruning before buffer clearing because the API overhead of the
994          * clear kernel launches can leave the GPU idle while it could be running
995          * the prune kernel.
996          */
997         if (nbv->isDynamicPruningStepGpu(step))
998         {
999             nbv->dispatchPruneKernelGpu(step);
1000         }
1001
1002         /* now clear the GPU outputs while we finish the step on the CPU */
1003         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1004         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1005         Nbnxm::gpu_clear_outputs(nbv->gpu_nbv, runScheduleWork.stepWork.computeVirial);
1006         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1007         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1008     }
1009
1010     if (useGpuPmeOnThisRank)
1011     {
1012         pme_gpu_reinit_computation(pmedata, wcycle);
1013     }
1014
1015     if (runScheduleWork.domainWork.haveGpuBondedWork && runScheduleWork.stepWork.computeEnergy)
1016     {
1017         // in principle this should be included in the DD balancing region,
1018         // but generally it is infrequent so we'll omit it for the sake of
1019         // simpler code
1020         gpuBonded->waitAccumulateEnergyTerms(enerd);
1021
1022         gpuBonded->clearEnergies();
1023     }
1024 }
1025
1026 //! \brief Data structure to hold dipole-related data and staging arrays
1027 struct DipoleData
1028 {
1029     //! Dipole staging for fast summing over MPI
1030     gmx::DVec muStaging[2] = { { 0.0, 0.0, 0.0 } };
1031     //! Dipole staging for states A and B (index 0 and 1 resp.)
1032     gmx::RVec muStateAB[2] = { { 0.0_real, 0.0_real, 0.0_real } };
1033 };
1034
1035
1036 static void reduceAndUpdateMuTot(DipoleData*                   dipoleData,
1037                                  const t_commrec*              cr,
1038                                  const bool                    haveFreeEnergy,
1039                                  gmx::ArrayRef<const real>     lambda,
1040                                  rvec                          muTotal,
1041                                  const DDBalanceRegionHandler& ddBalanceRegionHandler)
1042 {
1043     if (PAR(cr))
1044     {
1045         gmx_sumd(2 * DIM, dipoleData->muStaging[0], cr);
1046         ddBalanceRegionHandler.reopenRegionCpu();
1047     }
1048     for (int i = 0; i < 2; i++)
1049     {
1050         for (int j = 0; j < DIM; j++)
1051         {
1052             dipoleData->muStateAB[i][j] = dipoleData->muStaging[i][j];
1053         }
1054     }
1055
1056     if (!haveFreeEnergy)
1057     {
1058         copy_rvec(dipoleData->muStateAB[0], muTotal);
1059     }
1060     else
1061     {
1062         for (int j = 0; j < DIM; j++)
1063         {
1064             muTotal[j] = (1.0 - lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)])
1065                                  * dipoleData->muStateAB[0][j]
1066                          + lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)]
1067                                    * dipoleData->muStateAB[1][j];
1068         }
1069     }
1070 }
1071
1072 /*! \brief Combines MTS level0 and level1 force buffes into a full and MTS-combined force buffer.
1073  *
1074  * \param[in]     numAtoms        The number of atoms to combine forces for
1075  * \param[in,out] forceMtsLevel0  Input: F_level0, output: F_level0 + F_level1
1076  * \param[in,out] forceMts        Input: F_level1, output: F_level0 + mtsFactor * F_level1
1077  * \param[in]     mtsFactor       The factor between the level0 and level1 time step
1078  */
1079 static void combineMtsForces(const int      numAtoms,
1080                              ArrayRef<RVec> forceMtsLevel0,
1081                              ArrayRef<RVec> forceMts,
1082                              const real     mtsFactor)
1083 {
1084     const int gmx_unused numThreads = gmx_omp_nthreads_get(emntDefault);
1085 #pragma omp parallel for num_threads(numThreads) schedule(static)
1086     for (int i = 0; i < numAtoms; i++)
1087     {
1088         const RVec forceMtsLevel0Tmp = forceMtsLevel0[i];
1089         forceMtsLevel0[i] += forceMts[i];
1090         forceMts[i] = forceMtsLevel0Tmp + mtsFactor * forceMts[i];
1091     }
1092 }
1093
1094 /*! \brief Setup for the local and non-local GPU force reductions:
1095  * reinitialization plus the registration of forces and dependencies.
1096  *
1097  * \param [in] runScheduleWork               Schedule workload flag structure
1098  * \param [in] cr                            Communication record object
1099  * \param [in] fr                            Force record object
1100  */
1101 static void setupGpuForceReductions(gmx::MdrunScheduleWorkload* runScheduleWork,
1102                                     const t_commrec*            cr,
1103                                     t_forcerec*                 fr)
1104 {
1105
1106     nonbonded_verlet_t*          nbv      = fr->nbv.get();
1107     gmx::StatePropagatorDataGpu* stateGpu = fr->stateGpu;
1108
1109     // (re-)initialize local GPU force reduction
1110     const bool accumulate =
1111             runScheduleWork->domainWork.haveCpuLocalForceWork || havePPDomainDecomposition(cr);
1112     const int atomStart = 0;
1113     fr->gpuForceReduction[gmx::AtomLocality::Local]->reinit(stateGpu->getForces(),
1114                                                             nbv->getNumAtoms(AtomLocality::Local),
1115                                                             nbv->getGridIndices(),
1116                                                             atomStart,
1117                                                             accumulate,
1118                                                             stateGpu->fReducedOnDevice());
1119
1120     // register forces and add dependencies
1121     fr->gpuForceReduction[gmx::AtomLocality::Local]->registerNbnxmForce(nbv->getGpuForces());
1122
1123     if (runScheduleWork->simulationWork.useGpuPme
1124         && (thisRankHasDuty(cr, DUTY_PME) || runScheduleWork->simulationWork.useGpuPmePpCommunication))
1125     {
1126         DeviceBuffer<gmx::RVec> forcePtr =
1127                 thisRankHasDuty(cr, DUTY_PME) ? pme_gpu_get_device_f(fr->pmedata)
1128                                               :                    // PME force buffer on same GPU
1129                         fr->pmePpCommGpu->getGpuForceStagingPtr(); // buffer received from other GPU
1130         fr->gpuForceReduction[gmx::AtomLocality::Local]->registerRvecForce(forcePtr);
1131
1132         GpuEventSynchronizer* const pmeSynchronizer =
1133                 (thisRankHasDuty(cr, DUTY_PME) ? pme_gpu_get_f_ready_synchronizer(fr->pmedata)
1134                                                : // PME force buffer on same GPU
1135                          fr->pmePpCommGpu->getForcesReadySynchronizer()); // buffer received from other GPU
1136         fr->gpuForceReduction[gmx::AtomLocality::Local]->addDependency(pmeSynchronizer);
1137     }
1138
1139     if ((runScheduleWork->domainWork.haveCpuLocalForceWork || havePPDomainDecomposition(cr))
1140         && !runScheduleWork->simulationWork.useGpuHaloExchange)
1141     {
1142         auto forcesReadyLocality = havePPDomainDecomposition(cr) ? AtomLocality::Local : AtomLocality::All;
1143         const bool useGpuForceBufferOps = true;
1144         fr->gpuForceReduction[gmx::AtomLocality::Local]->addDependency(
1145                 stateGpu->getForcesReadyOnDeviceEvent(forcesReadyLocality, useGpuForceBufferOps));
1146     }
1147
1148     if (runScheduleWork->simulationWork.useGpuHaloExchange)
1149     {
1150         fr->gpuForceReduction[gmx::AtomLocality::Local]->addDependency(
1151                 cr->dd->gpuHaloExchange[0][0]->getForcesReadyOnDeviceEvent());
1152     }
1153
1154     if (havePPDomainDecomposition(cr))
1155     {
1156         // (re-)initialize non-local GPU force reduction
1157         const bool accumulate = runScheduleWork->domainWork.haveCpuBondedWork
1158                                 || runScheduleWork->domainWork.haveFreeEnergyWork;
1159         const int atomStart = dd_numHomeAtoms(*cr->dd);
1160         fr->gpuForceReduction[gmx::AtomLocality::NonLocal]->reinit(stateGpu->getForces(),
1161                                                                    nbv->getNumAtoms(AtomLocality::NonLocal),
1162                                                                    nbv->getGridIndices(),
1163                                                                    atomStart,
1164                                                                    accumulate);
1165
1166         // register forces and add dependencies
1167         fr->gpuForceReduction[gmx::AtomLocality::NonLocal]->registerNbnxmForce(nbv->getGpuForces());
1168         if (runScheduleWork->domainWork.haveCpuBondedWork || runScheduleWork->domainWork.haveFreeEnergyWork)
1169         {
1170             fr->gpuForceReduction[gmx::AtomLocality::NonLocal]->addDependency(
1171                     stateGpu->getForcesReadyOnDeviceEvent(AtomLocality::NonLocal, true));
1172         }
1173     }
1174 }
1175
1176
1177 void do_force(FILE*                               fplog,
1178               const t_commrec*                    cr,
1179               const gmx_multisim_t*               ms,
1180               const t_inputrec&                   inputrec,
1181               gmx::Awh*                           awh,
1182               gmx_enfrot*                         enforcedRotation,
1183               gmx::ImdSession*                    imdSession,
1184               pull_t*                             pull_work,
1185               int64_t                             step,
1186               t_nrnb*                             nrnb,
1187               gmx_wallcycle_t                     wcycle,
1188               const gmx_localtop_t*               top,
1189               const matrix                        box,
1190               gmx::ArrayRefWithPadding<gmx::RVec> x,
1191               const history_t*                    hist,
1192               gmx::ForceBuffersView*              forceView,
1193               tensor                              vir_force,
1194               const t_mdatoms*                    mdatoms,
1195               gmx_enerdata_t*                     enerd,
1196               gmx::ArrayRef<const real>           lambda,
1197               t_forcerec*                         fr,
1198               gmx::MdrunScheduleWorkload*         runScheduleWork,
1199               gmx::VirtualSitesHandler*           vsite,
1200               rvec                                muTotal,
1201               double                              t,
1202               gmx_edsam*                          ed,
1203               int                                 legacyFlags,
1204               const DDBalanceRegionHandler&       ddBalanceRegionHandler)
1205 {
1206     auto force = forceView->forceWithPadding();
1207     GMX_ASSERT(force.unpaddedArrayRef().ssize() >= fr->natoms_force_constr,
1208                "The size of the force buffer should be at least the number of atoms to compute "
1209                "forces for");
1210
1211     nonbonded_verlet_t*  nbv = fr->nbv.get();
1212     interaction_const_t* ic  = fr->ic.get();
1213
1214     gmx::StatePropagatorDataGpu* stateGpu = fr->stateGpu;
1215
1216     const SimulationWorkload& simulationWork = runScheduleWork->simulationWork;
1217
1218     runScheduleWork->stepWork = setupStepWorkload(
1219             legacyFlags, inputrec.mtsLevels, step, simulationWork, thisRankHasDuty(cr, DUTY_PME));
1220     const StepWorkload& stepWork = runScheduleWork->stepWork;
1221
1222     const bool useGpuPmeOnThisRank =
1223             simulationWork.useGpuPme && thisRankHasDuty(cr, DUTY_PME) && stepWork.computeSlowForces;
1224
1225     /* At a search step we need to start the first balancing region
1226      * somewhere early inside the step after communication during domain
1227      * decomposition (and not during the previous step as usual).
1228      */
1229     if (stepWork.doNeighborSearch)
1230     {
1231         ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::yes);
1232     }
1233
1234     clear_mat(vir_force);
1235
1236     if (fr->pbcType != PbcType::No)
1237     {
1238         /* Compute shift vectors every step,
1239          * because of pressure coupling or box deformation!
1240          */
1241         if (stepWork.haveDynamicBox && stepWork.stateChanged)
1242         {
1243             calc_shifts(box, fr->shift_vec);
1244         }
1245
1246         const bool fillGrid = (stepWork.doNeighborSearch && stepWork.stateChanged);
1247         const bool calcCGCM = (fillGrid && !DOMAINDECOMP(cr));
1248         if (calcCGCM)
1249         {
1250             put_atoms_in_box_omp(fr->pbcType,
1251                                  box,
1252                                  x.unpaddedArrayRef().subArray(0, mdatoms->homenr),
1253                                  gmx_omp_nthreads_get(emntDefault));
1254             inc_nrnb(nrnb, eNR_SHIFTX, mdatoms->homenr);
1255         }
1256     }
1257
1258     nbnxn_atomdata_copy_shiftvec(stepWork.haveDynamicBox, fr->shift_vec, nbv->nbat.get());
1259
1260     const bool pmeSendCoordinatesFromGpu =
1261             GMX_MPI && simulationWork.useGpuPmePpCommunication && !(stepWork.doNeighborSearch);
1262     const bool reinitGpuPmePpComms =
1263             GMX_MPI && simulationWork.useGpuPmePpCommunication && (stepWork.doNeighborSearch);
1264
1265     const auto localXReadyOnDevice = (useGpuPmeOnThisRank || simulationWork.useGpuBufferOps)
1266                                              ? stateGpu->getCoordinatesReadyOnDeviceEvent(
1267                                                        AtomLocality::Local, simulationWork, stepWork)
1268                                              : nullptr;
1269
1270     // Copy coordinate from the GPU if update is on the GPU and there
1271     // are forces to be computed on the CPU, or for the computation of
1272     // virial, or if host-side data will be transferred from this task
1273     // to a remote task for halo exchange or PME-PP communication. At
1274     // search steps the current coordinates are already on the host,
1275     // hence copy is not needed.
1276     const bool haveHostPmePpComms =
1277             !thisRankHasDuty(cr, DUTY_PME) && !simulationWork.useGpuPmePpCommunication;
1278
1279     GMX_ASSERT(simulationWork.useGpuHaloExchange
1280                        == ((cr->dd != nullptr) && (!cr->dd->gpuHaloExchange[0].empty())),
1281                "The GPU halo exchange is active, but it has not been constructed.");
1282     const bool haveHostHaloExchangeComms =
1283             havePPDomainDecomposition(cr) && !simulationWork.useGpuHaloExchange;
1284
1285     bool gmx_used_in_debug haveCopiedXFromGpu = false;
1286     if (simulationWork.useGpuUpdate && !stepWork.doNeighborSearch
1287         && (runScheduleWork->domainWork.haveCpuLocalForceWork || stepWork.computeVirial
1288             || haveHostPmePpComms || haveHostHaloExchangeComms))
1289     {
1290         stateGpu->copyCoordinatesFromGpu(x.unpaddedArrayRef(), AtomLocality::Local);
1291         haveCopiedXFromGpu = true;
1292     }
1293
1294     // If coordinates are to be sent to PME task from CPU memory, perform that send here.
1295     // Otherwise the send will occur after H2D coordinate transfer.
1296     if (GMX_MPI && !thisRankHasDuty(cr, DUTY_PME) && !pmeSendCoordinatesFromGpu && stepWork.computeSlowForces)
1297     {
1298         /* Send particle coordinates to the pme nodes */
1299         if (!stepWork.doNeighborSearch && simulationWork.useGpuUpdate)
1300         {
1301             stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local);
1302         }
1303
1304         gmx_pme_send_coordinates(fr,
1305                                  cr,
1306                                  box,
1307                                  as_rvec_array(x.unpaddedArrayRef().data()),
1308                                  lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)],
1309                                  lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Vdw)],
1310                                  (stepWork.computeVirial || stepWork.computeEnergy),
1311                                  step,
1312                                  simulationWork.useGpuPmePpCommunication,
1313                                  reinitGpuPmePpComms,
1314                                  pmeSendCoordinatesFromGpu,
1315                                  localXReadyOnDevice,
1316                                  wcycle);
1317     }
1318
1319     // Coordinates on the device are needed if PME or BufferOps are offloaded.
1320     // The local coordinates can be copied right away.
1321     // NOTE: Consider moving this copy to right after they are updated and constrained,
1322     //       if the later is not offloaded.
1323     if (useGpuPmeOnThisRank || stepWork.useGpuXBufferOps)
1324     {
1325         if (stepWork.doNeighborSearch)
1326         {
1327             // TODO refactor this to do_md, after partitioning.
1328             stateGpu->reinit(mdatoms->homenr,
1329                              cr->dd != nullptr ? dd_numAtomsZones(*cr->dd) : mdatoms->homenr);
1330             if (useGpuPmeOnThisRank)
1331             {
1332                 // TODO: This should be moved into PME setup function ( pme_gpu_prepare_computation(...) )
1333                 pme_gpu_set_device_x(fr->pmedata, stateGpu->getCoordinates());
1334             }
1335         }
1336         // We need to copy coordinates when:
1337         // 1. Update is not offloaded
1338         // 2. The buffers were reinitialized on search step
1339         if (!simulationWork.useGpuUpdate || stepWork.doNeighborSearch)
1340         {
1341             GMX_ASSERT(stateGpu != nullptr, "stateGpu should not be null");
1342             stateGpu->copyCoordinatesToGpu(x.unpaddedArrayRef(), AtomLocality::Local);
1343         }
1344     }
1345
1346     // If coordinates are to be sent to PME task from GPU memory, perform that send here.
1347     // Otherwise the send will occur before the H2D coordinate transfer.
1348     if (!thisRankHasDuty(cr, DUTY_PME) && pmeSendCoordinatesFromGpu)
1349     {
1350         /* Send particle coordinates to the pme nodes */
1351         gmx_pme_send_coordinates(fr,
1352                                  cr,
1353                                  box,
1354                                  as_rvec_array(x.unpaddedArrayRef().data()),
1355                                  lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)],
1356                                  lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Vdw)],
1357                                  (stepWork.computeVirial || stepWork.computeEnergy),
1358                                  step,
1359                                  simulationWork.useGpuPmePpCommunication,
1360                                  reinitGpuPmePpComms,
1361                                  pmeSendCoordinatesFromGpu,
1362                                  localXReadyOnDevice,
1363                                  wcycle);
1364     }
1365
1366     if (useGpuPmeOnThisRank)
1367     {
1368         launchPmeGpuSpread(fr->pmedata,
1369                            box,
1370                            stepWork,
1371                            localXReadyOnDevice,
1372                            lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)],
1373                            wcycle);
1374     }
1375
1376     const gmx::DomainLifetimeWorkload& domainWork = runScheduleWork->domainWork;
1377
1378     /* do gridding for pair search */
1379     if (stepWork.doNeighborSearch)
1380     {
1381         if (fr->wholeMoleculeTransform && stepWork.stateChanged)
1382         {
1383             fr->wholeMoleculeTransform->updateForAtomPbcJumps(x.unpaddedArrayRef(), box);
1384         }
1385
1386         wallcycle_start(wcycle, ewcNS);
1387         if (!DOMAINDECOMP(cr))
1388         {
1389             const rvec vzero       = { 0.0_real, 0.0_real, 0.0_real };
1390             const rvec boxDiagonal = { box[XX][XX], box[YY][YY], box[ZZ][ZZ] };
1391             wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL);
1392             nbnxn_put_on_grid(nbv,
1393                               box,
1394                               0,
1395                               vzero,
1396                               boxDiagonal,
1397                               nullptr,
1398                               { 0, mdatoms->homenr },
1399                               -1,
1400                               fr->cginfo,
1401                               x.unpaddedArrayRef(),
1402                               0,
1403                               nullptr);
1404             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL);
1405         }
1406         else
1407         {
1408             wallcycle_sub_start(wcycle, ewcsNBS_GRID_NONLOCAL);
1409             nbnxn_put_on_grid_nonlocal(nbv, domdec_zones(cr->dd), fr->cginfo, x.unpaddedArrayRef());
1410             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_NONLOCAL);
1411         }
1412
1413         nbv->setAtomProperties(gmx::constArrayRefFromArray(mdatoms->typeA, mdatoms->nr),
1414                                gmx::constArrayRefFromArray(mdatoms->chargeA, mdatoms->nr),
1415                                fr->cginfo);
1416
1417         wallcycle_stop(wcycle, ewcNS);
1418
1419         /* initialize the GPU nbnxm atom data and bonded data structures */
1420         if (simulationWork.useGpuNonbonded)
1421         {
1422             // Note: cycle counting only nononbondeds, gpuBonded counts internally
1423             wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1424             wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1425             Nbnxm::gpu_init_atomdata(nbv->gpu_nbv, nbv->nbat.get());
1426             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1427             wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1428
1429             if (fr->gpuBonded)
1430             {
1431                 /* Now we put all atoms on the grid, we can assign bonded
1432                  * interactions to the GPU, where the grid order is
1433                  * needed. Also the xq, f and fshift device buffers have
1434                  * been reallocated if needed, so the bonded code can
1435                  * learn about them. */
1436                 // TODO the xq, f, and fshift buffers are now shared
1437                 // resources, so they should be maintained by a
1438                 // higher-level object than the nb module.
1439                 fr->gpuBonded->updateInteractionListsAndDeviceBuffers(nbv->getGridIndices(),
1440                                                                       top->idef,
1441                                                                       Nbnxm::gpu_get_xq(nbv->gpu_nbv),
1442                                                                       Nbnxm::gpu_get_f(nbv->gpu_nbv),
1443                                                                       Nbnxm::gpu_get_fshift(nbv->gpu_nbv));
1444             }
1445         }
1446
1447         // Need to run after the GPU-offload bonded interaction lists
1448         // are set up to be able to determine whether there is bonded work.
1449         runScheduleWork->domainWork = setupDomainLifetimeWorkload(
1450                 inputrec, *fr, pull_work, ed, *mdatoms, simulationWork, stepWork);
1451
1452         wallcycle_start_nocount(wcycle, ewcNS);
1453         wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_LOCAL);
1454         /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1455         nbv->constructPairlist(InteractionLocality::Local, top->excls, step, nrnb);
1456
1457         nbv->setupGpuShortRangeWork(fr->gpuBonded, InteractionLocality::Local);
1458
1459         wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_LOCAL);
1460         wallcycle_stop(wcycle, ewcNS);
1461
1462         if (stepWork.useGpuXBufferOps)
1463         {
1464             nbv->atomdata_init_copy_x_to_nbat_x_gpu();
1465         }
1466
1467         if (simulationWork.useGpuBufferOps)
1468         {
1469             setupGpuForceReductions(runScheduleWork, cr, fr);
1470         }
1471     }
1472     else if (!EI_TPI(inputrec.eI) && stepWork.computeNonbondedForces)
1473     {
1474         if (stepWork.useGpuXBufferOps)
1475         {
1476             GMX_ASSERT(stateGpu, "stateGpu should be valid when buffer ops are offloaded");
1477             nbv->convertCoordinatesGpu(AtomLocality::Local, stateGpu->getCoordinates(), localXReadyOnDevice);
1478         }
1479         else
1480         {
1481             if (simulationWork.useGpuUpdate)
1482             {
1483                 GMX_ASSERT(stateGpu, "need a valid stateGpu object");
1484                 GMX_ASSERT(haveCopiedXFromGpu,
1485                            "a wait should only be triggered if copy has been scheduled");
1486                 stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local);
1487             }
1488             nbv->convertCoordinates(AtomLocality::Local, x.unpaddedArrayRef());
1489         }
1490     }
1491
1492     if (simulationWork.useGpuNonbonded && (stepWork.computeNonbondedForces || domainWork.haveGpuBondedWork))
1493     {
1494         ddBalanceRegionHandler.openBeforeForceComputationGpu();
1495
1496         wallcycle_start(wcycle, ewcLAUNCH_GPU);
1497         wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1498         Nbnxm::gpu_upload_shiftvec(nbv->gpu_nbv, nbv->nbat.get());
1499         if (stepWork.doNeighborSearch || !stepWork.useGpuXBufferOps)
1500         {
1501             Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(), AtomLocality::Local);
1502         }
1503         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1504         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1505         // with X buffer ops offloaded to the GPU on all but the search steps
1506
1507         // bonded work not split into separate local and non-local, so with DD
1508         // we can only launch the kernel after non-local coordinates have been received.
1509         if (domainWork.haveGpuBondedWork && !havePPDomainDecomposition(cr))
1510         {
1511             fr->gpuBonded->setPbcAndlaunchKernel(fr->pbcType, box, fr->bMolPBC, stepWork);
1512         }
1513
1514         /* launch local nonbonded work on GPU */
1515         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1516         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1517         do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::Local, enbvClearFNo, step, nrnb, wcycle);
1518         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1519         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1520     }
1521
1522     if (useGpuPmeOnThisRank)
1523     {
1524         // In PME GPU and mixed mode we launch FFT / gather after the
1525         // X copy/transform to allow overlap as well as after the GPU NB
1526         // launch to avoid FFT launch overhead hijacking the CPU and delaying
1527         // the nonbonded kernel.
1528         launchPmeGpuFftAndGather(fr->pmedata,
1529                                  lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)],
1530                                  wcycle,
1531                                  stepWork);
1532     }
1533
1534     /* Communicate coordinates and sum dipole if necessary +
1535        do non-local pair search */
1536     if (havePPDomainDecomposition(cr))
1537     {
1538         if (stepWork.doNeighborSearch)
1539         {
1540             // TODO: fuse this branch with the above large stepWork.doNeighborSearch block
1541             wallcycle_start_nocount(wcycle, ewcNS);
1542             wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1543             /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1544             nbv->constructPairlist(InteractionLocality::NonLocal, top->excls, step, nrnb);
1545
1546             nbv->setupGpuShortRangeWork(fr->gpuBonded, InteractionLocality::NonLocal);
1547             wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1548             wallcycle_stop(wcycle, ewcNS);
1549             // TODO refactor this GPU halo exchange re-initialisation
1550             // to location in do_md where GPU halo exchange is
1551             // constructed at partitioning, after above stateGpu
1552             // re-initialization has similarly been refactored
1553             if (simulationWork.useGpuHaloExchange)
1554             {
1555                 reinitGpuHaloExchange(*cr, stateGpu->getCoordinates(), stateGpu->getForces());
1556             }
1557         }
1558         else
1559         {
1560             if (stepWork.useGpuXHalo)
1561             {
1562                 // The following must be called after local setCoordinates (which records an event
1563                 // when the coordinate data has been copied to the device).
1564                 communicateGpuHaloCoordinates(*cr, box, localXReadyOnDevice);
1565
1566                 if (domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork)
1567                 {
1568                     // non-local part of coordinate buffer must be copied back to host for CPU work
1569                     stateGpu->copyCoordinatesFromGpu(x.unpaddedArrayRef(), AtomLocality::NonLocal);
1570                 }
1571             }
1572             else
1573             {
1574                 if (simulationWork.useGpuUpdate)
1575                 {
1576                     GMX_ASSERT(haveCopiedXFromGpu,
1577                                "a wait should only be triggered if copy has been scheduled");
1578                     stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local);
1579                 }
1580                 dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
1581             }
1582
1583             if (stepWork.useGpuXBufferOps)
1584             {
1585                 if (!useGpuPmeOnThisRank && !stepWork.useGpuXHalo)
1586                 {
1587                     stateGpu->copyCoordinatesToGpu(x.unpaddedArrayRef(), AtomLocality::NonLocal);
1588                 }
1589                 nbv->convertCoordinatesGpu(AtomLocality::NonLocal,
1590                                            stateGpu->getCoordinates(),
1591                                            stateGpu->getCoordinatesReadyOnDeviceEvent(
1592                                                    AtomLocality::NonLocal, simulationWork, stepWork));
1593             }
1594             else
1595             {
1596                 nbv->convertCoordinates(AtomLocality::NonLocal, x.unpaddedArrayRef());
1597             }
1598         }
1599
1600         if (simulationWork.useGpuNonbonded)
1601         {
1602
1603             if (stepWork.doNeighborSearch || !stepWork.useGpuXBufferOps)
1604             {
1605                 wallcycle_start(wcycle, ewcLAUNCH_GPU);
1606                 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1607                 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(), AtomLocality::NonLocal);
1608                 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1609                 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1610             }
1611
1612             if (domainWork.haveGpuBondedWork)
1613             {
1614                 fr->gpuBonded->setPbcAndlaunchKernel(fr->pbcType, box, fr->bMolPBC, stepWork);
1615             }
1616
1617             /* launch non-local nonbonded tasks on GPU */
1618             wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1619             wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1620             do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step, nrnb, wcycle);
1621             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1622             wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1623         }
1624     }
1625
1626     if (simulationWork.useGpuNonbonded && stepWork.computeNonbondedForces)
1627     {
1628         /* launch D2H copy-back F */
1629         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1630         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1631
1632         if (havePPDomainDecomposition(cr))
1633         {
1634             Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(), stepWork, AtomLocality::NonLocal);
1635         }
1636         Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(), stepWork, AtomLocality::Local);
1637         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1638
1639         if (domainWork.haveGpuBondedWork && stepWork.computeEnergy)
1640         {
1641             fr->gpuBonded->launchEnergyTransfer();
1642         }
1643         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1644     }
1645
1646     gmx::ArrayRef<const gmx::RVec> xWholeMolecules;
1647     if (fr->wholeMoleculeTransform)
1648     {
1649         xWholeMolecules = fr->wholeMoleculeTransform->wholeMoleculeCoordinates(x.unpaddedArrayRef(), box);
1650     }
1651
1652     DipoleData dipoleData;
1653
1654     if (simulationWork.computeMuTot)
1655     {
1656         const int start = 0;
1657
1658         /* Calculate total (local) dipole moment in a temporary common array.
1659          * This makes it possible to sum them over nodes faster.
1660          */
1661         gmx::ArrayRef<const gmx::RVec> xRef =
1662                 (xWholeMolecules.empty() ? x.unpaddedArrayRef() : xWholeMolecules);
1663         calc_mu(start,
1664                 mdatoms->homenr,
1665                 xRef,
1666                 mdatoms->chargeA,
1667                 mdatoms->chargeB,
1668                 mdatoms->nChargePerturbed,
1669                 dipoleData.muStaging[0],
1670                 dipoleData.muStaging[1]);
1671
1672         reduceAndUpdateMuTot(
1673                 &dipoleData, cr, (fr->efep != FreeEnergyPerturbationType::No), lambda, muTotal, ddBalanceRegionHandler);
1674     }
1675
1676     /* Reset energies */
1677     reset_enerdata(enerd);
1678
1679     if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1680     {
1681         wallcycle_start(wcycle, ewcPPDURINGPME);
1682         dd_force_flop_start(cr->dd, nrnb);
1683     }
1684
1685     // For the rest of the CPU tasks that depend on GPU-update produced coordinates,
1686     // this wait ensures that the D2H transfer is complete.
1687     if (simulationWork.useGpuUpdate && !stepWork.doNeighborSearch
1688         && (runScheduleWork->domainWork.haveCpuLocalForceWork || stepWork.computeVirial))
1689     {
1690         GMX_ASSERT(haveCopiedXFromGpu, "a wait should only be triggered if copy has been scheduled");
1691         stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local);
1692     }
1693
1694     if (inputrec.bRot)
1695     {
1696         wallcycle_start(wcycle, ewcROT);
1697         do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, stepWork.doNeighborSearch);
1698         wallcycle_stop(wcycle, ewcROT);
1699     }
1700
1701     /* Start the force cycle counter.
1702      * Note that a different counter is used for dynamic load balancing.
1703      */
1704     wallcycle_start(wcycle, ewcFORCE);
1705
1706     /* Set up and clear force outputs:
1707      * forceOutMtsLevel0:  everything except what is in the other two outputs
1708      * forceOutMtsLevel1:  PME-mesh and listed-forces group 1
1709      * forceOutNonbonded: non-bonded forces
1710      * Without multiple time stepping all point to the same object.
1711      * With multiple time-stepping the use is different for MTS fast (level0 only) and slow steps.
1712      */
1713     ForceOutputs forceOutMtsLevel0 =
1714             setupForceOutputs(&fr->forceHelperBuffers[0], force, stepWork, wcycle);
1715
1716     // Force output for MTS combined forces, only set at level1 MTS steps
1717     std::optional<ForceOutputs> forceOutMts =
1718             (fr->useMts && stepWork.computeSlowForces)
1719                     ? std::optional(setupForceOutputs(&fr->forceHelperBuffers[1],
1720                                                       forceView->forceMtsCombinedWithPadding(),
1721                                                       stepWork,
1722                                                       wcycle))
1723                     : std::nullopt;
1724
1725     ForceOutputs* forceOutMtsLevel1 =
1726             fr->useMts ? (stepWork.computeSlowForces ? &forceOutMts.value() : nullptr) : &forceOutMtsLevel0;
1727
1728     const bool nonbondedAtMtsLevel1 = runScheduleWork->simulationWork.computeNonbondedAtMtsLevel1;
1729
1730     ForceOutputs* forceOutNonbonded = nonbondedAtMtsLevel1 ? forceOutMtsLevel1 : &forceOutMtsLevel0;
1731
1732     if (inputrec.bPull && pull_have_constraint(*pull_work))
1733     {
1734         clear_pull_forces(pull_work);
1735     }
1736
1737     /* We calculate the non-bonded forces, when done on the CPU, here.
1738      * We do this before calling do_force_lowlevel, because in that
1739      * function, the listed forces are calculated before PME, which
1740      * does communication.  With this order, non-bonded and listed
1741      * force calculation imbalance can be balanced out by the domain
1742      * decomposition load balancing.
1743      */
1744
1745     const bool useOrEmulateGpuNb = simulationWork.useGpuNonbonded || fr->nbv->emulateGpu();
1746
1747     if (!useOrEmulateGpuNb)
1748     {
1749         do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::Local, enbvClearFYes, step, nrnb, wcycle);
1750     }
1751
1752     if (fr->efep != FreeEnergyPerturbationType::No && stepWork.computeNonbondedForces)
1753     {
1754         /* Calculate the local and non-local free energy interactions here.
1755          * Happens here on the CPU both with and without GPU.
1756          */
1757         nbv->dispatchFreeEnergyKernel(InteractionLocality::Local,
1758                                       fr,
1759                                       as_rvec_array(x.unpaddedArrayRef().data()),
1760                                       &forceOutNonbonded->forceWithShiftForces(),
1761                                       *mdatoms,
1762                                       inputrec.fepvals.get(),
1763                                       lambda,
1764                                       enerd,
1765                                       stepWork,
1766                                       nrnb);
1767
1768         if (havePPDomainDecomposition(cr))
1769         {
1770             nbv->dispatchFreeEnergyKernel(InteractionLocality::NonLocal,
1771                                           fr,
1772                                           as_rvec_array(x.unpaddedArrayRef().data()),
1773                                           &forceOutNonbonded->forceWithShiftForces(),
1774                                           *mdatoms,
1775                                           inputrec.fepvals.get(),
1776                                           lambda,
1777                                           enerd,
1778                                           stepWork,
1779                                           nrnb);
1780         }
1781     }
1782
1783     if (stepWork.computeNonbondedForces && !useOrEmulateGpuNb)
1784     {
1785         if (havePPDomainDecomposition(cr))
1786         {
1787             do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step, nrnb, wcycle);
1788         }
1789
1790         if (stepWork.computeForces)
1791         {
1792             /* Add all the non-bonded force to the normal force array.
1793              * This can be split into a local and a non-local part when overlapping
1794              * communication with calculation with domain decomposition.
1795              */
1796             wallcycle_stop(wcycle, ewcFORCE);
1797             nbv->atomdata_add_nbat_f_to_f(AtomLocality::All,
1798                                           forceOutNonbonded->forceWithShiftForces().force());
1799             wallcycle_start_nocount(wcycle, ewcFORCE);
1800         }
1801
1802         /* If there are multiple fshift output buffers we need to reduce them */
1803         if (stepWork.computeVirial)
1804         {
1805             /* This is not in a subcounter because it takes a
1806                negligible and constant-sized amount of time */
1807             nbnxn_atomdata_add_nbat_fshift_to_fshift(
1808                     *nbv->nbat, forceOutNonbonded->forceWithShiftForces().shiftForces());
1809         }
1810     }
1811
1812     // TODO Force flags should include haveFreeEnergyWork for this domain
1813     if (stepWork.useGpuXHalo && (domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork))
1814     {
1815         wallcycle_stop(wcycle, ewcFORCE);
1816         /* Wait for non-local coordinate data to be copied from device */
1817         stateGpu->waitCoordinatesReadyOnHost(AtomLocality::NonLocal);
1818         wallcycle_start_nocount(wcycle, ewcFORCE);
1819     }
1820
1821     // Compute wall interactions, when present.
1822     // Note: should be moved to special forces.
1823     if (inputrec.nwall && stepWork.computeNonbondedForces)
1824     {
1825         /* foreign lambda component for walls */
1826         real dvdl_walls = do_walls(inputrec,
1827                                    *fr,
1828                                    box,
1829                                    *mdatoms,
1830                                    x.unpaddedConstArrayRef(),
1831                                    &forceOutMtsLevel0.forceWithVirial(),
1832                                    lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Vdw)],
1833                                    enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::LJSR].data(),
1834                                    nrnb);
1835         enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Vdw] += dvdl_walls;
1836     }
1837
1838     if (stepWork.computeListedForces)
1839     {
1840         /* Check whether we need to take into account PBC in listed interactions */
1841         bool needMolPbc = false;
1842         for (const auto& listedForces : fr->listedForces)
1843         {
1844             if (listedForces.haveCpuListedForces(*fr->fcdata))
1845             {
1846                 needMolPbc = fr->bMolPBC;
1847             }
1848         }
1849
1850         t_pbc pbc;
1851
1852         if (needMolPbc)
1853         {
1854             /* Since all atoms are in the rectangular or triclinic unit-cell,
1855              * only single box vector shifts (2 in x) are required.
1856              */
1857             set_pbc_dd(&pbc, fr->pbcType, DOMAINDECOMP(cr) ? cr->dd->numCells : nullptr, TRUE, box);
1858         }
1859
1860         for (int mtsIndex = 0; mtsIndex < (fr->useMts && stepWork.computeSlowForces ? 2 : 1); mtsIndex++)
1861         {
1862             ListedForces& listedForces = fr->listedForces[mtsIndex];
1863             ForceOutputs& forceOut     = (mtsIndex == 0 ? forceOutMtsLevel0 : *forceOutMtsLevel1);
1864             listedForces.calculate(wcycle,
1865                                    box,
1866                                    inputrec.fepvals.get(),
1867                                    cr,
1868                                    ms,
1869                                    x,
1870                                    xWholeMolecules,
1871                                    fr->fcdata.get(),
1872                                    hist,
1873                                    &forceOut,
1874                                    fr,
1875                                    &pbc,
1876                                    enerd,
1877                                    nrnb,
1878                                    lambda,
1879                                    mdatoms,
1880                                    DOMAINDECOMP(cr) ? cr->dd->globalAtomIndices.data() : nullptr,
1881                                    stepWork);
1882         }
1883     }
1884
1885     if (stepWork.computeSlowForces)
1886     {
1887         calculateLongRangeNonbondeds(fr,
1888                                      inputrec,
1889                                      cr,
1890                                      nrnb,
1891                                      wcycle,
1892                                      mdatoms,
1893                                      x.unpaddedConstArrayRef(),
1894                                      &forceOutMtsLevel1->forceWithVirial(),
1895                                      enerd,
1896                                      box,
1897                                      lambda,
1898                                      dipoleData.muStateAB,
1899                                      stepWork,
1900                                      ddBalanceRegionHandler);
1901     }
1902
1903     wallcycle_stop(wcycle, ewcFORCE);
1904
1905     // VdW dispersion correction, only computed on master rank to avoid double counting
1906     if ((stepWork.computeEnergy || stepWork.computeVirial) && fr->dispersionCorrection && MASTER(cr))
1907     {
1908         // Calculate long range corrections to pressure and energy
1909         const DispersionCorrection::Correction correction = fr->dispersionCorrection->calculate(
1910                 box, lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Vdw)]);
1911
1912         if (stepWork.computeEnergy)
1913         {
1914             enerd->term[F_DISPCORR] = correction.energy;
1915             enerd->term[F_DVDL_VDW] += correction.dvdl;
1916             enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Vdw] += correction.dvdl;
1917         }
1918         if (stepWork.computeVirial)
1919         {
1920             correction.correctVirial(vir_force);
1921             enerd->term[F_PDISPCORR] = correction.pressure;
1922         }
1923     }
1924
1925     computeSpecialForces(fplog,
1926                          cr,
1927                          inputrec,
1928                          awh,
1929                          enforcedRotation,
1930                          imdSession,
1931                          pull_work,
1932                          step,
1933                          t,
1934                          wcycle,
1935                          fr->forceProviders,
1936                          box,
1937                          x.unpaddedArrayRef(),
1938                          mdatoms,
1939                          lambda,
1940                          stepWork,
1941                          &forceOutMtsLevel0.forceWithVirial(),
1942                          forceOutMtsLevel1 ? &forceOutMtsLevel1->forceWithVirial() : nullptr,
1943                          enerd,
1944                          ed,
1945                          stepWork.doNeighborSearch);
1946
1947     if (havePPDomainDecomposition(cr) && stepWork.computeForces && stepWork.useGpuFHalo
1948         && domainWork.haveCpuLocalForceWork)
1949     {
1950         stateGpu->copyForcesToGpu(forceOutMtsLevel0.forceWithShiftForces().force(), AtomLocality::Local);
1951     }
1952
1953     GMX_ASSERT(!(nonbondedAtMtsLevel1 && stepWork.useGpuFBufferOps),
1954                "The schedule below does not allow for nonbonded MTS with GPU buffer ops");
1955     GMX_ASSERT(!(nonbondedAtMtsLevel1 && stepWork.useGpuFHalo),
1956                "The schedule below does not allow for nonbonded MTS with GPU halo exchange");
1957     // Will store the amount of cycles spent waiting for the GPU that
1958     // will be later used in the DLB accounting.
1959     float cycles_wait_gpu = 0;
1960     if (useOrEmulateGpuNb && stepWork.computeNonbondedForces)
1961     {
1962         auto& forceWithShiftForces = forceOutNonbonded->forceWithShiftForces();
1963
1964         /* wait for non-local forces (or calculate in emulation mode) */
1965         if (havePPDomainDecomposition(cr))
1966         {
1967             if (simulationWork.useGpuNonbonded)
1968             {
1969                 cycles_wait_gpu += Nbnxm::gpu_wait_finish_task(
1970                         nbv->gpu_nbv,
1971                         stepWork,
1972                         AtomLocality::NonLocal,
1973                         enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::LJSR].data(),
1974                         enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::CoulombSR].data(),
1975                         forceWithShiftForces.shiftForces(),
1976                         wcycle);
1977             }
1978             else
1979             {
1980                 wallcycle_start_nocount(wcycle, ewcFORCE);
1981                 do_nb_verlet(
1982                         fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFYes, step, nrnb, wcycle);
1983                 wallcycle_stop(wcycle, ewcFORCE);
1984             }
1985
1986             if (stepWork.useGpuFBufferOps)
1987             {
1988                 // TODO: move this into DomainLifetimeWorkload, including the second part of the
1989                 // condition The bonded and free energy CPU tasks can have non-local force
1990                 // contributions which are a dependency for the GPU force reduction.
1991                 bool haveNonLocalForceContribInCpuBuffer =
1992                         domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork;
1993
1994                 if (haveNonLocalForceContribInCpuBuffer)
1995                 {
1996                     stateGpu->copyForcesToGpu(forceOutMtsLevel0.forceWithShiftForces().force(),
1997                                               AtomLocality::NonLocal);
1998                 }
1999
2000
2001                 fr->gpuForceReduction[gmx::AtomLocality::NonLocal]->execute();
2002
2003                 if (!stepWork.useGpuFHalo)
2004                 {
2005                     // copy from GPU input for dd_move_f()
2006                     stateGpu->copyForcesFromGpu(forceOutMtsLevel0.forceWithShiftForces().force(),
2007                                                 AtomLocality::NonLocal);
2008                 }
2009             }
2010             else
2011             {
2012                 nbv->atomdata_add_nbat_f_to_f(AtomLocality::NonLocal, forceWithShiftForces.force());
2013             }
2014
2015             if (fr->nbv->emulateGpu() && stepWork.computeVirial)
2016             {
2017                 nbnxn_atomdata_add_nbat_fshift_to_fshift(*nbv->nbat, forceWithShiftForces.shiftForces());
2018             }
2019         }
2020     }
2021
2022     /* Combining the forces for multiple time stepping before the halo exchange, when possible,
2023      * avoids an extra halo exchange (when DD is used) and post-processing step.
2024      */
2025     const bool combineMtsForcesBeforeHaloExchange =
2026             (stepWork.computeForces && fr->useMts && stepWork.computeSlowForces
2027              && (legacyFlags & GMX_FORCE_DO_NOT_NEED_NORMAL_FORCE) != 0
2028              && !(stepWork.computeVirial || simulationWork.useGpuNonbonded || useGpuPmeOnThisRank));
2029     if (combineMtsForcesBeforeHaloExchange)
2030     {
2031         const int numAtoms = havePPDomainDecomposition(cr) ? dd_numAtomsZones(*cr->dd) : mdatoms->homenr;
2032         combineMtsForces(numAtoms,
2033                          force.unpaddedArrayRef(),
2034                          forceView->forceMtsCombined(),
2035                          inputrec.mtsLevels[1].stepFactor);
2036     }
2037
2038     if (havePPDomainDecomposition(cr))
2039     {
2040         /* We are done with the CPU compute.
2041          * We will now communicate the non-local forces.
2042          * If we use a GPU this will overlap with GPU work, so in that case
2043          * we do not close the DD force balancing region here.
2044          */
2045         ddBalanceRegionHandler.closeAfterForceComputationCpu();
2046
2047         if (stepWork.computeForces)
2048         {
2049
2050             if (stepWork.useGpuFHalo)
2051             {
2052                 // If there exist CPU forces, data from halo exchange should accumulate into these
2053                 bool accumulateForces = domainWork.haveCpuLocalForceWork;
2054                 if (!accumulateForces)
2055                 {
2056                     // Force halo exchange will set a subset of local atoms with remote non-local data
2057                     // First clear local portion of force array, so that untouched atoms are zero
2058                     stateGpu->clearForcesOnGpu(AtomLocality::Local);
2059                 }
2060                 communicateGpuHaloForces(*cr, accumulateForces);
2061             }
2062             else
2063             {
2064                 if (stepWork.useGpuFBufferOps)
2065                 {
2066                     stateGpu->waitForcesReadyOnHost(AtomLocality::NonLocal);
2067                 }
2068
2069                 // Without MTS or with MTS at slow steps with uncombined forces we need to
2070                 // communicate the fast forces
2071                 if (!fr->useMts || !combineMtsForcesBeforeHaloExchange)
2072                 {
2073                     dd_move_f(cr->dd, &forceOutMtsLevel0.forceWithShiftForces(), wcycle);
2074                 }
2075                 // With MTS we need to communicate the slow or combined (in forceOutMtsLevel1) forces
2076                 if (fr->useMts && stepWork.computeSlowForces)
2077                 {
2078                     dd_move_f(cr->dd, &forceOutMtsLevel1->forceWithShiftForces(), wcycle);
2079                 }
2080             }
2081         }
2082     }
2083
2084     // With both nonbonded and PME offloaded a GPU on the same rank, we use
2085     // an alternating wait/reduction scheme.
2086     bool alternateGpuWait = (!c_disableAlternatingWait && useGpuPmeOnThisRank && simulationWork.useGpuNonbonded
2087                              && !DOMAINDECOMP(cr) && !stepWork.useGpuFBufferOps);
2088     if (alternateGpuWait)
2089     {
2090         alternatePmeNbGpuWaitReduce(fr->nbv.get(),
2091                                     fr->pmedata,
2092                                     forceOutNonbonded,
2093                                     forceOutMtsLevel1,
2094                                     enerd,
2095                                     lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)],
2096                                     stepWork,
2097                                     wcycle);
2098     }
2099
2100     if (!alternateGpuWait && useGpuPmeOnThisRank)
2101     {
2102         pme_gpu_wait_and_reduce(fr->pmedata,
2103                                 stepWork,
2104                                 wcycle,
2105                                 &forceOutMtsLevel1->forceWithVirial(),
2106                                 enerd,
2107                                 lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)]);
2108     }
2109
2110     /* Wait for local GPU NB outputs on the non-alternating wait path */
2111     if (!alternateGpuWait && stepWork.computeNonbondedForces && simulationWork.useGpuNonbonded)
2112     {
2113         /* Measured overhead on CUDA and OpenCL with(out) GPU sharing
2114          * is between 0.5 and 1.5 Mcycles. So 2 MCycles is an overestimate,
2115          * but even with a step of 0.1 ms the difference is less than 1%
2116          * of the step time.
2117          */
2118         const float gpuWaitApiOverheadMargin = 2e6F; /* cycles */
2119         const float waitCycles               = Nbnxm::gpu_wait_finish_task(
2120                 nbv->gpu_nbv,
2121                 stepWork,
2122                 AtomLocality::Local,
2123                 enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::LJSR].data(),
2124                 enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::CoulombSR].data(),
2125                 forceOutNonbonded->forceWithShiftForces().shiftForces(),
2126                 wcycle);
2127
2128         if (ddBalanceRegionHandler.useBalancingRegion())
2129         {
2130             DdBalanceRegionWaitedForGpu waitedForGpu = DdBalanceRegionWaitedForGpu::yes;
2131             if (stepWork.computeForces && waitCycles <= gpuWaitApiOverheadMargin)
2132             {
2133                 /* We measured few cycles, it could be that the kernel
2134                  * and transfer finished earlier and there was no actual
2135                  * wait time, only API call overhead.
2136                  * Then the actual time could be anywhere between 0 and
2137                  * cycles_wait_est. We will use half of cycles_wait_est.
2138                  */
2139                 waitedForGpu = DdBalanceRegionWaitedForGpu::no;
2140             }
2141             ddBalanceRegionHandler.closeAfterForceComputationGpu(cycles_wait_gpu, waitedForGpu);
2142         }
2143     }
2144
2145     if (fr->nbv->emulateGpu())
2146     {
2147         // NOTE: emulation kernel is not included in the balancing region,
2148         // but emulation mode does not target performance anyway
2149         wallcycle_start_nocount(wcycle, ewcFORCE);
2150         do_nb_verlet(fr,
2151                      ic,
2152                      enerd,
2153                      stepWork,
2154                      InteractionLocality::Local,
2155                      DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes,
2156                      step,
2157                      nrnb,
2158                      wcycle);
2159         wallcycle_stop(wcycle, ewcFORCE);
2160     }
2161
2162     // If on GPU PME-PP comms path, receive forces from PME before GPU buffer ops
2163     // TODO refactor this and unify with below default-path call to the same function
2164     if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME) && stepWork.computeSlowForces
2165         && simulationWork.useGpuPmePpCommunication)
2166     {
2167         /* In case of node-splitting, the PP nodes receive the long-range
2168          * forces, virial and energy from the PME nodes here.
2169          */
2170         pme_receive_force_ener(fr,
2171                                cr,
2172                                &forceOutMtsLevel1->forceWithVirial(),
2173                                enerd,
2174                                simulationWork.useGpuPmePpCommunication,
2175                                stepWork.useGpuPmeFReduction,
2176                                wcycle);
2177     }
2178
2179
2180     /* Do the nonbonded GPU (or emulation) force buffer reduction
2181      * on the non-alternating path. */
2182     GMX_ASSERT(!(nonbondedAtMtsLevel1 && stepWork.useGpuFBufferOps),
2183                "The schedule below does not allow for nonbonded MTS with GPU buffer ops");
2184     if (useOrEmulateGpuNb && !alternateGpuWait)
2185     {
2186         if (stepWork.useGpuFBufferOps)
2187         {
2188             ArrayRef<gmx::RVec> forceWithShift = forceOutNonbonded->forceWithShiftForces().force();
2189
2190             // Flag to specify whether the CPU force buffer has contributions to
2191             // local atoms. This depends on whether there are CPU-based force tasks
2192             // or when DD is active the halo exchange has resulted in contributions
2193             // from the non-local part.
2194             const bool haveLocalForceContribInCpuBuffer =
2195                     (domainWork.haveCpuLocalForceWork || havePPDomainDecomposition(cr));
2196
2197             // TODO: move these steps as early as possible:
2198             // - CPU f H2D should be as soon as all CPU-side forces are done
2199             // - wait for force reduction does not need to block host (at least not here, it's sufficient to wait
2200             //   before the next CPU task that consumes the forces: vsite spread or update)
2201             // - copy is not perfomed if GPU force halo exchange is active, because it would overwrite the result
2202             //   of the halo exchange. In that case the copy is instead performed above, before the exchange.
2203             //   These should be unified.
2204             if (haveLocalForceContribInCpuBuffer && !stepWork.useGpuFHalo)
2205             {
2206                 // Note: AtomLocality::All is used for the non-DD case because, as in this
2207                 // case copyForcesToGpu() uses a separate stream, it allows overlap of
2208                 // CPU force H2D with GPU force tasks on all streams including those in the
2209                 // local stream which would otherwise be implicit dependencies for the
2210                 // transfer and would not overlap.
2211                 auto locality = havePPDomainDecomposition(cr) ? AtomLocality::Local : AtomLocality::All;
2212
2213                 stateGpu->copyForcesToGpu(forceWithShift, locality);
2214             }
2215
2216             if (stepWork.computeNonbondedForces)
2217             {
2218                 fr->gpuForceReduction[gmx::AtomLocality::Local]->execute();
2219             }
2220
2221             // Copy forces to host if they are needed for update or if virtual sites are enabled.
2222             // If there are vsites, we need to copy forces every step to spread vsite forces on host.
2223             // TODO: When the output flags will be included in step workload, this copy can be combined with the
2224             //       copy call done in sim_utils(...) for the output.
2225             // NOTE: If there are virtual sites, the forces are modified on host after this D2H copy. Hence,
2226             //       they should not be copied in do_md(...) for the output.
2227             if (!simulationWork.useGpuUpdate
2228                 || (simulationWork.useGpuUpdate && DOMAINDECOMP(cr) && haveHostPmePpComms) || vsite)
2229             {
2230                 stateGpu->copyForcesFromGpu(forceWithShift, AtomLocality::Local);
2231                 stateGpu->waitForcesReadyOnHost(AtomLocality::Local);
2232             }
2233         }
2234         else if (stepWork.computeNonbondedForces)
2235         {
2236             ArrayRef<gmx::RVec> forceWithShift = forceOutNonbonded->forceWithShiftForces().force();
2237             nbv->atomdata_add_nbat_f_to_f(AtomLocality::Local, forceWithShift);
2238         }
2239     }
2240
2241     launchGpuEndOfStepTasks(
2242             nbv, fr->gpuBonded, fr->pmedata, enerd, *runScheduleWork, useGpuPmeOnThisRank, step, wcycle);
2243
2244     if (DOMAINDECOMP(cr))
2245     {
2246         dd_force_flop_stop(cr->dd, nrnb);
2247     }
2248
2249     const bool haveCombinedMtsForces = (stepWork.computeForces && fr->useMts && stepWork.computeSlowForces
2250                                         && combineMtsForcesBeforeHaloExchange);
2251     if (stepWork.computeForces)
2252     {
2253         postProcessForceWithShiftForces(
2254                 nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOutMtsLevel0, vir_force, *mdatoms, *fr, vsite, stepWork);
2255
2256         if (fr->useMts && stepWork.computeSlowForces && !haveCombinedMtsForces)
2257         {
2258             postProcessForceWithShiftForces(
2259                     nrnb, wcycle, box, x.unpaddedArrayRef(), forceOutMtsLevel1, vir_force, *mdatoms, *fr, vsite, stepWork);
2260         }
2261     }
2262
2263     // TODO refactor this and unify with above GPU PME-PP / GPU update path call to the same function
2264     if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME) && !simulationWork.useGpuPmePpCommunication
2265         && stepWork.computeSlowForces)
2266     {
2267         /* In case of node-splitting, the PP nodes receive the long-range
2268          * forces, virial and energy from the PME nodes here.
2269          */
2270         pme_receive_force_ener(fr,
2271                                cr,
2272                                &forceOutMtsLevel1->forceWithVirial(),
2273                                enerd,
2274                                simulationWork.useGpuPmePpCommunication,
2275                                false,
2276                                wcycle);
2277     }
2278
2279     if (stepWork.computeForces)
2280     {
2281         /* If we don't use MTS or if we already combined the MTS forces before, we only
2282          * need to post-process one ForceOutputs object here, called forceOutCombined,
2283          * otherwise we have to post-process two outputs and then combine them.
2284          */
2285         ForceOutputs& forceOutCombined = (haveCombinedMtsForces ? forceOutMts.value() : forceOutMtsLevel0);
2286         postProcessForces(
2287                 cr, step, nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOutCombined, vir_force, mdatoms, fr, vsite, stepWork);
2288
2289         if (fr->useMts && stepWork.computeSlowForces && !haveCombinedMtsForces)
2290         {
2291             postProcessForces(
2292                     cr, step, nrnb, wcycle, box, x.unpaddedArrayRef(), forceOutMtsLevel1, vir_force, mdatoms, fr, vsite, stepWork);
2293
2294             combineMtsForces(mdatoms->homenr,
2295                              force.unpaddedArrayRef(),
2296                              forceView->forceMtsCombined(),
2297                              inputrec.mtsLevels[1].stepFactor);
2298         }
2299     }
2300
2301     if (stepWork.computeEnergy)
2302     {
2303         /* Compute the final potential energy terms */
2304         accumulatePotentialEnergies(enerd, lambda, inputrec.fepvals.get());
2305
2306         if (!EI_TPI(inputrec.eI))
2307         {
2308             checkPotentialEnergyValidity(step, *enerd, inputrec);
2309         }
2310     }
2311
2312     /* In case we don't have constraints and are using GPUs, the next balancing
2313      * region starts here.
2314      * Some "special" work at the end of do_force_cuts?, such as vsite spread,
2315      * virial calculation and COM pulling, is not thus not included in
2316      * the balance timing, which is ok as most tasks do communication.
2317      */
2318     ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::no);
2319 }