"plugins/vscode:/vscode.git/clone" did not exist on "41abd9fb9464de0b9dc859aeea520393034f42e9"
OpenCLBondedUtilities.cpp 15.1 KB
Newer Older
Peter Eastman's avatar
Peter Eastman committed
1
2
3
4
5
6
7
8
/* -------------------------------------------------------------------------- *
 *                                   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.               *
 *                                                                            *
9
 * Portions copyright (c) 2011-2016 Stanford University and the Authors.      *
Peter Eastman's avatar
Peter Eastman committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 * 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 "OpenCLBondedUtilities.h"
#include "OpenCLExpressionUtilities.h"
#include "openmm/OpenMMException.h"
#include "OpenCLNonbondedUtilities.h"
#include <iostream>

using namespace OpenMM;
using namespace std;

peastman's avatar
peastman committed
36
OpenCLBondedUtilities::OpenCLBondedUtilities(OpenCLContext& context) : context(context), numForceBuffers(0), maxBonds(0), allGroups(0), hasInitializedKernels(false) {
Peter Eastman's avatar
Peter Eastman committed
37
38
39
40
41
42
43
44
45
}

OpenCLBondedUtilities::~OpenCLBondedUtilities() {
    for (int i = 0; i < (int) atomIndices.size(); i++)
        delete atomIndices[i];
    for (int i = 0; i < (int) bufferIndices.size(); i++)
        delete bufferIndices[i];
}

46
void OpenCLBondedUtilities::addInteraction(const vector<vector<int> >& atoms, const string& source, int group) {
Peter Eastman's avatar
Peter Eastman committed
47
48
49
    if (atoms.size() > 0) {
        forceAtoms.push_back(atoms);
        forceSource.push_back(source);
50
        forceGroup.push_back(group);
peastman's avatar
peastman committed
51
        allGroups |= 1<<group;
Peter Eastman's avatar
Peter Eastman committed
52
        int width = 1;
53
        while (width < (int) atoms[0].size())
Peter Eastman's avatar
Peter Eastman committed
54
55
56
57
58
            width *= 2;
        indexWidth.push_back(width);
    }
}

59
string OpenCLBondedUtilities::addArgument(cl::Memory& data, const string& type) {
Peter Eastman's avatar
Peter Eastman committed
60
61
    arguments.push_back(&data);
    argTypes.push_back(type);
62
    return "customArg"+context.intToString(arguments.size());
Peter Eastman's avatar
Peter Eastman committed
63
64
}

65
66
67
68
69
70
71
72
73
74
75
76
77
string OpenCLBondedUtilities::addEnergyParameterDerivative(const string& param) {
    // See if the parameter has already been added.
    
    int index;
    for (index = 0; index < energyParameterDerivatives.size(); index++)
        if (param == energyParameterDerivatives[index])
            break;
    if (index == energyParameterDerivatives.size())
        energyParameterDerivatives.push_back(param);
    context.addEnergyParameterDerivative(param);
    return string("energyParamDeriv")+context.intToString(index);
}

78
void OpenCLBondedUtilities::addPrefixCode(const string& source) {
79
80
81
    for (int i = 0; i < (int) prefixCode.size(); i++)
        if (prefixCode[i] == source)
            return;
82
83
84
    prefixCode.push_back(source);
}

Peter Eastman's avatar
Peter Eastman committed
85
86
87
88
89
void OpenCLBondedUtilities::initialize(const System& system) {
    int numForces = forceAtoms.size();
    if (numForces == 0)
        return;
    
peastman's avatar
peastman committed
90
    // Build the lists of atom indices and buffer indices.
Peter Eastman's avatar
Peter Eastman committed
91
92
93
94
95
96
97
98
99
100
101
102
103
    
    vector<vector<cl_uint> > bufferVec(numForces);
    vector<vector<int> > bufferCounter(numForces, vector<int>(system.getNumParticles(), 0));
    vector<int> numBuffers(numForces, 0);
    for (int i = 0; i < numForces; i++) {
        int numBonds = forceAtoms[i].size();
        int numAtoms = forceAtoms[i][0].size();
        int width = indexWidth[i];
        vector<cl_uint> indexVec(width*numBonds);
        for (int bond = 0; bond < numBonds; bond++) {
            for (int atom = 0; atom < numAtoms; atom++)
                indexVec[bond*width+atom] = forceAtoms[i][bond][atom];
        }
104
        OpenCLArray* indices = OpenCLArray::create<cl_uint>(context, indexVec.size(), "bondedIndices");
Peter Eastman's avatar
Peter Eastman committed
105
106
107
108
109
110
111
112
113
114
115
116
        indices->upload(indexVec);
        atomIndices.push_back(indices);
        bufferVec[i].resize(width*numBonds, 0);
        for (int bond = 0; bond < numBonds; bond++) {
            for (int atom = 0; atom < numAtoms; atom++)
                bufferVec[i][bond*width+atom] = bufferCounter[i][forceAtoms[i][bond][atom]]++;
        }
        for (int j = 0; j < (int) bufferCounter[i].size(); j++)
            numBuffers[i] = max(numBuffers[i], bufferCounter[i][j]);
    }
    
    // For efficiency, we want to merge multiple forces into a single kernel - but only if that
117
    // won't increase the number of force buffers.
Peter Eastman's avatar
Peter Eastman committed
118
    
119
120
121
122
    if (context.getSupports64BitGlobalAtomics()) {
        // Put all the forces in the same set.
        
        numForceBuffers = 1;
Peter Eastman's avatar
Peter Eastman committed
123
        forceSets.push_back(vector<int>());
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        for (int i = 0; i < numForces; i++)
            forceSets[0].push_back(i);
    }
    else {
        // Figure out how many force buffers will be required.
    
        for (int i = 0; i < numForces; i++)
            numForceBuffers = max(numForceBuffers, numBuffers[i]);
        int bufferLimit = max(numForceBuffers, (int) context.getPlatformData().contexts.size());
        if (context.getNonbondedUtilities().getHasInteractions())
            bufferLimit = max(bufferLimit, context.getNonbondedUtilities().getNumForceBuffers());
        
        // Figure out sets of forces that can be merged.
        
        vector<int> unmerged(numForces);
        for (int i = 0; i < numForces; i++)
            unmerged[i] = i;
        for (int i = 0; i < numForces; i++)
            for (int j = i-1; j >= 0; j--) {
                if (numBuffers[unmerged[j]] <= numBuffers[unmerged[j+1]])
                    break;
                int temp = unmerged[j+1];
                unmerged[j+1] = unmerged[j];
                unmerged[j] = temp;
            }
        while (unmerged.size() > 0) {
            int sum = numBuffers[unmerged.back()];
            int i;
            for (i = 0; i < (int) unmerged.size()-1; i++) {
                if (sum+numBuffers[unmerged[i]] > bufferLimit)
                    break;
                sum += numBuffers[unmerged[i]];
            }
            forceSets.push_back(vector<int>());
            for (int j = 0; j < i; j++)
                forceSets.back().push_back(unmerged[j]);
            forceSets.back().push_back(unmerged.back());
            for (int j = 0; j < i; j++)
                unmerged.erase(unmerged.begin());
            unmerged.pop_back();
        }
Peter Eastman's avatar
Peter Eastman committed
165
166
167
168
169
170
    }

    // Update the buffer indices based on merged sets.
    
    bufferIndices.resize(numForces);
    for (int i = 0; i < (int) forceSets.size(); i++)
171
        for (int j = 0; j < (int) forceSets[i].size(); j++) {
Peter Eastman's avatar
Peter Eastman committed
172
173
174
175
176
177
178
179
            int force = forceSets[i][j];
            int numBonds = forceAtoms[force].size();
            int numAtoms = forceAtoms[force][0].size();
            int width = indexWidth[force];
            for (int k = 0; k < j; k++)
                for (int bond = 0; bond < numBonds; bond++)
                    for (int atom = 0; atom < numAtoms; atom++)
                        bufferVec[force][bond*width+atom] += bufferCounter[forceSets[i][k]][forceAtoms[force][bond][atom]];
180
            OpenCLArray* buffers = OpenCLArray::create<cl_uint>(context, bufferVec[force].size(), "bondedBufferIndices");
Peter Eastman's avatar
Peter Eastman committed
181
182
183
184
185
186
            buffers->upload(bufferVec[force]);
            bufferIndices[force] = buffers;
        }

    // Create the kernels.

peastman's avatar
peastman committed
187
    for (auto& set : forceSets) {
Peter Eastman's avatar
Peter Eastman committed
188
189
        int setSize = set.size();
        stringstream s;
190
191
192
        s<<"#ifdef SUPPORTS_64_BIT_ATOMICS\n";
        s<<"#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable\n";
        s<<"#endif\n";
193
194
        for (int i = 0; i < (int) prefixCode.size(); i++)
            s<<prefixCode[i];
195
        string bufferType = (context.getSupports64BitGlobalAtomics() ? "long" : "real4");
196
        s<<"__kernel void computeBondedForces(__global "<<bufferType<<"* restrict forceBuffers, __global mixed* restrict energyBuffer, __global const real4* restrict posq, int groups, real4 periodicBoxSize, real4 invPeriodicBoxSize, real4 periodicBoxVecX, real4 periodicBoxVecY, real4 periodicBoxVecZ";
Peter Eastman's avatar
Peter Eastman committed
197
198
        for (int i = 0; i < setSize; i++) {
            int force = set[i];
199
            string indexType = "uint"+(indexWidth[force] == 1 ? "" : context.intToString(indexWidth[force]));
200
201
            s<<", __global const "<<indexType<<"* restrict atomIndices"<<i;
            s<<", __global const "<<indexType<<"* restrict bufferIndices"<<i;
Peter Eastman's avatar
Peter Eastman committed
202
203
204
        }
        for (int i = 0; i < (int) arguments.size(); i++)
            s<<", __global "<<argTypes[i]<<"* customArg"<<(i+1);
205
        if (energyParameterDerivatives.size() > 0)
206
            s<<", __global mixed* restrict energyParamDerivs";
Peter Eastman's avatar
Peter Eastman committed
207
        s<<") {\n";
208
        s<<"mixed energy = 0;\n";
209
210
        for (int i = 0; i < energyParameterDerivatives.size(); i++)
            s<<"mixed energyParamDeriv"<<i<<" = 0;\n";
Peter Eastman's avatar
Peter Eastman committed
211
212
        for (int i = 0; i < setSize; i++) {
            int force = set[i];
213
            s<<createForceSource(i, forceAtoms[force].size(), forceAtoms[force][0].size(), forceGroup[force], forceSource[force]);
Peter Eastman's avatar
Peter Eastman committed
214
215
        }
        s<<"energyBuffer[get_global_id(0)] += energy;\n";
216
217
218
219
220
        const vector<string>& allParamDerivNames = context.getEnergyParamDerivNames();
        int numDerivs = allParamDerivNames.size();
        for (int i = 0; i < energyParameterDerivatives.size(); i++)
            for (int index = 0; index < numDerivs; index++)
                if (allParamDerivNames[index] == energyParameterDerivatives[i])
221
                    s<<"energyParamDerivs[get_global_id(0)*"<<numDerivs<<"+"<<index<<"] += energyParamDeriv"<<i<<";\n";
Peter Eastman's avatar
Peter Eastman committed
222
223
        s<<"}\n";
        map<string, string> defines;
224
        defines["PADDED_NUM_ATOMS"] = context.intToString(context.getPaddedNumAtoms());
Peter Eastman's avatar
Peter Eastman committed
225
226
227
228
229
230
231
        cl::Program program = context.createProgram(s.str(), defines);
        kernels.push_back(cl::Kernel(program, "computeBondedForces"));
    }
    forceAtoms.clear();
    forceSource.clear();
}

232
string OpenCLBondedUtilities::createForceSource(int forceIndex, int numBonds, int numAtoms, int group, const string& computeForce) {
Peter Eastman's avatar
Peter Eastman committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    maxBonds = max(maxBonds, numBonds);
    int width = 1;
    while (width < numAtoms)
        width *= 2;
    string suffix1[] = {""};
    string suffix4[] = {".x", ".y", ".z", ".w"};
    string suffix16[] = {".s0", ".s1", ".s2", ".s3", ".s4", ".s5", ".s6", ".s7",
        ".s8", ".s9", ".s10", ".s11", ".s12", ".s13", ".s14", ".s15"};
    string* suffix;
    if (width == 1)
        suffix = suffix1;
    else if (width <= 4)
        suffix = suffix4;
    else
        suffix = suffix16;
248
    string indexType = "uint"+(width == 1 ? "" : context.intToString(width));
Peter Eastman's avatar
Peter Eastman committed
249
    stringstream s;
250
    s<<"if ((groups&"<<(1<<group)<<") != 0)\n";
Peter Eastman's avatar
Peter Eastman committed
251
252
253
254
255
    s<<"for (unsigned int index = get_global_id(0); index < "<<numBonds<<"; index += get_global_size(0)) {\n";
    s<<"    "<<indexType<<" atoms = atomIndices"<<forceIndex<<"[index];\n";
    s<<"    "<<indexType<<" buffers = bufferIndices"<<forceIndex<<"[index];\n";
    for (int i = 0; i < numAtoms; i++) {
        s<<"    unsigned int atom"<<(i+1)<<" = atoms"<<suffix[i]<<";\n";
256
        s<<"    real4 pos"<<(i+1)<<" = posq[atom"<<(i+1)<<"];\n";
Peter Eastman's avatar
Peter Eastman committed
257
258
259
260
    }
    s<<computeForce<<"\n";
    for (int i = 0; i < numAtoms; i++) {
        s<<"    {\n";
261
262
263
264
265
266
267
268
269
270
271
        if (context.getSupports64BitGlobalAtomics()) {
            s<<"    atom_add(&forceBuffers[atom"<<(i+1)<<"], (long) (force"<<(i+1)<<".x*0x100000000));\n";
            s<<"    atom_add(&forceBuffers[atom"<<(i+1)<<"+PADDED_NUM_ATOMS], (long) (force"<<(i+1)<<".y*0x100000000));\n";
            s<<"    atom_add(&forceBuffers[atom"<<(i+1)<<"+2*PADDED_NUM_ATOMS], (long) (force"<<(i+1)<<".z*0x100000000));\n";
        }
        else {
            s<<"    unsigned int offset = atom"<<(i+1)<<"+buffers"<<suffix[i]<<"*PADDED_NUM_ATOMS;\n";
            s<<"    real4 force = forceBuffers[offset];\n";
            s<<"    force.xyz += force"<<(i+1)<<".xyz;\n";
            s<<"    forceBuffers[offset] = force;\n";
        }
Peter Eastman's avatar
Peter Eastman committed
272
273
274
275
276
277
        s<<"    }\n";
    }
    s<<"}\n";
    return s.str();
}

278
void OpenCLBondedUtilities::computeInteractions(int groups) {
peastman's avatar
peastman committed
279
280
    if ((groups&allGroups) == 0)
        return;
Peter Eastman's avatar
Peter Eastman committed
281
282
283
284
285
    if (!hasInitializedKernels) {
        hasInitializedKernels = true;
        for (int i = 0; i < (int) forceSets.size(); i++) {
            int index = 0;
            cl::Kernel& kernel = kernels[i];
286
287
288
289
            if (context.getSupports64BitGlobalAtomics())
                kernel.setArg<cl::Buffer>(index++, context.getLongForceBuffer().getDeviceBuffer());
            else
                kernel.setArg<cl::Buffer>(index++, context.getForceBuffers().getDeviceBuffer());
Peter Eastman's avatar
Peter Eastman committed
290
291
            kernel.setArg<cl::Buffer>(index++, context.getEnergyBuffer().getDeviceBuffer());
            kernel.setArg<cl::Buffer>(index++, context.getPosq().getDeviceBuffer());
292
            index += 6;
Peter Eastman's avatar
Peter Eastman committed
293
294
295
296
297
298
            for (int j = 0; j < (int) forceSets[i].size(); j++) {
                kernel.setArg<cl::Buffer>(index++, atomIndices[forceSets[i][j]]->getDeviceBuffer());
                kernel.setArg<cl::Buffer>(index++, bufferIndices[forceSets[i][j]]->getDeviceBuffer());
            }
            for (int j = 0; j < (int) arguments.size(); j++)
                kernel.setArg<cl::Memory>(index++, *arguments[j]);
299
300
            if (energyParameterDerivatives.size() > 0)
                kernel.setArg<cl::Memory>(index++, context.getEnergyParamDerivBuffer().getDeviceBuffer());
Peter Eastman's avatar
Peter Eastman committed
301
302
        }
    }
303
    for (int i = 0; i < (int) kernels.size(); i++) {
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
        cl::Kernel& kernel = kernels[i];
        kernel.setArg<cl_int>(3, groups);
        if (context.getUseDoublePrecision()) {
            kernel.setArg<mm_double4>(4, context.getPeriodicBoxSizeDouble());
            kernel.setArg<mm_double4>(5, context.getInvPeriodicBoxSizeDouble());
            kernel.setArg<mm_double4>(6, context.getPeriodicBoxVecXDouble());
            kernel.setArg<mm_double4>(7, context.getPeriodicBoxVecYDouble());
            kernel.setArg<mm_double4>(8, context.getPeriodicBoxVecZDouble());
        }
        else {
            kernel.setArg<mm_float4>(4, context.getPeriodicBoxSize());
            kernel.setArg<mm_float4>(5, context.getInvPeriodicBoxSize());
            kernel.setArg<mm_float4>(6, context.getPeriodicBoxVecX());
            kernel.setArg<mm_float4>(7, context.getPeriodicBoxVecY());
            kernel.setArg<mm_float4>(8, context.getPeriodicBoxVecZ());
        }
Peter Eastman's avatar
Peter Eastman committed
320
        context.executeKernel(kernels[i], maxBonds);
321
    }
Peter Eastman's avatar
Peter Eastman committed
322
}