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