Silence Clang's constant-logical-operand warning
[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 #include "gromacs/gpu_utils/gpueventsynchronizer.h"
63 #include "gromacs/gpu_utils/gputraits.h"
64 #include "gromacs/mdlib/leapfrog_gpu.h"
65 #include "gromacs/mdlib/update_constrain_gpu.h"
66 #include "gromacs/mdlib/update_constrain_gpu_internal.h"
67 #include "gromacs/mdtypes/mdatom.h"
68 #include "gromacs/timing/wallcycle.h"
69 #include "gromacs/topology/mtop_util.h"
70
71 static constexpr bool sc_haveGpuConstraintSupport = bool(GMX_GPU_CUDA) || bool(GMX_GPU_SYCL);
72
73 namespace gmx
74 {
75
76 void UpdateConstrainGpu::Impl::integrate(GpuEventSynchronizer*             fReadyOnDevice,
77                                          const real                        dt,
78                                          const bool                        updateVelocities,
79                                          const bool                        computeVirial,
80                                          tensor                            virial,
81                                          const bool                        doTemperatureScaling,
82                                          gmx::ArrayRef<const t_grp_tcstat> tcstat,
83                                          const bool                        doParrinelloRahman,
84                                          const float                       dtPressureCouple,
85                                          const matrix                      prVelocityScalingMatrix)
86 {
87     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
88     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
89
90     // Clearing virial matrix
91     // TODO There is no point in having separate virial matrix for constraints
92     clear_mat(virial);
93
94     // Make sure that the forces are ready on device before proceeding with the update.
95     fReadyOnDevice->enqueueWaitEvent(deviceStream_);
96
97     // The integrate should save a copy of the current coordinates in d_xp_ and write updated
98     // once into d_x_. The d_xp_ is only needed by constraints.
99     integrator_->integrate(
100             d_x_, d_xp_, d_v_, d_f_, dt, doTemperatureScaling, tcstat, doParrinelloRahman, dtPressureCouple, prVelocityScalingMatrix);
101     // Constraints need both coordinates before (d_x_) and after (d_xp_) update. However, after constraints
102     // are applied, the d_x_ can be discarded. So we intentionally swap the d_x_ and d_xp_ here to avoid the
103     // d_xp_ -> d_x_ copy after constraints. Note that the integrate saves them in the wrong order as well.
104     if (sc_haveGpuConstraintSupport)
105     {
106         lincsGpu_->apply(d_xp_, d_x_, updateVelocities, d_v_, 1.0 / dt, computeVirial, virial, pbcAiuc_);
107         settleGpu_->apply(d_xp_, d_x_, updateVelocities, d_v_, 1.0 / dt, computeVirial, virial, pbcAiuc_);
108     }
109
110     // scaledVirial -> virial (methods above returns scaled values)
111     float scaleFactor = 0.5F / (dt * dt);
112     for (int i = 0; i < DIM; i++)
113     {
114         for (int j = 0; j < DIM; j++)
115         {
116             virial[i][j] = scaleFactor * virial[i][j];
117         }
118     }
119
120     xUpdatedOnDeviceEvent_.markEvent(deviceStream_);
121
122     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
123     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
124 }
125
126 void UpdateConstrainGpu::Impl::scaleCoordinates(const matrix scalingMatrix)
127 {
128     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
129     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
130
131     ScalingMatrix mu(scalingMatrix);
132
133     launchScaleCoordinatesKernel(numAtoms_, d_x_, mu, deviceStream_);
134
135     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
136     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
137 }
138
139 void UpdateConstrainGpu::Impl::scaleVelocities(const matrix scalingMatrix)
140 {
141     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
142     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
143
144     ScalingMatrix mu(scalingMatrix);
145
146     launchScaleCoordinatesKernel(numAtoms_, d_v_, mu, deviceStream_);
147
148     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
149     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
150 }
151
152 UpdateConstrainGpu::Impl::Impl(const t_inputrec&    ir,
153                                const gmx_mtop_t&    mtop,
154                                const int            numTempScaleValues,
155                                const DeviceContext& deviceContext,
156                                const DeviceStream&  deviceStream,
157                                gmx_wallcycle*       wcycle) :
158     deviceContext_(deviceContext), deviceStream_(deviceStream), wcycle_(wcycle)
159 {
160     integrator_ = std::make_unique<LeapFrogGpu>(deviceContext_, deviceStream_, numTempScaleValues);
161     if (sc_haveGpuConstraintSupport)
162     {
163         lincsGpu_ = std::make_unique<LincsGpu>(ir.nLincsIter, ir.nProjOrder, deviceContext_, deviceStream_);
164         settleGpu_ = std::make_unique<SettleGpu>(mtop, deviceContext_, deviceStream_);
165     }
166 }
167
168 UpdateConstrainGpu::Impl::~Impl() {}
169
170 void UpdateConstrainGpu::Impl::set(DeviceBuffer<Float3>          d_x,
171                                    DeviceBuffer<Float3>          d_v,
172                                    const DeviceBuffer<Float3>    d_f,
173                                    const InteractionDefinitions& idef,
174                                    const t_mdatoms&              md)
175 {
176     wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu);
177     wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
178
179     GMX_ASSERT(d_x, "Coordinates device buffer should not be null.");
180     GMX_ASSERT(d_v, "Velocities device buffer should not be null.");
181     GMX_ASSERT(d_f, "Forces device buffer should not be null.");
182
183     d_x_ = d_x;
184     d_v_ = d_v;
185     d_f_ = d_f;
186
187     numAtoms_ = md.nr;
188
189     reallocateDeviceBuffer(&d_xp_, numAtoms_, &numXp_, &numXpAlloc_, deviceContext_);
190
191     reallocateDeviceBuffer(
192             &d_inverseMasses_, numAtoms_, &numInverseMasses_, &numInverseMassesAlloc_, deviceContext_);
193
194     // Integrator should also update something, but it does not even have a method yet
195     integrator_->set(numAtoms_, md.invmass, md.cTC);
196     if (sc_haveGpuConstraintSupport)
197     {
198         lincsGpu_->set(idef, numAtoms_, md.invmass);
199         settleGpu_->set(idef);
200     }
201     else
202     {
203         GMX_ASSERT(idef.il[F_SETTLE].empty(), "SETTLE not supported");
204         GMX_ASSERT(idef.il[F_CONSTR].empty(), "LINCS not supported");
205     }
206
207     wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain);
208     wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu);
209 }
210
211 void UpdateConstrainGpu::Impl::setPbc(const PbcType pbcType, const matrix box)
212 {
213     // TODO wallcycle
214     setPbcAiuc(numPbcDimensions(pbcType), box, &pbcAiuc_);
215 }
216
217 GpuEventSynchronizer* UpdateConstrainGpu::Impl::xUpdatedOnDeviceEvent()
218 {
219     return &xUpdatedOnDeviceEvent_;
220 }
221
222 UpdateConstrainGpu::UpdateConstrainGpu(const t_inputrec&    ir,
223                                        const gmx_mtop_t&    mtop,
224                                        const int            numTempScaleValues,
225                                        const DeviceContext& deviceContext,
226                                        const DeviceStream&  deviceStream,
227                                        gmx_wallcycle*       wcycle) :
228     impl_(new Impl(ir, mtop, numTempScaleValues, deviceContext, deviceStream, wcycle))
229 {
230 }
231
232 UpdateConstrainGpu::~UpdateConstrainGpu() = default;
233
234 void UpdateConstrainGpu::integrate(GpuEventSynchronizer*             fReadyOnDevice,
235                                    const real                        dt,
236                                    const bool                        updateVelocities,
237                                    const bool                        computeVirial,
238                                    tensor                            virialScaled,
239                                    const bool                        doTemperatureScaling,
240                                    gmx::ArrayRef<const t_grp_tcstat> tcstat,
241                                    const bool                        doParrinelloRahman,
242                                    const float                       dtPressureCouple,
243                                    const matrix                      prVelocityScalingMatrix)
244 {
245     impl_->integrate(fReadyOnDevice,
246                      dt,
247                      updateVelocities,
248                      computeVirial,
249                      virialScaled,
250                      doTemperatureScaling,
251                      tcstat,
252                      doParrinelloRahman,
253                      dtPressureCouple,
254                      prVelocityScalingMatrix);
255 }
256
257 void UpdateConstrainGpu::scaleCoordinates(const matrix scalingMatrix)
258 {
259     impl_->scaleCoordinates(scalingMatrix);
260 }
261
262 void UpdateConstrainGpu::scaleVelocities(const matrix scalingMatrix)
263 {
264     impl_->scaleVelocities(scalingMatrix);
265 }
266
267 void UpdateConstrainGpu::set(DeviceBuffer<Float3>          d_x,
268                              DeviceBuffer<Float3>          d_v,
269                              const DeviceBuffer<Float3>    d_f,
270                              const InteractionDefinitions& idef,
271                              const t_mdatoms&              md)
272 {
273     impl_->set(d_x, d_v, d_f, idef, md);
274 }
275
276 void UpdateConstrainGpu::setPbc(const PbcType pbcType, const matrix box)
277 {
278     impl_->setPbc(pbcType, box);
279 }
280
281 GpuEventSynchronizer* UpdateConstrainGpu::xUpdatedOnDeviceEvent()
282 {
283     return impl_->xUpdatedOnDeviceEvent();
284 }
285
286 bool UpdateConstrainGpu::isNumCoupledConstraintsSupported(const gmx_mtop_t& mtop)
287 {
288     return LincsGpu::isNumCoupledConstraintsSupported(mtop);
289 }
290
291 bool UpdateConstrainGpu::areConstraintsSupported()
292 {
293     return sc_haveGpuConstraintSupport;
294 }
295
296 } // namespace gmx