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