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