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