2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015,2016,2017,2018,2019, 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.
48 #include "gromacs/domdec/domdec_struct.h"
49 #include "gromacs/gmxlib/nrnb.h"
50 #include "gromacs/math/functions.h"
51 #include "gromacs/math/utilities.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/mdlib/gmx_omp_nthreads.h"
54 #include "gromacs/mdlib/ns.h"
55 #include "gromacs/mdtypes/group.h"
56 #include "gromacs/mdtypes/md_enums.h"
57 #include "gromacs/nbnxm/atomdata.h"
58 #include "gromacs/nbnxm/gpu_data_mgmt.h"
59 #include "gromacs/nbnxm/nbnxm.h"
60 #include "gromacs/nbnxm/nbnxm_geometry.h"
61 #include "gromacs/nbnxm/nbnxm_simd.h"
62 #include "gromacs/nbnxm/pairlistset.h"
63 #include "gromacs/pbcutil/ishift.h"
64 #include "gromacs/pbcutil/pbc.h"
65 #include "gromacs/simd/simd.h"
66 #include "gromacs/simd/vector_operations.h"
67 #include "gromacs/topology/block.h"
68 #include "gromacs/utility/exceptions.h"
69 #include "gromacs/utility/fatalerror.h"
70 #include "gromacs/utility/gmxomp.h"
71 #include "gromacs/utility/smalloc.h"
75 #include "pairlistwork.h"
77 using namespace gmx; // TODO: Remove when this file is moved into gmx namespace
79 // Convience alias for partial Nbnxn namespace usage
80 using InteractionLocality = Nbnxm::InteractionLocality;
82 /* We shift the i-particles backward for PBC.
83 * This leads to more conditionals than shifting forward.
84 * We do this to get more balanced pair lists.
86 constexpr bool c_pbcShiftBackward = true;
89 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
91 for (int i = 0; i < enbsCCnr; i++)
98 static double Mcyc_av(const nbnxn_cycle_t *cc)
100 return static_cast<double>(cc->c)*1e-6/cc->count;
103 static void nbs_cycle_print(FILE *fp, const nbnxn_search *nbs)
106 fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
107 nbs->cc[enbsCCgrid].count,
108 Mcyc_av(&nbs->cc[enbsCCgrid]),
109 Mcyc_av(&nbs->cc[enbsCCsearch]),
110 Mcyc_av(&nbs->cc[enbsCCreducef]));
112 if (nbs->work.size() > 1)
114 if (nbs->cc[enbsCCcombine].count > 0)
116 fprintf(fp, " comb %5.2f",
117 Mcyc_av(&nbs->cc[enbsCCcombine]));
119 fprintf(fp, " s. th");
120 for (const nbnxn_search_work_t &work : nbs->work)
122 fprintf(fp, " %4.1f",
123 Mcyc_av(&work.cc[enbsCCsearch]));
129 /* Layout for the nonbonded NxN pair lists */
130 enum class NbnxnLayout
132 NoSimd4x4, // i-cluster size 4, j-cluster size 4
133 Simd4xN, // i-cluster size 4, j-cluster size SIMD width
134 Simd2xNN, // i-cluster size 4, j-cluster size half SIMD width
135 Gpu8x8x8 // i-cluster size 8, j-cluster size 8 + super-clustering
139 /* Returns the j-cluster size */
140 template <NbnxnLayout layout>
141 static constexpr int jClusterSize()
143 static_assert(layout == NbnxnLayout::NoSimd4x4 || layout == NbnxnLayout::Simd4xN || layout == NbnxnLayout::Simd2xNN, "Currently jClusterSize only supports CPU layouts");
145 return layout == NbnxnLayout::Simd4xN ? GMX_SIMD_REAL_WIDTH : (layout == NbnxnLayout::Simd2xNN ? GMX_SIMD_REAL_WIDTH/2 : c_nbnxnCpuIClusterSize);
148 /*! \brief Returns the j-cluster index given the i-cluster index.
150 * \tparam jClusterSize The number of atoms in a j-cluster
151 * \tparam jSubClusterIndex The j-sub-cluster index (0/1), used when size(j-cluster) < size(i-cluster)
152 * \param[in] ci The i-cluster index
154 template <int jClusterSize, int jSubClusterIndex>
155 static inline int cjFromCi(int ci)
157 static_assert(jClusterSize == c_nbnxnCpuIClusterSize/2 || jClusterSize == c_nbnxnCpuIClusterSize || jClusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
159 static_assert(jSubClusterIndex == 0 || jSubClusterIndex == 1,
160 "Only sub-cluster indices 0 and 1 are supported");
162 if (jClusterSize == c_nbnxnCpuIClusterSize/2)
164 if (jSubClusterIndex == 0)
170 return ((ci + 1) << 1) - 1;
173 else if (jClusterSize == c_nbnxnCpuIClusterSize)
183 /*! \brief Returns the j-cluster index given the i-cluster index.
185 * \tparam layout The pair-list layout
186 * \tparam jSubClusterIndex The j-sub-cluster index (0/1), used when size(j-cluster) < size(i-cluster)
187 * \param[in] ci The i-cluster index
189 template <NbnxnLayout layout, int jSubClusterIndex>
190 static inline int cjFromCi(int ci)
192 constexpr int clusterSize = jClusterSize<layout>();
194 return cjFromCi<clusterSize, jSubClusterIndex>(ci);
197 /* Returns the nbnxn coordinate data index given the i-cluster index */
198 template <NbnxnLayout layout>
199 static inline int xIndexFromCi(int ci)
201 constexpr int clusterSize = jClusterSize<layout>();
203 static_assert(clusterSize == c_nbnxnCpuIClusterSize/2 || clusterSize == c_nbnxnCpuIClusterSize || clusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
205 if (clusterSize <= c_nbnxnCpuIClusterSize)
207 /* Coordinates are stored packed in groups of 4 */
212 /* Coordinates packed in 8, i-cluster size is half the packing width */
213 return (ci >> 1)*STRIDE_P8 + (ci & 1)*(c_packX8 >> 1);
217 /* Returns the nbnxn coordinate data index given the j-cluster index */
218 template <NbnxnLayout layout>
219 static inline int xIndexFromCj(int cj)
221 constexpr int clusterSize = jClusterSize<layout>();
223 static_assert(clusterSize == c_nbnxnCpuIClusterSize/2 || clusterSize == c_nbnxnCpuIClusterSize || clusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
225 if (clusterSize == c_nbnxnCpuIClusterSize/2)
227 /* Coordinates are stored packed in groups of 4 */
228 return (cj >> 1)*STRIDE_P4 + (cj & 1)*(c_packX4 >> 1);
230 else if (clusterSize == c_nbnxnCpuIClusterSize)
232 /* Coordinates are stored packed in groups of 4 */
237 /* Coordinates are stored packed in groups of 8 */
243 /* Initializes a single nbnxn_pairlist_t data structure */
244 static void nbnxn_init_pairlist_fep(t_nblist *nl)
246 nl->type = GMX_NBLIST_INTERACTION_FREE_ENERGY;
247 nl->igeometry = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
248 /* The interaction functions are set in the free energy kernel fuction */
261 nl->jindex = nullptr;
263 nl->excl_fep = nullptr;
267 static void free_nblist(t_nblist *nl)
277 nbnxn_search_work_t::nbnxn_search_work_t() :
280 buffer_flags({0, nullptr, 0}),
282 nbl_fep(new t_nblist),
285 nbnxn_init_pairlist_fep(nbl_fep.get());
290 nbnxn_search_work_t::~nbnxn_search_work_t()
292 sfree(buffer_flags.flag);
294 free_nblist(nbl_fep.get());
297 nbnxn_search::nbnxn_search(int ePBC,
298 const ivec *n_dd_cells,
299 const gmx_domdec_zones_t *zones,
310 // The correct value will be set during the gridding
314 DomDec = n_dd_cells != nullptr;
317 for (int d = 0; d < DIM; d++)
319 if ((*n_dd_cells)[d] > 1)
322 /* Each grid matches a DD zone */
328 grid.resize(numGrids);
330 /* Initialize detailed nbsearch cycle counting */
331 print_cycles = (getenv("GMX_NBNXN_CYCLE") != nullptr);
335 nbnxn_search *nbnxn_init_search(int ePBC,
336 const ivec *n_dd_cells,
337 const gmx_domdec_zones_t *zones,
341 return new nbnxn_search(ePBC, n_dd_cells, zones, bFEP, nthread_max);
344 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
347 flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
348 if (flags->nflag > flags->flag_nalloc)
350 flags->flag_nalloc = over_alloc_large(flags->nflag);
351 srenew(flags->flag, flags->flag_nalloc);
353 for (int b = 0; b < flags->nflag; b++)
355 bitmask_clear(&(flags->flag[b]));
359 /* Returns the pair-list cutoff between a bounding box and a grid cell given an atom-to-atom pair-list cutoff
361 * Given a cutoff distance between atoms, this functions returns the cutoff
362 * distance2 between a bounding box of a group of atoms and a grid cell.
363 * Since atoms can be geometrically outside of the cell they have been
364 * assigned to (when atom groups instead of individual atoms are assigned
365 * to cells), this distance returned can be larger than the input.
367 static real listRangeForBoundingBoxToGridCell(real rlist,
368 const nbnxn_grid_t &grid)
370 return rlist + grid.maxAtomGroupRadius;
373 /* Returns the pair-list cutoff between a grid cells given an atom-to-atom pair-list cutoff
375 * Given a cutoff distance between atoms, this functions returns the cutoff
376 * distance2 between two grid cells.
377 * Since atoms can be geometrically outside of the cell they have been
378 * assigned to (when atom groups instead of individual atoms are assigned
379 * to cells), this distance returned can be larger than the input.
381 static real listRangeForGridCellToGridCell(real rlist,
382 const nbnxn_grid_t &iGrid,
383 const nbnxn_grid_t &jGrid)
385 return rlist + iGrid.maxAtomGroupRadius + jGrid.maxAtomGroupRadius;
388 /* Determines the cell range along one dimension that
389 * the bounding box b0 - b1 sees.
392 static void get_cell_range(real b0, real b1,
393 const nbnxn_grid_t &jGrid,
394 real d2, real rlist, int *cf, int *cl)
396 real listRangeBBToCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGrid));
397 real distanceInCells = (b0 - jGrid.c0[dim])*jGrid.invCellSize[dim];
398 *cf = std::max(static_cast<int>(distanceInCells), 0);
401 d2 + gmx::square((b0 - jGrid.c0[dim]) - (*cf - 1 + 1)*jGrid.cellSize[dim]) < listRangeBBToCell2)
406 *cl = std::min(static_cast<int>((b1 - jGrid.c0[dim])*jGrid.invCellSize[dim]), jGrid.numCells[dim] - 1);
407 while (*cl < jGrid.numCells[dim] - 1 &&
408 d2 + gmx::square((*cl + 1)*jGrid.cellSize[dim] - (b1 - jGrid.c0[dim])) < listRangeBBToCell2)
414 /* Reference code calculating the distance^2 between two bounding boxes */
416 static float box_dist2(float bx0, float bx1, float by0,
417 float by1, float bz0, float bz1,
418 const nbnxn_bb_t *bb)
421 float dl, dh, dm, dm0;
425 dl = bx0 - bb->upper[BB_X];
426 dh = bb->lower[BB_X] - bx1;
427 dm = std::max(dl, dh);
428 dm0 = std::max(dm, 0.0f);
431 dl = by0 - bb->upper[BB_Y];
432 dh = bb->lower[BB_Y] - by1;
433 dm = std::max(dl, dh);
434 dm0 = std::max(dm, 0.0f);
437 dl = bz0 - bb->upper[BB_Z];
438 dh = bb->lower[BB_Z] - bz1;
439 dm = std::max(dl, dh);
440 dm0 = std::max(dm, 0.0f);
447 /* Plain C code calculating the distance^2 between two bounding boxes */
448 static float subc_bb_dist2(int si,
449 const nbnxn_bb_t *bb_i_ci,
451 gmx::ArrayRef<const nbnxn_bb_t> bb_j_all)
453 const nbnxn_bb_t *bb_i = bb_i_ci + si;
454 const nbnxn_bb_t *bb_j = bb_j_all.data() + csj;
457 float dl, dh, dm, dm0;
459 dl = bb_i->lower[BB_X] - bb_j->upper[BB_X];
460 dh = bb_j->lower[BB_X] - bb_i->upper[BB_X];
461 dm = std::max(dl, dh);
462 dm0 = std::max(dm, 0.0f);
465 dl = bb_i->lower[BB_Y] - bb_j->upper[BB_Y];
466 dh = bb_j->lower[BB_Y] - bb_i->upper[BB_Y];
467 dm = std::max(dl, dh);
468 dm0 = std::max(dm, 0.0f);
471 dl = bb_i->lower[BB_Z] - bb_j->upper[BB_Z];
472 dh = bb_j->lower[BB_Z] - bb_i->upper[BB_Z];
473 dm = std::max(dl, dh);
474 dm0 = std::max(dm, 0.0f);
480 #if NBNXN_SEARCH_BB_SIMD4
482 /* 4-wide SIMD code for bb distance for bb format xyz0 */
483 static float subc_bb_dist2_simd4(int si,
484 const nbnxn_bb_t *bb_i_ci,
486 gmx::ArrayRef<const nbnxn_bb_t> bb_j_all)
488 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
491 Simd4Float bb_i_S0, bb_i_S1;
492 Simd4Float bb_j_S0, bb_j_S1;
498 bb_i_S0 = load4(&bb_i_ci[si].lower[0]);
499 bb_i_S1 = load4(&bb_i_ci[si].upper[0]);
500 bb_j_S0 = load4(&bb_j_all[csj].lower[0]);
501 bb_j_S1 = load4(&bb_j_all[csj].upper[0]);
503 dl_S = bb_i_S0 - bb_j_S1;
504 dh_S = bb_j_S0 - bb_i_S1;
506 dm_S = max(dl_S, dh_S);
507 dm0_S = max(dm_S, simd4SetZeroF());
509 return dotProduct(dm0_S, dm0_S);
512 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
513 #define SUBC_BB_DIST2_SIMD4_XXXX_INNER(si, bb_i, d2) \
517 Simd4Float dx_0, dy_0, dz_0; \
518 Simd4Float dx_1, dy_1, dz_1; \
520 Simd4Float mx, my, mz; \
521 Simd4Float m0x, m0y, m0z; \
523 Simd4Float d2x, d2y, d2z; \
524 Simd4Float d2s, d2t; \
526 shi = (si)*NNBSBB_D*DIM; \
528 xi_l = load4((bb_i)+shi+0*STRIDE_PBB); \
529 yi_l = load4((bb_i)+shi+1*STRIDE_PBB); \
530 zi_l = load4((bb_i)+shi+2*STRIDE_PBB); \
531 xi_h = load4((bb_i)+shi+3*STRIDE_PBB); \
532 yi_h = load4((bb_i)+shi+4*STRIDE_PBB); \
533 zi_h = load4((bb_i)+shi+5*STRIDE_PBB); \
535 dx_0 = xi_l - xj_h; \
536 dy_0 = yi_l - yj_h; \
537 dz_0 = zi_l - zj_h; \
539 dx_1 = xj_l - xi_h; \
540 dy_1 = yj_l - yi_h; \
541 dz_1 = zj_l - zi_h; \
543 mx = max(dx_0, dx_1); \
544 my = max(dy_0, dy_1); \
545 mz = max(dz_0, dz_1); \
547 m0x = max(mx, zero); \
548 m0y = max(my, zero); \
549 m0z = max(mz, zero); \
558 store4((d2)+(si), d2t); \
561 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
562 static void subc_bb_dist2_simd4_xxxx(const float *bb_j,
563 int nsi, const float *bb_i,
566 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
569 Simd4Float xj_l, yj_l, zj_l;
570 Simd4Float xj_h, yj_h, zj_h;
571 Simd4Float xi_l, yi_l, zi_l;
572 Simd4Float xi_h, yi_h, zi_h;
578 xj_l = Simd4Float(bb_j[0*STRIDE_PBB]);
579 yj_l = Simd4Float(bb_j[1*STRIDE_PBB]);
580 zj_l = Simd4Float(bb_j[2*STRIDE_PBB]);
581 xj_h = Simd4Float(bb_j[3*STRIDE_PBB]);
582 yj_h = Simd4Float(bb_j[4*STRIDE_PBB]);
583 zj_h = Simd4Float(bb_j[5*STRIDE_PBB]);
585 /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
586 * But as we know the number of iterations is 1 or 2, we unroll manually.
588 SUBC_BB_DIST2_SIMD4_XXXX_INNER(0, bb_i, d2);
589 if (STRIDE_PBB < nsi)
591 SUBC_BB_DIST2_SIMD4_XXXX_INNER(STRIDE_PBB, bb_i, d2);
595 #endif /* NBNXN_SEARCH_BB_SIMD4 */
598 /* Returns if any atom pair from two clusters is within distance sqrt(rlist2) */
599 static inline gmx_bool
600 clusterpair_in_range(const NbnxnPairlistGpuWork &work,
602 int csj, int stride, const real *x_j,
605 #if !GMX_SIMD4_HAVE_REAL
608 * All coordinates are stored as xyzxyz...
611 const real *x_i = work.iSuperClusterData.x.data();
613 for (int i = 0; i < c_nbnxnGpuClusterSize; i++)
615 int i0 = (si*c_nbnxnGpuClusterSize + i)*DIM;
616 for (int j = 0; j < c_nbnxnGpuClusterSize; j++)
618 int j0 = (csj*c_nbnxnGpuClusterSize + j)*stride;
620 real d2 = gmx::square(x_i[i0 ] - x_j[j0 ]) + gmx::square(x_i[i0+1] - x_j[j0+1]) + gmx::square(x_i[i0+2] - x_j[j0+2]);
631 #else /* !GMX_SIMD4_HAVE_REAL */
633 /* 4-wide SIMD version.
634 * The coordinates x_i are stored as xxxxyyyy..., x_j is stored xyzxyz...
635 * Using 8-wide AVX(2) is not faster on Intel Sandy Bridge and Haswell.
637 static_assert(c_nbnxnGpuClusterSize == 8 || c_nbnxnGpuClusterSize == 4,
638 "A cluster is hard-coded to 4/8 atoms.");
640 Simd4Real rc2_S = Simd4Real(rlist2);
642 const real *x_i = work.iSuperClusterData.xSimd.data();
644 int dim_stride = c_nbnxnGpuClusterSize*DIM;
645 Simd4Real ix_S0 = load4(x_i + si*dim_stride + 0*GMX_SIMD4_WIDTH);
646 Simd4Real iy_S0 = load4(x_i + si*dim_stride + 1*GMX_SIMD4_WIDTH);
647 Simd4Real iz_S0 = load4(x_i + si*dim_stride + 2*GMX_SIMD4_WIDTH);
649 Simd4Real ix_S1, iy_S1, iz_S1;
650 if (c_nbnxnGpuClusterSize == 8)
652 ix_S1 = load4(x_i + si*dim_stride + 3*GMX_SIMD4_WIDTH);
653 iy_S1 = load4(x_i + si*dim_stride + 4*GMX_SIMD4_WIDTH);
654 iz_S1 = load4(x_i + si*dim_stride + 5*GMX_SIMD4_WIDTH);
656 /* We loop from the outer to the inner particles to maximize
657 * the chance that we find a pair in range quickly and return.
659 int j0 = csj*c_nbnxnGpuClusterSize;
660 int j1 = j0 + c_nbnxnGpuClusterSize - 1;
663 Simd4Real jx0_S, jy0_S, jz0_S;
664 Simd4Real jx1_S, jy1_S, jz1_S;
666 Simd4Real dx_S0, dy_S0, dz_S0;
667 Simd4Real dx_S1, dy_S1, dz_S1;
668 Simd4Real dx_S2, dy_S2, dz_S2;
669 Simd4Real dx_S3, dy_S3, dz_S3;
680 Simd4Bool wco_any_S01, wco_any_S23, wco_any_S;
682 jx0_S = Simd4Real(x_j[j0*stride+0]);
683 jy0_S = Simd4Real(x_j[j0*stride+1]);
684 jz0_S = Simd4Real(x_j[j0*stride+2]);
686 jx1_S = Simd4Real(x_j[j1*stride+0]);
687 jy1_S = Simd4Real(x_j[j1*stride+1]);
688 jz1_S = Simd4Real(x_j[j1*stride+2]);
690 /* Calculate distance */
691 dx_S0 = ix_S0 - jx0_S;
692 dy_S0 = iy_S0 - jy0_S;
693 dz_S0 = iz_S0 - jz0_S;
694 dx_S2 = ix_S0 - jx1_S;
695 dy_S2 = iy_S0 - jy1_S;
696 dz_S2 = iz_S0 - jz1_S;
697 if (c_nbnxnGpuClusterSize == 8)
699 dx_S1 = ix_S1 - jx0_S;
700 dy_S1 = iy_S1 - jy0_S;
701 dz_S1 = iz_S1 - jz0_S;
702 dx_S3 = ix_S1 - jx1_S;
703 dy_S3 = iy_S1 - jy1_S;
704 dz_S3 = iz_S1 - jz1_S;
707 /* rsq = dx*dx+dy*dy+dz*dz */
708 rsq_S0 = norm2(dx_S0, dy_S0, dz_S0);
709 rsq_S2 = norm2(dx_S2, dy_S2, dz_S2);
710 if (c_nbnxnGpuClusterSize == 8)
712 rsq_S1 = norm2(dx_S1, dy_S1, dz_S1);
713 rsq_S3 = norm2(dx_S3, dy_S3, dz_S3);
716 wco_S0 = (rsq_S0 < rc2_S);
717 wco_S2 = (rsq_S2 < rc2_S);
718 if (c_nbnxnGpuClusterSize == 8)
720 wco_S1 = (rsq_S1 < rc2_S);
721 wco_S3 = (rsq_S3 < rc2_S);
723 if (c_nbnxnGpuClusterSize == 8)
725 wco_any_S01 = wco_S0 || wco_S1;
726 wco_any_S23 = wco_S2 || wco_S3;
727 wco_any_S = wco_any_S01 || wco_any_S23;
731 wco_any_S = wco_S0 || wco_S2;
734 if (anyTrue(wco_any_S))
745 #endif /* !GMX_SIMD4_HAVE_REAL */
748 /* Returns the j-cluster index for index cjIndex in a cj list */
749 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj_t> cjList,
752 return cjList[cjIndex].cj;
755 /* Returns the j-cluster index for index cjIndex in a cj4 list */
756 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj4_t> cj4List,
759 return cj4List[cjIndex/c_nbnxnGpuJgroupSize].cj[cjIndex & (c_nbnxnGpuJgroupSize - 1)];
762 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
763 static unsigned int nbl_imask0(const NbnxnPairlistGpu *nbl, int cj_ind)
765 return nbl->cj4[cj_ind/c_nbnxnGpuJgroupSize].imei[0].imask;
768 /* Initializes a single NbnxnPairlistCpu data structure */
769 static void nbnxn_init_pairlist(NbnxnPairlistCpu *nbl)
771 nbl->na_ci = c_nbnxnCpuIClusterSize;
774 nbl->ciOuter.clear();
777 nbl->cjOuter.clear();
780 nbl->work = new NbnxnPairlistCpuWork();
783 NbnxnPairlistGpu::NbnxnPairlistGpu(gmx::PinningPolicy pinningPolicy) :
784 na_ci(c_nbnxnGpuClusterSize),
785 na_cj(c_nbnxnGpuClusterSize),
786 na_sc(c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize),
788 sci({}, {pinningPolicy}),
789 cj4({}, {pinningPolicy}),
790 excl({}, {pinningPolicy}),
793 static_assert(c_nbnxnGpuNumClusterPerSupercluster == c_gpuNumClusterPerCell,
794 "The search code assumes that the a super-cluster matches a search grid cell");
796 static_assert(sizeof(cj4[0].imei[0].imask)*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell,
797 "The i super-cluster cluster interaction mask does not contain a sufficient number of bits");
799 static_assert(sizeof(excl[0])*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell, "The GPU exclusion mask does not contain a sufficient number of bits");
801 // We always want a first entry without any exclusions
804 work = new NbnxnPairlistGpuWork();
807 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list)
810 (nbl_list->params.pairlistType == PairlistType::Simple4x2 ||
811 nbl_list->params.pairlistType == PairlistType::Simple4x4 ||
812 nbl_list->params.pairlistType == PairlistType::Simple4x8);
813 // Currently GPU lists are always combined
814 nbl_list->bCombined = !nbl_list->bSimple;
816 nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
818 if (!nbl_list->bCombined &&
819 nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
821 gmx_fatal(FARGS, "%d OpenMP threads were requested. Since the non-bonded force buffer reduction is prohibitively slow with more than %d threads, we do not allow this. Use %d or less OpenMP threads.",
822 nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
825 if (nbl_list->bSimple)
827 snew(nbl_list->nbl, nbl_list->nnbl);
828 if (nbl_list->nnbl > 1)
830 snew(nbl_list->nbl_work, nbl_list->nnbl);
835 snew(nbl_list->nblGpu, nbl_list->nnbl);
837 nbl_list->nbl_fep.resize(nbl_list->nnbl);
838 /* Execute in order to avoid memory interleaving between threads */
839 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
840 for (int i = 0; i < nbl_list->nnbl; i++)
844 /* Allocate the nblist data structure locally on each thread
845 * to optimize memory access for NUMA architectures.
847 if (nbl_list->bSimple)
849 nbl_list->nbl[i] = new NbnxnPairlistCpu();
851 nbnxn_init_pairlist(nbl_list->nbl[i]);
852 if (nbl_list->nnbl > 1)
854 nbl_list->nbl_work[i] = new NbnxnPairlistCpu();
855 nbnxn_init_pairlist(nbl_list->nbl_work[i]);
860 /* Only list 0 is used on the GPU, use normal allocation for i>0 */
861 auto pinningPolicy = (i == 0 ? gmx::PinningPolicy::PinnedIfSupported : gmx::PinningPolicy::CannotBePinned);
863 nbl_list->nblGpu[i] = new NbnxnPairlistGpu(pinningPolicy);
866 snew(nbl_list->nbl_fep[i], 1);
867 nbnxn_init_pairlist_fep(nbl_list->nbl_fep[i]);
869 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
873 /* Print statistics of a pair list, used for debug output */
874 static void print_nblist_statistics(FILE *fp, const NbnxnPairlistCpu *nbl,
875 const nbnxn_search *nbs, real rl)
877 const nbnxn_grid_t *grid;
881 grid = &nbs->grid[0];
883 fprintf(fp, "nbl nci %zu ncj %d\n",
884 nbl->ci.size(), nbl->ncjInUse);
885 fprintf(fp, "nbl na_cj %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
886 nbl->na_cj, rl, nbl->ncjInUse, nbl->ncjInUse/static_cast<double>(grid->nc),
887 nbl->ncjInUse/static_cast<double>(grid->nc)*grid->na_cj,
888 nbl->ncjInUse/static_cast<double>(grid->nc)*grid->na_cj/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nc*grid->na_cj/(grid->size[XX]*grid->size[YY]*grid->size[ZZ])));
890 fprintf(fp, "nbl average j cell list length %.1f\n",
891 0.25*nbl->ncjInUse/std::max(static_cast<double>(nbl->ci.size()), 1.0));
893 for (int s = 0; s < SHIFTS; s++)
898 for (const nbnxn_ci_t &ciEntry : nbl->ci)
900 cs[ciEntry.shift & NBNXN_CI_SHIFT] +=
901 ciEntry.cj_ind_end - ciEntry.cj_ind_start;
903 int j = ciEntry.cj_ind_start;
904 while (j < ciEntry.cj_ind_end &&
905 nbl->cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
911 fprintf(fp, "nbl cell pairs, total: %zu excl: %d %.1f%%\n",
912 nbl->cj.size(), npexcl, 100*npexcl/std::max(static_cast<double>(nbl->cj.size()), 1.0));
913 for (int s = 0; s < SHIFTS; s++)
917 fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
922 /* Print statistics of a pair lists, used for debug output */
923 static void print_nblist_statistics(FILE *fp, const NbnxnPairlistGpu *nbl,
924 const nbnxn_search *nbs, real rl)
926 const nbnxn_grid_t *grid;
928 int c[c_gpuNumClusterPerCell + 1];
929 double sum_nsp, sum_nsp2;
932 /* This code only produces correct statistics with domain decomposition */
933 grid = &nbs->grid[0];
935 fprintf(fp, "nbl nsci %zu ncj4 %zu nsi %d excl4 %zu\n",
936 nbl->sci.size(), nbl->cj4.size(), nbl->nci_tot, nbl->excl.size());
937 fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
938 nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/static_cast<double>(grid->nsubc_tot),
939 nbl->nci_tot/static_cast<double>(grid->nsubc_tot)*grid->na_c,
940 nbl->nci_tot/static_cast<double>(grid->nsubc_tot)*grid->na_c/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nsubc_tot*grid->na_c/(grid->size[XX]*grid->size[YY]*grid->size[ZZ])));
945 for (int si = 0; si <= c_gpuNumClusterPerCell; si++)
949 for (const nbnxn_sci_t &sci : nbl->sci)
952 for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
954 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
957 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
959 if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
970 nsp_max = std::max(nsp_max, nsp);
972 if (!nbl->sci.empty())
974 sum_nsp /= nbl->sci.size();
975 sum_nsp2 /= nbl->sci.size();
977 fprintf(fp, "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n",
978 sum_nsp, std::sqrt(sum_nsp2 - sum_nsp*sum_nsp), nsp_max);
980 if (!nbl->cj4.empty())
982 for (b = 0; b <= c_gpuNumClusterPerCell; b++)
984 fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
985 b, c[b], 100.0*c[b]/size_t {nbl->cj4.size()*c_nbnxnGpuJgroupSize});
990 /* Returns a pointer to the exclusion mask for j-cluster-group \p cj4 and warp \p warp
991 * Generates a new exclusion entry when the j-cluster-group uses
992 * the default all-interaction mask at call time, so the returned mask
993 * can be modified when needed.
995 static nbnxn_excl_t *get_exclusion_mask(NbnxnPairlistGpu *nbl,
999 if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
1001 /* No exclusions set, make a new list entry */
1002 const size_t oldSize = nbl->excl.size();
1003 GMX_ASSERT(oldSize >= 1, "We should always have entry [0]");
1004 /* Add entry with default values: no exclusions */
1005 nbl->excl.resize(oldSize + 1);
1006 nbl->cj4[cj4].imei[warp].excl_ind = oldSize;
1009 return &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
1012 static void set_self_and_newton_excls_supersub(NbnxnPairlistGpu *nbl,
1013 int cj4_ind, int sj_offset,
1014 int i_cluster_in_cell)
1016 nbnxn_excl_t *excl[c_nbnxnGpuClusterpairSplit];
1018 /* Here we only set the set self and double pair exclusions */
1020 /* Reserve extra elements, so the resize() in get_exclusion_mask()
1021 * will not invalidate excl entries in the loop below
1023 nbl->excl.reserve(nbl->excl.size() + c_nbnxnGpuClusterpairSplit);
1024 for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1026 excl[w] = get_exclusion_mask(nbl, cj4_ind, w);
1029 /* Only minor < major bits set */
1030 for (int ej = 0; ej < nbl->na_ci; ej++)
1033 for (int ei = ej; ei < nbl->na_ci; ei++)
1035 excl[w]->pair[(ej & (c_nbnxnGpuJgroupSize-1))*nbl->na_ci + ei] &=
1036 ~(1U << (sj_offset*c_gpuNumClusterPerCell + i_cluster_in_cell));
1041 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
1042 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
1044 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1047 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
1048 gmx_unused static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
1050 return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
1051 (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
1052 NBNXN_INTERACTION_MASK_ALL));
1055 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
1056 gmx_unused static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
1058 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1061 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
1062 gmx_unused static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
1064 return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
1065 (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
1066 NBNXN_INTERACTION_MASK_ALL));
1070 #if GMX_SIMD_REAL_WIDTH == 2
1071 #define get_imask_simd_4xn get_imask_simd_j2
1073 #if GMX_SIMD_REAL_WIDTH == 4
1074 #define get_imask_simd_4xn get_imask_simd_j4
1076 #if GMX_SIMD_REAL_WIDTH == 8
1077 #define get_imask_simd_4xn get_imask_simd_j8
1078 #define get_imask_simd_2xnn get_imask_simd_j4
1080 #if GMX_SIMD_REAL_WIDTH == 16
1081 #define get_imask_simd_2xnn get_imask_simd_j8
1085 /* Plain C code for checking and adding cluster-pairs to the list.
1087 * \param[in] gridj The j-grid
1088 * \param[in,out] nbl The pair-list to store the cluster pairs in
1089 * \param[in] icluster The index of the i-cluster
1090 * \param[in] jclusterFirst The first cluster in the j-range
1091 * \param[in] jclusterLast The last cluster in the j-range
1092 * \param[in] excludeSubDiagonal Exclude atom pairs with i-index > j-index
1093 * \param[in] x_j Coordinates for the j-atom, in xyz format
1094 * \param[in] rlist2 The squared list cut-off
1095 * \param[in] rbb2 The squared cut-off for putting cluster-pairs in the list based on bounding box distance only
1096 * \param[in,out] numDistanceChecks The number of distance checks performed
1099 makeClusterListSimple(const nbnxn_grid_t &jGrid,
1100 NbnxnPairlistCpu * nbl,
1104 bool excludeSubDiagonal,
1105 const real * gmx_restrict x_j,
1108 int * gmx_restrict numDistanceChecks)
1110 const nbnxn_bb_t * gmx_restrict bb_ci = nbl->work->iClusterData.bb.data();
1111 const real * gmx_restrict x_ci = nbl->work->iClusterData.x.data();
1116 while (!InRange && jclusterFirst <= jclusterLast)
1118 real d2 = subc_bb_dist2(0, bb_ci, jclusterFirst, jGrid.bb);
1119 *numDistanceChecks += 2;
1121 /* Check if the distance is within the distance where
1122 * we use only the bounding box distance rbb,
1123 * or within the cut-off and there is at least one atom pair
1124 * within the cut-off.
1130 else if (d2 < rlist2)
1132 int cjf_gl = jGrid.cell0 + jclusterFirst;
1133 for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
1135 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
1137 InRange = InRange ||
1138 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+XX]) +
1139 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+YY]) +
1140 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+ZZ]) < rlist2);
1143 *numDistanceChecks += c_nbnxnCpuIClusterSize*c_nbnxnCpuIClusterSize;
1156 while (!InRange && jclusterLast > jclusterFirst)
1158 real d2 = subc_bb_dist2(0, bb_ci, jclusterLast, jGrid.bb);
1159 *numDistanceChecks += 2;
1161 /* Check if the distance is within the distance where
1162 * we use only the bounding box distance rbb,
1163 * or within the cut-off and there is at least one atom pair
1164 * within the cut-off.
1170 else if (d2 < rlist2)
1172 int cjl_gl = jGrid.cell0 + jclusterLast;
1173 for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
1175 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
1177 InRange = InRange ||
1178 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+XX]) +
1179 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+YY]) +
1180 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+ZZ]) < rlist2);
1183 *numDistanceChecks += c_nbnxnCpuIClusterSize*c_nbnxnCpuIClusterSize;
1191 if (jclusterFirst <= jclusterLast)
1193 for (int jcluster = jclusterFirst; jcluster <= jclusterLast; jcluster++)
1195 /* Store cj and the interaction mask */
1197 cjEntry.cj = jGrid.cell0 + jcluster;
1198 cjEntry.excl = get_imask(excludeSubDiagonal, icluster, jcluster);
1199 nbl->cj.push_back(cjEntry);
1201 /* Increase the closing index in the i list */
1202 nbl->ci.back().cj_ind_end = nbl->cj.size();
1206 #ifdef GMX_NBNXN_SIMD_4XN
1207 #include "gromacs/nbnxm/pairlist_simd_4xm.h"
1209 #ifdef GMX_NBNXN_SIMD_2XNN
1210 #include "gromacs/nbnxm/pairlist_simd_2xmm.h"
1213 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
1214 * Checks bounding box distances and possibly atom pair distances.
1216 static void make_cluster_list_supersub(const nbnxn_grid_t &iGrid,
1217 const nbnxn_grid_t &jGrid,
1218 NbnxnPairlistGpu *nbl,
1221 const bool excludeSubDiagonal,
1226 int *numDistanceChecks)
1228 NbnxnPairlistGpuWork &work = *nbl->work;
1231 const float *pbb_ci = work.iSuperClusterData.bbPacked.data();
1233 const nbnxn_bb_t *bb_ci = work.iSuperClusterData.bb.data();
1236 assert(c_nbnxnGpuClusterSize == iGrid.na_c);
1237 assert(c_nbnxnGpuClusterSize == jGrid.na_c);
1239 /* We generate the pairlist mainly based on bounding-box distances
1240 * and do atom pair distance based pruning on the GPU.
1241 * Only if a j-group contains a single cluster-pair, we try to prune
1242 * that pair based on atom distances on the CPU to avoid empty j-groups.
1244 #define PRUNE_LIST_CPU_ONE 1
1245 #define PRUNE_LIST_CPU_ALL 0
1247 #if PRUNE_LIST_CPU_ONE
1251 float *d2l = work.distanceBuffer.data();
1253 for (int subc = 0; subc < jGrid.nsubc[scj]; subc++)
1255 const int cj4_ind = work.cj_ind/c_nbnxnGpuJgroupSize;
1256 const int cj_offset = work.cj_ind - cj4_ind*c_nbnxnGpuJgroupSize;
1257 const int cj = scj*c_gpuNumClusterPerCell + subc;
1259 const int cj_gl = jGrid.cell0*c_gpuNumClusterPerCell + cj;
1262 if (excludeSubDiagonal && sci == scj)
1268 ci1 = iGrid.nsubc[sci];
1272 /* Determine all ci1 bb distances in one call with SIMD4 */
1273 subc_bb_dist2_simd4_xxxx(jGrid.pbb.data() + (cj >> STRIDE_PBB_2LOG)*NNBSBB_XXXX + (cj & (STRIDE_PBB-1)),
1275 *numDistanceChecks += c_nbnxnGpuClusterSize*2;
1279 unsigned int imask = 0;
1280 /* We use a fixed upper-bound instead of ci1 to help optimization */
1281 for (int ci = 0; ci < c_gpuNumClusterPerCell; ci++)
1289 /* Determine the bb distance between ci and cj */
1290 d2l[ci] = subc_bb_dist2(ci, bb_ci, cj, jGrid.bb);
1291 *numDistanceChecks += 2;
1295 #if PRUNE_LIST_CPU_ALL
1296 /* Check if the distance is within the distance where
1297 * we use only the bounding box distance rbb,
1298 * or within the cut-off and there is at least one atom pair
1299 * within the cut-off. This check is very costly.
1301 *numDistanceChecks += c_nbnxnGpuClusterSize*c_nbnxnGpuClusterSize;
1304 clusterpair_in_range(work, ci, cj_gl, stride, x, rlist2)))
1306 /* Check if the distance between the two bounding boxes
1307 * in within the pair-list cut-off.
1312 /* Flag this i-subcell to be taken into account */
1313 imask |= (1U << (cj_offset*c_gpuNumClusterPerCell + ci));
1315 #if PRUNE_LIST_CPU_ONE
1323 #if PRUNE_LIST_CPU_ONE
1324 /* If we only found 1 pair, check if any atoms are actually
1325 * within the cut-off, so we could get rid of it.
1327 if (npair == 1 && d2l[ci_last] >= rbb2 &&
1328 !clusterpair_in_range(work, ci_last, cj_gl, stride, x, rlist2))
1330 imask &= ~(1U << (cj_offset*c_gpuNumClusterPerCell + ci_last));
1337 /* We have at least one cluster pair: add a j-entry */
1338 if (static_cast<size_t>(cj4_ind) == nbl->cj4.size())
1340 nbl->cj4.resize(nbl->cj4.size() + 1);
1342 nbnxn_cj4_t *cj4 = &nbl->cj4[cj4_ind];
1344 cj4->cj[cj_offset] = cj_gl;
1346 /* Set the exclusions for the ci==sj entry.
1347 * Here we don't bother to check if this entry is actually flagged,
1348 * as it will nearly always be in the list.
1350 if (excludeSubDiagonal && sci == scj)
1352 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, subc);
1355 /* Copy the cluster interaction mask to the list */
1356 for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1358 cj4->imei[w].imask |= imask;
1361 nbl->work->cj_ind++;
1363 /* Keep the count */
1364 nbl->nci_tot += npair;
1366 /* Increase the closing index in i super-cell list */
1367 nbl->sci.back().cj4_ind_end =
1368 (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
1373 /* Returns how many contiguous j-clusters we have starting in the i-list */
1374 template <typename CjListType>
1375 static int numContiguousJClusters(const int cjIndexStart,
1376 const int cjIndexEnd,
1377 gmx::ArrayRef<const CjListType> cjList)
1379 const int firstJCluster = nblCj(cjList, cjIndexStart);
1381 int numContiguous = 0;
1383 while (cjIndexStart + numContiguous < cjIndexEnd &&
1384 nblCj(cjList, cjIndexStart + numContiguous) == firstJCluster + numContiguous)
1389 return numContiguous;
1393 * \brief Helper struct for efficient searching for excluded atoms in a j-list
1397 /*! \brief Constructs a j-list range from \p cjList with the given index range */
1398 template <typename CjListType>
1399 JListRanges(int cjIndexStart,
1401 gmx::ArrayRef<const CjListType> cjList);
1403 int cjIndexStart; //!< The start index in the j-list
1404 int cjIndexEnd; //!< The end index in the j-list
1405 int cjFirst; //!< The j-cluster with index cjIndexStart
1406 int cjLast; //!< The j-cluster with index cjIndexEnd-1
1407 int numDirect; //!< Up to cjIndexStart+numDirect the j-clusters are cjFirst + the index offset
1411 template <typename CjListType>
1412 JListRanges::JListRanges(int cjIndexStart,
1414 gmx::ArrayRef<const CjListType> cjList) :
1415 cjIndexStart(cjIndexStart),
1416 cjIndexEnd(cjIndexEnd)
1418 GMX_ASSERT(cjIndexEnd > cjIndexStart, "JListRanges should only be called with non-empty lists");
1420 cjFirst = nblCj(cjList, cjIndexStart);
1421 cjLast = nblCj(cjList, cjIndexEnd - 1);
1423 /* Determine how many contiguous j-cells we have starting
1424 * from the first i-cell. This number can be used to directly
1425 * calculate j-cell indices for excluded atoms.
1427 numDirect = numContiguousJClusters(cjIndexStart, cjIndexEnd, cjList);
1431 /* Return the index of \p jCluster in the given range or -1 when not present
1433 * Note: This code is executed very often and therefore performance is
1434 * important. It should be inlined and fully optimized.
1436 template <typename CjListType>
1438 findJClusterInJList(int jCluster,
1439 const JListRanges &ranges,
1440 gmx::ArrayRef<const CjListType> cjList)
1444 if (jCluster < ranges.cjFirst + ranges.numDirect)
1446 /* We can calculate the index directly using the offset */
1447 index = ranges.cjIndexStart + jCluster - ranges.cjFirst;
1451 /* Search for jCluster using bisection */
1453 int rangeStart = ranges.cjIndexStart + ranges.numDirect;
1454 int rangeEnd = ranges.cjIndexEnd;
1456 while (index == -1 && rangeStart < rangeEnd)
1458 rangeMiddle = (rangeStart + rangeEnd) >> 1;
1460 const int clusterMiddle = nblCj(cjList, rangeMiddle);
1462 if (jCluster == clusterMiddle)
1464 index = rangeMiddle;
1466 else if (jCluster < clusterMiddle)
1468 rangeEnd = rangeMiddle;
1472 rangeStart = rangeMiddle + 1;
1480 // TODO: Get rid of the two functions below by renaming sci to ci (or something better)
1482 /* Return the i-entry in the list we are currently operating on */
1483 static nbnxn_ci_t *getOpenIEntry(NbnxnPairlistCpu *nbl)
1485 return &nbl->ci.back();
1488 /* Return the i-entry in the list we are currently operating on */
1489 static nbnxn_sci_t *getOpenIEntry(NbnxnPairlistGpu *nbl)
1491 return &nbl->sci.back();
1494 /* Set all atom-pair exclusions for a simple type list i-entry
1496 * Set all atom-pair exclusions from the topology stored in exclusions
1497 * as masks in the pair-list for simple list entry iEntry.
1500 setExclusionsForIEntry(const nbnxn_search *nbs,
1501 NbnxnPairlistCpu *nbl,
1502 gmx_bool diagRemoved,
1504 const nbnxn_ci_t &iEntry,
1505 const t_blocka &exclusions)
1507 if (iEntry.cj_ind_end == iEntry.cj_ind_start)
1509 /* Empty list: no exclusions */
1513 const JListRanges ranges(iEntry.cj_ind_start, iEntry.cj_ind_end, gmx::makeConstArrayRef(nbl->cj));
1515 const int iCluster = iEntry.ci;
1517 gmx::ArrayRef<const int> cell = nbs->cell;
1519 /* Loop over the atoms in the i-cluster */
1520 for (int i = 0; i < nbl->na_ci; i++)
1522 const int iIndex = iCluster*nbl->na_ci + i;
1523 const int iAtom = nbs->a[iIndex];
1526 /* Loop over the topology-based exclusions for this i-atom */
1527 for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
1529 const int jAtom = exclusions.a[exclIndex];
1533 /* The self exclusion are already set, save some time */
1537 /* Get the index of the j-atom in the nbnxn atom data */
1538 const int jIndex = cell[jAtom];
1540 /* Without shifts we only calculate interactions j>i
1541 * for one-way pair-lists.
1543 if (diagRemoved && jIndex <= iIndex)
1548 const int jCluster = (jIndex >> na_cj_2log);
1550 /* Could the cluster se be in our list? */
1551 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
1554 findJClusterInJList(jCluster, ranges,
1555 gmx::makeConstArrayRef(nbl->cj));
1559 /* We found an exclusion, clear the corresponding
1562 const int innerJ = jIndex - (jCluster << na_cj_2log);
1564 nbl->cj[index].excl &= ~(1U << ((i << na_cj_2log) + innerJ));
1572 /* Add a new i-entry to the FEP list and copy the i-properties */
1573 static inline void fep_list_new_nri_copy(t_nblist *nlist)
1575 /* Add a new i-entry */
1578 assert(nlist->nri < nlist->maxnri);
1580 /* Duplicate the last i-entry, except for jindex, which continues */
1581 nlist->iinr[nlist->nri] = nlist->iinr[nlist->nri-1];
1582 nlist->shift[nlist->nri] = nlist->shift[nlist->nri-1];
1583 nlist->gid[nlist->nri] = nlist->gid[nlist->nri-1];
1584 nlist->jindex[nlist->nri] = nlist->nrj;
1587 /* For load balancing of the free-energy lists over threads, we set
1588 * the maximum nrj size of an i-entry to 40. This leads to good
1589 * load balancing in the worst case scenario of a single perturbed
1590 * particle on 16 threads, while not introducing significant overhead.
1591 * Note that half of the perturbed pairs will anyhow end up in very small lists,
1592 * since non perturbed i-particles will see few perturbed j-particles).
1594 const int max_nrj_fep = 40;
1596 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
1597 * singularities for overlapping particles (0/0), since the charges and
1598 * LJ parameters have been zeroed in the nbnxn data structure.
1599 * Simultaneously make a group pair list for the perturbed pairs.
1601 static void make_fep_list(const nbnxn_search *nbs,
1602 const nbnxn_atomdata_t *nbat,
1603 NbnxnPairlistCpu *nbl,
1604 gmx_bool bDiagRemoved,
1606 real gmx_unused shx,
1607 real gmx_unused shy,
1608 real gmx_unused shz,
1609 real gmx_unused rlist_fep2,
1610 const nbnxn_grid_t &iGrid,
1611 const nbnxn_grid_t &jGrid,
1614 int ci, cj_ind_start, cj_ind_end, cja, cjr;
1616 int ngid, gid_i = 0, gid_j, gid;
1617 int egp_shift, egp_mask;
1619 int ind_i, ind_j, ai, aj;
1621 gmx_bool bFEP_i, bFEP_i_all;
1623 if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
1631 cj_ind_start = nbl_ci->cj_ind_start;
1632 cj_ind_end = nbl_ci->cj_ind_end;
1634 /* In worst case we have alternating energy groups
1635 * and create #atom-pair lists, which means we need the size
1636 * of a cluster pair (na_ci*na_cj) times the number of cj's.
1638 nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
1639 if (nlist->nri + nri_max > nlist->maxnri)
1641 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1642 reallocate_nblist(nlist);
1645 const nbnxn_atomdata_t::Params &nbatParams = nbat->params();
1647 ngid = nbatParams.nenergrp;
1649 if (ngid*jGrid.na_cj > gmx::index(sizeof(gid_cj)*8))
1651 gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %zu energy groups",
1652 iGrid.na_c, jGrid.na_cj, (sizeof(gid_cj)*8)/jGrid.na_cj);
1655 egp_shift = nbatParams.neg_2log;
1656 egp_mask = (1 << egp_shift) - 1;
1658 /* Loop over the atoms in the i sub-cell */
1660 for (int i = 0; i < nbl->na_ci; i++)
1662 ind_i = ci*nbl->na_ci + i;
1667 nlist->jindex[nri+1] = nlist->jindex[nri];
1668 nlist->iinr[nri] = ai;
1669 /* The actual energy group pair index is set later */
1670 nlist->gid[nri] = 0;
1671 nlist->shift[nri] = nbl_ci->shift & NBNXN_CI_SHIFT;
1673 bFEP_i = ((iGrid.fep[ci - iGrid.cell0] & (1 << i)) != 0u);
1675 bFEP_i_all = bFEP_i_all && bFEP_i;
1677 if (nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
1679 nlist->maxnrj = over_alloc_small(nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj);
1680 srenew(nlist->jjnr, nlist->maxnrj);
1681 srenew(nlist->excl_fep, nlist->maxnrj);
1686 gid_i = (nbatParams.energrp[ci] >> (egp_shift*i)) & egp_mask;
1689 for (int cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
1691 unsigned int fep_cj;
1693 cja = nbl->cj[cj_ind].cj;
1695 if (jGrid.na_cj == jGrid.na_c)
1697 cjr = cja - jGrid.cell0;
1698 fep_cj = jGrid.fep[cjr];
1701 gid_cj = nbatParams.energrp[cja];
1704 else if (2*jGrid.na_cj == jGrid.na_c)
1706 cjr = cja - jGrid.cell0*2;
1707 /* Extract half of the ci fep/energrp mask */
1708 fep_cj = (jGrid.fep[cjr>>1] >> ((cjr&1)*jGrid.na_cj)) & ((1<<jGrid.na_cj) - 1);
1711 gid_cj = nbatParams.energrp[cja>>1] >> ((cja&1)*jGrid.na_cj*egp_shift) & ((1<<(jGrid.na_cj*egp_shift)) - 1);
1716 cjr = cja - (jGrid.cell0>>1);
1717 /* Combine two ci fep masks/energrp */
1718 fep_cj = jGrid.fep[cjr*2] + (jGrid.fep[cjr*2+1] << jGrid.na_c);
1721 gid_cj = nbatParams.energrp[cja*2] + (nbatParams.energrp[cja*2+1] << (jGrid.na_c*egp_shift));
1725 if (bFEP_i || fep_cj != 0)
1727 for (int j = 0; j < nbl->na_cj; j++)
1729 /* Is this interaction perturbed and not excluded? */
1730 ind_j = cja*nbl->na_cj + j;
1733 (bFEP_i || (fep_cj & (1 << j))) &&
1734 (!bDiagRemoved || ind_j >= ind_i))
1738 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
1739 gid = GID(gid_i, gid_j, ngid);
1741 if (nlist->nrj > nlist->jindex[nri] &&
1742 nlist->gid[nri] != gid)
1744 /* Energy group pair changed: new list */
1745 fep_list_new_nri_copy(nlist);
1748 nlist->gid[nri] = gid;
1751 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1753 fep_list_new_nri_copy(nlist);
1757 /* Add it to the FEP list */
1758 nlist->jjnr[nlist->nrj] = aj;
1759 nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
1762 /* Exclude it from the normal list.
1763 * Note that the charge has been set to zero,
1764 * but we need to avoid 0/0, as perturbed atoms
1765 * can be on top of each other.
1767 nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
1773 if (nlist->nrj > nlist->jindex[nri])
1775 /* Actually add this new, non-empty, list */
1777 nlist->jindex[nlist->nri] = nlist->nrj;
1784 /* All interactions are perturbed, we can skip this entry */
1785 nbl_ci->cj_ind_end = cj_ind_start;
1786 nbl->ncjInUse -= cj_ind_end - cj_ind_start;
1790 /* Return the index of atom a within a cluster */
1791 static inline int cj_mod_cj4(int cj)
1793 return cj & (c_nbnxnGpuJgroupSize - 1);
1796 /* Convert a j-cluster to a cj4 group */
1797 static inline int cj_to_cj4(int cj)
1799 return cj/c_nbnxnGpuJgroupSize;
1802 /* Return the index of an j-atom within a warp */
1803 static inline int a_mod_wj(int a)
1805 return a & (c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit - 1);
1808 /* As make_fep_list above, but for super/sub lists. */
1809 static void make_fep_list(const nbnxn_search *nbs,
1810 const nbnxn_atomdata_t *nbat,
1811 NbnxnPairlistGpu *nbl,
1812 gmx_bool bDiagRemoved,
1813 const nbnxn_sci_t *nbl_sci,
1818 const nbnxn_grid_t &iGrid,
1819 const nbnxn_grid_t &jGrid,
1824 int ind_i, ind_j, ai, aj;
1828 const nbnxn_cj4_t *cj4;
1830 const int numJClusterGroups = nbl_sci->numJClusterGroups();
1831 if (numJClusterGroups == 0)
1837 const int sci = nbl_sci->sci;
1839 const int cj4_ind_start = nbl_sci->cj4_ind_start;
1840 const int cj4_ind_end = nbl_sci->cj4_ind_end;
1842 /* Here we process one super-cell, max #atoms na_sc, versus a list
1843 * cj4 entries, each with max c_nbnxnGpuJgroupSize cj's, each
1844 * of size na_cj atoms.
1845 * On the GPU we don't support energy groups (yet).
1846 * So for each of the na_sc i-atoms, we need max one FEP list
1847 * for each max_nrj_fep j-atoms.
1849 nri_max = nbl->na_sc*nbl->na_cj*(1 + (numJClusterGroups*c_nbnxnGpuJgroupSize)/max_nrj_fep);
1850 if (nlist->nri + nri_max > nlist->maxnri)
1852 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1853 reallocate_nblist(nlist);
1856 /* Loop over the atoms in the i super-cluster */
1857 for (int c = 0; c < c_gpuNumClusterPerCell; c++)
1859 c_abs = sci*c_gpuNumClusterPerCell + c;
1861 for (int i = 0; i < nbl->na_ci; i++)
1863 ind_i = c_abs*nbl->na_ci + i;
1868 nlist->jindex[nri+1] = nlist->jindex[nri];
1869 nlist->iinr[nri] = ai;
1870 /* With GPUs, energy groups are not supported */
1871 nlist->gid[nri] = 0;
1872 nlist->shift[nri] = nbl_sci->shift & NBNXN_CI_SHIFT;
1874 bFEP_i = ((iGrid.fep[c_abs - iGrid.cell0*c_gpuNumClusterPerCell] & (1 << i)) != 0u);
1876 xi = nbat->x()[ind_i*nbat->xstride+XX] + shx;
1877 yi = nbat->x()[ind_i*nbat->xstride+YY] + shy;
1878 zi = nbat->x()[ind_i*nbat->xstride+ZZ] + shz;
1880 const int nrjMax = nlist->nrj + numJClusterGroups*c_nbnxnGpuJgroupSize*nbl->na_cj;
1881 if (nrjMax > nlist->maxnrj)
1883 nlist->maxnrj = over_alloc_small(nrjMax);
1884 srenew(nlist->jjnr, nlist->maxnrj);
1885 srenew(nlist->excl_fep, nlist->maxnrj);
1888 for (int cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
1890 cj4 = &nbl->cj4[cj4_ind];
1892 for (int gcj = 0; gcj < c_nbnxnGpuJgroupSize; gcj++)
1894 unsigned int fep_cj;
1896 if ((cj4->imei[0].imask & (1U << (gcj*c_gpuNumClusterPerCell + c))) == 0)
1898 /* Skip this ci for this cj */
1903 cj4->cj[gcj] - jGrid.cell0*c_gpuNumClusterPerCell;
1905 fep_cj = jGrid.fep[cjr];
1907 if (bFEP_i || fep_cj != 0)
1909 for (int j = 0; j < nbl->na_cj; j++)
1911 /* Is this interaction perturbed and not excluded? */
1912 ind_j = (jGrid.cell0*c_gpuNumClusterPerCell + cjr)*nbl->na_cj + j;
1915 (bFEP_i || (fep_cj & (1 << j))) &&
1916 (!bDiagRemoved || ind_j >= ind_i))
1919 unsigned int excl_bit;
1922 const int jHalf = j/(c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit);
1923 nbnxn_excl_t *excl =
1924 get_exclusion_mask(nbl, cj4_ind, jHalf);
1926 excl_pair = a_mod_wj(j)*nbl->na_ci + i;
1927 excl_bit = (1U << (gcj*c_gpuNumClusterPerCell + c));
1929 dx = nbat->x()[ind_j*nbat->xstride+XX] - xi;
1930 dy = nbat->x()[ind_j*nbat->xstride+YY] - yi;
1931 dz = nbat->x()[ind_j*nbat->xstride+ZZ] - zi;
1933 /* The unpruned GPU list has more than 2/3
1934 * of the atom pairs beyond rlist. Using
1935 * this list will cause a lot of overhead
1936 * in the CPU FEP kernels, especially
1937 * relative to the fast GPU kernels.
1938 * So we prune the FEP list here.
1940 if (dx*dx + dy*dy + dz*dz < rlist_fep2)
1942 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1944 fep_list_new_nri_copy(nlist);
1948 /* Add it to the FEP list */
1949 nlist->jjnr[nlist->nrj] = aj;
1950 nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
1954 /* Exclude it from the normal list.
1955 * Note that the charge and LJ parameters have
1956 * been set to zero, but we need to avoid 0/0,
1957 * as perturbed atoms can be on top of each other.
1959 excl->pair[excl_pair] &= ~excl_bit;
1963 /* Note that we could mask out this pair in imask
1964 * if all i- and/or all j-particles are perturbed.
1965 * But since the perturbed pairs on the CPU will
1966 * take an order of magnitude more time, the GPU
1967 * will finish before the CPU and there is no gain.
1973 if (nlist->nrj > nlist->jindex[nri])
1975 /* Actually add this new, non-empty, list */
1977 nlist->jindex[nlist->nri] = nlist->nrj;
1984 /* Set all atom-pair exclusions for a GPU type list i-entry
1986 * Sets all atom-pair exclusions from the topology stored in exclusions
1987 * as masks in the pair-list for i-super-cluster list entry iEntry.
1990 setExclusionsForIEntry(const nbnxn_search *nbs,
1991 NbnxnPairlistGpu *nbl,
1992 gmx_bool diagRemoved,
1993 int gmx_unused na_cj_2log,
1994 const nbnxn_sci_t &iEntry,
1995 const t_blocka &exclusions)
1997 if (iEntry.numJClusterGroups() == 0)
2003 /* Set the search ranges using start and end j-cluster indices.
2004 * Note that here we can not use cj4_ind_end, since the last cj4
2005 * can be only partially filled, so we use cj_ind.
2007 const JListRanges ranges(iEntry.cj4_ind_start*c_nbnxnGpuJgroupSize,
2009 gmx::makeConstArrayRef(nbl->cj4));
2011 GMX_ASSERT(nbl->na_ci == c_nbnxnGpuClusterSize, "na_ci should match the GPU cluster size");
2012 constexpr int c_clusterSize = c_nbnxnGpuClusterSize;
2013 constexpr int c_superClusterSize = c_nbnxnGpuNumClusterPerSupercluster*c_nbnxnGpuClusterSize;
2015 const int iSuperCluster = iEntry.sci;
2017 gmx::ArrayRef<const int> cell = nbs->cell;
2019 /* Loop over the atoms in the i super-cluster */
2020 for (int i = 0; i < c_superClusterSize; i++)
2022 const int iIndex = iSuperCluster*c_superClusterSize + i;
2023 const int iAtom = nbs->a[iIndex];
2026 const int iCluster = i/c_clusterSize;
2028 /* Loop over the topology-based exclusions for this i-atom */
2029 for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
2031 const int jAtom = exclusions.a[exclIndex];
2035 /* The self exclusions are already set, save some time */
2039 /* Get the index of the j-atom in the nbnxn atom data */
2040 const int jIndex = cell[jAtom];
2042 /* Without shifts we only calculate interactions j>i
2043 * for one-way pair-lists.
2045 /* NOTE: We would like to use iIndex on the right hand side,
2046 * but that makes this routine 25% slower with gcc6/7.
2047 * Even using c_superClusterSize makes it slower.
2048 * Either of these changes triggers peeling of the exclIndex
2049 * loop, which apparently leads to far less efficient code.
2051 if (diagRemoved && jIndex <= iSuperCluster*nbl->na_sc + i)
2056 const int jCluster = jIndex/c_clusterSize;
2058 /* Check whether the cluster is in our list? */
2059 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
2062 findJClusterInJList(jCluster, ranges,
2063 gmx::makeConstArrayRef(nbl->cj4));
2067 /* We found an exclusion, clear the corresponding
2070 const unsigned int pairMask = (1U << (cj_mod_cj4(index)*c_gpuNumClusterPerCell + iCluster));
2071 /* Check if the i-cluster interacts with the j-cluster */
2072 if (nbl_imask0(nbl, index) & pairMask)
2074 const int innerI = (i & (c_clusterSize - 1));
2075 const int innerJ = (jIndex & (c_clusterSize - 1));
2077 /* Determine which j-half (CUDA warp) we are in */
2078 const int jHalf = innerJ/(c_clusterSize/c_nbnxnGpuClusterpairSplit);
2080 nbnxn_excl_t *interactionMask =
2081 get_exclusion_mask(nbl, cj_to_cj4(index), jHalf);
2083 interactionMask->pair[a_mod_wj(innerJ)*c_clusterSize + innerI] &= ~pairMask;
2092 /* Make a new ci entry at the back of nbl->ci */
2093 static void addNewIEntry(NbnxnPairlistCpu *nbl, int ci, int shift, int flags)
2097 ciEntry.shift = shift;
2098 /* Store the interaction flags along with the shift */
2099 ciEntry.shift |= flags;
2100 ciEntry.cj_ind_start = nbl->cj.size();
2101 ciEntry.cj_ind_end = nbl->cj.size();
2102 nbl->ci.push_back(ciEntry);
2105 /* Make a new sci entry at index nbl->nsci */
2106 static void addNewIEntry(NbnxnPairlistGpu *nbl, int sci, int shift, int gmx_unused flags)
2108 nbnxn_sci_t sciEntry;
2110 sciEntry.shift = shift;
2111 sciEntry.cj4_ind_start = nbl->cj4.size();
2112 sciEntry.cj4_ind_end = nbl->cj4.size();
2114 nbl->sci.push_back(sciEntry);
2117 /* Sort the simple j-list cj on exclusions.
2118 * Entries with exclusions will all be sorted to the beginning of the list.
2120 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
2121 NbnxnPairlistCpuWork *work)
2123 work->cj.resize(ncj);
2125 /* Make a list of the j-cells involving exclusions */
2127 for (int j = 0; j < ncj; j++)
2129 if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2131 work->cj[jnew++] = cj[j];
2134 /* Check if there are exclusions at all or not just the first entry */
2135 if (!((jnew == 0) ||
2136 (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
2138 for (int j = 0; j < ncj; j++)
2140 if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
2142 work->cj[jnew++] = cj[j];
2145 for (int j = 0; j < ncj; j++)
2147 cj[j] = work->cj[j];
2152 /* Close this simple list i entry */
2153 static void closeIEntry(NbnxnPairlistCpu *nbl,
2154 int gmx_unused sp_max_av,
2155 gmx_bool gmx_unused progBal,
2156 float gmx_unused nsp_tot_est,
2157 int gmx_unused thread,
2158 int gmx_unused nthread)
2160 nbnxn_ci_t &ciEntry = nbl->ci.back();
2162 /* All content of the new ci entry have already been filled correctly,
2163 * we only need to sort and increase counts or remove the entry when empty.
2165 const int jlen = ciEntry.cj_ind_end - ciEntry.cj_ind_start;
2168 sort_cj_excl(nbl->cj.data() + ciEntry.cj_ind_start, jlen, nbl->work);
2170 /* The counts below are used for non-bonded pair/flop counts
2171 * and should therefore match the available kernel setups.
2173 if (!(ciEntry.shift & NBNXN_CI_DO_COUL(0)))
2175 nbl->work->ncj_noq += jlen;
2177 else if ((ciEntry.shift & NBNXN_CI_HALF_LJ(0)) ||
2178 !(ciEntry.shift & NBNXN_CI_DO_LJ(0)))
2180 nbl->work->ncj_hlj += jlen;
2185 /* Entry is empty: remove it */
2190 /* Split sci entry for load balancing on the GPU.
2191 * Splitting ensures we have enough lists to fully utilize the whole GPU.
2192 * With progBal we generate progressively smaller lists, which improves
2193 * load balancing. As we only know the current count on our own thread,
2194 * we will need to estimate the current total amount of i-entries.
2195 * As the lists get concatenated later, this estimate depends
2196 * both on nthread and our own thread index.
2198 static void split_sci_entry(NbnxnPairlistGpu *nbl,
2200 gmx_bool progBal, float nsp_tot_est,
2201 int thread, int nthread)
2209 /* Estimate the total numbers of ci's of the nblist combined
2210 * over all threads using the target number of ci's.
2212 nsp_est = (nsp_tot_est*thread)/nthread + nbl->nci_tot;
2214 /* The first ci blocks should be larger, to avoid overhead.
2215 * The last ci blocks should be smaller, to improve load balancing.
2216 * The factor 3/2 makes the first block 3/2 times the target average
2217 * and ensures that the total number of blocks end up equal to
2218 * that of equally sized blocks of size nsp_target_av.
2220 nsp_max = static_cast<int>(nsp_target_av*(nsp_tot_est*1.5/(nsp_est + nsp_tot_est)));
2224 nsp_max = nsp_target_av;
2227 const int cj4_start = nbl->sci.back().cj4_ind_start;
2228 const int cj4_end = nbl->sci.back().cj4_ind_end;
2229 const int j4len = cj4_end - cj4_start;
2231 if (j4len > 1 && j4len*c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize > nsp_max)
2233 /* Modify the last ci entry and process the cj4's again */
2239 for (int cj4 = cj4_start; cj4 < cj4_end; cj4++)
2241 int nsp_cj4_p = nsp_cj4;
2242 /* Count the number of cluster pairs in this cj4 group */
2244 for (int p = 0; p < c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize; p++)
2246 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
2249 /* If adding the current cj4 with nsp_cj4 pairs get us further
2250 * away from our target nsp_max, split the list before this cj4.
2252 if (nsp > 0 && nsp_max - nsp < nsp + nsp_cj4 - nsp_max)
2254 /* Split the list at cj4 */
2255 nbl->sci.back().cj4_ind_end = cj4;
2256 /* Create a new sci entry */
2258 sciNew.sci = nbl->sci.back().sci;
2259 sciNew.shift = nbl->sci.back().shift;
2260 sciNew.cj4_ind_start = cj4;
2261 nbl->sci.push_back(sciNew);
2264 nsp_cj4_e = nsp_cj4_p;
2270 /* Put the remaining cj4's in the last sci entry */
2271 nbl->sci.back().cj4_ind_end = cj4_end;
2273 /* Possibly balance out the last two sci's
2274 * by moving the last cj4 of the second last sci.
2276 if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
2278 GMX_ASSERT(nbl->sci.size() >= 2, "We expect at least two elements");
2279 nbl->sci[nbl->sci.size() - 2].cj4_ind_end--;
2280 nbl->sci[nbl->sci.size() - 1].cj4_ind_start--;
2285 /* Clost this super/sub list i entry */
2286 static void closeIEntry(NbnxnPairlistGpu *nbl,
2288 gmx_bool progBal, float nsp_tot_est,
2289 int thread, int nthread)
2291 nbnxn_sci_t &sciEntry = *getOpenIEntry(nbl);
2293 /* All content of the new ci entry have already been filled correctly,
2294 * we only need to, potentially, split or remove the entry when empty.
2296 int j4len = sciEntry.numJClusterGroups();
2299 /* We can only have complete blocks of 4 j-entries in a list,
2300 * so round the count up before closing.
2302 int ncj4 = (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
2303 nbl->work->cj_ind = ncj4*c_nbnxnGpuJgroupSize;
2307 /* Measure the size of the new entry and potentially split it */
2308 split_sci_entry(nbl, nsp_max_av, progBal, nsp_tot_est,
2314 /* Entry is empty: remove it */
2315 nbl->sci.pop_back();
2319 /* Syncs the working array before adding another grid pair to the GPU list */
2320 static void sync_work(NbnxnPairlistCpu gmx_unused *nbl)
2324 /* Syncs the working array before adding another grid pair to the GPU list */
2325 static void sync_work(NbnxnPairlistGpu *nbl)
2327 nbl->work->cj_ind = nbl->cj4.size()*c_nbnxnGpuJgroupSize;
2330 /* Clears an NbnxnPairlistCpu data structure */
2331 static void clear_pairlist(NbnxnPairlistCpu *nbl)
2337 nbl->ciOuter.clear();
2338 nbl->cjOuter.clear();
2340 nbl->work->ncj_noq = 0;
2341 nbl->work->ncj_hlj = 0;
2344 /* Clears an NbnxnPairlistGpu data structure */
2345 static void clear_pairlist(NbnxnPairlistGpu *nbl)
2349 nbl->excl.resize(1);
2353 /* Clears a group scheme pair list */
2354 static void clear_pairlist_fep(t_nblist *nl)
2358 if (nl->jindex == nullptr)
2360 snew(nl->jindex, 1);
2365 /* Sets a simple list i-cell bounding box, including PBC shift */
2366 static inline void set_icell_bb_simple(gmx::ArrayRef<const nbnxn_bb_t> bb,
2368 real shx, real shy, real shz,
2371 bb_ci->lower[BB_X] = bb[ci].lower[BB_X] + shx;
2372 bb_ci->lower[BB_Y] = bb[ci].lower[BB_Y] + shy;
2373 bb_ci->lower[BB_Z] = bb[ci].lower[BB_Z] + shz;
2374 bb_ci->upper[BB_X] = bb[ci].upper[BB_X] + shx;
2375 bb_ci->upper[BB_Y] = bb[ci].upper[BB_Y] + shy;
2376 bb_ci->upper[BB_Z] = bb[ci].upper[BB_Z] + shz;
2379 /* Sets a simple list i-cell bounding box, including PBC shift */
2380 static inline void set_icell_bb(const nbnxn_grid_t &iGrid,
2382 real shx, real shy, real shz,
2383 NbnxnPairlistCpuWork *work)
2385 set_icell_bb_simple(iGrid.bb, ci, shx, shy, shz, &work->iClusterData.bb[0]);
2389 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2390 static void set_icell_bbxxxx_supersub(gmx::ArrayRef<const float> bb,
2392 real shx, real shy, real shz,
2395 int ia = ci*(c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX;
2396 for (int m = 0; m < (c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
2398 for (int i = 0; i < STRIDE_PBB; i++)
2400 bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
2401 bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
2402 bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
2403 bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
2404 bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
2405 bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
2411 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2412 gmx_unused static void set_icell_bb_supersub(gmx::ArrayRef<const nbnxn_bb_t> bb,
2414 real shx, real shy, real shz,
2417 for (int i = 0; i < c_gpuNumClusterPerCell; i++)
2419 set_icell_bb_simple(bb, ci*c_gpuNumClusterPerCell+i,
2425 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2426 gmx_unused static void set_icell_bb(const nbnxn_grid_t &iGrid,
2428 real shx, real shy, real shz,
2429 NbnxnPairlistGpuWork *work)
2432 set_icell_bbxxxx_supersub(iGrid.pbb, ci, shx, shy, shz,
2433 work->iSuperClusterData.bbPacked.data());
2435 set_icell_bb_supersub(iGrid.bb, ci, shx, shy, shz,
2436 work->iSuperClusterData.bb.data());
2440 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
2441 static void icell_set_x_simple(int ci,
2442 real shx, real shy, real shz,
2443 int stride, const real *x,
2444 NbnxnPairlistCpuWork::IClusterData *iClusterData)
2446 const int ia = ci*c_nbnxnCpuIClusterSize;
2448 for (int i = 0; i < c_nbnxnCpuIClusterSize; i++)
2450 iClusterData->x[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
2451 iClusterData->x[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
2452 iClusterData->x[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
2456 static void icell_set_x(int ci,
2457 real shx, real shy, real shz,
2458 int stride, const real *x,
2459 const Nbnxm::KernelType kernelType,
2460 NbnxnPairlistCpuWork *work)
2465 #ifdef GMX_NBNXN_SIMD_4XN
2466 case Nbnxm::KernelType::Cpu4xN_Simd_4xN:
2467 icell_set_x_simd_4xn(ci, shx, shy, shz, stride, x, work);
2470 #ifdef GMX_NBNXN_SIMD_2XNN
2471 case Nbnxm::KernelType::Cpu4xN_Simd_2xNN:
2472 icell_set_x_simd_2xnn(ci, shx, shy, shz, stride, x, work);
2476 case Nbnxm::KernelType::Cpu4x4_PlainC:
2477 icell_set_x_simple(ci, shx, shy, shz, stride, x, &work->iClusterData);
2480 GMX_ASSERT(false, "Unhandled case");
2485 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
2486 static void icell_set_x(int ci,
2487 real shx, real shy, real shz,
2488 int stride, const real *x,
2489 Nbnxm::KernelType gmx_unused kernelType,
2490 NbnxnPairlistGpuWork *work)
2492 #if !GMX_SIMD4_HAVE_REAL
2494 real * x_ci = work->iSuperClusterData.x.data();
2496 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize;
2497 for (int i = 0; i < c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize; i++)
2499 x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
2500 x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
2501 x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
2504 #else /* !GMX_SIMD4_HAVE_REAL */
2506 real * x_ci = work->iSuperClusterData.xSimd.data();
2508 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2510 for (int i = 0; i < c_nbnxnGpuClusterSize; i += GMX_SIMD4_WIDTH)
2512 int io = si*c_nbnxnGpuClusterSize + i;
2513 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize + io;
2514 for (int j = 0; j < GMX_SIMD4_WIDTH; j++)
2516 x_ci[io*DIM + j + XX*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + XX] + shx;
2517 x_ci[io*DIM + j + YY*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + YY] + shy;
2518 x_ci[io*DIM + j + ZZ*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + ZZ] + shz;
2523 #endif /* !GMX_SIMD4_HAVE_REAL */
2526 static real minimum_subgrid_size_xy(const nbnxn_grid_t &grid)
2530 return std::min(grid.cellSize[XX], grid.cellSize[YY]);
2534 return std::min(grid.cellSize[XX]/c_gpuNumClusterPerCellX,
2535 grid.cellSize[YY]/c_gpuNumClusterPerCellY);
2539 static real effective_buffer_1x1_vs_MxN(const nbnxn_grid_t &iGrid,
2540 const nbnxn_grid_t &jGrid)
2542 const real eff_1x1_buffer_fac_overest = 0.1;
2544 /* Determine an atom-pair list cut-off buffer size for atom pairs,
2545 * to be added to rlist (including buffer) used for MxN.
2546 * This is for converting an MxN list to a 1x1 list. This means we can't
2547 * use the normal buffer estimate, as we have an MxN list in which
2548 * some atom pairs beyond rlist are missing. We want to capture
2549 * the beneficial effect of buffering by extra pairs just outside rlist,
2550 * while removing the useless pairs that are further away from rlist.
2551 * (Also the buffer could have been set manually not using the estimate.)
2552 * This buffer size is an overestimate.
2553 * We add 10% of the smallest grid sub-cell dimensions.
2554 * Note that the z-size differs per cell and we don't use this,
2555 * so we overestimate.
2556 * With PME, the 10% value gives a buffer that is somewhat larger
2557 * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
2558 * Smaller tolerances or using RF lead to a smaller effective buffer,
2559 * so 10% gives a safe overestimate.
2561 return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(iGrid) +
2562 minimum_subgrid_size_xy(jGrid));
2565 /* Estimates the interaction volume^2 for non-local interactions */
2566 static real nonlocal_vol2(const struct gmx_domdec_zones_t *zones, const rvec ls, real r)
2574 /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
2575 * not home interaction volume^2. As these volumes are not additive,
2576 * this is an overestimate, but it would only be significant in the limit
2577 * of small cells, where we anyhow need to split the lists into
2578 * as small parts as possible.
2581 for (int z = 0; z < zones->n; z++)
2583 if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
2588 for (int d = 0; d < DIM; d++)
2590 if (zones->shift[z][d] == 0)
2594 za *= zones->size[z].x1[d] - zones->size[z].x0[d];
2598 /* 4 octants of a sphere */
2599 vold_est = 0.25*M_PI*r*r*r*r;
2600 /* 4 quarter pie slices on the edges */
2601 vold_est += 4*cl*M_PI/6.0*r*r*r;
2602 /* One rectangular volume on a face */
2603 vold_est += ca*0.5*r*r;
2605 vol2_est_tot += vold_est*za;
2609 return vol2_est_tot;
2612 /* Estimates the average size of a full j-list for super/sub setup */
2613 static void get_nsubpair_target(const nbnxn_search *nbs,
2614 const InteractionLocality iloc,
2616 const int min_ci_balanced,
2617 int *nsubpair_target,
2618 float *nsubpair_tot_est)
2620 /* The target value of 36 seems to be the optimum for Kepler.
2621 * Maxwell is less sensitive to the exact value.
2623 const int nsubpair_target_min = 36;
2624 real r_eff_sup, vol_est, nsp_est, nsp_est_nl;
2626 const nbnxn_grid_t &grid = nbs->grid[0];
2628 /* We don't need to balance list sizes if:
2629 * - We didn't request balancing.
2630 * - The number of grid cells >= the number of lists requested,
2631 * since we will always generate at least #cells lists.
2632 * - We don't have any cells, since then there won't be any lists.
2634 if (min_ci_balanced <= 0 || grid.nc >= min_ci_balanced || grid.nc == 0)
2636 /* nsubpair_target==0 signals no balancing */
2637 *nsubpair_target = 0;
2638 *nsubpair_tot_est = 0;
2644 ls[XX] = (grid.c1[XX] - grid.c0[XX])/(grid.numCells[XX]*c_gpuNumClusterPerCellX);
2645 ls[YY] = (grid.c1[YY] - grid.c0[YY])/(grid.numCells[YY]*c_gpuNumClusterPerCellY);
2646 ls[ZZ] = grid.na_c/(grid.atom_density*ls[XX]*ls[YY]);
2648 /* The formulas below are a heuristic estimate of the average nsj per si*/
2649 r_eff_sup = rlist + nbnxn_get_rlist_effective_inc(grid.na_c, ls);
2651 if (!nbs->DomDec || nbs->zones->n == 1)
2658 gmx::square(grid.atom_density/grid.na_c)*
2659 nonlocal_vol2(nbs->zones, ls, r_eff_sup);
2662 if (iloc == InteractionLocality::Local)
2664 /* Sub-cell interacts with itself */
2665 vol_est = ls[XX]*ls[YY]*ls[ZZ];
2666 /* 6/2 rectangular volume on the faces */
2667 vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
2668 /* 12/2 quarter pie slices on the edges */
2669 vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*gmx::square(r_eff_sup);
2670 /* 4 octants of a sphere */
2671 vol_est += 0.5*4.0/3.0*M_PI*gmx::power3(r_eff_sup);
2673 /* Estimate the number of cluster pairs as the local number of
2674 * clusters times the volume they interact with times the density.
2676 nsp_est = grid.nsubc_tot*vol_est*grid.atom_density/grid.na_c;
2678 /* Subtract the non-local pair count */
2679 nsp_est -= nsp_est_nl;
2681 /* For small cut-offs nsp_est will be an underesimate.
2682 * With DD nsp_est_nl is an overestimate so nsp_est can get negative.
2683 * So to avoid too small or negative nsp_est we set a minimum of
2684 * all cells interacting with all 3^3 direct neighbors (3^3-1)/2+1=14.
2685 * This might be a slight overestimate for small non-periodic groups of
2686 * atoms as will occur for a local domain with DD, but for small
2687 * groups of atoms we'll anyhow be limited by nsubpair_target_min,
2688 * so this overestimation will not matter.
2690 nsp_est = std::max(nsp_est, grid.nsubc_tot*14._real);
2694 fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
2695 nsp_est, nsp_est_nl);
2700 nsp_est = nsp_est_nl;
2703 /* Thus the (average) maximum j-list size should be as follows.
2704 * Since there is overhead, we shouldn't make the lists too small
2705 * (and we can't chop up j-groups) so we use a minimum target size of 36.
2707 *nsubpair_target = std::max(nsubpair_target_min,
2708 roundToInt(nsp_est/min_ci_balanced));
2709 *nsubpair_tot_est = static_cast<int>(nsp_est);
2713 fprintf(debug, "nbl nsp estimate %.1f, nsubpair_target %d\n",
2714 nsp_est, *nsubpair_target);
2718 /* Debug list print function */
2719 static void print_nblist_ci_cj(FILE *fp, const NbnxnPairlistCpu *nbl)
2721 for (const nbnxn_ci_t &ciEntry : nbl->ci)
2723 fprintf(fp, "ci %4d shift %2d ncj %3d\n",
2724 ciEntry.ci, ciEntry.shift,
2725 ciEntry.cj_ind_end - ciEntry.cj_ind_start);
2727 for (int j = ciEntry.cj_ind_start; j < ciEntry.cj_ind_end; j++)
2729 fprintf(fp, " cj %5d imask %x\n",
2736 /* Debug list print function */
2737 static void print_nblist_sci_cj(FILE *fp, const NbnxnPairlistGpu *nbl)
2739 for (const nbnxn_sci_t &sci : nbl->sci)
2741 fprintf(fp, "ci %4d shift %2d ncj4 %2d\n",
2743 sci.numJClusterGroups());
2746 for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
2748 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
2750 fprintf(fp, " sj %5d imask %x\n",
2752 nbl->cj4[j4].imei[0].imask);
2753 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2755 if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
2762 fprintf(fp, "ci %4d shift %2d ncj4 %2d ncp %3d\n",
2764 sci.numJClusterGroups(),
2769 /* Combine pair lists *nbl generated on multiple threads nblc */
2770 static void combine_nblists(int nnbl, NbnxnPairlistGpu **nbl,
2771 NbnxnPairlistGpu *nblc)
2773 int nsci = nblc->sci.size();
2774 int ncj4 = nblc->cj4.size();
2775 int nexcl = nblc->excl.size();
2776 for (int i = 0; i < nnbl; i++)
2778 nsci += nbl[i]->sci.size();
2779 ncj4 += nbl[i]->cj4.size();
2780 nexcl += nbl[i]->excl.size();
2783 /* Resize with the final, combined size, so we can fill in parallel */
2784 /* NOTE: For better performance we should use default initialization */
2785 nblc->sci.resize(nsci);
2786 nblc->cj4.resize(ncj4);
2787 nblc->excl.resize(nexcl);
2789 /* Each thread should copy its own data to the combined arrays,
2790 * as otherwise data will go back and forth between different caches.
2792 #if GMX_OPENMP && !(defined __clang_analyzer__)
2793 int nthreads = gmx_omp_nthreads_get(emntPairsearch);
2796 #pragma omp parallel for num_threads(nthreads) schedule(static)
2797 for (int n = 0; n < nnbl; n++)
2801 /* Determine the offset in the combined data for our thread.
2802 * Note that the original sizes in nblc are lost.
2804 int sci_offset = nsci;
2805 int cj4_offset = ncj4;
2806 int excl_offset = nexcl;
2808 for (int i = n; i < nnbl; i++)
2810 sci_offset -= nbl[i]->sci.size();
2811 cj4_offset -= nbl[i]->cj4.size();
2812 excl_offset -= nbl[i]->excl.size();
2815 const NbnxnPairlistGpu &nbli = *nbl[n];
2817 for (size_t i = 0; i < nbli.sci.size(); i++)
2819 nblc->sci[sci_offset + i] = nbli.sci[i];
2820 nblc->sci[sci_offset + i].cj4_ind_start += cj4_offset;
2821 nblc->sci[sci_offset + i].cj4_ind_end += cj4_offset;
2824 for (size_t j4 = 0; j4 < nbli.cj4.size(); j4++)
2826 nblc->cj4[cj4_offset + j4] = nbli.cj4[j4];
2827 nblc->cj4[cj4_offset + j4].imei[0].excl_ind += excl_offset;
2828 nblc->cj4[cj4_offset + j4].imei[1].excl_ind += excl_offset;
2831 for (size_t j4 = 0; j4 < nbli.excl.size(); j4++)
2833 nblc->excl[excl_offset + j4] = nbli.excl[j4];
2836 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2839 for (int n = 0; n < nnbl; n++)
2841 nblc->nci_tot += nbl[n]->nci_tot;
2845 static void balance_fep_lists(const nbnxn_search *nbs,
2846 nbnxn_pairlist_set_t *nbl_lists)
2849 int nri_tot, nrj_tot, nrj_target;
2853 nnbl = nbl_lists->nnbl;
2857 /* Nothing to balance */
2861 /* Count the total i-lists and pairs */
2864 for (int th = 0; th < nnbl; th++)
2866 nri_tot += nbl_lists->nbl_fep[th]->nri;
2867 nrj_tot += nbl_lists->nbl_fep[th]->nrj;
2870 nrj_target = (nrj_tot + nnbl - 1)/nnbl;
2872 assert(gmx_omp_nthreads_get(emntNonbonded) == nnbl);
2874 #pragma omp parallel for schedule(static) num_threads(nnbl)
2875 for (int th = 0; th < nnbl; th++)
2879 t_nblist *nbl = nbs->work[th].nbl_fep.get();
2881 /* Note that here we allocate for the total size, instead of
2882 * a per-thread esimate (which is hard to obtain).
2884 if (nri_tot > nbl->maxnri)
2886 nbl->maxnri = over_alloc_large(nri_tot);
2887 reallocate_nblist(nbl);
2889 if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
2891 nbl->maxnrj = over_alloc_small(nrj_tot);
2892 srenew(nbl->jjnr, nbl->maxnrj);
2893 srenew(nbl->excl_fep, nbl->maxnrj);
2896 clear_pairlist_fep(nbl);
2898 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2901 /* Loop over the source lists and assign and copy i-entries */
2903 nbld = nbs->work[th_dest].nbl_fep.get();
2904 for (int th = 0; th < nnbl; th++)
2908 nbls = nbl_lists->nbl_fep[th];
2910 for (int i = 0; i < nbls->nri; i++)
2914 /* The number of pairs in this i-entry */
2915 nrj = nbls->jindex[i+1] - nbls->jindex[i];
2917 /* Decide if list th_dest is too large and we should procede
2918 * to the next destination list.
2920 if (th_dest+1 < nnbl && nbld->nrj > 0 &&
2921 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
2924 nbld = nbs->work[th_dest].nbl_fep.get();
2927 nbld->iinr[nbld->nri] = nbls->iinr[i];
2928 nbld->gid[nbld->nri] = nbls->gid[i];
2929 nbld->shift[nbld->nri] = nbls->shift[i];
2931 for (int j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
2933 nbld->jjnr[nbld->nrj] = nbls->jjnr[j];
2934 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
2938 nbld->jindex[nbld->nri] = nbld->nrj;
2942 /* Swap the list pointers */
2943 for (int th = 0; th < nnbl; th++)
2945 t_nblist *nbl_tmp = nbs->work[th].nbl_fep.release();
2946 nbs->work[th].nbl_fep.reset(nbl_lists->nbl_fep[th]);
2947 nbl_lists->nbl_fep[th] = nbl_tmp;
2951 fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
2953 nbl_lists->nbl_fep[th]->nri,
2954 nbl_lists->nbl_fep[th]->nrj);
2959 /* Returns the next ci to be processes by our thread */
2960 static gmx_bool next_ci(const nbnxn_grid_t &grid,
2961 int nth, int ci_block,
2962 int *ci_x, int *ci_y,
2968 if (*ci_b == ci_block)
2970 /* Jump to the next block assigned to this task */
2971 *ci += (nth - 1)*ci_block;
2980 while (*ci >= grid.cxy_ind[*ci_x*grid.numCells[YY] + *ci_y + 1])
2983 if (*ci_y == grid.numCells[YY])
2993 /* Returns the distance^2 for which we put cell pairs in the list
2994 * without checking atom pair distances. This is usually < rlist^2.
2996 static float boundingbox_only_distance2(const nbnxn_grid_t &iGrid,
2997 const nbnxn_grid_t &jGrid,
3001 /* If the distance between two sub-cell bounding boxes is less
3002 * than this distance, do not check the distance between
3003 * all particle pairs in the sub-cell, since then it is likely
3004 * that the box pair has atom pairs within the cut-off.
3005 * We use the nblist cut-off minus 0.5 times the average x/y diagonal
3006 * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
3007 * Using more than 0.5 gains at most 0.5%.
3008 * If forces are calculated more than twice, the performance gain
3009 * in the force calculation outweighs the cost of checking.
3010 * Note that with subcell lists, the atom-pair distance check
3011 * is only performed when only 1 out of 8 sub-cells in within range,
3012 * this is because the GPU is much faster than the cpu.
3017 bbx = 0.5*(iGrid.cellSize[XX] + jGrid.cellSize[XX]);
3018 bby = 0.5*(iGrid.cellSize[YY] + jGrid.cellSize[YY]);
3021 bbx /= c_gpuNumClusterPerCellX;
3022 bby /= c_gpuNumClusterPerCellY;
3025 rbb2 = std::max(0.0, rlist - 0.5*std::sqrt(bbx*bbx + bby*bby));
3031 return (float)((1+GMX_FLOAT_EPS)*rbb2);
3035 static int get_ci_block_size(const nbnxn_grid_t &iGrid,
3036 gmx_bool bDomDec, int nth)
3038 const int ci_block_enum = 5;
3039 const int ci_block_denom = 11;
3040 const int ci_block_min_atoms = 16;
3043 /* Here we decide how to distribute the blocks over the threads.
3044 * We use prime numbers to try to avoid that the grid size becomes
3045 * a multiple of the number of threads, which would lead to some
3046 * threads getting "inner" pairs and others getting boundary pairs,
3047 * which in turns will lead to load imbalance between threads.
3048 * Set the block size as 5/11/ntask times the average number of cells
3049 * in a y,z slab. This should ensure a quite uniform distribution
3050 * of the grid parts of the different thread along all three grid
3051 * zone boundaries with 3D domain decomposition. At the same time
3052 * the blocks will not become too small.
3054 ci_block = (iGrid.nc*ci_block_enum)/(ci_block_denom*iGrid.numCells[XX]*nth);
3056 /* Ensure the blocks are not too small: avoids cache invalidation */
3057 if (ci_block*iGrid.na_sc < ci_block_min_atoms)
3059 ci_block = (ci_block_min_atoms + iGrid.na_sc - 1)/iGrid.na_sc;
3062 /* Without domain decomposition
3063 * or with less than 3 blocks per task, divide in nth blocks.
3065 if (!bDomDec || nth*3*ci_block > iGrid.nc)
3067 ci_block = (iGrid.nc + nth - 1)/nth;
3070 if (ci_block > 1 && (nth - 1)*ci_block >= iGrid.nc)
3072 /* Some threads have no work. Although reducing the block size
3073 * does not decrease the block count on the first few threads,
3074 * with GPUs better mixing of "upper" cells that have more empty
3075 * clusters results in a somewhat lower max load over all threads.
3076 * Without GPUs the regime of so few atoms per thread is less
3077 * performance relevant, but with 8-wide SIMD the same reasoning
3078 * applies, since the pair list uses 4 i-atom "sub-clusters".
3086 /* Returns the number of bits to right-shift a cluster index to obtain
3087 * the corresponding force buffer flag index.
3089 static int getBufferFlagShift(int numAtomsPerCluster)
3091 int bufferFlagShift = 0;
3092 while ((numAtomsPerCluster << bufferFlagShift) < NBNXN_BUFFERFLAG_SIZE)
3097 return bufferFlagShift;
3100 static bool pairlistIsSimple(const NbnxnPairlistCpu gmx_unused &pairlist)
3105 static bool pairlistIsSimple(const NbnxnPairlistGpu gmx_unused &pairlist)
3110 static void makeClusterListWrapper(NbnxnPairlistCpu *nbl,
3111 const nbnxn_grid_t gmx_unused &iGrid,
3113 const nbnxn_grid_t &jGrid,
3114 const int firstCell,
3116 const bool excludeSubDiagonal,
3117 const nbnxn_atomdata_t *nbat,
3120 const Nbnxm::KernelType kernelType,
3121 int *numDistanceChecks)
3125 case Nbnxm::KernelType::Cpu4x4_PlainC:
3126 makeClusterListSimple(jGrid,
3127 nbl, ci, firstCell, lastCell,
3133 #ifdef GMX_NBNXN_SIMD_4XN
3134 case Nbnxm::KernelType::Cpu4xN_Simd_4xN:
3135 makeClusterListSimd4xn(jGrid,
3136 nbl, ci, firstCell, lastCell,
3143 #ifdef GMX_NBNXN_SIMD_2XNN
3144 case Nbnxm::KernelType::Cpu4xN_Simd_2xNN:
3145 makeClusterListSimd2xnn(jGrid,
3146 nbl, ci, firstCell, lastCell,
3154 GMX_ASSERT(false, "Unhandled kernel type");
3158 static void makeClusterListWrapper(NbnxnPairlistGpu *nbl,
3159 const nbnxn_grid_t &gmx_unused iGrid,
3161 const nbnxn_grid_t &jGrid,
3162 const int firstCell,
3164 const bool excludeSubDiagonal,
3165 const nbnxn_atomdata_t *nbat,
3168 Nbnxm::KernelType gmx_unused kernelType,
3169 int *numDistanceChecks)
3171 for (int cj = firstCell; cj <= lastCell; cj++)
3173 make_cluster_list_supersub(iGrid, jGrid,
3176 nbat->xstride, nbat->x().data(),
3182 static int getNumSimpleJClustersInList(const NbnxnPairlistCpu &nbl)
3184 return nbl.cj.size();
3187 static int getNumSimpleJClustersInList(const gmx_unused NbnxnPairlistGpu &nbl)
3192 static void incrementNumSimpleJClustersInList(NbnxnPairlistCpu *nbl,
3195 nbl->ncjInUse += nbl->cj.size() - ncj_old_j;
3198 static void incrementNumSimpleJClustersInList(NbnxnPairlistGpu gmx_unused *nbl,
3199 int gmx_unused ncj_old_j)
3203 static void checkListSizeConsistency(const NbnxnPairlistCpu &nbl,
3204 const bool haveFreeEnergy)
3206 GMX_RELEASE_ASSERT(static_cast<size_t>(nbl.ncjInUse) == nbl.cj.size() || haveFreeEnergy,
3207 "Without free-energy all cj pair-list entries should be in use. "
3208 "Note that subsequent code does not make use of the equality, "
3209 "this check is only here to catch bugs");
3212 static void checkListSizeConsistency(const NbnxnPairlistGpu gmx_unused &nbl,
3213 bool gmx_unused haveFreeEnergy)
3215 /* We currently can not check consistency here */
3218 /* Set the buffer flags for newly added entries in the list */
3219 static void setBufferFlags(const NbnxnPairlistCpu &nbl,
3220 const int ncj_old_j,
3221 const int gridj_flag_shift,
3222 gmx_bitmask_t *gridj_flag,
3225 if (gmx::ssize(nbl.cj) > ncj_old_j)
3227 int cbFirst = nbl.cj[ncj_old_j].cj >> gridj_flag_shift;
3228 int cbLast = nbl.cj.back().cj >> gridj_flag_shift;
3229 for (int cb = cbFirst; cb <= cbLast; cb++)
3231 bitmask_init_bit(&gridj_flag[cb], th);
3236 static void setBufferFlags(const NbnxnPairlistGpu gmx_unused &nbl,
3237 int gmx_unused ncj_old_j,
3238 int gmx_unused gridj_flag_shift,
3239 gmx_bitmask_t gmx_unused *gridj_flag,
3242 GMX_ASSERT(false, "This function should never be called");
3245 /* Generates the part of pair-list nbl assigned to our thread */
3246 template <typename T>
3247 static void nbnxn_make_pairlist_part(const nbnxn_search *nbs,
3248 const nbnxn_grid_t &iGrid,
3249 const nbnxn_grid_t &jGrid,
3250 nbnxn_search_work_t *work,
3251 const nbnxn_atomdata_t *nbat,
3252 const t_blocka &exclusions,
3254 const Nbnxm::KernelType kernelType,
3256 gmx_bool bFBufferFlag,
3259 float nsubpair_tot_est,
3266 real rlist2, rl_fep2 = 0;
3268 int ci_b, ci, ci_x, ci_y, ci_xy;
3270 real bx0, bx1, by0, by1, bz0, bz1;
3272 real d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
3273 int cxf, cxl, cyf, cyf_x, cyl;
3274 int numDistanceChecks;
3275 int gridi_flag_shift = 0, gridj_flag_shift = 0;
3276 gmx_bitmask_t *gridj_flag = nullptr;
3277 int ncj_old_i, ncj_old_j;
3279 nbs_cycle_start(&work->cc[enbsCCsearch]);
3281 if (jGrid.bSimple != pairlistIsSimple(*nbl) ||
3282 iGrid.bSimple != pairlistIsSimple(*nbl))
3284 gmx_incons("Grid incompatible with pair-list");
3288 GMX_ASSERT(nbl->na_ci == jGrid.na_c, "The cluster sizes in the list and grid should match");
3289 nbl->na_cj = Nbnxm::JClusterSizePerKernelType[kernelType];
3290 na_cj_2log = get_2log(nbl->na_cj);
3296 /* Determine conversion of clusters to flag blocks */
3297 gridi_flag_shift = getBufferFlagShift(nbl->na_ci);
3298 gridj_flag_shift = getBufferFlagShift(nbl->na_cj);
3300 gridj_flag = work->buffer_flags.flag;
3303 copy_mat(nbs->box, box);
3305 rlist2 = nbl->rlist*nbl->rlist;
3307 if (nbs->bFEP && !pairlistIsSimple(*nbl))
3309 /* Determine an atom-pair list cut-off distance for FEP atom pairs.
3310 * We should not simply use rlist, since then we would not have
3311 * the small, effective buffering of the NxN lists.
3312 * The buffer is on overestimate, but the resulting cost for pairs
3313 * beyond rlist is neglible compared to the FEP pairs within rlist.
3315 rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(iGrid, jGrid);
3319 fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
3321 rl_fep2 = rl_fep2*rl_fep2;
3324 rbb2 = boundingbox_only_distance2(iGrid, jGrid, nbl->rlist, pairlistIsSimple(*nbl));
3328 fprintf(debug, "nbl bounding box only distance %f\n", std::sqrt(rbb2));
3331 const bool isIntraGridList = (&iGrid == &jGrid);
3333 /* Set the shift range */
3334 for (int d = 0; d < DIM; d++)
3336 /* Check if we need periodicity shifts.
3337 * Without PBC or with domain decomposition we don't need them.
3339 if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
3345 const real listRangeCellToCell = listRangeForGridCellToGridCell(rlist, iGrid, jGrid);
3347 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < listRangeCellToCell)
3357 const bool bSimple = pairlistIsSimple(*nbl);
3358 gmx::ArrayRef<const nbnxn_bb_t> bb_i;
3360 gmx::ArrayRef<const float> pbb_i;
3370 /* We use the normal bounding box format for both grid types */
3373 gmx::ArrayRef<const float> bbcz_i = iGrid.bbcz;
3374 gmx::ArrayRef<const int> flags_i = iGrid.flags;
3375 gmx::ArrayRef<const float> bbcz_j = jGrid.bbcz;
3376 int cell0_i = iGrid.cell0;
3380 fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
3381 iGrid.nc, iGrid.nc/static_cast<double>(iGrid.numCells[XX]*iGrid.numCells[YY]), ci_block);
3384 numDistanceChecks = 0;
3386 const real listRangeBBToJCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGrid));
3388 /* Initially ci_b and ci to 1 before where we want them to start,
3389 * as they will both be incremented in next_ci.
3392 ci = th*ci_block - 1;
3395 while (next_ci(iGrid, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
3397 if (bSimple && flags_i[ci] == 0)
3402 ncj_old_i = getNumSimpleJClustersInList(*nbl);
3405 if (!isIntraGridList && shp[XX] == 0)
3409 bx1 = bb_i[ci].upper[BB_X];
3413 bx1 = iGrid.c0[XX] + (ci_x+1)*iGrid.cellSize[XX];
3415 if (bx1 < jGrid.c0[XX])
3417 d2cx = gmx::square(jGrid.c0[XX] - bx1);
3419 if (d2cx >= listRangeBBToJCell2)
3426 ci_xy = ci_x*iGrid.numCells[YY] + ci_y;
3428 /* Loop over shift vectors in three dimensions */
3429 for (int tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
3431 const real shz = tz*box[ZZ][ZZ];
3433 bz0 = bbcz_i[ci*NNBSBB_D ] + shz;
3434 bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
3442 d2z = gmx::square(bz1);
3446 d2z = gmx::square(bz0 - box[ZZ][ZZ]);
3449 d2z_cx = d2z + d2cx;
3451 if (d2z_cx >= rlist2)
3456 bz1_frac = bz1/(iGrid.cxy_ind[ci_xy+1] - iGrid.cxy_ind[ci_xy]);
3461 /* The check with bz1_frac close to or larger than 1 comes later */
3463 for (int ty = -shp[YY]; ty <= shp[YY]; ty++)
3465 const real shy = ty*box[YY][YY] + tz*box[ZZ][YY];
3469 by0 = bb_i[ci].lower[BB_Y] + shy;
3470 by1 = bb_i[ci].upper[BB_Y] + shy;
3474 by0 = iGrid.c0[YY] + (ci_y )*iGrid.cellSize[YY] + shy;
3475 by1 = iGrid.c0[YY] + (ci_y+1)*iGrid.cellSize[YY] + shy;
3478 get_cell_range<YY>(by0, by1,
3489 if (by1 < jGrid.c0[YY])
3491 d2z_cy += gmx::square(jGrid.c0[YY] - by1);
3493 else if (by0 > jGrid.c1[YY])
3495 d2z_cy += gmx::square(by0 - jGrid.c1[YY]);
3498 for (int tx = -shp[XX]; tx <= shp[XX]; tx++)
3500 const int shift = XYZ2IS(tx, ty, tz);
3502 const bool excludeSubDiagonal = (isIntraGridList && shift == CENTRAL);
3504 if (c_pbcShiftBackward && isIntraGridList && shift > CENTRAL)
3509 const real shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
3513 bx0 = bb_i[ci].lower[BB_X] + shx;
3514 bx1 = bb_i[ci].upper[BB_X] + shx;
3518 bx0 = iGrid.c0[XX] + (ci_x )*iGrid.cellSize[XX] + shx;
3519 bx1 = iGrid.c0[XX] + (ci_x+1)*iGrid.cellSize[XX] + shx;
3522 get_cell_range<XX>(bx0, bx1,
3532 addNewIEntry(nbl, cell0_i+ci, shift, flags_i[ci]);
3534 if ((!c_pbcShiftBackward || excludeSubDiagonal) &&
3537 /* Leave the pairs with i > j.
3538 * x is the major index, so skip half of it.
3543 set_icell_bb(iGrid, ci, shx, shy, shz,
3546 icell_set_x(cell0_i+ci, shx, shy, shz,
3547 nbat->xstride, nbat->x().data(),
3551 for (int cx = cxf; cx <= cxl; cx++)
3554 if (jGrid.c0[XX] + cx*jGrid.cellSize[XX] > bx1)
3556 d2zx += gmx::square(jGrid.c0[XX] + cx*jGrid.cellSize[XX] - bx1);
3558 else if (jGrid.c0[XX] + (cx+1)*jGrid.cellSize[XX] < bx0)
3560 d2zx += gmx::square(jGrid.c0[XX] + (cx+1)*jGrid.cellSize[XX] - bx0);
3563 if (isIntraGridList &&
3565 (!c_pbcShiftBackward || shift == CENTRAL) &&
3568 /* Leave the pairs with i > j.
3569 * Skip half of y when i and j have the same x.
3578 for (int cy = cyf_x; cy <= cyl; cy++)
3580 const int columnStart = jGrid.cxy_ind[cx*jGrid.numCells[YY] + cy];
3581 const int columnEnd = jGrid.cxy_ind[cx*jGrid.numCells[YY] + cy + 1];
3584 if (jGrid.c0[YY] + cy*jGrid.cellSize[YY] > by1)
3586 d2zxy += gmx::square(jGrid.c0[YY] + cy*jGrid.cellSize[YY] - by1);
3588 else if (jGrid.c0[YY] + (cy+1)*jGrid.cellSize[YY] < by0)
3590 d2zxy += gmx::square(jGrid.c0[YY] + (cy+1)*jGrid.cellSize[YY] - by0);
3592 if (columnStart < columnEnd && d2zxy < listRangeBBToJCell2)
3594 /* To improve efficiency in the common case
3595 * of a homogeneous particle distribution,
3596 * we estimate the index of the middle cell
3597 * in range (midCell). We search down and up
3598 * starting from this index.
3600 * Note that the bbcz_j array contains bounds
3601 * for i-clusters, thus for clusters of 4 atoms.
3602 * For the common case where the j-cluster size
3603 * is 8, we could step with a stride of 2,
3604 * but we do not do this because it would
3605 * complicate this code even more.
3607 int midCell = columnStart + static_cast<int>(bz1_frac*(columnEnd - columnStart));
3608 if (midCell >= columnEnd)
3610 midCell = columnEnd - 1;
3615 /* Find the lowest cell that can possibly
3617 * Check if we hit the bottom of the grid,
3618 * if the j-cell is below the i-cell and if so,
3619 * if it is within range.
3621 int downTestCell = midCell;
3622 while (downTestCell >= columnStart &&
3623 (bbcz_j[downTestCell*NNBSBB_D + 1] >= bz0 ||
3624 d2xy + gmx::square(bbcz_j[downTestCell*NNBSBB_D + 1] - bz0) < rlist2))
3628 int firstCell = downTestCell + 1;
3630 /* Find the highest cell that can possibly
3632 * Check if we hit the top of the grid,
3633 * if the j-cell is above the i-cell and if so,
3634 * if it is within range.
3636 int upTestCell = midCell + 1;
3637 while (upTestCell < columnEnd &&
3638 (bbcz_j[upTestCell*NNBSBB_D] <= bz1 ||
3639 d2xy + gmx::square(bbcz_j[upTestCell*NNBSBB_D] - bz1) < rlist2))
3643 int lastCell = upTestCell - 1;
3645 #define NBNXN_REFCODE 0
3648 /* Simple reference code, for debugging,
3649 * overrides the more complex code above.
3651 firstCell = columnEnd;
3653 for (int k = columnStart; k < columnEnd; k++)
3655 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D + 1] - bz0) < rlist2 &&
3660 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D] - bz1) < rlist2 &&
3669 if (isIntraGridList)
3671 /* We want each atom/cell pair only once,
3672 * only use cj >= ci.
3674 if (!c_pbcShiftBackward || shift == CENTRAL)
3676 firstCell = std::max(firstCell, ci);
3680 if (firstCell <= lastCell)
3682 GMX_ASSERT(firstCell >= columnStart && lastCell < columnEnd, "The range should reside within the current grid column");
3684 /* For f buffer flags with simple lists */
3685 ncj_old_j = getNumSimpleJClustersInList(*nbl);
3687 makeClusterListWrapper(nbl,
3689 jGrid, firstCell, lastCell,
3694 &numDistanceChecks);
3698 setBufferFlags(*nbl, ncj_old_j, gridj_flag_shift,
3702 incrementNumSimpleJClustersInList(nbl, ncj_old_j);
3708 /* Set the exclusions for this ci list */
3709 setExclusionsForIEntry(nbs,
3713 *getOpenIEntry(nbl),
3718 make_fep_list(nbs, nbat, nbl,
3723 iGrid, jGrid, nbl_fep);
3726 /* Close this ci list */
3729 progBal, nsubpair_tot_est,
3735 if (bFBufferFlag && getNumSimpleJClustersInList(*nbl) > ncj_old_i)
3737 bitmask_init_bit(&(work->buffer_flags.flag[(iGrid.cell0+ci) >> gridi_flag_shift]), th);
3741 work->ndistc = numDistanceChecks;
3743 nbs_cycle_stop(&work->cc[enbsCCsearch]);
3745 checkListSizeConsistency(*nbl, nbs->bFEP);
3749 fprintf(debug, "number of distance checks %d\n", numDistanceChecks);
3751 print_nblist_statistics(debug, nbl, nbs, rlist);
3755 fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
3760 static void reduce_buffer_flags(const nbnxn_search *nbs,
3762 const nbnxn_buffer_flags_t *dest)
3764 for (int s = 0; s < nsrc; s++)
3766 gmx_bitmask_t * flag = nbs->work[s].buffer_flags.flag;
3768 for (int b = 0; b < dest->nflag; b++)
3770 bitmask_union(&(dest->flag[b]), flag[b]);
3775 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
3777 int nelem, nkeep, ncopy, nred, out;
3778 gmx_bitmask_t mask_0;
3784 bitmask_init_bit(&mask_0, 0);
3785 for (int b = 0; b < flags->nflag; b++)
3787 if (bitmask_is_equal(flags->flag[b], mask_0))
3789 /* Only flag 0 is set, no copy of reduction required */
3793 else if (!bitmask_is_zero(flags->flag[b]))
3796 for (out = 0; out < nout; out++)
3798 if (bitmask_is_set(flags->flag[b], out))
3815 fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
3817 nelem/static_cast<double>(flags->nflag),
3818 nkeep/static_cast<double>(flags->nflag),
3819 ncopy/static_cast<double>(flags->nflag),
3820 nred/static_cast<double>(flags->nflag));
3823 /* Copies the list entries from src to dest when cjStart <= *cjGlobal < cjEnd.
3824 * *cjGlobal is updated with the cj count in src.
3825 * When setFlags==true, flag bit t is set in flag for all i and j clusters.
3827 template<bool setFlags>
3828 static void copySelectedListRange(const nbnxn_ci_t * gmx_restrict srcCi,
3829 const NbnxnPairlistCpu * gmx_restrict src,
3830 NbnxnPairlistCpu * gmx_restrict dest,
3831 gmx_bitmask_t *flag,
3832 int iFlagShift, int jFlagShift, int t)
3834 const int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3836 dest->ci.push_back(*srcCi);
3837 dest->ci.back().cj_ind_start = dest->cj.size();
3838 dest->ci.back().cj_ind_end = dest->cj.size() + ncj;
3842 bitmask_init_bit(&flag[srcCi->ci >> iFlagShift], t);
3845 for (int j = srcCi->cj_ind_start; j < srcCi->cj_ind_end; j++)
3847 dest->cj.push_back(src->cj[j]);
3851 /* NOTE: This is relatively expensive, since this
3852 * operation is done for all elements in the list,
3853 * whereas at list generation this is done only
3854 * once for each flag entry.
3856 bitmask_init_bit(&flag[src->cj[j].cj >> jFlagShift], t);
3861 /* This routine re-balances the pairlists such that all are nearly equally
3862 * sized. Only whole i-entries are moved between lists. These are moved
3863 * between the ends of the lists, such that the buffer reduction cost should
3864 * not change significantly.
3865 * Note that all original reduction flags are currently kept. This can lead
3866 * to reduction of parts of the force buffer that could be avoided. But since
3867 * the original lists are quite balanced, this will only give minor overhead.
3869 static void rebalanceSimpleLists(int numLists,
3870 NbnxnPairlistCpu * const * const srcSet,
3871 NbnxnPairlistCpu **destSet,
3872 gmx::ArrayRef<nbnxn_search_work_t> searchWork)
3875 for (int s = 0; s < numLists; s++)
3877 ncjTotal += srcSet[s]->ncjInUse;
3879 int ncjTarget = (ncjTotal + numLists - 1)/numLists;
3881 #pragma omp parallel num_threads(numLists)
3883 int t = gmx_omp_get_thread_num();
3885 int cjStart = ncjTarget* t;
3886 int cjEnd = ncjTarget*(t + 1);
3888 /* The destination pair-list for task/thread t */
3889 NbnxnPairlistCpu *dest = destSet[t];
3891 clear_pairlist(dest);
3892 dest->na_cj = srcSet[0]->na_cj;
3894 /* Note that the flags in the work struct (still) contain flags
3895 * for all entries that are present in srcSet->nbl[t].
3897 gmx_bitmask_t *flag = searchWork[t].buffer_flags.flag;
3899 int iFlagShift = getBufferFlagShift(dest->na_ci);
3900 int jFlagShift = getBufferFlagShift(dest->na_cj);
3903 for (int s = 0; s < numLists && cjGlobal < cjEnd; s++)
3905 const NbnxnPairlistCpu *src = srcSet[s];
3907 if (cjGlobal + src->ncjInUse > cjStart)
3909 for (gmx::index i = 0; i < gmx::ssize(src->ci) && cjGlobal < cjEnd; i++)
3911 const nbnxn_ci_t *srcCi = &src->ci[i];
3912 int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3913 if (cjGlobal >= cjStart)
3915 /* If the source list is not our own, we need to set
3916 * extra flags (the template bool parameter).
3920 copySelectedListRange
3923 flag, iFlagShift, jFlagShift, t);
3927 copySelectedListRange
3930 dest, flag, iFlagShift, jFlagShift, t);
3938 cjGlobal += src->ncjInUse;
3942 dest->ncjInUse = dest->cj.size();
3946 int ncjTotalNew = 0;
3947 for (int s = 0; s < numLists; s++)
3949 ncjTotalNew += destSet[s]->ncjInUse;
3951 GMX_RELEASE_ASSERT(ncjTotalNew == ncjTotal, "The total size of the lists before and after rebalancing should match");
3955 /* Returns if the pairlists are so imbalanced that it is worth rebalancing. */
3956 static bool checkRebalanceSimpleLists(const nbnxn_pairlist_set_t *listSet)
3958 int numLists = listSet->nnbl;
3961 for (int s = 0; s < numLists; s++)
3963 ncjMax = std::max(ncjMax, listSet->nbl[s]->ncjInUse);
3964 ncjTotal += listSet->nbl[s]->ncjInUse;
3968 fprintf(debug, "Pair-list ncjMax %d ncjTotal %d\n", ncjMax, ncjTotal);
3970 /* The rebalancing adds 3% extra time to the search. Heuristically we
3971 * determined that under common conditions the non-bonded kernel balance
3972 * improvement will outweigh this when the imbalance is more than 3%.
3973 * But this will, obviously, depend on search vs kernel time and nstlist.
3975 const real rebalanceTolerance = 1.03;
3977 return numLists*ncjMax > ncjTotal*rebalanceTolerance;
3980 /* Perform a count (linear) sort to sort the smaller lists to the end.
3981 * This avoids load imbalance on the GPU, as large lists will be
3982 * scheduled and executed first and the smaller lists later.
3983 * Load balancing between multi-processors only happens at the end
3984 * and there smaller lists lead to more effective load balancing.
3985 * The sorting is done on the cj4 count, not on the actual pair counts.
3986 * Not only does this make the sort faster, but it also results in
3987 * better load balancing than using a list sorted on exact load.
3988 * This function swaps the pointer in the pair list to avoid a copy operation.
3990 static void sort_sci(NbnxnPairlistGpu *nbl)
3992 if (nbl->cj4.size() <= nbl->sci.size())
3994 /* nsci = 0 or all sci have size 1, sorting won't change the order */
3998 NbnxnPairlistGpuWork &work = *nbl->work;
4000 /* We will distinguish differences up to double the average */
4001 const int m = (2*nbl->cj4.size())/nbl->sci.size();
4003 /* Resize work.sci_sort so we can sort into it */
4004 work.sci_sort.resize(nbl->sci.size());
4006 std::vector<int> &sort = work.sortBuffer;
4007 /* Set up m + 1 entries in sort, initialized at 0 */
4009 sort.resize(m + 1, 0);
4010 /* Count the entries of each size */
4011 for (const nbnxn_sci_t &sci : nbl->sci)
4013 int i = std::min(m, sci.numJClusterGroups());
4016 /* Calculate the offset for each count */
4019 for (int i = m - 1; i >= 0; i--)
4022 sort[i] = sort[i + 1] + s0;
4026 /* Sort entries directly into place */
4027 gmx::ArrayRef<nbnxn_sci_t> sci_sort = work.sci_sort;
4028 for (const nbnxn_sci_t &sci : nbl->sci)
4030 int i = std::min(m, sci.numJClusterGroups());
4031 sci_sort[sort[i]++] = sci;
4034 /* Swap the sci pointers so we use the new, sorted list */
4035 std::swap(nbl->sci, work.sci_sort);
4038 void nbnxn_make_pairlist(nonbonded_verlet_t *nbv,
4039 const InteractionLocality iLocality,
4040 nbnxn_pairlist_set_t *nbl_list,
4041 const t_blocka *excl,
4045 nbnxn_search *nbs = nbv->nbs.get();
4046 nbnxn_atomdata_t *nbat = nbv->nbat;
4047 const real rlist = nbv->listParams->rlistOuter;
4049 int nsubpair_target;
4050 float nsubpair_tot_est;
4053 gmx_bool CombineNBLists;
4055 int np_tot, np_noq, np_hlj, nap;
4057 nnbl = nbl_list->nnbl;
4058 CombineNBLists = nbl_list->bCombined;
4062 fprintf(debug, "ns making %d nblists\n", nnbl);
4065 nbat->bUseBufferFlags = (nbat->out.size() > 1);
4066 /* We should re-init the flags before making the first list */
4067 if (nbat->bUseBufferFlags && iLocality == InteractionLocality::Local)
4069 init_buffer_flags(&nbat->buffer_flags, nbat->numAtoms());
4073 if (iLocality == InteractionLocality::Local)
4075 /* Only zone (grid) 0 vs 0 */
4080 nzi = nbs->zones->nizone;
4083 if (!nbl_list->bSimple && nbv->min_ci_balanced > 0)
4085 get_nsubpair_target(nbs, iLocality, rlist, nbv->min_ci_balanced,
4086 &nsubpair_target, &nsubpair_tot_est);
4090 nsubpair_target = 0;
4091 nsubpair_tot_est = 0;
4094 /* Clear all pair-lists */
4095 for (int th = 0; th < nnbl; th++)
4097 if (nbl_list->bSimple)
4099 clear_pairlist(nbl_list->nbl[th]);
4103 clear_pairlist(nbl_list->nblGpu[th]);
4108 clear_pairlist_fep(nbl_list->nbl_fep[th]);
4112 for (int zi = 0; zi < nzi; zi++)
4114 const nbnxn_grid_t &iGrid = nbs->grid[zi];
4118 if (iLocality == InteractionLocality::Local)
4125 zj0 = nbs->zones->izone[zi].j0;
4126 zj1 = nbs->zones->izone[zi].j1;
4132 for (int zj = zj0; zj < zj1; zj++)
4134 const nbnxn_grid_t &jGrid = nbs->grid[zj];
4138 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
4141 nbs_cycle_start(&nbs->cc[enbsCCsearch]);
4143 ci_block = get_ci_block_size(iGrid, nbs->DomDec, nnbl);
4145 /* With GPU: generate progressively smaller lists for
4146 * load balancing for local only or non-local with 2 zones.
4148 progBal = (iLocality == InteractionLocality::Local || nbs->zones->n <= 2);
4150 #pragma omp parallel for num_threads(nnbl) schedule(static)
4151 for (int th = 0; th < nnbl; th++)
4155 /* Re-init the thread-local work flag data before making
4156 * the first list (not an elegant conditional).
4158 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0)))
4160 init_buffer_flags(&nbs->work[th].buffer_flags, nbat->numAtoms());
4163 if (CombineNBLists && th > 0)
4165 GMX_ASSERT(!nbl_list->bSimple, "Can only combine GPU lists");
4167 clear_pairlist(nbl_list->nblGpu[th]);
4170 /* Divide the i super cell equally over the nblists */
4171 if (nbl_list->bSimple)
4173 nbnxn_make_pairlist_part(nbs, iGrid, jGrid,
4174 &nbs->work[th], nbat, *excl,
4176 nbv->kernelSetup().kernelType,
4178 nbat->bUseBufferFlags,
4180 progBal, nsubpair_tot_est,
4183 nbl_list->nbl_fep[th]);
4187 nbnxn_make_pairlist_part(nbs, iGrid, jGrid,
4188 &nbs->work[th], nbat, *excl,
4190 nbv->kernelSetup().kernelType,
4192 nbat->bUseBufferFlags,
4194 progBal, nsubpair_tot_est,
4196 nbl_list->nblGpu[th],
4197 nbl_list->nbl_fep[th]);
4200 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4202 nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
4207 for (int th = 0; th < nnbl; th++)
4209 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
4211 if (nbl_list->bSimple)
4213 NbnxnPairlistCpu *nbl = nbl_list->nbl[th];
4214 np_tot += nbl->cj.size();
4215 np_noq += nbl->work->ncj_noq;
4216 np_hlj += nbl->work->ncj_hlj;
4220 NbnxnPairlistGpu *nbl = nbl_list->nblGpu[th];
4221 /* This count ignores potential subsequent pair pruning */
4222 np_tot += nbl->nci_tot;
4225 if (nbl_list->bSimple)
4227 nap = nbl_list->nbl[0]->na_ci*nbl_list->nbl[0]->na_cj;
4231 nap = gmx::square(nbl_list->nblGpu[0]->na_ci);
4233 nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
4234 nbl_list->natpair_lj = np_noq*nap;
4235 nbl_list->natpair_q = np_hlj*nap/2;
4237 if (CombineNBLists && nnbl > 1)
4239 GMX_ASSERT(!nbl_list->bSimple, "Can only combine GPU lists");
4240 NbnxnPairlistGpu **nbl = nbl_list->nblGpu;
4242 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
4244 combine_nblists(nnbl-1, nbl+1, nbl[0]);
4246 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
4251 if (nbl_list->bSimple)
4253 if (nnbl > 1 && checkRebalanceSimpleLists(nbl_list))
4255 rebalanceSimpleLists(nbl_list->nnbl, nbl_list->nbl, nbl_list->nbl_work, nbs->work);
4257 /* Swap the pointer of the sets of pair lists */
4258 NbnxnPairlistCpu **tmp = nbl_list->nbl;
4259 nbl_list->nbl = nbl_list->nbl_work;
4260 nbl_list->nbl_work = tmp;
4265 /* Sort the entries on size, large ones first */
4266 if (CombineNBLists || nnbl == 1)
4268 sort_sci(nbl_list->nblGpu[0]);
4272 #pragma omp parallel for num_threads(nnbl) schedule(static)
4273 for (int th = 0; th < nnbl; th++)
4277 sort_sci(nbl_list->nblGpu[th]);
4279 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4284 if (nbat->bUseBufferFlags)
4286 reduce_buffer_flags(nbs, nbl_list->nnbl, &nbat->buffer_flags);
4291 /* Balance the free-energy lists over all the threads */
4292 balance_fep_lists(nbs, nbl_list);
4295 if (nbl_list->bSimple)
4297 /* This is a fresh list, so not pruned, stored using ci.
4298 * ciOuter is invalid at this point.
4300 GMX_ASSERT(nbl_list->nbl[0]->ciOuter.empty(), "ciOuter is invalid so it should be empty");
4303 nbl_list->outerListCreationStep = step;
4305 /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
4306 if (iLocality == InteractionLocality::Local)
4308 nbs->search_count++;
4310 if (nbs->print_cycles &&
4311 (!nbs->DomDec || iLocality == InteractionLocality::NonLocal) &&
4312 nbs->search_count % 100 == 0)
4314 nbs_cycle_print(stderr, nbs);
4317 /* If we have more than one list, they either got rebalancing (CPU)
4318 * or combined (GPU), so we should dump the final result to debug.
4320 if (debug && nbl_list->nnbl > 1)
4322 if (nbl_list->bSimple)
4324 for (int t = 0; t < nbl_list->nnbl; t++)
4326 print_nblist_statistics(debug, nbl_list->nbl[t], nbs, rlist);
4331 print_nblist_statistics(debug, nbl_list->nblGpu[0], nbs, rlist);
4339 if (nbl_list->bSimple)
4341 for (int t = 0; t < nbl_list->nnbl; t++)
4343 print_nblist_ci_cj(debug, nbl_list->nbl[t]);
4348 print_nblist_sci_cj(debug, nbl_list->nblGpu[0]);
4352 if (nbat->bUseBufferFlags)
4354 print_reduction_cost(&nbat->buffer_flags, nbl_list->nnbl);
4358 if (nbv->listParams->useDynamicPruning && !nbv->useGpu())
4360 nbnxnPrepareListForDynamicPruning(nbl_list);
4365 /* Launch the transfer of the pairlist to the GPU.
4367 * NOTE: The launch overhead is currently not timed separately
4369 Nbnxm::gpu_init_pairlist(nbv->gpu_nbv,
4370 nbl_list->nblGpu[0],
4375 void nbnxnPrepareListForDynamicPruning(nbnxn_pairlist_set_t *listSet)
4377 GMX_RELEASE_ASSERT(listSet->bSimple, "Should only be called for simple lists");
4379 /* TODO: Restructure the lists so we have actual outer and inner
4380 * list objects so we can set a single pointer instead of
4381 * swapping several pointers.
4384 for (int i = 0; i < listSet->nnbl; i++)
4386 NbnxnPairlistCpu &list = *listSet->nbl[i];
4388 /* The search produced a list in ci/cj.
4389 * Swap the list pointers so we get the outer list is ciOuter,cjOuter
4390 * and we can prune that to get an inner list in ci/cj.
4392 GMX_RELEASE_ASSERT(list.ciOuter.empty() && list.cjOuter.empty(),
4393 "The outer lists should be empty before preparation");
4395 std::swap(list.ci, list.ciOuter);
4396 std::swap(list.cj, list.cjOuter);