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