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