Move dispersion correction call to do_force()
[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, 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
48 #include "gromacs/awh/awh.h"
49 #include "gromacs/domdec/dlbtiming.h"
50 #include "gromacs/domdec/domdec.h"
51 #include "gromacs/domdec/domdec_struct.h"
52 #include "gromacs/domdec/gpuhaloexchange.h"
53 #include "gromacs/domdec/partition.h"
54 #include "gromacs/essentialdynamics/edsam.h"
55 #include "gromacs/ewald/pme.h"
56 #include "gromacs/ewald/pme_pp.h"
57 #include "gromacs/ewald/pme_pp_comm_gpu.h"
58 #include "gromacs/gmxlib/network.h"
59 #include "gromacs/gmxlib/nonbonded/nb_free_energy.h"
60 #include "gromacs/gmxlib/nonbonded/nb_kernel.h"
61 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
62 #include "gromacs/gpu_utils/gpu_utils.h"
63 #include "gromacs/imd/imd.h"
64 #include "gromacs/listed_forces/disre.h"
65 #include "gromacs/listed_forces/gpubonded.h"
66 #include "gromacs/listed_forces/listed_forces.h"
67 #include "gromacs/listed_forces/orires.h"
68 #include "gromacs/math/arrayrefwithpadding.h"
69 #include "gromacs/math/functions.h"
70 #include "gromacs/math/units.h"
71 #include "gromacs/math/vec.h"
72 #include "gromacs/math/vecdump.h"
73 #include "gromacs/mdlib/calcmu.h"
74 #include "gromacs/mdlib/calcvir.h"
75 #include "gromacs/mdlib/constr.h"
76 #include "gromacs/mdlib/dispersioncorrection.h"
77 #include "gromacs/mdlib/enerdata_utils.h"
78 #include "gromacs/mdlib/force.h"
79 #include "gromacs/mdlib/force_flags.h"
80 #include "gromacs/mdlib/forcerec.h"
81 #include "gromacs/mdlib/gmx_omp_nthreads.h"
82 #include "gromacs/mdlib/update.h"
83 #include "gromacs/mdlib/vsite.h"
84 #include "gromacs/mdlib/wholemoleculetransform.h"
85 #include "gromacs/mdtypes/commrec.h"
86 #include "gromacs/mdtypes/enerdata.h"
87 #include "gromacs/mdtypes/forceoutput.h"
88 #include "gromacs/mdtypes/forcerec.h"
89 #include "gromacs/mdtypes/iforceprovider.h"
90 #include "gromacs/mdtypes/inputrec.h"
91 #include "gromacs/mdtypes/md_enums.h"
92 #include "gromacs/mdtypes/mdatom.h"
93 #include "gromacs/mdtypes/simulation_workload.h"
94 #include "gromacs/mdtypes/state.h"
95 #include "gromacs/mdtypes/state_propagator_data_gpu.h"
96 #include "gromacs/nbnxm/gpu_data_mgmt.h"
97 #include "gromacs/nbnxm/nbnxm.h"
98 #include "gromacs/nbnxm/nbnxm_gpu.h"
99 #include "gromacs/pbcutil/ishift.h"
100 #include "gromacs/pbcutil/pbc.h"
101 #include "gromacs/pulling/pull.h"
102 #include "gromacs/pulling/pull_rotation.h"
103 #include "gromacs/timing/cyclecounter.h"
104 #include "gromacs/timing/gpu_timing.h"
105 #include "gromacs/timing/wallcycle.h"
106 #include "gromacs/timing/wallcyclereporting.h"
107 #include "gromacs/timing/walltime_accounting.h"
108 #include "gromacs/topology/topology.h"
109 #include "gromacs/utility/arrayref.h"
110 #include "gromacs/utility/basedefinitions.h"
111 #include "gromacs/utility/cstringutil.h"
112 #include "gromacs/utility/exceptions.h"
113 #include "gromacs/utility/fatalerror.h"
114 #include "gromacs/utility/fixedcapacityvector.h"
115 #include "gromacs/utility/gmxassert.h"
116 #include "gromacs/utility/gmxmpi.h"
117 #include "gromacs/utility/logger.h"
118 #include "gromacs/utility/smalloc.h"
119 #include "gromacs/utility/strconvert.h"
120 #include "gromacs/utility/sysinfo.h"
121
122 using gmx::ArrayRef;
123 using gmx::AtomLocality;
124 using gmx::DomainLifetimeWorkload;
125 using gmx::ForceOutputs;
126 using gmx::ForceWithShiftForces;
127 using gmx::InteractionLocality;
128 using gmx::RVec;
129 using gmx::SimulationWorkload;
130 using gmx::StepWorkload;
131
132 // TODO: this environment variable allows us to verify before release
133 // that on less common architectures the total cost of polling is not larger than
134 // a blocking wait (so polling does not introduce overhead when the static
135 // PME-first ordering would suffice).
136 static const bool c_disableAlternatingWait = (getenv("GMX_DISABLE_ALTERNATING_GPU_WAIT") != nullptr);
137
138 static void sum_forces(ArrayRef<RVec> f, ArrayRef<const RVec> forceToAdd)
139 {
140     GMX_ASSERT(f.size() >= forceToAdd.size(), "Accumulation buffer should be sufficiently large");
141     const int end = forceToAdd.size();
142
143     int gmx_unused nt = gmx_omp_nthreads_get(emntDefault);
144 #pragma omp parallel for num_threads(nt) schedule(static)
145     for (int i = 0; i < end; i++)
146     {
147         rvec_inc(f[i], forceToAdd[i]);
148     }
149 }
150
151 static void calc_virial(int                              start,
152                         int                              homenr,
153                         const rvec                       x[],
154                         const gmx::ForceWithShiftForces& forceWithShiftForces,
155                         tensor                           vir_part,
156                         const matrix                     box,
157                         t_nrnb*                          nrnb,
158                         const t_forcerec*                fr,
159                         PbcType                          pbcType)
160 {
161     /* The short-range virial from surrounding boxes */
162     const rvec* fshift = as_rvec_array(forceWithShiftForces.shiftForces().data());
163     calc_vir(SHIFTS, fr->shift_vec, fshift, vir_part, pbcType == PbcType::Screw, box);
164     inc_nrnb(nrnb, eNR_VIRIAL, SHIFTS);
165
166     /* Calculate partial virial, for local atoms only, based on short range.
167      * Total virial is computed in global_stat, called from do_md
168      */
169     const rvec* f = as_rvec_array(forceWithShiftForces.force().data());
170     f_calc_vir(start, start + homenr, x, f, vir_part, box);
171     inc_nrnb(nrnb, eNR_VIRIAL, homenr);
172
173     if (debug)
174     {
175         pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
176     }
177 }
178
179 static void pull_potential_wrapper(const t_commrec*               cr,
180                                    const t_inputrec*              ir,
181                                    const matrix                   box,
182                                    gmx::ArrayRef<const gmx::RVec> x,
183                                    gmx::ForceWithVirial*          force,
184                                    const t_mdatoms*               mdatoms,
185                                    gmx_enerdata_t*                enerd,
186                                    pull_t*                        pull_work,
187                                    const real*                    lambda,
188                                    double                         t,
189                                    gmx_wallcycle_t                wcycle)
190 {
191     t_pbc pbc;
192     real  dvdl;
193
194     /* Calculate the center of mass forces, this requires communication,
195      * which is why pull_potential is called close to other communication.
196      */
197     wallcycle_start(wcycle, ewcPULLPOT);
198     set_pbc(&pbc, ir->pbcType, box);
199     dvdl = 0;
200     enerd->term[F_COM_PULL] +=
201             pull_potential(pull_work, mdatoms->massT, &pbc, cr, t, lambda[efptRESTRAINT],
202                            as_rvec_array(x.data()), force, &dvdl);
203     enerd->dvdl_lin[efptRESTRAINT] += dvdl;
204     for (auto& dhdl : enerd->dhdlLambda)
205     {
206         dhdl += dvdl;
207     }
208     wallcycle_stop(wcycle, ewcPULLPOT);
209 }
210
211 static void pme_receive_force_ener(t_forcerec*           fr,
212                                    const t_commrec*      cr,
213                                    gmx::ForceWithVirial* forceWithVirial,
214                                    gmx_enerdata_t*       enerd,
215                                    bool                  useGpuPmePpComms,
216                                    bool                  receivePmeForceToGpu,
217                                    gmx_wallcycle_t       wcycle)
218 {
219     real  e_q, e_lj, dvdl_q, dvdl_lj;
220     float cycles_ppdpme, cycles_seppme;
221
222     cycles_ppdpme = wallcycle_stop(wcycle, ewcPPDURINGPME);
223     dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
224
225     /* In case of node-splitting, the PP nodes receive the long-range
226      * forces, virial and energy from the PME nodes here.
227      */
228     wallcycle_start(wcycle, ewcPP_PMEWAITRECVF);
229     dvdl_q  = 0;
230     dvdl_lj = 0;
231     gmx_pme_receive_f(fr->pmePpCommGpu.get(), cr, forceWithVirial, &e_q, &e_lj, &dvdl_q, &dvdl_lj,
232                       useGpuPmePpComms, receivePmeForceToGpu, &cycles_seppme);
233     enerd->term[F_COUL_RECIP] += e_q;
234     enerd->term[F_LJ_RECIP] += e_lj;
235     enerd->dvdl_lin[efptCOUL] += dvdl_q;
236     enerd->dvdl_lin[efptVDW] += dvdl_lj;
237
238     for (auto& dhdl : enerd->dhdlLambda)
239     {
240         dhdl += dvdl_q + dvdl_lj;
241     }
242
243     if (wcycle)
244     {
245         dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
246     }
247     wallcycle_stop(wcycle, ewcPP_PMEWAITRECVF);
248 }
249
250 static void print_large_forces(FILE*                fp,
251                                const t_mdatoms*     md,
252                                const t_commrec*     cr,
253                                int64_t              step,
254                                real                 forceTolerance,
255                                ArrayRef<const RVec> x,
256                                ArrayRef<const RVec> f)
257 {
258     real       force2Tolerance = gmx::square(forceTolerance);
259     gmx::index numNonFinite    = 0;
260     for (int i = 0; i < md->homenr; i++)
261     {
262         real force2    = norm2(f[i]);
263         bool nonFinite = !std::isfinite(force2);
264         if (force2 >= force2Tolerance || nonFinite)
265         {
266             fprintf(fp, "step %" PRId64 " atom %6d  x %8.3f %8.3f %8.3f  force %12.5e\n", step,
267                     ddglatnr(cr->dd, i), x[i][XX], x[i][YY], x[i][ZZ], std::sqrt(force2));
268         }
269         if (nonFinite)
270         {
271             numNonFinite++;
272         }
273     }
274     if (numNonFinite > 0)
275     {
276         /* Note that with MPI this fatal call on one rank might interrupt
277          * the printing on other ranks. But we can only avoid that with
278          * an expensive MPI barrier that we would need at each step.
279          */
280         gmx_fatal(FARGS, "At step %" PRId64 " detected non-finite forces on %td atoms", step, numNonFinite);
281     }
282 }
283
284 //! When necessary, spreads forces on vsites and computes the virial for \p forceOutputs->forceWithShiftForces()
285 static void postProcessForceWithShiftForces(t_nrnb*                   nrnb,
286                                             gmx_wallcycle_t           wcycle,
287                                             const matrix              box,
288                                             ArrayRef<const RVec>      x,
289                                             ForceOutputs*             forceOutputs,
290                                             tensor                    vir_force,
291                                             const t_mdatoms&          mdatoms,
292                                             const t_forcerec&         fr,
293                                             gmx::VirtualSitesHandler* vsite,
294                                             const StepWorkload&       stepWork)
295 {
296     ForceWithShiftForces& forceWithShiftForces = forceOutputs->forceWithShiftForces();
297
298     /* If we have NoVirSum forces, but we do not calculate the virial,
299      * we later sum the forceWithShiftForces buffer together with
300      * the noVirSum buffer and spread the combined vsite forces at once.
301      */
302     if (vsite && (!forceOutputs->haveForceWithVirial() || stepWork.computeVirial))
303     {
304         using VirialHandling = gmx::VirtualSitesHandler::VirialHandling;
305
306         auto                 f      = forceWithShiftForces.force();
307         auto                 fshift = forceWithShiftForces.shiftForces();
308         const VirialHandling virialHandling =
309                 (stepWork.computeVirial ? VirialHandling::Pbc : VirialHandling::None);
310         vsite->spreadForces(x, f, virialHandling, fshift, nullptr, nrnb, box, wcycle);
311         forceWithShiftForces.haveSpreadVsiteForces() = true;
312     }
313
314     if (stepWork.computeVirial)
315     {
316         /* Calculation of the virial must be done after vsites! */
317         calc_virial(0, mdatoms.homenr, as_rvec_array(x.data()), forceWithShiftForces, vir_force,
318                     box, nrnb, &fr, fr.pbcType);
319     }
320 }
321
322 //! Spread, compute virial for and sum forces, when necessary
323 static void postProcessForces(const t_commrec*          cr,
324                               int64_t                   step,
325                               t_nrnb*                   nrnb,
326                               gmx_wallcycle_t           wcycle,
327                               const matrix              box,
328                               ArrayRef<const RVec>      x,
329                               ForceOutputs*             forceOutputs,
330                               tensor                    vir_force,
331                               const t_mdatoms*          mdatoms,
332                               const t_forcerec*         fr,
333                               gmx::VirtualSitesHandler* vsite,
334                               const StepWorkload&       stepWork)
335 {
336     // Extract the final output force buffer, which is also the buffer for forces with shift forces
337     ArrayRef<RVec> f = forceOutputs->forceWithShiftForces().force();
338
339     if (forceOutputs->haveForceWithVirial())
340     {
341         auto& forceWithVirial = forceOutputs->forceWithVirial();
342
343         if (vsite)
344         {
345             /* Spread the mesh force on virtual sites to the other particles...
346              * This is parallellized. MPI communication is performed
347              * if the constructing atoms aren't local.
348              */
349             GMX_ASSERT(!stepWork.computeVirial || f.data() != forceWithVirial.force_.data(),
350                        "We need separate force buffers for shift and virial forces when "
351                        "computing the virial");
352             GMX_ASSERT(!stepWork.computeVirial
353                                || forceOutputs->forceWithShiftForces().haveSpreadVsiteForces(),
354                        "We should spread the force with shift forces separately when computing "
355                        "the virial");
356             const gmx::VirtualSitesHandler::VirialHandling virialHandling =
357                     (stepWork.computeVirial ? gmx::VirtualSitesHandler::VirialHandling::NonLinear
358                                             : gmx::VirtualSitesHandler::VirialHandling::None);
359             matrix virial = { { 0 } };
360             vsite->spreadForces(x, forceWithVirial.force_, virialHandling, {}, virial, nrnb, box, wcycle);
361             forceWithVirial.addVirialContribution(virial);
362         }
363
364         if (stepWork.computeVirial)
365         {
366             /* Now add the forces, this is local */
367             sum_forces(f, forceWithVirial.force_);
368
369             /* Add the direct virial contributions */
370             GMX_ASSERT(
371                     forceWithVirial.computeVirial_,
372                     "forceWithVirial should request virial computation when we request the virial");
373             m_add(vir_force, forceWithVirial.getVirial(), vir_force);
374
375             if (debug)
376             {
377                 pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
378             }
379         }
380     }
381     else
382     {
383         GMX_ASSERT(vsite == nullptr || forceOutputs->forceWithShiftForces().haveSpreadVsiteForces(),
384                    "We should have spread the vsite forces (earlier)");
385     }
386
387     if (fr->print_force >= 0)
388     {
389         print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
390     }
391 }
392
393 static void do_nb_verlet(t_forcerec*                fr,
394                          const interaction_const_t* ic,
395                          gmx_enerdata_t*            enerd,
396                          const StepWorkload&        stepWork,
397                          const InteractionLocality  ilocality,
398                          const int                  clearF,
399                          const int64_t              step,
400                          t_nrnb*                    nrnb,
401                          gmx_wallcycle_t            wcycle)
402 {
403     if (!stepWork.computeNonbondedForces)
404     {
405         /* skip non-bonded calculation */
406         return;
407     }
408
409     nonbonded_verlet_t* nbv = fr->nbv.get();
410
411     /* GPU kernel launch overhead is already timed separately */
412     if (fr->cutoff_scheme != ecutsVERLET)
413     {
414         gmx_incons("Invalid cut-off scheme passed!");
415     }
416
417     if (!nbv->useGpu())
418     {
419         /* When dynamic pair-list  pruning is requested, we need to prune
420          * at nstlistPrune steps.
421          */
422         if (nbv->isDynamicPruningStepCpu(step))
423         {
424             /* Prune the pair-list beyond fr->ic->rlistPrune using
425              * the current coordinates of the atoms.
426              */
427             wallcycle_sub_start(wcycle, ewcsNONBONDED_PRUNING);
428             nbv->dispatchPruneKernelCpu(ilocality, fr->shift_vec);
429             wallcycle_sub_stop(wcycle, ewcsNONBONDED_PRUNING);
430         }
431     }
432
433     nbv->dispatchNonbondedKernel(ilocality, *ic, stepWork, clearF, *fr, enerd, nrnb);
434 }
435
436 static inline void clearRVecs(ArrayRef<RVec> v, const bool useOpenmpThreading)
437 {
438     int nth = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, v.ssize());
439
440     /* Note that we would like to avoid this conditional by putting it
441      * into the omp pragma instead, but then we still take the full
442      * omp parallel for overhead (at least with gcc5).
443      */
444     if (!useOpenmpThreading || nth == 1)
445     {
446         for (RVec& elem : v)
447         {
448             clear_rvec(elem);
449         }
450     }
451     else
452     {
453 #pragma omp parallel for num_threads(nth) schedule(static)
454         for (gmx::index i = 0; i < v.ssize(); i++)
455         {
456             clear_rvec(v[i]);
457         }
458     }
459 }
460
461 /*! \brief Return an estimate of the average kinetic energy or 0 when unreliable
462  *
463  * \param groupOptions  Group options, containing T-coupling options
464  */
465 static real averageKineticEnergyEstimate(const t_grpopts& groupOptions)
466 {
467     real nrdfCoupled   = 0;
468     real nrdfUncoupled = 0;
469     real kineticEnergy = 0;
470     for (int g = 0; g < groupOptions.ngtc; g++)
471     {
472         if (groupOptions.tau_t[g] >= 0)
473         {
474             nrdfCoupled += groupOptions.nrdf[g];
475             kineticEnergy += groupOptions.nrdf[g] * 0.5 * groupOptions.ref_t[g] * BOLTZ;
476         }
477         else
478         {
479             nrdfUncoupled += groupOptions.nrdf[g];
480         }
481     }
482
483     /* This conditional with > also catches nrdf=0 */
484     if (nrdfCoupled > nrdfUncoupled)
485     {
486         return kineticEnergy * (nrdfCoupled + nrdfUncoupled) / nrdfCoupled;
487     }
488     else
489     {
490         return 0;
491     }
492 }
493
494 /*! \brief This routine checks that the potential energy is finite.
495  *
496  * Always checks that the potential energy is finite. If step equals
497  * inputrec.init_step also checks that the magnitude of the potential energy
498  * is reasonable. Terminates with a fatal error when a check fails.
499  * Note that passing this check does not guarantee finite forces,
500  * since those use slightly different arithmetics. But in most cases
501  * there is just a narrow coordinate range where forces are not finite
502  * and energies are finite.
503  *
504  * \param[in] step      The step number, used for checking and printing
505  * \param[in] enerd     The energy data; the non-bonded group energies need to be added to
506  * enerd.term[F_EPOT] before calling this routine \param[in] inputrec  The input record
507  */
508 static void checkPotentialEnergyValidity(int64_t step, const gmx_enerdata_t& enerd, const t_inputrec& inputrec)
509 {
510     /* Threshold valid for comparing absolute potential energy against
511      * the kinetic energy. Normally one should not consider absolute
512      * potential energy values, but with a factor of one million
513      * we should never get false positives.
514      */
515     constexpr real c_thresholdFactor = 1e6;
516
517     bool energyIsNotFinite    = !std::isfinite(enerd.term[F_EPOT]);
518     real averageKineticEnergy = 0;
519     /* We only check for large potential energy at the initial step,
520      * because that is by far the most likely step for this too occur
521      * and because computing the average kinetic energy is not free.
522      * Note: nstcalcenergy >> 1 often does not allow to catch large energies
523      * before they become NaN.
524      */
525     if (step == inputrec.init_step && EI_DYNAMICS(inputrec.eI))
526     {
527         averageKineticEnergy = averageKineticEnergyEstimate(inputrec.opts);
528     }
529
530     if (energyIsNotFinite
531         || (averageKineticEnergy > 0 && enerd.term[F_EPOT] > c_thresholdFactor * averageKineticEnergy))
532     {
533         gmx_fatal(
534                 FARGS,
535                 "Step %" PRId64
536                 ": The total potential energy is %g, which is %s. The LJ and electrostatic "
537                 "contributions to the energy are %g and %g, respectively. A %s potential energy "
538                 "can be caused by overlapping interactions in bonded interactions or very large%s "
539                 "coordinate values. Usually this is caused by a badly- or non-equilibrated initial "
540                 "configuration, incorrect interactions or parameters in the topology.",
541                 step, enerd.term[F_EPOT], energyIsNotFinite ? "not finite" : "extremely high",
542                 enerd.term[F_LJ], enerd.term[F_COUL_SR],
543                 energyIsNotFinite ? "non-finite" : "very high", energyIsNotFinite ? " or Nan" : "");
544     }
545 }
546
547 /*! \brief Return true if there are special forces computed this step.
548  *
549  * The conditionals exactly correspond to those in computeSpecialForces().
550  */
551 static bool haveSpecialForces(const t_inputrec&          inputrec,
552                               const gmx::ForceProviders& forceProviders,
553                               const pull_t*              pull_work,
554                               const bool                 computeForces,
555                               const gmx_edsam*           ed)
556 {
557
558     return ((computeForces && forceProviders.hasForceProvider()) || // forceProviders
559             (inputrec.bPull && pull_have_potential(pull_work)) ||   // pull
560             inputrec.bRot ||                                        // enforced rotation
561             (ed != nullptr) ||                                      // flooding
562             (inputrec.bIMD && computeForces));                      // IMD
563 }
564
565 /*! \brief Compute forces and/or energies for special algorithms
566  *
567  * The intention is to collect all calls to algorithms that compute
568  * forces on local atoms only and that do not contribute to the local
569  * virial sum (but add their virial contribution separately).
570  * Eventually these should likely all become ForceProviders.
571  * Within this function the intention is to have algorithms that do
572  * global communication at the end, so global barriers within the MD loop
573  * are as close together as possible.
574  *
575  * \param[in]     fplog            The log file
576  * \param[in]     cr               The communication record
577  * \param[in]     inputrec         The input record
578  * \param[in]     awh              The Awh module (nullptr if none in use).
579  * \param[in]     enforcedRotation Enforced rotation module.
580  * \param[in]     imdSession       The IMD session
581  * \param[in]     pull_work        The pull work structure.
582  * \param[in]     step             The current MD step
583  * \param[in]     t                The current time
584  * \param[in,out] wcycle           Wallcycle accounting struct
585  * \param[in,out] forceProviders   Pointer to a list of force providers
586  * \param[in]     box              The unit cell
587  * \param[in]     x                The coordinates
588  * \param[in]     mdatoms          Per atom properties
589  * \param[in]     lambda           Array of free-energy lambda values
590  * \param[in]     stepWork         Step schedule flags
591  * \param[in,out] forceWithVirial  Force and virial buffers
592  * \param[in,out] enerd            Energy buffer
593  * \param[in,out] ed               Essential dynamics pointer
594  * \param[in]     didNeighborSearch Tells if we did neighbor searching this step, used for ED sampling
595  *
596  * \todo Remove didNeighborSearch, which is used incorrectly.
597  * \todo Convert all other algorithms called here to ForceProviders.
598  */
599 static void computeSpecialForces(FILE*                          fplog,
600                                  const t_commrec*               cr,
601                                  const t_inputrec*              inputrec,
602                                  gmx::Awh*                      awh,
603                                  gmx_enfrot*                    enforcedRotation,
604                                  gmx::ImdSession*               imdSession,
605                                  pull_t*                        pull_work,
606                                  int64_t                        step,
607                                  double                         t,
608                                  gmx_wallcycle_t                wcycle,
609                                  gmx::ForceProviders*           forceProviders,
610                                  const matrix                   box,
611                                  gmx::ArrayRef<const gmx::RVec> x,
612                                  const t_mdatoms*               mdatoms,
613                                  real*                          lambda,
614                                  const StepWorkload&            stepWork,
615                                  gmx::ForceWithVirial*          forceWithVirial,
616                                  gmx_enerdata_t*                enerd,
617                                  gmx_edsam*                     ed,
618                                  bool                           didNeighborSearch)
619 {
620     /* NOTE: Currently all ForceProviders only provide forces.
621      *       When they also provide energies, remove this conditional.
622      */
623     if (stepWork.computeForces)
624     {
625         gmx::ForceProviderInput  forceProviderInput(x, *mdatoms, t, box, *cr);
626         gmx::ForceProviderOutput forceProviderOutput(forceWithVirial, enerd);
627
628         /* Collect forces from modules */
629         forceProviders->calculateForces(forceProviderInput, &forceProviderOutput);
630     }
631
632     if (inputrec->bPull && pull_have_potential(pull_work))
633     {
634         pull_potential_wrapper(cr, inputrec, box, x, forceWithVirial, mdatoms, enerd, pull_work,
635                                lambda, t, wcycle);
636
637         if (awh)
638         {
639             enerd->term[F_COM_PULL] += awh->applyBiasForcesAndUpdateBias(
640                     inputrec->pbcType, mdatoms->massT, box, forceWithVirial, t, step, wcycle, fplog);
641         }
642     }
643
644     rvec* f = as_rvec_array(forceWithVirial->force_.data());
645
646     /* Add the forces from enforced rotation potentials (if any) */
647     if (inputrec->bRot)
648     {
649         wallcycle_start(wcycle, ewcROTadd);
650         enerd->term[F_COM_PULL] += add_rot_forces(enforcedRotation, f, cr, step, t);
651         wallcycle_stop(wcycle, ewcROTadd);
652     }
653
654     if (ed)
655     {
656         /* Note that since init_edsam() is called after the initialization
657          * of forcerec, edsam doesn't request the noVirSum force buffer.
658          * Thus if no other algorithm (e.g. PME) requires it, the forces
659          * here will contribute to the virial.
660          */
661         do_flood(cr, inputrec, as_rvec_array(x.data()), f, ed, box, step, didNeighborSearch);
662     }
663
664     /* Add forces from interactive molecular dynamics (IMD), if any */
665     if (inputrec->bIMD && stepWork.computeForces)
666     {
667         imdSession->applyForces(f);
668     }
669 }
670
671 /*! \brief Launch the prepare_step and spread stages of PME GPU.
672  *
673  * \param[in]  pmedata              The PME structure
674  * \param[in]  box                  The box matrix
675  * \param[in]  stepWork             Step schedule flags
676  * \param[in]  xReadyOnDevice       Event synchronizer indicating that the coordinates are ready in
677  * the device memory. \param[in]  wcycle               The wallcycle structure
678  */
679 static inline void launchPmeGpuSpread(gmx_pme_t*            pmedata,
680                                       const matrix          box,
681                                       const StepWorkload&   stepWork,
682                                       GpuEventSynchronizer* xReadyOnDevice,
683                                       gmx_wallcycle_t       wcycle)
684 {
685     pme_gpu_prepare_computation(pmedata, box, wcycle, stepWork);
686     pme_gpu_launch_spread(pmedata, xReadyOnDevice, wcycle);
687 }
688
689 /*! \brief Launch the FFT and gather stages of PME GPU
690  *
691  * This function only implements setting the output forces (no accumulation).
692  *
693  * \param[in]  pmedata        The PME structure
694  * \param[in]  wcycle         The wallcycle structure
695  * \param[in]  stepWork       Step schedule flags
696  */
697 static void launchPmeGpuFftAndGather(gmx_pme_t* pmedata, gmx_wallcycle_t wcycle, const gmx::StepWorkload& stepWork)
698 {
699     pme_gpu_launch_complex_transforms(pmedata, wcycle, stepWork);
700     pme_gpu_launch_gather(pmedata, wcycle);
701 }
702
703 /*! \brief
704  *  Polling wait for either of the PME or nonbonded GPU tasks.
705  *
706  * Instead of a static order in waiting for GPU tasks, this function
707  * polls checking which of the two tasks completes first, and does the
708  * associated force buffer reduction overlapped with the other task.
709  * By doing that, unlike static scheduling order, it can always overlap
710  * one of the reductions, regardless of the GPU task completion order.
711  *
712  * \param[in]     nbv              Nonbonded verlet structure
713  * \param[in,out] pmedata          PME module data
714  * \param[in,out] forceOutputs     Output buffer for the forces and virial
715  * \param[in,out] enerd            Energy data structure results are reduced into
716  * \param[in]     stepWork         Step schedule flags
717  * \param[in]     wcycle           The wallcycle structure
718  */
719 static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t* nbv,
720                                         gmx_pme_t*          pmedata,
721                                         gmx::ForceOutputs*  forceOutputs,
722                                         gmx_enerdata_t*     enerd,
723                                         const StepWorkload& stepWork,
724                                         gmx_wallcycle_t     wcycle)
725 {
726     bool isPmeGpuDone = false;
727     bool isNbGpuDone  = false;
728
729
730     gmx::ForceWithShiftForces& forceWithShiftForces = forceOutputs->forceWithShiftForces();
731     gmx::ForceWithVirial&      forceWithVirial      = forceOutputs->forceWithVirial();
732
733     gmx::ArrayRef<const gmx::RVec> pmeGpuForces;
734
735     while (!isPmeGpuDone || !isNbGpuDone)
736     {
737         if (!isPmeGpuDone)
738         {
739             GpuTaskCompletion completionType =
740                     (isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
741             isPmeGpuDone = pme_gpu_try_finish_task(pmedata, stepWork, wcycle, &forceWithVirial,
742                                                    enerd, completionType);
743         }
744
745         if (!isNbGpuDone)
746         {
747             GpuTaskCompletion completionType =
748                     (isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
749             isNbGpuDone = Nbnxm::gpu_try_finish_task(
750                     nbv->gpu_nbv, stepWork, AtomLocality::Local, enerd->grpp.ener[egLJSR].data(),
751                     enerd->grpp.ener[egCOULSR].data(), forceWithShiftForces.shiftForces(),
752                     completionType, wcycle);
753
754             if (isNbGpuDone)
755             {
756                 nbv->atomdata_add_nbat_f_to_f(AtomLocality::Local, forceWithShiftForces.force());
757             }
758         }
759     }
760 }
761
762 /*! \brief Set up the different force buffers; also does clearing.
763  *
764  * \param[in] forceHelperBuffers  Helper force buffers
765  * \param[in] pull_work The pull work object.
766  * \param[in] inputrec  input record
767  * \param[in] force     force array
768  * \param[in] stepWork  Step schedule flags
769  * \param[out] wcycle   wallcycle recording structure
770  *
771  * \returns             Cleared force output structure
772  */
773 static ForceOutputs setupForceOutputs(ForceHelperBuffers*                 forceHelperBuffers,
774                                       pull_t*                             pull_work,
775                                       const t_inputrec&                   inputrec,
776                                       gmx::ArrayRefWithPadding<gmx::RVec> force,
777                                       const StepWorkload&                 stepWork,
778                                       gmx_wallcycle_t                     wcycle)
779 {
780     wallcycle_sub_start(wcycle, ewcsCLEAR_FORCE_BUFFER);
781
782     /* NOTE: We assume fr->shiftForces is all zeros here */
783     gmx::ForceWithShiftForces forceWithShiftForces(force, stepWork.computeVirial,
784                                                    forceHelperBuffers->shiftForces());
785
786     if (stepWork.computeForces)
787     {
788         /* Clear the short- and long-range forces */
789         clearRVecs(forceWithShiftForces.force(), true);
790
791         /* Clear the shift forces */
792         clearRVecs(forceWithShiftForces.shiftForces(), false);
793     }
794
795     /* If we need to compute the virial, we might need a separate
796      * force buffer for algorithms for which the virial is calculated
797      * directly, such as PME. Otherwise, forceWithVirial uses the
798      * the same force (f in legacy calls) buffer as other algorithms.
799      */
800     const bool useSeparateForceWithVirialBuffer =
801             (stepWork.computeForces
802              && (stepWork.computeVirial && forceHelperBuffers->haveDirectVirialContributions()));
803     /* forceWithVirial uses the local atom range only */
804     gmx::ForceWithVirial forceWithVirial(
805             useSeparateForceWithVirialBuffer ? forceHelperBuffers->forceBufferForDirectVirialContributions()
806                                              : force.unpaddedArrayRef(),
807             stepWork.computeVirial);
808
809     if (useSeparateForceWithVirialBuffer)
810     {
811         /* TODO: update comment
812          * We only compute forces on local atoms. Note that vsites can
813          * spread to non-local atoms, but that part of the buffer is
814          * cleared separately in the vsite spreading code.
815          */
816         clearRVecs(forceWithVirial.force_, true);
817     }
818
819     if (inputrec.bPull && pull_have_constraint(pull_work))
820     {
821         clear_pull_forces(pull_work);
822     }
823
824     wallcycle_sub_stop(wcycle, ewcsCLEAR_FORCE_BUFFER);
825
826     return ForceOutputs(forceWithShiftForces, forceHelperBuffers->haveDirectVirialContributions(),
827                         forceWithVirial);
828 }
829
830
831 /*! \brief Set up flags that have the lifetime of the domain indicating what type of work is there to compute.
832  */
833 static DomainLifetimeWorkload setupDomainLifetimeWorkload(const t_inputrec&         inputrec,
834                                                           const t_forcerec&         fr,
835                                                           const pull_t*             pull_work,
836                                                           const gmx_edsam*          ed,
837                                                           const t_mdatoms&          mdatoms,
838                                                           const SimulationWorkload& simulationWork,
839                                                           const StepWorkload&       stepWork)
840 {
841     DomainLifetimeWorkload domainWork;
842     // Note that haveSpecialForces is constant over the whole run
843     domainWork.haveSpecialForces =
844             haveSpecialForces(inputrec, *fr.forceProviders, pull_work, stepWork.computeForces, ed);
845     domainWork.haveCpuBondedWork  = fr.listedForces->haveCpuBondeds();
846     domainWork.haveGpuBondedWork  = ((fr.gpuBonded != nullptr) && fr.gpuBonded->haveInteractions());
847     domainWork.haveRestraintsWork = fr.listedForces->haveRestraints();
848     domainWork.haveCpuListedForceWork = fr.listedForces->haveCpuListedForces();
849     // Note that haveFreeEnergyWork is constant over the whole run
850     domainWork.haveFreeEnergyWork = (fr.efep != efepNO && mdatoms.nPerturbed != 0);
851     // We assume we have local force work if there are CPU
852     // force tasks including PME or nonbondeds.
853     domainWork.haveCpuLocalForceWork =
854             domainWork.haveSpecialForces || domainWork.haveCpuListedForceWork
855             || domainWork.haveFreeEnergyWork || simulationWork.useCpuNonbonded || simulationWork.useCpuPme
856             || simulationWork.haveEwaldSurfaceContribution || inputrec.nwall > 0;
857
858     return domainWork;
859 }
860
861 /*! \brief Set up force flag stuct from the force bitmask.
862  *
863  * \param[in]      legacyFlags          Force bitmask flags used to construct the new flags
864  * \param[in]      isNonbondedOn        Global override, if false forces to turn off all nonbonded calculation.
865  * \param[in]      simulationWork       Simulation workload description.
866  * \param[in]      rankHasPmeDuty       If this rank computes PME.
867  *
868  * \returns New Stepworkload description.
869  */
870 static StepWorkload setupStepWorkload(const int                 legacyFlags,
871                                       const bool                isNonbondedOn,
872                                       const SimulationWorkload& simulationWork,
873                                       const bool                rankHasPmeDuty)
874 {
875     StepWorkload flags;
876     flags.stateChanged           = ((legacyFlags & GMX_FORCE_STATECHANGED) != 0);
877     flags.haveDynamicBox         = ((legacyFlags & GMX_FORCE_DYNAMICBOX) != 0);
878     flags.doNeighborSearch       = ((legacyFlags & GMX_FORCE_NS) != 0);
879     flags.computeVirial          = ((legacyFlags & GMX_FORCE_VIRIAL) != 0);
880     flags.computeEnergy          = ((legacyFlags & GMX_FORCE_ENERGY) != 0);
881     flags.computeForces          = ((legacyFlags & GMX_FORCE_FORCES) != 0);
882     flags.computeListedForces    = ((legacyFlags & GMX_FORCE_LISTED) != 0);
883     flags.computeNonbondedForces = ((legacyFlags & GMX_FORCE_NONBONDED) != 0) && isNonbondedOn;
884     flags.computeDhdl            = ((legacyFlags & GMX_FORCE_DHDL) != 0);
885
886     if (simulationWork.useGpuBufferOps)
887     {
888         GMX_ASSERT(simulationWork.useGpuNonbonded,
889                    "Can only offload buffer ops if nonbonded computation is also offloaded");
890     }
891     flags.useGpuXBufferOps = simulationWork.useGpuBufferOps;
892     // on virial steps the CPU reduction path is taken
893     flags.useGpuFBufferOps    = simulationWork.useGpuBufferOps && !flags.computeVirial;
894     flags.useGpuPmeFReduction = flags.useGpuFBufferOps
895                                 && (simulationWork.useGpuPme
896                                     && (rankHasPmeDuty || simulationWork.useGpuPmePpCommunication));
897
898     return flags;
899 }
900
901
902 /* \brief Launch end-of-step GPU tasks: buffer clearing and rolling pruning.
903  *
904  * TODO: eliminate \p useGpuPmeOnThisRank when this is
905  * incorporated in DomainLifetimeWorkload.
906  */
907 static void launchGpuEndOfStepTasks(nonbonded_verlet_t*               nbv,
908                                     gmx::GpuBonded*                   gpuBonded,
909                                     gmx_pme_t*                        pmedata,
910                                     gmx_enerdata_t*                   enerd,
911                                     const gmx::MdrunScheduleWorkload& runScheduleWork,
912                                     bool                              useGpuPmeOnThisRank,
913                                     int64_t                           step,
914                                     gmx_wallcycle_t                   wcycle)
915 {
916     if (runScheduleWork.simulationWork.useGpuNonbonded)
917     {
918         /* Launch pruning before buffer clearing because the API overhead of the
919          * clear kernel launches can leave the GPU idle while it could be running
920          * the prune kernel.
921          */
922         if (nbv->isDynamicPruningStepGpu(step))
923         {
924             nbv->dispatchPruneKernelGpu(step);
925         }
926
927         /* now clear the GPU outputs while we finish the step on the CPU */
928         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
929         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
930         Nbnxm::gpu_clear_outputs(nbv->gpu_nbv, runScheduleWork.stepWork.computeVirial);
931         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
932         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
933     }
934
935     if (useGpuPmeOnThisRank)
936     {
937         pme_gpu_reinit_computation(pmedata, wcycle);
938     }
939
940     if (runScheduleWork.domainWork.haveGpuBondedWork && runScheduleWork.stepWork.computeEnergy)
941     {
942         // in principle this should be included in the DD balancing region,
943         // but generally it is infrequent so we'll omit it for the sake of
944         // simpler code
945         gpuBonded->waitAccumulateEnergyTerms(enerd);
946
947         gpuBonded->clearEnergies();
948     }
949 }
950
951 //! \brief Data structure to hold dipole-related data and staging arrays
952 struct DipoleData
953 {
954     //! Dipole staging for fast summing over MPI
955     gmx::DVec muStaging[2] = { { 0.0, 0.0, 0.0 } };
956     //! Dipole staging for states A and B (index 0 and 1 resp.)
957     gmx::RVec muStateAB[2] = { { 0.0_real, 0.0_real, 0.0_real } };
958 };
959
960
961 static void reduceAndUpdateMuTot(DipoleData*                   dipoleData,
962                                  const t_commrec*              cr,
963                                  const bool                    haveFreeEnergy,
964                                  gmx::ArrayRef<const real>     lambda,
965                                  rvec                          muTotal,
966                                  const DDBalanceRegionHandler& ddBalanceRegionHandler)
967 {
968     if (PAR(cr))
969     {
970         gmx_sumd(2 * DIM, dipoleData->muStaging[0], cr);
971         ddBalanceRegionHandler.reopenRegionCpu();
972     }
973     for (int i = 0; i < 2; i++)
974     {
975         for (int j = 0; j < DIM; j++)
976         {
977             dipoleData->muStateAB[i][j] = dipoleData->muStaging[i][j];
978         }
979     }
980
981     if (!haveFreeEnergy)
982     {
983         copy_rvec(dipoleData->muStateAB[0], muTotal);
984     }
985     else
986     {
987         for (int j = 0; j < DIM; j++)
988         {
989             muTotal[j] = (1.0 - lambda[efptCOUL]) * dipoleData->muStateAB[0][j]
990                          + lambda[efptCOUL] * dipoleData->muStateAB[1][j];
991         }
992     }
993 }
994
995 void do_force(FILE*                               fplog,
996               const t_commrec*                    cr,
997               const gmx_multisim_t*               ms,
998               const t_inputrec*                   inputrec,
999               gmx::Awh*                           awh,
1000               gmx_enfrot*                         enforcedRotation,
1001               gmx::ImdSession*                    imdSession,
1002               pull_t*                             pull_work,
1003               int64_t                             step,
1004               t_nrnb*                             nrnb,
1005               gmx_wallcycle_t                     wcycle,
1006               const gmx_localtop_t*               top,
1007               const matrix                        box,
1008               gmx::ArrayRefWithPadding<gmx::RVec> x,
1009               history_t*                          hist,
1010               gmx::ArrayRefWithPadding<gmx::RVec> force,
1011               tensor                              vir_force,
1012               const t_mdatoms*                    mdatoms,
1013               gmx_enerdata_t*                     enerd,
1014               gmx::ArrayRef<real>                 lambda,
1015               t_forcerec*                         fr,
1016               gmx::MdrunScheduleWorkload*         runScheduleWork,
1017               gmx::VirtualSitesHandler*           vsite,
1018               rvec                                muTotal,
1019               double                              t,
1020               gmx_edsam*                          ed,
1021               int                                 legacyFlags,
1022               const DDBalanceRegionHandler&       ddBalanceRegionHandler)
1023 {
1024     GMX_ASSERT(force.unpaddedArrayRef().ssize() >= fr->natoms_force_constr,
1025                "The size of the force buffer should be at least the number of atoms to compute "
1026                "forces for");
1027
1028     nonbonded_verlet_t*          nbv      = fr->nbv.get();
1029     interaction_const_t*         ic       = fr->ic;
1030     gmx::StatePropagatorDataGpu* stateGpu = fr->stateGpu;
1031
1032     const SimulationWorkload& simulationWork = runScheduleWork->simulationWork;
1033
1034
1035     runScheduleWork->stepWork    = setupStepWorkload(legacyFlags, fr->bNonbonded, simulationWork,
1036                                                   thisRankHasDuty(cr, DUTY_PME));
1037     const StepWorkload& stepWork = runScheduleWork->stepWork;
1038
1039
1040     const bool useGpuPmeOnThisRank = simulationWork.useGpuPme && thisRankHasDuty(cr, DUTY_PME);
1041
1042     /* At a search step we need to start the first balancing region
1043      * somewhere early inside the step after communication during domain
1044      * decomposition (and not during the previous step as usual).
1045      */
1046     if (stepWork.doNeighborSearch)
1047     {
1048         ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::yes);
1049     }
1050
1051     clear_mat(vir_force);
1052
1053     if (fr->pbcType != PbcType::No)
1054     {
1055         /* Compute shift vectors every step,
1056          * because of pressure coupling or box deformation!
1057          */
1058         if (stepWork.haveDynamicBox && stepWork.stateChanged)
1059         {
1060             calc_shifts(box, fr->shift_vec);
1061         }
1062
1063         const bool fillGrid = (stepWork.doNeighborSearch && stepWork.stateChanged);
1064         const bool calcCGCM = (fillGrid && !DOMAINDECOMP(cr));
1065         if (calcCGCM)
1066         {
1067             put_atoms_in_box_omp(fr->pbcType, box, x.unpaddedArrayRef().subArray(0, mdatoms->homenr),
1068                                  gmx_omp_nthreads_get(emntDefault));
1069             inc_nrnb(nrnb, eNR_SHIFTX, mdatoms->homenr);
1070         }
1071     }
1072
1073     nbnxn_atomdata_copy_shiftvec(stepWork.haveDynamicBox, fr->shift_vec, nbv->nbat.get());
1074
1075     const bool pmeSendCoordinatesFromGpu =
1076             GMX_MPI && simulationWork.useGpuPmePpCommunication && !(stepWork.doNeighborSearch);
1077     const bool reinitGpuPmePpComms =
1078             GMX_MPI && simulationWork.useGpuPmePpCommunication && (stepWork.doNeighborSearch);
1079
1080     const auto localXReadyOnDevice = (useGpuPmeOnThisRank || simulationWork.useGpuBufferOps)
1081                                              ? stateGpu->getCoordinatesReadyOnDeviceEvent(
1082                                                        AtomLocality::Local, simulationWork, stepWork)
1083                                              : nullptr;
1084
1085     // If coordinates are to be sent to PME task from CPU memory, perform that send here.
1086     // Otherwise the send will occur after H2D coordinate transfer.
1087     if (GMX_MPI && !thisRankHasDuty(cr, DUTY_PME) && !pmeSendCoordinatesFromGpu)
1088     {
1089         /* Send particle coordinates to the pme nodes */
1090         if (!stepWork.doNeighborSearch && simulationWork.useGpuUpdate)
1091         {
1092             GMX_RELEASE_ASSERT(false,
1093                                "GPU update and separate PME ranks are only supported with GPU "
1094                                "direct communication!");
1095             // TODO: when this code-path becomes supported add:
1096             // stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local);
1097         }
1098
1099         gmx_pme_send_coordinates(fr, cr, box, as_rvec_array(x.unpaddedArrayRef().data()), lambda[efptCOUL],
1100                                  lambda[efptVDW], (stepWork.computeVirial || stepWork.computeEnergy),
1101                                  step, simulationWork.useGpuPmePpCommunication, reinitGpuPmePpComms,
1102                                  pmeSendCoordinatesFromGpu, localXReadyOnDevice, wcycle);
1103     }
1104
1105     // Coordinates on the device are needed if PME or BufferOps are offloaded.
1106     // The local coordinates can be copied right away.
1107     // NOTE: Consider moving this copy to right after they are updated and constrained,
1108     //       if the later is not offloaded.
1109     if (useGpuPmeOnThisRank || stepWork.useGpuXBufferOps)
1110     {
1111         if (stepWork.doNeighborSearch)
1112         {
1113             // TODO refactor this to do_md, after partitioning.
1114             stateGpu->reinit(mdatoms->homenr,
1115                              cr->dd != nullptr ? dd_numAtomsZones(*cr->dd) : mdatoms->homenr);
1116             if (useGpuPmeOnThisRank)
1117             {
1118                 // TODO: This should be moved into PME setup function ( pme_gpu_prepare_computation(...) )
1119                 pme_gpu_set_device_x(fr->pmedata, stateGpu->getCoordinates());
1120             }
1121         }
1122         // We need to copy coordinates when:
1123         // 1. Update is not offloaded
1124         // 2. The buffers were reinitialized on search step
1125         if (!simulationWork.useGpuUpdate || stepWork.doNeighborSearch)
1126         {
1127             GMX_ASSERT(stateGpu != nullptr, "stateGpu should not be null");
1128             stateGpu->copyCoordinatesToGpu(x.unpaddedArrayRef(), AtomLocality::Local);
1129         }
1130     }
1131
1132     // TODO Update this comment when introducing SimulationWorkload
1133     //
1134     // The conditions for gpuHaloExchange e.g. using GPU buffer
1135     // operations were checked before construction, so here we can
1136     // just use it and assert upon any conditions.
1137     const bool ddUsesGpuDirectCommunication =
1138             ((cr->dd != nullptr) && (!cr->dd->gpuHaloExchange.empty()));
1139     GMX_ASSERT(!ddUsesGpuDirectCommunication || stepWork.useGpuXBufferOps,
1140                "Must use coordinate buffer ops with GPU halo exchange");
1141     const bool useGpuForcesHaloExchange = ddUsesGpuDirectCommunication && stepWork.useGpuFBufferOps;
1142
1143     // Copy coordinate from the GPU if update is on the GPU and there
1144     // are forces to be computed on the CPU, or for the computation of
1145     // virial, or if host-side data will be transferred from this task
1146     // to a remote task for halo exchange or PME-PP communication. At
1147     // search steps the current coordinates are already on the host,
1148     // hence copy is not needed.
1149     const bool haveHostPmePpComms =
1150             !thisRankHasDuty(cr, DUTY_PME) && !simulationWork.useGpuPmePpCommunication;
1151     const bool haveHostHaloExchangeComms = havePPDomainDecomposition(cr) && !ddUsesGpuDirectCommunication;
1152
1153     bool gmx_used_in_debug haveCopiedXFromGpu = false;
1154     if (simulationWork.useGpuUpdate && !stepWork.doNeighborSearch
1155         && (runScheduleWork->domainWork.haveCpuLocalForceWork || stepWork.computeVirial
1156             || haveHostPmePpComms || haveHostHaloExchangeComms))
1157     {
1158         GMX_ASSERT(stateGpu != nullptr, "stateGpu should not be null");
1159         stateGpu->copyCoordinatesFromGpu(x.unpaddedArrayRef(), AtomLocality::Local);
1160         haveCopiedXFromGpu = true;
1161     }
1162
1163     // If coordinates are to be sent to PME task from GPU memory, perform that send here.
1164     // Otherwise the send will occur before the H2D coordinate transfer.
1165     if (!thisRankHasDuty(cr, DUTY_PME) && pmeSendCoordinatesFromGpu)
1166     {
1167         /* Send particle coordinates to the pme nodes */
1168         gmx_pme_send_coordinates(fr, cr, box, as_rvec_array(x.unpaddedArrayRef().data()), lambda[efptCOUL],
1169                                  lambda[efptVDW], (stepWork.computeVirial || stepWork.computeEnergy),
1170                                  step, simulationWork.useGpuPmePpCommunication, reinitGpuPmePpComms,
1171                                  pmeSendCoordinatesFromGpu, localXReadyOnDevice, wcycle);
1172     }
1173
1174     if (useGpuPmeOnThisRank)
1175     {
1176         launchPmeGpuSpread(fr->pmedata, box, stepWork, localXReadyOnDevice, wcycle);
1177     }
1178
1179     /* do gridding for pair search */
1180     if (stepWork.doNeighborSearch)
1181     {
1182         if (fr->wholeMoleculeTransform && stepWork.stateChanged)
1183         {
1184             fr->wholeMoleculeTransform->updateForAtomPbcJumps(x.unpaddedArrayRef(), box);
1185         }
1186
1187         // TODO
1188         // - vzero is constant, do we need to pass it?
1189         // - box_diag should be passed directly to nbnxn_put_on_grid
1190         //
1191         rvec vzero;
1192         clear_rvec(vzero);
1193
1194         rvec box_diag;
1195         box_diag[XX] = box[XX][XX];
1196         box_diag[YY] = box[YY][YY];
1197         box_diag[ZZ] = box[ZZ][ZZ];
1198
1199         wallcycle_start(wcycle, ewcNS);
1200         if (!DOMAINDECOMP(cr))
1201         {
1202             wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL);
1203             nbnxn_put_on_grid(nbv, box, 0, vzero, box_diag, nullptr, { 0, mdatoms->homenr }, -1,
1204                               fr->cginfo, x.unpaddedArrayRef(), 0, nullptr);
1205             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL);
1206         }
1207         else
1208         {
1209             wallcycle_sub_start(wcycle, ewcsNBS_GRID_NONLOCAL);
1210             nbnxn_put_on_grid_nonlocal(nbv, domdec_zones(cr->dd), fr->cginfo, x.unpaddedArrayRef());
1211             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_NONLOCAL);
1212         }
1213
1214         nbv->setAtomProperties(gmx::constArrayRefFromArray(mdatoms->typeA, mdatoms->nr),
1215                                gmx::constArrayRefFromArray(mdatoms->chargeA, mdatoms->nr), fr->cginfo);
1216
1217         wallcycle_stop(wcycle, ewcNS);
1218
1219         /* initialize the GPU nbnxm atom data and bonded data structures */
1220         if (simulationWork.useGpuNonbonded)
1221         {
1222             wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1223
1224             wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1225             Nbnxm::gpu_init_atomdata(nbv->gpu_nbv, nbv->nbat.get());
1226             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1227
1228             if (fr->gpuBonded)
1229             {
1230                 /* Now we put all atoms on the grid, we can assign bonded
1231                  * interactions to the GPU, where the grid order is
1232                  * needed. Also the xq, f and fshift device buffers have
1233                  * been reallocated if needed, so the bonded code can
1234                  * learn about them. */
1235                 // TODO the xq, f, and fshift buffers are now shared
1236                 // resources, so they should be maintained by a
1237                 // higher-level object than the nb module.
1238                 fr->gpuBonded->updateInteractionListsAndDeviceBuffers(
1239                         nbv->getGridIndices(), top->idef, Nbnxm::gpu_get_xq(nbv->gpu_nbv),
1240                         Nbnxm::gpu_get_f(nbv->gpu_nbv), Nbnxm::gpu_get_fshift(nbv->gpu_nbv));
1241             }
1242             wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1243         }
1244
1245         // Need to run after the GPU-offload bonded interaction lists
1246         // are set up to be able to determine whether there is bonded work.
1247         runScheduleWork->domainWork = setupDomainLifetimeWorkload(
1248                 *inputrec, *fr, pull_work, ed, *mdatoms, simulationWork, stepWork);
1249
1250         wallcycle_start_nocount(wcycle, ewcNS);
1251         wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_LOCAL);
1252         /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1253         nbv->constructPairlist(InteractionLocality::Local, top->excls, step, nrnb);
1254
1255         nbv->setupGpuShortRangeWork(fr->gpuBonded, InteractionLocality::Local);
1256
1257         wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_LOCAL);
1258         wallcycle_stop(wcycle, ewcNS);
1259
1260         if (stepWork.useGpuXBufferOps)
1261         {
1262             nbv->atomdata_init_copy_x_to_nbat_x_gpu();
1263         }
1264         // For force buffer ops, we use the below conditon rather than
1265         // useGpuFBufferOps to ensure that init is performed even if this
1266         // NS step is also a virial step (on which f buf ops are deactivated).
1267         if (simulationWork.useGpuBufferOps && simulationWork.useGpuNonbonded && (GMX_GPU == GMX_GPU_CUDA))
1268         {
1269             GMX_ASSERT(stateGpu, "stateGpu should be valid when buffer ops are offloaded");
1270             nbv->atomdata_init_add_nbat_f_to_f_gpu(stateGpu->fReducedOnDevice());
1271         }
1272     }
1273     else if (!EI_TPI(inputrec->eI))
1274     {
1275         if (stepWork.useGpuXBufferOps)
1276         {
1277             GMX_ASSERT(stateGpu, "stateGpu should be valid when buffer ops are offloaded");
1278             nbv->convertCoordinatesGpu(AtomLocality::Local, false, stateGpu->getCoordinates(),
1279                                        localXReadyOnDevice);
1280         }
1281         else
1282         {
1283             if (simulationWork.useGpuUpdate)
1284             {
1285                 GMX_ASSERT(stateGpu, "need a valid stateGpu object");
1286                 GMX_ASSERT(haveCopiedXFromGpu,
1287                            "a wait should only be triggered if copy has been scheduled");
1288                 stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local);
1289             }
1290             nbv->convertCoordinates(AtomLocality::Local, false, x.unpaddedArrayRef());
1291         }
1292     }
1293
1294     const gmx::DomainLifetimeWorkload& domainWork = runScheduleWork->domainWork;
1295
1296     if (simulationWork.useGpuNonbonded)
1297     {
1298         ddBalanceRegionHandler.openBeforeForceComputationGpu();
1299
1300         wallcycle_start(wcycle, ewcLAUNCH_GPU);
1301
1302         wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1303         Nbnxm::gpu_upload_shiftvec(nbv->gpu_nbv, nbv->nbat.get());
1304         if (stepWork.doNeighborSearch || !stepWork.useGpuXBufferOps)
1305         {
1306             Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(), AtomLocality::Local);
1307         }
1308         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1309         // with X buffer ops offloaded to the GPU on all but the search steps
1310
1311         // bonded work not split into separate local and non-local, so with DD
1312         // we can only launch the kernel after non-local coordinates have been received.
1313         if (domainWork.haveGpuBondedWork && !havePPDomainDecomposition(cr))
1314         {
1315             wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1316             fr->gpuBonded->setPbcAndlaunchKernel(fr->pbcType, box, fr->bMolPBC, stepWork);
1317             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1318         }
1319
1320         /* launch local nonbonded work on GPU */
1321         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1322         do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::Local, enbvClearFNo, step, nrnb, wcycle);
1323         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1324         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1325     }
1326
1327     if (useGpuPmeOnThisRank)
1328     {
1329         // In PME GPU and mixed mode we launch FFT / gather after the
1330         // X copy/transform to allow overlap as well as after the GPU NB
1331         // launch to avoid FFT launch overhead hijacking the CPU and delaying
1332         // the nonbonded kernel.
1333         launchPmeGpuFftAndGather(fr->pmedata, wcycle, stepWork);
1334     }
1335
1336     /* Communicate coordinates and sum dipole if necessary +
1337        do non-local pair search */
1338     if (havePPDomainDecomposition(cr))
1339     {
1340         if (stepWork.doNeighborSearch)
1341         {
1342             // TODO: fuse this branch with the above large stepWork.doNeighborSearch block
1343             wallcycle_start_nocount(wcycle, ewcNS);
1344             wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1345             /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1346             nbv->constructPairlist(InteractionLocality::NonLocal, top->excls, step, nrnb);
1347
1348             nbv->setupGpuShortRangeWork(fr->gpuBonded, InteractionLocality::NonLocal);
1349             wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1350             wallcycle_stop(wcycle, ewcNS);
1351             // TODO refactor this GPU halo exchange re-initialisation
1352             // to location in do_md where GPU halo exchange is
1353             // constructed at partitioning, after above stateGpu
1354             // re-initialization has similarly been refactored
1355             if (ddUsesGpuDirectCommunication)
1356             {
1357                 reinitGpuHaloExchange(*cr, stateGpu->getCoordinates(), stateGpu->getForces());
1358             }
1359         }
1360         else
1361         {
1362             if (ddUsesGpuDirectCommunication)
1363             {
1364                 // The following must be called after local setCoordinates (which records an event
1365                 // when the coordinate data has been copied to the device).
1366                 communicateGpuHaloCoordinates(*cr, box, localXReadyOnDevice);
1367
1368                 if (domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork)
1369                 {
1370                     // non-local part of coordinate buffer must be copied back to host for CPU work
1371                     stateGpu->copyCoordinatesFromGpu(x.unpaddedArrayRef(), AtomLocality::NonLocal);
1372                 }
1373             }
1374             else
1375             {
1376                 // Note: GPU update + DD without direct communication is not supported,
1377                 // a waitCoordinatesReadyOnHost() should be issued if it will be.
1378                 GMX_ASSERT(!simulationWork.useGpuUpdate,
1379                            "GPU update is not supported with CPU halo exchange");
1380                 dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
1381             }
1382
1383             if (stepWork.useGpuXBufferOps)
1384             {
1385                 if (!useGpuPmeOnThisRank && !ddUsesGpuDirectCommunication)
1386                 {
1387                     stateGpu->copyCoordinatesToGpu(x.unpaddedArrayRef(), AtomLocality::NonLocal);
1388                 }
1389                 nbv->convertCoordinatesGpu(AtomLocality::NonLocal, false, stateGpu->getCoordinates(),
1390                                            stateGpu->getCoordinatesReadyOnDeviceEvent(
1391                                                    AtomLocality::NonLocal, simulationWork, stepWork));
1392             }
1393             else
1394             {
1395                 nbv->convertCoordinates(AtomLocality::NonLocal, false, x.unpaddedArrayRef());
1396             }
1397         }
1398
1399         if (simulationWork.useGpuNonbonded)
1400         {
1401             wallcycle_start(wcycle, ewcLAUNCH_GPU);
1402
1403             if (stepWork.doNeighborSearch || !stepWork.useGpuXBufferOps)
1404             {
1405                 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1406                 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(), AtomLocality::NonLocal);
1407                 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1408             }
1409
1410             if (domainWork.haveGpuBondedWork)
1411             {
1412                 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1413                 fr->gpuBonded->setPbcAndlaunchKernel(fr->pbcType, box, fr->bMolPBC, stepWork);
1414                 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1415             }
1416
1417             /* launch non-local nonbonded tasks on GPU */
1418             wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1419             do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step,
1420                          nrnb, wcycle);
1421             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1422
1423             wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1424         }
1425     }
1426
1427     if (simulationWork.useGpuNonbonded)
1428     {
1429         /* launch D2H copy-back F */
1430         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1431         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1432
1433         if (havePPDomainDecomposition(cr))
1434         {
1435             Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(), stepWork, AtomLocality::NonLocal);
1436         }
1437         Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(), stepWork, AtomLocality::Local);
1438         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1439
1440         if (domainWork.haveGpuBondedWork && stepWork.computeEnergy)
1441         {
1442             fr->gpuBonded->launchEnergyTransfer();
1443         }
1444         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1445     }
1446
1447     gmx::ArrayRef<const gmx::RVec> xWholeMolecules;
1448     if (fr->wholeMoleculeTransform)
1449     {
1450         xWholeMolecules = fr->wholeMoleculeTransform->wholeMoleculeCoordinates(x.unpaddedArrayRef(), box);
1451     }
1452
1453     DipoleData dipoleData;
1454
1455     if (simulationWork.computeMuTot)
1456     {
1457         const int start = 0;
1458
1459         /* Calculate total (local) dipole moment in a temporary common array.
1460          * This makes it possible to sum them over nodes faster.
1461          */
1462         gmx::ArrayRef<const gmx::RVec> xRef =
1463                 (xWholeMolecules.empty() ? x.unpaddedArrayRef() : xWholeMolecules);
1464         calc_mu(start, mdatoms->homenr, xRef, mdatoms->chargeA, mdatoms->chargeB,
1465                 mdatoms->nChargePerturbed, dipoleData.muStaging[0], dipoleData.muStaging[1]);
1466
1467         reduceAndUpdateMuTot(&dipoleData, cr, (fr->efep != efepNO), lambda, muTotal, ddBalanceRegionHandler);
1468     }
1469
1470     /* Reset energies */
1471     reset_enerdata(enerd);
1472
1473     if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1474     {
1475         wallcycle_start(wcycle, ewcPPDURINGPME);
1476         dd_force_flop_start(cr->dd, nrnb);
1477     }
1478
1479     // For the rest of the CPU tasks that depend on GPU-update produced coordinates,
1480     // this wait ensures that the D2H transfer is complete.
1481     if ((simulationWork.useGpuUpdate)
1482         && (runScheduleWork->domainWork.haveCpuLocalForceWork || stepWork.computeVirial))
1483     {
1484         stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local);
1485     }
1486
1487     if (inputrec->bRot)
1488     {
1489         wallcycle_start(wcycle, ewcROT);
1490         do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step,
1491                     stepWork.doNeighborSearch);
1492         wallcycle_stop(wcycle, ewcROT);
1493     }
1494
1495     /* Start the force cycle counter.
1496      * Note that a different counter is used for dynamic load balancing.
1497      */
1498     wallcycle_start(wcycle, ewcFORCE);
1499
1500     // Set up and clear force outputs.
1501     // We use std::move to keep the compiler happy, it has no effect.
1502     ForceOutputs forceOut = setupForceOutputs(fr->forceHelperBuffers.get(), pull_work, *inputrec,
1503                                               std::move(force), stepWork, wcycle);
1504
1505     /* We calculate the non-bonded forces, when done on the CPU, here.
1506      * We do this before calling do_force_lowlevel, because in that
1507      * function, the listed forces are calculated before PME, which
1508      * does communication.  With this order, non-bonded and listed
1509      * force calculation imbalance can be balanced out by the domain
1510      * decomposition load balancing.
1511      */
1512
1513     const bool useOrEmulateGpuNb = simulationWork.useGpuNonbonded || fr->nbv->emulateGpu();
1514
1515     if (!useOrEmulateGpuNb)
1516     {
1517         do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::Local, enbvClearFYes, step, nrnb, wcycle);
1518     }
1519
1520     if (fr->efep != efepNO)
1521     {
1522         /* Calculate the local and non-local free energy interactions here.
1523          * Happens here on the CPU both with and without GPU.
1524          */
1525         nbv->dispatchFreeEnergyKernel(InteractionLocality::Local, fr,
1526                                       as_rvec_array(x.unpaddedArrayRef().data()),
1527                                       &forceOut.forceWithShiftForces(), *mdatoms, inputrec->fepvals,
1528                                       lambda.data(), enerd, stepWork, nrnb);
1529
1530         if (havePPDomainDecomposition(cr))
1531         {
1532             nbv->dispatchFreeEnergyKernel(InteractionLocality::NonLocal, fr,
1533                                           as_rvec_array(x.unpaddedArrayRef().data()),
1534                                           &forceOut.forceWithShiftForces(), *mdatoms,
1535                                           inputrec->fepvals, lambda.data(), enerd, stepWork, nrnb);
1536         }
1537     }
1538
1539     if (!useOrEmulateGpuNb)
1540     {
1541         if (havePPDomainDecomposition(cr))
1542         {
1543             do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step,
1544                          nrnb, wcycle);
1545         }
1546
1547         if (stepWork.computeForces)
1548         {
1549             /* Add all the non-bonded force to the normal force array.
1550              * This can be split into a local and a non-local part when overlapping
1551              * communication with calculation with domain decomposition.
1552              */
1553             wallcycle_stop(wcycle, ewcFORCE);
1554             nbv->atomdata_add_nbat_f_to_f(AtomLocality::All, forceOut.forceWithShiftForces().force());
1555             wallcycle_start_nocount(wcycle, ewcFORCE);
1556         }
1557
1558         /* If there are multiple fshift output buffers we need to reduce them */
1559         if (stepWork.computeVirial)
1560         {
1561             /* This is not in a subcounter because it takes a
1562                negligible and constant-sized amount of time */
1563             nbnxn_atomdata_add_nbat_fshift_to_fshift(*nbv->nbat,
1564                                                      forceOut.forceWithShiftForces().shiftForces());
1565         }
1566     }
1567
1568     // TODO Force flags should include haveFreeEnergyWork for this domain
1569     if (ddUsesGpuDirectCommunication && (domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork))
1570     {
1571         /* Wait for non-local coordinate data to be copied from device */
1572         stateGpu->waitCoordinatesReadyOnHost(AtomLocality::NonLocal);
1573     }
1574     /* Compute the bonded and non-bonded energies and optionally forces */
1575     do_force_lowlevel(fr, inputrec, cr, ms, nrnb, wcycle, mdatoms, x, xWholeMolecules, hist,
1576                       &forceOut, enerd, box, lambda.data(), as_rvec_array(dipoleData.muStateAB),
1577                       stepWork, ddBalanceRegionHandler);
1578
1579     wallcycle_stop(wcycle, ewcFORCE);
1580
1581     computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation, imdSession, pull_work, step, t,
1582                          wcycle, fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda.data(),
1583                          stepWork, &forceOut.forceWithVirial(), enerd, ed, stepWork.doNeighborSearch);
1584
1585
1586     // Will store the amount of cycles spent waiting for the GPU that
1587     // will be later used in the DLB accounting.
1588     float cycles_wait_gpu = 0;
1589     if (useOrEmulateGpuNb)
1590     {
1591         auto& forceWithShiftForces = forceOut.forceWithShiftForces();
1592
1593         /* wait for non-local forces (or calculate in emulation mode) */
1594         if (havePPDomainDecomposition(cr))
1595         {
1596             if (simulationWork.useGpuNonbonded)
1597             {
1598                 cycles_wait_gpu += Nbnxm::gpu_wait_finish_task(
1599                         nbv->gpu_nbv, stepWork, AtomLocality::NonLocal, enerd->grpp.ener[egLJSR].data(),
1600                         enerd->grpp.ener[egCOULSR].data(), forceWithShiftForces.shiftForces(), wcycle);
1601             }
1602             else
1603             {
1604                 wallcycle_start_nocount(wcycle, ewcFORCE);
1605                 do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFYes,
1606                              step, nrnb, wcycle);
1607                 wallcycle_stop(wcycle, ewcFORCE);
1608             }
1609
1610             if (stepWork.useGpuFBufferOps)
1611             {
1612                 gmx::FixedCapacityVector<GpuEventSynchronizer*, 1> dependencyList;
1613
1614                 // TODO: move this into DomainLifetimeWorkload, including the second part of the
1615                 // condition The bonded and free energy CPU tasks can have non-local force
1616                 // contributions which are a dependency for the GPU force reduction.
1617                 bool haveNonLocalForceContribInCpuBuffer =
1618                         domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork;
1619
1620                 if (haveNonLocalForceContribInCpuBuffer)
1621                 {
1622                     stateGpu->copyForcesToGpu(forceOut.forceWithShiftForces().force(),
1623                                               AtomLocality::NonLocal);
1624                     dependencyList.push_back(stateGpu->getForcesReadyOnDeviceEvent(
1625                             AtomLocality::NonLocal, stepWork.useGpuFBufferOps));
1626                 }
1627
1628                 nbv->atomdata_add_nbat_f_to_f_gpu(AtomLocality::NonLocal, stateGpu->getForces(),
1629                                                   pme_gpu_get_device_f(fr->pmedata), dependencyList,
1630                                                   false, haveNonLocalForceContribInCpuBuffer);
1631                 if (!useGpuForcesHaloExchange)
1632                 {
1633                     // copy from GPU input for dd_move_f()
1634                     stateGpu->copyForcesFromGpu(forceOut.forceWithShiftForces().force(),
1635                                                 AtomLocality::NonLocal);
1636                 }
1637             }
1638             else
1639             {
1640                 nbv->atomdata_add_nbat_f_to_f(AtomLocality::NonLocal, forceWithShiftForces.force());
1641             }
1642
1643
1644             if (fr->nbv->emulateGpu() && stepWork.computeVirial)
1645             {
1646                 nbnxn_atomdata_add_nbat_fshift_to_fshift(*nbv->nbat, forceWithShiftForces.shiftForces());
1647             }
1648         }
1649     }
1650
1651     if (havePPDomainDecomposition(cr))
1652     {
1653         /* We are done with the CPU compute.
1654          * We will now communicate the non-local forces.
1655          * If we use a GPU this will overlap with GPU work, so in that case
1656          * we do not close the DD force balancing region here.
1657          */
1658         ddBalanceRegionHandler.closeAfterForceComputationCpu();
1659
1660         if (stepWork.computeForces)
1661         {
1662
1663             if (useGpuForcesHaloExchange)
1664             {
1665                 if (domainWork.haveCpuLocalForceWork)
1666                 {
1667                     stateGpu->copyForcesToGpu(forceOut.forceWithShiftForces().force(), AtomLocality::Local);
1668                 }
1669                 communicateGpuHaloForces(*cr, domainWork.haveCpuLocalForceWork);
1670             }
1671             else
1672             {
1673                 if (stepWork.useGpuFBufferOps)
1674                 {
1675                     stateGpu->waitForcesReadyOnHost(AtomLocality::NonLocal);
1676                 }
1677                 dd_move_f(cr->dd, &forceOut.forceWithShiftForces(), wcycle);
1678             }
1679         }
1680     }
1681
1682     // With both nonbonded and PME offloaded a GPU on the same rank, we use
1683     // an alternating wait/reduction scheme.
1684     bool alternateGpuWait = (!c_disableAlternatingWait && useGpuPmeOnThisRank && simulationWork.useGpuNonbonded
1685                              && !DOMAINDECOMP(cr) && !stepWork.useGpuFBufferOps);
1686     if (alternateGpuWait)
1687     {
1688         alternatePmeNbGpuWaitReduce(fr->nbv.get(), fr->pmedata, &forceOut, enerd, stepWork, wcycle);
1689     }
1690
1691     if (!alternateGpuWait && useGpuPmeOnThisRank)
1692     {
1693         pme_gpu_wait_and_reduce(fr->pmedata, stepWork, wcycle, &forceOut.forceWithVirial(), enerd);
1694     }
1695
1696     /* Wait for local GPU NB outputs on the non-alternating wait path */
1697     if (!alternateGpuWait && simulationWork.useGpuNonbonded)
1698     {
1699         /* Measured overhead on CUDA and OpenCL with(out) GPU sharing
1700          * is between 0.5 and 1.5 Mcycles. So 2 MCycles is an overestimate,
1701          * but even with a step of 0.1 ms the difference is less than 1%
1702          * of the step time.
1703          */
1704         const float gpuWaitApiOverheadMargin = 2e6F; /* cycles */
1705         const float waitCycles               = Nbnxm::gpu_wait_finish_task(
1706                 nbv->gpu_nbv, stepWork, AtomLocality::Local, enerd->grpp.ener[egLJSR].data(),
1707                 enerd->grpp.ener[egCOULSR].data(), forceOut.forceWithShiftForces().shiftForces(), wcycle);
1708
1709         if (ddBalanceRegionHandler.useBalancingRegion())
1710         {
1711             DdBalanceRegionWaitedForGpu waitedForGpu = DdBalanceRegionWaitedForGpu::yes;
1712             if (stepWork.computeForces && waitCycles <= gpuWaitApiOverheadMargin)
1713             {
1714                 /* We measured few cycles, it could be that the kernel
1715                  * and transfer finished earlier and there was no actual
1716                  * wait time, only API call overhead.
1717                  * Then the actual time could be anywhere between 0 and
1718                  * cycles_wait_est. We will use half of cycles_wait_est.
1719                  */
1720                 waitedForGpu = DdBalanceRegionWaitedForGpu::no;
1721             }
1722             ddBalanceRegionHandler.closeAfterForceComputationGpu(cycles_wait_gpu, waitedForGpu);
1723         }
1724     }
1725
1726     if (fr->nbv->emulateGpu())
1727     {
1728         // NOTE: emulation kernel is not included in the balancing region,
1729         // but emulation mode does not target performance anyway
1730         wallcycle_start_nocount(wcycle, ewcFORCE);
1731         do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::Local,
1732                      DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes, step, nrnb, wcycle);
1733         wallcycle_stop(wcycle, ewcFORCE);
1734     }
1735
1736     // If on GPU PME-PP comms or GPU update path, receive forces from PME before GPU buffer ops
1737     // TODO refactor this and unify with below default-path call to the same function
1738     if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME)
1739         && (simulationWork.useGpuPmePpCommunication || simulationWork.useGpuUpdate))
1740     {
1741         /* In case of node-splitting, the PP nodes receive the long-range
1742          * forces, virial and energy from the PME nodes here.
1743          */
1744         pme_receive_force_ener(fr, cr, &forceOut.forceWithVirial(), enerd,
1745                                simulationWork.useGpuPmePpCommunication,
1746                                stepWork.useGpuPmeFReduction, wcycle);
1747     }
1748
1749
1750     /* Do the nonbonded GPU (or emulation) force buffer reduction
1751      * on the non-alternating path. */
1752     if (useOrEmulateGpuNb && !alternateGpuWait)
1753     {
1754         // TODO simplify the below conditionals. Pass buffer and sync pointers at init stage rather than here. Unify getter fns for sameGPU/otherGPU cases.
1755         void* pmeForcePtr =
1756                 stepWork.useGpuPmeFReduction
1757                         ? (thisRankHasDuty(cr, DUTY_PME) ? pme_gpu_get_device_f(fr->pmedata)
1758                                                          : // PME force buffer on same GPU
1759                                    fr->pmePpCommGpu->getGpuForceStagingPtr()) // buffer received from other GPU
1760                         : nullptr; // PME reduction not active on GPU
1761
1762         GpuEventSynchronizer* const pmeSynchronizer =
1763                 stepWork.useGpuPmeFReduction
1764                         ? (thisRankHasDuty(cr, DUTY_PME) ? pme_gpu_get_f_ready_synchronizer(fr->pmedata)
1765                                                          : // PME force buffer on same GPU
1766                                    static_cast<GpuEventSynchronizer*>(
1767                                            fr->pmePpCommGpu->getForcesReadySynchronizer())) // buffer received from other GPU
1768                         : nullptr; // PME reduction not active on GPU
1769
1770         gmx::FixedCapacityVector<GpuEventSynchronizer*, 3> dependencyList;
1771
1772         if (stepWork.useGpuPmeFReduction)
1773         {
1774             dependencyList.push_back(pmeSynchronizer);
1775         }
1776
1777         gmx::ArrayRef<gmx::RVec> forceWithShift = forceOut.forceWithShiftForces().force();
1778
1779         if (stepWork.useGpuFBufferOps)
1780         {
1781             // Flag to specify whether the CPU force buffer has contributions to
1782             // local atoms. This depends on whether there are CPU-based force tasks
1783             // or when DD is active the halo exchange has resulted in contributions
1784             // from the non-local part.
1785             const bool haveLocalForceContribInCpuBuffer =
1786                     (domainWork.haveCpuLocalForceWork || havePPDomainDecomposition(cr));
1787
1788             // TODO: move these steps as early as possible:
1789             // - CPU f H2D should be as soon as all CPU-side forces are done
1790             // - wait for force reduction does not need to block host (at least not here, it's sufficient to wait
1791             //   before the next CPU task that consumes the forces: vsite spread or update)
1792             // - copy is not perfomed if GPU force halo exchange is active, because it would overwrite the result
1793             //   of the halo exchange. In that case the copy is instead performed above, before the exchange.
1794             //   These should be unified.
1795             if (haveLocalForceContribInCpuBuffer && !useGpuForcesHaloExchange)
1796             {
1797                 // Note: AtomLocality::All is used for the non-DD case because, as in this
1798                 // case copyForcesToGpu() uses a separate stream, it allows overlap of
1799                 // CPU force H2D with GPU force tasks on all streams including those in the
1800                 // local stream which would otherwise be implicit dependencies for the
1801                 // transfer and would not overlap.
1802                 auto locality = havePPDomainDecomposition(cr) ? AtomLocality::Local : AtomLocality::All;
1803
1804                 stateGpu->copyForcesToGpu(forceWithShift, locality);
1805                 dependencyList.push_back(
1806                         stateGpu->getForcesReadyOnDeviceEvent(locality, stepWork.useGpuFBufferOps));
1807             }
1808             if (useGpuForcesHaloExchange)
1809             {
1810                 dependencyList.push_back(cr->dd->gpuHaloExchange[0]->getForcesReadyOnDeviceEvent());
1811             }
1812             nbv->atomdata_add_nbat_f_to_f_gpu(AtomLocality::Local, stateGpu->getForces(), pmeForcePtr,
1813                                               dependencyList, stepWork.useGpuPmeFReduction,
1814                                               haveLocalForceContribInCpuBuffer);
1815             // Copy forces to host if they are needed for update or if virtual sites are enabled.
1816             // If there are vsites, we need to copy forces every step to spread vsite forces on host.
1817             // TODO: When the output flags will be included in step workload, this copy can be combined with the
1818             //       copy call done in sim_utils(...) for the output.
1819             // NOTE: If there are virtual sites, the forces are modified on host after this D2H copy. Hence,
1820             //       they should not be copied in do_md(...) for the output.
1821             if (!simulationWork.useGpuUpdate || vsite)
1822             {
1823                 stateGpu->copyForcesFromGpu(forceWithShift, AtomLocality::Local);
1824                 stateGpu->waitForcesReadyOnHost(AtomLocality::Local);
1825             }
1826         }
1827         else
1828         {
1829             nbv->atomdata_add_nbat_f_to_f(AtomLocality::Local, forceWithShift);
1830         }
1831     }
1832
1833     launchGpuEndOfStepTasks(nbv, fr->gpuBonded, fr->pmedata, enerd, *runScheduleWork,
1834                             useGpuPmeOnThisRank, step, wcycle);
1835
1836     if (DOMAINDECOMP(cr))
1837     {
1838         dd_force_flop_stop(cr->dd, nrnb);
1839     }
1840
1841     if (stepWork.computeForces)
1842     {
1843         postProcessForceWithShiftForces(nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOut,
1844                                         vir_force, *mdatoms, *fr, vsite, stepWork);
1845     }
1846
1847     // VdW dispersion correction, only computed on master rank to avoid double counting
1848     if ((stepWork.computeEnergy || stepWork.computeVirial) && fr->dispersionCorrection && MASTER(cr))
1849     {
1850         // Calculate long range corrections to pressure and energy
1851         const DispersionCorrection::Correction correction =
1852                 fr->dispersionCorrection->calculate(box, lambda[efptVDW]);
1853
1854         if (stepWork.computeEnergy)
1855         {
1856             enerd->term[F_DISPCORR] = correction.energy;
1857             enerd->term[F_DVDL_VDW] += correction.dvdl;
1858         }
1859         if (stepWork.computeVirial)
1860         {
1861             correction.correctVirial(vir_force);
1862             enerd->term[F_PDISPCORR] = correction.pressure;
1863         }
1864     }
1865
1866     // TODO refactor this and unify with above GPU PME-PP / GPU update path call to the same function
1867     if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME) && !simulationWork.useGpuPmePpCommunication
1868         && !simulationWork.useGpuUpdate)
1869     {
1870         /* In case of node-splitting, the PP nodes receive the long-range
1871          * forces, virial and energy from the PME nodes here.
1872          */
1873         pme_receive_force_ener(fr, cr, &forceOut.forceWithVirial(), enerd,
1874                                simulationWork.useGpuPmePpCommunication, false, wcycle);
1875     }
1876
1877     if (stepWork.computeForces)
1878     {
1879         postProcessForces(cr, step, nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOut, vir_force,
1880                           mdatoms, fr, vsite, stepWork);
1881     }
1882
1883     if (stepWork.computeEnergy)
1884     {
1885         /* Sum the potential energy terms from group contributions */
1886         sum_epot(&(enerd->grpp), enerd->term);
1887
1888         if (!EI_TPI(inputrec->eI))
1889         {
1890             checkPotentialEnergyValidity(step, *enerd, *inputrec);
1891         }
1892     }
1893
1894     /* In case we don't have constraints and are using GPUs, the next balancing
1895      * region starts here.
1896      * Some "special" work at the end of do_force_cuts?, such as vsite spread,
1897      * virial calculation and COM pulling, is not thus not included in
1898      * the balance timing, which is ok as most tasks do communication.
1899      */
1900     ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::no);
1901 }