Minor fixes to mdrun performance documentation
[alexxy/gromacs.git] / docs / user-guide / mdrun-performance.rst
1 .. _gmx-performance:
2
3 Getting good performance from :ref:`mdrun <gmx mdrun>`
4 ======================================================
5 The |Gromacs| build system and the :ref:`gmx mdrun` tool has a lot of built-in
6 and configurable intelligence to detect your hardware and make pretty
7 effective use of that hardware. For a lot of casual and serious use of
8 :ref:`gmx mdrun`, the automatic machinery works well enough. But to get the
9 most from your hardware to maximize your scientific quality, read on!
10
11 Hardware background information
12 -------------------------------
13 Modern computer hardware is complex and heterogeneous, so we need to
14 discuss a little bit of background information and set up some
15 definitions. Experienced HPC users can skip this section.
16
17 .. glossary::
18
19     core
20         A hardware compute unit that actually executes
21         instructions. There is normally more than one core in a
22         processor, often many more.
23
24     cache
25         A special kind of memory local to core(s) that is much faster
26         to access than main memory, kind of like the top of a human's
27         desk, compared to their filing cabinet. There are often
28         several layers of caches associated with a core.
29
30     socket
31         A group of cores that share some kind of locality, such as a
32         shared cache. This makes it more efficient to spread
33         computational work over cores within a socket than over cores
34         in different sockets. Modern processors often have more than
35         one socket.
36
37     node
38         A group of sockets that share coarser-level locality, such as
39         shared access to the same memory without requiring any network
40         hardware. A normal laptop or desktop computer is a node. A
41         node is often the smallest amount of a large compute cluster
42         that a user can request to use.
43
44     thread
45         A stream of instructions for a core to execute. There are many
46         different programming abstractions that create and manage
47         spreading computation over multiple threads, such as OpenMP,
48         pthreads, winthreads, CUDA, OpenCL, and OpenACC. Some kinds of
49         hardware can map more than one software thread to a core; on
50         Intel x86 processors this is called "hyper-threading", while
51         the more general concept is often called SMT for
52         "simultaneous multi-threading". IBM Power8 can for instance use
53         up to 8 hardware threads per core.
54         This feature can usually be enabled or disabled either in
55         the hardware bios or through a setting in the Linux operating
56         system. |Gromacs| can typically make use of this, for a moderate
57         free performance boost. In most cases it will be
58         enabled by default e.g. on new x86 processors, but in some cases
59         the system administrators might have disabled it. If that is the
60         case, ask if they can re-enable it for you. If you are not sure
61         if it is enabled, check the output of the CPU information in
62         the log file and compare with CPU specifications you find online.
63
64     thread affinity (pinning)
65         By default, most operating systems allow software threads to migrate
66         between cores (or hardware threads) to help automatically balance
67         workload. However, the performance of :ref:`gmx mdrun` can deteriorate
68         if this is permitted and will degrade dramatically especially when
69         relying on multi-threading within a rank. To avoid this,
70         :ref:`gmx mdrun` will by default
71         set the affinity of its threads to individual cores/hardware threads,
72         unless the user or software environment has already done so
73         (or not the entire node is used for the run, i.e. there is potential
74         for node sharing).
75         Setting thread affinity is sometimes called thread "pinning".
76
77     MPI
78         The dominant multi-node parallelization-scheme, which provides
79         a standardized language in which programs can be written that
80         work across more than one node.
81
82     rank
83         In MPI, a rank is the smallest grouping of hardware used in
84         the multi-node parallelization scheme. That grouping can be
85         controlled by the user, and might correspond to a core, a
86         socket, a node, or a group of nodes. The best choice varies
87         with the hardware, software and compute task. Sometimes an MPI
88         rank is called an MPI process.
89
90     GPU
91         A graphics processing unit, which is often faster and more
92         efficient than conventional processors for particular kinds of
93         compute workloads. A GPU is always associated with a
94         particular node, and often a particular socket within that
95         node.
96
97     OpenMP
98         A standardized technique supported by many compilers to share
99         a compute workload over multiple cores. Often combined with
100         MPI to achieve hybrid MPI/OpenMP parallelism.
101
102     CUDA
103         A proprietary parallel computing framework and API developed by NVIDIA
104         that allows targeting their accelerator hardware.
105         |Gromacs| uses CUDA for GPU acceleration support with NVIDIA hardware.
106
107     OpenCL
108         An open standard-based parallel computing framework that consists
109         of a C99-based compiler and a programming API for targeting heterogeneous
110         and accelerator hardware. |Gromacs| uses OpenCL for GPU acceleration
111         on AMD devices (both GPUs and APUs); NVIDIA hardware is also supported.
112
113     SIMD
114         A type of CPU instruction by which modern CPU cores can execute large
115         numbers of floating-point instructions in a single cycle.
116
117
118 |Gromacs| background information
119 --------------------------------
120 The algorithms in :ref:`gmx mdrun` and their implementations are most relevant
121 when choosing how to make good use of the hardware. For details,
122 see the Reference Manual. The most important of these are
123
124 .. _gmx-domain-decomp:
125
126 .. glossary::
127
128     Domain Decomposition
129         The domain decomposition (DD) algorithm decomposes the
130         (short-ranged) component of the non-bonded interactions into
131         domains that share spatial locality, which permits the use of
132         efficient algorithms. Each domain handles all of the
133         particle-particle (PP) interactions for its members, and is
134         mapped to a single MPI rank. Within a PP rank, OpenMP threads
135         can share the workload, and some work can be off-loaded to a
136         GPU. The PP rank also handles any bonded interactions for the
137         members of its domain. A GPU may perform work for more than
138         one PP rank, but it is normally most efficient to use a single
139         PP rank per GPU and for that rank to have thousands of
140         particles. When the work of a PP rank is done on the CPU,
141         :ref:`mdrun <gmx mdrun>` will make extensive use of the SIMD
142         capabilities of the core. There are various
143         :ref:`command-line options <controlling-the-domain-decomposition-algorithm>`
144         to control the behaviour of the DD algorithm.
145
146     Particle-mesh Ewald
147         The particle-mesh Ewald (PME) algorithm treats the long-ranged
148         component of the non-bonded interactions (Coulomb and/or
149         Lennard-Jones).  Either all, or just a subset of ranks may
150         participate in the work for computing the long-ranged component
151         (often inaccurately called simply the "PME"
152         component). Because the algorithm uses a 3D FFT that requires
153         global communication, its performance gets worse as more ranks
154         participate, which can mean it is fastest to use just a subset
155         of ranks (e.g.  one-quarter to one-half of the ranks). If
156         there are separate PME ranks, then the remaining ranks handle
157         the PP work. Otherwise, all ranks do both PP and PME work.
158
159 Running :ref:`mdrun <gmx mdrun>` within a single node
160 -----------------------------------------------------
161
162 :ref:`gmx mdrun` can be configured and compiled in several different ways that
163 are efficient to use within a single :term:`node`. The default configuration
164 using a suitable compiler will deploy a multi-level hybrid parallelism
165 that uses CUDA, OpenMP and the threading platform native to the
166 hardware. For programming convenience, in |Gromacs|, those native
167 threads are used to implement on a single node the same MPI scheme as
168 would be used between nodes, but much more efficient; this is called
169 thread-MPI. From a user's perspective, real MPI and thread-MPI look
170 almost the same, and |Gromacs| refers to MPI ranks to mean either kind,
171 except where noted. A real external MPI can be used for :ref:`gmx mdrun` within
172 a single node, but runs more slowly than the thread-MPI version.
173
174 By default, :ref:`gmx mdrun` will inspect the hardware available at run time
175 and do its best to make fairly efficient use of the whole node. The
176 log file, stdout and stderr are used to print diagnostics that
177 inform the user about the choices made and possible consequences.
178
179 A number of command-line parameters are available to modify the default
180 behavior.
181
182 ``-nt``
183     The total number of threads to use. The default, 0, will start as
184     many threads as available cores. Whether the threads are
185     thread-MPI ranks, and/or OpenMP threads within such ranks depends on
186     other settings.
187
188 ``-ntmpi``
189     The total number of thread-MPI ranks to use. The default, 0,
190     will start one rank per GPU (if present), and otherwise one rank
191     per core.
192
193 ``-ntomp``
194     The total number of OpenMP threads per rank to start. The
195     default, 0, will start one thread on each available core.
196     Alternatively, :ref:`mdrun <gmx mdrun>` will honor the appropriate system
197     environment variable (e.g. ``OMP_NUM_THREADS``) if set.
198
199 ``-npme``
200     The total number of ranks to dedicate to the long-ranged
201     component of PME, if used. The default, -1, will dedicate ranks
202     only if the total number of threads is at least 12, and will use
203     around a quarter of the ranks for the long-ranged component.
204
205 ``-ntomp_pme``
206     When using PME with separate PME ranks,
207     the total number of OpenMP threads per separate PME ranks.
208     The default, 0, copies the value from ``-ntomp``.
209
210 ``-pin``
211     Can be set to "auto," "on" or "off" to control whether
212     :ref:`mdrun <gmx mdrun>` will attempt to set the affinity of threads to cores.
213     Defaults to "auto," which means that if :ref:`mdrun <gmx mdrun>` detects that all the
214     cores on the node are being used for :ref:`mdrun <gmx mdrun>`, then it should behave
215     like "on," and attempt to set the affinities (unless they are
216     already set by something else).
217
218 ``-pinoffset``
219     If ``-pin on``, specifies the logical core number to
220     which :ref:`mdrun <gmx mdrun>` should pin the first thread. When running more than
221     one instance of :ref:`mdrun <gmx mdrun>` on a node, use this option to to avoid
222     pinning threads from different :ref:`mdrun <gmx mdrun>` instances to the same core.
223
224 ``-pinstride``
225     If ``-pin on``, specifies the stride in logical core
226     numbers for the cores to which :ref:`mdrun <gmx mdrun>` should pin its threads. When
227     running more than one instance of :ref:`mdrun <gmx mdrun>` on a node, use this option
228     to to avoid pinning threads from different :ref:`mdrun <gmx mdrun>` instances to the
229     same core.  Use the default, 0, to minimize the number of threads
230     per physical core - this lets :ref:`mdrun <gmx mdrun>` manage the hardware-, OS- and
231     configuration-specific details of how to map logical cores to
232     physical cores.
233
234 ``-ddorder``
235     Can be set to "interleave," "pp_pme" or "cartesian."
236     Defaults to "interleave," which means that any separate PME ranks
237     will be mapped to MPI ranks in an order like PP, PP, PME, PP, PP,
238     PME, ... etc. This generally makes the best use of the available
239     hardware. "pp_pme" maps all PP ranks first, then all PME
240     ranks. "cartesian" is a special-purpose mapping generally useful
241     only on special torus networks with accelerated global
242     communication for Cartesian communicators. Has no effect if there
243     are no separate PME ranks.
244
245 ``-nb``
246     Used to set where to execute the non-bonded interactions.
247     Can be set to "auto", "cpu", "gpu."
248     Defaults to "auto," which uses a compatible GPU if available.
249     Setting "cpu" requires that no GPU is used. Setting "gpu" requires
250     that a compatible GPU be available and will be used.
251
252 ``-gpu_id``
253     A string that specifies the ID numbers of the GPUs that
254     are available to be used by ranks on this node. For example,
255     "12" specifies that the GPUs with IDs 1 and 2 (as reported
256     by the GPU runtime) can be used by :ref:`mdrun <gmx mdrun>`. This is useful
257     when sharing a node with other computations, or if a GPU
258     is best used to support a display.  Without specifying this
259     parameter, :ref:`mdrun <gmx mdrun>` will utilize all GPUs. When many GPUs are
260     present, a comma may be used to separate the IDs, so
261     "12,13" would make GPUs 12 and 13 available to :ref:`mdrun <gmx mdrun>`.
262     It could be necessary to use different GPUs on different
263     nodes of a simulation, in which case the environment
264     variable ``GMX_GPU_ID`` can be set differently for the ranks
265     on different nodes to achieve that result.
266     In |Gromacs| versions preceding 2018 this parameter used to
267     specify both GPU availability and GPU task assignment.
268     The latter is now done with the ``-gputasks`` parameter.
269
270 ``-gputasks``
271     A string that specifies the ID numbers of the GPUs to be
272     used by corresponding GPU tasks on this node. For example,
273     "0011" specifies that the first two GPU tasks will use GPU 0,
274     and the other two use GPU 1. When using this option, the
275     number of ranks must be known to :ref:`mdrun <gmx mdrun>`, as well as where
276     tasks of different types should be run, such as by using
277     ``-nb gpu`` - only the tasks which are set to run on GPUs
278     count for parsing the mapping.
279     In |Gromacs| versions preceding 2018 only a single type
280     of GPU task could be run on any rank. Now that there is some
281     support for running PME on GPUs, the number of GPU tasks
282     (and the number of GPU IDs expected in the ``-gputasks`` string)
283     can actually be 2 for a single-rank simulation. The IDs
284     still have to be the same in this case, as using multiple GPUs
285     per single rank is not yet implemented.
286     The order of GPU tasks per rank in the string is short-range first,
287     PME second. The order of ranks with different kinds of GPU tasks
288     is the same by default, but can be influenced with the ``-ddorder``
289     option and gets quite complex when using multiple nodes.
290     The GPU task assignment (whether manually set, or automated),
291     will be reported in the :ref:`mdrun <gmx mdrun>` output on
292     the first physical node of the simulation. For example:
293
294     ::
295
296       gmx mdrun -gputasks 0001 -nb gpu -pme gpu -npme 1 -ntmpi 4
297
298     will produce the following output in the log file/terminal:
299
300     ::
301
302       On host tcbl14 2 GPUs user-selected for this run.
303       Mapping of GPU IDs to the 4 GPU tasks in the 4 ranks on this node:
304       PP:0,PP:0,PP:0,PME:1
305
306     In this case, 3 ranks are set by user to compute short-range work
307     on GPU 0, and 1 rank to compute PME on GPU 1.
308     The detailed indexing of the GPUs is also reported in the log file.
309
310     For more information about GPU tasks, please refer to
311     :ref:`Types of GPU tasks<gmx-gpu-tasks>`.
312
313 Examples for :ref:`mdrun <gmx mdrun>` on one node
314 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
315
316 ::
317
318     gmx mdrun
319
320 Starts :ref:`mdrun <gmx mdrun>` using all the available resources. :ref:`mdrun <gmx mdrun>`
321 will automatically choose a fairly efficient division
322 into thread-MPI ranks, OpenMP threads and assign work
323 to compatible GPUs. Details will vary with hardware
324 and the kind of simulation being run.
325
326 ::
327
328     gmx mdrun -nt 8
329
330 Starts :ref:`mdrun <gmx mdrun>` using 8 threads, which might be thread-MPI
331 or OpenMP threads depending on hardware and the kind
332 of simulation being run.
333
334 ::
335
336     gmx mdrun -ntmpi 2 -ntomp 4
337
338 Starts :ref:`mdrun <gmx mdrun>` using eight total threads, with two thread-MPI
339 ranks and four OpenMP threads per rank. You should only use
340 these options when seeking optimal performance, and
341 must take care that the ranks you create can have
342 all of their OpenMP threads run on the same socket.
343 The number of ranks must be a multiple of the number of
344 sockets, and the number of cores per node must be
345 a multiple of the number of threads per rank.
346
347 ::
348
349     gmx mdrun -gpu_id 12
350
351 Starts :ref:`mdrun <gmx mdrun>` using GPUs with IDs 1 and 2 (e.g. because
352 GPU 0 is dedicated to running a display). This requires
353 two thread-MPI ranks, and will split the available
354 CPU cores between them using OpenMP threads.
355
356 ::
357
358     gmx mdrun -ntmpi 4 -nb gpu -gputasks 1122
359
360 Starts :ref:`mdrun <gmx mdrun>` using four thread-MPI ranks, and maps them
361 to GPUs with IDs 1 and 2. The CPU cores available will
362 be split evenly between the ranks using OpenMP threads.
363
364 ::
365
366     gmx mdrun -nt 6 -pin on -pinoffset 0 -pinstride 1
367     gmx mdrun -nt 6 -pin on -pinoffset 6 -pinstride 1
368
369 Starts two :ref:`mdrun <gmx mdrun>` processes, each with six total threads
370 arranged so that the processes affect each other as little as possible by
371 being assigned to disjoint sets of physical cores.
372 Threads will have their affinities set to particular
373 logical cores, beginning from the first and 7th logical cores, respectively. The
374 above would work well on an Intel CPU with six physical cores and
375 hyper-threading enabled. Use this kind of setup only
376 if restricting :ref:`mdrun <gmx mdrun>` to a subset of cores to share a
377 node with other processes.
378
379 ::
380
381     mpirun -np 2 gmx_mpi mdrun
382
383 When using an :ref:`gmx mdrun` compiled with external MPI,
384 this will start two ranks and as many OpenMP threads
385 as the hardware and MPI setup will permit. If the
386 MPI setup is restricted to one node, then the resulting
387 :ref:`gmx mdrun` will be local to that node.
388
389 Running :ref:`mdrun <gmx mdrun>` on more than one node
390 ------------------------------------------------------
391 This requires configuring |Gromacs| to build with an external MPI
392 library. By default, this :ref:`mdrun <gmx mdrun>` executable is run with
393 :ref:`mdrun_mpi`. All of the considerations for running single-node
394 :ref:`mdrun <gmx mdrun>` still apply, except that ``-ntmpi`` and ``-nt`` cause a fatal
395 error, and instead the number of ranks is controlled by the
396 MPI environment.
397 Settings such as ``-npme`` are much more important when
398 using multiple nodes. Configuring the MPI environment to
399 produce one rank per core is generally good until one
400 approaches the strong-scaling limit. At that point, using
401 OpenMP to spread the work of an MPI rank over more than one
402 core is needed to continue to improve absolute performance.
403 The location of the scaling limit depends on the processor,
404 presence of GPUs, network, and simulation algorithm, but
405 it is worth measuring at around ~200 particles/core if you
406 need maximum throughput.
407
408 There are further command-line parameters that are relevant in these
409 cases.
410
411 ``-tunepme``
412     Defaults to "on." If "on," a Verlet-scheme simulation will
413     optimize various aspects of the PME and DD algorithms, shifting
414     load between ranks and/or GPUs to maximize throughput. Some
415     :ref:`mdrun <gmx mdrun>` features are not compatible with this, and these ignore
416     this option.
417
418 ``-dlb``
419     Can be set to "auto," "no," or "yes."
420     Defaults to "auto." Doing Dynamic Load Balancing between MPI ranks
421     is needed to maximize performance. This is particularly important
422     for molecular systems with heterogeneous particle or interaction
423     density. When a certain threshold for performance loss is
424     exceeded, DLB activates and shifts particles between ranks to improve
425     performance.
426
427 ``-gcom``
428     During the simulation :ref:`gmx mdrun` must communicate between all ranks to
429     compute quantities such as kinetic energy. By default, this
430     happens whenever plausible, and is influenced by a lot of :ref:`[.mdp]
431     options. <mdp-general>` The period between communication phases
432     must be a multiple of :mdp:`nstlist`, and defaults to
433     the minimum of :mdp:`nstcalcenergy` and :mdp:`nstlist`.
434     ``mdrun -gcom`` sets the number of steps that must elapse between
435     such communication phases, which can improve performance when
436     running on a lot of ranks. Note that this means that _e.g._
437     temperature coupling algorithms will
438     effectively remain at constant energy until the next
439     communication phase. :ref:`gmx mdrun` will always honor the
440     setting of ``mdrun -gcom``, by changing :mdp:`nstcalcenergy`,
441     :mdp:`nstenergy`, :mdp:`nstlog`, :mdp:`nsttcouple` and/or
442     :mdp:`nstpcouple` if necessary.
443
444 Note that ``-tunepme`` has more effect when there is more than one
445 :term:`node`, because the cost of communication for the PP and PME
446 ranks differs. It still shifts load between PP and PME ranks, but does
447 not change the number of separate PME ranks in use.
448
449 Note also that ``-dlb`` and ``-tunepme`` can interfere with each other, so
450 if you experience performance variation that could result from this,
451 you may wish to tune PME separately, and run the result with ``mdrun
452 -notunepme -dlb yes``.
453
454 The :ref:`gmx tune_pme` utility is available to search a wider
455 range of parameter space, including making safe
456 modifications to the :ref:`tpr` file, and varying ``-npme``.
457 It is only aware of the number of ranks created by
458 the MPI environment, and does not explicitly manage
459 any aspect of OpenMP during the optimization.
460
461 Examples for :ref:`mdrun <gmx mdrun>` on more than one node
462 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
463 The examples and explanations for for single-node :ref:`mdrun <gmx mdrun>` are
464 still relevant, but ``-nt`` is no longer the way
465 to choose the number of MPI ranks.
466
467 ::
468
469     mpirun -np 16 gmx_mpi mdrun
470
471 Starts :ref:`mdrun_mpi` with 16 ranks, which are mapped to
472 the hardware by the MPI library, e.g. as specified
473 in an MPI hostfile. The available cores will be
474 automatically split among ranks using OpenMP threads,
475 depending on the hardware and any environment settings
476 such as ``OMP_NUM_THREADS``.
477
478 ::
479
480     mpirun -np 16 gmx_mpi mdrun -npme 5
481
482 Starts :ref:`mdrun_mpi` with 16 ranks, as above, and
483 require that 5 of them are dedicated to the PME
484 component.
485
486 ::
487
488     mpirun -np 11 gmx_mpi mdrun -ntomp 2 -npme 6 -ntomp_pme 1
489
490 Starts :ref:`mdrun_mpi` with 11 ranks, as above, and
491 require that six of them are dedicated to the PME
492 component with one OpenMP thread each. The remaining
493 five do the PP component, with two OpenMP threads
494 each.
495
496 ::
497
498     mpirun -np 4 gmx_mpi mdrun -ntomp 6 -nb gpu -gputasks 00
499
500 Starts :ref:`mdrun_mpi` on a machine with two nodes, using
501 four total ranks, each rank with six OpenMP threads,
502 and both ranks on a node sharing GPU with ID 0.
503
504 ::
505
506     mpirun -np 8 gmx_mpi mdrun -ntomp 3 -gputasks 0000
507
508 Using a same/similar hardware as above,
509 starts :ref:`mdrun_mpi` on a machine with two nodes, using
510 eight total ranks, each rank with three OpenMP threads,
511 and all four ranks on a node sharing GPU with ID 0.
512 This may or may not be faster than the previous setup
513 on the same hardware.
514
515 ::
516
517     mpirun -np 20 gmx_mpi mdrun -ntomp 4 -gputasks 00
518
519 Starts :ref:`mdrun_mpi` with 20 ranks, and assigns the CPU cores evenly
520 across ranks each to one OpenMP thread. This setup is likely to be
521 suitable when there are ten nodes, each with one GPU, and each node
522 has two sockets each of four cores.
523
524 ::
525
526     mpirun -np 10 gmx_mpi mdrun -gpu_id 1
527
528 Starts :ref:`mdrun_mpi` with 20 ranks, and assigns the CPU cores evenly
529 across ranks each to one OpenMP thread. This setup is likely to be
530 suitable when there are ten nodes, each with two GPUs, but another
531 job on each node is using GPU 0. The job scheduler should set the
532 affinity of threads of both jobs to their allocated cores, or the
533 performance of :ref:`mdrun <gmx mdrun>` will suffer greatly.
534
535 ::
536
537     mpirun -np 20 gmx_mpi mdrun -gpu_id 01
538
539 Starts :ref:`mdrun_mpi` with 20 ranks. This setup is likely
540 to be suitable when there are ten nodes, each with two
541 GPUs, but there is no need to specify ``-gpu_id`` for the
542 normal case where all the GPUs on the node are available
543 for use.
544
545 .. _controlling-the-domain-decomposition-algorithm:
546
547 Controlling the domain decomposition algorithm
548 ----------------------------------------------
549 This section lists all the options that affect how the domain
550 decomposition algorithm decomposes the workload to the available
551 parallel hardware.
552
553 ``-rdd``
554     Can be used to set the required maximum distance for inter
555     charge-group bonded interactions. Communication for two-body
556     bonded interactions below the non-bonded cut-off distance always
557     comes for free with the non-bonded communication. Particles beyond
558     the non-bonded cut-off are only communicated when they have
559     missing bonded interactions; this means that the extra cost is
560     minor and nearly independent of the value of ``-rdd``. With dynamic
561     load balancing, option ``-rdd`` also sets the lower limit for the
562     domain decomposition cell sizes. By default ``-rdd`` is determined
563     by :ref:`gmx mdrun` based on the initial coordinates. The chosen value will
564     be a balance between interaction range and communication cost.
565
566 ``-ddcheck``
567     On by default. When inter charge-group bonded interactions are
568     beyond the bonded cut-off distance, :ref:`gmx mdrun` terminates with an
569     error message. For pair interactions and tabulated bonds that do
570     not generate exclusions, this check can be turned off with the
571     option ``-noddcheck``.
572
573 ``-rcon``
574     When constraints are present, option ``-rcon`` influences
575     the cell size limit as well.
576     Particles connected by NC constraints, where NC is the LINCS order
577     plus 1, should not be beyond the smallest cell size. A error
578     message is generated when this happens, and the user should change
579     the decomposition or decrease the LINCS order and increase the
580     number of LINCS iterations.  By default :ref:`gmx mdrun` estimates the
581     minimum cell size required for P-LINCS in a conservative
582     fashion. For high parallelization, it can be useful to set the
583     distance required for P-LINCS with ``-rcon``.
584
585 ``-dds``
586     Sets the minimum allowed x, y and/or z scaling of the cells with
587     dynamic load balancing. :ref:`gmx mdrun` will ensure that the cells can
588     scale down by at least this factor. This option is used for the
589     automated spatial decomposition (when not using ``-dd``) as well as
590     for determining the number of grid pulses, which in turn sets the
591     minimum allowed cell size. Under certain circumstances the value
592     of ``-dds`` might need to be adjusted to account for high or low
593     spatial inhomogeneity of the system.
594
595 Finding out how to run :ref:`mdrun <gmx mdrun>` better
596 ------------------------------------------------------
597
598 The Wallcycle module is used for runtime performance measurement of :ref:`gmx mdrun`.
599 At the end of the log file of each run, the "Real cycle and time accounting" section
600 provides a table with runtime statistics for different parts of the :ref:`gmx mdrun` code
601 in rows of the table.
602 The table contains colums indicating the number of ranks and threads that
603 executed the respective part of the run, wall-time and cycle
604 count aggregates (across all threads and ranks) averaged over the entire run.
605 The last column also shows what precentage of the total runtime each row represents.
606 Note that the :ref:`gmx mdrun` timer resetting functionalities (`-resethway` and `-resetstep`)
607 reset the performance counters and therefore are useful to avoid startup overhead and
608 performance instability (e.g. due to load balancing) at the beginning of the run.
609
610 The performance counters are:
611
612 * Particle-particle during Particle mesh Ewald
613 * Domain decomposition
614 * Domain decomposition communication load
615 * Domain decomposition communication bounds
616 * Virtual site constraints
617 * Send X to Particle mesh Ewald
618 * Neighbor search
619 * Launch GPU operations
620 * Communication of coordinates
621 * Force
622 * Waiting + Communication of force
623 * Particle mesh Ewald
624 * PME redist. X/F
625 * PME spread
626 * PME gather
627 * PME 3D-FFT
628 * PME 3D-FFT Communication
629 * PME solve Lennard-Jones
630 * PME solve LJ
631 * PME solve Elec
632 * PME wait for particle-particle
633 * Wait + Receive PME force
634 * Wait GPU nonlocal
635 * Wait GPU local
636 * Wait PME GPU spread
637 * Wait PME GPU gather
638 * Reduce PME GPU Force
639 * Non-bonded position/force buffer operations
640 * Virtual site spread
641 * COM pull force
642 * AWH (accelerated weight histogram method)
643 * Write trajectory
644 * Update
645 * Constraints
646 * Communication of energies
647 * Enforced rotation
648 * Add rotational forces
649 * Position swapping
650 * Interactive MD
651
652 As performance data is collected for every run, they are essential to assessing
653 and tuning the performance of :ref:`gmx mdrun` performance. Therefore, they benefit
654 both code developers as well as users of the program.
655 The counters are an average of the time/cycles different parts of the simulation take,
656 hence can not directly reveal fluctuations during a single run (although comparisons across
657 multiple runs are still very useful).
658
659 Counters will appear in an MD log file only if the related parts of the code were
660 executed during the :ref:`gmx mdrun` run. There is also a special counter called "Rest" which
661 indicates the amount of time not accounted for by any of the counters above. Therefore,
662 a significant amount "Rest" time (more than a few percent) will often be an indication of
663 parallelization inefficiency (e.g. serial code) and it is recommended to be reported to the
664 developers.
665
666 An additional set of subcounters can offer more fine-grained inspection of performance. They are:
667
668 * Domain decomposition redistribution
669 * DD neighbor search grid + sort
670 * DD setup communication
671 * DD make topology
672 * DD make constraints
673 * DD topology other
674 * Neighbor search grid local
675 * NS grid non-local
676 * NS search local
677 * NS search non-local
678 * Bonded force
679 * Bonded-FEP force
680 * Restraints force
681 * Listed buffer operations
682 * Nonbonded pruning
683 * Nonbonded force
684 * Launch non-bonded GPU tasks
685 * Launch PME GPU tasks
686 * Ewald force correction
687 * Non-bonded position buffer operations
688 * Non-bonded force buffer operations
689
690 Subcounters are geared toward developers and have to be enabled during compilation. See
691 :doc:`/dev-manual/build-system` for more information.
692
693 TODO In future patch:
694 - red flags in log files, how to interpret wallcycle output
695 - hints to devs how to extend wallcycles
696
697 .. _gmx-mdrun-on-gpu:
698
699 Running :ref:`mdrun <gmx mdrun>` with GPUs
700 ------------------------------------------
701
702 NVIDIA GPUs from the professional line (Tesla or Quadro) starting with
703 the Kepler generation (compute capability 3.5 and later) support changing the
704 processor and memory clock frequency with the help of the applications clocks feature.
705 With many workloads, using higher clock rates than the default provides significant
706 performance improvements.
707 For more information see the `NVIDIA blog article`_ on this topic.
708 For |Gromacs| the highest application clock rates are optimal on all hardware
709 available to date (up to and including Maxwell, compute capability 5.2).
710
711 Application clocks can be set using the NVIDIA system managemet tool
712 ``nvidia-smi``. If the system permissions allow, :ref:`gmx mdrun` has
713 built-in support to set application clocks if built with :ref:`NVML support<CUDA GPU acceleration>`.
714 Note that application clocks are a global setting, hence affect the
715 performance of all applications that use the respective GPU(s).
716 For this reason, :ref:`gmx mdrun` sets application clocks at initialization
717 to the values optimal for |Gromacs| and it restores them before exiting
718 to the values found at startup, unless it detects that they were altered
719 during its runtime.
720
721 .. _NVIDIA blog article: https://devblogs.nvidia.com/parallelforall/increase-performance-gpu-boost-k80-autoboost/
722
723 .. _gmx-gpu-tasks:
724
725 Types of GPU tasks
726 ^^^^^^^^^^^^^^^^^^
727
728 To better understand the later sections on different GPU use cases for
729 calculation of :ref:`short range<gmx-gpu-pp>` and :ref:`PME <gmx-gpu-pme>`,
730 we first introduce the concept of different GPU tasks. When thinking about
731 running a simulation, several different kinds of interactions between the atoms
732 have to be calculated (for more information please refer to the reference manual).
733 The calculation can thus be split into several distinct parts that are largely independent
734 of each other (hence can be calculated in any order, e.g. sequentially or concurrently),
735 with the information from each of them combined at the end of
736 time step to obtain the final forces on each atom and to propagate the system
737 to the next time point. For a better understanding also please see the section
738 on :ref:`domain decomposition <gmx-domain-decomp>`.
739
740 Of all calculations required for an MD step,
741 GROMACS aims to optimize performance bottom-up for each step
742 from the lowest level (SIMD unit, cores, sockets, accelerators, etc.).
743 Therefore many of the individual computation units are
744 highly tuned for the lowest level of hardware parallelism: the SIMD units.
745 Additionally, with GPU accelerators used as *co-processors*, some of the work
746 can be *offloaded*, that is calculated simultaneously/concurrently with the CPU
747 on the accelerator device, with the result being communicated to the CPU.
748 Right now, |Gromacs| supports GPU accelerator offload of two tasks:
749 the short-range :ref:`nonbonded interactions in real space <gmx-gpu-pp>`,
750 and :ref:`PME <gmx-gpu-pme>`.
751
752 **Please note that the solving of PME on GPU is still only the initial
753 version supporting this behaviour, and comes with a set of limitations
754 outlined further below.**
755
756 Right now, we generally support short-range nonbonded offload with and
757 without dynamic pruning on a wide range of GPU accelerators
758 (both NVIDIA and AMD). This is compatible with the grand majority of
759 the features and parallelization modes and can be used to scale to large machines.
760
761 Simultaneously offloading both short-range nonbonded and long-range
762 PME work to GPU accelerators is a new feature that that has some
763 restrictions in terms of feature and parallelization
764 compatibility (please see the :ref:`section below <gmx-pme-gpu-limitations>`).
765
766 .. _gmx-gpu-pp:
767
768 GPU computation of short range nonbonded interactions
769 .....................................................
770
771 .. TODO make this more elaborate and include figures
772
773 Using the GPU for the short-ranged nonbonded interactions provides
774 the majority of the available speed-up compared to run using only the CPU.
775 Here, the GPU acts as an accelerator that can effectively parallelize
776 this problem and thus reduce the calculation time.
777
778 .. _gmx-gpu-pme:
779
780 GPU accelerated calculation of PME
781 ..................................
782
783 .. TODO again, extend this and add some actual useful information concerning performance etc...
784
785 Recent additions to |Gromacs| now also allow the off-loading of the PME calculation
786 to the GPU, to further reduce the load on the CPU and improve usage overlap between
787 CPU and GPU. Here, the solving of PME will be performed in addition to the calculation
788 of the short range interactions on the same GPU as the short range interactions.
789
790 .. _gmx-pme-gpu-limitations:
791
792 Known limitations
793 .................
794
795 **Please note again the limitations outlined below!**
796
797 - Only compilation with CUDA is supported.
798
799 - Only a PME order of 4 is supported on GPUs.
800
801 - PME will run on a GPU only when exactly one rank has a
802   PME task, ie. decompositions with multiple ranks doing PME are not supported.
803
804 - Only single precision is supported.
805
806 - Free energy calculations where charges are perturbed are not supported,
807   because only single PME grids can be calculated.
808
809 - LJ PME is not supported on GPUs.
810
811 Assigning tasks to GPUs
812 .......................
813
814 Depending on which tasks should be performed on which hardware, different kinds of
815 calculations can be combined on the same or different GPUs, according to the information
816 provided for running :ref:`mdrun <gmx mdrun>`.
817
818 .. Someone more knowledgeable than me should check the accuracy of this part, so that
819    I don't say something that is factually wrong :)
820
821 It is possible to assign the calculation of the different computational tasks to the same GPU, meaning
822 that they will share the computational resources on the same device, or to different processing units
823 that will each perform one task each.
824
825 One overview over the possible task assignments is given below:
826
827 |Gromacs| version 2018:
828
829   Two different types of GPU accelerated tasks are available, NB and PME.
830   Each PP rank has a NB task that can be offloaded to a GPU.
831   If there is only one rank with a PME task (including if that rank is a
832   PME-only rank), then that task can be offloaded to a GPU. Such a PME
833   task can run wholly on the GPU, or have its latter stages run only on the CPU.
834
835   Limitations are that PME on GPU does not support PME domain decomposition,
836   so that only one PME task can be offloaded to a single GPU
837   assigned to a separate PME rank, while NB can be decomposed and offloaded to multiple GPUs.
838
839 .. Future |Gromacs| versions past 2018:
840
841 ..   Combinations of different number of NB and single PME ranks on different
842      GPUs are being planned to be implemented in the near future. In addition,
843      we plan to add support for using multiple GPUs for each rank (e.g. having one GPU
844      each to solve the NB and PME part for a single rank), and to
845      implement domain decomposition on GPUs to allow the separation of the PME
846      part to different GPU tasks.
847
848
849 Performance considerations for GPU tasks
850 ........................................
851
852 #) The performance balance depends on the speed and number of CPU cores you
853    have vs the speed and number of GPUs you have.
854
855 #) With slow/old GPUs and/or fast/modern CPUs with many
856    cores, it might make more sense to let the CPU do PME calculation,
857    with the GPUs focused on the calculation of the NB.
858
859 #) With fast/modern GPUs and/or slow/old CPUs with few cores,
860    it generally helps to have the GPU do PME.
861
862 #) It *is* possible to use multiple GPUs with PME offload
863    by letting e.g.
864    3 MPI ranks use one GPU each for short-range interactions,
865    while a fourth rank does the PME on its GPU.
866
867 #) The only way to know for sure what alternative is best for
868    your machine is to test and check performance.
869
870 .. TODO: we need to be more concrete here, i.e. what machine/software aspects to take into consideration, when will default run mode be using PME-GPU and when will it not, when/how should the user reason about testing different settings than the default.
871
872 .. TODO someone who knows about the mixed mode should comment further.
873
874 Reducing overheads in GPU accelerated runs
875 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
876
877 In order for CPU cores and GPU(s) to execute concurrently, tasks are
878 launched and executed asynchronously on the GPU(s) while the CPU cores
879 execute non-offloaded force computation (like long-range PME electrostatics).
880 Asynchronous task launches are handled by GPU device driver and
881 require CPU involvement. Therefore, the work of scheduling
882 GPU tasks will incur an overhead that can in some cases significantly
883 delay or interfere with the CPU execution.
884
885 Delays in CPU execution are caused by the latency of launching GPU tasks,
886 an overhead that can become significant as simulation ns/day increases
887 (i.e. with shorter wall-time per step).
888 The overhead is measured by :ref:`gmx mdrun` and reported in the performance
889 summary section of the log file ("Launch GPU ops" row).
890 A few percent of runtime spent in this category is normal,
891 but in fast-iterating and multi-GPU parallel runs 10% or larger overheads can be observed.
892 In general, a user can do little to avoid such overheads, but there
893 are a few cases where tweaks can give performance benefits.
894 In single-rank runs timing of GPU tasks is by default enabled and,
895 while in most cases its impact is small, in fast runs performance can be affected.
896 The performance impact will be most significant on NVIDIA GPUs with CUDA,
897 less on AMD with OpenCL.
898 In these cases, when more than a few percent of "Launch GPU ops" time is observed,
899 it is recommended to turn off timing by setting the ``GMX_DISABLE_GPU_TIMING``
900 environment variable.
901 In parallel runs with many ranks sharing a GPU,
902 launch overheads can also be reduced by starting fewer thread-MPI
903 or MPI ranks per GPU; e.g. most often one rank per thread or core is not optimal.
904
905 The second type of overhead, interference of the GPU driver with CPU computation,
906 is caused by the scheduling and coordination of GPU tasks.
907 A separate GPU driver thread can require CPU resources
908 which may clash with the concurrently running non-offloaded tasks,
909 potentially degrading the performance of PME or bonded force computation.
910 This effect is most pronounced when using AMD GPUs with OpenCL with
911 older driver releases (e.g. fglrx 12.15).
912 To minimize the overhead it is recommended to
913 leave a CPU hardware thread unused when launching :ref:`gmx mdrun`,
914 especially on CPUs with high core counts and/or HyperThreading enabled.
915 E.g. on a machine with a 4-core CPU and eight threads (via HyperThreading) and an AMD GPU,
916 try ``gmx mdrun -ntomp 7 -pin on``.
917 This will leave free CPU resources for the GPU task scheduling
918 reducing interference with CPU computation.
919 Note that assigning fewer resources to :ref:`gmx mdrun` CPU computation
920 involves a tradeoff which may outweigh the benefits of reduced GPU driver overhead,
921 in particular without HyperThreading and with few CPU cores.
922
923 TODO In future patch: any tips not covered above
924
925 Running the OpenCL version of mdrun
926 -----------------------------------
927
928 The current version works with GCN-based AMD GPUs, and NVIDIA CUDA
929 GPUs. Make sure that you have the latest drivers installed. For AMD GPUs,
930 the compute-oriented `ROCm <https://rocm.github.io/>`_ stack is recommended;
931 alternatively, the AMDGPU-PRO stack is also compatible; using the outdated
932 and unsupported `fglrx` proprietary driver and runtime is not recommended (but
933 for certain older hardware that may be the only way to obtain support).
934 In addition Mesa version 17.0 or newer with LLVM 4.0 or newer is also supported.
935 For NVIDIA GPUs, using the proprietary driver is
936 required as the open source nouveau driver (available in Mesa) does not
937 provide the OpenCL support.
938 The minimum OpenCL version required is |REQUIRED_OPENCL_MIN_VERSION|. See
939 also the :ref:`known limitations <opencl-known-limitations>`.
940
941 Devices from the AMD GCN architectures (all series) are compatible
942 and regularly tested; NVIDIA Fermi and later (compute capability 2.0)
943 are known to work, but before doing production runs always make sure that the |Gromacs| tests
944 pass successfully on the hardware.
945
946 The OpenCL GPU kernels are compiled at run time. Hence,
947 building the OpenCL program can take a few seconds, introducing a slight
948 delay in the :ref:`gmx mdrun` startup. This is not normally a
949 problem for long production MD, but you might prefer to do some kinds
950 of work, e.g. that runs very few steps, on just the CPU (e.g. see ``-nb`` above).
951
952 The same ``-gpu_id`` option (or ``GMX_GPU_ID`` environment variable)
953 used to select CUDA devices, or to define a mapping of GPUs to PP
954 ranks, is used for OpenCL devices.
955
956 Some other :ref:`OpenCL management <opencl-management>` environment
957 variables may be of interest to developers.
958
959 .. _opencl-known-limitations:
960
961 Known limitations of the OpenCL support
962 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
963
964 Limitations in the current OpenCL support of interest to |Gromacs| users:
965
966 - PME GPU offload is not supported with OpenCL.
967 - No Intel devices (CPUs, GPUs or Xeon Phi) are supported
968 - Due to blocking behavior of some asynchronous task enqueuing functions
969   in the NVIDIA OpenCL runtime, with the affected driver versions there is
970   almost no performance gain when using NVIDIA GPUs.
971   The issue affects NVIDIA driver versions up to 349 series, but it
972   known to be fixed 352 and later driver releases.
973 - On NVIDIA GPUs the OpenCL kernels achieve much lower performance
974   than the equivalent CUDA kernels due to limitations of the NVIDIA OpenCL
975   compiler.
976
977 Limitations of interest to |Gromacs| developers:
978
979 - The current implementation is not compatible with OpenCL devices that are
980   not using warp/wavefronts or for which the warp/wavefront size is not a
981   multiple of 32
982
983 Performance checklist
984 ---------------------
985
986 There are many different aspects that affect the performance of simulations in
987 |Gromacs|. Most simulations require a lot of computational resources, therefore
988 it can be worthwhile to optimize the use of those resources. Several issues
989 mentioned in the list below could lead to a performance difference of a factor
990 of 2. So it can be useful go through the checklist.
991
992 |Gromacs| configuration
993 ^^^^^^^^^^^^^^^^^^^^^^^
994
995 * Don't use double precision unless you're absolute sure you need it.
996 * Compile the FFTW library (yourself) with the correct flags on x86 (in most
997   cases, the correct flags are automatically configured).
998 * On x86, use gcc or icc as the compiler (not pgi or the Cray compiler).
999 * On POWER, use gcc instead of IBM's xlc.
1000 * Use a new compiler version, especially for gcc (e.g. from version 5 to 6
1001   the performance of the compiled code improved a lot).
1002 * MPI library: OpenMPI usually has good performance and causes little trouble.
1003 * Make sure your compiler supports OpenMP (some versions of Clang don't).
1004 * If you have GPUs that support either CUDA or OpenCL, use them.
1005
1006   * Configure with ``-DGMX_GPU=ON`` (add ``-DGMX_USE_OPENCL=ON`` for OpenCL).
1007   * For CUDA, use the newest CUDA availabe for your GPU to take advantage of the
1008     latest performance enhancements.
1009   * Use a recent GPU driver.
1010   * If compiling on a cluster head node, make sure that ``GMX_SIMD``
1011     is appropriate for the compute nodes.
1012
1013 Run setup
1014 ^^^^^^^^^
1015
1016 * For an approximately spherical solute, use a rhombic dodecahedron unit cell.
1017 * When using a time-step of 2 fs, use :mdp-value:`constraints=h-bonds`
1018   (and not :mdp-value:`constraints=all-bonds`), since this is faster, especially with GPUs,
1019   and most force fields have been parametrized with only bonds involving
1020   hydrogens constrained.
1021 * You can increase the time-step to 4 or 5 fs when using virtual interaction
1022   sites (``gmx pdb2gmx -vsite h``).
1023 * For massively parallel runs with PME, you might need to try different numbers
1024   of PME ranks (``gmx mdrun -npme ???``) to achieve best performance;
1025   :ref:`gmx tune_pme` can help automate this search.
1026 * For massively parallel runs (also ``gmx mdrun -multidir``), or with a slow
1027   network, global communication can become a bottleneck and you can reduce it
1028   with ``gmx mdrun -gcom`` (note that this does affect the frequency of
1029   temperature and pressure coupling).
1030
1031 Checking and improving performance
1032 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1033
1034 * Look at the end of the ``md.log`` file to see the performance and the cycle
1035   counters and wall-clock time for different parts of the MD calculation. The
1036   PP/PME load ratio is also printed, with a warning when a lot of performance is
1037   lost due to imbalance.
1038 * Adjust the number of PME ranks and/or the cut-off and PME grid-spacing when
1039   there is a large PP/PME imbalance. Note that even with a small reported
1040   imbalance, the automated PME-tuning might have reduced the initial imbalance.
1041   You could still gain performance by changing the mdp parameters or increasing
1042   the number of PME ranks.
1043 * If the neighbor searching takes a lot of time, increase nstlist (with the
1044   Verlet cut-off scheme, this automatically adjusts the size of the neighbour
1045   list to do more non-bonded computation to keep energy drift constant).
1046
1047   * If ``Comm. energies`` takes a lot of time (a note will be printed in the log
1048     file), increase nstcalcenergy or use ``mdrun -gcom``.
1049   * If all communication takes a lot of time, you might be running on too many
1050     cores, or you could try running combined MPI/OpenMP parallelization with 2
1051     or 4 OpenMP threads per MPI process.