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