c61e0d640d5ccbb4a45952897ed3b2c0155c786b
[alexxy/gromacs.git] / src / gromacs / ewald / pme-load-balancing.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016,2017, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  *
37  * \brief This file contains function definitions necessary for
38  * managing automatic load balance of PME calculations (Coulomb and
39  * LJ).
40  *
41  * \author Berk Hess <hess@kth.se>
42  * \ingroup module_ewald
43  */
44 #include "gmxpre.h"
45
46 #include "pme-load-balancing.h"
47
48 #include "config.h"
49
50 #include <assert.h>
51
52 #include <cmath>
53
54 #include <algorithm>
55
56 #include "gromacs/domdec/domdec.h"
57 #include "gromacs/domdec/domdec_network.h"
58 #include "gromacs/domdec/domdec_struct.h"
59 #include "gromacs/ewald/pme.h"
60 #include "gromacs/fft/calcgrid.h"
61 #include "gromacs/gmxlib/network.h"
62 #include "gromacs/math/functions.h"
63 #include "gromacs/math/vec.h"
64 #include "gromacs/mdlib/forcerec.h"
65 #include "gromacs/mdlib/nbnxn_gpu_data_mgmt.h"
66 #include "gromacs/mdlib/sim_util.h"
67 #include "gromacs/mdtypes/commrec.h"
68 #include "gromacs/mdtypes/inputrec.h"
69 #include "gromacs/mdtypes/md_enums.h"
70 #include "gromacs/mdtypes/state.h"
71 #include "gromacs/pbcutil/pbc.h"
72 #include "gromacs/timing/wallcycle.h"
73 #include "gromacs/utility/cstringutil.h"
74 #include "gromacs/utility/fatalerror.h"
75 #include "gromacs/utility/gmxassert.h"
76 #include "gromacs/utility/logger.h"
77 #include "gromacs/utility/smalloc.h"
78
79 #include "pme-internal.h"
80
81 /*! \brief Parameters and settings for one PP-PME setup */
82 struct pme_setup_t {
83     real              rcut_coulomb;    /**< Coulomb cut-off                              */
84     real              rlist;           /**< pair-list cut-off                            */
85     real              spacing;         /**< (largest) PME grid spacing                   */
86     ivec              grid;            /**< the PME grid dimensions                      */
87     real              grid_efficiency; /**< ineffiency factor for non-uniform grids <= 1 */
88     real              ewaldcoeff_q;    /**< Electrostatic Ewald coefficient            */
89     real              ewaldcoeff_lj;   /**< LJ Ewald coefficient, only for the call to send_switchgrid */
90     struct gmx_pme_t *pmedata;         /**< the data structure used in the PME code      */
91     int               count;           /**< number of times this setup has been timed    */
92     double            cycles;          /**< the fastest time for this setup in cycles    */
93 };
94
95 /*! \brief After 50 nstlist periods of not observing imbalance: never tune PME */
96 const int  PMETunePeriod = 50;
97 /*! \brief Trigger PME load balancing at more than 5% PME overload */
98 const real loadBalanceTriggerFactor = 1.05;
99 /*! \brief In the initial scan, step by grids that are at least a factor 0.8 coarser */
100 const real gridScaleFactor = 0.8;
101 /*! \brief In the initial scan, try to skip grids with uneven x/y/z spacing,
102  * checking if the "efficiency" is more than 5% worse than the previous grid.
103  */
104 const real relativeEfficiencyFactor = 1.05;
105 /*! \brief Rerun until a run is 12% slower setups than the fastest run so far */
106 const real maxRelativeSlowdownAccepted = 1.12;
107 /*! \brief If setups get more than 2% faster, do another round to avoid
108  * choosing a slower setup due to acceleration or fluctuations.
109  */
110 const real maxFluctuationAccepted = 1.02;
111
112 /*! \brief Enumeration whose values describe the effect limiting the load balancing */
113 enum epmelb {
114     epmelblimNO, epmelblimBOX, epmelblimDD, epmelblimPMEGRID, epmelblimNR
115 };
116
117 /*! \brief Descriptive strings matching ::epmelb */
118 const char *pmelblim_str[epmelblimNR] =
119 { "no", "box size", "domain decompostion", "PME grid restriction" };
120
121 struct pme_load_balancing_t {
122     gmx_bool     bSepPMERanks;       /**< do we have separate PME ranks? */
123     gmx_bool     bActive;            /**< is PME tuning active? */
124     gmx_int64_t  step_rel_stop;      /**< stop the tuning after this value of step_rel */
125     gmx_bool     bTriggerOnDLB;      /**< trigger balancing only on DD DLB */
126     gmx_bool     bBalance;           /**< are we in the balancing phase, i.e. trying different setups? */
127     int          nstage;             /**< the current maximum number of stages */
128
129     real         cut_spacing;        /**< the minimum cutoff / PME grid spacing ratio */
130     real         rcut_vdw;           /**< Vdw cutoff (does not change) */
131     real         rcut_coulomb_start; /**< Initial electrostatics cutoff */
132     real         rbuf_coulomb;       /**< the pairlist buffer size */
133     real         rbuf_vdw;           /**< the pairlist buffer size */
134     matrix       box_start;          /**< the initial simulation box */
135     int          n;                  /**< the count of setup as well as the allocation size */
136     pme_setup_t *setup;              /**< the PME+cutoff setups */
137     int          cur;                /**< the inex (in setup) of the current setup */
138     int          fastest;            /**< index of the fastest setup up till now */
139     int          lower_limit;        /**< don't go below this setup index */
140     int          start;              /**< start of setup index range to consider in stage>0 */
141     int          end;                /**< end   of setup index range to consider in stage>0 */
142     int          elimited;           /**< was the balancing limited, uses enum above */
143     int          cutoff_scheme;      /**< Verlet or group cut-offs */
144
145     int          stage;              /**< the current stage */
146
147     int          cycles_n;           /**< step cycle counter cummulative count */
148     double       cycles_c;           /**< step cycle counter cummulative cycles */
149 };
150
151 /* TODO The code in this file should call this getter, rather than
152  * read bActive anywhere */
153 bool pme_loadbal_is_active(const pme_load_balancing_t *pme_lb)
154 {
155     return pme_lb != nullptr && pme_lb->bActive;
156 }
157
158 void pme_loadbal_init(pme_load_balancing_t     **pme_lb_p,
159                       t_commrec                 *cr,
160                       const gmx::MDLogger       &mdlog,
161                       const t_inputrec          *ir,
162                       matrix                     box,
163                       const interaction_const_t *ic,
164                       gmx_pme_t                 *pmedata,
165                       gmx_bool                   bUseGPU,
166                       gmx_bool                  *bPrinting)
167 {
168     pme_load_balancing_t *pme_lb;
169     real                  spm, sp;
170     int                   d;
171
172     // Note that we don't (yet) support PME load balancing with LJ-PME only.
173     GMX_RELEASE_ASSERT(EEL_PME(ir->coulombtype), "pme_loadbal_init called without PME electrostatics");
174     // To avoid complexity, we require a single cut-off with PME for q+LJ.
175     // This is checked by grompp, but it doesn't hurt to check again.
176     GMX_RELEASE_ASSERT(!(EEL_PME(ir->coulombtype) && EVDW_PME(ir->vdwtype) && ir->rcoulomb != ir->rvdw), "With Coulomb and LJ PME, rcoulomb should be equal to rvdw");
177
178     snew(pme_lb, 1);
179
180     pme_lb->bSepPMERanks  = !(cr->duty & DUTY_PME);
181
182     /* Initially we turn on balancing directly on based on PP/PME imbalance */
183     pme_lb->bTriggerOnDLB = FALSE;
184
185     /* Any number of stages >= 2 is supported */
186     pme_lb->nstage        = 2;
187
188     pme_lb->cutoff_scheme = ir->cutoff_scheme;
189
190     pme_lb->rbuf_coulomb  = ic->rlist - ic->rcoulomb;
191     pme_lb->rbuf_vdw      = ic->rlist - ic->rvdw;
192
193     copy_mat(box, pme_lb->box_start);
194     if (ir->ePBC == epbcXY && ir->nwall == 2)
195     {
196         svmul(ir->wall_ewald_zfac, pme_lb->box_start[ZZ], pme_lb->box_start[ZZ]);
197     }
198
199     pme_lb->n = 1;
200     snew(pme_lb->setup, pme_lb->n);
201
202     pme_lb->rcut_vdw                 = ic->rvdw;
203     pme_lb->rcut_coulomb_start       = ir->rcoulomb;
204
205     pme_lb->cur                      = 0;
206     pme_lb->setup[0].rcut_coulomb    = ic->rcoulomb;
207     pme_lb->setup[0].rlist           = ic->rlist;
208     pme_lb->setup[0].grid[XX]        = ir->nkx;
209     pme_lb->setup[0].grid[YY]        = ir->nky;
210     pme_lb->setup[0].grid[ZZ]        = ir->nkz;
211     pme_lb->setup[0].ewaldcoeff_q    = ic->ewaldcoeff_q;
212     pme_lb->setup[0].ewaldcoeff_lj   = ic->ewaldcoeff_lj;
213
214     pme_lb->setup[0].pmedata         = pmedata;
215
216     spm = 0;
217     for (d = 0; d < DIM; d++)
218     {
219         sp = norm(pme_lb->box_start[d])/pme_lb->setup[0].grid[d];
220         if (sp > spm)
221         {
222             spm = sp;
223         }
224     }
225     pme_lb->setup[0].spacing = spm;
226
227     if (ir->fourier_spacing > 0)
228     {
229         pme_lb->cut_spacing = ir->rcoulomb/ir->fourier_spacing;
230     }
231     else
232     {
233         pme_lb->cut_spacing = ir->rcoulomb/pme_lb->setup[0].spacing;
234     }
235
236     pme_lb->stage = 0;
237
238     pme_lb->fastest     = 0;
239     pme_lb->lower_limit = 0;
240     pme_lb->start       = 0;
241     pme_lb->end         = 0;
242     pme_lb->elimited    = epmelblimNO;
243
244     pme_lb->cycles_n = 0;
245     pme_lb->cycles_c = 0;
246
247     if (!wallcycle_have_counter())
248     {
249         GMX_LOG(mdlog.warning).asParagraph().appendText("NOTE: Cycle counters unsupported or not enabled in kernel. Cannot use PME-PP balancing.");
250     }
251
252     /* Tune with GPUs and/or separate PME ranks.
253      * When running only on a CPU without PME ranks, PME tuning will only help
254      * with small numbers of atoms in the cut-off sphere.
255      */
256     pme_lb->bActive  = (wallcycle_have_counter() && (bUseGPU ||
257                                                      pme_lb->bSepPMERanks));
258
259     /* With GPUs and no separate PME ranks we can't measure the PP/PME
260      * imbalance, so we start balancing right away.
261      * Otherwise we only start balancing after we observe imbalance.
262      */
263     pme_lb->bBalance = (pme_lb->bActive && (bUseGPU && !pme_lb->bSepPMERanks));
264
265     pme_lb->step_rel_stop = PMETunePeriod*ir->nstlist;
266
267     /* Delay DD load balancing when GPUs are used */
268     if (pme_lb->bActive && DOMAINDECOMP(cr) && cr->dd->nnodes > 1 && bUseGPU)
269     {
270         /* Lock DLB=auto to off (does nothing when DLB=yes/no.
271          * With GPUs and separate PME nodes, we want to first
272          * do PME tuning without DLB, since DLB might limit
273          * the cut-off, which never improves performance.
274          * We allow for DLB + PME tuning after a first round of tuning.
275          */
276         dd_dlb_lock(cr->dd);
277         if (dd_dlb_is_locked(cr->dd))
278         {
279             GMX_LOG(mdlog.warning).asParagraph().appendText("NOTE: DLB will not turn on during the first phase of PME tuning");
280         }
281     }
282
283     *pme_lb_p = pme_lb;
284
285     *bPrinting = pme_lb->bBalance;
286 }
287
288 /*! \brief Try to increase the cutoff during load balancing */
289 static gmx_bool pme_loadbal_increase_cutoff(pme_load_balancing_t *pme_lb,
290                                             int                   pme_order,
291                                             const gmx_domdec_t   *dd)
292 {
293     pme_setup_t *set;
294     int          npmeranks_x, npmeranks_y;
295     real         fac, sp;
296     real         tmpr_coulomb, tmpr_vdw;
297     int          d;
298     bool         grid_ok;
299
300     /* Try to add a new setup with next larger cut-off to the list */
301     pme_lb->n++;
302     srenew(pme_lb->setup, pme_lb->n);
303     set          = &pme_lb->setup[pme_lb->n-1];
304     set->pmedata = nullptr;
305
306     get_pme_nnodes(dd, &npmeranks_x, &npmeranks_y);
307
308     fac = 1;
309     do
310     {
311         /* Avoid infinite while loop, which can occur at the minimum grid size.
312          * Note that in practice load balancing will stop before this point.
313          * The factor 2.1 allows for the extreme case in which only grids
314          * of powers of 2 are allowed (the current code supports more grids).
315          */
316         if (fac > 2.1)
317         {
318             pme_lb->n--;
319
320             return FALSE;
321         }
322
323         fac *= 1.01;
324         clear_ivec(set->grid);
325         sp = calcFftGrid(nullptr, pme_lb->box_start,
326                          fac*pme_lb->setup[pme_lb->cur].spacing,
327                          minimalPmeGridSize(pme_order),
328                          &set->grid[XX],
329                          &set->grid[YY],
330                          &set->grid[ZZ]);
331
332         /* As here we can't easily check if one of the PME ranks
333          * uses threading, we do a conservative grid check.
334          * This means we can't use pme_order or less grid lines
335          * per PME rank along x, which is not a strong restriction.
336          */
337         grid_ok = gmx_pme_check_restrictions(pme_order,
338                                              set->grid[XX], set->grid[YY], set->grid[ZZ],
339                                              npmeranks_x,
340                                              true,
341                                              false);
342     }
343     while (sp <= 1.001*pme_lb->setup[pme_lb->cur].spacing || !grid_ok);
344
345     set->rcut_coulomb = pme_lb->cut_spacing*sp;
346     if (set->rcut_coulomb < pme_lb->rcut_coulomb_start)
347     {
348         /* This is unlikely, but can happen when e.g. continuing from
349          * a checkpoint after equilibration where the box shrank a lot.
350          * We want to avoid rcoulomb getting smaller than rvdw
351          * and there might be more issues with decreasing rcoulomb.
352          */
353         set->rcut_coulomb = pme_lb->rcut_coulomb_start;
354     }
355
356     if (pme_lb->cutoff_scheme == ecutsVERLET)
357     {
358         /* Never decrease the Coulomb and VdW list buffers */
359         set->rlist        = std::max(set->rcut_coulomb + pme_lb->rbuf_coulomb,
360                                      pme_lb->rcut_vdw + pme_lb->rbuf_vdw);
361     }
362     else
363     {
364         tmpr_coulomb          = set->rcut_coulomb + pme_lb->rbuf_coulomb;
365         tmpr_vdw              = pme_lb->rcut_vdw + pme_lb->rbuf_vdw;
366         set->rlist            = std::min(tmpr_coulomb, tmpr_vdw);
367     }
368
369     set->spacing      = sp;
370     /* The grid efficiency is the size wrt a grid with uniform x/y/z spacing */
371     set->grid_efficiency = 1;
372     for (d = 0; d < DIM; d++)
373     {
374         set->grid_efficiency *= (set->grid[d]*sp)/norm(pme_lb->box_start[d]);
375     }
376     /* The Ewald coefficient is inversly proportional to the cut-off */
377     set->ewaldcoeff_q =
378         pme_lb->setup[0].ewaldcoeff_q*pme_lb->setup[0].rcut_coulomb/set->rcut_coulomb;
379     /* We set ewaldcoeff_lj in set, even when LJ-PME is not used */
380     set->ewaldcoeff_lj =
381         pme_lb->setup[0].ewaldcoeff_lj*pme_lb->setup[0].rcut_coulomb/set->rcut_coulomb;
382
383     set->count   = 0;
384     set->cycles  = 0;
385
386     if (debug)
387     {
388         fprintf(debug, "PME loadbal: grid %d %d %d, coulomb cutoff %f\n",
389                 set->grid[XX], set->grid[YY], set->grid[ZZ], set->rcut_coulomb);
390     }
391     return TRUE;
392 }
393
394 /*! \brief Print the PME grid */
395 static void print_grid(FILE *fp_err, FILE *fp_log,
396                        const char *pre,
397                        const char *desc,
398                        const pme_setup_t *set,
399                        double cycles)
400 {
401     char buf[STRLEN], buft[STRLEN];
402
403     if (cycles >= 0)
404     {
405         sprintf(buft, ": %.1f M-cycles", cycles*1e-6);
406     }
407     else
408     {
409         buft[0] = '\0';
410     }
411     sprintf(buf, "%-11s%10s pme grid %d %d %d, coulomb cutoff %.3f%s",
412             pre,
413             desc, set->grid[XX], set->grid[YY], set->grid[ZZ], set->rcut_coulomb,
414             buft);
415     if (fp_err != nullptr)
416     {
417         fprintf(fp_err, "\r%s\n", buf);
418         fflush(fp_err);
419     }
420     if (fp_log != nullptr)
421     {
422         fprintf(fp_log, "%s\n", buf);
423     }
424 }
425
426 /*! \brief Return the index of the last setup used in PME load balancing */
427 static int pme_loadbal_end(pme_load_balancing_t *pme_lb)
428 {
429     /* In the initial stage only n is set; end is not set yet */
430     if (pme_lb->end > 0)
431     {
432         return pme_lb->end;
433     }
434     else
435     {
436         return pme_lb->n;
437     }
438 }
439
440 /*! \brief Print descriptive string about what limits PME load balancing */
441 static void print_loadbal_limited(FILE *fp_err, FILE *fp_log,
442                                   gmx_int64_t step,
443                                   pme_load_balancing_t *pme_lb)
444 {
445     char buf[STRLEN], sbuf[22];
446
447     sprintf(buf, "step %4s: the %s limits the PME load balancing to a coulomb cut-off of %.3f",
448             gmx_step_str(step, sbuf),
449             pmelblim_str[pme_lb->elimited],
450             pme_lb->setup[pme_loadbal_end(pme_lb)-1].rcut_coulomb);
451     if (fp_err != nullptr)
452     {
453         fprintf(fp_err, "\r%s\n", buf);
454         fflush(fp_err);
455     }
456     if (fp_log != nullptr)
457     {
458         fprintf(fp_log, "%s\n", buf);
459     }
460 }
461
462 /*! \brief Switch load balancing to stage 1
463  *
464  * In this stage, only reasonably fast setups are run again. */
465 static void switch_to_stage1(pme_load_balancing_t *pme_lb)
466 {
467     /* Increase start until we find a setup that is not slower than
468      * maxRelativeSlowdownAccepted times the fastest setup.
469      */
470     pme_lb->start = pme_lb->lower_limit;
471     while (pme_lb->start + 1 < pme_lb->n &&
472            (pme_lb->setup[pme_lb->start].count == 0 ||
473             pme_lb->setup[pme_lb->start].cycles >
474             pme_lb->setup[pme_lb->fastest].cycles*maxRelativeSlowdownAccepted))
475     {
476         pme_lb->start++;
477     }
478     /* While increasing start, we might have skipped setups that we did not
479      * time during stage 0. We want to extend the range for stage 1 to include
480      * any skipped setups that lie between setups that were measured to be
481      * acceptably fast and too slow.
482      */
483     while (pme_lb->start > pme_lb->lower_limit &&
484            pme_lb->setup[pme_lb->start - 1].count == 0)
485     {
486         pme_lb->start--;
487     }
488
489     /* Decrease end only with setups that we timed and that are slow. */
490     pme_lb->end = pme_lb->n;
491     if (pme_lb->setup[pme_lb->end - 1].count > 0 &&
492         pme_lb->setup[pme_lb->end - 1].cycles >
493         pme_lb->setup[pme_lb->fastest].cycles*maxRelativeSlowdownAccepted)
494     {
495         pme_lb->end--;
496     }
497
498     pme_lb->stage = 1;
499
500     /* Next we want to choose setup pme_lb->end-1, but as we will decrease
501      * pme_lb->cur by one right after returning, we set cur to end.
502      */
503     pme_lb->cur = pme_lb->end;
504 }
505
506 /*! \brief Process the timings and try to adjust the PME grid and Coulomb cut-off
507  *
508  * The adjustment is done to generate a different non-bonded PP and PME load.
509  * With separate PME ranks (PP and PME on different processes) or with
510  * a GPU (PP on GPU, PME on CPU), PP and PME run on different resources
511  * and changing the load will affect the load balance and performance.
512  * The total time for a set of integration steps is monitored and a range
513  * of grid/cut-off setups is scanned. After calling pme_load_balance many
514  * times and acquiring enough statistics, the best performing setup is chosen.
515  * Here we try to take into account fluctuations and changes due to external
516  * factors as well as DD load balancing.
517  */
518 static void
519 pme_load_balance(pme_load_balancing_t      *pme_lb,
520                  t_commrec                 *cr,
521                  FILE                      *fp_err,
522                  FILE                      *fp_log,
523                  const gmx::MDLogger       &mdlog,
524                  const t_inputrec          *ir,
525                  t_state                   *state,
526                  double                     cycles,
527                  interaction_const_t       *ic,
528                  struct nonbonded_verlet_t *nbv,
529                  struct gmx_pme_t **        pmedata,
530                  gmx_int64_t                step)
531 {
532     gmx_bool     OK;
533     pme_setup_t *set;
534     double       cycles_fast;
535     char         buf[STRLEN], sbuf[22];
536     real         rtab;
537
538     if (PAR(cr))
539     {
540         gmx_sumd(1, &cycles, cr);
541         cycles /= cr->nnodes;
542     }
543
544     set = &pme_lb->setup[pme_lb->cur];
545     set->count++;
546
547     rtab = ir->rlist + ir->tabext;
548
549     if (set->count % 2 == 1)
550     {
551         /* Skip the first cycle, because the first step after a switch
552          * is much slower due to allocation and/or caching effects.
553          */
554         return;
555     }
556
557     sprintf(buf, "step %4s: ", gmx_step_str(step, sbuf));
558     print_grid(fp_err, fp_log, buf, "timed with", set, cycles);
559
560     if (set->count <= 2)
561     {
562         set->cycles = cycles;
563     }
564     else
565     {
566         if (cycles*maxFluctuationAccepted < set->cycles &&
567             pme_lb->stage == pme_lb->nstage - 1)
568         {
569             /* The performance went up a lot (due to e.g. DD load balancing).
570              * Add a stage, keep the minima, but rescan all setups.
571              */
572             pme_lb->nstage++;
573
574             if (debug)
575             {
576                 fprintf(debug, "The performance for grid %d %d %d went from %.3f to %.1f M-cycles, this is more than %f\n"
577                         "Increased the number stages to %d"
578                         " and ignoring the previous performance\n",
579                         set->grid[XX], set->grid[YY], set->grid[ZZ],
580                         set->cycles*1e-6, cycles*1e-6, maxFluctuationAccepted,
581                         pme_lb->nstage);
582             }
583         }
584         set->cycles = std::min(set->cycles, cycles);
585     }
586
587     if (set->cycles < pme_lb->setup[pme_lb->fastest].cycles)
588     {
589         pme_lb->fastest = pme_lb->cur;
590
591         if (DOMAINDECOMP(cr))
592         {
593             /* We found a new fastest setting, ensure that with subsequent
594              * shorter cut-off's the dynamic load balancing does not make
595              * the use of the current cut-off impossible. This solution is
596              * a trade-off, as the PME load balancing and DD domain size
597              * load balancing can interact in complex ways.
598              * With the Verlet kernels, DD load imbalance will usually be
599              * mainly due to bonded interaction imbalance, which will often
600              * quickly push the domain boundaries beyond the limit for the
601              * optimal, PME load balanced, cut-off. But it could be that
602              * better overal performance can be obtained with a slightly
603              * shorter cut-off and better DD load balancing.
604              */
605             set_dd_dlb_max_cutoff(cr, pme_lb->setup[pme_lb->fastest].rlist);
606         }
607     }
608     cycles_fast = pme_lb->setup[pme_lb->fastest].cycles;
609
610     /* Check in stage 0 if we should stop scanning grids.
611      * Stop when the time is more than maxRelativeSlowDownAccepted longer than the fastest.
612      */
613     if (pme_lb->stage == 0 && pme_lb->cur > 0 &&
614         cycles > pme_lb->setup[pme_lb->fastest].cycles*maxRelativeSlowdownAccepted)
615     {
616         pme_lb->n = pme_lb->cur + 1;
617         /* Done with scanning, go to stage 1 */
618         switch_to_stage1(pme_lb);
619     }
620
621     if (pme_lb->stage == 0)
622     {
623         int gridsize_start;
624
625         gridsize_start = set->grid[XX]*set->grid[YY]*set->grid[ZZ];
626
627         do
628         {
629             if (pme_lb->cur+1 < pme_lb->n)
630             {
631                 /* We had already generated the next setup */
632                 OK = TRUE;
633             }
634             else
635             {
636                 /* Find the next setup */
637                 OK = pme_loadbal_increase_cutoff(pme_lb, ir->pme_order, cr->dd);
638
639                 if (!OK)
640                 {
641                     pme_lb->elimited = epmelblimPMEGRID;
642                 }
643             }
644
645             if (OK && ir->ePBC != epbcNONE)
646             {
647                 OK = (gmx::square(pme_lb->setup[pme_lb->cur+1].rlist)
648                       <= max_cutoff2(ir->ePBC, state->box));
649                 if (!OK)
650                 {
651                     pme_lb->elimited = epmelblimBOX;
652                 }
653             }
654
655             if (OK)
656             {
657                 pme_lb->cur++;
658
659                 if (DOMAINDECOMP(cr))
660                 {
661                     OK = change_dd_cutoff(cr, state, ir,
662                                           pme_lb->setup[pme_lb->cur].rlist);
663                     if (!OK)
664                     {
665                         /* Failed: do not use this setup */
666                         pme_lb->cur--;
667                         pme_lb->elimited = epmelblimDD;
668                     }
669                 }
670             }
671             if (!OK)
672             {
673                 /* We hit the upper limit for the cut-off,
674                  * the setup should not go further than cur.
675                  */
676                 pme_lb->n = pme_lb->cur + 1;
677                 print_loadbal_limited(fp_err, fp_log, step, pme_lb);
678                 /* Switch to the next stage */
679                 switch_to_stage1(pme_lb);
680             }
681         }
682         while (OK &&
683                !(pme_lb->setup[pme_lb->cur].grid[XX]*
684                  pme_lb->setup[pme_lb->cur].grid[YY]*
685                  pme_lb->setup[pme_lb->cur].grid[ZZ] <
686                  gridsize_start*gridScaleFactor
687                  &&
688                  pme_lb->setup[pme_lb->cur].grid_efficiency <
689                  pme_lb->setup[pme_lb->cur-1].grid_efficiency*relativeEfficiencyFactor));
690     }
691
692     if (pme_lb->stage > 0 && pme_lb->end == 1)
693     {
694         pme_lb->cur   = pme_lb->lower_limit;
695         pme_lb->stage = pme_lb->nstage;
696     }
697     else if (pme_lb->stage > 0 && pme_lb->end > 1)
698     {
699         /* If stage = nstage-1:
700          *   scan over all setups, rerunning only those setups
701          *   which are not much slower than the fastest
702          * else:
703          *   use the next setup
704          * Note that we loop backward to minimize the risk of the cut-off
705          * getting limited by DD DLB, since the DLB cut-off limit is set
706          * to the fastest PME setup.
707          */
708         do
709         {
710             if (pme_lb->cur > pme_lb->start)
711             {
712                 pme_lb->cur--;
713             }
714             else
715             {
716                 pme_lb->stage++;
717
718                 pme_lb->cur = pme_lb->end - 1;
719             }
720         }
721         while (pme_lb->stage == pme_lb->nstage - 1 &&
722                pme_lb->setup[pme_lb->cur].count > 0 &&
723                pme_lb->setup[pme_lb->cur].cycles > cycles_fast*maxRelativeSlowdownAccepted);
724
725         if (pme_lb->stage == pme_lb->nstage)
726         {
727             /* We are done optimizing, use the fastest setup we found */
728             pme_lb->cur = pme_lb->fastest;
729         }
730     }
731
732     if (DOMAINDECOMP(cr) && pme_lb->stage > 0)
733     {
734         OK = change_dd_cutoff(cr, state, ir, pme_lb->setup[pme_lb->cur].rlist);
735         if (!OK)
736         {
737             /* For some reason the chosen cut-off is incompatible with DD.
738              * We should continue scanning a more limited range of cut-off's.
739              */
740             if (pme_lb->cur > 1 && pme_lb->stage == pme_lb->nstage)
741             {
742                 /* stage=nstage says we're finished, but we should continue
743                  * balancing, so we set back stage which was just incremented.
744                  */
745                 pme_lb->stage--;
746             }
747             if (pme_lb->cur <= pme_lb->fastest)
748             {
749                 /* This should not happen, as we set limits on the DLB bounds.
750                  * But we implement a complete failsafe solution anyhow.
751                  */
752                 GMX_LOG(mdlog.warning).asParagraph().appendTextFormatted(
753                         "The fastest PP/PME load balancing setting (cutoff %.3f nm) is no longer available due to DD DLB or box size limitations", pme_lb->fastest);
754                 pme_lb->fastest = pme_lb->lower_limit;
755                 pme_lb->start   = pme_lb->lower_limit;
756             }
757             /* Limit the range to below the current cut-off, scan from start */
758             pme_lb->end         = pme_lb->cur;
759             pme_lb->cur         = pme_lb->start;
760             pme_lb->elimited    = epmelblimDD;
761             print_loadbal_limited(fp_err, fp_log, step, pme_lb);
762         }
763     }
764
765     /* Change the Coulomb cut-off and the PME grid */
766
767     set = &pme_lb->setup[pme_lb->cur];
768
769     ic->rcoulomb     = set->rcut_coulomb;
770     ic->rlist        = set->rlist;
771     ic->ewaldcoeff_q = set->ewaldcoeff_q;
772     /* TODO: centralize the code that sets the potentials shifts */
773     if (ic->coulomb_modifier == eintmodPOTSHIFT)
774     {
775         ic->sh_ewald = std::erfc(ic->ewaldcoeff_q*ic->rcoulomb);
776     }
777     if (EVDW_PME(ic->vdwtype))
778     {
779         /* We have PME for both Coulomb and VdW, set rvdw equal to rcoulomb */
780         ic->rvdw            = set->rcut_coulomb;
781         ic->ewaldcoeff_lj   = set->ewaldcoeff_lj;
782         if (ic->vdw_modifier == eintmodPOTSHIFT)
783         {
784             real       crc2;
785
786             ic->dispersion_shift.cpot = -1.0/gmx::power6(static_cast<double>(ic->rvdw));
787             ic->repulsion_shift.cpot  = -1.0/gmx::power12(static_cast<double>(ic->rvdw));
788             ic->sh_invrc6             = -ic->dispersion_shift.cpot;
789             crc2                      = gmx::square(ic->ewaldcoeff_lj*ic->rvdw);
790             ic->sh_lj_ewald           = (std::exp(-crc2)*(1 + crc2 + 0.5*crc2*crc2) - 1)/gmx::power6(ic->rvdw);
791         }
792     }
793
794     /* We always re-initialize the tables whether they are used or not */
795     init_interaction_const_tables(nullptr, ic, rtab);
796
797     nbnxn_gpu_pme_loadbal_update_param(nbv, ic);
798
799     /* With tMPI + GPUs some ranks may be sharing GPU(s) and therefore
800      * also sharing texture references. To keep the code simple, we don't
801      * treat texture references as shared resources, but this means that
802      * the coulomb_tab texture ref will get updated by multiple threads.
803      * Hence, to ensure that the non-bonded kernels don't start before all
804      * texture binding operations are finished, we need to wait for all ranks
805      * to arrive here before continuing.
806      *
807      * Note that we could omit this barrier if GPUs are not shared (or
808      * texture objects are used), but as this is initialization code, there
809      * is not point in complicating things.
810      */
811 #if GMX_THREAD_MPI
812     if (PAR(cr) && use_GPU(nbv))
813     {
814         gmx_barrier(cr);
815     }
816 #endif  /* GMX_THREAD_MPI */
817
818     if (!pme_lb->bSepPMERanks)
819     {
820         if (pme_lb->setup[pme_lb->cur].pmedata == nullptr)
821         {
822             /* Generate a new PME data structure,
823              * copying part of the old pointers.
824              */
825             gmx_pme_reinit(&set->pmedata,
826                            cr, pme_lb->setup[0].pmedata, ir,
827                            set->grid, set->ewaldcoeff_q, set->ewaldcoeff_lj);
828         }
829         *pmedata = set->pmedata;
830     }
831     else
832     {
833         /* Tell our PME-only rank to switch grid */
834         gmx_pme_send_switchgrid(cr, set->grid, set->ewaldcoeff_q, set->ewaldcoeff_lj);
835     }
836
837     if (debug)
838     {
839         print_grid(nullptr, debug, "", "switched to", set, -1);
840     }
841
842     if (pme_lb->stage == pme_lb->nstage)
843     {
844         print_grid(fp_err, fp_log, "", "optimal", set, -1);
845     }
846 }
847
848 /*! \brief Prepare for another round of PME load balancing
849  *
850  * \param[in,out] pme_lb       Pointer to PME load balancing struct
851  * \param[in]     bDlbUnlocked TRUE is DLB was locked and is now unlocked
852  *
853  * If the conditions (e.g. DLB off/on, CPU/GPU throttling etc.) changed,
854  * the PP/PME balance might change and re-balancing can improve performance.
855  * This function adds 2 stages and adjusts the considered setup range.
856  */
857 static void continue_pme_loadbal(pme_load_balancing_t *pme_lb,
858                                  gmx_bool              bDlbUnlocked)
859 {
860     /* Add 2 tuning stages, keep the detected end of the setup range */
861     pme_lb->nstage          += 2;
862     if (bDlbUnlocked && pme_lb->bSepPMERanks)
863     {
864         /* With separate PME ranks, DLB should always lower the PP load and
865          * can only increase the PME load (more communication and imbalance),
866          * so we only need to scan longer cut-off's.
867          */
868         pme_lb->lower_limit  = pme_lb->cur;
869     }
870     pme_lb->start            = pme_lb->lower_limit;
871 }
872
873 void pme_loadbal_do(pme_load_balancing_t *pme_lb,
874                     t_commrec            *cr,
875                     FILE                 *fp_err,
876                     FILE                 *fp_log,
877                     const gmx::MDLogger  &mdlog,
878                     const t_inputrec     *ir,
879                     t_forcerec           *fr,
880                     t_state              *state,
881                     gmx_wallcycle_t       wcycle,
882                     gmx_int64_t           step,
883                     gmx_int64_t           step_rel,
884                     gmx_bool             *bPrinting)
885 {
886     int    n_prev;
887     double cycles_prev;
888
889     assert(pme_lb != NULL);
890
891     if (!pme_lb->bActive)
892     {
893         return;
894     }
895
896     n_prev      = pme_lb->cycles_n;
897     cycles_prev = pme_lb->cycles_c;
898     wallcycle_get(wcycle, ewcSTEP, &pme_lb->cycles_n, &pme_lb->cycles_c);
899
900     /* Before the first step we haven't done any steps yet.
901      * Also handle cases where ir->init_step % ir->nstlist != 0.
902      */
903     if (pme_lb->cycles_n < ir->nstlist)
904     {
905         return;
906     }
907     /* Sanity check, we expect nstlist cycle counts */
908     if (pme_lb->cycles_n - n_prev != ir->nstlist)
909     {
910         /* We could return here, but it's safer to issue an error and quit */
911         gmx_incons("pme_loadbal_do called at an interval != nstlist");
912     }
913
914     /* PME grid + cut-off optimization with GPUs or PME ranks */
915     if (!pme_lb->bBalance && pme_lb->bSepPMERanks)
916     {
917         if (pme_lb->bTriggerOnDLB)
918         {
919             pme_lb->bBalance = dd_dlb_is_on(cr->dd);
920         }
921         /* We should ignore the first timing to avoid timing allocation
922          * overhead. And since the PME load balancing is called just
923          * before DD repartitioning, the ratio returned by dd_pme_f_ratio
924          * is not over the last nstlist steps, but the nstlist steps before
925          * that. So the first useful ratio is available at step_rel=3*nstlist.
926          */
927         else if (step_rel >= 3*ir->nstlist)
928         {
929             if (DDMASTER(cr->dd))
930             {
931                 /* If PME rank load is too high, start tuning */
932                 pme_lb->bBalance =
933                     (dd_pme_f_ratio(cr->dd) >= loadBalanceTriggerFactor);
934             }
935             dd_bcast(cr->dd, sizeof(gmx_bool), &pme_lb->bBalance);
936         }
937
938         pme_lb->bActive = (pme_lb->bBalance ||
939                            step_rel <= pme_lb->step_rel_stop);
940     }
941
942     /* The location in the code of this balancing termination is strange.
943      * You would expect to have it after the call to pme_load_balance()
944      * below, since there pme_lb->stage is updated.
945      * But when terminating directly after deciding on and selecting the
946      * optimal setup, DLB will turn on right away if it was locked before.
947      * This might be due to PME reinitialization. So we check stage here
948      * to allow for another nstlist steps with DLB locked to stabilize
949      * the performance.
950      */
951     if (pme_lb->bBalance && pme_lb->stage == pme_lb->nstage)
952     {
953         pme_lb->bBalance = FALSE;
954
955         if (DOMAINDECOMP(cr) && dd_dlb_is_locked(cr->dd))
956         {
957             /* Unlock the DLB=auto, DLB is allowed to activate */
958             dd_dlb_unlock(cr->dd);
959             GMX_LOG(mdlog.warning).asParagraph().appendText("NOTE: DLB can now turn on, when beneficial");
960
961             /* We don't deactivate the tuning yet, since we will balance again
962              * after DLB gets turned on, if it does within PMETune_period.
963              */
964             continue_pme_loadbal(pme_lb, TRUE);
965             pme_lb->bTriggerOnDLB = TRUE;
966             pme_lb->step_rel_stop = step_rel + PMETunePeriod*ir->nstlist;
967         }
968         else
969         {
970             /* We're completely done with PME tuning */
971             pme_lb->bActive = FALSE;
972         }
973
974         if (DOMAINDECOMP(cr))
975         {
976             /* Set the cut-off limit to the final selected cut-off,
977              * so we don't have artificial DLB limits.
978              * This also ensures that we won't disable the currently
979              * optimal setting during a second round of PME balancing.
980              */
981             set_dd_dlb_max_cutoff(cr, fr->ic->rlist);
982         }
983     }
984
985     if (pme_lb->bBalance)
986     {
987         /* We might not have collected nstlist steps in cycles yet,
988          * since init_step might not be a multiple of nstlist,
989          * but the first data collected is skipped anyhow.
990          */
991         pme_load_balance(pme_lb, cr,
992                          fp_err, fp_log, mdlog,
993                          ir, state, pme_lb->cycles_c - cycles_prev,
994                          fr->ic, fr->nbv, &fr->pmedata,
995                          step);
996
997         /* Update constants in forcerec/inputrec to keep them in sync with fr->ic */
998         fr->ewaldcoeff_q  = fr->ic->ewaldcoeff_q;
999         fr->ewaldcoeff_lj = fr->ic->ewaldcoeff_lj;
1000         fr->rlist         = fr->ic->rlist;
1001         fr->rcoulomb      = fr->ic->rcoulomb;
1002         fr->rvdw          = fr->ic->rvdw;
1003
1004         if (ir->eDispCorr != edispcNO)
1005         {
1006             calc_enervirdiff(nullptr, ir->eDispCorr, fr);
1007         }
1008     }
1009
1010     if (!pme_lb->bBalance &&
1011         (!pme_lb->bSepPMERanks || step_rel > pme_lb->step_rel_stop))
1012     {
1013         /* We have just deactivated the balancing and we're not measuring PP/PME
1014          * imbalance during the first steps of the run: deactivate the tuning.
1015          */
1016         pme_lb->bActive = FALSE;
1017     }
1018
1019     if (!(pme_lb->bActive) && DOMAINDECOMP(cr) && dd_dlb_is_locked(cr->dd))
1020     {
1021         /* Make sure DLB is allowed when we deactivate PME tuning */
1022         dd_dlb_unlock(cr->dd);
1023         GMX_LOG(mdlog.warning).asParagraph().appendText("NOTE: DLB can now turn on, when beneficial");
1024     }
1025
1026     *bPrinting = pme_lb->bBalance;
1027 }
1028
1029 /*! \brief Return product of the number of PME grid points in each dimension */
1030 static int pme_grid_points(const pme_setup_t *setup)
1031 {
1032     return setup->grid[XX]*setup->grid[YY]*setup->grid[ZZ];
1033 }
1034
1035 /*! \brief Print one load-balancing setting */
1036 static void print_pme_loadbal_setting(FILE              *fplog,
1037                                       const char        *name,
1038                                       const pme_setup_t *setup)
1039 {
1040     fprintf(fplog,
1041             "   %-7s %6.3f nm %6.3f nm     %3d %3d %3d   %5.3f nm  %5.3f nm\n",
1042             name,
1043             setup->rcut_coulomb, setup->rlist,
1044             setup->grid[XX], setup->grid[YY], setup->grid[ZZ],
1045             setup->spacing, 1/setup->ewaldcoeff_q);
1046 }
1047
1048 /*! \brief Print all load-balancing settings */
1049 static void print_pme_loadbal_settings(pme_load_balancing_t *pme_lb,
1050                                        FILE                 *fplog,
1051                                        const gmx::MDLogger  &mdlog,
1052                                        gmx_bool              bNonBondedOnGPU)
1053 {
1054     double     pp_ratio, grid_ratio;
1055     real       pp_ratio_temporary;
1056
1057     pp_ratio_temporary = pme_lb->setup[pme_lb->cur].rlist / pme_lb->setup[0].rlist;
1058     pp_ratio           = gmx::power3(pp_ratio_temporary);
1059     grid_ratio         = pme_grid_points(&pme_lb->setup[pme_lb->cur])/
1060         (double)pme_grid_points(&pme_lb->setup[0]);
1061
1062     fprintf(fplog, "\n");
1063     fprintf(fplog, "       P P   -   P M E   L O A D   B A L A N C I N G\n");
1064     fprintf(fplog, "\n");
1065     /* Here we only warn when the optimal setting is the last one */
1066     if (pme_lb->elimited != epmelblimNO &&
1067         pme_lb->cur == pme_loadbal_end(pme_lb)-1)
1068     {
1069         fprintf(fplog, " NOTE: The PP/PME load balancing was limited by the %s,\n",
1070                 pmelblim_str[pme_lb->elimited]);
1071         fprintf(fplog, "       you might not have reached a good load balance.\n");
1072         if (pme_lb->elimited == epmelblimDD)
1073         {
1074             fprintf(fplog, "       Try different mdrun -dd settings or lower the -dds value.\n");
1075         }
1076         fprintf(fplog, "\n");
1077     }
1078     fprintf(fplog, " PP/PME load balancing changed the cut-off and PME settings:\n");
1079     fprintf(fplog, "           particle-particle                    PME\n");
1080     fprintf(fplog, "            rcoulomb  rlist            grid      spacing   1/beta\n");
1081     print_pme_loadbal_setting(fplog, "initial", &pme_lb->setup[0]);
1082     print_pme_loadbal_setting(fplog, "final", &pme_lb->setup[pme_lb->cur]);
1083     fprintf(fplog, " cost-ratio           %4.2f             %4.2f\n",
1084             pp_ratio, grid_ratio);
1085     fprintf(fplog, " (note that these numbers concern only part of the total PP and PME load)\n");
1086
1087     if (pp_ratio > 1.5 && !bNonBondedOnGPU)
1088     {
1089         GMX_LOG(mdlog.warning).asParagraph().appendText(
1090                 "NOTE: PME load balancing increased the non-bonded workload by more than 50%.\n"
1091                 "      For better performance, use (more) PME ranks (mdrun -npme),\n"
1092                 "      or if you are beyond the scaling limit, use fewer total ranks (or nodes).");
1093     }
1094     else
1095     {
1096         fprintf(fplog, "\n");
1097     }
1098 }
1099
1100 void pme_loadbal_done(pme_load_balancing_t *pme_lb,
1101                       FILE                 *fplog,
1102                       const gmx::MDLogger  &mdlog,
1103                       gmx_bool              bNonBondedOnGPU)
1104 {
1105     if (fplog != nullptr && (pme_lb->cur > 0 || pme_lb->elimited != epmelblimNO))
1106     {
1107         print_pme_loadbal_settings(pme_lb, fplog, mdlog, bNonBondedOnGPU);
1108     }
1109
1110     /* TODO: Here we should free all pointers in pme_lb,
1111      * but as it contains pme data structures,
1112      * we need to first make pme.c free all data.
1113      */
1114 }