2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2015,2016,2017,2018,2019 by the GROMACS development team.
5 * Copyright (c) 2020,2021, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
37 * \brief Defines functionality for deciding whether tasks will run on GPUs.
39 * \author Mark Abraham <mark.j.abraham@gmail.com>
40 * \ingroup module_taskassignment
45 #include "decidegpuusage.h"
55 #include "gromacs/ewald/pme.h"
56 #include "gromacs/hardware/cpuinfo.h"
57 #include "gromacs/hardware/detecthardware.h"
58 #include "gromacs/hardware/hardwaretopology.h"
59 #include "gromacs/hardware/hw_info.h"
60 #include "gromacs/listed_forces/listed_forces_gpu.h"
61 #include "gromacs/mdlib/gmx_omp_nthreads.h"
62 #include "gromacs/mdlib/update_constrain_gpu.h"
63 #include "gromacs/mdtypes/commrec.h"
64 #include "gromacs/mdtypes/inputrec.h"
65 #include "gromacs/mdtypes/md_enums.h"
66 #include "gromacs/mdtypes/mdrunoptions.h"
67 #include "gromacs/pulling/pull.h"
68 #include "gromacs/taskassignment/taskassignment.h"
69 #include "gromacs/topology/mtop_util.h"
70 #include "gromacs/topology/topology.h"
71 #include "gromacs/utility/baseversion.h"
72 #include "gromacs/utility/exceptions.h"
73 #include "gromacs/utility/fatalerror.h"
74 #include "gromacs/utility/gmxassert.h"
75 #include "gromacs/utility/logger.h"
76 #include "gromacs/utility/stringutil.h"
85 //! Helper variable to localise the text of an often repeated message.
86 const char* const g_specifyEverythingFormatString =
87 "When you use mdrun -gputasks, %s must be set to non-default "
88 "values, so that the device IDs can be interpreted correctly."
90 " If you simply want to restrict which GPUs are used, then it is "
91 "better to use mdrun -gpu_id. Otherwise, setting the "
93 "CUDA_VISIBLE_DEVICES"
95 // Technically there is no portable way to do this offered by the
96 // OpenCL standard, but the only current relevant case for GROMACS
97 // is AMD OpenCL, which offers this variable.
99 # elif GMX_GPU_SYCL && GMX_SYCL_DPCPP
100 // https://github.com/intel/llvm/blob/sycl/sycl/doc/EnvironmentVariables.md
102 # elif GMX_GPU_SYCL && GMX_SYCL_HIPSYCL
103 // Not true if we use hipSYCL over CUDA or IntelLLVM, but in that case the user probably
104 // knows what they are doing.
105 // https://rocmdocs.amd.com/en/latest/Other_Solutions/Other-Solutions.html#hip-environment-variables
106 "HIP_VISIBLE_DEVICES"
108 # error "Unreachable branch"
110 " environment variable in your bash profile or job "
111 "script may be more convenient."
117 bool decideWhetherToUseGpusForNonbondedWithThreadMpi(const TaskTarget nonbondedTarget,
118 const bool haveAvailableDevices,
119 const std::vector<int>& userGpuTaskAssignment,
120 const EmulateGpuNonbonded emulateGpuNonbonded,
121 const bool buildSupportsNonbondedOnGpu,
122 const bool nonbondedOnGpuIsUseful,
123 const int numRanksPerSimulation)
125 // First, exclude all cases where we can't run NB on GPUs.
126 if (nonbondedTarget == TaskTarget::Cpu || emulateGpuNonbonded == EmulateGpuNonbonded::Yes
127 || !nonbondedOnGpuIsUseful || !buildSupportsNonbondedOnGpu)
129 // If the user required NB on GPUs, we issue an error later.
133 // We now know that NB on GPUs makes sense, if we have any.
135 if (!userGpuTaskAssignment.empty())
137 // Specifying -gputasks requires specifying everything.
138 if (nonbondedTarget == TaskTarget::Auto || numRanksPerSimulation < 1)
140 GMX_THROW(InconsistentInputError(
141 formatString(g_specifyEverythingFormatString, "-nb and -ntmpi")));
146 if (nonbondedTarget == TaskTarget::Gpu)
151 // Because this is thread-MPI, we already know about the GPUs that
152 // all potential ranks can use, and can use that in a global
153 // decision that will later be consistent.
154 // If we get here, then the user permitted or required GPUs.
155 return haveAvailableDevices;
158 bool decideWhetherToUseGpusForPmeWithThreadMpi(const bool useGpuForNonbonded,
159 const TaskTarget pmeTarget,
160 const int numDevicesToUse,
161 const std::vector<int>& userGpuTaskAssignment,
162 const gmx_hw_info_t& hardwareInfo,
163 const t_inputrec& inputrec,
164 const int numRanksPerSimulation,
165 const int numPmeRanksPerSimulation)
167 // First, exclude all cases where we can't run PME on GPUs.
168 if ((pmeTarget == TaskTarget::Cpu) || !useGpuForNonbonded || !pme_gpu_supports_build(nullptr)
169 || !pme_gpu_supports_hardware(hardwareInfo, nullptr) || !pme_gpu_supports_input(inputrec, nullptr))
171 // PME can't run on a GPU. If the user required that, we issue
176 // We now know that PME on GPUs might make sense, if we have any.
178 if (!userGpuTaskAssignment.empty())
180 // Follow the user's choice of GPU task assignment, if we
181 // can. Checking that their IDs are for compatible GPUs comes
184 // Specifying -gputasks requires specifying everything.
185 if (pmeTarget == TaskTarget::Auto || numRanksPerSimulation < 1)
187 GMX_THROW(InconsistentInputError(
188 formatString(g_specifyEverythingFormatString, "all of -nb, -pme, and -ntmpi")));
191 // PME on GPUs is only supported in a single case
192 if (pmeTarget == TaskTarget::Gpu)
194 if (((numRanksPerSimulation > 1) && (numPmeRanksPerSimulation == 0))
195 || (numPmeRanksPerSimulation > 1))
197 GMX_THROW(InconsistentInputError(
198 "When you run mdrun -pme gpu -gputasks, you must supply a PME-enabled .tpr "
199 "file and use a single PME rank."));
204 // pmeTarget == TaskTarget::Auto
205 return numRanksPerSimulation == 1;
208 // Because this is thread-MPI, we already know about the GPUs that
209 // all potential ranks can use, and can use that in a global
210 // decision that will later be consistent.
212 if (pmeTarget == TaskTarget::Gpu)
214 if (((numRanksPerSimulation > 1) && (numPmeRanksPerSimulation == 0))
215 || (numPmeRanksPerSimulation > 1))
217 GMX_THROW(NotImplementedError(
218 "PME tasks were required to run on GPUs, but that is not implemented with "
219 "more than one PME rank. Use a single rank simulation, or a separate PME rank, "
220 "or permit PME tasks to be assigned to the CPU."));
225 if (numRanksPerSimulation == 1)
227 // PME can run well on a GPU shared with NB, and we permit
228 // mdrun to default to try that.
229 return numDevicesToUse > 0;
232 if (numRanksPerSimulation < 1)
234 // Full automated mode for thread-MPI (the default). PME can
235 // run well on a GPU shared with NB, and we permit mdrun to
236 // default to it if there is only one GPU available.
237 return (numDevicesToUse == 1);
240 // Not enough support for PME on GPUs for anything else
244 bool decideWhetherToUseGpusForNonbonded(const TaskTarget nonbondedTarget,
245 const std::vector<int>& userGpuTaskAssignment,
246 const EmulateGpuNonbonded emulateGpuNonbonded,
247 const bool buildSupportsNonbondedOnGpu,
248 const bool nonbondedOnGpuIsUseful,
249 const bool gpusWereDetected)
251 if (nonbondedTarget == TaskTarget::Cpu)
253 if (!userGpuTaskAssignment.empty())
255 GMX_THROW(InconsistentInputError(
256 "A GPU task assignment was specified, but nonbonded interactions were "
257 "assigned to the CPU. Make no more than one of these choices."));
263 if (!buildSupportsNonbondedOnGpu && nonbondedTarget == TaskTarget::Gpu)
265 GMX_THROW(InconsistentInputError(
266 "Nonbonded interactions on the GPU were requested with -nb gpu, "
267 "but the GROMACS binary has been built without GPU support. "
268 "Either run without selecting GPU options, or recompile GROMACS "
269 "with GPU support enabled"));
272 // TODO refactor all these TaskTarget::Gpu checks into one place?
273 // e.g. use a subfunction that handles only the cases where
274 // TaskTargets are not Cpu?
275 if (emulateGpuNonbonded == EmulateGpuNonbonded::Yes)
277 if (nonbondedTarget == TaskTarget::Gpu)
279 GMX_THROW(InconsistentInputError(
280 "Nonbonded interactions on the GPU were required, which is inconsistent "
281 "with choosing emulation. Make no more than one of these choices."));
283 if (!userGpuTaskAssignment.empty())
286 InconsistentInputError("GPU ID usage was specified, as was GPU emulation. Make "
287 "no more than one of these choices."));
293 if (!nonbondedOnGpuIsUseful)
295 if (nonbondedTarget == TaskTarget::Gpu)
297 GMX_THROW(InconsistentInputError(
298 "Nonbonded interactions on the GPU were required, but not supported for these "
299 "simulation settings. Change your settings, or do not require using GPUs."));
305 if (!userGpuTaskAssignment.empty())
307 // Specifying -gputasks requires specifying everything.
308 if (nonbondedTarget == TaskTarget::Auto)
310 GMX_THROW(InconsistentInputError(
311 formatString(g_specifyEverythingFormatString, "-nb and -ntmpi")));
317 if (nonbondedTarget == TaskTarget::Gpu)
319 // We still don't know whether it is an error if no GPUs are found
320 // because we don't know the duty of this rank, yet. For example,
321 // a node with only PME ranks and -pme cpu is OK if there are not
326 // If we get here, then the user permitted GPUs, which we should
327 // use for nonbonded interactions.
328 return buildSupportsNonbondedOnGpu && gpusWereDetected;
331 bool decideWhetherToUseGpusForPme(const bool useGpuForNonbonded,
332 const TaskTarget pmeTarget,
333 const std::vector<int>& userGpuTaskAssignment,
334 const gmx_hw_info_t& hardwareInfo,
335 const t_inputrec& inputrec,
336 const int numRanksPerSimulation,
337 const int numPmeRanksPerSimulation,
338 const bool gpusWereDetected)
340 if (pmeTarget == TaskTarget::Cpu)
345 if (!useGpuForNonbonded)
347 if (pmeTarget == TaskTarget::Gpu)
349 GMX_THROW(NotImplementedError(
350 "PME on GPUs is only supported when nonbonded interactions run on GPUs also."));
356 if (!pme_gpu_supports_build(&message))
358 if (pmeTarget == TaskTarget::Gpu)
360 GMX_THROW(NotImplementedError("Cannot compute PME interactions on a GPU, because " + message));
364 if (!pme_gpu_supports_hardware(hardwareInfo, &message))
366 if (pmeTarget == TaskTarget::Gpu)
368 GMX_THROW(NotImplementedError("Cannot compute PME interactions on a GPU, because " + message));
372 if (!pme_gpu_supports_input(inputrec, &message))
374 if (pmeTarget == TaskTarget::Gpu)
376 GMX_THROW(NotImplementedError("Cannot compute PME interactions on a GPU, because " + message));
381 if (pmeTarget == TaskTarget::Cpu)
383 if (!userGpuTaskAssignment.empty())
385 GMX_THROW(InconsistentInputError(
386 "A GPU task assignment was specified, but PME interactions were "
387 "assigned to the CPU. Make no more than one of these choices."));
393 if (!userGpuTaskAssignment.empty())
395 // Specifying -gputasks requires specifying everything.
396 if (pmeTarget == TaskTarget::Auto)
398 GMX_THROW(InconsistentInputError(formatString(
399 g_specifyEverythingFormatString, "all of -nb, -pme, and -ntmpi"))); // TODO ntmpi?
405 // We still don't know whether it is an error if no GPUs are found
406 // because we don't know the duty of this rank, yet. For example,
407 // a node with only PME ranks and -pme cpu is OK if there are not
410 if (pmeTarget == TaskTarget::Gpu)
412 if (((numRanksPerSimulation > 1) && (numPmeRanksPerSimulation == 0))
413 || (numPmeRanksPerSimulation > 1))
415 GMX_THROW(NotImplementedError(
416 "PME tasks were required to run on GPUs, but that is not implemented with "
417 "more than one PME rank. Use a single rank simulation, or a separate PME rank, "
418 "or permit PME tasks to be assigned to the CPU."));
423 // If we get here, then the user permitted GPUs.
424 if (numRanksPerSimulation == 1)
426 // PME can run well on a single GPU shared with NB when there
427 // is one rank, so we permit mdrun to try that if we have
429 return gpusWereDetected;
432 // Not enough support for PME on GPUs for anything else
437 PmeRunMode determinePmeRunMode(const bool useGpuForPme, const TaskTarget& pmeFftTarget, const t_inputrec& inputrec)
439 if (!EEL_PME(inputrec.coulombtype))
441 return PmeRunMode::None;
446 if (pmeFftTarget == TaskTarget::Cpu)
448 return PmeRunMode::Mixed;
452 return PmeRunMode::GPU;
457 if (pmeFftTarget == TaskTarget::Gpu)
460 "Assigning FFTs to GPU requires PME to be assigned to GPU as well. With PME "
461 "on CPU you should not be using -pmefft.");
463 return PmeRunMode::CPU;
467 bool decideWhetherToUseGpusForBonded(bool useGpuForNonbonded,
469 TaskTarget bondedTarget,
470 const t_inputrec& inputrec,
471 const gmx_mtop_t& mtop,
472 int numPmeRanksPerSimulation,
473 bool gpusWereDetected)
475 if (bondedTarget == TaskTarget::Cpu)
480 std::string errorMessage;
482 if (!buildSupportsListedForcesGpu(&errorMessage))
484 if (bondedTarget == TaskTarget::Gpu)
486 GMX_THROW(InconsistentInputError(errorMessage.c_str()));
492 if (!inputSupportsListedForcesGpu(inputrec, mtop, &errorMessage))
494 if (bondedTarget == TaskTarget::Gpu)
496 GMX_THROW(InconsistentInputError(errorMessage.c_str()));
502 if (!useGpuForNonbonded)
504 if (bondedTarget == TaskTarget::Gpu)
506 GMX_THROW(InconsistentInputError(
507 "Bonded interactions on the GPU were required, but this requires that "
508 "short-ranged non-bonded interactions are also run on the GPU. Change "
509 "your settings, or do not require using GPUs."));
515 // TODO If the bonded kernels do not get fused, then performance
516 // overheads might suggest alternative choices here.
518 if (bondedTarget == TaskTarget::Gpu)
520 // We still don't know whether it is an error if no GPUs are
525 // If we get here, then the user permitted GPUs, which we should
526 // use for bonded interactions if any were detected and the CPU
527 // is busy, for which we currently only check PME or Ewald.
528 // (It would be better to dynamically assign bondeds based on timings)
529 // Note that here we assume that the auto setting of PME ranks will not
530 // choose seperate PME ranks when nonBonded are assigned to the GPU.
531 bool usingOurCpuForPmeOrEwald =
532 (EVDW_PME(inputrec.vdwtype)
533 || (EEL_PME_EWALD(inputrec.coulombtype) && !useGpuForPme && numPmeRanksPerSimulation <= 0));
535 return gpusWereDetected && usingOurCpuForPmeOrEwald;
538 bool decideWhetherToUseGpuForUpdate(const bool isDomainDecomposition,
539 const bool useUpdateGroups,
540 const PmeRunMode pmeRunMode,
541 const bool havePmeOnlyRank,
542 const bool useGpuForNonbonded,
543 const TaskTarget updateTarget,
544 const bool gpusWereDetected,
545 const t_inputrec& inputrec,
546 const gmx_mtop_t& mtop,
547 const bool useEssentialDynamics,
548 const bool doOrientationRestraints,
549 const bool haveFrozenAtoms,
551 const DevelopmentFeatureFlags& devFlags,
552 const gmx::MDLogger& mdlog)
555 // '-update cpu' overrides the environment variable, '-update auto' does not
556 if (updateTarget == TaskTarget::Cpu
557 || (updateTarget == TaskTarget::Auto && !devFlags.forceGpuUpdateDefault))
562 const bool hasAnyConstraints = gmx_mtop_interaction_count(mtop, IF_CONSTRAINT) > 0;
563 const bool pmeUsesCpu = (pmeRunMode == PmeRunMode::CPU || pmeRunMode == PmeRunMode::Mixed);
565 std::string errorMessage;
567 if (isDomainDecomposition)
569 if (hasAnyConstraints && !useUpdateGroups)
572 "Domain decomposition is only supported with constraints when update "
574 "are used. This means constraining all bonds is not supported, except for "
575 "small molecules, and box sizes close to half the pair-list cutoff are not "
584 errorMessage += "With separate PME rank(s), PME must run fully on the GPU.\n";
590 errorMessage += "Multiple time stepping is not supported.\n";
593 if (inputrec.eConstrAlg == ConstraintAlgorithm::Shake && hasAnyConstraints
594 && gmx_mtop_ftype_count(mtop, F_CONSTR) > 0)
596 errorMessage += "SHAKE constraints are not supported.\n";
598 // Using the GPU-version of update if:
599 // 1. PME is on the GPU (there should be a copy of coordinates on GPU for PME spread) or inactive, or
600 // 2. Non-bonded interactions are on the GPU.
601 if ((pmeRunMode == PmeRunMode::CPU || pmeRunMode == PmeRunMode::None) && !useGpuForNonbonded)
604 "Either PME or short-ranged non-bonded interaction tasks must run on the GPU.\n";
606 if (!gpusWereDetected)
608 errorMessage += "Compatible GPUs must have been found.\n";
612 errorMessage += "Only a CUDA build is supported.\n";
614 if (inputrec.eI != IntegrationAlgorithm::MD)
616 errorMessage += "Only the md integrator is supported.\n";
618 if (inputrec.etc == TemperatureCoupling::NoseHoover)
620 errorMessage += "Nose-Hoover temperature coupling is not supported.\n";
622 if (!(inputrec.epc == PressureCoupling::No || inputrec.epc == PressureCoupling::ParrinelloRahman
623 || inputrec.epc == PressureCoupling::Berendsen || inputrec.epc == PressureCoupling::CRescale))
626 "Only Parrinello-Rahman, Berendsen, and C-rescale pressure coupling are "
629 if (EEL_PME_EWALD(inputrec.coulombtype) && inputrec.epsilon_surface != 0)
631 // The graph is needed, but not supported
632 errorMessage += "Ewald surface correction is not supported.\n";
634 if (gmx_mtop_interaction_count(mtop, IF_VSITE) > 0)
636 errorMessage += "Virtual sites are not supported.\n";
638 if (useEssentialDynamics)
640 errorMessage += "Essential dynamics is not supported.\n";
642 if (inputrec.bPull && pull_have_constraint(*inputrec.pull))
644 errorMessage += "Constraints pulling is not supported.\n";
646 if (doOrientationRestraints)
648 // The graph is needed, but not supported
649 errorMessage += "Orientation restraints are not supported.\n";
651 if (inputrec.efep != FreeEnergyPerturbationType::No
652 && (haveFepPerturbedMasses(mtop) || havePerturbedConstraints(mtop)))
654 errorMessage += "Free energy perturbation for mass and constraints are not supported.\n";
656 const auto particleTypes = gmx_mtop_particletype_count(mtop);
657 if (particleTypes[ParticleType::Shell] > 0)
659 errorMessage += "Shells are not supported.\n";
661 if (inputrec.eSwapCoords != SwapType::No)
663 errorMessage += "Swapping the coordinates is not supported.\n";
667 errorMessage += "Re-run is not supported.\n";
670 // TODO: F_CONSTRNC is only unsupported, because isNumCoupledConstraintsSupported()
671 // does not support it, the actual CUDA LINCS code does support it
672 if (gmx_mtop_ftype_count(mtop, F_CONSTRNC) > 0)
674 errorMessage += "Non-connecting constraints are not supported\n";
676 if (!UpdateConstrainGpu::isNumCoupledConstraintsSupported(mtop))
679 "The number of coupled constraints is higher than supported in the GPU LINCS "
682 if (hasAnyConstraints && !UpdateConstrainGpu::areConstraintsSupported())
684 errorMessage += "Chosen GPU implementation does not support constraints.\n";
688 // There is a known bug with frozen atoms and GPU update, see Issue #3920.
689 errorMessage += "Frozen atoms not supported.\n";
692 if (!errorMessage.empty())
694 if (updateTarget == TaskTarget::Auto && devFlags.forceGpuUpdateDefault)
696 GMX_LOG(mdlog.warning)
699 "Update task on the GPU was required, by the "
700 "GMX_FORCE_UPDATE_DEFAULT_GPU environment variable, but the following "
701 "condition(s) were not satisfied:");
702 GMX_LOG(mdlog.warning).asParagraph().appendText(errorMessage.c_str());
703 GMX_LOG(mdlog.warning).asParagraph().appendText("Will use CPU version of update.");
705 else if (updateTarget == TaskTarget::Gpu)
707 std::string prefix = gmx::formatString(
708 "Update task on the GPU was required,\n"
709 "but the following condition(s) were not satisfied:\n");
710 GMX_THROW(InconsistentInputError((prefix + errorMessage).c_str()));
715 return (updateTarget == TaskTarget::Gpu
716 || (updateTarget == TaskTarget::Auto && devFlags.forceGpuUpdateDefault));
719 bool decideWhetherToUseGpuForHalo(const DevelopmentFeatureFlags& devFlags,
720 bool havePPDomainDecomposition,
721 bool useGpuForNonbonded,
722 bool useModularSimulator,
724 bool haveEnergyMinimization)
726 return havePPDomainDecomposition && devFlags.enableGpuHaloExchange && useGpuForNonbonded
727 && !useModularSimulator && !doRerun && !haveEnergyMinimization;