Sort includes outside src/gromacs
[alexxy/gromacs.git] / src / programs / mdrun / pme_loadbal.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014, 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 #include "gmxpre.h"
36
37 #include "pme_loadbal.h"
38
39 #include "config.h"
40
41 #include "gromacs/legacyheaders/calcgrid.h"
42 #include "gromacs/legacyheaders/domdec.h"
43 #include "gromacs/legacyheaders/force.h"
44 #include "gromacs/legacyheaders/macros.h"
45 #include "gromacs/legacyheaders/md_logging.h"
46 #include "gromacs/legacyheaders/network.h"
47 #include "gromacs/legacyheaders/pme.h"
48 #include "gromacs/legacyheaders/sim_util.h"
49 #include "gromacs/legacyheaders/types/commrec.h"
50 #include "gromacs/math/vec.h"
51 #include "gromacs/mdlib/nbnxn_cuda/nbnxn_cuda_data_mgmt.h"
52 #include "gromacs/pbcutil/pbc.h"
53 #include "gromacs/utility/cstringutil.h"
54 #include "gromacs/utility/smalloc.h"
55
56 /* Parameters and setting for one PP-PME setup */
57 typedef struct {
58     real      rcut_coulomb;    /* Coulomb cut-off                              */
59     real      rlist;           /* pair-list cut-off                            */
60     real      rlistlong;       /* LR pair-list cut-off                         */
61     int       nstcalclr;       /* frequency of evaluating long-range forces for group scheme */
62     real      spacing;         /* (largest) PME grid spacing                   */
63     ivec      grid;            /* the PME grid dimensions                      */
64     real      grid_efficiency; /* ineffiency factor for non-uniform grids <= 1 */
65     real      ewaldcoeff_q;    /* Electrostatic Ewald coefficient            */
66     real      ewaldcoeff_lj;   /* LJ Ewald coefficient, only for the call to send_switchgrid */
67     gmx_pme_t pmedata;         /* the data structure used in the PME code      */
68     int       count;           /* number of times this setup has been timed    */
69     double    cycles;          /* the fastest time for this setup in cycles    */
70 } pme_setup_t;
71
72 /* In the initial scan, step by grids that are at least a factor 0.8 coarser */
73 #define PME_LB_GRID_SCALE_FAC  0.8
74 /* In the initial scan, try to skip grids with uneven x/y/z spacing,
75  * checking if the "efficiency" is more than 5% worse than the previous grid.
76  */
77 #define PME_LB_GRID_EFFICIENCY_REL_FAC  1.05
78 /* Rerun up till 12% slower setups than the fastest up till now */
79 #define PME_LB_SLOW_FAC  1.12
80 /* If setups get more than 2% faster, do another round to avoid
81  * choosing a slower setup due to acceleration or fluctuations.
82  */
83 #define PME_LB_ACCEL_TOL 1.02
84
85 enum {
86     epmelblimNO, epmelblimBOX, epmelblimDD, epmelblimPMEGRID, epmelblimNR
87 };
88
89 const char *pmelblim_str[epmelblimNR] =
90 { "no", "box size", "domain decompostion", "PME grid restriction" };
91
92 struct pme_load_balancing {
93     int          nstage;             /* the current maximum number of stages */
94
95     real         cut_spacing;        /* the minimum cutoff / PME grid spacing ratio */
96     real         rcut_vdw;           /* Vdw cutoff (does not change) */
97     real         rcut_coulomb_start; /* Initial electrostatics cutoff */
98     int          nstcalclr_start;    /* Initial electrostatics cutoff */
99     real         rbuf_coulomb;       /* the pairlist buffer size */
100     real         rbuf_vdw;           /* the pairlist buffer size */
101     matrix       box_start;          /* the initial simulation box */
102     int          n;                  /* the count of setup as well as the allocation size */
103     pme_setup_t *setup;              /* the PME+cutoff setups */
104     int          cur;                /* the current setup */
105     int          fastest;            /* fastest setup up till now */
106     int          start;              /* start of setup range to consider in stage>0 */
107     int          end;                /* end   of setup range to consider in stage>0 */
108     int          elimited;           /* was the balancing limited, uses enum above */
109     int          cutoff_scheme;      /* Verlet or group cut-offs */
110
111     int          stage;              /* the current stage */
112 };
113
114 void pme_loadbal_init(pme_load_balancing_t *pme_lb_p,
115                       const t_inputrec *ir, matrix box,
116                       const interaction_const_t *ic,
117                       gmx_pme_t pmedata)
118 {
119     pme_load_balancing_t pme_lb;
120     real                 spm, sp;
121     int                  d;
122
123     snew(pme_lb, 1);
124
125     /* Any number of stages >= 2 is supported */
126     pme_lb->nstage   = 2;
127
128     pme_lb->cutoff_scheme = ir->cutoff_scheme;
129
130     if (pme_lb->cutoff_scheme == ecutsVERLET)
131     {
132         pme_lb->rbuf_coulomb = ic->rlist - ic->rcoulomb;
133         pme_lb->rbuf_vdw     = pme_lb->rbuf_coulomb;
134     }
135     else
136     {
137         if (ic->rcoulomb > ic->rlist)
138         {
139             pme_lb->rbuf_coulomb = ic->rlistlong - ic->rcoulomb;
140         }
141         else
142         {
143             pme_lb->rbuf_coulomb = ic->rlist - ic->rcoulomb;
144         }
145         if (ic->rvdw > ic->rlist)
146         {
147             pme_lb->rbuf_vdw = ic->rlistlong - ic->rvdw;
148         }
149         else
150         {
151             pme_lb->rbuf_vdw = ic->rlist - ic->rvdw;
152         }
153     }
154
155     copy_mat(box, pme_lb->box_start);
156     if (ir->ePBC == epbcXY && ir->nwall == 2)
157     {
158         svmul(ir->wall_ewald_zfac, pme_lb->box_start[ZZ], pme_lb->box_start[ZZ]);
159     }
160
161     pme_lb->n = 1;
162     snew(pme_lb->setup, pme_lb->n);
163
164     pme_lb->rcut_vdw                 = ic->rvdw;
165     pme_lb->rcut_coulomb_start       = ir->rcoulomb;
166     pme_lb->nstcalclr_start          = ir->nstcalclr;
167
168     pme_lb->cur                      = 0;
169     pme_lb->setup[0].rcut_coulomb    = ic->rcoulomb;
170     pme_lb->setup[0].rlist           = ic->rlist;
171     pme_lb->setup[0].rlistlong       = ic->rlistlong;
172     pme_lb->setup[0].nstcalclr       = ir->nstcalclr;
173     pme_lb->setup[0].grid[XX]        = ir->nkx;
174     pme_lb->setup[0].grid[YY]        = ir->nky;
175     pme_lb->setup[0].grid[ZZ]        = ir->nkz;
176     pme_lb->setup[0].ewaldcoeff_q    = ic->ewaldcoeff_q;
177     pme_lb->setup[0].ewaldcoeff_lj   = ic->ewaldcoeff_lj;
178
179     pme_lb->setup[0].pmedata  = pmedata;
180
181     spm = 0;
182     for (d = 0; d < DIM; d++)
183     {
184         sp = norm(pme_lb->box_start[d])/pme_lb->setup[0].grid[d];
185         if (sp > spm)
186         {
187             spm = sp;
188         }
189     }
190     pme_lb->setup[0].spacing = spm;
191
192     if (ir->fourier_spacing > 0)
193     {
194         pme_lb->cut_spacing = ir->rcoulomb/ir->fourier_spacing;
195     }
196     else
197     {
198         pme_lb->cut_spacing = ir->rcoulomb/pme_lb->setup[0].spacing;
199     }
200
201     pme_lb->stage = 0;
202
203     pme_lb->fastest  = 0;
204     pme_lb->start    = 0;
205     pme_lb->end      = 0;
206     pme_lb->elimited = epmelblimNO;
207
208     *pme_lb_p = pme_lb;
209 }
210
211 static gmx_bool pme_loadbal_increase_cutoff(pme_load_balancing_t  pme_lb,
212                                             int                   pme_order,
213                                             const gmx_domdec_t   *dd)
214 {
215     pme_setup_t *set;
216     int          npmenodes_x, npmenodes_y;
217     real         fac, sp;
218     real         tmpr_coulomb, tmpr_vdw;
219     int          d;
220     gmx_bool     grid_ok;
221
222     /* Try to add a new setup with next larger cut-off to the list */
223     pme_lb->n++;
224     srenew(pme_lb->setup, pme_lb->n);
225     set          = &pme_lb->setup[pme_lb->n-1];
226     set->pmedata = NULL;
227
228     get_pme_nnodes(dd, &npmenodes_x, &npmenodes_y);
229
230     fac = 1;
231     do
232     {
233         /* Avoid infinite while loop, which can occur at the minimum grid size.
234          * Note that in practice load balancing will stop before this point.
235          * The factor 2.1 allows for the extreme case in which only grids
236          * of powers of 2 are allowed (the current code supports more grids).
237          */
238         if (fac > 2.1)
239         {
240             pme_lb->n--;
241
242             return FALSE;
243         }
244
245         fac *= 1.01;
246         clear_ivec(set->grid);
247         sp = calc_grid(NULL, pme_lb->box_start,
248                        fac*pme_lb->setup[pme_lb->cur].spacing,
249                        &set->grid[XX],
250                        &set->grid[YY],
251                        &set->grid[ZZ]);
252
253         /* As here we can't easily check if one of the PME nodes
254          * uses threading, we do a conservative grid check.
255          * This means we can't use pme_order or less grid lines
256          * per PME node along x, which is not a strong restriction.
257          */
258         gmx_pme_check_restrictions(pme_order,
259                                    set->grid[XX], set->grid[YY], set->grid[ZZ],
260                                    npmenodes_x, npmenodes_y,
261                                    TRUE,
262                                    FALSE,
263                                    &grid_ok);
264     }
265     while (sp <= 1.001*pme_lb->setup[pme_lb->cur].spacing || !grid_ok);
266
267     set->rcut_coulomb = pme_lb->cut_spacing*sp;
268
269     if (pme_lb->cutoff_scheme == ecutsVERLET)
270     {
271         set->rlist        = set->rcut_coulomb + pme_lb->rbuf_coulomb;
272         /* We dont use LR lists with Verlet, but this avoids if-statements in further checks */
273         set->rlistlong    = set->rlist;
274     }
275     else
276     {
277         tmpr_coulomb          = set->rcut_coulomb + pme_lb->rbuf_coulomb;
278         tmpr_vdw              = pme_lb->rcut_vdw + pme_lb->rbuf_vdw;
279         set->rlist            = min(tmpr_coulomb, tmpr_vdw);
280         set->rlistlong        = max(tmpr_coulomb, tmpr_vdw);
281
282         /* Set the long-range update frequency */
283         if (set->rlist == set->rlistlong)
284         {
285             /* No long-range interactions if the short-/long-range cutoffs are identical */
286             set->nstcalclr = 0;
287         }
288         else if (pme_lb->nstcalclr_start == 0 || pme_lb->nstcalclr_start == 1)
289         {
290             /* We were not doing long-range before, but now we are since rlist!=rlistlong */
291             set->nstcalclr = 1;
292         }
293         else
294         {
295             /* We were already doing long-range interactions from the start */
296             if (pme_lb->rcut_vdw > pme_lb->rcut_coulomb_start)
297             {
298                 /* We were originally doing long-range VdW-only interactions.
299                  * If rvdw is still longer than rcoulomb we keep the original nstcalclr,
300                  * but if the coulomb cutoff has become longer we should update the long-range
301                  * part every step.
302                  */
303                 set->nstcalclr = (tmpr_vdw > tmpr_coulomb) ? pme_lb->nstcalclr_start : 1;
304             }
305             else
306             {
307                 /* We were not doing any long-range interaction from the start,
308                  * since it is not possible to do twin-range coulomb for the PME interaction.
309                  */
310                 set->nstcalclr = 1;
311             }
312         }
313     }
314
315     set->spacing      = sp;
316     /* The grid efficiency is the size wrt a grid with uniform x/y/z spacing */
317     set->grid_efficiency = 1;
318     for (d = 0; d < DIM; d++)
319     {
320         set->grid_efficiency *= (set->grid[d]*sp)/norm(pme_lb->box_start[d]);
321     }
322     /* The Ewald coefficient is inversly proportional to the cut-off */
323     set->ewaldcoeff_q =
324         pme_lb->setup[0].ewaldcoeff_q*pme_lb->setup[0].rcut_coulomb/set->rcut_coulomb;
325     /* We set ewaldcoeff_lj in set, even when LJ-PME is not used */
326     set->ewaldcoeff_lj =
327         pme_lb->setup[0].ewaldcoeff_lj*pme_lb->setup[0].rcut_coulomb/set->rcut_coulomb;
328
329     set->count   = 0;
330     set->cycles  = 0;
331
332     if (debug)
333     {
334         fprintf(debug, "PME loadbal: grid %d %d %d, coulomb cutoff %f\n",
335                 set->grid[XX], set->grid[YY], set->grid[ZZ], set->rcut_coulomb);
336     }
337     return TRUE;
338 }
339
340 static void print_grid(FILE *fp_err, FILE *fp_log,
341                        const char *pre,
342                        const char *desc,
343                        const pme_setup_t *set,
344                        double cycles)
345 {
346     char buf[STRLEN], buft[STRLEN];
347
348     if (cycles >= 0)
349     {
350         sprintf(buft, ": %.1f M-cycles", cycles*1e-6);
351     }
352     else
353     {
354         buft[0] = '\0';
355     }
356     sprintf(buf, "%-11s%10s pme grid %d %d %d, coulomb cutoff %.3f%s",
357             pre,
358             desc, set->grid[XX], set->grid[YY], set->grid[ZZ], set->rcut_coulomb,
359             buft);
360     if (fp_err != NULL)
361     {
362         fprintf(fp_err, "\r%s\n", buf);
363     }
364     if (fp_log != NULL)
365     {
366         fprintf(fp_log, "%s\n", buf);
367     }
368 }
369
370 static int pme_loadbal_end(pme_load_balancing_t pme_lb)
371 {
372     /* In the initial stage only n is set; end is not set yet */
373     if (pme_lb->end > 0)
374     {
375         return pme_lb->end;
376     }
377     else
378     {
379         return pme_lb->n;
380     }
381 }
382
383 static void print_loadbal_limited(FILE *fp_err, FILE *fp_log,
384                                   gmx_int64_t step,
385                                   pme_load_balancing_t pme_lb)
386 {
387     char buf[STRLEN], sbuf[22];
388
389     sprintf(buf, "step %4s: the %s limits the PME load balancing to a coulomb cut-off of %.3f",
390             gmx_step_str(step, sbuf),
391             pmelblim_str[pme_lb->elimited],
392             pme_lb->setup[pme_loadbal_end(pme_lb)-1].rcut_coulomb);
393     if (fp_err != NULL)
394     {
395         fprintf(fp_err, "\r%s\n", buf);
396     }
397     if (fp_log != NULL)
398     {
399         fprintf(fp_log, "%s\n", buf);
400     }
401 }
402
403 static void switch_to_stage1(pme_load_balancing_t pme_lb)
404 {
405     pme_lb->start = 0;
406     while (pme_lb->start+1 < pme_lb->n &&
407            (pme_lb->setup[pme_lb->start].count == 0 ||
408             pme_lb->setup[pme_lb->start].cycles >
409             pme_lb->setup[pme_lb->fastest].cycles*PME_LB_SLOW_FAC))
410     {
411         pme_lb->start++;
412     }
413     while (pme_lb->start > 0 && pme_lb->setup[pme_lb->start-1].cycles == 0)
414     {
415         pme_lb->start--;
416     }
417
418     pme_lb->end = pme_lb->n;
419     if (pme_lb->setup[pme_lb->end-1].count > 0 &&
420         pme_lb->setup[pme_lb->end-1].cycles >
421         pme_lb->setup[pme_lb->fastest].cycles*PME_LB_SLOW_FAC)
422     {
423         pme_lb->end--;
424     }
425
426     pme_lb->stage = 1;
427
428     /* Next we want to choose setup pme_lb->start, but as we will increase
429      * pme_ln->cur by one right after returning, we subtract 1 here.
430      */
431     pme_lb->cur = pme_lb->start - 1;
432 }
433
434 gmx_bool pme_load_balance(pme_load_balancing_t        pme_lb,
435                           t_commrec                  *cr,
436                           FILE                       *fp_err,
437                           FILE                       *fp_log,
438                           t_inputrec                 *ir,
439                           t_state                    *state,
440                           double                      cycles,
441                           interaction_const_t        *ic,
442                           struct nonbonded_verlet_t  *nbv,
443                           gmx_pme_t                  *pmedata,
444                           gmx_int64_t                 step)
445 {
446     gmx_bool     OK;
447     pme_setup_t *set;
448     double       cycles_fast;
449     char         buf[STRLEN], sbuf[22];
450     real         rtab;
451     gmx_bool     bUsesSimpleTables = TRUE;
452
453     if (pme_lb->stage == pme_lb->nstage)
454     {
455         return FALSE;
456     }
457
458     if (PAR(cr))
459     {
460         gmx_sumd(1, &cycles, cr);
461         cycles /= cr->nnodes;
462     }
463
464     set = &pme_lb->setup[pme_lb->cur];
465     set->count++;
466
467     rtab = ir->rlistlong + ir->tabext;
468
469     if (set->count % 2 == 1)
470     {
471         /* Skip the first cycle, because the first step after a switch
472          * is much slower due to allocation and/or caching effects.
473          */
474         return TRUE;
475     }
476
477     sprintf(buf, "step %4s: ", gmx_step_str(step, sbuf));
478     print_grid(fp_err, fp_log, buf, "timed with", set, cycles);
479
480     if (set->count <= 2)
481     {
482         set->cycles = cycles;
483     }
484     else
485     {
486         if (cycles*PME_LB_ACCEL_TOL < set->cycles &&
487             pme_lb->stage == pme_lb->nstage - 1)
488         {
489             /* The performance went up a lot (due to e.g. DD load balancing).
490              * Add a stage, keep the minima, but rescan all setups.
491              */
492             pme_lb->nstage++;
493
494             if (debug)
495             {
496                 fprintf(debug, "The performance for grid %d %d %d went from %.3f to %.1f M-cycles, this is more than %f\n"
497                         "Increased the number stages to %d"
498                         " and ignoring the previous performance\n",
499                         set->grid[XX], set->grid[YY], set->grid[ZZ],
500                         cycles*1e-6, set->cycles*1e-6, PME_LB_ACCEL_TOL,
501                         pme_lb->nstage);
502             }
503         }
504         set->cycles = min(set->cycles, cycles);
505     }
506
507     if (set->cycles < pme_lb->setup[pme_lb->fastest].cycles)
508     {
509         pme_lb->fastest = pme_lb->cur;
510
511         if (DOMAINDECOMP(cr))
512         {
513             /* We found a new fastest setting, ensure that with subsequent
514              * shorter cut-off's the dynamic load balancing does not make
515              * the use of the current cut-off impossible. This solution is
516              * a trade-off, as the PME load balancing and DD domain size
517              * load balancing can interact in complex ways.
518              * With the Verlet kernels, DD load imbalance will usually be
519              * mainly due to bonded interaction imbalance, which will often
520              * quickly push the domain boundaries beyond the limit for the
521              * optimal, PME load balanced, cut-off. But it could be that
522              * better overal performance can be obtained with a slightly
523              * shorter cut-off and better DD load balancing.
524              */
525             change_dd_dlb_cutoff_limit(cr);
526         }
527     }
528     cycles_fast = pme_lb->setup[pme_lb->fastest].cycles;
529
530     /* Check in stage 0 if we should stop scanning grids.
531      * Stop when the time is more than SLOW_FAC longer than the fastest.
532      */
533     if (pme_lb->stage == 0 && pme_lb->cur > 0 &&
534         cycles > pme_lb->setup[pme_lb->fastest].cycles*PME_LB_SLOW_FAC)
535     {
536         pme_lb->n = pme_lb->cur + 1;
537         /* Done with scanning, go to stage 1 */
538         switch_to_stage1(pme_lb);
539     }
540
541     if (pme_lb->stage == 0)
542     {
543         int gridsize_start;
544
545         gridsize_start = set->grid[XX]*set->grid[YY]*set->grid[ZZ];
546
547         do
548         {
549             if (pme_lb->cur+1 < pme_lb->n)
550             {
551                 /* We had already generated the next setup */
552                 OK = TRUE;
553             }
554             else
555             {
556                 /* Find the next setup */
557                 OK = pme_loadbal_increase_cutoff(pme_lb, ir->pme_order, cr->dd);
558
559                 if (!OK)
560                 {
561                     pme_lb->elimited = epmelblimPMEGRID;
562                 }
563             }
564
565             if (OK && ir->ePBC != epbcNONE)
566             {
567                 OK = (sqr(pme_lb->setup[pme_lb->cur+1].rlistlong)
568                       <= max_cutoff2(ir->ePBC, state->box));
569                 if (!OK)
570                 {
571                     pme_lb->elimited = epmelblimBOX;
572                 }
573             }
574
575             if (OK)
576             {
577                 pme_lb->cur++;
578
579                 if (DOMAINDECOMP(cr))
580                 {
581                     OK = change_dd_cutoff(cr, state, ir,
582                                           pme_lb->setup[pme_lb->cur].rlistlong);
583                     if (!OK)
584                     {
585                         /* Failed: do not use this setup */
586                         pme_lb->cur--;
587                         pme_lb->elimited = epmelblimDD;
588                     }
589                 }
590             }
591             if (!OK)
592             {
593                 /* We hit the upper limit for the cut-off,
594                  * the setup should not go further than cur.
595                  */
596                 pme_lb->n = pme_lb->cur + 1;
597                 print_loadbal_limited(fp_err, fp_log, step, pme_lb);
598                 /* Switch to the next stage */
599                 switch_to_stage1(pme_lb);
600             }
601         }
602         while (OK &&
603                !(pme_lb->setup[pme_lb->cur].grid[XX]*
604                  pme_lb->setup[pme_lb->cur].grid[YY]*
605                  pme_lb->setup[pme_lb->cur].grid[ZZ] <
606                  gridsize_start*PME_LB_GRID_SCALE_FAC
607                  &&
608                  pme_lb->setup[pme_lb->cur].grid_efficiency <
609                  pme_lb->setup[pme_lb->cur-1].grid_efficiency*PME_LB_GRID_EFFICIENCY_REL_FAC));
610     }
611
612     if (pme_lb->stage > 0 && pme_lb->end == 1)
613     {
614         pme_lb->cur   = 0;
615         pme_lb->stage = pme_lb->nstage;
616     }
617     else if (pme_lb->stage > 0 && pme_lb->end > 1)
618     {
619         /* If stage = nstage-1:
620          *   scan over all setups, rerunning only those setups
621          *   which are not much slower than the fastest
622          * else:
623          *   use the next setup
624          */
625         do
626         {
627             pme_lb->cur++;
628             if (pme_lb->cur == pme_lb->end)
629             {
630                 pme_lb->stage++;
631                 pme_lb->cur = pme_lb->start;
632             }
633         }
634         while (pme_lb->stage == pme_lb->nstage - 1 &&
635                pme_lb->setup[pme_lb->cur].count > 0 &&
636                pme_lb->setup[pme_lb->cur].cycles > cycles_fast*PME_LB_SLOW_FAC);
637
638         if (pme_lb->stage == pme_lb->nstage)
639         {
640             /* We are done optimizing, use the fastest setup we found */
641             pme_lb->cur = pme_lb->fastest;
642         }
643     }
644
645     if (DOMAINDECOMP(cr) && pme_lb->stage > 0)
646     {
647         OK = change_dd_cutoff(cr, state, ir, pme_lb->setup[pme_lb->cur].rlistlong);
648         if (!OK)
649         {
650             /* Failsafe solution */
651             if (pme_lb->cur > 1 && pme_lb->stage == pme_lb->nstage)
652             {
653                 pme_lb->stage--;
654             }
655             pme_lb->fastest  = 0;
656             pme_lb->start    = 0;
657             pme_lb->end      = pme_lb->cur;
658             pme_lb->cur      = pme_lb->start;
659             pme_lb->elimited = epmelblimDD;
660             print_loadbal_limited(fp_err, fp_log, step, pme_lb);
661         }
662     }
663
664     /* Change the Coulomb cut-off and the PME grid */
665
666     set = &pme_lb->setup[pme_lb->cur];
667
668     ic->rcoulomb     = set->rcut_coulomb;
669     ic->rlist        = set->rlist;
670     ic->rlistlong    = set->rlistlong;
671     ir->nstcalclr    = set->nstcalclr;
672     ic->ewaldcoeff_q = set->ewaldcoeff_q;
673     /* TODO: centralize the code that sets the potentials shifts */
674     if (ic->coulomb_modifier == eintmodPOTSHIFT)
675     {
676         ic->sh_ewald = gmx_erfc(ic->ewaldcoeff_q*ic->rcoulomb);
677     }
678     if (EVDW_PME(ic->vdwtype))
679     {
680         /* We have PME for both Coulomb and VdW, set rvdw equal to rcoulomb */
681         ic->rvdw            = set->rcut_coulomb;
682         ic->ewaldcoeff_lj   = set->ewaldcoeff_lj;
683         if (ic->vdw_modifier == eintmodPOTSHIFT)
684         {
685             real crc2;
686
687             ic->dispersion_shift.cpot = -pow(ic->rvdw, -6.0);
688             ic->repulsion_shift.cpot  = -pow(ic->rvdw, -12.0);
689             ic->sh_invrc6             = -ic->dispersion_shift.cpot;
690             crc2                      = sqr(ic->ewaldcoeff_lj*ic->rvdw);
691             ic->sh_lj_ewald           = (exp(-crc2)*(1 + crc2 + 0.5*crc2*crc2) - 1)*pow(ic->rvdw, -6.0);
692         }
693     }
694
695     bUsesSimpleTables = uses_simple_tables(ir->cutoff_scheme, nbv, 0);
696     nbnxn_cuda_pme_loadbal_update_param(nbv, ic);
697
698     /* With tMPI + GPUs some ranks may be sharing GPU(s) and therefore
699      * also sharing texture references. To keep the code simple, we don't
700      * treat texture references as shared resources, but this means that
701      * the coulomb_tab texture ref will get updated by multiple threads.
702      * Hence, to ensure that the non-bonded kernels don't start before all
703      * texture binding operations are finished, we need to wait for all ranks
704      * to arrive here before continuing.
705      *
706      * Note that we could omit this barrier if GPUs are not shared (or
707      * texture objects are used), but as this is initialization code, there
708      * is not point in complicating things.
709      */
710 #ifdef GMX_THREAD_MPI
711     if (PAR(cr) && use_GPU(nbv))
712     {
713         gmx_barrier(cr);
714     }
715 #endif  /* GMX_THREAD_MPI */
716
717     /* Usually we won't need the simple tables with GPUs.
718      * But we do with hybrid acceleration and with free energy.
719      * To avoid bugs, we always re-initialize the simple tables here.
720      */
721     init_interaction_const_tables(NULL, ic, bUsesSimpleTables, rtab);
722
723     if (cr->duty & DUTY_PME)
724     {
725         if (pme_lb->setup[pme_lb->cur].pmedata == NULL)
726         {
727             /* Generate a new PME data structure,
728              * copying part of the old pointers.
729              */
730             gmx_pme_reinit(&set->pmedata,
731                            cr, pme_lb->setup[0].pmedata, ir,
732                            set->grid);
733         }
734         *pmedata = set->pmedata;
735     }
736     else
737     {
738         /* Tell our PME-only node to switch grid */
739         gmx_pme_send_switchgrid(cr, set->grid, set->ewaldcoeff_q, set->ewaldcoeff_lj);
740     }
741
742     if (debug)
743     {
744         print_grid(NULL, debug, "", "switched to", set, -1);
745     }
746
747     if (pme_lb->stage == pme_lb->nstage)
748     {
749         print_grid(fp_err, fp_log, "", "optimal", set, -1);
750     }
751
752     return TRUE;
753 }
754
755 void restart_pme_loadbal(pme_load_balancing_t pme_lb, int n)
756 {
757     pme_lb->nstage += n;
758 }
759
760 static int pme_grid_points(const pme_setup_t *setup)
761 {
762     return setup->grid[XX]*setup->grid[YY]*setup->grid[ZZ];
763 }
764
765 static real pme_loadbal_rlist(const pme_setup_t *setup)
766 {
767     /* With the group cut-off scheme we can have twin-range either
768      * for Coulomb or for VdW, so we need a check here.
769      * With the Verlet cut-off scheme rlist=rlistlong.
770      */
771     if (setup->rcut_coulomb > setup->rlist)
772     {
773         return setup->rlistlong;
774     }
775     else
776     {
777         return setup->rlist;
778     }
779 }
780
781 static void print_pme_loadbal_setting(FILE              *fplog,
782                                       char              *name,
783                                       const pme_setup_t *setup)
784 {
785     fprintf(fplog,
786             "   %-7s %6.3f nm %6.3f nm     %3d %3d %3d   %5.3f nm  %5.3f nm\n",
787             name,
788             setup->rcut_coulomb, pme_loadbal_rlist(setup),
789             setup->grid[XX], setup->grid[YY], setup->grid[ZZ],
790             setup->spacing, 1/setup->ewaldcoeff_q);
791 }
792
793 static void print_pme_loadbal_settings(pme_load_balancing_t pme_lb,
794                                        t_commrec           *cr,
795                                        FILE                *fplog,
796                                        gmx_bool             bNonBondedOnGPU)
797 {
798     double pp_ratio, grid_ratio;
799
800     pp_ratio   = pow(pme_loadbal_rlist(&pme_lb->setup[pme_lb->cur])/pme_loadbal_rlist(&pme_lb->setup[0]), 3.0);
801     grid_ratio = pme_grid_points(&pme_lb->setup[pme_lb->cur])/
802         (double)pme_grid_points(&pme_lb->setup[0]);
803
804     fprintf(fplog, "\n");
805     fprintf(fplog, "       P P   -   P M E   L O A D   B A L A N C I N G\n");
806     fprintf(fplog, "\n");
807     /* Here we only warn when the optimal setting is the last one */
808     if (pme_lb->elimited != epmelblimNO &&
809         pme_lb->cur == pme_loadbal_end(pme_lb)-1)
810     {
811         fprintf(fplog, " NOTE: The PP/PME load balancing was limited by the %s,\n",
812                 pmelblim_str[pme_lb->elimited]);
813         fprintf(fplog, "       you might not have reached a good load balance.\n");
814         if (pme_lb->elimited == epmelblimDD)
815         {
816             fprintf(fplog, "       Try different mdrun -dd settings or lower the -dds value.\n");
817         }
818         fprintf(fplog, "\n");
819     }
820     fprintf(fplog, " PP/PME load balancing changed the cut-off and PME settings:\n");
821     fprintf(fplog, "           particle-particle                    PME\n");
822     fprintf(fplog, "            rcoulomb  rlist            grid      spacing   1/beta\n");
823     print_pme_loadbal_setting(fplog, "initial", &pme_lb->setup[0]);
824     print_pme_loadbal_setting(fplog, "final", &pme_lb->setup[pme_lb->cur]);
825     fprintf(fplog, " cost-ratio           %4.2f             %4.2f\n",
826             pp_ratio, grid_ratio);
827     fprintf(fplog, " (note that these numbers concern only part of the total PP and PME load)\n");
828
829     if (pp_ratio > 1.5 && !bNonBondedOnGPU)
830     {
831         md_print_warn(cr, fplog,
832                       "NOTE: PME load balancing increased the non-bonded workload by more than 50%%.\n"
833                       "      For better performance, use (more) PME ranks (mdrun -npme),\n"
834                       "      or if you are beyond the scaling limit, use fewer total ranks (or nodes).\n");
835     }
836     else
837     {
838         fprintf(fplog, "\n");
839     }
840 }
841
842 void pme_loadbal_done(pme_load_balancing_t pme_lb,
843                       t_commrec *cr, FILE *fplog,
844                       gmx_bool bNonBondedOnGPU)
845 {
846     if (fplog != NULL && (pme_lb->cur > 0 || pme_lb->elimited != epmelblimNO))
847     {
848         print_pme_loadbal_settings(pme_lb, cr, fplog, bNonBondedOnGPU);
849     }
850
851     /* TODO: Here we should free all pointers in pme_lb,
852      * but as it contains pme data structures,
853      * we need to first make pme.c free all data.
854      */
855 }