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/gpuhaloexchange.h"
53 #include "gromacs/domdec/partition.h"
54 #include "gromacs/essentialdynamics/edsam.h"
55 #include "gromacs/ewald/pme.h"
56 #include "gromacs/gmxlib/network.h"
57 #include "gromacs/gmxlib/nonbonded/nb_free_energy.h"
58 #include "gromacs/gmxlib/nonbonded/nb_kernel.h"
59 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
60 #include "gromacs/gpu_utils/gpu_utils.h"
61 #include "gromacs/imd/imd.h"
62 #include "gromacs/listed_forces/disre.h"
63 #include "gromacs/listed_forces/gpubonded.h"
64 #include "gromacs/listed_forces/listed_forces.h"
65 #include "gromacs/listed_forces/manage_threading.h"
66 #include "gromacs/listed_forces/orires.h"
67 #include "gromacs/math/arrayrefwithpadding.h"
68 #include "gromacs/math/functions.h"
69 #include "gromacs/math/units.h"
70 #include "gromacs/math/vec.h"
71 #include "gromacs/math/vecdump.h"
72 #include "gromacs/mdlib/calcmu.h"
73 #include "gromacs/mdlib/calcvir.h"
74 #include "gromacs/mdlib/constr.h"
75 #include "gromacs/mdlib/enerdata_utils.h"
76 #include "gromacs/mdlib/force.h"
77 #include "gromacs/mdlib/forcerec.h"
78 #include "gromacs/mdlib/gmx_omp_nthreads.h"
79 #include "gromacs/mdlib/qmmm.h"
80 #include "gromacs/mdlib/update.h"
81 #include "gromacs/mdtypes/commrec.h"
82 #include "gromacs/mdtypes/enerdata.h"
83 #include "gromacs/mdtypes/forceoutput.h"
84 #include "gromacs/mdtypes/iforceprovider.h"
85 #include "gromacs/mdtypes/inputrec.h"
86 #include "gromacs/mdtypes/md_enums.h"
87 #include "gromacs/mdtypes/simulation_workload.h"
88 #include "gromacs/mdtypes/state.h"
89 #include "gromacs/nbnxm/atomdata.h"
90 #include "gromacs/nbnxm/gpu_data_mgmt.h"
91 #include "gromacs/nbnxm/nbnxm.h"
92 #include "gromacs/pbcutil/ishift.h"
93 #include "gromacs/pbcutil/mshift.h"
94 #include "gromacs/pbcutil/pbc.h"
95 #include "gromacs/pulling/pull.h"
96 #include "gromacs/pulling/pull_rotation.h"
97 #include "gromacs/timing/cyclecounter.h"
98 #include "gromacs/timing/gpu_timing.h"
99 #include "gromacs/timing/wallcycle.h"
100 #include "gromacs/timing/wallcyclereporting.h"
101 #include "gromacs/timing/walltime_accounting.h"
102 #include "gromacs/topology/topology.h"
103 #include "gromacs/utility/arrayref.h"
104 #include "gromacs/utility/basedefinitions.h"
105 #include "gromacs/utility/cstringutil.h"
106 #include "gromacs/utility/exceptions.h"
107 #include "gromacs/utility/fatalerror.h"
108 #include "gromacs/utility/gmxassert.h"
109 #include "gromacs/utility/gmxmpi.h"
110 #include "gromacs/utility/logger.h"
111 #include "gromacs/utility/smalloc.h"
112 #include "gromacs/utility/strconvert.h"
113 #include "gromacs/utility/sysinfo.h"
115 using gmx::ForceOutputs;
116 using gmx::StepWorkload;
117 using gmx::DomainLifetimeWorkload;
119 // TODO: this environment variable allows us to verify before release
120 // that on less common architectures the total cost of polling is not larger than
121 // a blocking wait (so polling does not introduce overhead when the static
122 // PME-first ordering would suffice).
123 static const bool c_disableAlternatingWait = (getenv("GMX_DISABLE_ALTERNATING_GPU_WAIT") != nullptr);
125 // environment variable to enable GPU buffer ops, to allow incremental and optional
126 // introduction of this functionality.
127 // TODO eventially tie this in with other existing GPU flags.
128 static const bool c_enableGpuBufOps = (getenv("GMX_USE_GPU_BUFFER_OPS") != nullptr);
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[],
143 const gmx::ForceWithShiftForces &forceWithShiftForces,
144 tensor vir_part, const t_graph *graph, const matrix box,
145 t_nrnb *nrnb, const t_forcerec *fr, int ePBC)
147 /* The short-range virial from surrounding boxes */
148 const rvec *fshift = as_rvec_array(forceWithShiftForces.shiftForces().data());
149 calc_vir(SHIFTS, fr->shift_vec, fshift, vir_part, ePBC == epbcSCREW, box);
150 inc_nrnb(nrnb, eNR_VIRIAL, SHIFTS);
152 /* Calculate partial virial, for local atoms only, based on short range.
153 * Total virial is computed in global_stat, called from do_md
155 const rvec *f = as_rvec_array(forceWithShiftForces.force().data());
156 f_calc_vir(start, start+homenr, x, f, vir_part, graph, box);
157 inc_nrnb(nrnb, eNR_VIRIAL, homenr);
161 pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
165 static void pull_potential_wrapper(const t_commrec *cr,
166 const t_inputrec *ir,
167 const matrix box, gmx::ArrayRef<const gmx::RVec> x,
168 gmx::ForceWithVirial *force,
169 const t_mdatoms *mdatoms,
170 gmx_enerdata_t *enerd,
174 gmx_wallcycle_t wcycle)
179 /* Calculate the center of mass forces, this requires communication,
180 * which is why pull_potential is called close to other communication.
182 wallcycle_start(wcycle, ewcPULLPOT);
183 set_pbc(&pbc, ir->ePBC, box);
185 enerd->term[F_COM_PULL] +=
186 pull_potential(pull_work, mdatoms, &pbc,
187 cr, t, lambda[efptRESTRAINT], as_rvec_array(x.data()), force, &dvdl);
188 enerd->dvdl_lin[efptRESTRAINT] += dvdl;
189 wallcycle_stop(wcycle, ewcPULLPOT);
192 static void pme_receive_force_ener(const t_commrec *cr,
193 gmx::ForceWithVirial *forceWithVirial,
194 gmx_enerdata_t *enerd,
195 gmx_wallcycle_t wcycle)
197 real e_q, e_lj, dvdl_q, dvdl_lj;
198 float cycles_ppdpme, cycles_seppme;
200 cycles_ppdpme = wallcycle_stop(wcycle, ewcPPDURINGPME);
201 dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
203 /* In case of node-splitting, the PP nodes receive the long-range
204 * forces, virial and energy from the PME nodes here.
206 wallcycle_start(wcycle, ewcPP_PMEWAITRECVF);
209 gmx_pme_receive_f(cr, forceWithVirial, &e_q, &e_lj, &dvdl_q, &dvdl_lj,
211 enerd->term[F_COUL_RECIP] += e_q;
212 enerd->term[F_LJ_RECIP] += e_lj;
213 enerd->dvdl_lin[efptCOUL] += dvdl_q;
214 enerd->dvdl_lin[efptVDW] += dvdl_lj;
218 dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
220 wallcycle_stop(wcycle, ewcPP_PMEWAITRECVF);
223 static void print_large_forces(FILE *fp,
231 real force2Tolerance = gmx::square(forceTolerance);
232 gmx::index numNonFinite = 0;
233 for (int i = 0; i < md->homenr; i++)
235 real force2 = norm2(f[i]);
236 bool nonFinite = !std::isfinite(force2);
237 if (force2 >= force2Tolerance || nonFinite)
239 fprintf(fp, "step %" PRId64 " atom %6d x %8.3f %8.3f %8.3f force %12.5e\n",
241 ddglatnr(cr->dd, i), x[i][XX], x[i][YY], x[i][ZZ], std::sqrt(force2));
248 if (numNonFinite > 0)
250 /* Note that with MPI this fatal call on one rank might interrupt
251 * the printing on other ranks. But we can only avoid that with
252 * an expensive MPI barrier that we would need at each step.
254 gmx_fatal(FARGS, "At step %" PRId64 " detected non-finite forces on %td atoms", step, numNonFinite);
258 static void post_process_forces(const t_commrec *cr,
261 gmx_wallcycle_t wcycle,
262 const gmx_localtop_t *top,
265 ForceOutputs *forceOutputs,
267 const t_mdatoms *mdatoms,
268 const t_graph *graph,
269 const t_forcerec *fr,
270 const gmx_vsite_t *vsite,
271 const StepWorkload &stepWork)
273 rvec *f = as_rvec_array(forceOutputs->forceWithShiftForces().force().data());
275 if (fr->haveDirectVirialContributions)
277 auto &forceWithVirial = forceOutputs->forceWithVirial();
278 rvec *fDirectVir = as_rvec_array(forceWithVirial.force_.data());
282 /* Spread the mesh force on virtual sites to the other particles...
283 * This is parallellized. MPI communication is performed
284 * if the constructing atoms aren't local.
286 matrix virial = { { 0 } };
287 spread_vsite_f(vsite, x, fDirectVir, nullptr,
288 stepWork.computeVirial, virial,
290 &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
291 forceWithVirial.addVirialContribution(virial);
294 if (stepWork.computeVirial)
296 /* Now add the forces, this is local */
297 sum_forces(f, forceWithVirial.force_);
299 /* Add the direct virial contributions */
300 GMX_ASSERT(forceWithVirial.computeVirial_, "forceWithVirial should request virial computation when we request the virial");
301 m_add(vir_force, forceWithVirial.getVirial(), vir_force);
305 pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
310 if (fr->print_force >= 0)
312 print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
316 static void do_nb_verlet(t_forcerec *fr,
317 const interaction_const_t *ic,
318 gmx_enerdata_t *enerd,
319 const StepWorkload &stepWork,
320 const Nbnxm::InteractionLocality ilocality,
324 gmx_wallcycle_t wcycle)
326 if (!stepWork.computeNonbondedForces)
328 /* skip non-bonded calculation */
332 nonbonded_verlet_t *nbv = fr->nbv.get();
334 /* GPU kernel launch overhead is already timed separately */
335 if (fr->cutoff_scheme != ecutsVERLET)
337 gmx_incons("Invalid cut-off scheme passed!");
342 /* When dynamic pair-list pruning is requested, we need to prune
343 * at nstlistPrune steps.
345 if (nbv->isDynamicPruningStepCpu(step))
347 /* Prune the pair-list beyond fr->ic->rlistPrune using
348 * the current coordinates of the atoms.
350 wallcycle_sub_start(wcycle, ewcsNONBONDED_PRUNING);
351 nbv->dispatchPruneKernelCpu(ilocality, fr->shift_vec);
352 wallcycle_sub_stop(wcycle, ewcsNONBONDED_PRUNING);
356 nbv->dispatchNonbondedKernel(ilocality, *ic, stepWork, clearF, *fr, enerd, nrnb);
359 static inline void clear_rvecs_omp(int n, rvec v[])
361 int nth = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, n);
363 /* Note that we would like to avoid this conditional by putting it
364 * into the omp pragma instead, but then we still take the full
365 * omp parallel for overhead (at least with gcc5).
369 for (int i = 0; i < n; i++)
376 #pragma omp parallel for num_threads(nth) schedule(static)
377 for (int i = 0; i < n; i++)
384 /*! \brief Return an estimate of the average kinetic energy or 0 when unreliable
386 * \param groupOptions Group options, containing T-coupling options
388 static real averageKineticEnergyEstimate(const t_grpopts &groupOptions)
390 real nrdfCoupled = 0;
391 real nrdfUncoupled = 0;
392 real kineticEnergy = 0;
393 for (int g = 0; g < groupOptions.ngtc; g++)
395 if (groupOptions.tau_t[g] >= 0)
397 nrdfCoupled += groupOptions.nrdf[g];
398 kineticEnergy += groupOptions.nrdf[g]*0.5*groupOptions.ref_t[g]*BOLTZ;
402 nrdfUncoupled += groupOptions.nrdf[g];
406 /* This conditional with > also catches nrdf=0 */
407 if (nrdfCoupled > nrdfUncoupled)
409 return kineticEnergy*(nrdfCoupled + nrdfUncoupled)/nrdfCoupled;
417 /*! \brief This routine checks that the potential energy is finite.
419 * Always checks that the potential energy is finite. If step equals
420 * inputrec.init_step also checks that the magnitude of the potential energy
421 * is reasonable. Terminates with a fatal error when a check fails.
422 * Note that passing this check does not guarantee finite forces,
423 * since those use slightly different arithmetics. But in most cases
424 * there is just a narrow coordinate range where forces are not finite
425 * and energies are finite.
427 * \param[in] step The step number, used for checking and printing
428 * \param[in] enerd The energy data; the non-bonded group energies need to be added to enerd.term[F_EPOT] before calling this routine
429 * \param[in] inputrec The input record
431 static void checkPotentialEnergyValidity(int64_t step,
432 const gmx_enerdata_t &enerd,
433 const t_inputrec &inputrec)
435 /* Threshold valid for comparing absolute potential energy against
436 * the kinetic energy. Normally one should not consider absolute
437 * potential energy values, but with a factor of one million
438 * we should never get false positives.
440 constexpr real c_thresholdFactor = 1e6;
442 bool energyIsNotFinite = !std::isfinite(enerd.term[F_EPOT]);
443 real averageKineticEnergy = 0;
444 /* We only check for large potential energy at the initial step,
445 * because that is by far the most likely step for this too occur
446 * and because computing the average kinetic energy is not free.
447 * Note: nstcalcenergy >> 1 often does not allow to catch large energies
448 * before they become NaN.
450 if (step == inputrec.init_step && EI_DYNAMICS(inputrec.eI))
452 averageKineticEnergy = averageKineticEnergyEstimate(inputrec.opts);
455 if (energyIsNotFinite || (averageKineticEnergy > 0 &&
456 enerd.term[F_EPOT] > c_thresholdFactor*averageKineticEnergy))
458 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.",
461 energyIsNotFinite ? "not finite" : "extremely high",
463 enerd.term[F_COUL_SR],
464 energyIsNotFinite ? "non-finite" : "very high",
465 energyIsNotFinite ? " or Nan" : "");
469 /*! \brief Return true if there are special forces computed this step.
471 * The conditionals exactly correspond to those in computeSpecialForces().
474 haveSpecialForces(const t_inputrec &inputrec,
475 const gmx::ForceProviders &forceProviders,
476 const pull_t *pull_work,
477 const bool computeForces,
482 ((computeForces && forceProviders.hasForceProvider()) || // forceProviders
483 (inputrec.bPull && pull_have_potential(pull_work)) || // pull
484 inputrec.bRot || // enforced rotation
485 (ed != nullptr) || // flooding
486 (inputrec.bIMD && computeForces)); // IMD
489 /*! \brief Compute forces and/or energies for special algorithms
491 * The intention is to collect all calls to algorithms that compute
492 * forces on local atoms only and that do not contribute to the local
493 * virial sum (but add their virial contribution separately).
494 * Eventually these should likely all become ForceProviders.
495 * Within this function the intention is to have algorithms that do
496 * global communication at the end, so global barriers within the MD loop
497 * are as close together as possible.
499 * \param[in] fplog The log file
500 * \param[in] cr The communication record
501 * \param[in] inputrec The input record
502 * \param[in] awh The Awh module (nullptr if none in use).
503 * \param[in] enforcedRotation Enforced rotation module.
504 * \param[in] imdSession The IMD session
505 * \param[in] pull_work The pull work structure.
506 * \param[in] step The current MD step
507 * \param[in] t The current time
508 * \param[in,out] wcycle Wallcycle accounting struct
509 * \param[in,out] forceProviders Pointer to a list of force providers
510 * \param[in] box The unit cell
511 * \param[in] x The coordinates
512 * \param[in] mdatoms Per atom properties
513 * \param[in] lambda Array of free-energy lambda values
514 * \param[in] stepWork Step schedule flags
515 * \param[in,out] forceWithVirial Force and virial buffers
516 * \param[in,out] enerd Energy buffer
517 * \param[in,out] ed Essential dynamics pointer
518 * \param[in] didNeighborSearch Tells if we did neighbor searching this step, used for ED sampling
520 * \todo Remove didNeighborSearch, which is used incorrectly.
521 * \todo Convert all other algorithms called here to ForceProviders.
524 computeSpecialForces(FILE *fplog,
526 const t_inputrec *inputrec,
528 gmx_enfrot *enforcedRotation,
529 gmx::ImdSession *imdSession,
533 gmx_wallcycle_t wcycle,
534 gmx::ForceProviders *forceProviders,
536 gmx::ArrayRef<const gmx::RVec> x,
537 const t_mdatoms *mdatoms,
539 const StepWorkload &stepWork,
540 gmx::ForceWithVirial *forceWithVirial,
541 gmx_enerdata_t *enerd,
543 bool didNeighborSearch)
545 /* NOTE: Currently all ForceProviders only provide forces.
546 * When they also provide energies, remove this conditional.
548 if (stepWork.computeForces)
550 gmx::ForceProviderInput forceProviderInput(x, *mdatoms, t, box, *cr);
551 gmx::ForceProviderOutput forceProviderOutput(forceWithVirial, enerd);
553 /* Collect forces from modules */
554 forceProviders->calculateForces(forceProviderInput, &forceProviderOutput);
557 if (inputrec->bPull && pull_have_potential(pull_work))
559 pull_potential_wrapper(cr, inputrec, box, x,
561 mdatoms, enerd, pull_work, lambda, t,
566 enerd->term[F_COM_PULL] +=
567 awh->applyBiasForcesAndUpdateBias(inputrec->ePBC, *mdatoms, box,
569 t, step, wcycle, fplog);
573 rvec *f = as_rvec_array(forceWithVirial->force_.data());
575 /* Add the forces from enforced rotation potentials (if any) */
578 wallcycle_start(wcycle, ewcROTadd);
579 enerd->term[F_COM_PULL] += add_rot_forces(enforcedRotation, f, cr, step, t);
580 wallcycle_stop(wcycle, ewcROTadd);
585 /* Note that since init_edsam() is called after the initialization
586 * of forcerec, edsam doesn't request the noVirSum force buffer.
587 * Thus if no other algorithm (e.g. PME) requires it, the forces
588 * here will contribute to the virial.
590 do_flood(cr, inputrec, as_rvec_array(x.data()), f, ed, box, step, didNeighborSearch);
593 /* Add forces from interactive molecular dynamics (IMD), if any */
594 if (inputrec->bIMD && stepWork.computeForces)
596 imdSession->applyForces(f);
600 /*! \brief Launch the prepare_step and spread stages of PME GPU.
602 * \param[in] pmedata The PME structure
603 * \param[in] box The box matrix
604 * \param[in] x Coordinate array
605 * \param[in] stepWork Step schedule flags
606 * \param[in] pmeFlags PME flags
607 * \param[in] useGpuForceReduction True if GPU-based force reduction is active this step
608 * \param[in] wcycle The wallcycle structure
610 static inline void launchPmeGpuSpread(gmx_pme_t *pmedata,
613 const StepWorkload &stepWork,
615 bool useGpuForceReduction,
616 gmx_wallcycle_t wcycle)
618 pme_gpu_prepare_computation(pmedata, stepWork.haveDynamicBox, box, wcycle, pmeFlags, useGpuForceReduction);
619 pme_gpu_copy_coordinates_to_gpu(pmedata, x, wcycle);
620 pme_gpu_launch_spread(pmedata, wcycle);
623 /*! \brief Launch the FFT and gather stages of PME GPU
625 * This function only implements setting the output forces (no accumulation).
627 * \param[in] pmedata The PME structure
628 * \param[in] wcycle The wallcycle structure
630 static void launchPmeGpuFftAndGather(gmx_pme_t *pmedata,
631 gmx_wallcycle_t wcycle)
633 pme_gpu_launch_complex_transforms(pmedata, wcycle);
634 pme_gpu_launch_gather(pmedata, wcycle, PmeForceOutputHandling::Set);
638 * Polling wait for either of the PME or nonbonded GPU tasks.
640 * Instead of a static order in waiting for GPU tasks, this function
641 * polls checking which of the two tasks completes first, and does the
642 * associated force buffer reduction overlapped with the other task.
643 * By doing that, unlike static scheduling order, it can always overlap
644 * one of the reductions, regardless of the GPU task completion order.
646 * \param[in] nbv Nonbonded verlet structure
647 * \param[in,out] pmedata PME module data
648 * \param[in,out] forceOutputs Output buffer for the forces and virial
649 * \param[in,out] enerd Energy data structure results are reduced into
650 * \param[in] stepWork Step schedule flags
651 * \param[in] pmeFlags PME flags
652 * \param[in] wcycle The wallcycle structure
654 static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t *nbv,
656 gmx::ForceOutputs *forceOutputs,
657 gmx_enerdata_t *enerd,
658 const StepWorkload &stepWork,
660 gmx_wallcycle_t wcycle)
662 bool isPmeGpuDone = false;
663 bool isNbGpuDone = false;
667 gmx::ForceWithShiftForces &forceWithShiftForces = forceOutputs->forceWithShiftForces();
668 gmx::ForceWithVirial &forceWithVirial = forceOutputs->forceWithVirial();
670 gmx::ArrayRef<const gmx::RVec> pmeGpuForces;
672 while (!isPmeGpuDone || !isNbGpuDone)
676 GpuTaskCompletion completionType = (isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
677 isPmeGpuDone = pme_gpu_try_finish_task(pmedata, pmeFlags, wcycle, &forceWithVirial, enerd, completionType);
682 GpuTaskCompletion completionType = (isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
683 isNbGpuDone = Nbnxm::gpu_try_finish_task(nbv->gpu_nbv,
685 Nbnxm::AtomLocality::Local,
686 enerd->grpp.ener[egLJSR].data(),
687 enerd->grpp.ener[egCOULSR].data(),
688 forceWithShiftForces.shiftForces(), completionType, wcycle);
692 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local,
693 forceWithShiftForces.force());
699 /*! \brief Set up the different force buffers; also does clearing.
701 * \param[in] fr force record pointer
702 * \param[in] pull_work The pull work object.
703 * \param[in] inputrec input record
704 * \param[in] force force array
705 * \param[in] stepWork Step schedule flags
706 * \param[out] wcycle wallcycle recording structure
708 * \returns Cleared force output structure
711 setupForceOutputs(t_forcerec *fr,
713 const t_inputrec &inputrec,
714 gmx::ArrayRefWithPadding<gmx::RVec> force,
715 const StepWorkload &stepWork,
716 gmx_wallcycle_t wcycle)
718 wallcycle_sub_start(wcycle, ewcsCLEAR_FORCE_BUFFER);
720 /* NOTE: We assume fr->shiftForces is all zeros here */
721 gmx::ForceWithShiftForces forceWithShiftForces(force, stepWork.computeVirial, fr->shiftForces);
723 if (stepWork.computeForces)
725 /* Clear the short- and long-range forces */
726 clear_rvecs_omp(fr->natoms_force_constr,
727 as_rvec_array(forceWithShiftForces.force().data()));
730 /* If we need to compute the virial, we might need a separate
731 * force buffer for algorithms for which the virial is calculated
732 * directly, such as PME. Otherwise, forceWithVirial uses the
733 * the same force (f in legacy calls) buffer as other algorithms.
735 const bool useSeparateForceWithVirialBuffer = (stepWork.computeForces &&
736 (stepWork.computeVirial && fr->haveDirectVirialContributions));
737 /* forceWithVirial uses the local atom range only */
738 gmx::ForceWithVirial forceWithVirial(useSeparateForceWithVirialBuffer ?
739 fr->forceBufferForDirectVirialContributions : force.unpaddedArrayRef(),
740 stepWork.computeVirial);
742 if (useSeparateForceWithVirialBuffer)
744 /* TODO: update comment
745 * We only compute forces on local atoms. Note that vsites can
746 * spread to non-local atoms, but that part of the buffer is
747 * cleared separately in the vsite spreading code.
749 clear_rvecs_omp(forceWithVirial.force_.size(), as_rvec_array(forceWithVirial.force_.data()));
752 if (inputrec.bPull && pull_have_constraint(pull_work))
754 clear_pull_forces(pull_work);
757 wallcycle_sub_stop(wcycle, ewcsCLEAR_FORCE_BUFFER);
759 return ForceOutputs(forceWithShiftForces, forceWithVirial);
763 /*! \brief Set up flags that have the lifetime of the domain indicating what type of work is there to compute.
766 setupDomainLifetimeWorkload(DomainLifetimeWorkload *domainWork,
767 const t_inputrec &inputrec,
768 const t_forcerec &fr,
769 const pull_t *pull_work,
773 const t_mdatoms &mdatoms,
774 const StepWorkload &stepWork)
776 // Note that haveSpecialForces is constant over the whole run
777 domainWork->haveSpecialForces = haveSpecialForces(inputrec, *fr.forceProviders, pull_work, stepWork.computeForces, ed);
778 domainWork->haveCpuBondedWork = haveCpuBondeds(fr);
779 domainWork->haveGpuBondedWork = ((fr.gpuBonded != nullptr) && fr.gpuBonded->haveInteractions());
780 domainWork->haveRestraintsWork = havePositionRestraints(idef, fcd);
781 domainWork->haveCpuListedForceWork = haveCpuListedForces(fr, idef, fcd);
782 // Note that haveFreeEnergyWork is constant over the whole run
783 domainWork->haveFreeEnergyWork = (fr.efep != efepNO && mdatoms.nPerturbed != 0);
786 /*! \brief Set up force flag stuct from the force bitmask.
788 * \param[out] flags Force schedule flags
789 * \param[in] legacyFlags Force bitmask flags used to construct the new flags
790 * \param[in] isNonbondedOn Global override, if false forces to turn off all nonbonded calculation.
793 setupStepWorkload(StepWorkload *flags,
794 const int legacyFlags,
795 const bool isNonbondedOn)
797 flags->stateChanged = ((legacyFlags & GMX_FORCE_STATECHANGED) != 0);
798 flags->haveDynamicBox = ((legacyFlags & GMX_FORCE_DYNAMICBOX) != 0);
799 flags->doNeighborSearch = ((legacyFlags & GMX_FORCE_NS) != 0);
800 flags->computeVirial = ((legacyFlags & GMX_FORCE_VIRIAL) != 0);
801 flags->computeEnergy = ((legacyFlags & GMX_FORCE_ENERGY) != 0);
802 flags->computeForces = ((legacyFlags & GMX_FORCE_FORCES) != 0);
803 flags->computeListedForces = ((legacyFlags & GMX_FORCE_LISTED) != 0);
804 flags->computeNonbondedForces = ((legacyFlags & GMX_FORCE_NONBONDED) != 0) && isNonbondedOn;
805 flags->computeDhdl = ((legacyFlags & GMX_FORCE_DHDL) != 0);
809 /* \brief Launch end-of-step GPU tasks: buffer clearing and rolling pruning.
811 * TODO: eliminate the \p useGpuNonbonded and \p useGpuNonbonded when these are
812 * incorporated in DomainLifetimeWorkload.
815 launchGpuEndOfStepTasks(nonbonded_verlet_t *nbv,
816 gmx::GpuBonded *gpuBonded,
818 gmx_enerdata_t *enerd,
819 const gmx::MdrunScheduleWorkload &runScheduleWork,
820 bool useGpuNonbonded,
823 gmx_wallcycle_t wcycle)
827 /* Launch pruning before buffer clearing because the API overhead of the
828 * clear kernel launches can leave the GPU idle while it could be running
831 if (nbv->isDynamicPruningStepGpu(step))
833 nbv->dispatchPruneKernelGpu(step);
836 /* now clear the GPU outputs while we finish the step on the CPU */
837 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
838 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
839 Nbnxm::gpu_clear_outputs(nbv->gpu_nbv, runScheduleWork.stepWork.computeVirial);
840 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
841 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
846 pme_gpu_reinit_computation(pmedata, wcycle);
849 if (runScheduleWork.domainWork.haveGpuBondedWork && runScheduleWork.stepWork.computeEnergy)
851 // in principle this should be included in the DD balancing region,
852 // but generally it is infrequent so we'll omit it for the sake of
854 gpuBonded->waitAccumulateEnergyTerms(enerd);
856 gpuBonded->clearEnergies();
861 void do_force(FILE *fplog,
863 const gmx_multisim_t *ms,
864 const t_inputrec *inputrec,
866 gmx_enfrot *enforcedRotation,
867 gmx::ImdSession *imdSession,
871 gmx_wallcycle_t wcycle,
872 const gmx_localtop_t *top,
874 gmx::ArrayRefWithPadding<gmx::RVec> x,
876 gmx::ArrayRefWithPadding<gmx::RVec> force,
878 const t_mdatoms *mdatoms,
879 gmx_enerdata_t *enerd,
881 gmx::ArrayRef<real> lambda,
884 gmx::MdrunScheduleWorkload *runScheduleWork,
885 const gmx_vsite_t *vsite,
890 const DDBalanceRegionHandler &ddBalanceRegionHandler)
894 gmx_bool bFillGrid, bCalcCGCM;
895 gmx_bool bUseGPU, bUseOrEmulGPU;
896 nonbonded_verlet_t *nbv = fr->nbv.get();
897 interaction_const_t *ic = fr->ic;
899 // TODO remove the code below when the legacy flags are not in use anymore
900 /* modify force flag if not doing nonbonded */
903 legacyFlags &= ~GMX_FORCE_NONBONDED;
905 setupStepWorkload(&runScheduleWork->stepWork, legacyFlags, fr->bNonbonded);
907 const gmx::StepWorkload &stepWork = runScheduleWork->stepWork;
909 bFillGrid = (stepWork.doNeighborSearch && stepWork.stateChanged);
910 bCalcCGCM = (bFillGrid && !DOMAINDECOMP(cr));
911 bUseGPU = fr->nbv->useGpu();
912 bUseOrEmulGPU = bUseGPU || fr->nbv->emulateGpu();
914 const auto pmeRunMode = fr->pmedata ? pme_run_mode(fr->pmedata) : PmeRunMode::CPU;
915 // TODO slim this conditional down - inputrec and duty checks should mean the same in proper code!
916 const bool useGpuPme = EEL_PME(fr->ic->eeltype) && thisRankHasDuty(cr, DUTY_PME) &&
917 ((pmeRunMode == PmeRunMode::GPU) || (pmeRunMode == PmeRunMode::Mixed));
918 const int pmeFlags = GMX_PME_SPREAD | GMX_PME_SOLVE |
919 (stepWork.computeVirial ? GMX_PME_CALC_ENER_VIR : 0) |
920 (stepWork.computeEnergy ? GMX_PME_CALC_ENER_VIR : 0) |
921 (stepWork.computeForces ? GMX_PME_CALC_F : 0);
923 // Switches on whether to use GPU for position and force buffer operations
924 // TODO consider all possible combinations of triggers, and how to combine optimally in each case.
925 const BufferOpsUseGpu useGpuXBufOps = (c_enableGpuBufOps && bUseGPU && (GMX_GPU == GMX_GPU_CUDA)) ?
926 BufferOpsUseGpu::True : BufferOpsUseGpu::False;;
927 // GPU Force buffer ops are disabled on virial steps, because the virial calc is not yet ported to GPU
928 const BufferOpsUseGpu useGpuFBufOps = (c_enableGpuBufOps && bUseGPU && (GMX_GPU == GMX_GPU_CUDA))
929 && !(stepWork.computeVirial || stepWork.computeEnergy) ?
930 BufferOpsUseGpu::True : BufferOpsUseGpu::False;
931 // TODO: move / add this flag to the internal PME GPU data structures
932 const bool useGpuPmeFReduction = (useGpuFBufOps == BufferOpsUseGpu::True) &&
933 thisRankHasDuty(cr, DUTY_PME) && useGpuPme; // only supported if this rank is perfoming PME on the GPU
935 /* At a search step we need to start the first balancing region
936 * somewhere early inside the step after communication during domain
937 * decomposition (and not during the previous step as usual).
939 if (stepWork.doNeighborSearch)
941 ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::yes);
945 const int homenr = mdatoms->homenr;
947 clear_mat(vir_force);
949 if (stepWork.stateChanged)
951 if (inputrecNeedMutot(inputrec))
953 /* Calculate total (local) dipole moment in a temporary common array.
954 * This makes it possible to sum them over nodes faster.
956 calc_mu(start, homenr,
957 x.unpaddedArrayRef(), mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
962 if (fr->ePBC != epbcNONE)
964 /* Compute shift vectors every step,
965 * because of pressure coupling or box deformation!
967 if (stepWork.haveDynamicBox && stepWork.stateChanged)
969 calc_shifts(box, fr->shift_vec);
974 put_atoms_in_box_omp(fr->ePBC, box, x.unpaddedArrayRef().subArray(0, homenr), gmx_omp_nthreads_get(emntDefault));
975 inc_nrnb(nrnb, eNR_SHIFTX, homenr);
977 else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
979 unshift_self(graph, box, as_rvec_array(x.unpaddedArrayRef().data()));
983 nbnxn_atomdata_copy_shiftvec(stepWork.haveDynamicBox,
984 fr->shift_vec, nbv->nbat.get());
987 if (!thisRankHasDuty(cr, DUTY_PME))
989 /* Send particle coordinates to the pme nodes.
990 * Since this is only implemented for domain decomposition
991 * and domain decomposition does not use the graph,
992 * we do not need to worry about shifting.
994 gmx_pme_send_coordinates(cr, box, as_rvec_array(x.unpaddedArrayRef().data()),
995 lambda[efptCOUL], lambda[efptVDW],
996 (stepWork.computeVirial || stepWork.computeEnergy),
1003 launchPmeGpuSpread(fr->pmedata, box, as_rvec_array(x.unpaddedArrayRef().data()), stepWork, pmeFlags, useGpuPmeFReduction, wcycle);
1006 /* do gridding for pair search */
1007 if (stepWork.doNeighborSearch)
1009 if (graph && stepWork.stateChanged)
1011 /* Calculate intramolecular shift vectors to make molecules whole */
1012 mk_mshift(fplog, graph, fr->ePBC, box, as_rvec_array(x.unpaddedArrayRef().data()));
1016 // - vzero is constant, do we need to pass it?
1017 // - box_diag should be passed directly to nbnxn_put_on_grid
1023 box_diag[XX] = box[XX][XX];
1024 box_diag[YY] = box[YY][YY];
1025 box_diag[ZZ] = box[ZZ][ZZ];
1027 wallcycle_start(wcycle, ewcNS);
1028 if (!DOMAINDECOMP(cr))
1030 wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL);
1031 nbnxn_put_on_grid(nbv, box,
1033 nullptr, 0, mdatoms->homenr, -1,
1034 fr->cginfo, x.unpaddedArrayRef(),
1036 wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL);
1040 wallcycle_sub_start(wcycle, ewcsNBS_GRID_NONLOCAL);
1041 nbnxn_put_on_grid_nonlocal(nbv, domdec_zones(cr->dd),
1042 fr->cginfo, x.unpaddedArrayRef());
1043 wallcycle_sub_stop(wcycle, ewcsNBS_GRID_NONLOCAL);
1046 nbv->setAtomProperties(*mdatoms, fr->cginfo);
1048 wallcycle_stop(wcycle, ewcNS);
1050 /* initialize the GPU nbnxm atom data and bonded data structures */
1053 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1055 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1056 Nbnxm::gpu_init_atomdata(nbv->gpu_nbv, nbv->nbat.get());
1057 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1061 /* Now we put all atoms on the grid, we can assign bonded
1062 * interactions to the GPU, where the grid order is
1063 * needed. Also the xq, f and fshift device buffers have
1064 * been reallocated if needed, so the bonded code can
1065 * learn about them. */
1066 // TODO the xq, f, and fshift buffers are now shared
1067 // resources, so they should be maintained by a
1068 // higher-level object than the nb module.
1069 fr->gpuBonded->updateInteractionListsAndDeviceBuffers(nbv->getGridIndices(),
1071 Nbnxm::gpu_get_xq(nbv->gpu_nbv),
1072 Nbnxm::gpu_get_f(nbv->gpu_nbv),
1073 Nbnxm::gpu_get_fshift(nbv->gpu_nbv));
1075 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1079 if (stepWork.doNeighborSearch)
1081 // Need to run after the GPU-offload bonded interaction lists
1082 // are set up to be able to determine whether there is bonded work.
1083 setupDomainLifetimeWorkload(&runScheduleWork->domainWork,
1094 const gmx::DomainLifetimeWorkload &domainWork = runScheduleWork->domainWork;
1096 /* do local pair search */
1097 if (stepWork.doNeighborSearch)
1099 // TODO: fuse this branch with the above stepWork.doNeighborSearch block
1100 wallcycle_start_nocount(wcycle, ewcNS);
1101 wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_LOCAL);
1102 /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1103 nbv->constructPairlist(Nbnxm::InteractionLocality::Local,
1104 &top->excls, step, nrnb);
1106 nbv->setupGpuShortRangeWork(fr->gpuBonded, Nbnxm::InteractionLocality::Local);
1108 wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_LOCAL);
1109 wallcycle_stop(wcycle, ewcNS);
1111 if (useGpuXBufOps == BufferOpsUseGpu::True)
1113 nbv->atomdata_init_copy_x_to_nbat_x_gpu();
1115 // For force buffer ops, we use the below conditon rather than
1116 // useGpuFBufOps to ensure that init is performed even if this
1117 // NS step is also a virial step (on which f buf ops are deactivated).
1118 if (c_enableGpuBufOps && bUseGPU && (GMX_GPU == GMX_GPU_CUDA))
1120 nbv->atomdata_init_add_nbat_f_to_f_gpu();
1123 else if (!EI_TPI(inputrec->eI))
1125 if (useGpuXBufOps == BufferOpsUseGpu::True)
1127 // The condition here was (pme != nullptr && pme_gpu_get_device_x(fr->pmedata) != nullptr)
1130 nbv->copyCoordinatesToGpu(Nbnxm::AtomLocality::Local, false,
1131 x.unpaddedArrayRef());
1133 nbv->convertCoordinatesGpu(Nbnxm::AtomLocality::Local, false,
1134 useGpuPme ? pme_gpu_get_device_x(fr->pmedata) : nbv->getDeviceCoordinates());
1138 nbv->convertCoordinates(Nbnxm::AtomLocality::Local, false,
1139 x.unpaddedArrayRef());
1145 ddBalanceRegionHandler.openBeforeForceComputationGpu();
1147 wallcycle_start(wcycle, ewcLAUNCH_GPU);
1149 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1150 Nbnxm::gpu_upload_shiftvec(nbv->gpu_nbv, nbv->nbat.get());
1151 if (stepWork.doNeighborSearch || (useGpuXBufOps == BufferOpsUseGpu::False))
1153 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
1154 Nbnxm::AtomLocality::Local);
1156 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1157 // with X buffer ops offloaded to the GPU on all but the search steps
1159 // bonded work not split into separate local and non-local, so with DD
1160 // we can only launch the kernel after non-local coordinates have been received.
1161 if (domainWork.haveGpuBondedWork && !havePPDomainDecomposition(cr))
1163 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1164 fr->gpuBonded->launchKernel(fr, stepWork, box);
1165 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1168 /* launch local nonbonded work on GPU */
1169 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1170 do_nb_verlet(fr, ic, enerd, stepWork, Nbnxm::InteractionLocality::Local, enbvClearFNo,
1171 step, nrnb, wcycle);
1172 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1173 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1178 // In PME GPU and mixed mode we launch FFT / gather after the
1179 // X copy/transform to allow overlap as well as after the GPU NB
1180 // launch to avoid FFT launch overhead hijacking the CPU and delaying
1181 // the nonbonded kernel.
1182 launchPmeGpuFftAndGather(fr->pmedata, wcycle);
1185 // TODO Update this comment when introducing SimulationWorkload
1187 // The conditions for gpuHaloExchange e.g. using GPU buffer
1188 // operations were checked before construction, so here we can
1189 // just use it and assert upon any conditions.
1190 gmx::GpuHaloExchange *gpuHaloExchange = (havePPDomainDecomposition(cr) ? cr->dd->gpuHaloExchange.get() : nullptr);
1191 const bool ddUsesGpuDirectCommunication = (gpuHaloExchange != nullptr);
1192 GMX_ASSERT(!ddUsesGpuDirectCommunication || (useGpuXBufOps == BufferOpsUseGpu::True),
1193 "Must use coordinate buffer ops with GPU halo exchange");
1195 /* Communicate coordinates and sum dipole if necessary +
1196 do non-local pair search */
1197 if (havePPDomainDecomposition(cr))
1199 if (stepWork.doNeighborSearch)
1201 // TODO: fuse this branch with the above large stepWork.doNeighborSearch block
1202 wallcycle_start_nocount(wcycle, ewcNS);
1203 wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1204 /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1205 nbv->constructPairlist(Nbnxm::InteractionLocality::NonLocal,
1206 &top->excls, step, nrnb);
1208 nbv->setupGpuShortRangeWork(fr->gpuBonded, Nbnxm::InteractionLocality::NonLocal);
1209 wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1210 wallcycle_stop(wcycle, ewcNS);
1211 if (ddUsesGpuDirectCommunication)
1213 rvec* d_x = static_cast<rvec *> (nbv->get_gpu_xrvec());
1214 rvec* d_f = static_cast<rvec *> (nbv->get_gpu_frvec());
1215 gpuHaloExchange->reinitHalo(d_x, d_f);
1220 if (ddUsesGpuDirectCommunication)
1222 // The following must be called after local setCoordinates (which records an event
1223 // when the coordinate data has been copied to the device).
1224 gpuHaloExchange->communicateHaloCoordinates(box);
1226 if (domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork)
1228 //non-local part of coordinate buffer must be copied back to host for CPU work
1229 nbv->launch_copy_x_from_gpu(as_rvec_array(x.unpaddedArrayRef().data()), Nbnxm::AtomLocality::NonLocal);
1234 dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
1237 if (useGpuXBufOps == BufferOpsUseGpu::True)
1239 // The condition here was (pme != nullptr && pme_gpu_get_device_x(fr->pmedata) != nullptr)
1240 if (!useGpuPme && !ddUsesGpuDirectCommunication)
1242 nbv->copyCoordinatesToGpu(Nbnxm::AtomLocality::NonLocal, false,
1243 x.unpaddedArrayRef());
1245 nbv->convertCoordinatesGpu(Nbnxm::AtomLocality::NonLocal, false,
1246 useGpuPme ? pme_gpu_get_device_x(fr->pmedata) : nbv->getDeviceCoordinates());
1250 nbv->convertCoordinates(Nbnxm::AtomLocality::NonLocal, false,
1251 x.unpaddedArrayRef());
1258 wallcycle_start(wcycle, ewcLAUNCH_GPU);
1260 if (stepWork.doNeighborSearch || (useGpuXBufOps == BufferOpsUseGpu::False))
1262 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1263 Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
1264 Nbnxm::AtomLocality::NonLocal);
1265 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1268 if (domainWork.haveGpuBondedWork)
1270 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1271 fr->gpuBonded->launchKernel(fr, stepWork, box);
1272 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1275 /* launch non-local nonbonded tasks on GPU */
1276 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1277 do_nb_verlet(fr, ic, enerd, stepWork, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1278 step, nrnb, wcycle);
1279 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1281 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1287 /* launch D2H copy-back F */
1288 wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1289 wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1291 bool copyBackNbForce = (useGpuFBufOps == BufferOpsUseGpu::False);
1293 if (havePPDomainDecomposition(cr))
1295 Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1296 stepWork, Nbnxm::AtomLocality::NonLocal, copyBackNbForce);
1298 Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1299 stepWork, Nbnxm::AtomLocality::Local, copyBackNbForce);
1300 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1302 if (domainWork.haveGpuBondedWork && stepWork.computeEnergy)
1304 fr->gpuBonded->launchEnergyTransfer();
1306 wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1309 if (stepWork.stateChanged && inputrecNeedMutot(inputrec))
1313 gmx_sumd(2*DIM, mu, cr);
1315 ddBalanceRegionHandler.reopenRegionCpu();
1318 for (i = 0; i < 2; i++)
1320 for (j = 0; j < DIM; j++)
1322 fr->mu_tot[i][j] = mu[i*DIM + j];
1326 if (mdatoms->nChargePerturbed == 0)
1328 copy_rvec(fr->mu_tot[0], mu_tot);
1332 for (j = 0; j < DIM; j++)
1335 (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] +
1336 lambda[efptCOUL]*fr->mu_tot[1][j];
1340 /* Reset energies */
1341 reset_enerdata(enerd);
1342 /* Clear the shift forces */
1343 // TODO: This should be linked to the shift force buffer in use, or cleared before use instead
1344 for (gmx::RVec &elem : fr->shiftForces)
1346 elem = { 0.0_real, 0.0_real, 0.0_real };
1349 if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1351 wallcycle_start(wcycle, ewcPPDURINGPME);
1352 dd_force_flop_start(cr->dd, nrnb);
1357 wallcycle_start(wcycle, ewcROT);
1358 do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, stepWork.doNeighborSearch);
1359 wallcycle_stop(wcycle, ewcROT);
1362 /* Start the force cycle counter.
1363 * Note that a different counter is used for dynamic load balancing.
1365 wallcycle_start(wcycle, ewcFORCE);
1367 // Set up and clear force outputs.
1368 // We use std::move to keep the compiler happy, it has no effect.
1369 ForceOutputs forceOut = setupForceOutputs(fr, pull_work, *inputrec, std::move(force), stepWork, wcycle);
1371 /* We calculate the non-bonded forces, when done on the CPU, here.
1372 * We do this before calling do_force_lowlevel, because in that
1373 * function, the listed forces are calculated before PME, which
1374 * does communication. With this order, non-bonded and listed
1375 * force calculation imbalance can be balanced out by the domain
1376 * decomposition load balancing.
1381 do_nb_verlet(fr, ic, enerd, stepWork, Nbnxm::InteractionLocality::Local, enbvClearFYes,
1382 step, nrnb, wcycle);
1385 if (fr->efep != efepNO)
1387 /* Calculate the local and non-local free energy interactions here.
1388 * Happens here on the CPU both with and without GPU.
1390 nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::Local,
1391 fr, as_rvec_array(x.unpaddedArrayRef().data()), &forceOut.forceWithShiftForces(), *mdatoms,
1392 inputrec->fepvals, lambda.data(),
1393 enerd, stepWork, nrnb);
1395 if (havePPDomainDecomposition(cr))
1397 nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::NonLocal,
1398 fr, as_rvec_array(x.unpaddedArrayRef().data()), &forceOut.forceWithShiftForces(), *mdatoms,
1399 inputrec->fepvals, lambda.data(),
1400 enerd, stepWork, nrnb);
1406 if (havePPDomainDecomposition(cr))
1408 do_nb_verlet(fr, ic, enerd, stepWork, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1409 step, nrnb, wcycle);
1412 if (stepWork.computeForces)
1414 /* Add all the non-bonded force to the normal force array.
1415 * This can be split into a local and a non-local part when overlapping
1416 * communication with calculation with domain decomposition.
1418 wallcycle_stop(wcycle, ewcFORCE);
1419 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::All, forceOut.forceWithShiftForces().force());
1420 wallcycle_start_nocount(wcycle, ewcFORCE);
1423 /* If there are multiple fshift output buffers we need to reduce them */
1424 if (stepWork.computeVirial)
1426 /* This is not in a subcounter because it takes a
1427 negligible and constant-sized amount of time */
1428 nbnxn_atomdata_add_nbat_fshift_to_fshift(*nbv->nbat,
1429 forceOut.forceWithShiftForces().shiftForces());
1433 /* update QMMMrec, if necessary */
1436 update_QMMMrec(cr, fr, as_rvec_array(x.unpaddedArrayRef().data()), mdatoms, box);
1439 // TODO Force flags should include haveFreeEnergyWork for this domain
1440 if (ddUsesGpuDirectCommunication &&
1441 (domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork))
1443 /* Wait for non-local coordinate data to be copied from device */
1444 nbv->wait_nonlocal_x_copy_D2H_done();
1446 /* Compute the bonded and non-bonded energies and optionally forces */
1447 do_force_lowlevel(fr, inputrec, &(top->idef),
1448 cr, ms, nrnb, wcycle, mdatoms,
1449 x, hist, &forceOut, enerd, fcd,
1450 box, lambda.data(), graph, fr->mu_tot,
1452 ddBalanceRegionHandler);
1454 wallcycle_stop(wcycle, ewcFORCE);
1456 computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation,
1457 imdSession, pull_work, step, t, wcycle,
1458 fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda.data(),
1459 stepWork, &forceOut.forceWithVirial(), enerd,
1460 ed, stepWork.doNeighborSearch);
1463 // Will store the amount of cycles spent waiting for the GPU that
1464 // will be later used in the DLB accounting.
1465 float cycles_wait_gpu = 0;
1468 auto &forceWithShiftForces = forceOut.forceWithShiftForces();
1470 /* wait for non-local forces (or calculate in emulation mode) */
1471 if (havePPDomainDecomposition(cr))
1475 cycles_wait_gpu += Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1476 stepWork, Nbnxm::AtomLocality::NonLocal,
1477 enerd->grpp.ener[egLJSR].data(),
1478 enerd->grpp.ener[egCOULSR].data(),
1479 forceWithShiftForces.shiftForces(),
1484 wallcycle_start_nocount(wcycle, ewcFORCE);
1485 do_nb_verlet(fr, ic, enerd, stepWork, Nbnxm::InteractionLocality::NonLocal, enbvClearFYes,
1486 step, nrnb, wcycle);
1487 wallcycle_stop(wcycle, ewcFORCE);
1490 if (useGpuFBufOps == BufferOpsUseGpu::True)
1492 // TODO: move this into DomainLifetimeWorkload, including the second part of the condition
1493 // The bonded and free energy CPU tasks can have non-local force contributions
1494 // which are a dependency for the GPU force reduction.
1495 bool haveNonLocalForceContribInCpuBuffer = domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork;
1497 rvec *f = as_rvec_array(forceWithShiftForces.force().data());
1498 if (haveNonLocalForceContribInCpuBuffer)
1500 nbv->launch_copy_f_to_gpu(f, Nbnxm::AtomLocality::NonLocal);
1502 nbv->atomdata_add_nbat_f_to_f_gpu(Nbnxm::AtomLocality::NonLocal,
1503 nbv->getDeviceForces(),
1504 pme_gpu_get_device_f(fr->pmedata),
1505 pme_gpu_get_f_ready_synchronizer(fr->pmedata),
1506 useGpuPmeFReduction, haveNonLocalForceContribInCpuBuffer);
1507 nbv->launch_copy_f_from_gpu(f, Nbnxm::AtomLocality::NonLocal);
1511 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::NonLocal,
1512 forceWithShiftForces.force());
1516 if (fr->nbv->emulateGpu() && stepWork.computeVirial)
1518 nbnxn_atomdata_add_nbat_fshift_to_fshift(*nbv->nbat,
1519 forceWithShiftForces.shiftForces());
1524 const bool useGpuForcesHaloExchange = ddUsesGpuDirectCommunication && (useGpuFBufOps == BufferOpsUseGpu::True);
1525 const bool useCpuPmeFReduction = thisRankHasDuty(cr, DUTY_PME) && !useGpuPmeFReduction;
1526 // TODO: move this into DomainLifetimeWorkload, including the second part of the condition
1527 const bool haveCpuLocalForces = (domainWork.haveSpecialForces || domainWork.haveCpuListedForceWork || useCpuPmeFReduction ||
1528 (fr->efep != efepNO));
1530 if (havePPDomainDecomposition(cr))
1532 /* We are done with the CPU compute.
1533 * We will now communicate the non-local forces.
1534 * If we use a GPU this will overlap with GPU work, so in that case
1535 * we do not close the DD force balancing region here.
1537 ddBalanceRegionHandler.closeAfterForceComputationCpu();
1539 if (stepWork.computeForces)
1541 gmx::ArrayRef<gmx::RVec> force = forceOut.forceWithShiftForces().force();
1542 rvec *f = as_rvec_array(force.data());
1544 if (useGpuForcesHaloExchange)
1546 if (haveCpuLocalForces)
1548 nbv->launch_copy_f_to_gpu(f, Nbnxm::AtomLocality::Local);
1550 bool accumulateHaloForces = haveCpuLocalForces;
1551 gpuHaloExchange->communicateHaloForces(accumulateHaloForces);
1555 if (useGpuFBufOps == BufferOpsUseGpu::True)
1557 nbv->wait_for_gpu_force_reduction(Nbnxm::AtomLocality::NonLocal);
1559 dd_move_f(cr->dd, &forceOut.forceWithShiftForces(), wcycle);
1565 // With both nonbonded and PME offloaded a GPU on the same rank, we use
1566 // an alternating wait/reduction scheme.
1567 bool alternateGpuWait = (!c_disableAlternatingWait && useGpuPme && bUseGPU && !DOMAINDECOMP(cr) &&
1568 (useGpuFBufOps == BufferOpsUseGpu::False));
1569 if (alternateGpuWait)
1571 alternatePmeNbGpuWaitReduce(fr->nbv.get(), fr->pmedata, &forceOut, enerd,
1572 stepWork, pmeFlags, wcycle);
1575 if (!alternateGpuWait && useGpuPme)
1577 pme_gpu_wait_and_reduce(fr->pmedata, pmeFlags, wcycle, &forceOut.forceWithVirial(), enerd);
1580 /* Wait for local GPU NB outputs on the non-alternating wait path */
1581 if (!alternateGpuWait && bUseGPU)
1583 /* Measured overhead on CUDA and OpenCL with(out) GPU sharing
1584 * is between 0.5 and 1.5 Mcycles. So 2 MCycles is an overestimate,
1585 * but even with a step of 0.1 ms the difference is less than 1%
1588 const float gpuWaitApiOverheadMargin = 2e6F; /* cycles */
1589 const float waitCycles =
1590 Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1591 stepWork, Nbnxm::AtomLocality::Local,
1592 enerd->grpp.ener[egLJSR].data(),
1593 enerd->grpp.ener[egCOULSR].data(),
1594 forceOut.forceWithShiftForces().shiftForces(),
1597 if (ddBalanceRegionHandler.useBalancingRegion())
1599 DdBalanceRegionWaitedForGpu waitedForGpu = DdBalanceRegionWaitedForGpu::yes;
1600 if (stepWork.computeForces && waitCycles <= gpuWaitApiOverheadMargin)
1602 /* We measured few cycles, it could be that the kernel
1603 * and transfer finished earlier and there was no actual
1604 * wait time, only API call overhead.
1605 * Then the actual time could be anywhere between 0 and
1606 * cycles_wait_est. We will use half of cycles_wait_est.
1608 waitedForGpu = DdBalanceRegionWaitedForGpu::no;
1610 ddBalanceRegionHandler.closeAfterForceComputationGpu(cycles_wait_gpu, waitedForGpu);
1614 if (fr->nbv->emulateGpu())
1616 // NOTE: emulation kernel is not included in the balancing region,
1617 // but emulation mode does not target performance anyway
1618 wallcycle_start_nocount(wcycle, ewcFORCE);
1619 do_nb_verlet(fr, ic, enerd, stepWork, Nbnxm::InteractionLocality::Local,
1620 DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes,
1621 step, nrnb, wcycle);
1622 wallcycle_stop(wcycle, ewcFORCE);
1625 /* Do the nonbonded GPU (or emulation) force buffer reduction
1626 * on the non-alternating path. */
1627 if (bUseOrEmulGPU && !alternateGpuWait)
1629 gmx::ArrayRef<gmx::RVec> forceWithShift = forceOut.forceWithShiftForces().force();
1631 if (useGpuFBufOps == BufferOpsUseGpu::True)
1633 // Flag to specify whether the CPU force buffer has contributions to
1634 // local atoms. This depends on whether there are CPU-based force tasks
1635 // or when DD is active the halo exchange has resulted in contributions
1636 // from the non-local part.
1637 const bool haveLocalForceContribInCpuBuffer = (haveCpuLocalForces || havePPDomainDecomposition(cr));
1639 // TODO: move these steps as early as possible:
1640 // - CPU f H2D should be as soon as all CPU-side forces are done
1641 // - wait for force reduction does not need to block host (at least not here, it's sufficient to wait
1642 // before the next CPU task that consumes the forces: vsite spread or update)
1643 // - copy is not perfomed if GPU force halo exchange is active, because it would overwrite the result
1644 // of the halo exchange. In that case the copy is instead performed above, before the exchange.
1645 // These should be unified.
1646 rvec *f = as_rvec_array(forceWithShift.data());
1647 if (haveLocalForceContribInCpuBuffer && !useGpuForcesHaloExchange)
1649 nbv->launch_copy_f_to_gpu(f, Nbnxm::AtomLocality::Local);
1651 if (useGpuForcesHaloExchange)
1653 // Add a stream synchronization to satisfy a dependency
1654 // for the local buffer ops on the result of GPU halo
1655 // exchange, which operates in the non-local stream and
1656 // writes to to local parf og the force buffer.
1657 // TODO improve this through use of an event - see Redmine #3093
1658 nbv->stream_local_wait_for_nonlocal();
1660 nbv->atomdata_add_nbat_f_to_f_gpu(Nbnxm::AtomLocality::Local,
1661 nbv->getDeviceForces(),
1662 pme_gpu_get_device_f(fr->pmedata),
1663 pme_gpu_get_f_ready_synchronizer(fr->pmedata),
1664 useGpuPmeFReduction, haveLocalForceContribInCpuBuffer);
1665 nbv->launch_copy_f_from_gpu(f, Nbnxm::AtomLocality::Local);
1666 nbv->wait_for_gpu_force_reduction(Nbnxm::AtomLocality::Local);
1670 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local, forceWithShift);
1675 launchGpuEndOfStepTasks(nbv, fr->gpuBonded, fr->pmedata, enerd,
1681 if (DOMAINDECOMP(cr))
1683 dd_force_flop_stop(cr->dd, nrnb);
1686 if (stepWork.computeForces)
1688 rvec *f = as_rvec_array(forceOut.forceWithShiftForces().force().data());
1690 /* If we have NoVirSum forces, but we do not calculate the virial,
1691 * we sum fr->f_novirsum=forceOut.f later.
1693 if (vsite && !(fr->haveDirectVirialContributions && !stepWork.computeVirial))
1695 rvec *fshift = as_rvec_array(forceOut.forceWithShiftForces().shiftForces().data());
1696 spread_vsite_f(vsite, as_rvec_array(x.unpaddedArrayRef().data()), f, fshift, FALSE, nullptr, nrnb,
1697 &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
1700 if (stepWork.computeVirial)
1702 /* Calculation of the virial must be done after vsites! */
1703 calc_virial(0, mdatoms->homenr, as_rvec_array(x.unpaddedArrayRef().data()),
1704 forceOut.forceWithShiftForces(),
1705 vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1709 if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME))
1711 /* In case of node-splitting, the PP nodes receive the long-range
1712 * forces, virial and energy from the PME nodes here.
1714 pme_receive_force_ener(cr, &forceOut.forceWithVirial(), enerd, wcycle);
1717 if (stepWork.computeForces)
1719 post_process_forces(cr, step, nrnb, wcycle,
1720 top, box, as_rvec_array(x.unpaddedArrayRef().data()), &forceOut,
1721 vir_force, mdatoms, graph, fr, vsite,
1725 if (stepWork.computeEnergy)
1727 /* Sum the potential energy terms from group contributions */
1728 sum_epot(&(enerd->grpp), enerd->term);
1730 if (!EI_TPI(inputrec->eI))
1732 checkPotentialEnergyValidity(step, *enerd, *inputrec);
1736 /* In case we don't have constraints and are using GPUs, the next balancing
1737 * region starts here.
1738 * Some "special" work at the end of do_force_cuts?, such as vsite spread,
1739 * virial calculation and COM pulling, is not thus not included in
1740 * the balance timing, which is ok as most tasks do communication.
1742 ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::no);