forked from plumed/plumed2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsim_util.cpp
2620 lines (2387 loc) · 117 KB
/
sim_util.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright 1991- The GROMACS Authors
* and the project initiators Erik Lindahl, Berk Hess and David van der Spoel.
* Consult the AUTHORS/COPYING files and https://www.gromacs.org for details.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* https://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at https://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out https://www.gromacs.org.
*/
#include "gmxpre.h"
#include "config.h"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <array>
#include <optional>
#include "gromacs/applied_forces/awh/awh.h"
#include "gromacs/domdec/dlbtiming.h"
#include "gromacs/domdec/domdec.h"
#include "gromacs/domdec/domdec_struct.h"
#include "gromacs/domdec/gpuhaloexchange.h"
#include "gromacs/domdec/partition.h"
#include "gromacs/essentialdynamics/edsam.h"
#include "gromacs/ewald/pme.h"
#include "gromacs/ewald/pme_coordinate_receiver_gpu.h"
#include "gromacs/ewald/pme_pp.h"
#include "gromacs/ewald/pme_pp_comm_gpu.h"
#include "gromacs/gmxlib/network.h"
#include "gromacs/gmxlib/nonbonded/nb_free_energy.h"
#include "gromacs/gmxlib/nonbonded/nonbonded.h"
#include "gromacs/gmxlib/nrnb.h"
#include "gromacs/gpu_utils/gpu_utils.h"
#include "gromacs/imd/imd.h"
#include "gromacs/listed_forces/disre.h"
#include "gromacs/listed_forces/listed_forces.h"
#include "gromacs/listed_forces/listed_forces_gpu.h"
#include "gromacs/listed_forces/orires.h"
#include "gromacs/math/arrayrefwithpadding.h"
#include "gromacs/math/functions.h"
#include "gromacs/math/units.h"
#include "gromacs/math/vec.h"
#include "gromacs/math/vecdump.h"
#include "gromacs/mdlib/calcmu.h"
#include "gromacs/mdlib/calcvir.h"
#include "gromacs/mdlib/constr.h"
#include "gromacs/mdlib/dispersioncorrection.h"
#include "gromacs/mdlib/enerdata_utils.h"
#include "gromacs/mdlib/force.h"
#include "gromacs/mdlib/force_flags.h"
#include "gromacs/mdlib/forcerec.h"
#include "gromacs/mdlib/gmx_omp_nthreads.h"
#include "gromacs/mdlib/update.h"
#include "gromacs/mdlib/vsite.h"
#include "gromacs/mdlib/wall.h"
#include "gromacs/mdlib/wholemoleculetransform.h"
#include "gromacs/mdtypes/commrec.h"
#include "gromacs/mdtypes/enerdata.h"
#include "gromacs/mdtypes/forcebuffers.h"
#include "gromacs/mdtypes/forceoutput.h"
#include "gromacs/mdtypes/forcerec.h"
#include "gromacs/mdtypes/iforceprovider.h"
#include "gromacs/mdtypes/inputrec.h"
#include "gromacs/mdtypes/md_enums.h"
#include "gromacs/mdtypes/mdatom.h"
#include "gromacs/mdtypes/multipletimestepping.h"
#include "gromacs/mdtypes/simulation_workload.h"
#include "gromacs/mdtypes/state.h"
#include "gromacs/mdtypes/state_propagator_data_gpu.h"
#include "gromacs/nbnxm/gpu_data_mgmt.h"
#include "gromacs/nbnxm/nbnxm.h"
#include "gromacs/nbnxm/nbnxm_gpu.h"
#include "gromacs/pbcutil/ishift.h"
#include "gromacs/pbcutil/pbc.h"
#include "gromacs/pulling/pull.h"
#include "gromacs/pulling/pull_rotation.h"
#include "gromacs/timing/cyclecounter.h"
#include "gromacs/timing/gpu_timing.h"
#include "gromacs/timing/wallcycle.h"
#include "gromacs/timing/wallcyclereporting.h"
#include "gromacs/timing/walltime_accounting.h"
#include "gromacs/topology/topology.h"
#include "gromacs/utility/arrayref.h"
#include "gromacs/utility/basedefinitions.h"
#include "gromacs/utility/cstringutil.h"
#include "gromacs/utility/exceptions.h"
#include "gromacs/utility/fatalerror.h"
#include "gromacs/utility/fixedcapacityvector.h"
#include "gromacs/utility/gmxassert.h"
#include "gromacs/utility/gmxmpi.h"
#include "gromacs/utility/logger.h"
#include "gromacs/utility/smalloc.h"
#include "gromacs/utility/strconvert.h"
#include "gromacs/utility/stringutil.h"
#include "gromacs/utility/sysinfo.h"
#include "gpuforcereduction.h"
using gmx::ArrayRef;
using gmx::AtomLocality;
using gmx::DomainLifetimeWorkload;
using gmx::ForceOutputs;
using gmx::ForceWithShiftForces;
using gmx::InteractionLocality;
using gmx::RVec;
using gmx::SimulationWorkload;
using gmx::StepWorkload;
/* PLUMED */
#include "../../../Plumed.h"
extern int plumedswitch;
extern plumed plumedmain;
/* END PLUMED */
// TODO: this environment variable allows us to verify before release
// that on less common architectures the total cost of polling is not larger than
// a blocking wait (so polling does not introduce overhead when the static
// PME-first ordering would suffice).
static const bool c_disableAlternatingWait = (getenv("GMX_DISABLE_ALTERNATING_GPU_WAIT") != nullptr);
static void sum_forces(ArrayRef<RVec> f, ArrayRef<const RVec> forceToAdd)
{
GMX_ASSERT(f.size() >= forceToAdd.size(), "Accumulation buffer should be sufficiently large");
const int end = forceToAdd.size();
int gmx_unused nt = gmx_omp_nthreads_get(ModuleMultiThread::Default);
#pragma omp parallel for num_threads(nt) schedule(static)
for (int i = 0; i < end; i++)
{
rvec_inc(f[i], forceToAdd[i]);
}
}
static void calc_virial(int start,
int homenr,
const rvec x[],
const gmx::ForceWithShiftForces& forceWithShiftForces,
tensor vir_part,
const matrix box,
t_nrnb* nrnb,
const t_forcerec* fr,
PbcType pbcType)
{
/* The short-range virial from surrounding boxes */
const rvec* fshift = as_rvec_array(forceWithShiftForces.shiftForces().data());
const rvec* shiftVecPointer = as_rvec_array(fr->shift_vec.data());
calc_vir(gmx::c_numShiftVectors, shiftVecPointer, fshift, vir_part, pbcType == PbcType::Screw, box);
inc_nrnb(nrnb, eNR_VIRIAL, gmx::c_numShiftVectors);
/* Calculate partial virial, for local atoms only, based on short range.
* Total virial is computed in global_stat, called from do_md
*/
const rvec* f = as_rvec_array(forceWithShiftForces.force().data());
f_calc_vir(start, start + homenr, x, f, vir_part, box);
inc_nrnb(nrnb, eNR_VIRIAL, homenr);
if (debug)
{
pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
}
}
static void pull_potential_wrapper(const t_commrec* cr,
const t_inputrec& ir,
const matrix box,
gmx::ArrayRef<const gmx::RVec> x,
const t_mdatoms* mdatoms,
gmx_enerdata_t* enerd,
pull_t* pull_work,
const real* lambda,
double t,
gmx_wallcycle* wcycle)
{
t_pbc pbc;
real dvdl;
/* Calculate the center of mass forces, this requires communication,
* which is why pull_potential is called close to other communication.
*/
wallcycle_start(wcycle, WallCycleCounter::PullPot);
set_pbc(&pbc, ir.pbcType, box);
dvdl = 0;
enerd->term[F_COM_PULL] +=
pull_potential(pull_work,
mdatoms->massT,
pbc,
cr,
t,
lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Restraint)],
x,
&dvdl);
enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Restraint] += dvdl;
wallcycle_stop(wcycle, WallCycleCounter::PullPot);
}
static void pme_receive_force_ener(t_forcerec* fr,
const t_commrec* cr,
gmx::ForceWithVirial* forceWithVirial,
gmx_enerdata_t* enerd,
bool useGpuPmePpComms,
bool receivePmeForceToGpu,
gmx_wallcycle* wcycle)
{
real e_q, e_lj, dvdl_q, dvdl_lj;
float cycles_ppdpme, cycles_seppme;
cycles_ppdpme = wallcycle_stop(wcycle, WallCycleCounter::PpDuringPme);
dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
/* In case of node-splitting, the PP nodes receive the long-range
* forces, virial and energy from the PME nodes here.
*/
wallcycle_start(wcycle, WallCycleCounter::PpPmeWaitRecvF);
dvdl_q = 0;
dvdl_lj = 0;
gmx_pme_receive_f(fr->pmePpCommGpu.get(),
cr,
forceWithVirial,
&e_q,
&e_lj,
&dvdl_q,
&dvdl_lj,
useGpuPmePpComms,
receivePmeForceToGpu,
&cycles_seppme);
enerd->term[F_COUL_RECIP] += e_q;
enerd->term[F_LJ_RECIP] += e_lj;
enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Coul] += dvdl_q;
enerd->dvdl_lin[FreeEnergyPerturbationCouplingType::Vdw] += dvdl_lj;
if (wcycle)
{
dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
}
wallcycle_stop(wcycle, WallCycleCounter::PpPmeWaitRecvF);
}
static void print_large_forces(FILE* fp,
const t_mdatoms* md,
const t_commrec* cr,
int64_t step,
real forceTolerance,
ArrayRef<const RVec> x,
ArrayRef<const RVec> f)
{
real force2Tolerance = gmx::square(forceTolerance);
gmx::index numNonFinite = 0;
for (int i = 0; i < md->homenr; i++)
{
real force2 = norm2(f[i]);
bool nonFinite = !std::isfinite(force2);
if (force2 >= force2Tolerance || nonFinite)
{
fprintf(fp,
"step %" PRId64 " atom %6d x %8.3f %8.3f %8.3f force %12.5e\n",
step,
ddglatnr(cr->dd, i),
x[i][XX],
x[i][YY],
x[i][ZZ],
std::sqrt(force2));
}
if (nonFinite)
{
numNonFinite++;
}
}
if (numNonFinite > 0)
{
/* Note that with MPI this fatal call on one rank might interrupt
* the printing on other ranks. But we can only avoid that with
* an expensive MPI barrier that we would need at each step.
*/
gmx_fatal(FARGS, "At step %" PRId64 " detected non-finite forces on %td atoms", step, numNonFinite);
}
}
//! When necessary, spreads forces on vsites and computes the virial for \p forceOutputs->forceWithShiftForces()
static void postProcessForceWithShiftForces(t_nrnb* nrnb,
gmx_wallcycle* wcycle,
const matrix box,
ArrayRef<const RVec> x,
ForceOutputs* forceOutputs,
tensor vir_force,
const t_mdatoms& mdatoms,
const t_forcerec& fr,
gmx::VirtualSitesHandler* vsite,
const StepWorkload& stepWork)
{
ForceWithShiftForces& forceWithShiftForces = forceOutputs->forceWithShiftForces();
/* If we have NoVirSum forces, but we do not calculate the virial,
* we later sum the forceWithShiftForces buffer together with
* the noVirSum buffer and spread the combined vsite forces at once.
*/
if (vsite && (!forceOutputs->haveForceWithVirial() || stepWork.computeVirial))
{
using VirialHandling = gmx::VirtualSitesHandler::VirialHandling;
auto f = forceWithShiftForces.force();
auto fshift = forceWithShiftForces.shiftForces();
const VirialHandling virialHandling =
(stepWork.computeVirial ? VirialHandling::Pbc : VirialHandling::None);
vsite->spreadForces(x, f, virialHandling, fshift, nullptr, nrnb, box, wcycle);
forceWithShiftForces.haveSpreadVsiteForces() = true;
}
if (stepWork.computeVirial)
{
/* Calculation of the virial must be done after vsites! */
calc_virial(
0, mdatoms.homenr, as_rvec_array(x.data()), forceWithShiftForces, vir_force, box, nrnb, &fr, fr.pbcType);
}
}
//! Spread, compute virial for and sum forces, when necessary
static void postProcessForces(const t_commrec* cr,
int64_t step,
t_nrnb* nrnb,
gmx_wallcycle* wcycle,
const matrix box,
ArrayRef<const RVec> x,
ForceOutputs* forceOutputs,
tensor vir_force,
const t_mdatoms* mdatoms,
const t_forcerec* fr,
gmx::VirtualSitesHandler* vsite,
const StepWorkload& stepWork)
{
// Extract the final output force buffer, which is also the buffer for forces with shift forces
ArrayRef<RVec> f = forceOutputs->forceWithShiftForces().force();
if (forceOutputs->haveForceWithVirial())
{
auto& forceWithVirial = forceOutputs->forceWithVirial();
if (vsite)
{
/* Spread the mesh force on virtual sites to the other particles...
* This is parallellized. MPI communication is performed
* if the constructing atoms aren't local.
*/
GMX_ASSERT(!stepWork.computeVirial || f.data() != forceWithVirial.force_.data(),
"We need separate force buffers for shift and virial forces when "
"computing the virial");
GMX_ASSERT(!stepWork.computeVirial
|| forceOutputs->forceWithShiftForces().haveSpreadVsiteForces(),
"We should spread the force with shift forces separately when computing "
"the virial");
const gmx::VirtualSitesHandler::VirialHandling virialHandling =
(stepWork.computeVirial ? gmx::VirtualSitesHandler::VirialHandling::NonLinear
: gmx::VirtualSitesHandler::VirialHandling::None);
matrix virial = { { 0 } };
vsite->spreadForces(x, forceWithVirial.force_, virialHandling, {}, virial, nrnb, box, wcycle);
forceWithVirial.addVirialContribution(virial);
}
if (stepWork.computeVirial)
{
/* Now add the forces, this is local */
sum_forces(f, forceWithVirial.force_);
/* Add the direct virial contributions */
GMX_ASSERT(
forceWithVirial.computeVirial_,
"forceWithVirial should request virial computation when we request the virial");
m_add(vir_force, forceWithVirial.getVirial(), vir_force);
if (debug)
{
pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
}
}
}
else
{
GMX_ASSERT(vsite == nullptr || forceOutputs->forceWithShiftForces().haveSpreadVsiteForces(),
"We should have spread the vsite forces (earlier)");
}
if (fr->print_force >= 0)
{
print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
}
}
static void do_nb_verlet(t_forcerec* fr,
const interaction_const_t* ic,
gmx_enerdata_t* enerd,
const StepWorkload& stepWork,
const InteractionLocality ilocality,
const int clearF,
const int64_t step,
t_nrnb* nrnb,
gmx_wallcycle* wcycle)
{
if (!stepWork.computeNonbondedForces)
{
/* skip non-bonded calculation */
return;
}
nonbonded_verlet_t* nbv = fr->nbv.get();
/* GPU kernel launch overhead is already timed separately */
if (!nbv->useGpu())
{
/* When dynamic pair-list pruning is requested, we need to prune
* at nstlistPrune steps.
*/
if (nbv->isDynamicPruningStepCpu(step))
{
/* Prune the pair-list beyond fr->ic->rlistPrune using
* the current coordinates of the atoms.
*/
wallcycle_sub_start(wcycle, WallCycleSubCounter::NonbondedPruning);
nbv->dispatchPruneKernelCpu(ilocality, fr->shift_vec);
wallcycle_sub_stop(wcycle, WallCycleSubCounter::NonbondedPruning);
}
}
nbv->dispatchNonbondedKernel(
ilocality,
*ic,
stepWork,
clearF,
fr->shift_vec,
enerd->grpp.energyGroupPairTerms[fr->haveBuckingham ? NonBondedEnergyTerms::BuckinghamSR
: NonBondedEnergyTerms::LJSR],
enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::CoulombSR],
nrnb);
}
static inline void clearRVecs(ArrayRef<RVec> v, const bool useOpenmpThreading)
{
int nth = gmx_omp_nthreads_get_simple_rvec_task(ModuleMultiThread::Default, v.ssize());
/* Note that we would like to avoid this conditional by putting it
* into the omp pragma instead, but then we still take the full
* omp parallel for overhead (at least with gcc5).
*/
if (!useOpenmpThreading || nth == 1)
{
for (RVec& elem : v)
{
clear_rvec(elem);
}
}
else
{
#pragma omp parallel for num_threads(nth) schedule(static)
for (gmx::index i = 0; i < v.ssize(); i++)
{
clear_rvec(v[i]);
}
}
}
/*! \brief Return an estimate of the average kinetic energy or 0 when unreliable
*
* \param groupOptions Group options, containing T-coupling options
*/
static real averageKineticEnergyEstimate(const t_grpopts& groupOptions)
{
real nrdfCoupled = 0;
real nrdfUncoupled = 0;
real kineticEnergy = 0;
for (int g = 0; g < groupOptions.ngtc; g++)
{
if (groupOptions.tau_t[g] >= 0)
{
nrdfCoupled += groupOptions.nrdf[g];
kineticEnergy += groupOptions.nrdf[g] * 0.5 * groupOptions.ref_t[g] * gmx::c_boltz;
}
else
{
nrdfUncoupled += groupOptions.nrdf[g];
}
}
/* This conditional with > also catches nrdf=0 */
if (nrdfCoupled > nrdfUncoupled)
{
return kineticEnergy * (nrdfCoupled + nrdfUncoupled) / nrdfCoupled;
}
else
{
return 0;
}
}
/*! \brief This routine checks that the potential energy is finite.
*
* Always checks that the potential energy is finite. If step equals
* inputrec.init_step also checks that the magnitude of the potential energy
* is reasonable. Terminates with a fatal error when a check fails.
* Note that passing this check does not guarantee finite forces,
* since those use slightly different arithmetics. But in most cases
* there is just a narrow coordinate range where forces are not finite
* and energies are finite.
*
* \param[in] step The step number, used for checking and printing
* \param[in] enerd The energy data; the non-bonded group energies need to be added to
* \c enerd.term[F_EPOT] before calling this routine
* \param[in] inputrec The input record
*/
static void checkPotentialEnergyValidity(int64_t step, const gmx_enerdata_t& enerd, const t_inputrec& inputrec)
{
/* Threshold valid for comparing absolute potential energy against
* the kinetic energy. Normally one should not consider absolute
* potential energy values, but with a factor of one million
* we should never get false positives.
*/
constexpr real c_thresholdFactor = 1e6;
bool energyIsNotFinite = !std::isfinite(enerd.term[F_EPOT]);
real averageKineticEnergy = 0;
/* We only check for large potential energy at the initial step,
* because that is by far the most likely step for this too occur
* and because computing the average kinetic energy is not free.
* Note: nstcalcenergy >> 1 often does not allow to catch large energies
* before they become NaN.
*/
if (step == inputrec.init_step && EI_DYNAMICS(inputrec.eI))
{
averageKineticEnergy = averageKineticEnergyEstimate(inputrec.opts);
}
if (energyIsNotFinite
|| (averageKineticEnergy > 0 && enerd.term[F_EPOT] > c_thresholdFactor * averageKineticEnergy))
{
GMX_THROW(gmx::InternalError(gmx::formatString(
"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.",
step,
enerd.term[F_EPOT],
energyIsNotFinite ? "not finite" : "extremely high",
enerd.term[F_LJ],
enerd.term[F_COUL_SR],
energyIsNotFinite ? "non-finite" : "very high",
energyIsNotFinite ? " or Nan" : "")));
}
}
/*! \brief Return true if there are special forces computed.
*
* The conditionals exactly correspond to those in computeSpecialForces().
*/
static bool haveSpecialForces(const t_inputrec& inputrec,
const gmx::ForceProviders& forceProviders,
const pull_t* pull_work,
const gmx_edsam* ed)
{
return ((forceProviders.hasForceProvider()) || // forceProviders
(inputrec.bPull && pull_have_potential(*pull_work)) || // pull
inputrec.bRot || // enforced rotation
(ed != nullptr) || // flooding
(inputrec.bIMD)); // IMD
}
/*! \brief Compute forces and/or energies for special algorithms
*
* The intention is to collect all calls to algorithms that compute
* forces on local atoms only and that do not contribute to the local
* virial sum (but add their virial contribution separately).
* Eventually these should likely all become ForceProviders.
* Within this function the intention is to have algorithms that do
* global communication at the end, so global barriers within the MD loop
* are as close together as possible.
*
* \param[in] fplog The log file
* \param[in] cr The communication record
* \param[in] inputrec The input record
* \param[in] awh The Awh module (nullptr if none in use).
* \param[in] enforcedRotation Enforced rotation module.
* \param[in] imdSession The IMD session
* \param[in] pull_work The pull work structure.
* \param[in] step The current MD step
* \param[in] t The current time
* \param[in,out] wcycle Wallcycle accounting struct
* \param[in,out] forceProviders Pointer to a list of force providers
* \param[in] box The unit cell
* \param[in] x The coordinates
* \param[in] mdatoms Per atom properties
* \param[in] lambda Array of free-energy lambda values
* \param[in] stepWork Step schedule flags
* \param[in,out] forceWithVirialMtsLevel0 Force and virial for MTS level0 forces
* \param[in,out] forceWithVirialMtsLevel1 Force and virial for MTS level1 forces, can be nullptr
* \param[in,out] enerd Energy buffer
* \param[in,out] ed Essential dynamics pointer
* \param[in] didNeighborSearch Tells if we did neighbor searching this step, used for ED sampling
*
* \todo Remove didNeighborSearch, which is used incorrectly.
* \todo Convert all other algorithms called here to ForceProviders.
*/
static void computeSpecialForces(FILE* fplog,
const t_commrec* cr,
const t_inputrec& inputrec,
gmx::Awh* awh,
gmx_enfrot* enforcedRotation,
gmx::ImdSession* imdSession,
pull_t* pull_work,
int64_t step,
double t,
gmx_wallcycle* wcycle,
gmx::ForceProviders* forceProviders,
const matrix box,
gmx::ArrayRef<const gmx::RVec> x,
const t_mdatoms* mdatoms,
gmx::ArrayRef<const real> lambda,
const StepWorkload& stepWork,
gmx::ForceWithVirial* forceWithVirialMtsLevel0,
gmx::ForceWithVirial* forceWithVirialMtsLevel1,
gmx_enerdata_t* enerd,
gmx_edsam* ed,
bool didNeighborSearch)
{
/* NOTE: Currently all ForceProviders only provide forces.
* When they also provide energies, remove this conditional.
*/
if (stepWork.computeForces)
{
gmx::ForceProviderInput forceProviderInput(
x,
mdatoms->homenr,
gmx::makeArrayRef(mdatoms->chargeA).subArray(0, mdatoms->homenr),
gmx::makeArrayRef(mdatoms->massT).subArray(0, mdatoms->homenr),
t,
step,
box,
*cr);
gmx::ForceProviderOutput forceProviderOutput(forceWithVirialMtsLevel0, enerd);
/* Collect forces from modules */
forceProviders->calculateForces(forceProviderInput, &forceProviderOutput);
}
const int pullMtsLevel = forceGroupMtsLevel(inputrec.mtsLevels, gmx::MtsForceGroups::Pull);
const bool doPulling = (inputrec.bPull && pull_have_potential(*pull_work)
&& (pullMtsLevel == 0 || stepWork.computeSlowForces));
/* pull_potential_wrapper(), awh->applyBiasForcesAndUpdateBias(), pull_apply_forces()
* have to be called in this order
*/
if (doPulling)
{
pull_potential_wrapper(cr, inputrec, box, x, mdatoms, enerd, pull_work, lambda.data(), t, wcycle);
}
if (awh && (pullMtsLevel == 0 || stepWork.computeSlowForces))
{
const bool needForeignEnergyDifferences = awh->needForeignEnergyDifferences(step);
std::vector<double> foreignLambdaDeltaH, foreignLambdaDhDl;
if (needForeignEnergyDifferences)
{
enerd->foreignLambdaTerms.finalizePotentialContributions(
enerd->dvdl_lin, lambda, *inputrec.fepvals);
std::tie(foreignLambdaDeltaH, foreignLambdaDhDl) = enerd->foreignLambdaTerms.getTerms(cr);
}
enerd->term[F_COM_PULL] += awh->applyBiasForcesAndUpdateBias(
inputrec.pbcType, foreignLambdaDeltaH, foreignLambdaDhDl, box, t, step, wcycle, fplog);
}
if (doPulling)
{
wallcycle_start_nocount(wcycle, WallCycleCounter::PullPot);
auto& forceWithVirial = (pullMtsLevel == 0) ? forceWithVirialMtsLevel0 : forceWithVirialMtsLevel1;
pull_apply_forces(pull_work, mdatoms->massT, cr, forceWithVirial);
wallcycle_stop(wcycle, WallCycleCounter::PullPot);
}
/* Add the forces from enforced rotation potentials (if any) */
if (inputrec.bRot)
{
wallcycle_start(wcycle, WallCycleCounter::RotAdd);
enerd->term[F_COM_PULL] +=
add_rot_forces(enforcedRotation, forceWithVirialMtsLevel0->force_, cr, step, t);
wallcycle_stop(wcycle, WallCycleCounter::RotAdd);
}
if (ed)
{
/* Note that since init_edsam() is called after the initialization
* of forcerec, edsam doesn't request the noVirSum force buffer.
* Thus if no other algorithm (e.g. PME) requires it, the forces
* here will contribute to the virial.
*/
do_flood(cr, inputrec, x, forceWithVirialMtsLevel0->force_, ed, box, step, didNeighborSearch);
}
/* Add forces from interactive molecular dynamics (IMD), if any */
if (inputrec.bIMD && stepWork.computeForces)
{
imdSession->applyForces(forceWithVirialMtsLevel0->force_);
}
}
/*! \brief Launch the prepare_step and spread stages of PME GPU.
*
* \param[in] pmedata The PME structure
* \param[in] box The box matrix
* \param[in] stepWork Step schedule flags
* \param[in] xReadyOnDevice Event synchronizer indicating that the coordinates are ready in the device memory.
* \param[in] lambdaQ The Coulomb lambda of the current state.
* \param[in] useMdGpuGraph Whether MD GPU Graph is in use.
* \param[in] wcycle The wallcycle structure
*/
static inline void launchPmeGpuSpread(gmx_pme_t* pmedata,
const matrix box,
const StepWorkload& stepWork,
GpuEventSynchronizer* xReadyOnDevice,
const real lambdaQ,
bool useMdGpuGraph,
gmx_wallcycle* wcycle)
{
wallcycle_start(wcycle, WallCycleCounter::PmeGpuMesh);
pme_gpu_prepare_computation(pmedata, box, wcycle, stepWork);
bool useGpuDirectComm = false;
gmx::PmeCoordinateReceiverGpu* pmeCoordinateReceiverGpu = nullptr;
pme_gpu_launch_spread(
pmedata, xReadyOnDevice, wcycle, lambdaQ, useGpuDirectComm, pmeCoordinateReceiverGpu, useMdGpuGraph);
wallcycle_stop(wcycle, WallCycleCounter::PmeGpuMesh);
}
/*! \brief Launch the FFT and gather stages of PME GPU
*
* This function only implements setting the output forces (no accumulation).
*
* \param[in] pmedata The PME structure
* \param[in] lambdaQ The Coulomb lambda of the current system state.
* \param[in] wcycle The wallcycle structure
* \param[in] stepWork Step schedule flags
*/
static void launchPmeGpuFftAndGather(gmx_pme_t* pmedata,
const real lambdaQ,
gmx_wallcycle* wcycle,
const gmx::StepWorkload& stepWork)
{
wallcycle_start_nocount(wcycle, WallCycleCounter::PmeGpuMesh);
pme_gpu_launch_complex_transforms(pmedata, wcycle, stepWork);
pme_gpu_launch_gather(pmedata, wcycle, lambdaQ);
wallcycle_stop(wcycle, WallCycleCounter::PmeGpuMesh);
}
/*! \brief
* Blocks until PME GPU tasks are completed, and gets the output forces and virial/energy
* (if they were to be computed).
*
* \param[in] pme The PME data structure.
* \param[in] stepWork The required work for this simulation step
* \param[in] wcycle The wallclock counter.
* \param[out] forceWithVirial The output force and virial
* \param[out] enerd The output energies
* \param[in] lambdaQ The Coulomb lambda to use when calculating the results.
*/
static void pmeGpuWaitAndReduce(gmx_pme_t* pme,
const gmx::StepWorkload& stepWork,
gmx_wallcycle* wcycle,
gmx::ForceWithVirial* forceWithVirial,
gmx_enerdata_t* enerd,
const real lambdaQ)
{
wallcycle_start_nocount(wcycle, WallCycleCounter::PmeGpuMesh);
pme_gpu_wait_and_reduce(pme, stepWork, wcycle, forceWithVirial, enerd, lambdaQ);
wallcycle_stop(wcycle, WallCycleCounter::PmeGpuMesh);
}
/*! \brief
* Polling wait for either of the PME or nonbonded GPU tasks.
*
* Instead of a static order in waiting for GPU tasks, this function
* polls checking which of the two tasks completes first, and does the
* associated force buffer reduction overlapped with the other task.
* By doing that, unlike static scheduling order, it can always overlap
* one of the reductions, regardless of the GPU task completion order.
*
* \param[in] nbv Nonbonded verlet structure
* \param[in,out] pmedata PME module data
* \param[in,out] forceOutputsNonbonded Force outputs for the non-bonded forces and shift forces
* \param[in,out] forceOutputsPme Force outputs for the PME forces and virial
* \param[in,out] enerd Energy data structure results are reduced into
* \param[in] lambdaQ The Coulomb lambda of the current system state.
* \param[in] stepWork Step schedule flags
* \param[in] wcycle The wallcycle structure
*/
static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t* nbv,
gmx_pme_t* pmedata,
gmx::ForceOutputs* forceOutputsNonbonded,
gmx::ForceOutputs* forceOutputsPme,
gmx_enerdata_t* enerd,
const real lambdaQ,
const StepWorkload& stepWork,
gmx_wallcycle* wcycle)
{
bool isPmeGpuDone = false;
bool isNbGpuDone = false;
gmx::ArrayRef<const gmx::RVec> pmeGpuForces;
while (!isPmeGpuDone || !isNbGpuDone)
{
if (!isPmeGpuDone)
{
wallcycle_start_nocount(wcycle, WallCycleCounter::PmeGpuMesh);
GpuTaskCompletion completionType =
(isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
isPmeGpuDone = pme_gpu_try_finish_task(
pmedata, stepWork, wcycle, &forceOutputsPme->forceWithVirial(), enerd, lambdaQ, completionType);
wallcycle_stop(wcycle, WallCycleCounter::PmeGpuMesh);
}
if (!isNbGpuDone)
{
auto& forceBuffersNonbonded = forceOutputsNonbonded->forceWithShiftForces();
GpuTaskCompletion completionType =
(isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
isNbGpuDone = Nbnxm::gpu_try_finish_task(
nbv->gpu_nbv,
stepWork,
AtomLocality::Local,
enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::LJSR].data(),
enerd->grpp.energyGroupPairTerms[NonBondedEnergyTerms::CoulombSR].data(),
forceBuffersNonbonded.shiftForces(),
completionType,
wcycle);
if (isNbGpuDone)
{
nbv->atomdata_add_nbat_f_to_f(AtomLocality::Local, forceBuffersNonbonded.force());
}
}
}
}
/*! \brief Set up the different force buffers; also does clearing.
*
* \param[in] forceHelperBuffers Helper force buffers
* \param[in] force force array
* \param[in] domainWork Domain lifetime workload flags
* \param[in] stepWork Step schedule flags
* \param[in] havePpDomainDecomposition Whether we have a PP domain decomposition
* \param[out] wcycle wallcycle recording structure
*
* \returns Cleared force output structure
*/
static ForceOutputs setupForceOutputs(ForceHelperBuffers* forceHelperBuffers,
gmx::ArrayRefWithPadding<gmx::RVec> force,
const DomainLifetimeWorkload& domainWork,
const StepWorkload& stepWork,
const bool havePpDomainDecomposition,
gmx_wallcycle* wcycle)
{
wallcycle_sub_start(wcycle, WallCycleSubCounter::ClearForceBuffer);
/* NOTE: We assume fr->shiftForces is all zeros here */
gmx::ForceWithShiftForces forceWithShiftForces(
force, stepWork.computeVirial, forceHelperBuffers->shiftForces());
if (stepWork.computeForces
&& (domainWork.haveCpuLocalForceWork || !stepWork.useGpuFBufferOps
|| (havePpDomainDecomposition && !stepWork.useGpuFHalo)))
{
/* Clear the short- and long-range forces */
clearRVecs(forceWithShiftForces.force(), true);
/* Clear the shift forces */
clearRVecs(forceWithShiftForces.shiftForces(), false);
}
/* If we need to compute the virial, we might need a separate
* force buffer for algorithms for which the virial is calculated
* directly, such as PME. Otherwise, forceWithVirial uses the
* the same force (f in legacy calls) buffer as other algorithms.
*/
const bool useSeparateForceWithVirialBuffer =
(stepWork.computeForces
&& (stepWork.computeVirial && forceHelperBuffers->haveDirectVirialContributions()));
/* forceWithVirial uses the local atom range only */
gmx::ForceWithVirial forceWithVirial(
useSeparateForceWithVirialBuffer ? forceHelperBuffers->forceBufferForDirectVirialContributions()
: force.unpaddedArrayRef(),
stepWork.computeVirial);
if (useSeparateForceWithVirialBuffer)
{
/* TODO: update comment
* We only compute forces on local atoms. Note that vsites can
* spread to non-local atoms, but that part of the buffer is
* cleared separately in the vsite spreading code.
*/
clearRVecs(forceWithVirial.force_, true);
}
wallcycle_sub_stop(wcycle, WallCycleSubCounter::ClearForceBuffer);
return ForceOutputs(
forceWithShiftForces, forceHelperBuffers->haveDirectVirialContributions(), forceWithVirial);
}
/*! \brief Set up flags that have the lifetime of the domain indicating what type of work is there to compute.
*/
static DomainLifetimeWorkload setupDomainLifetimeWorkload(const t_inputrec& inputrec,
const t_forcerec& fr,
const pull_t* pull_work,
const gmx_edsam* ed,
const t_mdatoms& mdatoms,
const SimulationWorkload& simulationWork)
{
DomainLifetimeWorkload domainWork;
// Note that haveSpecialForces is constant over the whole run
domainWork.haveSpecialForces = haveSpecialForces(inputrec, *fr.forceProviders, pull_work, ed);
domainWork.haveCpuListedForceWork = false;
domainWork.haveCpuBondedWork = false;
for (const auto& listedForces : fr.listedForces)
{
if (listedForces.haveCpuListedForces(*fr.fcdata))
{
domainWork.haveCpuListedForceWork = true;
}
if (listedForces.haveCpuBondeds())
{
domainWork.haveCpuBondedWork = true;
}
}
domainWork.haveGpuBondedWork =
((fr.listedForcesGpu != nullptr) && fr.listedForcesGpu->haveInteractions());
// Note that haveFreeEnergyWork is constant over the whole run
domainWork.haveFreeEnergyWork =
(fr.efep != FreeEnergyPerturbationType::No && mdatoms.nPerturbed != 0);
// We assume we have local force work if there are CPU
// force tasks including PME or nonbondeds.
domainWork.haveCpuLocalForceWork =
domainWork.haveSpecialForces || domainWork.haveCpuListedForceWork
|| domainWork.haveFreeEnergyWork || simulationWork.useCpuNonbonded || simulationWork.useCpuPme
|| simulationWork.haveEwaldSurfaceContribution || inputrec.nwall > 0;
domainWork.haveCpuNonLocalForceWork = domainWork.haveCpuBondedWork || domainWork.haveFreeEnergyWork;
domainWork.haveLocalForceContribInCpuBuffer =
domainWork.haveCpuLocalForceWork || simulationWork.havePpDomainDecomposition;
return domainWork;
}
/*! \brief Set up force flag struct from the force bitmask.
*
* \param[in] legacyFlags Force bitmask flags used to construct the new flags
* \param[in] mtsLevels The multiple time-stepping levels, either empty or 2 levels
* \param[in] step The current MD step
* \param[in] domainWork Domain lifetime workload description.
* \param[in] simulationWork Simulation workload description.
*
* \returns New Stepworkload description.
*/
static StepWorkload setupStepWorkload(const int legacyFlags,
ArrayRef<const gmx::MtsLevel> mtsLevels,
const int64_t step,
const DomainLifetimeWorkload& domainWork,
const SimulationWorkload& simulationWork)
{
GMX_ASSERT(mtsLevels.empty() || mtsLevels.size() == 2, "Expect 0 or 2 MTS levels");
const bool computeSlowForces = (mtsLevels.empty() || step % mtsLevels[1].stepFactor == 0);
StepWorkload flags;
flags.stateChanged = ((legacyFlags & GMX_FORCE_STATECHANGED) != 0);
flags.haveDynamicBox = ((legacyFlags & GMX_FORCE_DYNAMICBOX) != 0);
flags.doNeighborSearch = ((legacyFlags & GMX_FORCE_NS) != 0);