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.
50 #include "gromacs/awh/awh.h"
51 #include "gromacs/domdec/dlbtiming.h"
52 #include "gromacs/domdec/domdec.h"
53 #include "gromacs/domdec/domdec_struct.h"
54 #include "gromacs/domdec/partition.h"
55 #include "gromacs/essentialdynamics/edsam.h"
56 #include "gromacs/ewald/pme.h"
57 #include "gromacs/gmxlib/chargegroup.h"
58 #include "gromacs/gmxlib/network.h"
59 #include "gromacs/gmxlib/nrnb.h"
60 #include "gromacs/gmxlib/nonbonded/nb_free_energy.h"
61 #include "gromacs/gmxlib/nonbonded/nb_kernel.h"
62 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
63 #include "gromacs/gpu_utils/gpu_utils.h"
64 #include "gromacs/imd/imd.h"
65 #include "gromacs/listed_forces/bonded.h"
66 #include "gromacs/listed_forces/disre.h"
67 #include "gromacs/listed_forces/gpubonded.h"
68 #include "gromacs/listed_forces/manage_threading.h"
69 #include "gromacs/listed_forces/orires.h"
70 #include "gromacs/math/arrayrefwithpadding.h"
71 #include "gromacs/math/functions.h"
72 #include "gromacs/math/units.h"
73 #include "gromacs/math/vec.h"
74 #include "gromacs/math/vecdump.h"
75 #include "gromacs/mdlib/calcmu.h"
76 #include "gromacs/mdlib/calcvir.h"
77 #include "gromacs/mdlib/constr.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/mdrun.h"
82 #include "gromacs/mdlib/ppforceworkload.h"
83 #include "gromacs/mdlib/qmmm.h"
84 #include "gromacs/mdlib/update.h"
85 #include "gromacs/mdtypes/commrec.h"
86 #include "gromacs/mdtypes/enerdata.h"
87 #include "gromacs/mdtypes/forceoutput.h"
88 #include "gromacs/mdtypes/iforceprovider.h"
89 #include "gromacs/mdtypes/inputrec.h"
90 #include "gromacs/mdtypes/md_enums.h"
91 #include "gromacs/mdtypes/state.h"
92 #include "gromacs/nbnxm/atomdata.h"
93 #include "gromacs/nbnxm/gpu_data_mgmt.h"
94 #include "gromacs/nbnxm/nbnxm.h"
95 #include "gromacs/pbcutil/ishift.h"
96 #include "gromacs/pbcutil/mshift.h"
97 #include "gromacs/pbcutil/pbc.h"
98 #include "gromacs/pulling/pull.h"
99 #include "gromacs/pulling/pull_rotation.h"
100 #include "gromacs/timing/cyclecounter.h"
101 #include "gromacs/timing/gpu_timing.h"
102 #include "gromacs/timing/wallcycle.h"
103 #include "gromacs/timing/wallcyclereporting.h"
104 #include "gromacs/timing/walltime_accounting.h"
105 #include "gromacs/topology/topology.h"
106 #include "gromacs/utility/arrayref.h"
107 #include "gromacs/utility/basedefinitions.h"
108 #include "gromacs/utility/cstringutil.h"
109 #include "gromacs/utility/exceptions.h"
110 #include "gromacs/utility/fatalerror.h"
111 #include "gromacs/utility/gmxassert.h"
112 #include "gromacs/utility/gmxmpi.h"
113 #include "gromacs/utility/logger.h"
114 #include "gromacs/utility/smalloc.h"
115 #include "gromacs/utility/strconvert.h"
116 #include "gromacs/utility/sysinfo.h"
118 // TODO: this environment variable allows us to verify before release
119 // that on less common architectures the total cost of polling is not larger than
120 // a blocking wait (so polling does not introduce overhead when the static
121 // PME-first ordering would suffice).
122 static const bool c_disableAlternatingWait = (getenv("GMX_DISABLE_ALTERNATING_GPU_WAIT") != nullptr);
125 static void sum_forces(rvec f[], gmx::ArrayRef<const gmx::RVec> forceToAdd)
127 const int end = forceToAdd.size();
129 int gmx_unused nt = gmx_omp_nthreads_get(emntDefault);
130 #pragma omp parallel for num_threads(nt) schedule(static)
131 for (int i = 0; i < end; i++)
133 rvec_inc(f[i], forceToAdd[i]);
137 static void calc_virial(int start, int homenr, const rvec x[], const rvec f[],
138 tensor vir_part, const t_graph *graph, const matrix box,
139 t_nrnb *nrnb, const t_forcerec *fr, int ePBC)
141 /* The short-range virial from surrounding boxes */
142 calc_vir(SHIFTS, fr->shift_vec, fr->fshift, vir_part, ePBC == epbcSCREW, box);
143 inc_nrnb(nrnb, eNR_VIRIAL, SHIFTS);
145 /* Calculate partial virial, for local atoms only, based on short range.
146 * Total virial is computed in global_stat, called from do_md
148 f_calc_vir(start, start+homenr, x, f, vir_part, graph, box);
149 inc_nrnb(nrnb, eNR_VIRIAL, homenr);
153 pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
157 static void pull_potential_wrapper(const t_commrec *cr,
158 const t_inputrec *ir,
159 const matrix box, gmx::ArrayRef<const gmx::RVec> x,
160 gmx::ForceWithVirial *force,
161 const t_mdatoms *mdatoms,
162 gmx_enerdata_t *enerd,
165 gmx_wallcycle_t wcycle)
170 /* Calculate the center of mass forces, this requires communication,
171 * which is why pull_potential is called close to other communication.
173 wallcycle_start(wcycle, ewcPULLPOT);
174 set_pbc(&pbc, ir->ePBC, box);
176 enerd->term[F_COM_PULL] +=
177 pull_potential(ir->pull_work, mdatoms, &pbc,
178 cr, t, lambda[efptRESTRAINT], as_rvec_array(x.data()), force, &dvdl);
179 enerd->dvdl_lin[efptRESTRAINT] += dvdl;
180 wallcycle_stop(wcycle, ewcPULLPOT);
183 static void pme_receive_force_ener(const t_commrec *cr,
184 gmx::ForceWithVirial *forceWithVirial,
185 gmx_enerdata_t *enerd,
186 gmx_wallcycle_t wcycle)
188 real e_q, e_lj, dvdl_q, dvdl_lj;
189 float cycles_ppdpme, cycles_seppme;
191 cycles_ppdpme = wallcycle_stop(wcycle, ewcPPDURINGPME);
192 dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
194 /* In case of node-splitting, the PP nodes receive the long-range
195 * forces, virial and energy from the PME nodes here.
197 wallcycle_start(wcycle, ewcPP_PMEWAITRECVF);
200 gmx_pme_receive_f(cr, forceWithVirial, &e_q, &e_lj, &dvdl_q, &dvdl_lj,
202 enerd->term[F_COUL_RECIP] += e_q;
203 enerd->term[F_LJ_RECIP] += e_lj;
204 enerd->dvdl_lin[efptCOUL] += dvdl_q;
205 enerd->dvdl_lin[efptVDW] += dvdl_lj;
209 dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
211 wallcycle_stop(wcycle, ewcPP_PMEWAITRECVF);
214 static void print_large_forces(FILE *fp,
222 real force2Tolerance = gmx::square(forceTolerance);
223 gmx::index numNonFinite = 0;
224 for (int i = 0; i < md->homenr; i++)
226 real force2 = norm2(f[i]);
227 bool nonFinite = !std::isfinite(force2);
228 if (force2 >= force2Tolerance || nonFinite)
230 fprintf(fp, "step %" PRId64 " atom %6d x %8.3f %8.3f %8.3f force %12.5e\n",
232 ddglatnr(cr->dd, i), x[i][XX], x[i][YY], x[i][ZZ], std::sqrt(force2));
239 if (numNonFinite > 0)
241 /* Note that with MPI this fatal call on one rank might interrupt
242 * the printing on other ranks. But we can only avoid that with
243 * an expensive MPI barrier that we would need at each step.
245 gmx_fatal(FARGS, "At step %" PRId64 " detected non-finite forces on %td atoms", step, numNonFinite);
249 static void post_process_forces(const t_commrec *cr,
252 gmx_wallcycle_t wcycle,
253 const gmx_localtop_t *top,
257 gmx::ForceWithVirial *forceWithVirial,
259 const t_mdatoms *mdatoms,
260 const t_graph *graph,
261 const t_forcerec *fr,
262 const gmx_vsite_t *vsite,
265 if (fr->haveDirectVirialContributions)
267 rvec *fDirectVir = as_rvec_array(forceWithVirial->force_.data());
271 /* Spread the mesh force on virtual sites to the other particles...
272 * This is parallellized. MPI communication is performed
273 * if the constructing atoms aren't local.
275 matrix virial = { { 0 } };
276 spread_vsite_f(vsite, x, fDirectVir, nullptr,
277 (flags & GMX_FORCE_VIRIAL) != 0, virial,
279 &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
280 forceWithVirial->addVirialContribution(virial);
283 if (flags & GMX_FORCE_VIRIAL)
285 /* Now add the forces, this is local */
286 sum_forces(f, forceWithVirial->force_);
288 /* Add the direct virial contributions */
289 GMX_ASSERT(forceWithVirial->computeVirial_, "forceWithVirial should request virial computation when we request the virial");
290 m_add(vir_force, forceWithVirial->getVirial(), vir_force);
294 pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
299 if (fr->print_force >= 0)
301 print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
305 static void do_nb_verlet(t_forcerec *fr,
306 const interaction_const_t *ic,
307 gmx_enerdata_t *enerd,
309 const Nbnxm::InteractionLocality ilocality,
313 gmx_wallcycle_t wcycle)
315 if (!(flags & GMX_FORCE_NONBONDED))
317 /* skip non-bonded calculation */
321 nonbonded_verlet_t *nbv = fr->nbv.get();
323 /* GPU kernel launch overhead is already timed separately */
324 if (fr->cutoff_scheme != ecutsVERLET)
326 gmx_incons("Invalid cut-off scheme passed!");
331 /* When dynamic pair-list pruning is requested, we need to prune
332 * at nstlistPrune steps.
334 if (nbv->pairlistSets().isDynamicPruningStepCpu(step))
336 /* Prune the pair-list beyond fr->ic->rlistPrune using
337 * the current coordinates of the atoms.
339 wallcycle_sub_start(wcycle, ewcsNONBONDED_PRUNING);
340 nbv->dispatchPruneKernelCpu(ilocality, fr->shift_vec);
341 wallcycle_sub_stop(wcycle, ewcsNONBONDED_PRUNING);
344 wallcycle_sub_start(wcycle, ewcsNONBONDED);
347 nbv->dispatchNonbondedKernel(ilocality, *ic, flags, clearF, fr, enerd, nrnb);
351 wallcycle_sub_stop(wcycle, ewcsNONBONDED);
355 gmx_bool use_GPU(const nonbonded_verlet_t *nbv)
357 return nbv != nullptr && nbv->useGpu();
360 static inline void clear_rvecs_omp(int n, rvec v[])
362 int nth = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, n);
364 /* Note that we would like to avoid this conditional by putting it
365 * into the omp pragma instead, but then we still take the full
366 * omp parallel for overhead (at least with gcc5).
370 for (int i = 0; i < n; i++)
377 #pragma omp parallel for num_threads(nth) schedule(static)
378 for (int i = 0; i < n; i++)
385 /*! \brief Return an estimate of the average kinetic energy or 0 when unreliable
387 * \param groupOptions Group options, containing T-coupling options
389 static real averageKineticEnergyEstimate(const t_grpopts &groupOptions)
391 real nrdfCoupled = 0;
392 real nrdfUncoupled = 0;
393 real kineticEnergy = 0;
394 for (int g = 0; g < groupOptions.ngtc; g++)
396 if (groupOptions.tau_t[g] >= 0)
398 nrdfCoupled += groupOptions.nrdf[g];
399 kineticEnergy += groupOptions.nrdf[g]*0.5*groupOptions.ref_t[g]*BOLTZ;
403 nrdfUncoupled += groupOptions.nrdf[g];
407 /* This conditional with > also catches nrdf=0 */
408 if (nrdfCoupled > nrdfUncoupled)
410 return kineticEnergy*(nrdfCoupled + nrdfUncoupled)/nrdfCoupled;
418 /*! \brief This routine checks that the potential energy is finite.
420 * Always checks that the potential energy is finite. If step equals
421 * inputrec.init_step also checks that the magnitude of the potential energy
422 * is reasonable. Terminates with a fatal error when a check fails.
423 * Note that passing this check does not guarantee finite forces,
424 * since those use slightly different arithmetics. But in most cases
425 * there is just a narrow coordinate range where forces are not finite
426 * and energies are finite.
428 * \param[in] step The step number, used for checking and printing
429 * \param[in] enerd The energy data; the non-bonded group energies need to be added to enerd.term[F_EPOT] before calling this routine
430 * \param[in] inputrec The input record
432 static void checkPotentialEnergyValidity(int64_t step,
433 const gmx_enerdata_t &enerd,
434 const t_inputrec &inputrec)
436 /* Threshold valid for comparing absolute potential energy against
437 * the kinetic energy. Normally one should not consider absolute
438 * potential energy values, but with a factor of one million
439 * we should never get false positives.
441 constexpr real c_thresholdFactor = 1e6;
443 bool energyIsNotFinite = !std::isfinite(enerd.term[F_EPOT]);
444 real averageKineticEnergy = 0;
445 /* We only check for large potential energy at the initial step,
446 * because that is by far the most likely step for this too occur
447 * and because computing the average kinetic energy is not free.
448 * Note: nstcalcenergy >> 1 often does not allow to catch large energies
449 * before they become NaN.
451 if (step == inputrec.init_step && EI_DYNAMICS(inputrec.eI))
453 averageKineticEnergy = averageKineticEnergyEstimate(inputrec.opts);
456 if (energyIsNotFinite || (averageKineticEnergy > 0 &&
457 enerd.term[F_EPOT] > c_thresholdFactor*averageKineticEnergy))
459 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.",
462 energyIsNotFinite ? "not finite" : "extremely high",
464 enerd.term[F_COUL_SR],
465 energyIsNotFinite ? "non-finite" : "very high",
466 energyIsNotFinite ? " or Nan" : "");
470 /*! \brief Compute forces and/or energies for special algorithms
472 * The intention is to collect all calls to algorithms that compute
473 * forces on local atoms only and that do not contribute to the local
474 * virial sum (but add their virial contribution separately).
475 * Eventually these should likely all become ForceProviders.
476 * Within this function the intention is to have algorithms that do
477 * global communication at the end, so global barriers within the MD loop
478 * are as close together as possible.
480 * \param[in] fplog The log file
481 * \param[in] cr The communication record
482 * \param[in] inputrec The input record
483 * \param[in] awh The Awh module (nullptr if none in use).
484 * \param[in] enforcedRotation Enforced rotation module.
485 * \param[in] step The current MD step
486 * \param[in] t The current time
487 * \param[in,out] wcycle Wallcycle accounting struct
488 * \param[in,out] forceProviders Pointer to a list of force providers
489 * \param[in] box The unit cell
490 * \param[in] x The coordinates
491 * \param[in] mdatoms Per atom properties
492 * \param[in] lambda Array of free-energy lambda values
493 * \param[in] forceFlags Flags that tell whether we should compute forces/energies/virial
494 * \param[in,out] forceWithVirial Force and virial buffers
495 * \param[in,out] enerd Energy buffer
496 * \param[in,out] ed Essential dynamics pointer
497 * \param[in] bNS Tells if we did neighbor searching this step, used for ED sampling
499 * \todo Remove bNS, which is used incorrectly.
500 * \todo Convert all other algorithms called here to ForceProviders.
503 computeSpecialForces(FILE *fplog,
505 const t_inputrec *inputrec,
507 gmx_enfrot *enforcedRotation,
510 gmx_wallcycle_t wcycle,
511 ForceProviders *forceProviders,
513 gmx::ArrayRef<const gmx::RVec> x,
514 const t_mdatoms *mdatoms,
517 gmx::ForceWithVirial *forceWithVirial,
518 gmx_enerdata_t *enerd,
522 const bool computeForces = (forceFlags & GMX_FORCE_FORCES) != 0;
524 /* NOTE: Currently all ForceProviders only provide forces.
525 * When they also provide energies, remove this conditional.
529 gmx::ForceProviderInput forceProviderInput(x, *mdatoms, t, box, *cr);
530 gmx::ForceProviderOutput forceProviderOutput(forceWithVirial, enerd);
532 /* Collect forces from modules */
533 forceProviders->calculateForces(forceProviderInput, &forceProviderOutput);
536 if (inputrec->bPull && pull_have_potential(inputrec->pull_work))
538 pull_potential_wrapper(cr, inputrec, box, x,
540 mdatoms, enerd, lambda, t,
545 enerd->term[F_COM_PULL] +=
546 awh->applyBiasForcesAndUpdateBias(inputrec->ePBC, *mdatoms, box,
548 t, step, wcycle, fplog);
552 rvec *f = as_rvec_array(forceWithVirial->force_.data());
554 /* Add the forces from enforced rotation potentials (if any) */
557 wallcycle_start(wcycle, ewcROTadd);
558 enerd->term[F_COM_PULL] += add_rot_forces(enforcedRotation, f, cr, step, t);
559 wallcycle_stop(wcycle, ewcROTadd);
564 /* Note that since init_edsam() is called after the initialization
565 * of forcerec, edsam doesn't request the noVirSum force buffer.
566 * Thus if no other algorithm (e.g. PME) requires it, the forces
567 * here will contribute to the virial.
569 do_flood(cr, inputrec, as_rvec_array(x.data()), f, ed, box, step, bNS);
572 /* Add forces from interactive molecular dynamics (IMD), if bIMD == TRUE. */
573 if (inputrec->bIMD && computeForces)
575 IMD_apply_forces(inputrec->bIMD, inputrec->imd, cr, f, wcycle);
579 /*! \brief Launch the prepare_step and spread stages of PME GPU.
581 * \param[in] pmedata The PME structure
582 * \param[in] box The box matrix
583 * \param[in] x Coordinate array
584 * \param[in] flags Force flags
585 * \param[in] pmeFlags PME flags
586 * \param[in] wcycle The wallcycle structure
588 static inline void launchPmeGpuSpread(gmx_pme_t *pmedata,
593 gmx_wallcycle_t wcycle)
595 pme_gpu_prepare_computation(pmedata, (flags & GMX_FORCE_DYNAMICBOX) != 0, box, wcycle, pmeFlags);
596 pme_gpu_launch_spread(pmedata, x, wcycle);
599 /*! \brief Launch the FFT and gather stages of PME GPU
601 * This function only implements setting the output forces (no accumulation).
603 * \param[in] pmedata The PME structure
604 * \param[in] wcycle The wallcycle structure
606 static void launchPmeGpuFftAndGather(gmx_pme_t *pmedata,
607 gmx_wallcycle_t wcycle)
609 pme_gpu_launch_complex_transforms(pmedata, wcycle);
610 pme_gpu_launch_gather(pmedata, wcycle, PmeForceOutputHandling::Set);
614 * Polling wait for either of the PME or nonbonded GPU tasks.
616 * Instead of a static order in waiting for GPU tasks, this function
617 * polls checking which of the two tasks completes first, and does the
618 * associated force buffer reduction overlapped with the other task.
619 * By doing that, unlike static scheduling order, it can always overlap
620 * one of the reductions, regardless of the GPU task completion order.
622 * \param[in] nbv Nonbonded verlet structure
623 * \param[in,out] pmedata PME module data
624 * \param[in,out] force Force array to reduce task outputs into.
625 * \param[in,out] forceWithVirial Force and virial buffers
626 * \param[in,out] fshift Shift force output vector results are reduced into
627 * \param[in,out] enerd Energy data structure results are reduced into
628 * \param[in] flags Force flags
629 * \param[in] pmeFlags PME flags
630 * \param[in] haveOtherWork Tells whether there is other work than non-bonded in the stream(s)
631 * \param[in] wcycle The wallcycle structure
633 static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t *nbv,
635 gmx::ArrayRefWithPadding<gmx::RVec> *force,
636 gmx::ForceWithVirial *forceWithVirial,
638 gmx_enerdata_t *enerd,
642 gmx_wallcycle_t wcycle)
644 bool isPmeGpuDone = false;
645 bool isNbGpuDone = false;
648 gmx::ArrayRef<const gmx::RVec> pmeGpuForces;
650 while (!isPmeGpuDone || !isNbGpuDone)
654 GpuTaskCompletion completionType = (isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
655 isPmeGpuDone = pme_gpu_try_finish_task(pmedata, pmeFlags, wcycle, forceWithVirial, enerd, completionType);
660 GpuTaskCompletion completionType = (isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
661 wallcycle_start_nocount(wcycle, ewcWAIT_GPU_NB_L);
662 isNbGpuDone = Nbnxm::gpu_try_finish_task(nbv->gpu_nbv,
664 Nbnxm::AtomLocality::Local,
666 enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
667 fshift, completionType);
668 wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
669 // To get the call count right, when the task finished we
670 // issue a start/stop.
671 // TODO: move the ewcWAIT_GPU_NB_L cycle counting into nbnxn_gpu_try_finish_task()
672 // and ewcNB_XF_BUF_OPS counting into nbnxn_atomdata_add_nbat_f_to_f().
675 wallcycle_start(wcycle, ewcWAIT_GPU_NB_L);
676 wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
678 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local,
679 as_rvec_array(force->unpaddedArrayRef().data()), wcycle);
685 static void do_force_cutsVERLET(FILE *fplog,
687 const gmx_multisim_t *ms,
688 const t_inputrec *inputrec,
690 gmx_enfrot *enforcedRotation,
693 gmx_wallcycle_t wcycle,
694 const gmx_localtop_t *top,
695 const gmx_groups_t * /* groups */,
696 matrix box, gmx::ArrayRefWithPadding<gmx::RVec> x,
698 gmx::ArrayRefWithPadding<gmx::RVec> force,
700 const t_mdatoms *mdatoms,
701 gmx_enerdata_t *enerd, t_fcdata *fcd,
705 gmx::PpForceWorkload *ppForceWorkload,
706 interaction_const_t *ic,
707 const gmx_vsite_t *vsite,
712 const DDBalanceRegionHandler &ddBalanceRegionHandler)
716 gmx_bool bStateChanged, bNS, bFillGrid, bCalcCGCM;
717 gmx_bool bDoForces, bUseGPU, bUseOrEmulGPU;
718 rvec vzero, box_diag;
719 float cycles_pme, cycles_wait_gpu;
720 nonbonded_verlet_t *nbv = fr->nbv.get();
722 bStateChanged = ((flags & GMX_FORCE_STATECHANGED) != 0);
723 bNS = ((flags & GMX_FORCE_NS) != 0);
724 bFillGrid = (bNS && bStateChanged);
725 bCalcCGCM = (bFillGrid && !DOMAINDECOMP(cr));
726 bDoForces = ((flags & GMX_FORCE_FORCES) != 0);
727 bUseGPU = fr->nbv->useGpu();
728 bUseOrEmulGPU = bUseGPU || fr->nbv->emulateGpu();
730 const auto pmeRunMode = fr->pmedata ? pme_run_mode(fr->pmedata) : PmeRunMode::CPU;
731 // TODO slim this conditional down - inputrec and duty checks should mean the same in proper code!
732 const bool useGpuPme = EEL_PME(fr->ic->eeltype) && thisRankHasDuty(cr, DUTY_PME) &&
733 ((pmeRunMode == PmeRunMode::GPU) || (pmeRunMode == PmeRunMode::Mixed));
734 const int pmeFlags = GMX_PME_SPREAD | GMX_PME_SOLVE |
735 ((flags & GMX_FORCE_VIRIAL) ? GMX_PME_CALC_ENER_VIR : 0) |
736 ((flags & GMX_FORCE_ENERGY) ? GMX_PME_CALC_ENER_VIR : 0) |
737 ((flags & GMX_FORCE_FORCES) ? GMX_PME_CALC_F : 0);
739 /* At a search step we need to start the first balancing region
740 * somewhere early inside the step after communication during domain
741 * decomposition (and not during the previous step as usual).
745 ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::yes);
751 const int homenr = mdatoms->homenr;
753 clear_mat(vir_force);
755 if (DOMAINDECOMP(cr))
757 cg1 = cr->dd->globalAtomGroupIndices.size();
770 update_forcerec(fr, box);
772 if (inputrecNeedMutot(inputrec))
774 /* Calculate total (local) dipole moment in a temporary common array.
775 * This makes it possible to sum them over nodes faster.
777 calc_mu(start, homenr,
778 x.unpaddedArrayRef(), mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
783 if (fr->ePBC != epbcNONE)
785 /* Compute shift vectors every step,
786 * because of pressure coupling or box deformation!
788 if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
790 calc_shifts(box, fr->shift_vec);
795 put_atoms_in_box_omp(fr->ePBC, box, x.unpaddedArrayRef().subArray(0, homenr));
796 inc_nrnb(nrnb, eNR_SHIFTX, homenr);
798 else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
800 unshift_self(graph, box, as_rvec_array(x.unpaddedArrayRef().data()));
804 nbnxn_atomdata_copy_shiftvec((flags & GMX_FORCE_DYNAMICBOX) != 0,
805 fr->shift_vec, nbv->nbat.get());
808 if (!thisRankHasDuty(cr, DUTY_PME))
810 /* Send particle coordinates to the pme nodes.
811 * Since this is only implemented for domain decomposition
812 * and domain decomposition does not use the graph,
813 * we do not need to worry about shifting.
815 gmx_pme_send_coordinates(cr, box, as_rvec_array(x.unpaddedArrayRef().data()),
816 lambda[efptCOUL], lambda[efptVDW],
817 (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY)) != 0,
824 launchPmeGpuSpread(fr->pmedata, box, as_rvec_array(x.unpaddedArrayRef().data()), flags, pmeFlags, wcycle);
827 /* do gridding for pair search */
830 if (graph && bStateChanged)
832 /* Calculate intramolecular shift vectors to make molecules whole */
833 mk_mshift(fplog, graph, fr->ePBC, box, as_rvec_array(x.unpaddedArrayRef().data()));
837 box_diag[XX] = box[XX][XX];
838 box_diag[YY] = box[YY][YY];
839 box_diag[ZZ] = box[ZZ][ZZ];
841 wallcycle_start(wcycle, ewcNS);
842 if (!DOMAINDECOMP(cr))
844 wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL);
845 nbnxn_put_on_grid(nbv, box,
847 nullptr, 0, mdatoms->homenr, -1,
848 fr->cginfo, x.unpaddedArrayRef(),
850 wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL);
854 wallcycle_sub_start(wcycle, ewcsNBS_GRID_NONLOCAL);
855 nbnxn_put_on_grid_nonlocal(nbv, domdec_zones(cr->dd),
856 fr->cginfo, x.unpaddedArrayRef());
857 wallcycle_sub_stop(wcycle, ewcsNBS_GRID_NONLOCAL);
860 nbnxn_atomdata_set(nbv->nbat.get(), nbv->nbs.get(), mdatoms, fr->cginfo);
862 wallcycle_stop(wcycle, ewcNS);
865 /* initialize the GPU atom data and copy shift vector */
868 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
869 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
873 Nbnxm::gpu_init_atomdata(nbv->gpu_nbv, nbv->nbat.get());
876 Nbnxm::gpu_upload_shiftvec(nbv->gpu_nbv, nbv->nbat.get());
878 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
880 if (bNS && fr->gpuBonded)
882 /* Now we put all atoms on the grid, we can assign bonded
883 * interactions to the GPU, where the grid order is
884 * needed. Also the xq, f and fshift device buffers have
885 * been reallocated if needed, so the bonded code can
886 * learn about them. */
887 // TODO the xq, f, and fshift buffers are now shared
888 // resources, so they should be maintained by a
889 // higher-level object than the nb module.
890 fr->gpuBonded->updateInteractionListsAndDeviceBuffers(nbnxn_get_gridindices(fr->nbv->nbs.get()),
892 Nbnxm::gpu_get_xq(nbv->gpu_nbv),
893 Nbnxm::gpu_get_f(nbv->gpu_nbv),
894 Nbnxm::gpu_get_fshift(nbv->gpu_nbv));
895 ppForceWorkload->haveGpuBondedWork = fr->gpuBonded->haveInteractions();
898 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
901 /* do local pair search */
904 wallcycle_start_nocount(wcycle, ewcNS);
905 wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_LOCAL);
906 /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
907 nbv->constructPairlist(Nbnxm::InteractionLocality::Local,
908 &top->excls, step, nrnb);
909 wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_LOCAL);
910 wallcycle_stop(wcycle, ewcNS);
914 nbnxn_atomdata_copy_x_to_nbat_x(nbv->nbs.get(), Nbnxm::AtomLocality::Local,
915 FALSE, as_rvec_array(x.unpaddedArrayRef().data()),
916 nbv->nbat.get(), wcycle);
921 ddBalanceRegionHandler.openBeforeForceComputationGpu();
923 wallcycle_start(wcycle, ewcLAUNCH_GPU);
925 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
926 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
927 Nbnxm::AtomLocality::Local,
928 ppForceWorkload->haveGpuBondedWork);
929 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
931 // bonded work not split into separate local and non-local, so with DD
932 // we can only launch the kernel after non-local coordinates have been received.
933 if (ppForceWorkload->haveGpuBondedWork && !havePPDomainDecomposition(cr))
935 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
936 fr->gpuBonded->launchKernels(fr, flags, box);
937 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
940 /* launch local nonbonded work on GPU */
941 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
942 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local, enbvClearFNo,
944 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
945 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
950 // In PME GPU and mixed mode we launch FFT / gather after the
951 // X copy/transform to allow overlap as well as after the GPU NB
952 // launch to avoid FFT launch overhead hijacking the CPU and delaying
953 // the nonbonded kernel.
954 launchPmeGpuFftAndGather(fr->pmedata, wcycle);
957 /* Communicate coordinates and sum dipole if necessary +
958 do non-local pair search */
959 if (havePPDomainDecomposition(cr))
963 wallcycle_start_nocount(wcycle, ewcNS);
964 wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_NONLOCAL);
965 /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
966 nbv->constructPairlist(Nbnxm::InteractionLocality::NonLocal,
967 &top->excls, step, nrnb);
968 wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_NONLOCAL);
969 wallcycle_stop(wcycle, ewcNS);
973 dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
975 nbnxn_atomdata_copy_x_to_nbat_x(nbv->nbs.get(), Nbnxm::AtomLocality::NonLocal,
976 FALSE, as_rvec_array(x.unpaddedArrayRef().data()),
977 nbv->nbat.get(), wcycle);
982 wallcycle_start(wcycle, ewcLAUNCH_GPU);
984 /* launch non-local nonbonded tasks on GPU */
985 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
986 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
987 Nbnxm::AtomLocality::NonLocal,
988 ppForceWorkload->haveGpuBondedWork);
989 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
991 if (ppForceWorkload->haveGpuBondedWork)
993 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
994 fr->gpuBonded->launchKernels(fr, flags, box);
995 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
998 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
999 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1000 step, nrnb, wcycle);
1001 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1003 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1009 /* launch D2H copy-back F */
1010 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1011 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1012 if (havePPDomainDecomposition(cr))
1014 Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1015 flags, Nbnxm::AtomLocality::NonLocal, ppForceWorkload->haveGpuBondedWork);
1017 Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1018 flags, Nbnxm::AtomLocality::Local, ppForceWorkload->haveGpuBondedWork);
1019 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1021 if (ppForceWorkload->haveGpuBondedWork && (flags & GMX_FORCE_ENERGY))
1023 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_BONDED);
1024 fr->gpuBonded->launchEnergyTransfer();
1025 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1027 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1030 if (bStateChanged && inputrecNeedMutot(inputrec))
1034 gmx_sumd(2*DIM, mu, cr);
1036 ddBalanceRegionHandler.reopenRegionCpu();
1039 for (i = 0; i < 2; i++)
1041 for (j = 0; j < DIM; j++)
1043 fr->mu_tot[i][j] = mu[i*DIM + j];
1047 if (fr->efep == efepNO)
1049 copy_rvec(fr->mu_tot[0], mu_tot);
1053 for (j = 0; j < DIM; j++)
1056 (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] +
1057 lambda[efptCOUL]*fr->mu_tot[1][j];
1061 /* Reset energies */
1062 reset_enerdata(enerd);
1063 clear_rvecs(SHIFTS, fr->fshift);
1065 if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1067 wallcycle_start(wcycle, ewcPPDURINGPME);
1068 dd_force_flop_start(cr->dd, nrnb);
1073 wallcycle_start(wcycle, ewcROT);
1074 do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, bNS);
1075 wallcycle_stop(wcycle, ewcROT);
1078 /* Temporary solution until all routines take PaddedRVecVector */
1079 rvec *const f = as_rvec_array(force.unpaddedArrayRef().data());
1081 /* Start the force cycle counter.
1082 * Note that a different counter is used for dynamic load balancing.
1084 wallcycle_start(wcycle, ewcFORCE);
1086 gmx::ArrayRef<gmx::RVec> forceRef = force.unpaddedArrayRef();
1089 /* If we need to compute the virial, we might need a separate
1090 * force buffer for algorithms for which the virial is calculated
1091 * directly, such as PME.
1093 if ((flags & GMX_FORCE_VIRIAL) && fr->haveDirectVirialContributions)
1095 forceRef = *fr->forceBufferForDirectVirialContributions;
1097 /* TODO: update comment
1098 * We only compute forces on local atoms. Note that vsites can
1099 * spread to non-local atoms, but that part of the buffer is
1100 * cleared separately in the vsite spreading code.
1102 clear_rvecs_omp(forceRef.size(), as_rvec_array(forceRef.data()));
1104 /* Clear the short- and long-range forces */
1105 clear_rvecs_omp(fr->natoms_force_constr, f);
1108 /* forceWithVirial uses the local atom range only */
1109 gmx::ForceWithVirial forceWithVirial(forceRef, (flags & GMX_FORCE_VIRIAL) != 0);
1111 if (inputrec->bPull && pull_have_constraint(inputrec->pull_work))
1113 clear_pull_forces(inputrec->pull_work);
1116 /* We calculate the non-bonded forces, when done on the CPU, here.
1117 * We do this before calling do_force_lowlevel, because in that
1118 * function, the listed forces are calculated before PME, which
1119 * does communication. With this order, non-bonded and listed
1120 * force calculation imbalance can be balanced out by the domain
1121 * decomposition load balancing.
1126 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local, enbvClearFYes,
1127 step, nrnb, wcycle);
1130 if (fr->efep != efepNO)
1132 /* Calculate the local and non-local free energy interactions here.
1133 * Happens here on the CPU both with and without GPU.
1135 wallcycle_sub_start(wcycle, ewcsNONBONDED);
1136 nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::Local,
1137 fr, as_rvec_array(x.unpaddedArrayRef().data()), f, *mdatoms,
1138 inputrec->fepvals, lambda,
1139 enerd, flags, nrnb);
1141 if (havePPDomainDecomposition(cr))
1143 nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::NonLocal,
1144 fr, as_rvec_array(x.unpaddedArrayRef().data()), f, *mdatoms,
1145 inputrec->fepvals, lambda,
1146 enerd, flags, nrnb);
1148 wallcycle_sub_stop(wcycle, ewcsNONBONDED);
1153 if (havePPDomainDecomposition(cr))
1155 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1156 step, nrnb, wcycle);
1159 /* Add all the non-bonded force to the normal force array.
1160 * This can be split into a local and a non-local part when overlapping
1161 * communication with calculation with domain decomposition.
1163 wallcycle_stop(wcycle, ewcFORCE);
1165 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::All, f, wcycle);
1167 wallcycle_start_nocount(wcycle, ewcFORCE);
1169 /* If there are multiple fshift output buffers we need to reduce them */
1170 if (flags & GMX_FORCE_VIRIAL)
1172 /* This is not in a subcounter because it takes a
1173 negligible and constant-sized amount of time */
1174 nbnxn_atomdata_add_nbat_fshift_to_fshift(nbv->nbat.get(),
1179 /* update QMMMrec, if necessary */
1182 update_QMMMrec(cr, fr, as_rvec_array(x.unpaddedArrayRef().data()), mdatoms, box);
1185 /* Compute the bonded and non-bonded energies and optionally forces */
1186 do_force_lowlevel(fr, inputrec, &(top->idef),
1187 cr, ms, nrnb, wcycle, mdatoms,
1188 as_rvec_array(x.unpaddedArrayRef().data()), hist, f, &forceWithVirial, enerd, fcd,
1189 box, inputrec->fepvals, lambda, graph, &(top->excls), fr->mu_tot,
1191 &cycles_pme, ddBalanceRegionHandler);
1193 wallcycle_stop(wcycle, ewcFORCE);
1195 computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation,
1197 fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda,
1198 flags, &forceWithVirial, enerd,
1203 /* wait for non-local forces (or calculate in emulation mode) */
1204 if (havePPDomainDecomposition(cr))
1208 wallcycle_start(wcycle, ewcWAIT_GPU_NB_NL);
1209 Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1210 flags, Nbnxm::AtomLocality::NonLocal,
1211 ppForceWorkload->haveGpuBondedWork,
1212 enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
1214 cycles_wait_gpu += wallcycle_stop(wcycle, ewcWAIT_GPU_NB_NL);
1218 wallcycle_start_nocount(wcycle, ewcFORCE);
1219 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFYes,
1220 step, nrnb, wcycle);
1221 wallcycle_stop(wcycle, ewcFORCE);
1224 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::NonLocal,
1229 if (havePPDomainDecomposition(cr))
1231 /* We are done with the CPU compute.
1232 * We will now communicate the non-local forces.
1233 * If we use a GPU this will overlap with GPU work, so in that case
1234 * we do not close the DD force balancing region here.
1236 ddBalanceRegionHandler.closeAfterForceComputationCpu();
1240 dd_move_f(cr->dd, force.unpaddedArrayRef(), fr->fshift, wcycle);
1244 // With both nonbonded and PME offloaded a GPU on the same rank, we use
1245 // an alternating wait/reduction scheme.
1246 bool alternateGpuWait = (!c_disableAlternatingWait && useGpuPme && bUseGPU && !DOMAINDECOMP(cr));
1247 if (alternateGpuWait)
1249 alternatePmeNbGpuWaitReduce(fr->nbv.get(), fr->pmedata, &force, &forceWithVirial, fr->fshift, enerd,
1250 flags, pmeFlags, ppForceWorkload->haveGpuBondedWork, wcycle);
1253 if (!alternateGpuWait && useGpuPme)
1255 pme_gpu_wait_and_reduce(fr->pmedata, pmeFlags, wcycle, &forceWithVirial, enerd);
1258 /* Wait for local GPU NB outputs on the non-alternating wait path */
1259 if (!alternateGpuWait && bUseGPU)
1261 /* Measured overhead on CUDA and OpenCL with(out) GPU sharing
1262 * is between 0.5 and 1.5 Mcycles. So 2 MCycles is an overestimate,
1263 * but even with a step of 0.1 ms the difference is less than 1%
1266 const float gpuWaitApiOverheadMargin = 2e6f; /* cycles */
1268 wallcycle_start(wcycle, ewcWAIT_GPU_NB_L);
1269 Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1270 flags, Nbnxm::AtomLocality::Local, ppForceWorkload->haveGpuBondedWork,
1271 enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
1273 float cycles_tmp = wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
1275 if (ddBalanceRegionHandler.useBalancingRegion())
1277 DdBalanceRegionWaitedForGpu waitedForGpu = DdBalanceRegionWaitedForGpu::yes;
1278 if (bDoForces && cycles_tmp <= gpuWaitApiOverheadMargin)
1280 /* We measured few cycles, it could be that the kernel
1281 * and transfer finished earlier and there was no actual
1282 * wait time, only API call overhead.
1283 * Then the actual time could be anywhere between 0 and
1284 * cycles_wait_est. We will use half of cycles_wait_est.
1286 waitedForGpu = DdBalanceRegionWaitedForGpu::no;
1288 ddBalanceRegionHandler.closeAfterForceComputationGpu(cycles_wait_gpu, waitedForGpu);
1292 if (fr->nbv->emulateGpu())
1294 // NOTE: emulation kernel is not included in the balancing region,
1295 // but emulation mode does not target performance anyway
1296 wallcycle_start_nocount(wcycle, ewcFORCE);
1297 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local,
1298 DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes,
1299 step, nrnb, wcycle);
1300 wallcycle_stop(wcycle, ewcFORCE);
1305 pme_gpu_reinit_computation(fr->pmedata, wcycle);
1310 /* now clear the GPU outputs while we finish the step on the CPU */
1311 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1312 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1313 Nbnxm::gpu_clear_outputs(nbv->gpu_nbv, flags);
1315 if (nbv->pairlistSets().isDynamicPruningStepGpu(step))
1317 nbv->dispatchPruneKernelGpu(step);
1319 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1320 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1323 if (ppForceWorkload->haveGpuBondedWork && (flags & GMX_FORCE_ENERGY))
1325 wallcycle_start(wcycle, ewcWAIT_GPU_BONDED);
1326 // in principle this should be included in the DD balancing region,
1327 // but generally it is infrequent so we'll omit it for the sake of
1329 fr->gpuBonded->accumulateEnergyTerms(enerd);
1330 wallcycle_stop(wcycle, ewcWAIT_GPU_BONDED);
1332 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1333 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_BONDED);
1334 fr->gpuBonded->clearEnergies();
1335 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1336 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1339 /* Do the nonbonded GPU (or emulation) force buffer reduction
1340 * on the non-alternating path. */
1341 if (bUseOrEmulGPU && !alternateGpuWait)
1343 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local,
1346 if (DOMAINDECOMP(cr))
1348 dd_force_flop_stop(cr->dd, nrnb);
1353 /* If we have NoVirSum forces, but we do not calculate the virial,
1354 * we sum fr->f_novirsum=f later.
1356 if (vsite && !(fr->haveDirectVirialContributions && !(flags & GMX_FORCE_VIRIAL)))
1358 spread_vsite_f(vsite, as_rvec_array(x.unpaddedArrayRef().data()), f, fr->fshift, FALSE, nullptr, nrnb,
1359 &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
1362 if (flags & GMX_FORCE_VIRIAL)
1364 /* Calculation of the virial must be done after vsites! */
1365 calc_virial(0, mdatoms->homenr, as_rvec_array(x.unpaddedArrayRef().data()), f,
1366 vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1370 if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME))
1372 /* In case of node-splitting, the PP nodes receive the long-range
1373 * forces, virial and energy from the PME nodes here.
1375 pme_receive_force_ener(cr, &forceWithVirial, enerd, wcycle);
1380 post_process_forces(cr, step, nrnb, wcycle,
1381 top, box, as_rvec_array(x.unpaddedArrayRef().data()), f, &forceWithVirial,
1382 vir_force, mdatoms, graph, fr, vsite,
1386 if (flags & GMX_FORCE_ENERGY)
1388 /* Sum the potential energy terms from group contributions */
1389 sum_epot(&(enerd->grpp), enerd->term);
1391 if (!EI_TPI(inputrec->eI))
1393 checkPotentialEnergyValidity(step, *enerd, *inputrec);
1398 static void do_force_cutsGROUP(FILE *fplog,
1399 const t_commrec *cr,
1400 const gmx_multisim_t *ms,
1401 const t_inputrec *inputrec,
1403 gmx_enfrot *enforcedRotation,
1406 gmx_wallcycle_t wcycle,
1407 gmx_localtop_t *top,
1408 const gmx_groups_t *groups,
1409 matrix box, gmx::ArrayRefWithPadding<gmx::RVec> x,
1411 gmx::ArrayRefWithPadding<gmx::RVec> force,
1413 const t_mdatoms *mdatoms,
1414 gmx_enerdata_t *enerd,
1419 const gmx_vsite_t *vsite,
1424 const DDBalanceRegionHandler &ddBalanceRegionHandler)
1428 gmx_bool bStateChanged, bNS, bFillGrid, bCalcCGCM;
1432 const int start = 0;
1433 const int homenr = mdatoms->homenr;
1435 clear_mat(vir_force);
1438 if (DOMAINDECOMP(cr))
1440 cg1 = cr->dd->globalAtomGroupIndices.size();
1451 bStateChanged = ((flags & GMX_FORCE_STATECHANGED) != 0);
1452 bNS = ((flags & GMX_FORCE_NS) != 0);
1453 /* Should we perform the long-range nonbonded evaluation inside the neighborsearching? */
1454 bFillGrid = (bNS && bStateChanged);
1455 bCalcCGCM = (bFillGrid && !DOMAINDECOMP(cr));
1456 bDoForces = ((flags & GMX_FORCE_FORCES) != 0);
1460 update_forcerec(fr, box);
1462 if (inputrecNeedMutot(inputrec))
1464 /* Calculate total (local) dipole moment in a temporary common array.
1465 * This makes it possible to sum them over nodes faster.
1467 calc_mu(start, homenr,
1468 x.unpaddedArrayRef(), mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
1473 if (fr->ePBC != epbcNONE)
1475 /* Compute shift vectors every step,
1476 * because of pressure coupling or box deformation!
1478 if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
1480 calc_shifts(box, fr->shift_vec);
1485 put_charge_groups_in_box(fplog, cg0, cg1, fr->ePBC, box,
1486 &(top->cgs), as_rvec_array(x.unpaddedArrayRef().data()), fr->cg_cm);
1487 inc_nrnb(nrnb, eNR_CGCM, homenr);
1488 inc_nrnb(nrnb, eNR_RESETX, cg1-cg0);
1490 else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
1492 unshift_self(graph, box, as_rvec_array(x.unpaddedArrayRef().data()));
1497 calc_cgcm(fplog, cg0, cg1, &(top->cgs), as_rvec_array(x.unpaddedArrayRef().data()), fr->cg_cm);
1498 inc_nrnb(nrnb, eNR_CGCM, homenr);
1501 if (bCalcCGCM && gmx_debug_at)
1503 pr_rvecs(debug, 0, "cgcm", fr->cg_cm, top->cgs.nr);
1507 if (!thisRankHasDuty(cr, DUTY_PME))
1509 /* Send particle coordinates to the pme nodes.
1510 * Since this is only implemented for domain decomposition
1511 * and domain decomposition does not use the graph,
1512 * we do not need to worry about shifting.
1514 gmx_pme_send_coordinates(cr, box, as_rvec_array(x.unpaddedArrayRef().data()),
1515 lambda[efptCOUL], lambda[efptVDW],
1516 (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY)) != 0,
1519 #endif /* GMX_MPI */
1521 /* Communicate coordinates and sum dipole if necessary */
1522 if (DOMAINDECOMP(cr))
1524 dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
1526 /* No GPU support, no move_x overlap, so reopen the balance region here */
1527 ddBalanceRegionHandler.reopenRegionCpu();
1530 if (inputrecNeedMutot(inputrec))
1536 gmx_sumd(2*DIM, mu, cr);
1538 ddBalanceRegionHandler.reopenRegionCpu();
1540 for (i = 0; i < 2; i++)
1542 for (j = 0; j < DIM; j++)
1544 fr->mu_tot[i][j] = mu[i*DIM + j];
1548 if (fr->efep == efepNO)
1550 copy_rvec(fr->mu_tot[0], mu_tot);
1554 for (j = 0; j < DIM; j++)
1557 (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] + lambda[efptCOUL]*fr->mu_tot[1][j];
1562 /* Reset energies */
1563 reset_enerdata(enerd);
1564 clear_rvecs(SHIFTS, fr->fshift);
1568 wallcycle_start(wcycle, ewcNS);
1570 if (graph && bStateChanged)
1572 /* Calculate intramolecular shift vectors to make molecules whole */
1573 mk_mshift(fplog, graph, fr->ePBC, box, as_rvec_array(x.unpaddedArrayRef().data()));
1576 /* Do the actual neighbour searching */
1578 groups, top, mdatoms,
1579 cr, nrnb, bFillGrid);
1581 wallcycle_stop(wcycle, ewcNS);
1584 if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1586 wallcycle_start(wcycle, ewcPPDURINGPME);
1587 dd_force_flop_start(cr->dd, nrnb);
1592 wallcycle_start(wcycle, ewcROT);
1593 do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, bNS);
1594 wallcycle_stop(wcycle, ewcROT);
1597 /* Temporary solution until all routines take PaddedRVecVector */
1598 rvec *f = as_rvec_array(force.unpaddedArrayRef().data());
1600 /* Start the force cycle counter.
1601 * Note that a different counter is used for dynamic load balancing.
1603 wallcycle_start(wcycle, ewcFORCE);
1605 gmx::ArrayRef<gmx::RVec> forceRef = force.paddedArrayRef();
1608 /* If we need to compute the virial, we might need a separate
1609 * force buffer for algorithms for which the virial is calculated
1610 * separately, such as PME.
1612 if ((flags & GMX_FORCE_VIRIAL) && fr->haveDirectVirialContributions)
1614 forceRef = *fr->forceBufferForDirectVirialContributions;
1616 clear_rvecs_omp(forceRef.size(), as_rvec_array(forceRef.data()));
1619 /* Clear the short- and long-range forces */
1620 clear_rvecs(fr->natoms_force_constr, f);
1623 /* forceWithVirial might need the full force atom range */
1624 gmx::ForceWithVirial forceWithVirial(forceRef, (flags & GMX_FORCE_VIRIAL) != 0);
1626 if (inputrec->bPull && pull_have_constraint(inputrec->pull_work))
1628 clear_pull_forces(inputrec->pull_work);
1631 /* update QMMMrec, if necessary */
1634 update_QMMMrec(cr, fr, as_rvec_array(x.unpaddedArrayRef().data()), mdatoms, box);
1637 /* Compute the bonded and non-bonded energies and optionally forces */
1638 do_force_lowlevel(fr, inputrec, &(top->idef),
1639 cr, ms, nrnb, wcycle, mdatoms,
1640 as_rvec_array(x.unpaddedArrayRef().data()), hist, f, &forceWithVirial, enerd, fcd,
1641 box, inputrec->fepvals, lambda,
1642 graph, &(top->excls), fr->mu_tot,
1644 &cycles_pme, ddBalanceRegionHandler);
1646 wallcycle_stop(wcycle, ewcFORCE);
1648 if (DOMAINDECOMP(cr))
1650 dd_force_flop_stop(cr->dd, nrnb);
1652 ddBalanceRegionHandler.closeAfterForceComputationCpu();
1655 computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation,
1657 fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda,
1658 flags, &forceWithVirial, enerd,
1663 /* Communicate the forces */
1664 if (DOMAINDECOMP(cr))
1666 dd_move_f(cr->dd, force.unpaddedArrayRef(), fr->fshift, wcycle);
1667 /* Do we need to communicate the separate force array
1668 * for terms that do not contribute to the single sum virial?
1669 * Position restraints and electric fields do not introduce
1670 * inter-cg forces, only full electrostatics methods do.
1671 * When we do not calculate the virial, fr->f_novirsum = f,
1672 * so we have already communicated these forces.
1674 if (EEL_FULL(fr->ic->eeltype) && cr->dd->n_intercg_excl &&
1675 (flags & GMX_FORCE_VIRIAL))
1677 dd_move_f(cr->dd, forceWithVirial.force_, nullptr, wcycle);
1681 /* If we have NoVirSum forces, but we do not calculate the virial,
1682 * we sum fr->f_novirsum=f later.
1684 if (vsite && !(fr->haveDirectVirialContributions && !(flags & GMX_FORCE_VIRIAL)))
1686 spread_vsite_f(vsite, as_rvec_array(x.unpaddedArrayRef().data()), f, fr->fshift, FALSE, nullptr, nrnb,
1687 &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
1690 if (flags & GMX_FORCE_VIRIAL)
1692 /* Calculation of the virial must be done after vsites! */
1693 calc_virial(0, mdatoms->homenr, as_rvec_array(x.unpaddedArrayRef().data()), f,
1694 vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1698 if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME))
1700 /* In case of node-splitting, the PP nodes receive the long-range
1701 * forces, virial and energy from the PME nodes here.
1703 pme_receive_force_ener(cr, &forceWithVirial, enerd, wcycle);
1708 post_process_forces(cr, step, nrnb, wcycle,
1709 top, box, as_rvec_array(x.unpaddedArrayRef().data()), f, &forceWithVirial,
1710 vir_force, mdatoms, graph, fr, vsite,
1714 if (flags & GMX_FORCE_ENERGY)
1716 /* Sum the potential energy terms from group contributions */
1717 sum_epot(&(enerd->grpp), enerd->term);
1719 if (!EI_TPI(inputrec->eI))
1721 checkPotentialEnergyValidity(step, *enerd, *inputrec);
1727 void do_force(FILE *fplog,
1728 const t_commrec *cr,
1729 const gmx_multisim_t *ms,
1730 const t_inputrec *inputrec,
1732 gmx_enfrot *enforcedRotation,
1735 gmx_wallcycle_t wcycle,
1736 gmx_localtop_t *top,
1737 const gmx_groups_t *groups,
1739 gmx::ArrayRefWithPadding<gmx::RVec> x, //NOLINT(performance-unnecessary-value-param)
1741 gmx::ArrayRefWithPadding<gmx::RVec> force, //NOLINT(performance-unnecessary-value-param)
1743 const t_mdatoms *mdatoms,
1744 gmx_enerdata_t *enerd,
1746 gmx::ArrayRef<real> lambda,
1749 gmx::PpForceWorkload *ppForceWorkload,
1750 const gmx_vsite_t *vsite,
1755 const DDBalanceRegionHandler &ddBalanceRegionHandler)
1757 /* modify force flag if not doing nonbonded */
1758 if (!fr->bNonbonded)
1760 flags &= ~GMX_FORCE_NONBONDED;
1763 switch (inputrec->cutoff_scheme)
1766 do_force_cutsVERLET(fplog, cr, ms, inputrec,
1767 awh, enforcedRotation, step, nrnb, wcycle,
1774 lambda.data(), graph,
1781 ddBalanceRegionHandler);
1784 do_force_cutsGROUP(fplog, cr, ms, inputrec,
1785 awh, enforcedRotation, step, nrnb, wcycle,
1792 lambda.data(), graph,
1796 ddBalanceRegionHandler);
1799 gmx_incons("Invalid cut-off scheme passed!");
1802 /* In case we don't have constraints and are using GPUs, the next balancing
1803 * region starts here.
1804 * Some "special" work at the end of do_force_cuts?, such as vsite spread,
1805 * virial calculation and COM pulling, is not thus not included in
1806 * the balance timing, which is ok as most tasks do communication.
1808 ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::no);
1812 void do_constrain_first(FILE *fplog, gmx::Constraints *constr,
1813 const t_inputrec *ir, const t_mdatoms *md,
1816 int i, m, start, end;
1818 real dt = ir->delta_t;
1822 /* We need to allocate one element extra, since we might use
1823 * (unaligned) 4-wide SIMD loads to access rvec entries.
1825 snew(savex, state->natoms + 1);
1832 fprintf(debug, "vcm: start=%d, homenr=%d, end=%d\n",
1833 start, md->homenr, end);
1835 /* Do a first constrain to reset particles... */
1836 step = ir->init_step;
1839 char buf[STEPSTRSIZE];
1840 fprintf(fplog, "\nConstraining the starting coordinates (step %s)\n",
1841 gmx_step_str(step, buf));
1845 /* constrain the current position */
1846 constr->apply(TRUE, FALSE,
1848 state->x.rvec_array(), state->x.rvec_array(), nullptr,
1850 state->lambda[efptBONDED], &dvdl_dum,
1851 nullptr, nullptr, gmx::ConstraintVariable::Positions);
1854 /* constrain the inital velocity, and save it */
1855 /* also may be useful if we need the ekin from the halfstep for velocity verlet */
1856 constr->apply(TRUE, FALSE,
1858 state->x.rvec_array(), state->v.rvec_array(), state->v.rvec_array(),
1860 state->lambda[efptBONDED], &dvdl_dum,
1861 nullptr, nullptr, gmx::ConstraintVariable::Velocities);
1863 /* constrain the inital velocities at t-dt/2 */
1864 if (EI_STATE_VELOCITY(ir->eI) && ir->eI != eiVV)
1866 auto x = makeArrayRef(state->x).subArray(start, end);
1867 auto v = makeArrayRef(state->v).subArray(start, end);
1868 for (i = start; (i < end); i++)
1870 for (m = 0; (m < DIM); m++)
1872 /* Reverse the velocity */
1874 /* Store the position at t-dt in buf */
1875 savex[i][m] = x[i][m] + dt*v[i][m];
1878 /* Shake the positions at t=-dt with the positions at t=0
1879 * as reference coordinates.
1883 char buf[STEPSTRSIZE];
1884 fprintf(fplog, "\nConstraining the coordinates at t0-dt (step %s)\n",
1885 gmx_step_str(step, buf));
1888 constr->apply(TRUE, FALSE,
1890 state->x.rvec_array(), savex, nullptr,
1892 state->lambda[efptBONDED], &dvdl_dum,
1893 state->v.rvec_array(), nullptr, gmx::ConstraintVariable::Positions);
1895 for (i = start; i < end; i++)
1897 for (m = 0; m < DIM; m++)
1899 /* Re-reverse the velocities */
1907 void put_atoms_in_box_omp(int ePBC, const matrix box, gmx::ArrayRef<gmx::RVec> x)
1910 nth = gmx_omp_nthreads_get(emntDefault);
1912 #pragma omp parallel for num_threads(nth) schedule(static)
1913 for (t = 0; t < nth; t++)
1917 size_t natoms = x.size();
1918 size_t offset = (natoms*t )/nth;
1919 size_t len = (natoms*(t + 1))/nth - offset;
1920 put_atoms_in_box(ePBC, box, x.subArray(offset, len));
1922 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
1926 void initialize_lambdas(FILE *fplog,
1927 const t_inputrec &ir,
1930 gmx::ArrayRef<real> lambda,
1933 /* TODO: Clean up initialization of fep_state and lambda in
1934 t_state. This function works, but could probably use a logic
1935 rewrite to keep all the different types of efep straight. */
1937 if ((ir.efep == efepNO) && (!ir.bSimTemp))
1942 const t_lambda *fep = ir.fepvals;
1945 *fep_state = fep->init_fep_state; /* this might overwrite the checkpoint
1946 if checkpoint is set -- a kludge is in for now
1950 for (int i = 0; i < efptNR; i++)
1953 /* overwrite lambda state with init_lambda for now for backwards compatibility */
1954 if (fep->init_lambda >= 0) /* if it's -1, it was never initialized */
1956 thisLambda = fep->init_lambda;
1960 thisLambda = fep->all_lambda[i][fep->init_fep_state];
1964 lambda[i] = thisLambda;
1966 if (lam0 != nullptr)
1968 lam0[i] = thisLambda;
1973 /* need to rescale control temperatures to match current state */
1974 for (int i = 0; i < ir.opts.ngtc; i++)
1976 if (ir.opts.ref_t[i] > 0)
1978 ir.opts.ref_t[i] = ir.simtempvals->temperatures[fep->init_fep_state];
1983 /* Send to the log the information on the current lambdas */
1984 if (fplog != nullptr)
1986 fprintf(fplog, "Initial vector of lambda components:[ ");
1987 for (const auto &l : lambda)
1989 fprintf(fplog, "%10.4f ", l);
1991 fprintf(fplog, "]\n");