2e43db5fc661148a191f501bcac6ce7d9d68a4bd
[alexxy/gromacs.git] / src / gromacs / nbnxm / nbnxm_setup.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2019, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief Common functions for the different NBNXN GPU implementations.
37  *
38  * \author Berk Hess <hess@kth.se>
39  *
40  * \ingroup module_nbnxm
41  */
42
43 #include "gmxpre.h"
44
45 #include "gromacs/domdec/domdec.h"
46 #include "gromacs/domdec/domdec_struct.h"
47 #include "gromacs/hardware/hw_info.h"
48 #include "gromacs/mdlib/gmx_omp_nthreads.h"
49 #include "gromacs/mdtypes/commrec.h"
50 #include "gromacs/mdtypes/forcerec.h"
51 #include "gromacs/mdtypes/inputrec.h"
52 #include "gromacs/nbnxm/atomdata.h"
53 #include "gromacs/nbnxm/gpu_data_mgmt.h"
54 #include "gromacs/nbnxm/nbnxm.h"
55 #include "gromacs/nbnxm/nbnxm_geometry.h"
56 #include "gromacs/nbnxm/nbnxm_simd.h"
57 #include "gromacs/nbnxm/pairlist.h"
58 #include "gromacs/nbnxm/pairlist_tuning.h"
59 #include "gromacs/nbnxm/pairlistset.h"
60 #include "gromacs/simd/simd.h"
61 #include "gromacs/utility/fatalerror.h"
62 #include "gromacs/utility/logger.h"
63
64 #include "gpu_types.h"
65 #include "grid.h"
66 #include "internal.h"
67
68 namespace Nbnxm
69 {
70
71 /*! \brief Returns whether CPU SIMD support exists for the given inputrec
72  *
73  * If the return value is FALSE and fplog/cr != NULL, prints a fallback
74  * message to fplog/stderr.
75  */
76 static gmx_bool nbnxn_simd_supported(const gmx::MDLogger &mdlog,
77                                      const t_inputrec    *ir)
78 {
79     if (ir->vdwtype == evdwPME && ir->ljpme_combination_rule == eljpmeLB)
80     {
81         /* LJ PME with LB combination rule does 7 mesh operations.
82          * This so slow that we don't compile SIMD non-bonded kernels
83          * for that. */
84         GMX_LOG(mdlog.warning).asParagraph().appendText("LJ-PME with Lorentz-Berthelot is not supported with SIMD kernels, falling back to plain C kernels");
85         return FALSE;
86     }
87
88     return TRUE;
89 }
90
91 /*! \brief Returns the most suitable CPU kernel type and Ewald handling */
92 static KernelSetup
93 pick_nbnxn_kernel_cpu(const t_inputrec gmx_unused    *ir,
94                       const gmx_hw_info_t gmx_unused &hardwareInfo)
95 {
96     KernelSetup kernelSetup;
97
98     if (!GMX_SIMD)
99     {
100         kernelSetup.kernelType         = KernelType::Cpu4x4_PlainC;
101         kernelSetup.ewaldExclusionType = EwaldExclusionType::Table;
102     }
103     else
104     {
105 #ifdef GMX_NBNXN_SIMD_4XN
106         kernelSetup.kernelType = KernelType::Cpu4xN_Simd_4xN;
107 #endif
108 #ifdef GMX_NBNXN_SIMD_2XNN
109         kernelSetup.kernelType = KernelType::Cpu4xN_Simd_2xNN;
110 #endif
111
112 #if defined GMX_NBNXN_SIMD_2XNN && defined GMX_NBNXN_SIMD_4XN
113         /* We need to choose if we want 2x(N+N) or 4xN kernels.
114          * This is based on the SIMD acceleration choice and CPU information
115          * detected at runtime.
116          *
117          * 4xN calculates more (zero) interactions, but has less pair-search
118          * work and much better kernel instruction scheduling.
119          *
120          * Up till now we have only seen that on Intel Sandy/Ivy Bridge,
121          * which doesn't have FMA, both the analytical and tabulated Ewald
122          * kernels have similar pair rates for 4x8 and 2x(4+4), so we choose
123          * 2x(4+4) because it results in significantly fewer pairs.
124          * For RF, the raw pair rate of the 4x8 kernel is higher than 2x(4+4),
125          * 10% with HT, 50% without HT. As we currently don't detect the actual
126          * use of HT, use 4x8 to avoid a potential performance hit.
127          * On Intel Haswell 4x8 is always faster.
128          */
129         kernelSetup.kernelType = KernelType::Cpu4xN_Simd_4xN;
130
131         if (!GMX_SIMD_HAVE_FMA && (EEL_PME_EWALD(ir->coulombtype) ||
132                                    EVDW_PME(ir->vdwtype)))
133         {
134             /* We have Ewald kernels without FMA (Intel Sandy/Ivy Bridge).
135              * There are enough instructions to make 2x(4+4) efficient.
136              */
137             kernelSetup.kernelType = KernelType::Cpu4xN_Simd_2xNN;
138         }
139
140         if (hardwareInfo.haveAmdZenCpu)
141         {
142             /* One 256-bit FMA per cycle makes 2xNN faster */
143             kernelSetup.kernelType = KernelType::Cpu4xN_Simd_2xNN;
144         }
145 #endif      /* GMX_NBNXN_SIMD_2XNN && GMX_NBNXN_SIMD_4XN */
146
147
148         if (getenv("GMX_NBNXN_SIMD_4XN") != nullptr)
149         {
150 #ifdef GMX_NBNXN_SIMD_4XN
151             kernelSetup.kernelType = KernelType::Cpu4xN_Simd_4xN;
152 #else
153             gmx_fatal(FARGS, "SIMD 4xN kernels requested, but GROMACS has been compiled without support for these kernels");
154 #endif
155         }
156         if (getenv("GMX_NBNXN_SIMD_2XNN") != nullptr)
157         {
158 #ifdef GMX_NBNXN_SIMD_2XNN
159             kernelSetup.kernelType = KernelType::Cpu4xN_Simd_2xNN;
160 #else
161             gmx_fatal(FARGS, "SIMD 2x(N+N) kernels requested, but GROMACS has been compiled without support for these kernels");
162 #endif
163         }
164
165         /* Analytical Ewald exclusion correction is only an option in
166          * the SIMD kernel.
167          * Since table lookup's don't parallelize with SIMD, analytical
168          * will probably always be faster for a SIMD width of 8 or more.
169          * With FMA analytical is sometimes faster for a width if 4 as well.
170          * In single precision, this is faster on Bulldozer.
171          * On AMD Zen, tabulated Ewald kernels are faster on all 4 combinations
172          * of single or double precision and 128 or 256-bit AVX2.
173          */
174         if (
175 #if GMX_SIMD
176             (GMX_SIMD_REAL_WIDTH >= 8 ||
177              (GMX_SIMD_REAL_WIDTH >= 4 && GMX_SIMD_HAVE_FMA && !GMX_DOUBLE)) &&
178 #endif
179             !hardwareInfo.haveAmdZenCpu)
180         {
181             kernelSetup.ewaldExclusionType = EwaldExclusionType::Analytical;
182         }
183         else
184         {
185             kernelSetup.ewaldExclusionType = EwaldExclusionType::Table;
186         }
187         if (getenv("GMX_NBNXN_EWALD_TABLE") != nullptr)
188         {
189             kernelSetup.ewaldExclusionType = EwaldExclusionType::Table;
190         }
191         if (getenv("GMX_NBNXN_EWALD_ANALYTICAL") != nullptr)
192         {
193             kernelSetup.ewaldExclusionType = EwaldExclusionType::Analytical;
194         }
195
196     }
197
198     return kernelSetup;
199 }
200
201 const char *lookup_kernel_name(const KernelType kernelType)
202 {
203     const char *returnvalue = nullptr;
204     switch (kernelType)
205     {
206         case KernelType::NotSet:
207             returnvalue = "not set";
208             break;
209         case KernelType::Cpu4x4_PlainC:
210             returnvalue = "plain C";
211             break;
212         case KernelType::Cpu4xN_Simd_4xN:
213         case KernelType::Cpu4xN_Simd_2xNN:
214 #if GMX_SIMD
215             returnvalue = "SIMD";
216 #else  // GMX_SIMD
217             returnvalue = "not available";
218 #endif // GMX_SIMD
219             break;
220         case KernelType::Gpu8x8x8: returnvalue        = "GPU"; break;
221         case KernelType::Cpu8x8x8_PlainC: returnvalue = "plain C"; break;
222
223         default:
224             gmx_fatal(FARGS, "Illegal kernel type selected");
225     }
226     return returnvalue;
227 };
228
229 /*! \brief Returns the most suitable kernel type and Ewald handling */
230 static KernelSetup
231 pick_nbnxn_kernel(const gmx::MDLogger     &mdlog,
232                   gmx_bool                 use_simd_kernels,
233                   const gmx_hw_info_t     &hardwareInfo,
234                   const NonbondedResource &nonbondedResource,
235                   const t_inputrec        *ir,
236                   gmx_bool                 bDoNonbonded)
237 {
238     KernelSetup kernelSetup;
239
240     if (nonbondedResource == NonbondedResource::EmulateGpu)
241     {
242         kernelSetup.kernelType         = KernelType::Cpu8x8x8_PlainC;
243         kernelSetup.ewaldExclusionType = EwaldExclusionType::DecidedByGpuModule;
244
245         if (bDoNonbonded)
246         {
247             GMX_LOG(mdlog.warning).asParagraph().appendText("Emulating a GPU run on the CPU (slow)");
248         }
249     }
250     else if (nonbondedResource == NonbondedResource::Gpu)
251     {
252         kernelSetup.kernelType         = KernelType::Gpu8x8x8;
253         kernelSetup.ewaldExclusionType = EwaldExclusionType::DecidedByGpuModule;
254     }
255     else
256     {
257         if (use_simd_kernels &&
258             nbnxn_simd_supported(mdlog, ir))
259         {
260             kernelSetup = pick_nbnxn_kernel_cpu(ir, hardwareInfo);
261         }
262         else
263         {
264             kernelSetup.kernelType         = KernelType::Cpu4x4_PlainC;
265             kernelSetup.ewaldExclusionType = EwaldExclusionType::Analytical;
266         }
267     }
268
269     if (bDoNonbonded)
270     {
271         GMX_LOG(mdlog.info).asParagraph().appendTextFormatted(
272                 "Using %s %dx%d nonbonded short-range kernels",
273                 lookup_kernel_name(kernelSetup.kernelType),
274                 IClusterSizePerKernelType[kernelSetup.kernelType],
275                 JClusterSizePerKernelType[kernelSetup.kernelType]);
276
277         if (KernelType::Cpu4x4_PlainC == kernelSetup.kernelType ||
278             KernelType::Cpu8x8x8_PlainC == kernelSetup.kernelType)
279         {
280             GMX_LOG(mdlog.warning).asParagraph().appendTextFormatted(
281                     "WARNING: Using the slow %s kernels. This should\n"
282                     "not happen during routine usage on supported platforms.",
283                     lookup_kernel_name(kernelSetup.kernelType));
284         }
285     }
286
287     GMX_RELEASE_ASSERT(kernelSetup.kernelType != KernelType::NotSet &&
288                        kernelSetup.ewaldExclusionType != EwaldExclusionType::NotSet,
289                        "All kernel setup parameters should be set here");
290
291     return kernelSetup;
292 }
293
294 } // namespace Nbnxm
295
296 nonbonded_verlet_t::PairlistSets::PairlistSets(const NbnxnListParameters &listParams,
297                                                const bool                 haveMultipleDomains,
298                                                const int                  minimumIlistCountForGpuBalancing) :
299     params_(listParams),
300     minimumIlistCountForGpuBalancing_(minimumIlistCountForGpuBalancing)
301 {
302     localSet_ = std::make_unique<nbnxn_pairlist_set_t>(params_);
303
304     if (haveMultipleDomains)
305     {
306         nonlocalSet_ = std::make_unique<nbnxn_pairlist_set_t>(params_);
307     }
308 }
309
310 namespace Nbnxm
311 {
312
313 /*! \brief Gets and returns the minimum i-list count for balacing based on the GPU used or env.var. when set */
314 static int getMinimumIlistCountForGpuBalancing(gmx_nbnxn_gpu_t *nbnxmGpu)
315 {
316     int minimumIlistCount;
317
318     if (const char *env = getenv("GMX_NB_MIN_CI"))
319     {
320         char *end;
321
322         minimumIlistCount = strtol(env, &end, 10);
323         if (!end || (*end != 0) || minimumIlistCount < 0)
324         {
325             gmx_fatal(FARGS, "Invalid value passed in GMX_NB_MIN_CI=%s, non-negative integer required", env);
326         }
327
328         if (debug)
329         {
330             fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n",
331                     minimumIlistCount);
332         }
333     }
334     else
335     {
336         minimumIlistCount = gpu_min_ci_balanced(nbnxmGpu);
337         if (debug)
338         {
339             fprintf(debug, "Neighbor-list balancing parameter: %d (auto-adjusted to the number of GPU multi-processors)\n",
340                     minimumIlistCount);
341         }
342     }
343
344     return minimumIlistCount;
345 }
346
347 std::unique_ptr<nonbonded_verlet_t>
348 init_nb_verlet(const gmx::MDLogger     &mdlog,
349                gmx_bool                 bFEP_NonBonded,
350                const t_inputrec        *ir,
351                const t_forcerec        *fr,
352                const t_commrec         *cr,
353                const gmx_hw_info_t     &hardwareInfo,
354                const gmx_device_info_t *deviceInfo,
355                const gmx_mtop_t        *mtop,
356                matrix                   box)
357 {
358     const bool          emulateGpu = (getenv("GMX_EMULATE_GPU") != nullptr);
359     const bool          useGpu     = deviceInfo != nullptr;
360
361     GMX_RELEASE_ASSERT(!(emulateGpu && useGpu), "When GPU emulation is active, there cannot be a GPU assignment");
362
363     NonbondedResource nonbondedResource;
364     if (useGpu)
365     {
366         nonbondedResource = NonbondedResource::Gpu;
367     }
368     else if (emulateGpu)
369     {
370         nonbondedResource = NonbondedResource::EmulateGpu;
371     }
372     else
373     {
374         nonbondedResource = NonbondedResource::Cpu;
375     }
376
377     Nbnxm::KernelSetup kernelSetup =
378         pick_nbnxn_kernel(mdlog, fr->use_simd_kernels, hardwareInfo,
379                           nonbondedResource, ir,
380                           fr->bNonbonded);
381
382     const bool          haveMultipleDomains = (DOMAINDECOMP(cr) && cr->dd->nnodes > 1);
383
384     NbnxnListParameters listParams(kernelSetup.kernelType,
385                                    ir->rlist,
386                                    havePPDomainDecomposition(cr));
387
388     setupDynamicPairlistPruning(mdlog, ir, mtop, box, fr->ic,
389                                 &listParams);
390
391     int      enbnxninitcombrule;
392     if (fr->ic->vdwtype == evdwCUT &&
393         (fr->ic->vdw_modifier == eintmodNONE ||
394          fr->ic->vdw_modifier == eintmodPOTSHIFT) &&
395         getenv("GMX_NO_LJ_COMB_RULE") == nullptr)
396     {
397         /* Plain LJ cut-off: we can optimize with combination rules */
398         enbnxninitcombrule = enbnxninitcombruleDETECT;
399     }
400     else if (fr->ic->vdwtype == evdwPME)
401     {
402         /* LJ-PME: we need to use a combination rule for the grid */
403         if (fr->ljpme_combination_rule == eljpmeGEOM)
404         {
405             enbnxninitcombrule = enbnxninitcombruleGEOM;
406         }
407         else
408         {
409             enbnxninitcombrule = enbnxninitcombruleLB;
410         }
411     }
412     else
413     {
414         /* We use a full combination matrix: no rule required */
415         enbnxninitcombrule = enbnxninitcombruleNONE;
416     }
417
418     std::unique_ptr<nbnxn_atomdata_t> nbat =
419         std::make_unique<nbnxn_atomdata_t>(useGpu ? gmx::PinningPolicy::PinnedIfSupported : gmx::PinningPolicy::CannotBePinned);
420
421     int mimimumNumEnergyGroupNonbonded = ir->opts.ngener;
422     if (ir->opts.ngener - ir->nwall == 1)
423     {
424         /* We have only one non-wall energy group, we do not need energy group
425          * support in the non-bondeds kernels, since all non-bonded energy
426          * contributions go to the first element of the energy group matrix.
427          */
428         mimimumNumEnergyGroupNonbonded = 1;
429     }
430     nbnxn_atomdata_init(mdlog,
431                         nbat.get(),
432                         kernelSetup.kernelType,
433                         enbnxninitcombrule,
434                         fr->ntype, fr->nbfp,
435                         mimimumNumEnergyGroupNonbonded,
436                         (useGpu || emulateGpu) ? 1 : gmx_omp_nthreads_get(emntNonbonded));
437
438     gmx_nbnxn_gpu_t *gpu_nbv = nullptr;
439     int              minimumIlistCountForGpuBalancing = 0;
440     if (useGpu)
441     {
442         /* init the NxN GPU data; the last argument tells whether we'll have
443          * both local and non-local NB calculation on GPU */
444         gpu_nbv = gpu_init(deviceInfo,
445                            fr->ic,
446                            &listParams,
447                            nbat.get(),
448                            cr->nodeid,
449                            haveMultipleDomains);
450
451         minimumIlistCountForGpuBalancing = getMinimumIlistCountForGpuBalancing(gpu_nbv);
452     }
453
454     std::unique_ptr<nonbonded_verlet_t::PairlistSets> pairlistSets =
455         std::make_unique<nonbonded_verlet_t::PairlistSets>(listParams,
456                                                            haveMultipleDomains,
457                                                            minimumIlistCountForGpuBalancing);
458
459     std::unique_ptr<nbnxn_search> nbs =
460         std::make_unique<nbnxn_search>(ir->ePBC,
461                                        DOMAINDECOMP(cr) ? &cr->dd->nc : nullptr,
462                                        DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : nullptr,
463                                        bFEP_NonBonded,
464                                        gmx_omp_nthreads_get(emntPairsearch));
465
466     return std::make_unique<nonbonded_verlet_t>(std::move(pairlistSets),
467                                                 std::move(nbs),
468                                                 std::move(nbat),
469                                                 kernelSetup,
470                                                 gpu_nbv);
471 }
472
473 } // namespace Nbnxm
474
475 nonbonded_verlet_t::nonbonded_verlet_t(std::unique_ptr<PairlistSets>      pairlistSets,
476                                        std::unique_ptr<nbnxn_search>      nbs_in,
477                                        std::unique_ptr<nbnxn_atomdata_t>  nbat_in,
478                                        const Nbnxm::KernelSetup          &kernelSetup,
479                                        gmx_nbnxn_gpu_t                   *gpu_nbv_ptr) :
480     pairlistSets_(std::move(pairlistSets)),
481     nbs(std::move(nbs_in)),
482     nbat(std::move(nbat_in)),
483     kernelSetup_(kernelSetup),
484     gpu_nbv(gpu_nbv_ptr)
485 {
486     GMX_RELEASE_ASSERT(pairlistSets_, "Need valid pairlistSets");
487     GMX_RELEASE_ASSERT(nbs, "Need valid search object");
488     GMX_RELEASE_ASSERT(nbat, "Need valid atomdata object");
489 }
490
491 nonbonded_verlet_t::~nonbonded_verlet_t()
492 {
493     Nbnxm::gpu_free(gpu_nbv);
494 }