Support GPU update without constraints
[alexxy/gromacs.git] / src / gromacs / mdlib / update_constrain_gpu_impl.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  *
37  * \brief Implements update and constraints class.
38  *
39  * The class combines Leap-Frog integrator with LINCS and SETTLE constraints.
40  *
41  * \todo The computational procedures in members should be integrated to improve
42  *       computational performance.
43  *
44  * \author Artem Zhmurov <zhmurov@gmail.com>
45  *
46  * \ingroup module_mdlib
47  */
48 #include "gmxpre.h"
49
50 #include "update_constrain_gpu_impl.h"
51
52 #include <assert.h>
53 #include <stdio.h>
54
55 #include <cmath>
56
57 #include <algorithm>
58
59 #include "gromacs/gpu_utils/device_context.h"
60 #include "gromacs/gpu_utils/device_stream.h"
61 #include "gromacs/gpu_utils/devicebuffer.h"
62 #if GMX_GPU_CUDA
63 #    include "gromacs/gpu_utils/gpueventsynchronizer.cuh"
64 #elif GMX_GPU_SYCL
65 #    include "gromacs/gpu_utils/gpueventsynchronizer_sycl.h"
66 #endif
67 #include "gromacs/gpu_utils/gputraits.h"
68 #include "gromacs/mdlib/leapfrog_gpu.h"
69 #include "gromacs/mdlib/update_constrain_gpu.h"
70 #include "gromacs/mdlib/update_constrain_gpu_internal.h"
71 #include "gromacs/mdtypes/mdatom.h"
72 #include "gromacs/timing/wallcycle.h"
73 #include "gromacs/topology/mtop_util.h"
74
75 static constexpr bool sc_haveGpuConstraintSupport = (GMX_GPU_CUDA);
76
77 namespace gmx
78 {
79
80 void UpdateConstrainGpu::Impl::integrate(GpuEventSynchronizer*             fReadyOnDevice,
81                                          const real                        dt,
82                                          const bool                        updateVelocities,
83                                          const bool                        computeVirial,
84                                          tensor                            virial,
85                                          const bool                        doTemperatureScaling,
86                                          gmx::ArrayRef<const t_grp_tcstat> tcstat,
87                                          const bool                        doParrinelloRahman,
88                                          const float                       dtPressureCouple,
89                                          const matrix                      prVelocityScalingMatrix)
90 {
91     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
92     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
93
94     // Clearing virial matrix
95     // TODO There is no point in having separate virial matrix for constraints
96     clear_mat(virial);
97
98     // Make sure that the forces are ready on device before proceeding with the update.
99     fReadyOnDevice->enqueueWaitEvent(deviceStream_);
100
101     // The integrate should save a copy of the current coordinates in d_xp_ and write updated
102     // once into d_x_. The d_xp_ is only needed by constraints.
103     integrator_->integrate(
104             d_x_, d_xp_, d_v_, d_f_, dt, doTemperatureScaling, tcstat, doParrinelloRahman, dtPressureCouple, prVelocityScalingMatrix);
105     // Constraints need both coordinates before (d_x_) and after (d_xp_) update. However, after constraints
106     // are applied, the d_x_ can be discarded. So we intentionally swap the d_x_ and d_xp_ here to avoid the
107     // d_xp_ -> d_x_ copy after constraints. Note that the integrate saves them in the wrong order as well.
108     if (sc_haveGpuConstraintSupport)
109     {
110         lincsGpu_->apply(d_xp_, d_x_, updateVelocities, d_v_, 1.0 / dt, computeVirial, virial, pbcAiuc_);
111         settleGpu_->apply(d_xp_, d_x_, updateVelocities, d_v_, 1.0 / dt, computeVirial, virial, pbcAiuc_);
112     }
113
114     // scaledVirial -> virial (methods above returns scaled values)
115     float scaleFactor = 0.5F / (dt * dt);
116     for (int i = 0; i < DIM; i++)
117     {
118         for (int j = 0; j < DIM; j++)
119         {
120             virial[i][j] = scaleFactor * virial[i][j];
121         }
122     }
123
124     coordinatesReady_->markEvent(deviceStream_);
125
126     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
127     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
128
129     return;
130 }
131
132 void UpdateConstrainGpu::Impl::scaleCoordinates(const matrix scalingMatrix)
133 {
134     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
135     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
136
137     ScalingMatrix mu(scalingMatrix);
138
139     launchScaleCoordinatesKernel(numAtoms_, d_x_, mu, deviceStream_);
140
141     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
142     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
143 }
144
145 void UpdateConstrainGpu::Impl::scaleVelocities(const matrix scalingMatrix)
146 {
147     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
148     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
149
150     ScalingMatrix mu(scalingMatrix);
151
152     launchScaleCoordinatesKernel(numAtoms_, d_v_, mu, deviceStream_);
153
154     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
155     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
156 }
157
158 UpdateConstrainGpu::Impl::Impl(const t_inputrec&     ir,
159                                const gmx_mtop_t&     mtop,
160                                const int             numTempScaleValues,
161                                const DeviceContext&  deviceContext,
162                                const DeviceStream&   deviceStream,
163                                GpuEventSynchronizer* xUpdatedOnDevice,
164                                gmx_wallcycle*        wcycle) :
165     deviceContext_(deviceContext),
166     deviceStream_(deviceStream),
167     coordinatesReady_(xUpdatedOnDevice),
168     wcycle_(wcycle)
169 {
170     GMX_ASSERT(xUpdatedOnDevice != nullptr, "The event synchronizer can not be nullptr.");
171
172     integrator_ = std::make_unique<LeapFrogGpu>(deviceContext_, deviceStream_, numTempScaleValues);
173     if (sc_haveGpuConstraintSupport)
174     {
175         lincsGpu_ = std::make_unique<LincsGpu>(ir.nLincsIter, ir.nProjOrder, deviceContext_, deviceStream_);
176         settleGpu_ = std::make_unique<SettleGpu>(mtop, deviceContext_, deviceStream_);
177     }
178 }
179
180 UpdateConstrainGpu::Impl::~Impl() {}
181
182 void UpdateConstrainGpu::Impl::set(DeviceBuffer<Float3>          d_x,
183                                    DeviceBuffer<Float3>          d_v,
184                                    const DeviceBuffer<Float3>    d_f,
185                                    const InteractionDefinitions& idef,
186                                    const t_mdatoms&              md)
187 {
188     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
189     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
190
191     GMX_ASSERT(d_x, "Coordinates device buffer should not be null.");
192     GMX_ASSERT(d_v, "Velocities device buffer should not be null.");
193     GMX_ASSERT(d_f, "Forces device buffer should not be null.");
194
195     d_x_ = d_x;
196     d_v_ = d_v;
197     d_f_ = d_f;
198
199     numAtoms_ = md.nr;
200
201     reallocateDeviceBuffer(&d_xp_, numAtoms_, &numXp_, &numXpAlloc_, deviceContext_);
202
203     reallocateDeviceBuffer(
204             &d_inverseMasses_, numAtoms_, &numInverseMasses_, &numInverseMassesAlloc_, deviceContext_);
205
206     // Integrator should also update something, but it does not even have a method yet
207     integrator_->set(numAtoms_, md.invmass, md.cTC);
208     if (sc_haveGpuConstraintSupport)
209     {
210         lincsGpu_->set(idef, numAtoms_, md.invmass);
211         settleGpu_->set(idef);
212     }
213     else
214     {
215         GMX_ASSERT(idef.il[F_SETTLE].empty(), "SETTLE not supported");
216         GMX_ASSERT(idef.il[F_CONSTR].empty(), "LINCS not supported");
217     }
218
219     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
220     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
221 }
222
223 void UpdateConstrainGpu::Impl::setPbc(const PbcType pbcType, const matrix box)
224 {
225     // TODO wallcycle
226     setPbcAiuc(numPbcDimensions(pbcType), box, &pbcAiuc_);
227 }
228
229 GpuEventSynchronizer* UpdateConstrainGpu::Impl::getCoordinatesReadySync()
230 {
231     return coordinatesReady_;
232 }
233
234 UpdateConstrainGpu::UpdateConstrainGpu(const t_inputrec&     ir,
235                                        const gmx_mtop_t&     mtop,
236                                        const int             numTempScaleValues,
237                                        const DeviceContext&  deviceContext,
238                                        const DeviceStream&   deviceStream,
239                                        GpuEventSynchronizer* xUpdatedOnDevice,
240                                        gmx_wallcycle*        wcycle) :
241     impl_(new Impl(ir, mtop, numTempScaleValues, deviceContext, deviceStream, xUpdatedOnDevice, wcycle))
242 {
243 }
244
245 UpdateConstrainGpu::~UpdateConstrainGpu() = default;
246
247 void UpdateConstrainGpu::integrate(GpuEventSynchronizer*             fReadyOnDevice,
248                                    const real                        dt,
249                                    const bool                        updateVelocities,
250                                    const bool                        computeVirial,
251                                    tensor                            virialScaled,
252                                    const bool                        doTemperatureScaling,
253                                    gmx::ArrayRef<const t_grp_tcstat> tcstat,
254                                    const bool                        doParrinelloRahman,
255                                    const float                       dtPressureCouple,
256                                    const matrix                      prVelocityScalingMatrix)
257 {
258     impl_->integrate(fReadyOnDevice,
259                      dt,
260                      updateVelocities,
261                      computeVirial,
262                      virialScaled,
263                      doTemperatureScaling,
264                      tcstat,
265                      doParrinelloRahman,
266                      dtPressureCouple,
267                      prVelocityScalingMatrix);
268 }
269
270 void UpdateConstrainGpu::scaleCoordinates(const matrix scalingMatrix)
271 {
272     impl_->scaleCoordinates(scalingMatrix);
273 }
274
275 void UpdateConstrainGpu::scaleVelocities(const matrix scalingMatrix)
276 {
277     impl_->scaleVelocities(scalingMatrix);
278 }
279
280 void UpdateConstrainGpu::set(DeviceBuffer<Float3>          d_x,
281                              DeviceBuffer<Float3>          d_v,
282                              const DeviceBuffer<Float3>    d_f,
283                              const InteractionDefinitions& idef,
284                              const t_mdatoms&              md)
285 {
286     impl_->set(d_x, d_v, d_f, idef, md);
287 }
288
289 void UpdateConstrainGpu::setPbc(const PbcType pbcType, const matrix box)
290 {
291     impl_->setPbc(pbcType, box);
292 }
293
294 GpuEventSynchronizer* UpdateConstrainGpu::getCoordinatesReadySync()
295 {
296     return impl_->getCoordinatesReadySync();
297 }
298
299 bool UpdateConstrainGpu::isNumCoupledConstraintsSupported(const gmx_mtop_t& mtop)
300 {
301     return LincsGpu::isNumCoupledConstraintsSupported(mtop);
302 }
303
304 bool UpdateConstrainGpu::areConstraintsSupported()
305 {
306     return sc_haveGpuConstraintSupport;
307 }
308
309 } // namespace gmx