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