"platforms/cuda2/src/kernels/nonbonded.cu" did not exist on "839f9a817684d45081a67ba44e38870d61da58fd"
OpenCLNonbondedUtilities.h 16.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
#ifndef OPENMM_OPENCLNONBONDEDUTILITIES_H_
#define OPENMM_OPENCLNONBONDEDUTILITIES_H_

/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
Peter Eastman's avatar
Peter Eastman committed
12
 * Portions copyright (c) 2009-2025 Stanford University and the Authors.      *
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 * Authors: Peter Eastman                                                     *
 * Contributors:                                                              *
 *                                                                            *
 * This program is free software: you can redistribute it and/or modify       *
 * it under the terms of the GNU Lesser General Public License as published   *
 * by the Free Software Foundation, either version 3 of the License, or       *
 * (at your option) any later version.                                        *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Lesser General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
 * -------------------------------------------------------------------------- */

#include "openmm/System.h"
31
#include "OpenCLArray.h"
32
#include "OpenCLExpressionUtilities.h"
33
#include "openmm/common/ComputeSort.h"
34
#include "openmm/common/NonbondedUtilities.h"
35
#include <sstream>
36
37
38
39
#include <string>
#include <vector>

namespace OpenMM {
40
    
41
class OpenCLContext;
42
43

/**
44
 * This class provides a generic interface for calculating nonbonded interactions.  It does this in two
45
 * ways.  First, it can be used to create Kernels that evaluate nonbonded interactions.  Clients
46
47
48
49
50
51
52
53
54
55
56
57
58
 * only need to provide the code for evaluating a single interaction and the list of parameters it depends on.
 * A complete kernel is then synthesized using an appropriate algorithm to evaluate all interactions on all
 * atoms.
 *
 * Second, this class itself creates and invokes a single "default" interaction kernel, allowing several
 * different forces to be evaluated at once for greater efficiency.  Call addInteraction() and addParameter()
 * to add interactions to this default kernel.
 *
 * During each force or energy evaluation, the following sequence of steps takes place:
 *
 * 1. Data structures (e.g. neighbor lists) are calculated to allow nonbonded interactions to be evaluated
 * quickly.
 *
59
 * 2. calcForcesAndEnergy() is called on each ForceImpl in the System.
60
61
62
63
64
 *
 * 3. Finally, the default interaction kernel is invoked to calculate all interactions that were added
 * to it.
 *
 * This sequence means that the default interaction kernel may depend on quantities that were calculated
65
 * by ForceImpls during calcForcesAndEnergy().
66
67
 */

68
class OPENMM_EXPORT_COMMON OpenCLNonbondedUtilities : public NonbondedUtilities {
69
public:
70
    class ParameterInfo;
71
72
73
    OpenCLNonbondedUtilities(OpenCLContext& context);
    ~OpenCLNonbondedUtilities();
    /**
74
     * Add a nonbonded interaction to be evaluated by the default interaction kernel.
75
76
77
     *
     * @param usesCutoff     specifies whether a cutoff should be applied to this interaction
     * @param usesPeriodic   specifies whether periodic boundary conditions should be applied to this interaction
78
     * @param usesExclusions specifies whether this interaction uses exclusions.  If this is true, it must have identical exclusions to every other interaction.
79
80
     * @param cutoffDistance the cutoff distance for this interaction (ignored if usesCutoff is false)
     * @param exclusionList  for each atom, specifies the list of other atoms whose interactions should be excluded
81
     * @param kernel         the code to evaluate the interaction
82
     * @param forceGroup     the force group in which the interaction should be calculated
83
84
     * @param useNeighborList  specifies whether a neighbor list should be used to optimize this interaction.  This should
     *                         be viewed as only a suggestion.  Even when it is false, a neighbor list may be used anyway.
85
     * @param supportsPairList specifies whether this interaction can work with a neighbor list that uses a separate pair list
86
     */
87
88
89
    void addInteraction(bool usesCutoff, bool usesPeriodic, bool usesExclusions, double cutoffDistance,
                        const std::vector<std::vector<int> >& exclusionList, const std::string& kernel,
                        int forceGroup, bool useNeighborList=true, bool supportsPairList=false);
90
    /**
91
     * Add a per-atom parameter that the default interaction kernel may depend on.
92
     */
93
94
95
96
97
98
    void addParameter(ComputeParameterInfo parameter);
    /**
     * Add a per-atom parameter that the default interaction kernel may depend on.
     * 
     * @deprecated Use the version that takes a ComputeParameterInfo instead.
     */
99
    void addParameter(const ParameterInfo& parameter);
100
101
102
    /**
     * Add an array (other than a per-atom parameter) that should be passed as an argument to the default interaction kernel.
     */
103
104
105
106
107
108
    void addArgument(ComputeParameterInfo parameter);
    /**
     * Add an array (other than a per-atom parameter) that should be passed as an argument to the default interaction kernel.
     * 
     * @deprecated Use the version that takes a ComputeParameterInfo instead.
     */
109
    void addArgument(const ParameterInfo& parameter);
110
111
112
113
114
115
116
117
118
    /**
     * Register that the interaction kernel will be computing the derivative of the potential energy
     * with respect to a parameter.
     * 
     * @param param   the name of the parameter
     * @return the variable that will be used to accumulate the derivative.  Any code you pass to addInteraction() should
     * add its contributions to this variable.
     */
    std::string addEnergyParameterDerivative(const std::string& param);
119
120
121
122
123
124
    /**
     * Specify the list of exclusions that an interaction outside the default kernel will depend on.
     * 
     * @param exclusionList  for each atom, specifies the list of other atoms whose interactions should be excluded
     */
    void requestExclusions(const std::vector<std::vector<int> >& exclusionList);
125
126
127
128
129
130
131
    /**
     * Initialize this object in preparation for a simulation.
     */
    void initialize(const System& system);
    /**
     * Get the number of force buffers required for nonbonded forces.
     */
132
    int getNumForceBuffers() const {
133
        return 1;
134
    }
135
136
137
138
139
140
    /**
     * Get the number of energy buffers required for nonbonded forces.
     */
    int getNumEnergyBuffers() {
        return numForceThreadBlocks*forceThreadBlockSize;
    }
141
142
143
144
145
146
147
148
149
150
151
152
    /**
     * Get whether a cutoff is being used.
     */
    bool getUseCutoff() {
        return useCutoff;
    }
    /**
     * Get whether periodic boundary conditions are being used.
     */
    bool getUsePeriodic() {
        return usePeriodic;
    }
153
154
155
156
157
158
159
160
161
162
163
164
    /**
     * Get the number of work groups used for computing nonbonded forces.
     */
    int getNumForceThreadBlocks() {
        return numForceThreadBlocks;
    }
    /**
     * Get the size of each work group used for computing nonbonded forces.
     */
    int getForceThreadBlockSize() {
        return forceThreadBlockSize;
    }
165
    /**
166
     * Get the maximum cutoff distance used by any force group.
167
     */
168
    double getMaxCutoffDistance();
Peter Eastman's avatar
Peter Eastman committed
169
170
171
172
    /**
     * Get whether any interactions have been added.
     */
    bool getHasInteractions() {
173
        return (groupCutoff.size() > 0);
174
    }
175
176
177
178
179
    /**
     * Given a nonbonded cutoff, get the padded cutoff distance used in computing
     * the neighbor list.
     */
    double padCutoff(double cutoff);
180
181
182
    /**
     * Prepare to compute interactions.  This updates the neighbor list.
     */
183
    void prepareInteractions(int forceGroups);
184
    /**
185
     * Compute the nonbonded interactions.
186
187
188
189
     * 
     * @param forceGroups    the flags specifying which force groups to include
     * @param includeForces  whether to compute forces
     * @param includeEnergy  whether to compute the potential energy
190
     */
191
    void computeInteractions(int forceGroups, bool includeForces, bool includeEnergy);
192
193
    /**
     * Check to see if the neighbor list arrays are large enough, and make them bigger if necessary.
194
195
     *
     * @return true if the neighbor list needed to be enlarged.
196
     */
197
    bool updateNeighborListSize();
198
199
200
    /**
     * Get the array containing the center of each atom block.
     */
201
    OpenCLArray& getBlockCenters() {
peastman's avatar
peastman committed
202
        return blockCenter;
203
204
205
206
    }
    /**
     * Get the array containing the dimensions of each atom block.
     */
207
    OpenCLArray& getBlockBoundingBoxes() {
peastman's avatar
peastman committed
208
        return blockBoundingBox;
209
210
211
212
    }
    /**
     * Get the array whose first element contains the number of tiles with interactions.
     */
213
    OpenCLArray& getInteractionCount() {
peastman's avatar
peastman committed
214
        return interactionCount;
215
216
217
218
    }
    /**
     * Get the array containing tiles with interactions.
     */
219
    OpenCLArray& getInteractingTiles() {
peastman's avatar
peastman committed
220
        return interactingTiles;
221
222
    }
    /**
223
     * Get the array containing the atoms in each tile with interactions.
224
     */
225
    OpenCLArray& getInteractingAtoms() {
peastman's avatar
peastman committed
226
        return interactingAtoms;
227
    }
228
229
230
    /**
     * Get the array containing exclusion flags.
     */
231
    OpenCLArray& getExclusions() {
peastman's avatar
peastman committed
232
        return exclusions;
233
    }
234
235
236
237
    /**
     * Get the array containing tiles with exclusions.
     */
    OpenCLArray& getExclusionTiles() {
peastman's avatar
peastman committed
238
        return exclusionTiles;
239
    }
240
241
242
    /**
     * Get the array containing the index into the exclusion array for each tile.
     */
243
    OpenCLArray& getExclusionIndices() {
peastman's avatar
peastman committed
244
        return exclusionIndices;
245
246
247
248
    }
    /**
     * Get the array listing where the exclusion data starts for each row.
     */
249
    OpenCLArray& getExclusionRowIndices() {
peastman's avatar
peastman committed
250
        return exclusionRowIndices;
251
    }
252
253
254
255
256
257
258
    /**
     * Get the array containing a flag for whether the neighbor list was rebuilt
     * on the most recent call to prepareInteractions().
     */
    OpenCLArray& getRebuildNeighborList() {
        return rebuildNeighborList;
    }
259
260
261
262
263
264
265
266
267
268
269
270
    /**
     * Get the index of the first tile this context is responsible for processing.
     */
    int getStartTileIndex() const {
        return startTileIndex;
    }
    /**
     * Get the total number of tiles this context is responsible for processing.
     */
    int getNumTiles() const {
        return numTiles;
    }
271
    /**
272
273
274
275
276
277
278
279
280
     * Set whether to add padding to the cutoff distance when building the neighbor list.
     * This increases the size of the neighbor list (and thus the cost of computing interactions),
     * but also means we don't need to rebuild it every time step.  The default value is true,
     * since usually this improves performance.  For very expensive interactions, however,
     * it may be better to set this to false.
     */
    void setUsePadding(bool padding);
    /**
     * Set the range of atom blocks and tiles that should be processed by this context.
281
     */
282
    void setAtomBlockRange(double startFraction, double endFraction);
283
284
285
286
287
288
289
    /**
     * Create a Kernel for evaluating a nonbonded interaction.  Cutoffs and periodic boundary conditions
     * are assumed to be the same as those for the default interaction Kernel, since this kernel will use
     * the same neighbor list.
     * 
     * @param source        the source code for evaluating the force and energy
     * @param params        the per-atom parameters this kernel may depend on
290
     * @param arguments     arrays (other than per-atom parameters) that should be passed as arguments to the kernel
291
     * @param useExclusions specifies whether exclusions are applied to this interaction
292
     * @param isSymmetric   specifies whether the interaction is symmetric
293
     * @param groups        the set of force groups this kernel is for
294
295
     * @param includeForces whether this kernel should compute forces
     * @param includeEnergy whether this kernel should compute potential energy
296
     */
297
    cl::Kernel createInteractionKernel(const std::string& source, const std::vector<ParameterInfo>& params, const std::vector<ParameterInfo>& arguments, bool useExclusions, bool isSymmetric, int groups, bool includeForces, bool includeEnergy);
298
299
300
301
    /**
     * Create the set of kernels that will be needed for a particular combination of force groups.
     * 
     * @param groups    the set of force groups
302
     */
303
    void createKernelsForGroups(int groups);
304
305
306
307
    /**
     * Set the source code for the main kernel.  It only needs to be changed in very unusual circumstances.
     */
    void setKernelSource(const std::string& source);
308
private:
309
    class KernelSet;
310
    class BlockSortTrait;
311
    OpenCLContext& context;
312
    std::map<int, KernelSet> groupKernels;
peastman's avatar
peastman committed
313
314
315
316
317
318
319
320
321
322
323
324
    OpenCLArray exclusionTiles;
    OpenCLArray exclusions;
    OpenCLArray exclusionIndices;
    OpenCLArray exclusionRowIndices;
    OpenCLArray interactingTiles;
    OpenCLArray interactingAtoms;
    OpenCLArray interactionCount;
    OpenCLArray blockCenter;
    OpenCLArray blockBoundingBox;
    OpenCLArray sortedBlocks;
    OpenCLArray sortedBlockCenter;
    OpenCLArray sortedBlockBoundingBox;
325
    OpenCLArray blockSizeRange;
326
327
    OpenCLArray largeBlockCenter;
    OpenCLArray largeBlockBoundingBox;
peastman's avatar
peastman committed
328
329
    OpenCLArray oldPositions;
    OpenCLArray rebuildNeighborList;
330
    ComputeSort blockSorter;
331
332
    cl::Event downloadCountEvent;
    cl::Buffer* pinnedCountBuffer;
333
    unsigned int* pinnedCountMemory;
334
335
    std::vector<std::vector<int> > atomExclusions;
    std::vector<ParameterInfo> parameters;
336
    std::vector<ParameterInfo> arguments;
337
    std::vector<std::string> energyParameterDerivatives;
338
339
    std::map<int, double> groupCutoff;
    std::map<int, std::string> groupKernelSource;
Peter Eastman's avatar
Peter Eastman committed
340
    double maxCutoff;
341
    bool useCutoff, usePeriodic, deviceIsCpu, anyExclusions, usePadding, useNeighborList, forceRebuildNeighborList, useLargeBlocks, isAMD;
342
    int startTileIndex, startBlockIndex, numBlocks, maxExclusions, numForceThreadBlocks;
343
    int forceThreadBlockSize, interactingBlocksThreadBlockSize, groupFlags, numBlockSizes;
344
    unsigned int tilesAfterReorder;
345
    long long numTiles;
346
    std::string kernelSource;
347
348
349
350
351
352
353
354
355
};

/**
 * This class stores the kernels to execute for a set of force groups.
 */

class OpenCLNonbondedUtilities::KernelSet {
public:
    bool hasForces;
356
357
    std::string source;
    cl::Kernel forceKernel, energyKernel, forceEnergyKernel;
358
    cl::Kernel findBlockBoundsKernel;
359
    cl::Kernel computeSortKeysKernel;
360
361
362
    cl::Kernel sortBoxDataKernel;
    cl::Kernel findInteractingBlocksKernel;
    cl::Kernel findInteractionsWithinBlocksKernel;
363
364
};

365
366
367
368
/**
 * This class stores information about a per-atom parameter that may be used in a nonbonded kernel.
 */

369
370
class OpenCLNonbondedUtilities::ParameterInfo {
public:
371
372
373
    /**
     * Create a ParameterInfo object.
     *
374
375
376
377
378
     * @param name           the name of the parameter
     * @param type           the data type of the parameter's components
     * @param numComponents  the number of components in the parameter
     * @param size           the size of the parameter in bytes
     * @param memory         the memory containing the parameter values
379
     * @param constant       whether the memory should be marked as constant
380
     */
381
382
    ParameterInfo(const std::string& name, const std::string& componentType, int numComponents, int size, cl::Memory& memory, bool constant=true) :
            name(name), componentType(componentType), numComponents(numComponents), size(size), memory(&memory), constant(constant) {
383
384
        if (numComponents == 1)
            type = componentType;
385
386
387
388
389
        else {
            std::stringstream s;
            s << componentType << numComponents;
            type = s.str();
        }
390
    }
391
392
393
    const std::string& getName() const {
        return name;
    }
394
395
396
    const std::string& getComponentType() const {
        return componentType;
    }
397
398
399
    const std::string& getType() const {
        return type;
    }
400
401
402
    int getNumComponents() const {
        return numComponents;
    }
403
404
405
    int getSize() const {
        return size;
    }
406
407
    cl::Memory& getMemory() const {
        return *memory;
408
    }
409
410
411
    bool isConstant() const {
        return constant;
    }
412
private:
413
    std::string name;
414
    std::string componentType;
415
    std::string type;
416
    int size, numComponents;
417
    cl::Memory* memory;
418
    bool constant;
419
420
421
422
423
};

} // namespace OpenMM

#endif /*OPENMM_OPENCLNONBONDEDUTILITIES_H_*/