2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2015,2016,2017, 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.
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.
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.
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.
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.
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.
36 * \brief Defines utility functionality for dividing resources and
37 * checking for consistency and usefulness.
39 * \author Mark Abraham <mark.j.abraham@gmail.com>
40 * \ingroup module_taskassignment
45 #include "resourcedivision.h"
54 #include "gromacs/ewald/pme.h"
55 #include "gromacs/hardware/cpuinfo.h"
56 #include "gromacs/hardware/detecthardware.h"
57 #include "gromacs/hardware/hardwaretopology.h"
58 #include "gromacs/hardware/hw_info.h"
59 #include "gromacs/math/functions.h"
60 #include "gromacs/mdlib/gmx_omp_nthreads.h"
61 #include "gromacs/mdtypes/commrec.h"
62 #include "gromacs/mdtypes/inputrec.h"
63 #include "gromacs/mdtypes/md_enums.h"
64 #include "gromacs/topology/mtop_util.h"
65 #include "gromacs/topology/topology.h"
66 #include "gromacs/utility/baseversion.h"
67 #include "gromacs/utility/fatalerror.h"
68 #include "gromacs/utility/gmxassert.h"
69 #include "gromacs/utility/logger.h"
70 #include "gromacs/utility/stringutil.h"
73 /* DISCLAIMER: All the atom count and thread numbers below are heuristic.
74 * The real switching points will depend on the system simulation,
75 * the algorithms used and the hardware it's running on, as well as if there
76 * are other jobs running on the same machine. We try to take into account
77 * factors that have a large influence, such as recent Intel CPUs being
78 * much better at wide multi-threading. The remaining factors should
79 * (hopefully) have a small influence, such that the performance just before
80 * and after a switch point doesn't change too much.
83 //! Constant used to help minimize preprocessed code
84 static const bool bHasOmpSupport = GMX_OPENMP;
86 /*! \brief The minimum number of atoms per thread-MPI thread when GPUs
87 * are present. With fewer atoms than this, the number of thread-MPI
88 * ranks will get lowered.
90 static const int min_atoms_per_mpi_thread = 90;
91 /*! \brief The minimum number of atoms per GPU with thread-MPI
92 * active. With fewer atoms than this, the number of thread-MPI ranks
95 static const int min_atoms_per_gpu = 900;
98 /*! \brief Constants for implementing default divisions of threads */
100 /* TODO choose nthreads_omp based on hardware topology
101 when we have a hardware topology detection library */
102 /* First we consider the case of no MPI (1 MPI rank).
103 * In general, when running up to 8 threads, OpenMP should be faster.
104 * Note: on AMD Bulldozer we should avoid running OpenMP over two dies.
105 * On Intel>=Nehalem running OpenMP on a single CPU is always faster,
106 * even on two CPUs it's usually faster (but with many OpenMP threads
107 * it could be faster not to use HT, currently we always use HT).
108 * On Nehalem/Westmere we want to avoid running 16 threads over
109 * two CPUs with HT, so we need a limit<16; thus we use 12.
110 * A reasonable limit for Intel Sandy and Ivy bridge,
111 * not knowing the topology, is 16 threads.
112 * Below we check for Intel and AVX, which for now includes
113 * Sandy/Ivy Bridge, Has/Broadwell. By checking for AVX instead of
114 * model numbers we ensure also future Intel CPUs are covered.
116 const int nthreads_omp_faster_default = 8;
117 const int nthreads_omp_faster_Nehalem = 12;
118 const int nthreads_omp_faster_Intel_AVX = 16;
119 const int nthreads_omp_faster_AMD_Ryzen = 16;
120 /* For CPU only runs the fastest options are usually MPI or OpenMP only.
121 * With one GPU, using MPI only is almost never optimal, so we need to
122 * compare running pure OpenMP with combined MPI+OpenMP. This means higher
123 * OpenMP threads counts can still be ok. Multiplying the numbers above
124 * by a factor of 2 seems to be a good estimate.
126 const int nthreads_omp_faster_gpu_fac = 2;
128 /* This is the case with MPI (2 or more MPI PP ranks).
129 * By default we will terminate with a fatal error when more than 8
130 * OpenMP thread are (indirectly) requested, since using less threads
131 * nearly always results in better performance.
132 * With thread-mpi and multiple GPUs or one GPU and too many threads
133 * we first try 6 OpenMP threads and then less until the number of MPI ranks
134 * is divisible by the number of GPUs.
136 #if GMX_OPENMP && GMX_MPI
137 const int nthreads_omp_mpi_ok_max = 8;
138 const int nthreads_omp_mpi_ok_min_cpu = 1;
140 const int nthreads_omp_mpi_ok_min_gpu = 2;
141 const int nthreads_omp_mpi_target_max = 6;
145 /*! \brief Returns the maximum OpenMP thread count for which using a single MPI rank
146 * should be faster than using multiple ranks with the same total thread count.
148 static int nthreads_omp_faster(const gmx::CpuInfo &cpuInfo, gmx_bool bUseGPU)
152 if (cpuInfo.vendor() == gmx::CpuInfo::Vendor::Intel &&
153 cpuInfo.feature(gmx::CpuInfo::Feature::X86_Avx))
155 nth = nthreads_omp_faster_Intel_AVX;
157 else if (gmx::cpuIsX86Nehalem(cpuInfo))
160 nth = nthreads_omp_faster_Nehalem;
162 else if (cpuInfo.vendor() == gmx::CpuInfo::Vendor::Amd && cpuInfo.family() >= 23)
165 nth = nthreads_omp_faster_AMD_Ryzen;
169 nth = nthreads_omp_faster_default;
174 nth *= nthreads_omp_faster_gpu_fac;
177 nth = std::min(nth, GMX_OPENMP_MAX_THREADS);
182 /*! \brief Returns that maximum OpenMP thread count that passes the efficiency check */
183 gmx_unused static int nthreads_omp_efficient_max(int gmx_unused nrank,
184 const gmx::CpuInfo &cpuInfo,
187 #if GMX_OPENMP && GMX_MPI
190 return nthreads_omp_mpi_ok_max;
195 return nthreads_omp_faster(cpuInfo, bUseGPU);
199 /*! \brief Return the number of thread-MPI ranks to use.
200 * This is chosen such that we can always obey our own efficiency checks.
202 gmx_unused static int get_tmpi_omp_thread_division(const gmx_hw_info_t *hwinfo,
203 const gmx_hw_opt_t &hw_opt,
208 const gmx::CpuInfo &cpuInfo = *hwinfo->cpuInfo;
210 GMX_RELEASE_ASSERT(nthreads_tot > 0, "There must be at least one thread per rank");
212 /* There are no separate PME nodes here, as we ensured in
213 * check_and_update_hw_opt that nthreads_tmpi>0 with PME nodes
214 * and a conditional ensures we would not have ended up here.
215 * Note that separate PME nodes might be switched on later.
221 /* When the user sets nthreads_omp, we can end up oversubscribing CPU cores
222 * if we simply start as many ranks as GPUs. To avoid this, we start as few
223 * tMPI ranks as necessary to avoid oversubscription and instead leave GPUs idle.
224 * If the user does not set the number of OpenMP threads, nthreads_omp==0 and
225 * this code has no effect.
227 GMX_RELEASE_ASSERT(hw_opt.nthreads_omp >= 0, "nthreads_omp is negative, but previous checks should have prevented this");
228 while (nrank*hw_opt.nthreads_omp > hwinfo->nthreads_hw_avail && nrank > 1)
233 if (nthreads_tot < nrank)
235 /* #thread < #gpu is very unlikely, but if so: waste gpu(s) */
236 nrank = nthreads_tot;
238 else if (nthreads_tot > nthreads_omp_faster(cpuInfo, ngpu > 0) ||
239 (ngpu > 1 && nthreads_tot/ngpu > nthreads_omp_mpi_target_max))
241 /* The high OpenMP thread count will likely result in sub-optimal
242 * performance. Increase the rank count to reduce the thread count
243 * per rank. This will lead to GPU sharing by MPI ranks/threads.
247 /* Increase the rank count as long as have we more than 6 OpenMP
248 * threads per rank or the number of hardware threads is not
249 * divisible by the rank count. Don't go below 2 OpenMP threads.
257 while (nthreads_tot/nrank > nthreads_omp_mpi_target_max ||
258 (nthreads_tot/(ngpu*(nshare + 1)) >= nthreads_omp_mpi_ok_min_gpu && nthreads_tot % nrank != 0));
261 else if (hw_opt.nthreads_omp > 0)
263 /* Here we could oversubscribe, when we do, we issue a warning later */
264 nrank = std::max(1, nthreads_tot/hw_opt.nthreads_omp);
268 if (nthreads_tot <= nthreads_omp_faster(cpuInfo, ngpu > 0))
270 /* Use pure OpenMP parallelization */
275 /* Don't use OpenMP parallelization */
276 nrank = nthreads_tot;
283 //! Return whether hyper threading is enabled.
285 gmxSmtIsEnabled(const gmx::HardwareTopology &hwTop)
287 return (hwTop.supportLevel() >= gmx::HardwareTopology::SupportLevel::Basic && hwTop.machine().sockets[0].cores[0].hwThreads.size() > 1);
293 //! Handles checks for algorithms that must use a single rank.
294 class SingleRankChecker
298 SingleRankChecker() : value_(false), reasons_() {}
299 /*! \brief Call this function for each possible condition
300 under which a single rank is required, along with a string
301 describing the constraint when it is applied. */
302 void applyConstraint(bool condition, const char *description)
307 reasons_.push_back(gmx::formatString("%s only supports a single rank.", description));
310 //! After applying any conditions, is a single rank required?
311 bool mustUseOneRank() const
315 /*! \brief Return a formatted string to use when writing a
316 message when a single rank is required, (or empty if no
317 constraint exists.) */
318 std::string getMessage() const
320 return formatAndJoin(reasons_, "\n", gmx::IdentityFormatter());
324 std::vector<std::string> reasons_;
329 /* Get the number of MPI ranks to use for thread-MPI based on how many
330 * were requested, which algorithms we're using,
331 * and how many particles there are.
332 * At the point we have already called check_and_update_hw_opt.
333 * Thus all options should be internally consistent and consistent
334 * with the hardware, except that ntmpi could be larger than #GPU.
336 int get_nthreads_mpi(const gmx_hw_info_t *hwinfo,
337 gmx_hw_opt_t *hw_opt,
338 const std::vector<int> &gpuIdsToUse,
341 const t_inputrec *inputrec,
342 const gmx_mtop_t *mtop,
343 const gmx::MDLogger &mdlog,
346 int nthreads_hw, nthreads_tot_max, nrank, ngpu;
347 int min_atoms_per_mpi_rank;
349 const gmx::CpuInfo &cpuInfo = *hwinfo->cpuInfo;
350 const gmx::HardwareTopology &hwTop = *hwinfo->hardwareTopology;
354 GMX_RELEASE_ASSERT((EEL_PME(inputrec->coulombtype) || EVDW_PME(inputrec->vdwtype)) &&
355 pme_gpu_supports_input(inputrec, nullptr),
356 "PME can't be on GPUs unless we are using PME");
358 // PME on GPUs supports a single PME rank with PP running on the same or few other ranks.
359 // For now, let's treat separate PME GPU rank as opt-in.
360 if (hw_opt->nthreads_tmpi < 1)
367 /* Check if an algorithm does not support parallel simulation. */
368 // TODO This might work better if e.g. implemented algorithms
369 // had to define a function that returns such requirements,
370 // and a description string.
371 SingleRankChecker checker;
372 checker.applyConstraint(inputrec->eI == eiLBFGS, "L-BFGS minimization");
373 checker.applyConstraint(inputrec->coulombtype == eelEWALD, "Plain Ewald electrostatics");
374 checker.applyConstraint(doMembed, "Membrane embedding");
375 bool useOrientationRestraints = (gmx_mtop_ftype_count(mtop, F_ORIRES) > 0);
376 checker.applyConstraint(useOrientationRestraints, "Orientation restraints");
377 if (checker.mustUseOneRank())
379 std::string message = checker.getMessage();
380 if (hw_opt->nthreads_tmpi > 1)
382 gmx_fatal(FARGS, "%s However, you asked for more than 1 thread-MPI rank, so mdrun cannot continue. Choose a single rank, or a different algorithm.", message.c_str());
384 GMX_LOG(mdlog.warning).asParagraph().appendTextFormatted("%s Choosing to use only a single thread-MPI rank.", message.c_str());
389 if (hw_opt->nthreads_tmpi > 0)
391 /* Trivial, return the user's choice right away */
392 return hw_opt->nthreads_tmpi;
395 // Now implement automatic selection of number of thread-MPI ranks
396 nthreads_hw = hwinfo->nthreads_hw_avail;
398 if (nthreads_hw <= 0)
400 /* This should normally not happen, but if it does, we handle it */
401 gmx_fatal(FARGS, "The number of available hardware threads can not be detected, please specify the number of MPI ranks and the number of OpenMP threads (if supported) manually with options -ntmpi and -ntomp, respectively");
404 /* How many total (#tMPI*#OpenMP) threads can we start? */
405 if (hw_opt->nthreads_tot > 0)
407 nthreads_tot_max = hw_opt->nthreads_tot;
411 nthreads_tot_max = nthreads_hw;
414 /* nonbondedOnGpu might be false e.g. because this simulation uses
415 * the group scheme, or is a rerun with energy groups. */
416 ngpu = (nonbondedOnGpu ? static_cast<int>(gpuIdsToUse.size()) : 0);
418 if (inputrec->cutoff_scheme == ecutsGROUP)
420 /* We checked this before, but it doesn't hurt to do it once more */
421 GMX_RELEASE_ASSERT(hw_opt->nthreads_omp == 1, "The group scheme only supports one OpenMP thread per rank");
425 get_tmpi_omp_thread_division(hwinfo, *hw_opt, nthreads_tot_max, ngpu);
427 if (inputrec->eI == eiNM || EI_TPI(inputrec->eI))
429 /* Dims/steps are divided over the nodes iso splitting the atoms.
430 * With NM we can't have more ranks than #atoms*#dim. With TPI it's
431 * unlikely we have fewer atoms than ranks, and if so, communication
432 * would become a bottleneck, so we set the limit to 1 atom/rank.
434 min_atoms_per_mpi_rank = 1;
440 min_atoms_per_mpi_rank = min_atoms_per_gpu;
444 min_atoms_per_mpi_rank = min_atoms_per_mpi_thread;
448 if (mtop->natoms/nrank < min_atoms_per_mpi_rank)
452 /* the rank number was chosen automatically, but there are too few
453 atoms per rank, so we need to reduce the rank count */
454 nrank_new = std::max(1, mtop->natoms/min_atoms_per_mpi_rank);
456 /* Avoid partial use of Hyper-Threading */
457 if (gmxSmtIsEnabled(hwTop) &&
458 nrank_new > nthreads_hw/2 && nrank_new < nthreads_hw)
460 nrank_new = nthreads_hw/2;
463 /* If the user specified the total thread count, ensure this is
464 * divisible by the number of ranks.
465 * It is quite likely that we have too many total threads compared
466 * to the size of the system, but if the user asked for this many
467 * threads we should respect that.
469 while (hw_opt->nthreads_tot > 0 &&
470 hw_opt->nthreads_tot % nrank_new != 0)
475 /* Avoid large prime numbers in the rank count */
478 /* Use only 6,8,10 with additional factors of 2 */
482 while (3*fac*2 <= nrank_new)
487 nrank_new = (nrank_new/fac)*fac;
491 /* Avoid 5, since small system won't fit 5 domains along
492 * a dimension. This might lead to waisting some cores, but this
493 * will have a small impact in this regime of very small systems.
503 /* We reduced the number of tMPI ranks, which means we might violate
504 * our own efficiency checks if we simply use all hardware threads.
506 if (bHasOmpSupport && hw_opt->nthreads_omp <= 0 && hw_opt->nthreads_tot <= 0)
508 /* The user set neither the total nor the OpenMP thread count,
509 * we should use all hardware threads, unless we will violate
510 * our own efficiency limitation on the thread count.
514 nt_omp_max = nthreads_omp_efficient_max(nrank, cpuInfo, ngpu >= 1);
516 if (nrank*nt_omp_max < hwinfo->nthreads_hw_avail)
518 /* Limit the number of OpenMP threads to start */
519 hw_opt->nthreads_omp = nt_omp_max;
523 fprintf(stderr, "\n");
524 fprintf(stderr, "NOTE: Parallelization is limited by the small number of atoms,\n");
525 fprintf(stderr, " only starting %d thread-MPI ranks.\n", nrank);
526 fprintf(stderr, " You can use the -nt and/or -ntmpi option to optimize the number of threads.\n\n");
533 void check_resource_division_efficiency(const gmx_hw_info_t *hwinfo,
534 bool willUsePhysicalGpu,
535 gmx_bool bNtOmpOptionSet,
537 const gmx::MDLogger &mdlog)
539 GMX_UNUSED_VALUE(hwinfo);
540 #if GMX_OPENMP && GMX_MPI
541 int nth_omp_min, nth_omp_max;
544 const char *mpi_option = " (option -ntmpi)";
546 const char *mpi_option = "";
549 /* This function should be called after thread-MPI (when configured) and
550 * OpenMP have been initialized. Check that here.
553 GMX_RELEASE_ASSERT(nthreads_omp_faster_default >= nthreads_omp_mpi_ok_max, "Inconsistent OpenMP thread count default values");
555 GMX_RELEASE_ASSERT(gmx_omp_nthreads_get(emntDefault) >= 1, "Must have at least one OpenMP thread");
557 nth_omp_min = gmx_omp_nthreads_get(emntDefault);
558 nth_omp_max = gmx_omp_nthreads_get(emntDefault);
560 bool anyRankIsUsingGpus = willUsePhysicalGpu;
561 /* Thread-MPI seems to have a bug with reduce on 1 node, so use a cond. */
562 if (cr->nnodes + cr->npmenodes > 1)
564 int count[3], count_max[3];
566 count[0] = -nth_omp_min;
567 count[1] = nth_omp_max;
568 count[2] = willUsePhysicalGpu;
570 MPI_Allreduce(count, count_max, 3, MPI_INT, MPI_MAX, cr->mpi_comm_mysim);
572 /* In case of an inhomogeneous run setup we use the maximum counts */
573 nth_omp_min = -count_max[0];
574 nth_omp_max = count_max[1];
575 anyRankIsUsingGpus = count_max[2] > 0;
578 int nthreads_omp_mpi_ok_min;
580 if (!anyRankIsUsingGpus)
582 nthreads_omp_mpi_ok_min = nthreads_omp_mpi_ok_min_cpu;
586 /* With GPUs we set the minimum number of OpenMP threads to 2 to catch
587 * cases where the user specifies #ranks == #cores.
589 nthreads_omp_mpi_ok_min = nthreads_omp_mpi_ok_min_gpu;
592 if (DOMAINDECOMP(cr) && cr->nnodes > 1)
594 if (nth_omp_max < nthreads_omp_mpi_ok_min ||
595 nth_omp_max > nthreads_omp_mpi_ok_max)
597 /* Note that we print target_max here, not ok_max */
598 sprintf(buf, "Your choice of number of MPI ranks and amount of resources results in using %d OpenMP threads per rank, which is most likely inefficient. The optimum is usually between %d and %d threads per rank.",
600 nthreads_omp_mpi_ok_min,
601 nthreads_omp_mpi_target_max);
605 GMX_LOG(mdlog.warning).asParagraph().appendTextFormatted("NOTE: %s", buf);
609 /* This fatal error, and the one below, is nasty, but it's
610 * probably the only way to ensure that all users don't waste
611 * a lot of resources, since many users don't read logs/stderr.
613 gmx_fatal(FARGS, "%s If you want to run with this setup, specify the -ntomp option. But we suggest to change the number of MPI ranks%s.", buf, mpi_option);
617 #else /* GMX_OPENMP && GMX_MPI */
618 /* No OpenMP and/or MPI: it doesn't make much sense to check */
619 GMX_UNUSED_VALUE(bNtOmpOptionSet);
620 GMX_UNUSED_VALUE(willUsePhysicalGpu);
621 GMX_UNUSED_VALUE(cr);
622 /* Check if we have more than 1 physical core, if detected,
623 * or more than 1 hardware thread if physical cores were not detected.
625 if (!GMX_OPENMP && !GMX_MPI && hwinfo->hardwareTopology->numberOfCores() > 1)
627 GMX_LOG(mdlog.warning).asParagraph().appendText("NOTE: GROMACS was compiled without OpenMP and (thread-)MPI support, can only use a single CPU core");
629 #endif /* GMX_OPENMP && GMX_MPI */
633 //! Dump a \c hw_opt to \c fp.
634 static void print_hw_opt(FILE *fp, const gmx_hw_opt_t *hw_opt)
636 fprintf(fp, "hw_opt: nt %d ntmpi %d ntomp %d ntomp_pme %d gpu_id '%s' gputasks '%s'\n",
637 hw_opt->nthreads_tot,
638 hw_opt->nthreads_tmpi,
639 hw_opt->nthreads_omp,
640 hw_opt->nthreads_omp_pme,
641 hw_opt->gpuIdsAvailable.c_str(),
642 hw_opt->userGpuTaskAssignment.c_str());
645 void check_and_update_hw_opt_1(gmx_hw_opt_t *hw_opt,
649 /* Currently hw_opt only contains default settings or settings supplied
650 * by the user on the command line.
652 if (hw_opt->nthreads_omp < 0)
654 gmx_fatal(FARGS, "The number of OpenMP threads supplied on the command line is %d, which is negative and not allowed", hw_opt->nthreads_omp);
657 /* Check for OpenMP settings stored in environment variables, which can
658 * potentially be different on different MPI ranks.
660 gmx_omp_nthreads_read_env(&hw_opt->nthreads_omp, SIMMASTER(cr));
662 /* Check restrictions on the user supplied options before modifying them.
663 * TODO: Put the user values in a const struct and preserve them.
666 if (hw_opt->nthreads_tot > 0)
668 gmx_fatal(FARGS, "Setting the total number of threads is only supported with thread-MPI and GROMACS was compiled without thread-MPI");
670 if (hw_opt->nthreads_tmpi > 0)
672 gmx_fatal(FARGS, "Setting the number of thread-MPI ranks is only supported with thread-MPI and GROMACS was compiled without thread-MPI");
676 /* With thread-MPI the master thread sets hw_opt->totNumThreadsIsAuto.
677 * The other threads receive a partially processed hw_opt from the master
678 * thread and should not set hw_opt->totNumThreadsIsAuto again.
680 if (!GMX_THREAD_MPI || SIMMASTER(cr))
682 /* Check if mdrun is free to choose the total number of threads */
683 hw_opt->totNumThreadsIsAuto = (hw_opt->nthreads_omp == 0 && hw_opt->nthreads_omp_pme == 0 && hw_opt->nthreads_tot == 0);
688 /* Check restrictions on PME thread related options set by the user */
690 if (hw_opt->nthreads_omp_pme > 0 && hw_opt->nthreads_omp <= 0)
692 gmx_fatal(FARGS, "You need to specify -ntomp in addition to -ntomp_pme");
695 if (hw_opt->nthreads_omp_pme >= 1 &&
696 hw_opt->nthreads_omp_pme != hw_opt->nthreads_omp &&
699 /* This can result in a fatal error on many MPI ranks,
700 * but since the thread count can differ per rank,
701 * we can't easily avoid this.
703 gmx_fatal(FARGS, "You need to explicitly specify the number of PME ranks (-npme) when using different number of OpenMP threads for PP and PME ranks");
708 /* GROMACS was configured without OpenMP support */
710 if (hw_opt->nthreads_omp > 1 || hw_opt->nthreads_omp_pme > 1)
712 gmx_fatal(FARGS, "More than 1 OpenMP thread requested, but GROMACS was compiled without OpenMP support");
714 hw_opt->nthreads_omp = 1;
715 hw_opt->nthreads_omp_pme = 1;
718 if (hw_opt->nthreads_tot > 0 && hw_opt->nthreads_omp_pme <= 0)
720 /* We have the same number of OpenMP threads for PP and PME ranks,
721 * thus we can perform several consistency checks.
723 if (hw_opt->nthreads_tmpi > 0 &&
724 hw_opt->nthreads_omp > 0 &&
725 hw_opt->nthreads_tot != hw_opt->nthreads_tmpi*hw_opt->nthreads_omp)
727 gmx_fatal(FARGS, "The total number of threads requested (%d) does not match the thread-MPI ranks (%d) times the OpenMP threads (%d) requested",
728 hw_opt->nthreads_tot, hw_opt->nthreads_tmpi, hw_opt->nthreads_omp);
731 if (hw_opt->nthreads_tmpi > 0 &&
732 hw_opt->nthreads_tot % hw_opt->nthreads_tmpi != 0)
734 gmx_fatal(FARGS, "The total number of threads requested (%d) is not divisible by the number of thread-MPI ranks requested (%d)",
735 hw_opt->nthreads_tot, hw_opt->nthreads_tmpi);
738 if (hw_opt->nthreads_omp > 0 &&
739 hw_opt->nthreads_tot % hw_opt->nthreads_omp != 0)
741 gmx_fatal(FARGS, "The total number of threads requested (%d) is not divisible by the number of OpenMP threads requested (%d)",
742 hw_opt->nthreads_tot, hw_opt->nthreads_omp);
746 if (hw_opt->nthreads_tot > 0)
748 if (hw_opt->nthreads_omp > hw_opt->nthreads_tot)
750 gmx_fatal(FARGS, "You requested %d OpenMP threads with %d total threads. Choose a total number of threads that is a multiple of the number of OpenMP threads.",
751 hw_opt->nthreads_omp, hw_opt->nthreads_tot);
754 if (hw_opt->nthreads_tmpi > hw_opt->nthreads_tot)
756 gmx_fatal(FARGS, "You requested %d thread-MPI ranks with %d total threads. Choose a total number of threads that is a multiple of the number of thread-MPI ranks.",
757 hw_opt->nthreads_tmpi, hw_opt->nthreads_tot);
763 print_hw_opt(debug, hw_opt);
766 /* Asserting this simplifies the hardware resource division later
768 GMX_RELEASE_ASSERT(!(hw_opt->nthreads_omp_pme >= 1 && hw_opt->nthreads_omp <= 0),
769 "PME thread count should only be set when the normal thread count is also set");
772 void check_and_update_hw_opt_2(gmx_hw_opt_t *hw_opt,
775 if (cutoff_scheme == ecutsGROUP)
777 /* We only have OpenMP support for PME only nodes */
778 if (hw_opt->nthreads_omp > 1)
780 gmx_fatal(FARGS, "OpenMP threads have been requested with cut-off scheme %s, but these are only supported with cut-off scheme %s",
781 ecutscheme_names[cutoff_scheme],
782 ecutscheme_names[ecutsVERLET]);
784 hw_opt->nthreads_omp = 1;
788 void checkAndUpdateRequestedNumOpenmpThreads(gmx_hw_opt_t *hw_opt,
789 const gmx_hw_info_t &hwinfo,
791 PmeRunMode pmeRunMode,
792 const gmx_mtop_t &mtop)
795 GMX_RELEASE_ASSERT(hw_opt->nthreads_tmpi >= 1, "Must have at least one thread-MPI rank");
797 /* If the user set the total number of threads on the command line
798 * and did not specify the number of OpenMP threads, set the latter here.
800 if (hw_opt->nthreads_tot > 0 && hw_opt->nthreads_omp <= 0)
802 hw_opt->nthreads_omp = hw_opt->nthreads_tot/hw_opt->nthreads_tmpi;
804 if (!bHasOmpSupport && hw_opt->nthreads_omp > 1)
806 gmx_fatal(FARGS, "You (indirectly) asked for OpenMP threads by setting -nt > -ntmpi, but GROMACS was compiled without OpenMP support");
811 /* With both non-bonded and PME on GPU, the work left on the CPU is often
812 * (much) slower with SMT than without SMT. This is mostly the case with
813 * few atoms per core. Thus, if the number of threads is set to auto,
814 * we turn off SMT in that case. Note that PME on GPU implies that also
815 * the non-bonded are computed on the GPU.
816 * We only need to do this when the number of hardware theads is larger
817 * than the number of cores. Note that a queuing system could limit
818 * the number of hardware threads available, but we are not trying to be
819 * too smart here in that case.
821 /* The thread reduction and synchronization costs go up roughy quadratically
822 * with the threads count, so we apply a threshold quadratic in #cores.
823 * Also more cores per GPU usually means the CPU gets faster than the GPU.
824 * The number 1000 atoms per core^2 is a reasonable threshold
825 * for Intel x86 and AMD Threadripper.
827 constexpr int c_numAtomsPerCoreSquaredSmtThreshold = 1000;
829 /* Prepare conditions for deciding if we should disable SMT.
830 * We currently only limit SMT for simulations using a single rank.
831 * TODO: Consider limiting also for multi-rank simulations.
833 bool canChooseNumOpenmpThreads = (bHasOmpSupport && hw_opt->nthreads_omp <= 0);
834 bool haveSmtSupport = (hwinfo.hardwareTopology->supportLevel() >= gmx::HardwareTopology::SupportLevel::Basic &&
835 hwinfo.hardwareTopology->machine().logicalProcessorCount > hwinfo.hardwareTopology->numberOfCores());
836 bool simRunsSingleRankNBAndPmeOnGpu = (cr->nnodes == 1 && pmeRunMode == PmeRunMode::GPU);
838 if (canChooseNumOpenmpThreads && haveSmtSupport &&
839 simRunsSingleRankNBAndPmeOnGpu)
841 /* Note that the queing system might have limited us from using
842 * all detected ncore_tot physical cores. We are currently not
843 * checking for that here.
845 int numRanksTot = cr->nnodes*(MULTISIM(cr) ? cr->ms->nsim : 1);
846 int numAtomsPerRank = mtop.natoms/cr->nnodes;
847 int numCoresPerRank = hwinfo.ncore_tot/numRanksTot;
848 if (numAtomsPerRank < c_numAtomsPerCoreSquaredSmtThreshold*gmx::square(numCoresPerRank))
850 int numRanksInThisNode = (cr ? cr->nrank_intranode : 1);
851 /* Choose one OpenMP thread per physical core */
852 hw_opt->nthreads_omp = std::max(1, hwinfo.hardwareTopology->numberOfCores()/numRanksInThisNode);
856 GMX_RELEASE_ASSERT(bHasOmpSupport || hw_opt->nthreads_omp == 1, "Without OpenMP support, only one thread per rank can be used");
858 /* We are done with updating nthreads_omp, we can set nthreads_omp_pme */
859 if (hw_opt->nthreads_omp_pme <= 0 && hw_opt->nthreads_omp > 0)
861 hw_opt->nthreads_omp_pme = hw_opt->nthreads_omp;
866 print_hw_opt(debug, hw_opt);
870 void checkHardwareOversubscription(int numThreadsOnThisRank,
871 const gmx::HardwareTopology &hwTop,
873 const gmx::MDLogger &mdlog)
875 if (hwTop.supportLevel() < gmx::HardwareTopology::SupportLevel::LogicalProcessorCount)
877 /* There is nothing we can check */
881 int numRanksOnThisNode = 1;
882 int numThreadsOnThisNode = numThreadsOnThisRank;
884 if (PAR(cr) || MULTISIM(cr))
886 /* Count the threads within this physical node */
887 MPI_Comm_size(cr->mpi_comm_physicalnode, &numRanksOnThisNode);
888 MPI_Allreduce(&numThreadsOnThisRank, &numThreadsOnThisNode, 1, MPI_INT, MPI_SUM, cr->mpi_comm_physicalnode);
892 if (numThreadsOnThisNode > hwTop.machine().logicalProcessorCount)
894 std::string mesg = "WARNING: ";
897 mesg += gmx::formatString("On rank %d: o", cr->sim_nodeid);
903 mesg += gmx::formatString("versubscribing the available %d logical CPU cores", hwTop.machine().logicalProcessorCount);
908 mesg += gmx::formatString(" with %d ", numThreadsOnThisNode);
909 if (numRanksOnThisNode == numThreadsOnThisNode)
913 mesg += "thread-MPI threads.";
917 mesg += "MPI processes.";
924 mesg += "\n This will cause considerable performance loss.";
925 /* Note that only the master rank logs to stderr and only ranks
926 * with an open log file write to log.
927 * TODO: When we have a proper parallel logging framework,
928 * the framework should add the rank and node numbers.
930 GMX_LOG(mdlog.warning).asParagraph().appendTextFormatted(mesg.c_str());