2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2008,2009,2010,2011,2012,2013,2014,2015,2017, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
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.
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.
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.
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.
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.
38 * \brief This file defines functions used by the domdec module
39 * in its initial setup phase.
41 * \author Berk Hess <hess@kth.se>
42 * \ingroup module_domdec
52 #include "gromacs/domdec/domdec.h"
53 #include "gromacs/domdec/domdec_struct.h"
54 #include "gromacs/ewald/pme.h"
55 #include "gromacs/gmxlib/network.h"
56 #include "gromacs/math/utilities.h"
57 #include "gromacs/math/vec.h"
58 #include "gromacs/mdlib/perf_est.h"
59 #include "gromacs/mdtypes/commrec.h"
60 #include "gromacs/mdtypes/inputrec.h"
61 #include "gromacs/mdtypes/md_enums.h"
62 #include "gromacs/pbcutil/pbc.h"
63 #include "gromacs/utility/fatalerror.h"
64 #include "gromacs/utility/smalloc.h"
66 /*! \brief Margin for setting up the DD grid */
67 #define DD_GRID_MARGIN_PRES_SCALE 1.05
69 /*! \brief Factorize \p n.
71 * \param[in] n Value to factorize
72 * \param[out] fac Pointer to array of factors (to be allocated in this function)
73 * \param[out] mfac Pointer to array of the number of times each factor repeats in the factorization (to be allocated in this function)
74 * \return The number of unique factors
76 static int factorize(int n, int **fac, int **mfac)
82 gmx_fatal(FARGS, "Can only factorize positive integers.");
85 /* Decompose n in factors */
94 if (ndiv == 0 || (*fac)[ndiv-1] != d)
108 /*! \brief Find largest divisor of \p n smaller than \p n*/
109 static gmx_bool largest_divisor(int n)
111 int ndiv, *div, *mdiv, ldiv;
113 ndiv = factorize(n, &div, &mdiv);
121 /*! \brief Compute largest common divisor of \p n1 and \b n2 */
122 static int lcd(int n1, int n2)
127 for (i = 2; (i <= n1 && i <= n2); i++)
129 if (n1 % i == 0 && n2 % i == 0)
138 /*! \brief Returns TRUE when there are enough PME ranks for the ratio */
139 static gmx_bool fits_pme_ratio(int nrank_tot, int nrank_pme, float ratio)
141 return ((double)nrank_pme/(double)nrank_tot > 0.95*ratio);
144 /*! \brief Returns TRUE when npme out of ntot ranks doing PME is expected to give reasonable performance */
145 static gmx_bool fits_pp_pme_perf(int ntot, int npme, float ratio)
147 int ndiv, *div, *mdiv, ldiv;
148 int npp_root3, npme_root2;
150 ndiv = factorize(ntot - npme, &div, &mdiv);
155 npp_root3 = static_cast<int>(std::cbrt(ntot - npme) + 0.5);
156 npme_root2 = static_cast<int>(std::sqrt(static_cast<double>(npme)) + 0.5);
158 /* The check below gives a reasonable division:
159 * factor 5 allowed at 5 or more PP ranks,
160 * factor 7 allowed at 49 or more PP ranks.
162 if (ldiv > 3 + npp_root3)
167 /* Check if the number of PP and PME ranks have a reasonable sized
168 * denominator in common, such that we can use 2D PME decomposition
169 * when required (which requires nx_pp == nx_pme).
170 * The factor of 2 allows for a maximum ratio of 2^2=4
171 * between nx_pme and ny_pme.
173 if (lcd(ntot - npme, npme)*2 < npme_root2)
178 /* Does this division gives a reasonable PME load? */
179 return fits_pme_ratio(ntot, npme, ratio);
182 /*! \brief Make a guess for the number of PME ranks to use. */
183 static int guess_npme(FILE *fplog, const gmx_mtop_t *mtop, const t_inputrec *ir,
190 ratio = pme_load_estimate(mtop, ir, box);
194 fprintf(fplog, "Guess for relative PME load: %.2f\n", ratio);
197 /* We assume the optimal rank ratio is close to the load ratio.
198 * The communication load is neglected,
199 * but (hopefully) this will balance out between PP and PME.
202 if (!fits_pme_ratio(nrank_tot, nrank_tot/2, ratio))
204 /* We would need more than nrank_tot/2 PME only nodes,
205 * which is not possible. Since the PME load is very high,
206 * we will not loose much performance when all ranks do PME.
212 /* First try to find npme as a factor of nrank_tot up to nrank_tot/3.
213 * We start with a minimum PME node fraction of 1/16
214 * and avoid ratios which lead to large prime factors in nnodes-npme.
216 npme = (nrank_tot + 15)/16;
217 while (npme <= nrank_tot/3)
219 if (nrank_tot % npme == 0)
221 /* Note that fits_perf might change the PME grid,
222 * in the current implementation it does not.
224 if (fits_pp_pme_perf(nrank_tot, npme, ratio))
231 if (npme > nrank_tot/3)
233 /* Try any possible number for npme */
235 while (npme <= nrank_tot/2)
237 /* Note that fits_perf may change the PME grid */
238 if (fits_pp_pme_perf(nrank_tot, npme, ratio))
245 if (npme > nrank_tot/2)
247 gmx_fatal(FARGS, "Could not find an appropriate number of separate PME ranks. i.e. >= %5f*#ranks (%d) and <= #ranks/2 (%d) and reasonable performance wise (grid_x=%d, grid_y=%d).\n"
248 "Use the -npme option of mdrun or change the number of ranks or the PME grid dimensions, see the manual for details.",
249 ratio, (int)(0.95*ratio*nrank_tot + 0.5), nrank_tot/2, ir->nkx, ir->nky);
250 /* Keep the compiler happy */
258 "Will use %d particle-particle and %d PME only ranks\n"
259 "This is a guess, check the performance at the end of the log file\n",
260 nrank_tot - npme, npme);
263 "Will use %d particle-particle and %d PME only ranks\n"
264 "This is a guess, check the performance at the end of the log file\n",
265 nrank_tot - npme, npme);
271 /*! \brief Return \p n divided by \p f rounded up to the next integer. */
272 static int div_up(int n, int f)
274 return (n + f - 1)/f;
277 real comm_box_frac(const ivec dd_nc, real cutoff, const gmx_ddbox_t *ddbox)
283 for (i = 0; i < DIM; i++)
285 real bt = ddbox->box_size[i]*ddbox->skew_fac[i];
286 nw[i] = dd_nc[i]*cutoff/bt;
290 for (i = 0; i < DIM; i++)
295 for (j = i+1; j < DIM; j++)
299 comm_vol += nw[i]*nw[j]*M_PI/4;
300 for (k = j+1; k < DIM; k++)
304 comm_vol += nw[i]*nw[j]*nw[k]*M_PI/6;
315 /*! \brief Return whether the DD inhomogeneous in the z direction */
316 static gmx_bool inhomogeneous_z(const t_inputrec *ir)
318 return ((EEL_PME(ir->coulombtype) || ir->coulombtype == eelEWALD) &&
319 ir->ePBC == epbcXYZ && ir->ewald_geometry == eewg3DC);
322 /*! \brief Estimate cost of PME FFT communication
324 * This only takes the communication into account and not imbalance
325 * in the calculation. But the imbalance in communication and calculation
326 * are similar and therefore these formulas also prefer load balance
327 * in the FFT and pme_solve calculation.
329 static float comm_pme_cost_vol(int npme, int a, int b, int c)
331 /* We use a float here, since an integer might overflow */
336 comm_vol *= div_up(a, npme);
337 comm_vol *= div_up(b, npme);
343 /*! \brief Estimate cost of communication for a possible domain decomposition. */
344 static float comm_cost_est(real limit, real cutoff,
345 const matrix box, const gmx_ddbox_t *ddbox,
346 int natoms, const t_inputrec *ir,
348 int npme_tot, ivec nc)
350 ivec npme = {1, 1, 1};
351 int i, j, nk, overlap;
353 float comm_vol, comm_vol_xf, comm_pme, cost_pbcdx;
354 /* This is the cost of a pbc_dx call relative to the cost
355 * of communicating the coordinate and force of an atom.
356 * This will be machine dependent.
357 * These factors are for x86 with SMP or Infiniband.
359 float pbcdx_rect_fac = 0.1;
360 float pbcdx_tric_fac = 0.2;
363 /* Check the DD algorithm restrictions */
364 if ((ir->ePBC == epbcXY && ir->nwall < 2 && nc[ZZ] > 1) ||
365 (ir->ePBC == epbcSCREW && (nc[XX] == 1 || nc[YY] > 1 || nc[ZZ] > 1)))
370 if (inhomogeneous_z(ir) && nc[ZZ] > 1)
375 assert(ddbox->npbcdim <= DIM);
377 /* Check if the triclinic requirements are met */
378 for (i = 0; i < DIM; i++)
380 for (j = i+1; j < ddbox->npbcdim; j++)
382 if (box[j][i] != 0 || ir->deform[j][i] != 0 ||
383 (ir->epc != epcNO && ir->compress[j][i] != 0))
385 if (nc[j] > 1 && nc[i] == 1)
393 for (i = 0; i < DIM; i++)
395 bt[i] = ddbox->box_size[i]*ddbox->skew_fac[i];
397 /* Without PBC and with 2 cells, there are no lower limits on the cell size */
398 if (!(i >= ddbox->npbcdim && nc[i] <= 2) && bt[i] < nc[i]*limit)
402 /* With PBC, check if the cut-off fits in nc[i]-1 cells */
403 if (i < ddbox->npbcdim && nc[i] > 1 && (nc[i] - 1)*bt[i] < nc[i]*cutoff)
411 /* The following choices should match those
412 * in init_domain_decomposition in domdec.c.
414 if (nc[XX] == 1 && nc[YY] > 1)
419 else if (nc[YY] == 1)
426 /* Will we use 1D or 2D PME decomposition? */
427 npme[XX] = (npme_tot % nc[XX] == 0) ? nc[XX] : npme_tot;
428 npme[YY] = npme_tot/npme[XX];
432 if (EEL_PME(ir->coulombtype) || EVDW_PME(ir->vdwtype))
434 /* Check the PME grid restrictions.
435 * Currently these can only be invalid here with too few grid lines
436 * along the x dimension per rank doing PME.
438 int npme_x = (npme_tot > 1 ? npme[XX] : nc[XX]);
440 /* Currently we don't have the OpenMP thread count available here.
441 * But with threads we have only tighter restrictions and it's
442 * probably better anyhow to avoid settings where we need to reduce
443 * grid lines over multiple ranks, as the thread check will do.
445 bool useThreads = true;
446 bool errorsAreFatal = false;
447 if (!gmx_pme_check_restrictions(ir->pme_order, ir->nkx, ir->nky, ir->nkz,
448 npme_x, useThreads, errorsAreFatal))
454 /* When two dimensions are (nearly) equal, use more cells
455 * for the smallest index, so the decomposition does not
456 * depend sensitively on the rounding of the box elements.
458 for (i = 0; i < DIM; i++)
460 for (j = i+1; j < DIM; j++)
462 /* Check if the box size is nearly identical,
463 * in that case we prefer nx > ny and ny > nz.
465 if (fabs(bt[j] - bt[i]) < 0.01*bt[i] && nc[j] > nc[i])
467 /* The XX/YY check is a bit compact. If nc[YY]==npme[YY]
468 * this means the swapped nc has nc[XX]==npme[XX],
469 * and we can also swap X and Y for PME.
471 /* Check if dimension i and j are equivalent for PME.
472 * For x/y: if nc[YY]!=npme[YY], we can not swap x/y
473 * For y/z: we can not have PME decomposition in z
476 !((i == XX && j == YY && nc[YY] != npme[YY]) ||
477 (i == YY && j == ZZ && npme[YY] > 1)))
485 /* This function determines only half of the communication cost.
486 * All PP, PME and PP-PME communication is symmetric
487 * and the "back"-communication cost is identical to the forward cost.
490 comm_vol = comm_box_frac(nc, cutoff, ddbox);
493 for (i = 0; i < 2; i++)
495 /* Determine the largest volume for PME x/f redistribution */
496 if (nc[i] % npme[i] != 0)
500 comm_vol_xf = (npme[i] == 2 ? 1.0/3.0 : 0.5);
504 comm_vol_xf = 1.0 - lcd(nc[i], npme[i])/(double)npme[i];
506 comm_pme += 3*natoms*comm_vol_xf;
509 /* Grid overlap communication */
512 nk = (i == 0 ? ir->nkx : ir->nky);
513 overlap = (nk % npme[i] == 0 ? ir->pme_order-1 : ir->pme_order);
521 /* Old line comm_pme += npme[i]*overlap*ir->nkx*ir->nky*ir->nkz/nk; */
525 comm_pme += comm_pme_cost_vol(npme[YY], ir->nky, ir->nkz, ir->nkx);
526 comm_pme += comm_pme_cost_vol(npme[XX], ir->nkx, ir->nky, ir->nkz);
528 /* Add cost of pbc_dx for bondeds */
530 if ((nc[XX] == 1 || nc[YY] == 1) || (nc[ZZ] == 1 && ir->ePBC != epbcXY))
532 if ((ddbox->tric_dir[XX] && nc[XX] == 1) ||
533 (ddbox->tric_dir[YY] && nc[YY] == 1))
535 cost_pbcdx = pbcdxr*pbcdx_tric_fac;
539 cost_pbcdx = pbcdxr*pbcdx_rect_fac;
546 "nc %2d %2d %2d %2d %2d vol pp %6.4f pbcdx %6.4f pme %9.3e tot %9.3e\n",
547 nc[XX], nc[YY], nc[ZZ], npme[XX], npme[YY],
548 comm_vol, cost_pbcdx, comm_pme/(3*natoms),
549 comm_vol + cost_pbcdx + comm_pme/(3*natoms));
552 return 3*natoms*(comm_vol + cost_pbcdx) + comm_pme;
555 /*! \brief Assign penalty factors to possible domain decompositions, based on the estimated communication costs. */
556 static void assign_factors(const gmx_domdec_t *dd,
557 real limit, real cutoff,
558 const matrix box, const gmx_ddbox_t *ddbox,
559 int natoms, const t_inputrec *ir,
560 float pbcdxr, int npme,
561 int ndiv, int *div, int *mdiv, ivec ir_try, ivec opt)
568 ce = comm_cost_est(limit, cutoff, box, ddbox,
569 natoms, ir, pbcdxr, npme, ir_try);
570 if (ce >= 0 && (opt[XX] == 0 ||
571 ce < comm_cost_est(limit, cutoff, box, ddbox,
575 copy_ivec(ir_try, opt);
581 for (x = mdiv[0]; x >= 0; x--)
583 for (i = 0; i < x; i++)
585 ir_try[XX] *= div[0];
587 for (y = mdiv[0]-x; y >= 0; y--)
589 for (i = 0; i < y; i++)
591 ir_try[YY] *= div[0];
593 for (i = 0; i < mdiv[0]-x-y; i++)
595 ir_try[ZZ] *= div[0];
599 assign_factors(dd, limit, cutoff, box, ddbox, natoms, ir, pbcdxr, npme,
600 ndiv-1, div+1, mdiv+1, ir_try, opt);
602 for (i = 0; i < mdiv[0]-x-y; i++)
604 ir_try[ZZ] /= div[0];
606 for (i = 0; i < y; i++)
608 ir_try[YY] /= div[0];
611 for (i = 0; i < x; i++)
613 ir_try[XX] /= div[0];
618 /*! \brief Determine the optimal distribution of DD cells for the simulation system and number of MPI ranks */
619 static real optimize_ncells(FILE *fplog,
620 int nnodes_tot, int npme_only,
621 gmx_bool bDynLoadBal, real dlb_scale,
622 const gmx_mtop_t *mtop,
623 const matrix box, const gmx_ddbox_t *ddbox,
624 const t_inputrec *ir,
626 real cellsize_limit, real cutoff,
627 gmx_bool bInterCGBondeds,
630 int npp, npme, ndiv, *div, *mdiv, d, nmax;
635 limit = cellsize_limit;
641 npp = nnodes_tot - npme_only;
642 if (EEL_PME(ir->coulombtype))
644 npme = (npme_only > 0 ? npme_only : npp);
653 /* If we can skip PBC for distance calculations in plain-C bondeds,
654 * we can save some time (e.g. 3D DD with pbc=xyz).
655 * Here we ignore SIMD bondeds as they always do (fast) PBC.
657 count_bonded_distances(mtop, ir, &pbcdxr, nullptr);
658 pbcdxr /= (double)mtop->natoms;
662 /* Every molecule is a single charge group: no pbc required */
665 /* Add a margin for DLB and/or pressure scaling */
668 if (dlb_scale >= 1.0)
670 gmx_fatal(FARGS, "The value for option -dds should be smaller than 1");
674 fprintf(fplog, "Scaling the initial minimum size with 1/%g (option -dds) = %g\n", dlb_scale, 1/dlb_scale);
678 else if (ir->epc != epcNO)
682 fprintf(fplog, "To account for pressure scaling, scaling the initial minimum size with %g\n", DD_GRID_MARGIN_PRES_SCALE);
683 limit *= DD_GRID_MARGIN_PRES_SCALE;
689 fprintf(fplog, "Optimizing the DD grid for %d cells with a minimum initial size of %.3f nm\n", npp, limit);
691 if (inhomogeneous_z(ir))
693 fprintf(fplog, "Ewald_geometry=%s: assuming inhomogeneous particle distribution in z, will not decompose in z.\n", eewg_names[ir->ewald_geometry]);
698 fprintf(fplog, "The maximum allowed number of cells is:");
699 for (d = 0; d < DIM; d++)
701 nmax = (int)(ddbox->box_size[d]*ddbox->skew_fac[d]/limit);
702 if (d >= ddbox->npbcdim && nmax < 2)
706 if (d == ZZ && inhomogeneous_z(ir))
710 fprintf(fplog, " %c %d", 'X' + d, nmax);
712 fprintf(fplog, "\n");
718 fprintf(debug, "Average nr of pbc_dx calls per atom %.2f\n", pbcdxr);
721 /* Decompose npp in factors */
722 ndiv = factorize(npp, &div, &mdiv);
728 assign_factors(dd, limit, cutoff, box, ddbox, mtop->natoms, ir, pbcdxr,
729 npme, ndiv, div, mdiv, itry, nc);
737 real dd_choose_grid(FILE *fplog,
738 t_commrec *cr, gmx_domdec_t *dd,
739 const t_inputrec *ir,
740 const gmx_mtop_t *mtop,
741 const matrix box, const gmx_ddbox_t *ddbox,
743 gmx_bool bDynLoadBal, real dlb_scale,
744 real cellsize_limit, real cutoff_dd,
745 gmx_bool bInterCGBondeds)
747 gmx_int64_t nnodes_div, ldiv;
752 nnodes_div = cr->nnodes;
753 if (EEL_PME(ir->coulombtype))
757 if (nPmeRanks >= cr->nnodes)
760 "Cannot have %d separate PME ranks with just %d total ranks",
761 nPmeRanks, cr->nnodes);
764 /* If the user purposely selected the number of PME nodes,
765 * only check for large primes in the PP node count.
767 nnodes_div -= nPmeRanks;
777 ldiv = largest_divisor(nnodes_div);
778 /* Check if the largest divisor is more than nnodes^2/3 */
779 if (ldiv*ldiv*ldiv > nnodes_div*nnodes_div)
781 gmx_fatal(FARGS, "The number of ranks you selected (%d) contains a large prime factor %d. In most cases this will lead to bad performance. Choose a number with smaller prime factors or set the decomposition (option -dd) manually.",
786 if (EEL_PME(ir->coulombtype))
790 /* Use PME nodes when the number of nodes is more than 16 */
791 if (cr->nnodes <= 18)
796 fprintf(fplog, "Using %d separate PME ranks, as there are too few total\n ranks for efficient splitting\n", cr->npmenodes);
801 cr->npmenodes = guess_npme(fplog, mtop, ir, box, cr->nnodes);
804 fprintf(fplog, "Using %d separate PME ranks, as guessed by mdrun\n", cr->npmenodes);
810 /* We checked above that nPmeRanks is a valid number */
811 cr->npmenodes = nPmeRanks;
814 fprintf(fplog, "Using %d separate PME ranks, per user request\n", cr->npmenodes);
819 limit = optimize_ncells(fplog, cr->nnodes, cr->npmenodes,
820 bDynLoadBal, dlb_scale,
821 mtop, box, ddbox, ir, dd,
822 cellsize_limit, cutoff_dd,
830 /* Communicate the information set by the master to all nodes */
831 gmx_bcast(sizeof(dd->nc), dd->nc, cr);
832 if (EEL_PME(ir->coulombtype))
834 gmx_bcast(sizeof(cr->npmenodes), &cr->npmenodes, cr);