Fix random typos
[alexxy/gromacs.git] / src / gromacs / mdlib / gmx_omp_nthreads.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016 by the GROMACS development team.
5  * Copyright (c) 2017,2018,2019,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.
9  *
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.
14  *
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.
19  *
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.
24  *
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.
32  *
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.
35  */
36
37 #include "gmxpre.h"
38
39 #include "gmx_omp_nthreads.h"
40
41 #include "config.h"
42
43 #include <cstdio>
44 #include <cstdlib>
45 #include <cstring>
46
47 #include "gromacs/gmxlib/network.h"
48 #include "gromacs/mdtypes/commrec.h"
49 #include "gromacs/utility/cstringutil.h"
50 #include "gromacs/utility/enumerationhelpers.h"
51 #include "gromacs/utility/fatalerror.h"
52 #include "gromacs/utility/gmxassert.h"
53 #include "gromacs/utility/gmxomp.h"
54 #include "gromacs/utility/logger.h"
55 #include "gromacs/utility/programcontext.h"
56
57 /** Structure with the number of threads for each OpenMP multi-threaded
58  *  algorithmic module in mdrun. */
59 typedef struct
60 {
61     int gnth;     /**< Global num. of threads per PP or PP+PME process/tMPI thread. */
62     int gnth_pme; /**< Global num. of threads per PME only process/tMPI thread. */
63
64     gmx::EnumerationArray<ModuleMultiThread, int> nth; /**< Number of threads for each module, indexed with module_nth_t */
65 } omp_module_nthreads_t;
66
67 /** Names of environment variables to set the per module number of threads.
68  *
69  *  Indexed with the values of module_nth_t.
70  * */
71 static const char* enumValueToEnvVariableString(ModuleMultiThread enumValue)
72 {
73     constexpr gmx::EnumerationArray<ModuleMultiThread, const char*> moduleMultiThreadEnvVariableNames = {
74         "GMX_DEFAULT_NUM_THREADS should never be set",
75         "GMX_DOMDEC_NUM_THREADS",
76         "GMX_PAIRSEARCH_NUM_THREADS",
77         "GMX_NONBONDED_NUM_THREADS",
78         "GMX_LISTED_FORCES_NUM_THREADS",
79         "GMX_PME_NUM_THREADS",
80         "GMX_UPDATE_NUM_THREADS",
81         "GMX_VSITE_NUM_THREADS",
82         "GMX_LINCS_NUM_THREADS",
83         "GMX_SETTLE_NUM_THREADS"
84     };
85     return moduleMultiThreadEnvVariableNames[enumValue];
86 }
87
88 /** Names of the modules. */
89 static const char* enumValueToString(ModuleMultiThread enumValue)
90 {
91     constexpr gmx::EnumerationArray<ModuleMultiThread, const char*> moduleMultiThreadNames = {
92         "default",     "domain decomposition",
93         "pair search", "non-bonded",
94         "bonded",      "PME",
95         "update",      "LINCS",
96         "SETTLE"
97     };
98     return moduleMultiThreadNames[enumValue];
99 }
100
101 /** Number of threads for each algorithmic module.
102  *
103  *  File-scope global variable that gets set once in pick_module_nthreads()
104  *  and queried via gmx_omp_nthreads_get().
105  *
106  *  All fields are initialized to 0 which should result in errors if
107  *  the init call is omitted.
108  * */
109 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
110 static omp_module_nthreads_t modth = { 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
111
112
113 /** Determine the number of threads for module \p mod.
114  *
115  *  \p m takes values form the module_nth_t enum and maps these to the
116  *  corresponding value in modth_env_var.
117  *
118  *  Each number of threads per module takes the default value unless
119  *  GMX_*_NUM_THERADS env var is set, case in which its value overrides
120  *  the default.
121  */
122 static void pick_module_nthreads(const gmx::MDLogger& mdlog, ModuleMultiThread m, gmx_bool bSepPME)
123 {
124     char* env;
125     int   nth;
126
127     const bool bOMP = GMX_OPENMP;
128
129     /* The default should never be set through a GMX_*_NUM_THREADS env var
130      * as it's always equal with gnth. */
131     if (m == ModuleMultiThread::Default)
132     {
133         return;
134     }
135
136     /* check the environment variable */
137     if ((env = getenv(enumValueToEnvVariableString(m))) != nullptr)
138     {
139         sscanf(env, "%d", &nth);
140
141         if (!bOMP)
142         {
143             gmx_warning("%s=%d is set, but %s is compiled without OpenMP!",
144                         enumValueToEnvVariableString(m),
145                         nth,
146                         gmx::getProgramContext().displayName());
147         }
148
149         /* with the verlet codepath, when any GMX_*_NUM_THREADS env var is set,
150          * OMP_NUM_THREADS also has to be set */
151         if (getenv("OMP_NUM_THREADS") == nullptr)
152         {
153             gmx_warning(
154                     "%s=%d is set, the default number of threads also "
155                     "needs to be set with OMP_NUM_THREADS!",
156                     enumValueToEnvVariableString(m),
157                     nth);
158         }
159
160         /* only babble if we are really overriding with a different value */
161         if ((bSepPME && m == ModuleMultiThread::Pme && nth != modth.gnth_pme) || (nth != modth.gnth))
162         {
163             GMX_LOG(mdlog.warning)
164                     .asParagraph()
165                     .appendTextFormatted("%s=%d set, overriding the default number of %s threads",
166                                          enumValueToString(m),
167                                          nth,
168                                          enumValueToEnvVariableString(m));
169         }
170     }
171     else
172     {
173         /* pick the global PME node nthreads if we are setting the number
174          * of threads in separate PME nodes  */
175         nth = (bSepPME && m == ModuleMultiThread::Pme) ? modth.gnth_pme : modth.gnth;
176     }
177
178     gmx_omp_nthreads_set(m, nth);
179 }
180
181 void gmx_omp_nthreads_read_env(const gmx::MDLogger& mdlog, int* nthreads_omp)
182 {
183     char*    env;
184     gmx_bool bCommandLineSetNthreadsOMP = *nthreads_omp > 0;
185     char     buffer[STRLEN];
186
187     GMX_RELEASE_ASSERT(nthreads_omp, "nthreads_omp must be a non-NULL pointer");
188
189     if ((env = getenv("OMP_NUM_THREADS")) != nullptr)
190     {
191         int nt_omp;
192
193         sscanf(env, "%d", &nt_omp);
194         if (nt_omp <= 0)
195         {
196             gmx_fatal(FARGS, "OMP_NUM_THREADS is invalid: '%s'", env);
197         }
198
199         if (bCommandLineSetNthreadsOMP && nt_omp != *nthreads_omp)
200         {
201             gmx_fatal(FARGS,
202                       "Environment variable OMP_NUM_THREADS (%d) and the number of threads "
203                       "requested on the command line (%d) have different values. Either omit one, "
204                       "or set them both to the same value.",
205                       nt_omp,
206                       *nthreads_omp);
207         }
208
209         /* Setting the number of OpenMP threads. */
210         *nthreads_omp = nt_omp;
211
212         /* Output the results */
213         sprintf(buffer,
214                 "\nThe number of OpenMP threads was set by environment variable OMP_NUM_THREADS to "
215                 "%d%s\n\n",
216                 nt_omp,
217                 bCommandLineSetNthreadsOMP ? " (and the command-line setting agreed with that)" : "");
218
219         /* This prints once per simulation for multi-simulations,
220          * which might help diagnose issues with inhomogenous
221          * cluster setups. */
222         GMX_LOG(mdlog.info).appendTextFormatted("%s", buffer);
223         if (debug)
224         {
225             /* This prints once per process for real MPI (i.e. once
226              * per debug file), and once per simulation for thread MPI
227              * (because of logic in the calling function). */
228             fputs(buffer, debug);
229         }
230     }
231 }
232
233 /*! \brief Helper function for parsing various input about the number
234     of OpenMP threads to use in various modules and deciding what to
235     do about it. */
236 static void manage_number_of_openmp_threads(const gmx::MDLogger& mdlog,
237                                             const t_commrec*     cr,
238                                             bool                 bOMP,
239                                             int                  nthreads_hw_avail,
240                                             int                  omp_nthreads_req,
241                                             int                  omp_nthreads_pme_req,
242                                             gmx_bool gmx_unused  bThisNodePMEOnly,
243                                             int                  numRanksOnThisNode,
244                                             gmx_bool             bSepPME)
245 {
246     int   nth;
247     char* env;
248
249 #if GMX_THREAD_MPI
250     /* modth is shared among tMPI threads, so for thread safety, the
251      * detection is done on the master only. It is not thread-safe
252      * with multiple simulations, but that's anyway not supported by
253      * tMPI. */
254     if (!SIMMASTER(cr))
255     {
256         return;
257     }
258 #else
259     GMX_UNUSED_VALUE(cr);
260 #endif
261
262     /* With full OpenMP support (verlet scheme) set the number of threads
263      * per process / default:
264      * - 1 if not compiled with OpenMP or
265      * - OMP_NUM_THREADS if the env. var is set, or
266      * - omp_nthreads_req = #of threads requested by the user on the mdrun
267      *   command line, otherwise
268      * - take the max number of available threads and distribute them
269      *   on the processes/tMPI threads.
270      * ~ The GMX_*_NUM_THREADS env var overrides the number of threads of
271      *   the respective module and it has to be used in conjunction with
272      *   OMP_NUM_THREADS.
273      *
274      * The number of PME threads is equal to:
275      * - 1 if not compiled with OpenMP or
276      * - GMX_PME_NUM_THREADS if defined, otherwise
277      * - OMP_NUM_THREADS if defined, otherwise
278      * - 1
279      */
280     nth = 1;
281     if ((env = getenv("OMP_NUM_THREADS")) != nullptr)
282     {
283         if (!bOMP && (std::strncmp(env, "1", 1) != 0))
284         {
285             gmx_warning("OMP_NUM_THREADS is set, but %s was compiled without OpenMP support!",
286                         gmx::getProgramContext().displayName());
287         }
288         else
289         {
290             nth = gmx_omp_get_max_threads();
291         }
292     }
293     else if (omp_nthreads_req > 0)
294     {
295         nth = omp_nthreads_req;
296     }
297     else if (bOMP)
298     {
299         /* max available threads per node */
300         nth = nthreads_hw_avail;
301
302         /* divide the threads among the MPI ranks */
303         if (nth >= numRanksOnThisNode)
304         {
305             nth /= numRanksOnThisNode;
306         }
307         else
308         {
309             nth = 1;
310         }
311     }
312
313     /* now we have the global values, set them:
314      * - 1 if not compiled with OpenMP
315      * - nth for the verlet scheme when compiled with OpenMP
316      */
317     if (bOMP)
318     {
319         modth.gnth = nth;
320     }
321     else
322     {
323         modth.gnth = 1;
324     }
325
326     if (bSepPME)
327     {
328         if (omp_nthreads_pme_req > 0)
329         {
330             modth.gnth_pme = omp_nthreads_pme_req;
331         }
332         else
333         {
334             modth.gnth_pme = nth;
335         }
336     }
337     else
338     {
339         modth.gnth_pme = 0;
340     }
341
342     /* now set the per-module values */
343     modth.nth[ModuleMultiThread::Default] = modth.gnth;
344     pick_module_nthreads(mdlog, ModuleMultiThread::Domdec, bSepPME);
345     pick_module_nthreads(mdlog, ModuleMultiThread::Pairsearch, bSepPME);
346     pick_module_nthreads(mdlog, ModuleMultiThread::Nonbonded, bSepPME);
347     pick_module_nthreads(mdlog, ModuleMultiThread::Bonded, bSepPME);
348     pick_module_nthreads(mdlog, ModuleMultiThread::Pme, bSepPME);
349     pick_module_nthreads(mdlog, ModuleMultiThread::Update, bSepPME);
350     pick_module_nthreads(mdlog, ModuleMultiThread::VirtualSite, bSepPME);
351     pick_module_nthreads(mdlog, ModuleMultiThread::Lincs, bSepPME);
352     pick_module_nthreads(mdlog, ModuleMultiThread::Settle, bSepPME);
353
354     /* set the number of threads globally */
355     if (bOMP)
356     {
357 #if !GMX_THREAD_MPI
358         if (bThisNodePMEOnly)
359         {
360             gmx_omp_set_num_threads(modth.gnth_pme);
361         }
362         else
363 #endif /* GMX_THREAD_MPI */
364         {
365             gmx_omp_set_num_threads(nth);
366         }
367     }
368 }
369
370 /*! \brief Report on the OpenMP settings that will be used */
371 static void reportOpenmpSettings(const gmx::MDLogger& mdlog, const t_commrec* cr, gmx_bool bOMP, gmx_bool bSepPME)
372 {
373 #if GMX_THREAD_MPI
374     const char* mpi_str = "per tMPI thread";
375 #else
376     const char* mpi_str = "per MPI process";
377 #endif
378     int nth_min, nth_max, nth_pme_min, nth_pme_max;
379
380     /* inform the user about the settings */
381     if (!bOMP)
382     {
383         return;
384     }
385
386 #if GMX_MPI
387     if (cr->nnodes > 1)
388     {
389         /* Get the min and max thread counts over the MPI ranks */
390         int buf_in[4], buf_out[4];
391
392         buf_in[0] = -modth.gnth;
393         buf_in[1] = modth.gnth;
394         buf_in[2] = -modth.gnth_pme;
395         buf_in[3] = modth.gnth_pme;
396
397         MPI_Allreduce(buf_in, buf_out, 4, MPI_INT, MPI_MAX, cr->mpi_comm_mysim);
398
399         nth_min     = -buf_out[0];
400         nth_max     = buf_out[1];
401         nth_pme_min = -buf_out[2];
402         nth_pme_max = buf_out[3];
403     }
404     else
405 #endif
406     {
407         nth_min     = modth.gnth;
408         nth_max     = modth.gnth;
409         nth_pme_min = modth.gnth_pme;
410         nth_pme_max = modth.gnth_pme;
411     }
412
413
414     if (nth_max == nth_min)
415     {
416         GMX_LOG(mdlog.warning)
417                 .appendTextFormatted("Using %d OpenMP thread%s %s",
418                                      nth_min,
419                                      nth_min > 1 ? "s" : "",
420                                      cr->nnodes > 1 ? mpi_str : "");
421     }
422     else
423     {
424         GMX_LOG(mdlog.warning).appendTextFormatted("Using %d - %d OpenMP threads %s", nth_min, nth_max, mpi_str);
425     }
426
427     if (bSepPME && (nth_pme_min != nth_min || nth_pme_max != nth_max))
428     {
429         if (nth_pme_max == nth_pme_min)
430         {
431             GMX_LOG(mdlog.warning)
432                     .appendTextFormatted("Using %d OpenMP thread%s %s for PME",
433                                          nth_pme_min,
434                                          nth_pme_min > 1 ? "s" : "",
435                                          cr->nnodes > 1 ? mpi_str : "");
436         }
437         else
438         {
439             GMX_LOG(mdlog.warning)
440                     .appendTextFormatted(
441                             "Using %d - %d OpenMP threads %s for PME", nth_pme_min, nth_pme_max, mpi_str);
442         }
443     }
444     GMX_LOG(mdlog.warning);
445 }
446
447 void gmx_omp_nthreads_init(const gmx::MDLogger& mdlog,
448                            t_commrec*           cr,
449                            int                  nthreads_hw_avail,
450                            int                  numRanksOnThisNode,
451                            int                  omp_nthreads_req,
452                            int                  omp_nthreads_pme_req,
453                            gmx_bool             bThisNodePMEOnly)
454 {
455     gmx_bool bSepPME;
456
457     const bool bOMP = GMX_OPENMP;
458
459     bSepPME = (thisRankHasDuty(cr, DUTY_PP) != thisRankHasDuty(cr, DUTY_PME));
460
461     manage_number_of_openmp_threads(mdlog,
462                                     cr,
463                                     bOMP,
464                                     nthreads_hw_avail,
465                                     omp_nthreads_req,
466                                     omp_nthreads_pme_req,
467                                     bThisNodePMEOnly,
468                                     numRanksOnThisNode,
469                                     bSepPME);
470 #if GMX_THREAD_MPI
471     /* Non-master threads have to wait for the OpenMP management to be
472      * done, so that code elsewhere that uses OpenMP can be certain
473      * the setup is complete. */
474     if (PAR(cr))
475     {
476         MPI_Barrier(cr->mpi_comm_mysim);
477     }
478 #endif
479
480     reportOpenmpSettings(mdlog, cr, bOMP, bSepPME);
481 }
482
483 int gmx_omp_nthreads_get(ModuleMultiThread mod)
484 {
485     if (mod < ModuleMultiThread::Default || mod >= ModuleMultiThread::Count)
486     {
487         /* invalid module queried */
488         return -1;
489     }
490     else
491     {
492         return modth.nth[mod];
493     }
494 }
495
496 void gmx_omp_nthreads_set(ModuleMultiThread mod, int nthreads)
497 {
498     /* Catch an attempt to set the number of threads on an invalid
499      * OpenMP module. */
500     GMX_RELEASE_ASSERT(mod >= ModuleMultiThread::Default && mod < ModuleMultiThread::Count,
501                        "Trying to set nthreads on invalid OpenMP module");
502
503     modth.nth[mod] = nthreads;
504 }