2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
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"
117 // TODO: this environment variable allows us to verify before release
118 // that on less common architectures the total cost of polling is not larger than
119 // a blocking wait (so polling does not introduce overhead when the static
120 // PME-first ordering would suffice).
121 static const bool c_disableAlternatingWait = (getenv("GMX_DISABLE_ALTERNATING_GPU_WAIT") != nullptr);
123 // environment variable to enable GPU buffer ops, to alow incremental and optional
124 // introduction of this functionality.
125 // TODO eventially tie this in with other existing GPU flags.
126 static const bool c_enableGpuBufOps = (getenv("GMX_USE_GPU_BUFFER_OPS") != nullptr);
130 static void sum_forces(rvec f[], gmx::ArrayRef<const gmx::RVec> forceToAdd)
132 const int end = forceToAdd.size();
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++)
138 rvec_inc(f[i], forceToAdd[i]);
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)
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);
150 /* Calculate partial virial, for local atoms only, based on short range.
151 * Total virial is computed in global_stat, called from do_md
153 f_calc_vir(start, start+homenr, x, f, vir_part, graph, box);
154 inc_nrnb(nrnb, eNR_VIRIAL, homenr);
158 pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
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,
171 gmx_wallcycle_t wcycle)
176 /* Calculate the center of mass forces, this requires communication,
177 * which is why pull_potential is called close to other communication.
179 wallcycle_start(wcycle, ewcPULLPOT);
180 set_pbc(&pbc, ir->ePBC, box);
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);
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)
194 real e_q, e_lj, dvdl_q, dvdl_lj;
195 float cycles_ppdpme, cycles_seppme;
197 cycles_ppdpme = wallcycle_stop(wcycle, ewcPPDURINGPME);
198 dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
200 /* In case of node-splitting, the PP nodes receive the long-range
201 * forces, virial and energy from the PME nodes here.
203 wallcycle_start(wcycle, ewcPP_PMEWAITRECVF);
206 gmx_pme_receive_f(cr, forceWithVirial, &e_q, &e_lj, &dvdl_q, &dvdl_lj,
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;
215 dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
217 wallcycle_stop(wcycle, ewcPP_PMEWAITRECVF);
220 static void print_large_forces(FILE *fp,
228 real force2Tolerance = gmx::square(forceTolerance);
229 gmx::index numNonFinite = 0;
230 for (int i = 0; i < md->homenr; i++)
232 real force2 = norm2(f[i]);
233 bool nonFinite = !std::isfinite(force2);
234 if (force2 >= force2Tolerance || nonFinite)
236 fprintf(fp, "step %" PRId64 " atom %6d x %8.3f %8.3f %8.3f force %12.5e\n",
238 ddglatnr(cr->dd, i), x[i][XX], x[i][YY], x[i][ZZ], std::sqrt(force2));
245 if (numNonFinite > 0)
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.
251 gmx_fatal(FARGS, "At step %" PRId64 " detected non-finite forces on %td atoms", step, numNonFinite);
255 static void post_process_forces(const t_commrec *cr,
258 gmx_wallcycle_t wcycle,
259 const gmx_localtop_t *top,
263 gmx::ForceWithVirial *forceWithVirial,
265 const t_mdatoms *mdatoms,
266 const t_graph *graph,
267 const t_forcerec *fr,
268 const gmx_vsite_t *vsite,
271 if (fr->haveDirectVirialContributions)
273 rvec *fDirectVir = as_rvec_array(forceWithVirial->force_.data());
277 /* Spread the mesh force on virtual sites to the other particles...
278 * This is parallellized. MPI communication is performed
279 * if the constructing atoms aren't local.
281 matrix virial = { { 0 } };
282 spread_vsite_f(vsite, x, fDirectVir, nullptr,
283 (flags & GMX_FORCE_VIRIAL) != 0, virial,
285 &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
286 forceWithVirial->addVirialContribution(virial);
289 if (flags & GMX_FORCE_VIRIAL)
291 /* Now add the forces, this is local */
292 sum_forces(f, forceWithVirial->force_);
294 /* Add the direct virial contributions */
295 GMX_ASSERT(forceWithVirial->computeVirial_, "forceWithVirial should request virial computation when we request the virial");
296 m_add(vir_force, forceWithVirial->getVirial(), vir_force);
300 pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
305 if (fr->print_force >= 0)
307 print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
311 static void do_nb_verlet(t_forcerec *fr,
312 const interaction_const_t *ic,
313 gmx_enerdata_t *enerd,
315 const Nbnxm::InteractionLocality ilocality,
319 gmx_wallcycle_t wcycle)
321 if (!(flags & GMX_FORCE_NONBONDED))
323 /* skip non-bonded calculation */
327 nonbonded_verlet_t *nbv = fr->nbv.get();
329 /* GPU kernel launch overhead is already timed separately */
330 if (fr->cutoff_scheme != ecutsVERLET)
332 gmx_incons("Invalid cut-off scheme passed!");
337 /* When dynamic pair-list pruning is requested, we need to prune
338 * at nstlistPrune steps.
340 if (nbv->isDynamicPruningStepCpu(step))
342 /* Prune the pair-list beyond fr->ic->rlistPrune using
343 * the current coordinates of the atoms.
345 wallcycle_sub_start(wcycle, ewcsNONBONDED_PRUNING);
346 nbv->dispatchPruneKernelCpu(ilocality, fr->shift_vec);
347 wallcycle_sub_stop(wcycle, ewcsNONBONDED_PRUNING);
351 nbv->dispatchNonbondedKernel(ilocality, *ic, flags, clearF, *fr, enerd, nrnb, wcycle);
354 static inline void clear_rvecs_omp(int n, rvec v[])
356 int nth = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, n);
358 /* Note that we would like to avoid this conditional by putting it
359 * into the omp pragma instead, but then we still take the full
360 * omp parallel for overhead (at least with gcc5).
364 for (int i = 0; i < n; i++)
371 #pragma omp parallel for num_threads(nth) schedule(static)
372 for (int i = 0; i < n; i++)
379 /*! \brief Return an estimate of the average kinetic energy or 0 when unreliable
381 * \param groupOptions Group options, containing T-coupling options
383 static real averageKineticEnergyEstimate(const t_grpopts &groupOptions)
385 real nrdfCoupled = 0;
386 real nrdfUncoupled = 0;
387 real kineticEnergy = 0;
388 for (int g = 0; g < groupOptions.ngtc; g++)
390 if (groupOptions.tau_t[g] >= 0)
392 nrdfCoupled += groupOptions.nrdf[g];
393 kineticEnergy += groupOptions.nrdf[g]*0.5*groupOptions.ref_t[g]*BOLTZ;
397 nrdfUncoupled += groupOptions.nrdf[g];
401 /* This conditional with > also catches nrdf=0 */
402 if (nrdfCoupled > nrdfUncoupled)
404 return kineticEnergy*(nrdfCoupled + nrdfUncoupled)/nrdfCoupled;
412 /*! \brief This routine checks that the potential energy is finite.
414 * Always checks that the potential energy is finite. If step equals
415 * inputrec.init_step also checks that the magnitude of the potential energy
416 * is reasonable. Terminates with a fatal error when a check fails.
417 * Note that passing this check does not guarantee finite forces,
418 * since those use slightly different arithmetics. But in most cases
419 * there is just a narrow coordinate range where forces are not finite
420 * and energies are finite.
422 * \param[in] step The step number, used for checking and printing
423 * \param[in] enerd The energy data; the non-bonded group energies need to be added to enerd.term[F_EPOT] before calling this routine
424 * \param[in] inputrec The input record
426 static void checkPotentialEnergyValidity(int64_t step,
427 const gmx_enerdata_t &enerd,
428 const t_inputrec &inputrec)
430 /* Threshold valid for comparing absolute potential energy against
431 * the kinetic energy. Normally one should not consider absolute
432 * potential energy values, but with a factor of one million
433 * we should never get false positives.
435 constexpr real c_thresholdFactor = 1e6;
437 bool energyIsNotFinite = !std::isfinite(enerd.term[F_EPOT]);
438 real averageKineticEnergy = 0;
439 /* We only check for large potential energy at the initial step,
440 * because that is by far the most likely step for this too occur
441 * and because computing the average kinetic energy is not free.
442 * Note: nstcalcenergy >> 1 often does not allow to catch large energies
443 * before they become NaN.
445 if (step == inputrec.init_step && EI_DYNAMICS(inputrec.eI))
447 averageKineticEnergy = averageKineticEnergyEstimate(inputrec.opts);
450 if (energyIsNotFinite || (averageKineticEnergy > 0 &&
451 enerd.term[F_EPOT] > c_thresholdFactor*averageKineticEnergy))
453 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 energyIsNotFinite ? "not finite" : "extremely high",
458 enerd.term[F_COUL_SR],
459 energyIsNotFinite ? "non-finite" : "very high",
460 energyIsNotFinite ? " or Nan" : "");
464 /*! \brief Return true if there are special forces computed this step.
466 * The conditionals exactly correspond to those in computeSpecialForces().
469 haveSpecialForces(const t_inputrec *inputrec,
470 ForceProviders *forceProviders,
471 const pull_t *pull_work,
475 const bool computeForces = (forceFlags & GMX_FORCE_FORCES) != 0;
478 ((computeForces && forceProviders->hasForceProvider()) || // forceProviders
479 (inputrec->bPull && pull_have_potential(pull_work)) || // pull
480 inputrec->bRot || // enforced rotation
481 (ed != nullptr) || // flooding
482 (inputrec->bIMD && computeForces)); // IMD
485 /*! \brief Compute forces and/or energies for special algorithms
487 * The intention is to collect all calls to algorithms that compute
488 * forces on local atoms only and that do not contribute to the local
489 * virial sum (but add their virial contribution separately).
490 * Eventually these should likely all become ForceProviders.
491 * Within this function the intention is to have algorithms that do
492 * global communication at the end, so global barriers within the MD loop
493 * are as close together as possible.
495 * \param[in] fplog The log file
496 * \param[in] cr The communication record
497 * \param[in] inputrec The input record
498 * \param[in] awh The Awh module (nullptr if none in use).
499 * \param[in] enforcedRotation Enforced rotation module.
500 * \param[in] imdSession The IMD session
501 * \param[in] pull_work The pull work structure.
502 * \param[in] step The current MD step
503 * \param[in] t The current time
504 * \param[in,out] wcycle Wallcycle accounting struct
505 * \param[in,out] forceProviders Pointer to a list of force providers
506 * \param[in] box The unit cell
507 * \param[in] x The coordinates
508 * \param[in] mdatoms Per atom properties
509 * \param[in] lambda Array of free-energy lambda values
510 * \param[in] forceFlags Flags that tell whether we should compute forces/energies/virial
511 * \param[in,out] forceWithVirial Force and virial buffers
512 * \param[in,out] enerd Energy buffer
513 * \param[in,out] ed Essential dynamics pointer
514 * \param[in] bNS Tells if we did neighbor searching this step, used for ED sampling
516 * \todo Remove bNS, which is used incorrectly.
517 * \todo Convert all other algorithms called here to ForceProviders.
520 computeSpecialForces(FILE *fplog,
522 const t_inputrec *inputrec,
524 gmx_enfrot *enforcedRotation,
525 gmx::ImdSession *imdSession,
529 gmx_wallcycle_t wcycle,
530 ForceProviders *forceProviders,
532 gmx::ArrayRef<const gmx::RVec> x,
533 const t_mdatoms *mdatoms,
536 gmx::ForceWithVirial *forceWithVirial,
537 gmx_enerdata_t *enerd,
541 const bool computeForces = (forceFlags & GMX_FORCE_FORCES) != 0;
543 /* NOTE: Currently all ForceProviders only provide forces.
544 * When they also provide energies, remove this conditional.
548 gmx::ForceProviderInput forceProviderInput(x, *mdatoms, t, box, *cr);
549 gmx::ForceProviderOutput forceProviderOutput(forceWithVirial, enerd);
551 /* Collect forces from modules */
552 forceProviders->calculateForces(forceProviderInput, &forceProviderOutput);
555 if (inputrec->bPull && pull_have_potential(pull_work))
557 pull_potential_wrapper(cr, inputrec, box, x,
559 mdatoms, enerd, pull_work, lambda, t,
564 enerd->term[F_COM_PULL] +=
565 awh->applyBiasForcesAndUpdateBias(inputrec->ePBC, *mdatoms, box,
567 t, step, wcycle, fplog);
571 rvec *f = as_rvec_array(forceWithVirial->force_.data());
573 /* Add the forces from enforced rotation potentials (if any) */
576 wallcycle_start(wcycle, ewcROTadd);
577 enerd->term[F_COM_PULL] += add_rot_forces(enforcedRotation, f, cr, step, t);
578 wallcycle_stop(wcycle, ewcROTadd);
583 /* Note that since init_edsam() is called after the initialization
584 * of forcerec, edsam doesn't request the noVirSum force buffer.
585 * Thus if no other algorithm (e.g. PME) requires it, the forces
586 * here will contribute to the virial.
588 do_flood(cr, inputrec, as_rvec_array(x.data()), f, ed, box, step, bNS);
591 /* Add forces from interactive molecular dynamics (IMD), if any */
592 if (inputrec->bIMD && computeForces)
594 imdSession->applyForces(f);
598 /*! \brief Launch the prepare_step and spread stages of PME GPU.
600 * \param[in] pmedata The PME structure
601 * \param[in] box The box matrix
602 * \param[in] x Coordinate array
603 * \param[in] flags Force flags
604 * \param[in] pmeFlags PME flags
605 * \param[in] wcycle The wallcycle structure
607 static inline void launchPmeGpuSpread(gmx_pme_t *pmedata,
612 gmx_wallcycle_t wcycle)
614 pme_gpu_prepare_computation(pmedata, (flags & GMX_FORCE_DYNAMICBOX) != 0, box, wcycle, pmeFlags);
615 pme_gpu_launch_spread(pmedata, x, wcycle);
618 /*! \brief Launch the FFT and gather stages of PME GPU
620 * This function only implements setting the output forces (no accumulation).
622 * \param[in] pmedata The PME structure
623 * \param[in] wcycle The wallcycle structure
625 static void launchPmeGpuFftAndGather(gmx_pme_t *pmedata,
626 gmx_wallcycle_t wcycle)
628 pme_gpu_launch_complex_transforms(pmedata, wcycle);
629 pme_gpu_launch_gather(pmedata, wcycle, PmeForceOutputHandling::Set);
633 * Polling wait for either of the PME or nonbonded GPU tasks.
635 * Instead of a static order in waiting for GPU tasks, this function
636 * polls checking which of the two tasks completes first, and does the
637 * associated force buffer reduction overlapped with the other task.
638 * By doing that, unlike static scheduling order, it can always overlap
639 * one of the reductions, regardless of the GPU task completion order.
641 * \param[in] nbv Nonbonded verlet structure
642 * \param[in,out] pmedata PME module data
643 * \param[in,out] force Force array to reduce task outputs into.
644 * \param[in,out] forceWithVirial Force and virial buffers
645 * \param[in,out] fshift Shift force output vector results are reduced into
646 * \param[in,out] enerd Energy data structure results are reduced into
647 * \param[in] flags Force flags
648 * \param[in] pmeFlags PME flags
649 * \param[in] haveOtherWork Tells whether there is other work than non-bonded in the stream(s)
650 * \param[in] wcycle The wallcycle structure
652 static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t *nbv,
654 gmx::ArrayRefWithPadding<gmx::RVec> *force,
655 gmx::ForceWithVirial *forceWithVirial,
657 gmx_enerdata_t *enerd,
661 gmx_wallcycle_t wcycle)
663 bool isPmeGpuDone = false;
664 bool isNbGpuDone = false;
667 gmx::ArrayRef<const gmx::RVec> pmeGpuForces;
669 while (!isPmeGpuDone || !isNbGpuDone)
673 GpuTaskCompletion completionType = (isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
674 isPmeGpuDone = pme_gpu_try_finish_task(pmedata, pmeFlags, wcycle, forceWithVirial, enerd, completionType);
679 GpuTaskCompletion completionType = (isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
680 wallcycle_start_nocount(wcycle, ewcWAIT_GPU_NB_L);
681 isNbGpuDone = Nbnxm::gpu_try_finish_task(nbv->gpu_nbv,
683 Nbnxm::AtomLocality::Local,
685 enerd->grpp.ener[egLJSR].data(),
686 enerd->grpp.ener[egCOULSR].data(),
687 fshift, completionType);
688 wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
689 // To get the call count right, when the task finished we
690 // issue a start/stop.
691 // TODO: move the ewcWAIT_GPU_NB_L cycle counting into nbnxn_gpu_try_finish_task()
692 // and ewcNB_XF_BUF_OPS counting into nbnxn_atomdata_add_nbat_f_to_f().
695 wallcycle_start(wcycle, ewcWAIT_GPU_NB_L);
696 wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
698 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local,
699 as_rvec_array(force->unpaddedArrayRef().data()), wcycle);
705 /*! \brief Hack structure with force ouput buffers for do_force for the home atoms for this domain */
709 ForceOutputs(rvec *f, gmx::ForceWithVirial const forceWithVirial) :
711 forceWithVirial(forceWithVirial) {}
713 //! Force output buffer used by legacy modules (without SIMD padding)
715 //! Force with direct virial contribution (if there are any; without SIMD padding)
716 gmx::ForceWithVirial forceWithVirial;
719 /*! \brief Set up the different force buffers; also does clearing.
721 * \param[in] fr force record pointer
722 * \param[in] pull_work The pull work object.
723 * \param[in] inputrec input record
724 * \param[in] force force array
725 * \param[in] bDoForces True if force are computed this step
726 * \param[in] doVirial True if virial is computed this step
727 * \param[out] wcycle wallcycle recording structure
729 * \returns Cleared force output structure
732 setupForceOutputs(const t_forcerec *fr,
734 const t_inputrec &inputrec,
735 gmx::ArrayRefWithPadding<gmx::RVec> force,
736 const bool bDoForces,
738 gmx_wallcycle_t wcycle)
740 wallcycle_sub_start(wcycle, ewcsCLEAR_FORCE_BUFFER);
742 /* Temporary solution until all routines take PaddedRVecVector */
743 rvec *const f = as_rvec_array(force.unpaddedArrayRef().data());
746 /* Clear the short- and long-range forces */
747 clear_rvecs_omp(fr->natoms_force_constr, f);
750 /* If we need to compute the virial, we might need a separate
751 * force buffer for algorithms for which the virial is calculated
752 * directly, such as PME. Otherwise, forceWithVirial uses the
753 * the same force (f in legacy calls) buffer as other algorithms.
755 const bool useSeparateForceWithVirialBuffer = (bDoForces && (doVirial && fr->haveDirectVirialContributions));
758 /* forceWithVirial uses the local atom range only */
759 gmx::ForceWithVirial forceWithVirial (useSeparateForceWithVirialBuffer ?
760 *fr->forceBufferForDirectVirialContributions : force.unpaddedArrayRef(),
763 if (useSeparateForceWithVirialBuffer)
765 /* TODO: update comment
766 * We only compute forces on local atoms. Note that vsites can
767 * spread to non-local atoms, but that part of the buffer is
768 * cleared separately in the vsite spreading code.
770 clear_rvecs_omp(forceWithVirial.force_.size(), as_rvec_array(forceWithVirial.force_.data()));
773 if (inputrec.bPull && pull_have_constraint(pull_work))
775 clear_pull_forces(pull_work);
778 wallcycle_sub_stop(wcycle, ewcsCLEAR_FORCE_BUFFER);
780 return ForceOutputs(f, forceWithVirial);
784 /*! \brief Set up flags that indicate what type of work is there to compute.
786 * Currently we only update it at search steps,
787 * but some properties may change more frequently (e.g. virial/non-virial step),
788 * so when including those either the frequency of update (per-step) or the scope
789 * of a flag will change (i.e. a set of flags for nstlist steps).
793 setupForceWorkload(gmx::PpForceWorkload *forceWork,
794 const t_inputrec *inputrec,
795 const t_forcerec *fr,
796 const pull_t *pull_work,
803 forceWork->haveSpecialForces = haveSpecialForces(inputrec, fr->forceProviders, pull_work, forceFlags, ed);
804 forceWork->haveCpuBondedWork = haveCpuBondeds(*fr);
805 forceWork->haveGpuBondedWork = ((fr->gpuBonded != nullptr) && fr->gpuBonded->haveInteractions());
806 forceWork->haveRestraintsWork = havePositionRestraints(idef, *fcd);
807 forceWork->haveCpuListedForceWork = haveCpuListedForces(*fr, idef, *fcd);
810 void do_force(FILE *fplog,
812 const gmx_multisim_t *ms,
813 const t_inputrec *inputrec,
815 gmx_enfrot *enforcedRotation,
816 gmx::ImdSession *imdSession,
820 gmx_wallcycle_t wcycle,
821 const gmx_localtop_t *top,
823 gmx::ArrayRefWithPadding<gmx::RVec> x, //NOLINT(performance-unnecessary-value-param)
825 gmx::ArrayRefWithPadding<gmx::RVec> force, //NOLINT(performance-unnecessary-value-param)
827 const t_mdatoms *mdatoms,
828 gmx_enerdata_t *enerd,
830 gmx::ArrayRef<real> lambda,
833 gmx::PpForceWorkload *ppForceWorkload,
834 const gmx_vsite_t *vsite,
839 const DDBalanceRegionHandler &ddBalanceRegionHandler)
843 gmx_bool bStateChanged, bNS, bFillGrid, bCalcCGCM;
844 gmx_bool bDoForces, bUseGPU, bUseOrEmulGPU;
845 nonbonded_verlet_t *nbv = fr->nbv.get();
846 interaction_const_t *ic = fr->ic;
848 /* modify force flag if not doing nonbonded */
851 flags &= ~GMX_FORCE_NONBONDED;
853 bStateChanged = ((flags & GMX_FORCE_STATECHANGED) != 0);
854 bNS = ((flags & GMX_FORCE_NS) != 0);
855 bFillGrid = (bNS && bStateChanged);
856 bCalcCGCM = (bFillGrid && !DOMAINDECOMP(cr));
857 bDoForces = ((flags & GMX_FORCE_FORCES) != 0);
858 bUseGPU = fr->nbv->useGpu();
859 bUseOrEmulGPU = bUseGPU || fr->nbv->emulateGpu();
861 const auto pmeRunMode = fr->pmedata ? pme_run_mode(fr->pmedata) : PmeRunMode::CPU;
862 // TODO slim this conditional down - inputrec and duty checks should mean the same in proper code!
863 const bool useGpuPme = EEL_PME(fr->ic->eeltype) && thisRankHasDuty(cr, DUTY_PME) &&
864 ((pmeRunMode == PmeRunMode::GPU) || (pmeRunMode == PmeRunMode::Mixed));
865 const int pmeFlags = GMX_PME_SPREAD | GMX_PME_SOLVE |
866 ((flags & GMX_FORCE_VIRIAL) ? GMX_PME_CALC_ENER_VIR : 0) |
867 ((flags & GMX_FORCE_ENERGY) ? GMX_PME_CALC_ENER_VIR : 0) |
868 ((flags & GMX_FORCE_FORCES) ? GMX_PME_CALC_F : 0);
870 const bool useGpuXBufOps = (c_enableGpuBufOps && bUseGPU && (GMX_GPU == GMX_GPU_CUDA));
872 /* At a search step we need to start the first balancing region
873 * somewhere early inside the step after communication during domain
874 * decomposition (and not during the previous step as usual).
878 ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::yes);
882 const int homenr = mdatoms->homenr;
884 clear_mat(vir_force);
888 update_forcerec(fr, box);
890 if (inputrecNeedMutot(inputrec))
892 /* Calculate total (local) dipole moment in a temporary common array.
893 * This makes it possible to sum them over nodes faster.
895 calc_mu(start, homenr,
896 x.unpaddedArrayRef(), mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
901 if (fr->ePBC != epbcNONE)
903 /* Compute shift vectors every step,
904 * because of pressure coupling or box deformation!
906 if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
908 calc_shifts(box, fr->shift_vec);
913 put_atoms_in_box_omp(fr->ePBC, box, x.unpaddedArrayRef().subArray(0, homenr), gmx_omp_nthreads_get(emntDefault));
914 inc_nrnb(nrnb, eNR_SHIFTX, homenr);
916 else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
918 unshift_self(graph, box, as_rvec_array(x.unpaddedArrayRef().data()));
922 nbnxn_atomdata_copy_shiftvec((flags & GMX_FORCE_DYNAMICBOX) != 0,
923 fr->shift_vec, nbv->nbat.get());
926 if (!thisRankHasDuty(cr, DUTY_PME))
928 /* Send particle coordinates to the pme nodes.
929 * Since this is only implemented for domain decomposition
930 * and domain decomposition does not use the graph,
931 * we do not need to worry about shifting.
933 gmx_pme_send_coordinates(cr, box, as_rvec_array(x.unpaddedArrayRef().data()),
934 lambda[efptCOUL], lambda[efptVDW],
935 (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY)) != 0,
942 launchPmeGpuSpread(fr->pmedata, box, as_rvec_array(x.unpaddedArrayRef().data()), flags, pmeFlags, wcycle);
945 /* do gridding for pair search */
948 if (graph && bStateChanged)
950 /* Calculate intramolecular shift vectors to make molecules whole */
951 mk_mshift(fplog, graph, fr->ePBC, box, as_rvec_array(x.unpaddedArrayRef().data()));
955 // - vzero is constant, do we need to pass it?
956 // - box_diag should be passed directly to nbnxn_put_on_grid
962 box_diag[XX] = box[XX][XX];
963 box_diag[YY] = box[YY][YY];
964 box_diag[ZZ] = box[ZZ][ZZ];
966 wallcycle_start(wcycle, ewcNS);
967 if (!DOMAINDECOMP(cr))
969 wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL);
970 nbnxn_put_on_grid(nbv, box,
972 nullptr, 0, mdatoms->homenr, -1,
973 fr->cginfo, x.unpaddedArrayRef(),
975 wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL);
979 wallcycle_sub_start(wcycle, ewcsNBS_GRID_NONLOCAL);
980 nbnxn_put_on_grid_nonlocal(nbv, domdec_zones(cr->dd),
981 fr->cginfo, x.unpaddedArrayRef());
982 wallcycle_sub_stop(wcycle, ewcsNBS_GRID_NONLOCAL);
985 nbv->setAtomProperties(*mdatoms, fr->cginfo);
987 wallcycle_stop(wcycle, ewcNS);
989 /* initialize the GPU nbnxm atom data and bonded data structures */
992 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
994 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
995 Nbnxm::gpu_init_atomdata(nbv->gpu_nbv, nbv->nbat.get());
996 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1000 /* Now we put all atoms on the grid, we can assign bonded
1001 * interactions to the GPU, where the grid order is
1002 * needed. Also the xq, f and fshift device buffers have
1003 * been reallocated if needed, so the bonded code can
1004 * learn about them. */
1005 // TODO the xq, f, and fshift buffers are now shared
1006 // resources, so they should be maintained by a
1007 // higher-level object than the nb module.
1008 fr->gpuBonded->updateInteractionListsAndDeviceBuffers(nbv->getGridIndices(),
1010 Nbnxm::gpu_get_xq(nbv->gpu_nbv),
1011 Nbnxm::gpu_get_f(nbv->gpu_nbv),
1012 Nbnxm::gpu_get_fshift(nbv->gpu_nbv));
1014 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1017 // Need to run after the GPU-offload bonded interaction lists
1018 // are set up to be able to determine whether there is bonded work.
1019 setupForceWorkload(ppForceWorkload,
1029 /* do local pair search */
1032 // TODO: fuse this branch with the above bNS block
1033 wallcycle_start_nocount(wcycle, ewcNS);
1034 wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_LOCAL);
1035 /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1036 nbv->constructPairlist(Nbnxm::InteractionLocality::Local,
1037 &top->excls, step, nrnb);
1038 wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_LOCAL);
1039 wallcycle_stop(wcycle, ewcNS);
1043 nbv->atomdata_init_copy_x_to_nbat_x_gpu( Nbnxm::AtomLocality::Local);
1049 nbv->setCoordinates(Nbnxm::AtomLocality::Local, false,
1050 x.unpaddedArrayRef(), useGpuXBufOps, pme_gpu_get_device_x(fr->pmedata), wcycle);
1055 ddBalanceRegionHandler.openBeforeForceComputationGpu();
1057 wallcycle_start(wcycle, ewcLAUNCH_GPU);
1059 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1060 Nbnxm::gpu_upload_shiftvec(nbv->gpu_nbv, nbv->nbat.get());
1061 if (bNS || !useGpuXBufOps)
1063 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
1064 Nbnxm::AtomLocality::Local,
1065 ppForceWorkload->haveGpuBondedWork);
1067 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1068 // with X buffer ops offloaded to the GPU on all but the search steps
1070 // bonded work not split into separate local and non-local, so with DD
1071 // we can only launch the kernel after non-local coordinates have been received.
1072 if (ppForceWorkload->haveGpuBondedWork && !havePPDomainDecomposition(cr))
1074 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1075 fr->gpuBonded->launchKernel(fr, flags, box);
1076 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1079 /* launch local nonbonded work on GPU */
1080 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1081 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local, enbvClearFNo,
1082 step, nrnb, wcycle);
1083 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1084 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1089 // In PME GPU and mixed mode we launch FFT / gather after the
1090 // X copy/transform to allow overlap as well as after the GPU NB
1091 // launch to avoid FFT launch overhead hijacking the CPU and delaying
1092 // the nonbonded kernel.
1093 launchPmeGpuFftAndGather(fr->pmedata, wcycle);
1096 /* Communicate coordinates and sum dipole if necessary +
1097 do non-local pair search */
1098 if (havePPDomainDecomposition(cr))
1102 // TODO: fuse this branch with the above large bNS block
1103 wallcycle_start_nocount(wcycle, ewcNS);
1104 wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1105 /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1106 nbv->constructPairlist(Nbnxm::InteractionLocality::NonLocal,
1107 &top->excls, step, nrnb);
1108 wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1109 wallcycle_stop(wcycle, ewcNS);
1114 nbv->atomdata_init_copy_x_to_nbat_x_gpu( Nbnxm::AtomLocality::NonLocal);
1119 dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
1121 nbv->setCoordinates(Nbnxm::AtomLocality::NonLocal, false,
1122 x.unpaddedArrayRef(), useGpuXBufOps, pme_gpu_get_device_x(fr->pmedata), wcycle);
1128 wallcycle_start(wcycle, ewcLAUNCH_GPU);
1130 if (bNS || !useGpuXBufOps)
1132 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1133 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
1134 Nbnxm::AtomLocality::NonLocal,
1135 ppForceWorkload->haveGpuBondedWork);
1136 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1139 if (ppForceWorkload->haveGpuBondedWork)
1141 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1142 fr->gpuBonded->launchKernel(fr, flags, box);
1143 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1146 /* launch non-local nonbonded tasks on GPU */
1147 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1148 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1149 step, nrnb, wcycle);
1150 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1152 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1158 /* launch D2H copy-back F */
1159 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1160 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1161 if (havePPDomainDecomposition(cr))
1163 Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1164 flags, Nbnxm::AtomLocality::NonLocal, ppForceWorkload->haveGpuBondedWork);
1166 Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1167 flags, Nbnxm::AtomLocality::Local, ppForceWorkload->haveGpuBondedWork);
1168 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1170 if (ppForceWorkload->haveGpuBondedWork && (flags & GMX_FORCE_ENERGY))
1172 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_BONDED);
1173 fr->gpuBonded->launchEnergyTransfer();
1174 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1176 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1179 if (bStateChanged && inputrecNeedMutot(inputrec))
1183 gmx_sumd(2*DIM, mu, cr);
1185 ddBalanceRegionHandler.reopenRegionCpu();
1188 for (i = 0; i < 2; i++)
1190 for (j = 0; j < DIM; j++)
1192 fr->mu_tot[i][j] = mu[i*DIM + j];
1196 if (fr->efep == efepNO)
1198 copy_rvec(fr->mu_tot[0], mu_tot);
1202 for (j = 0; j < DIM; j++)
1205 (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] +
1206 lambda[efptCOUL]*fr->mu_tot[1][j];
1210 /* Reset energies */
1211 reset_enerdata(enerd);
1212 clear_rvecs(SHIFTS, fr->fshift);
1214 if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1216 wallcycle_start(wcycle, ewcPPDURINGPME);
1217 dd_force_flop_start(cr->dd, nrnb);
1222 wallcycle_start(wcycle, ewcROT);
1223 do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, bNS);
1224 wallcycle_stop(wcycle, ewcROT);
1227 /* Start the force cycle counter.
1228 * Note that a different counter is used for dynamic load balancing.
1230 wallcycle_start(wcycle, ewcFORCE);
1232 // set up and clear force outputs
1233 struct ForceOutputs forceOut = setupForceOutputs(fr, pull_work, *inputrec, force, bDoForces,
1234 ((flags & GMX_FORCE_VIRIAL) != 0), wcycle);
1236 /* We calculate the non-bonded forces, when done on the CPU, here.
1237 * We do this before calling do_force_lowlevel, because in that
1238 * function, the listed forces are calculated before PME, which
1239 * does communication. With this order, non-bonded and listed
1240 * force calculation imbalance can be balanced out by the domain
1241 * decomposition load balancing.
1246 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local, enbvClearFYes,
1247 step, nrnb, wcycle);
1250 if (fr->efep != efepNO)
1252 /* Calculate the local and non-local free energy interactions here.
1253 * Happens here on the CPU both with and without GPU.
1255 nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::Local,
1256 fr, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, *mdatoms,
1257 inputrec->fepvals, lambda.data(),
1258 enerd, flags, nrnb, wcycle);
1260 if (havePPDomainDecomposition(cr))
1262 nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::NonLocal,
1263 fr, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, *mdatoms,
1264 inputrec->fepvals, lambda.data(),
1265 enerd, flags, nrnb, wcycle);
1271 if (havePPDomainDecomposition(cr))
1273 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1274 step, nrnb, wcycle);
1277 /* Add all the non-bonded force to the normal force array.
1278 * This can be split into a local and a non-local part when overlapping
1279 * communication with calculation with domain decomposition.
1281 wallcycle_stop(wcycle, ewcFORCE);
1283 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::All, forceOut.f, wcycle);
1285 wallcycle_start_nocount(wcycle, ewcFORCE);
1287 /* If there are multiple fshift output buffers we need to reduce them */
1288 if (flags & GMX_FORCE_VIRIAL)
1290 /* This is not in a subcounter because it takes a
1291 negligible and constant-sized amount of time */
1292 nbnxn_atomdata_add_nbat_fshift_to_fshift(nbv->nbat.get(),
1297 /* update QMMMrec, if necessary */
1300 update_QMMMrec(cr, fr, as_rvec_array(x.unpaddedArrayRef().data()), mdatoms, box);
1303 /* Compute the bonded and non-bonded energies and optionally forces */
1304 do_force_lowlevel(fr, inputrec, &(top->idef),
1305 cr, ms, nrnb, wcycle, mdatoms,
1306 x, hist, forceOut.f, &forceOut.forceWithVirial, enerd, fcd,
1307 box, lambda.data(), graph, fr->mu_tot,
1309 ddBalanceRegionHandler);
1311 wallcycle_stop(wcycle, ewcFORCE);
1313 computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation,
1314 imdSession, pull_work, step, t, wcycle,
1315 fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda.data(),
1316 flags, &forceOut.forceWithVirial, enerd,
1319 // Will store the amount of cycles spent waiting for the GPU that
1320 // will be later used in the DLB accounting.
1321 float cycles_wait_gpu = 0;
1324 /* wait for non-local forces (or calculate in emulation mode) */
1325 if (havePPDomainDecomposition(cr))
1329 wallcycle_start(wcycle, ewcWAIT_GPU_NB_NL);
1330 Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1331 flags, Nbnxm::AtomLocality::NonLocal,
1332 ppForceWorkload->haveGpuBondedWork,
1333 enerd->grpp.ener[egLJSR].data(),
1334 enerd->grpp.ener[egCOULSR].data(),
1336 cycles_wait_gpu += wallcycle_stop(wcycle, ewcWAIT_GPU_NB_NL);
1340 wallcycle_start_nocount(wcycle, ewcFORCE);
1341 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFYes,
1342 step, nrnb, wcycle);
1343 wallcycle_stop(wcycle, ewcFORCE);
1346 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::NonLocal,
1347 forceOut.f, wcycle);
1349 if (fr->nbv->emulateGpu() && (flags & GMX_FORCE_VIRIAL))
1351 nbnxn_atomdata_add_nbat_fshift_to_fshift(nbv->nbat.get(),
1357 if (havePPDomainDecomposition(cr))
1359 /* We are done with the CPU compute.
1360 * We will now communicate the non-local forces.
1361 * If we use a GPU this will overlap with GPU work, so in that case
1362 * we do not close the DD force balancing region here.
1364 ddBalanceRegionHandler.closeAfterForceComputationCpu();
1368 dd_move_f(cr->dd, force.unpaddedArrayRef(), fr->fshift, wcycle);
1372 // With both nonbonded and PME offloaded a GPU on the same rank, we use
1373 // an alternating wait/reduction scheme.
1374 bool alternateGpuWait = (!c_disableAlternatingWait && useGpuPme && bUseGPU && !DOMAINDECOMP(cr));
1375 if (alternateGpuWait)
1377 alternatePmeNbGpuWaitReduce(fr->nbv.get(), fr->pmedata, &force, &forceOut.forceWithVirial, fr->fshift, enerd,
1378 flags, pmeFlags, ppForceWorkload->haveGpuBondedWork, wcycle);
1381 if (!alternateGpuWait && useGpuPme)
1383 pme_gpu_wait_and_reduce(fr->pmedata, pmeFlags, wcycle, &forceOut.forceWithVirial, enerd);
1386 /* Wait for local GPU NB outputs on the non-alternating wait path */
1387 if (!alternateGpuWait && bUseGPU)
1389 /* Measured overhead on CUDA and OpenCL with(out) GPU sharing
1390 * is between 0.5 and 1.5 Mcycles. So 2 MCycles is an overestimate,
1391 * but even with a step of 0.1 ms the difference is less than 1%
1394 const float gpuWaitApiOverheadMargin = 2e6f; /* cycles */
1396 wallcycle_start(wcycle, ewcWAIT_GPU_NB_L);
1397 Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1398 flags, Nbnxm::AtomLocality::Local, ppForceWorkload->haveGpuBondedWork,
1399 enerd->grpp.ener[egLJSR].data(),
1400 enerd->grpp.ener[egCOULSR].data(),
1402 float cycles_tmp = wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
1404 if (ddBalanceRegionHandler.useBalancingRegion())
1406 DdBalanceRegionWaitedForGpu waitedForGpu = DdBalanceRegionWaitedForGpu::yes;
1407 if (bDoForces && cycles_tmp <= gpuWaitApiOverheadMargin)
1409 /* We measured few cycles, it could be that the kernel
1410 * and transfer finished earlier and there was no actual
1411 * wait time, only API call overhead.
1412 * Then the actual time could be anywhere between 0 and
1413 * cycles_wait_est. We will use half of cycles_wait_est.
1415 waitedForGpu = DdBalanceRegionWaitedForGpu::no;
1417 ddBalanceRegionHandler.closeAfterForceComputationGpu(cycles_wait_gpu, waitedForGpu);
1421 if (fr->nbv->emulateGpu())
1423 // NOTE: emulation kernel is not included in the balancing region,
1424 // but emulation mode does not target performance anyway
1425 wallcycle_start_nocount(wcycle, ewcFORCE);
1426 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local,
1427 DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes,
1428 step, nrnb, wcycle);
1429 wallcycle_stop(wcycle, ewcFORCE);
1434 pme_gpu_reinit_computation(fr->pmedata, wcycle);
1439 /* now clear the GPU outputs while we finish the step on the CPU */
1440 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1441 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1442 Nbnxm::gpu_clear_outputs(nbv->gpu_nbv, flags);
1444 if (nbv->isDynamicPruningStepGpu(step))
1446 nbv->dispatchPruneKernelGpu(step);
1448 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1449 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1452 if (ppForceWorkload->haveGpuBondedWork && (flags & GMX_FORCE_ENERGY))
1454 wallcycle_start(wcycle, ewcWAIT_GPU_BONDED);
1455 // in principle this should be included in the DD balancing region,
1456 // but generally it is infrequent so we'll omit it for the sake of
1458 fr->gpuBonded->accumulateEnergyTerms(enerd);
1459 wallcycle_stop(wcycle, ewcWAIT_GPU_BONDED);
1461 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1462 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_BONDED);
1463 fr->gpuBonded->clearEnergies();
1464 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1465 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1468 /* Do the nonbonded GPU (or emulation) force buffer reduction
1469 * on the non-alternating path. */
1470 if (bUseOrEmulGPU && !alternateGpuWait)
1472 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local,
1473 forceOut.f, wcycle);
1475 if (DOMAINDECOMP(cr))
1477 dd_force_flop_stop(cr->dd, nrnb);
1482 /* If we have NoVirSum forces, but we do not calculate the virial,
1483 * we sum fr->f_novirsum=forceOut.f later.
1485 if (vsite && !(fr->haveDirectVirialContributions && !(flags & GMX_FORCE_VIRIAL)))
1487 spread_vsite_f(vsite, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, fr->fshift, FALSE, nullptr, nrnb,
1488 &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
1491 if (flags & GMX_FORCE_VIRIAL)
1493 /* Calculation of the virial must be done after vsites! */
1494 calc_virial(0, mdatoms->homenr, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f,
1495 vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1499 if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME))
1501 /* In case of node-splitting, the PP nodes receive the long-range
1502 * forces, virial and energy from the PME nodes here.
1504 pme_receive_force_ener(cr, &forceOut.forceWithVirial, enerd, wcycle);
1509 post_process_forces(cr, step, nrnb, wcycle,
1510 top, box, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, &forceOut.forceWithVirial,
1511 vir_force, mdatoms, graph, fr, vsite,
1515 if (flags & GMX_FORCE_ENERGY)
1517 /* Sum the potential energy terms from group contributions */
1518 sum_epot(&(enerd->grpp), enerd->term);
1520 if (!EI_TPI(inputrec->eI))
1522 checkPotentialEnergyValidity(step, *enerd, *inputrec);
1526 /* In case we don't have constraints and are using GPUs, the next balancing
1527 * region starts here.
1528 * Some "special" work at the end of do_force_cuts?, such as vsite spread,
1529 * virial calculation and COM pulling, is not thus not included in
1530 * the balance timing, which is ok as most tasks do communication.
1532 ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::no);