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