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