Use ArrayRef in gmx_pme_send_parameters
[alexxy/gromacs.git] / src / gromacs / ewald / pme_pp.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7  * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 /*! \internal \file
39  *
40  * \brief This file contains function definitions necessary for
41  * managing the offload of long-ranged PME work to separate MPI rank,
42  * for computing energies and forces (Coulomb and LJ).
43  *
44  * \author Berk Hess <hess@kth.se>
45  * \ingroup module_ewald
46  */
47
48 #include "gmxpre.h"
49
50 #include "pme_pp.h"
51
52 #include "config.h"
53
54 #include <cstdio>
55 #include <cstring>
56
57 #include "gromacs/domdec/domdec.h"
58 #include "gromacs/domdec/domdec_struct.h"
59 #include "gromacs/ewald/pme.h"
60 #include "gromacs/ewald/pme_pp_comm_gpu.h"
61 #include "gromacs/gmxlib/network.h"
62 #include "gromacs/math/vec.h"
63 #include "gromacs/mdlib/gmx_omp_nthreads.h"
64 #include "gromacs/mdtypes/commrec.h"
65 #include "gromacs/mdtypes/forceoutput.h"
66 #include "gromacs/mdtypes/forcerec.h"
67 #include "gromacs/mdtypes/interaction_const.h"
68 #include "gromacs/mdtypes/md_enums.h"
69 #include "gromacs/mdtypes/state_propagator_data_gpu.h"
70 #include "gromacs/nbnxm/nbnxm.h"
71 #include "gromacs/timing/wallcycle.h"
72 #include "gromacs/utility/fatalerror.h"
73 #include "gromacs/utility/gmxmpi.h"
74 #include "gromacs/utility/smalloc.h"
75
76 #include "pme_pp_communication.h"
77
78 /*! \brief Block to wait for communication to PME ranks to complete
79  *
80  * This should be faster with a real non-blocking MPI implementation
81  */
82 static constexpr bool c_useDelayedWait = false;
83
84 /*! \brief Wait for the pending data send requests to PME ranks to complete */
85 static void gmx_pme_send_coeffs_coords_wait(gmx_domdec_t* dd)
86 {
87     if (dd->nreq_pme)
88     {
89 #if GMX_MPI
90         MPI_Waitall(dd->nreq_pme, dd->req_pme, MPI_STATUSES_IGNORE);
91 #endif
92         dd->nreq_pme = 0;
93     }
94 }
95
96 /*! \brief Send data to PME ranks */
97 static void gmx_pme_send_coeffs_coords(t_forcerec*         fr,
98                                        const t_commrec*    cr,
99                                        unsigned int        flags,
100                                        gmx::ArrayRef<real> chargeA,
101                                        gmx::ArrayRef<real> chargeB,
102                                        gmx::ArrayRef<real> c6A,
103                                        gmx::ArrayRef<real> c6B,
104                                        gmx::ArrayRef<real> sigmaA,
105                                        gmx::ArrayRef<real> sigmaB,
106                                        const matrix        box,
107                                        const rvec gmx_unused* x,
108                                        real                   lambda_q,
109                                        real                   lambda_lj,
110                                        int                    maxshift_x,
111                                        int                    maxshift_y,
112                                        int64_t                step,
113                                        bool                   useGpuPmePpComms,
114                                        bool                   reinitGpuPmePpComms,
115                                        bool                   sendCoordinatesFromGpu,
116                                        GpuEventSynchronizer*  coordinatesReadyOnDeviceEvent)
117 {
118     gmx_domdec_t*         dd;
119     gmx_pme_comm_n_box_t* cnb;
120     int                   n;
121
122     dd = cr->dd;
123     n  = dd_numHomeAtoms(*dd);
124
125     if (debug)
126     {
127         fprintf(debug,
128                 "PP rank %d sending to PME rank %d: %d%s%s%s%s\n",
129                 cr->sim_nodeid,
130                 dd->pme_nodeid,
131                 n,
132                 (flags & PP_PME_CHARGE) ? " charges" : "",
133                 (flags & PP_PME_SQRTC6) ? " sqrtC6" : "",
134                 (flags & PP_PME_SIGMA) ? " sigma" : "",
135                 (flags & PP_PME_COORD) ? " coordinates" : "");
136     }
137
138     if (useGpuPmePpComms)
139     {
140         flags |= PP_PME_GPUCOMMS;
141     }
142
143     if (c_useDelayedWait)
144     {
145         /* We can not use cnb until pending communication has finished */
146         gmx_pme_send_coeffs_coords_wait(dd);
147     }
148
149     if (dd->pme_receive_vir_ener)
150     {
151         /* Peer PP node: communicate all data */
152         if (dd->cnb == nullptr)
153         {
154             snew(dd->cnb, 1);
155         }
156         cnb = dd->cnb;
157
158         cnb->flags      = flags;
159         cnb->natoms     = n;
160         cnb->maxshift_x = maxshift_x;
161         cnb->maxshift_y = maxshift_y;
162         cnb->lambda_q   = lambda_q;
163         cnb->lambda_lj  = lambda_lj;
164         cnb->step       = step;
165         if (flags & PP_PME_COORD)
166         {
167             copy_mat(box, cnb->box);
168         }
169 #if GMX_MPI
170         MPI_Isend(cnb,
171                   sizeof(*cnb),
172                   MPI_BYTE,
173                   dd->pme_nodeid,
174                   eCommType_CNB,
175                   cr->mpi_comm_mysim,
176                   &dd->req_pme[dd->nreq_pme++]);
177 #endif
178     }
179     else if (flags & (PP_PME_CHARGE | PP_PME_SQRTC6 | PP_PME_SIGMA))
180     {
181 #if GMX_MPI
182         /* Communicate only the number of atoms */
183         MPI_Isend(&n,
184                   sizeof(n),
185                   MPI_BYTE,
186                   dd->pme_nodeid,
187                   eCommType_CNB,
188                   cr->mpi_comm_mysim,
189                   &dd->req_pme[dd->nreq_pme++]);
190 #endif
191     }
192
193 #if GMX_MPI
194     if (n > 0)
195     {
196         if (flags & PP_PME_CHARGE)
197         {
198             MPI_Isend(chargeA.data(),
199                       n * sizeof(real),
200                       MPI_BYTE,
201                       dd->pme_nodeid,
202                       eCommType_ChargeA,
203                       cr->mpi_comm_mysim,
204                       &dd->req_pme[dd->nreq_pme++]);
205         }
206         if (flags & PP_PME_CHARGEB)
207         {
208             MPI_Isend(chargeB.data(),
209                       n * sizeof(real),
210                       MPI_BYTE,
211                       dd->pme_nodeid,
212                       eCommType_ChargeB,
213                       cr->mpi_comm_mysim,
214                       &dd->req_pme[dd->nreq_pme++]);
215         }
216         if (flags & PP_PME_SQRTC6)
217         {
218             MPI_Isend(c6A.data(),
219                       n * sizeof(real),
220                       MPI_BYTE,
221                       dd->pme_nodeid,
222                       eCommType_SQRTC6A,
223                       cr->mpi_comm_mysim,
224                       &dd->req_pme[dd->nreq_pme++]);
225         }
226         if (flags & PP_PME_SQRTC6B)
227         {
228             MPI_Isend(c6B.data(),
229                       n * sizeof(real),
230                       MPI_BYTE,
231                       dd->pme_nodeid,
232                       eCommType_SQRTC6B,
233                       cr->mpi_comm_mysim,
234                       &dd->req_pme[dd->nreq_pme++]);
235         }
236         if (flags & PP_PME_SIGMA)
237         {
238             MPI_Isend(sigmaA.data(),
239                       n * sizeof(real),
240                       MPI_BYTE,
241                       dd->pme_nodeid,
242                       eCommType_SigmaA,
243                       cr->mpi_comm_mysim,
244                       &dd->req_pme[dd->nreq_pme++]);
245         }
246         if (flags & PP_PME_SIGMAB)
247         {
248             MPI_Isend(sigmaB.data(),
249                       n * sizeof(real),
250                       MPI_BYTE,
251                       dd->pme_nodeid,
252                       eCommType_SigmaB,
253                       cr->mpi_comm_mysim,
254                       &dd->req_pme[dd->nreq_pme++]);
255         }
256         if (flags & PP_PME_COORD)
257         {
258             if (reinitGpuPmePpComms)
259             {
260                 fr->pmePpCommGpu->reinit(n);
261             }
262
263
264             /* MPI_Isend does not accept a const buffer pointer */
265             real* xRealPtr = const_cast<real*>(x[0]);
266             if (useGpuPmePpComms && (fr != nullptr))
267             {
268                 void* sendPtr = sendCoordinatesFromGpu
269                                         ? static_cast<void*>(fr->stateGpu->getCoordinates())
270                                         : static_cast<void*>(xRealPtr);
271                 fr->pmePpCommGpu->sendCoordinatesToPmeCudaDirect(
272                         sendPtr, n, sendCoordinatesFromGpu, coordinatesReadyOnDeviceEvent);
273             }
274             else
275             {
276                 MPI_Isend(xRealPtr,
277                           n * sizeof(rvec),
278                           MPI_BYTE,
279                           dd->pme_nodeid,
280                           eCommType_COORD,
281                           cr->mpi_comm_mysim,
282                           &dd->req_pme[dd->nreq_pme++]);
283             }
284         }
285     }
286 #else
287     GMX_UNUSED_VALUE(fr);
288     GMX_UNUSED_VALUE(reinitGpuPmePpComms);
289     GMX_UNUSED_VALUE(sendCoordinatesFromGpu);
290     GMX_UNUSED_VALUE(coordinatesReadyOnDeviceEvent);
291 #endif
292     if (!c_useDelayedWait)
293     {
294         /* Wait for the data to arrive */
295         /* We can skip this wait as we are sure x and q will not be modified
296          * before the next call to gmx_pme_send_x_q or gmx_pme_receive_f.
297          */
298         gmx_pme_send_coeffs_coords_wait(dd);
299     }
300 }
301
302 void gmx_pme_send_parameters(const t_commrec*           cr,
303                              const interaction_const_t& interactionConst,
304                              bool                       bFreeEnergy_q,
305                              bool                       bFreeEnergy_lj,
306                              gmx::ArrayRef<real>        chargeA,
307                              gmx::ArrayRef<real>        chargeB,
308                              gmx::ArrayRef<real>        sqrt_c6A,
309                              gmx::ArrayRef<real>        sqrt_c6B,
310                              gmx::ArrayRef<real>        sigmaA,
311                              gmx::ArrayRef<real>        sigmaB,
312                              int                        maxshift_x,
313                              int                        maxshift_y)
314 {
315     unsigned int flags = 0;
316
317     if (EEL_PME(interactionConst.eeltype))
318     {
319         flags |= PP_PME_CHARGE;
320     }
321     if (EVDW_PME(interactionConst.vdwtype))
322     {
323         flags |= (PP_PME_SQRTC6 | PP_PME_SIGMA);
324     }
325     if (bFreeEnergy_q || bFreeEnergy_lj)
326     {
327         /* Assumes that the B state flags are in the bits just above
328          * the ones for the A state. */
329         flags |= (flags << 1);
330     }
331
332     gmx_pme_send_coeffs_coords(nullptr,
333                                cr,
334                                flags,
335                                chargeA,
336                                chargeB,
337                                sqrt_c6A,
338                                sqrt_c6B,
339                                sigmaA,
340                                sigmaB,
341                                nullptr,
342                                nullptr,
343                                0,
344                                0,
345                                maxshift_x,
346                                maxshift_y,
347                                -1,
348                                false,
349                                false,
350                                false,
351                                nullptr);
352 }
353
354 void gmx_pme_send_coordinates(t_forcerec*           fr,
355                               const t_commrec*      cr,
356                               const matrix          box,
357                               const rvec*           x,
358                               real                  lambda_q,
359                               real                  lambda_lj,
360                               bool                  computeEnergyAndVirial,
361                               int64_t               step,
362                               bool                  useGpuPmePpComms,
363                               bool                  receiveCoordinateAddressFromPme,
364                               bool                  sendCoordinatesFromGpu,
365                               GpuEventSynchronizer* coordinatesReadyOnDeviceEvent,
366                               gmx_wallcycle*        wcycle)
367 {
368     wallcycle_start(wcycle, ewcPP_PMESENDX);
369
370     unsigned int flags = PP_PME_COORD;
371     if (computeEnergyAndVirial)
372     {
373         flags |= PP_PME_ENER_VIR;
374     }
375     gmx_pme_send_coeffs_coords(fr,
376                                cr,
377                                flags,
378                                {},
379                                {},
380                                {},
381                                {},
382                                {},
383                                {},
384                                box,
385                                x,
386                                lambda_q,
387                                lambda_lj,
388                                0,
389                                0,
390                                step,
391                                useGpuPmePpComms,
392                                receiveCoordinateAddressFromPme,
393                                sendCoordinatesFromGpu,
394                                coordinatesReadyOnDeviceEvent);
395
396     wallcycle_stop(wcycle, ewcPP_PMESENDX);
397 }
398
399 void gmx_pme_send_finish(const t_commrec* cr)
400 {
401     unsigned int flags = PP_PME_FINISH;
402
403     gmx_pme_send_coeffs_coords(
404             nullptr, cr, flags, {}, {}, {}, {}, {}, {}, nullptr, nullptr, 0, 0, 0, 0, -1, false, false, false, nullptr);
405 }
406
407 void gmx_pme_send_switchgrid(const t_commrec* cr, ivec grid_size, real ewaldcoeff_q, real ewaldcoeff_lj)
408 {
409 #if GMX_MPI
410     gmx_pme_comm_n_box_t cnb;
411
412     /* Only let one PP node signal each PME node */
413     if (cr->dd->pme_receive_vir_ener)
414     {
415         cnb.flags = PP_PME_SWITCHGRID;
416         copy_ivec(grid_size, cnb.grid_size);
417         cnb.ewaldcoeff_q  = ewaldcoeff_q;
418         cnb.ewaldcoeff_lj = ewaldcoeff_lj;
419
420         /* We send this, uncommon, message blocking to simplify the code */
421         MPI_Send(&cnb, sizeof(cnb), MPI_BYTE, cr->dd->pme_nodeid, eCommType_CNB, cr->mpi_comm_mysim);
422     }
423 #else
424     GMX_UNUSED_VALUE(cr);
425     GMX_UNUSED_VALUE(grid_size);
426     GMX_UNUSED_VALUE(ewaldcoeff_q);
427     GMX_UNUSED_VALUE(ewaldcoeff_lj);
428 #endif
429 }
430
431 void gmx_pme_send_resetcounters(const t_commrec gmx_unused* cr, int64_t gmx_unused step)
432 {
433 #if GMX_MPI
434     gmx_pme_comm_n_box_t cnb;
435
436     /* Only let one PP node signal each PME node */
437     if (cr->dd->pme_receive_vir_ener)
438     {
439         cnb.flags = PP_PME_RESETCOUNTERS;
440         cnb.step  = step;
441
442         /* We send this, uncommon, message blocking to simplify the code */
443         MPI_Send(&cnb, sizeof(cnb), MPI_BYTE, cr->dd->pme_nodeid, eCommType_CNB, cr->mpi_comm_mysim);
444     }
445 #endif
446 }
447
448 /*! \brief Receive virial and energy from PME rank */
449 static void receive_virial_energy(const t_commrec*      cr,
450                                   gmx::ForceWithVirial* forceWithVirial,
451                                   real*                 energy_q,
452                                   real*                 energy_lj,
453                                   real*                 dvdlambda_q,
454                                   real*                 dvdlambda_lj,
455                                   float*                pme_cycles)
456 {
457     gmx_pme_comm_vir_ene_t cve;
458
459     if (cr->dd->pme_receive_vir_ener)
460     {
461         if (debug)
462         {
463             fprintf(debug,
464                     "PP rank %d receiving from PME rank %d: virial and energy\n",
465                     cr->sim_nodeid,
466                     cr->dd->pme_nodeid);
467         }
468 #if GMX_MPI
469         MPI_Recv(&cve, sizeof(cve), MPI_BYTE, cr->dd->pme_nodeid, 1, cr->mpi_comm_mysim, MPI_STATUS_IGNORE);
470 #else
471         memset(&cve, 0, sizeof(cve));
472 #endif
473
474         forceWithVirial->addVirialContribution(cve.vir_q);
475         forceWithVirial->addVirialContribution(cve.vir_lj);
476         *energy_q  = cve.energy_q;
477         *energy_lj = cve.energy_lj;
478         *dvdlambda_q += cve.dvdlambda_q;
479         *dvdlambda_lj += cve.dvdlambda_lj;
480         *pme_cycles = cve.cycles;
481
482         if (cve.stop_cond != gmx_stop_cond_none)
483         {
484             gmx_set_stop_condition(cve.stop_cond);
485         }
486     }
487     else
488     {
489         *energy_q   = 0;
490         *energy_lj  = 0;
491         *pme_cycles = 0;
492     }
493 }
494
495 /*! \brief Recieve force data from PME ranks */
496 static void recvFFromPme(gmx::PmePpCommGpu* pmePpCommGpu,
497                          void*              recvptr,
498                          int                n,
499                          const t_commrec*   cr,
500                          bool               useGpuPmePpComms,
501                          bool               receivePmeForceToGpu)
502 {
503     if (useGpuPmePpComms)
504     {
505         GMX_ASSERT(pmePpCommGpu != nullptr, "Need valid pmePpCommGpu");
506         // Receive directly using CUDA memory copy
507         pmePpCommGpu->receiveForceFromPmeCudaDirect(recvptr, n, receivePmeForceToGpu);
508     }
509     else
510     {
511         // Receive data using MPI
512 #if GMX_MPI
513         MPI_Recv(recvptr, n * sizeof(rvec), MPI_BYTE, cr->dd->pme_nodeid, 0, cr->mpi_comm_mysim, MPI_STATUS_IGNORE);
514 #else
515         GMX_UNUSED_VALUE(cr);
516 #endif
517     }
518 }
519
520
521 void gmx_pme_receive_f(gmx::PmePpCommGpu*    pmePpCommGpu,
522                        const t_commrec*      cr,
523                        gmx::ForceWithVirial* forceWithVirial,
524                        real*                 energy_q,
525                        real*                 energy_lj,
526                        real*                 dvdlambda_q,
527                        real*                 dvdlambda_lj,
528                        bool                  useGpuPmePpComms,
529                        bool                  receivePmeForceToGpu,
530                        float*                pme_cycles)
531 {
532     if (c_useDelayedWait)
533     {
534         /* Wait for the x request to finish */
535         gmx_pme_send_coeffs_coords_wait(cr->dd);
536     }
537
538     const int               natoms = dd_numHomeAtoms(*cr->dd);
539     std::vector<gmx::RVec>& buffer = cr->dd->pmeForceReceiveBuffer;
540     buffer.resize(natoms);
541
542     void* recvptr = reinterpret_cast<void*>(buffer.data());
543     recvFFromPme(pmePpCommGpu, recvptr, natoms, cr, useGpuPmePpComms, receivePmeForceToGpu);
544
545     int nt = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, natoms);
546
547     gmx::ArrayRef<gmx::RVec> f = forceWithVirial->force_;
548
549     if (!receivePmeForceToGpu)
550     {
551         /* Note that we would like to avoid this conditional by putting it
552          * into the omp pragma instead, but then we still take the full
553          * omp parallel for overhead (at least with gcc5).
554          */
555         if (nt == 1)
556         {
557             for (int i = 0; i < natoms; i++)
558             {
559                 f[i] += buffer[i];
560             }
561         }
562         else
563         {
564 #pragma omp parallel for num_threads(nt) schedule(static)
565             for (int i = 0; i < natoms; i++)
566             {
567                 f[i] += buffer[i];
568             }
569         }
570     }
571
572     receive_virial_energy(cr, forceWithVirial, energy_q, energy_lj, dvdlambda_q, dvdlambda_lj, pme_cycles);
573 }