OpenCLPlatform.cpp 15.2 KB
Newer Older
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.               *
 *                                                                            *
Peter Eastman's avatar
Peter Eastman committed
9
 * Portions copyright (c) 2008-2025 Stanford University and the Authors.      *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 * 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 "OpenCLContext.h"
#include "OpenCLPlatform.h"
#include "OpenCLKernelFactory.h"
#include "OpenCLKernels.h"
#include "openmm/Context.h"
#include "openmm/System.h"
33
34
#include "openmm/internal/ContextImpl.h"
#include "openmm/internal/hardware.h"
35
#include <algorithm>
36
#include <cctype>
37
#include <sstream>
38
39
40
41
#ifdef __APPLE__
#include "sys/sysctl.h"
#endif

42
43

using namespace OpenMM;
44
using namespace std;
45

46
#ifdef OPENMM_COMMON_BUILDING_STATIC_LIBRARY
47
extern "C" void registerOpenCLPlatform() {
48
49
    if (OpenCLPlatform::isPlatformSupported())
        Platform::registerPlatform(new OpenCLPlatform());
50
51
}
#else
52
extern "C" OPENMM_EXPORT_COMMON void registerPlatforms() {
53
54
    if (OpenCLPlatform::isPlatformSupported())
        Platform::registerPlatform(new OpenCLPlatform());
55
}
56
#endif
57
58

OpenCLPlatform::OpenCLPlatform() {
Peter Eastman's avatar
Peter Eastman committed
59
60
61
62
63
    deprecatedPropertyReplacements["OpenCLDeviceIndex"] = OpenCLDeviceIndex();
    deprecatedPropertyReplacements["OpenCLDeviceName"] = OpenCLDeviceName();
    deprecatedPropertyReplacements["OpenCLPrecision"] = OpenCLPrecision();
    deprecatedPropertyReplacements["OpenCLUseCpuPme"] = OpenCLUseCpuPme();
    deprecatedPropertyReplacements["OpenCLDisablePmeStream"] = OpenCLDisablePmeStream();
64
    OpenCLKernelFactory* factory = new OpenCLKernelFactory();
65
    registerKernelFactory(CalcForcesAndEnergyKernel::Name(), factory);
66
    registerKernelFactory(UpdateStateDataKernel::Name(), factory);
67
    registerKernelFactory(ApplyConstraintsKernel::Name(), factory);
68
    registerKernelFactory(VirtualSitesKernel::Name(), factory);
69
    registerKernelFactory(CalcHarmonicBondForceKernel::Name(), factory);
70
    registerKernelFactory(CalcCustomBondForceKernel::Name(), factory);
71
    registerKernelFactory(CalcHarmonicAngleForceKernel::Name(), factory);
72
    registerKernelFactory(CalcCustomAngleForceKernel::Name(), factory);
73
    registerKernelFactory(CalcPeriodicTorsionForceKernel::Name(), factory);
74
    registerKernelFactory(CalcRBTorsionForceKernel::Name(), factory);
75
    registerKernelFactory(CalcCMAPTorsionForceKernel::Name(), factory);
76
    registerKernelFactory(CalcCustomTorsionForceKernel::Name(), factory);
77
    registerKernelFactory(CalcNonbondedForceKernel::Name(), factory);
78
    registerKernelFactory(CalcCustomNonbondedForceKernel::Name(), factory);
79
    registerKernelFactory(CalcGBSAOBCForceKernel::Name(), factory);
80
    registerKernelFactory(CalcCustomGBForceKernel::Name(), factory);
81
    registerKernelFactory(CalcCustomExternalForceKernel::Name(), factory);
82
    registerKernelFactory(CalcCustomHbondForceKernel::Name(), factory);
83
    registerKernelFactory(CalcCustomCentroidBondForceKernel::Name(), factory);
84
    registerKernelFactory(CalcCustomCompoundBondForceKernel::Name(), factory);
85
    registerKernelFactory(CalcCustomCPPForceKernel::Name(), factory);
86
    registerKernelFactory(CalcCustomCVForceKernel::Name(), factory);
87
    registerKernelFactory(CalcATMForceKernel::Name(), factory);
peastman's avatar
peastman committed
88
    registerKernelFactory(CalcRMSDForceKernel::Name(), factory);
89
    registerKernelFactory(CalcCustomManyParticleForceKernel::Name(), factory);
90
    registerKernelFactory(CalcGayBerneForceKernel::Name(), factory);
91
    registerKernelFactory(IntegrateVerletStepKernel::Name(), factory);
92
    registerKernelFactory(IntegrateNoseHooverStepKernel::Name(), factory);
93
    registerKernelFactory(IntegrateLangevinMiddleStepKernel::Name(), factory);
94
    registerKernelFactory(IntegrateBrownianStepKernel::Name(), factory);
95
96
    registerKernelFactory(IntegrateVariableVerletStepKernel::Name(), factory);
    registerKernelFactory(IntegrateVariableLangevinStepKernel::Name(), factory);
97
    registerKernelFactory(IntegrateCustomStepKernel::Name(), factory);
Peter Eastman's avatar
Peter Eastman committed
98
    registerKernelFactory(IntegrateDPDStepKernel::Name(), factory);
99
    registerKernelFactory(ApplyAndersenThermostatKernel::Name(), factory);
100
    registerKernelFactory(ApplyMonteCarloBarostatKernel::Name(), factory);
101
    registerKernelFactory(RemoveCMMotionKernel::Name(), factory);
102
    platformProperties.push_back(OpenCLDeviceIndex());
103
    platformProperties.push_back(OpenCLDeviceName());
104
    platformProperties.push_back(OpenCLPlatformIndex());
105
    platformProperties.push_back(OpenCLPlatformName());
106
    platformProperties.push_back(OpenCLPrecision());
107
    platformProperties.push_back(OpenCLUseCpuPme());
108
    platformProperties.push_back(OpenCLDisablePmeStream());
109
    setPropertyDefaultValue(OpenCLDeviceIndex(), "");
110
    setPropertyDefaultValue(OpenCLDeviceName(), "");
111
    setPropertyDefaultValue(OpenCLPlatformIndex(), "");
112
    setPropertyDefaultValue(OpenCLPlatformName(), "");
113
    setPropertyDefaultValue(OpenCLPrecision(), "single");
114
    setPropertyDefaultValue(OpenCLUseCpuPme(), "false");
115
    setPropertyDefaultValue(OpenCLDisablePmeStream(), "false");
116
117
}

118
119
120
121
double OpenCLPlatform::getSpeed() const {
    return 50;
}

122
bool OpenCLPlatform::supportsDoublePrecision() const {
Peter Eastman's avatar
Peter Eastman committed
123
    return true;
124
125
}

126
127
bool OpenCLPlatform::isPlatformSupported() {
    // Return false for OpenCL implementations that are known
128
    // to be buggy (Apple OS X prior to 10.10).
129
130
131
132
133
134
135
136
137
138
139
140

#ifdef __APPLE__
    char str[256];
    size_t size = sizeof(str);
    int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);
    if (ret != 0)
        return false;

    int major, minor, micro;
    if (sscanf(str, "%d.%d.%d", &major, &minor, &micro) != 3)
        return false;

141
142
    if (major < 14 || (major == 14 && minor < 3))
        // 14.3.0 is the darwin release corresponding to OS X 10.10.3. Versions prior to that
143
144
        // contained a number of serious bugs in the Apple OpenCL libraries.
        // (See https://github.com/SimTk/openmm/issues/395 for example.)
145
146
147
        return false;
#endif

148
149
150
    // Make sure at least one OpenCL implementation is installed.

    std::vector<cl::Platform> platforms;
151
152
153
154
155
156
    try {
        cl::Platform::get(&platforms);
        if (platforms.size() == 0)
            return false;
    }
    catch (...) {
157
        return false;
158
    }
159
160
161
    return true;
}

162
163
164
const string& OpenCLPlatform::getPropertyValue(const Context& context, const string& property) const {
    const ContextImpl& impl = getContextImpl(context);
    const PlatformData* data = reinterpret_cast<const PlatformData*>(impl.getPlatformData());
165
166
167
168
    string propertyName = property;
    if (deprecatedPropertyReplacements.find(property) != deprecatedPropertyReplacements.end())
        propertyName = deprecatedPropertyReplacements.find(property)->second;
    map<string, string>::const_iterator value = data->propertyValues.find(propertyName);
169
170
171
172
173
174
175
176
    if (value != data->propertyValues.end())
        return value->second;
    return Platform::getPropertyValue(context, property);
}

void OpenCLPlatform::setPropertyValue(Context& context, const string& property, const string& value) const {
}

177
void OpenCLPlatform::contextCreated(ContextImpl& context, const map<string, string>& properties) const {
178
179
    const string& platformPropValue = (properties.find(OpenCLPlatformIndex()) == properties.end() ?
            getPropertyDefaultValue(OpenCLPlatformIndex()) : properties.find(OpenCLPlatformIndex())->second);
180
181
    const string& devicePropValue = (properties.find(OpenCLDeviceIndex()) == properties.end() ?
            getPropertyDefaultValue(OpenCLDeviceIndex()) : properties.find(OpenCLDeviceIndex())->second);
182
183
    string precisionPropValue = (properties.find(OpenCLPrecision()) == properties.end() ?
            getPropertyDefaultValue(OpenCLPrecision()) : properties.find(OpenCLPrecision())->second);
184
185
    string cpuPmePropValue = (properties.find(OpenCLUseCpuPme()) == properties.end() ?
            getPropertyDefaultValue(OpenCLUseCpuPme()) : properties.find(OpenCLUseCpuPme())->second);
186
187
    string pmeStreamPropValue = (properties.find(OpenCLDisablePmeStream()) == properties.end() ?
            getPropertyDefaultValue(OpenCLDisablePmeStream()) : properties.find(OpenCLDisablePmeStream())->second);
188
189
    transform(precisionPropValue.begin(), precisionPropValue.end(), precisionPropValue.begin(), ::tolower);
    transform(cpuPmePropValue.begin(), cpuPmePropValue.end(), cpuPmePropValue.begin(), ::tolower);
190
    transform(pmeStreamPropValue.begin(), pmeStreamPropValue.end(), pmeStreamPropValue.begin(), ::tolower);
191
192
193
194
    vector<string> pmeKernelName;
    pmeKernelName.push_back(CalcPmeReciprocalForceKernel::Name());
    if (!supportsKernels(pmeKernelName))
        cpuPmePropValue = "false";
195
196
197
198
    int threads = getNumProcessors();
    char* threadsEnv = getenv("OPENMM_CPU_THREADS");
    if (threadsEnv != NULL)
        stringstream(threadsEnv) >> threads;
199
    context.setPlatformData(new PlatformData(context.getSystem(), &context, platformPropValue, devicePropValue, precisionPropValue, cpuPmePropValue,
200
201
202
203
204
205
206
207
208
209
210
            pmeStreamPropValue, threads, NULL));
}

void OpenCLPlatform::linkedContextCreated(ContextImpl& context, ContextImpl& originalContext) const {
    Platform& platform = originalContext.getPlatform();
    string platformPropValue = platform.getPropertyValue(originalContext.getOwner(), OpenCLPlatformIndex());
    string devicePropValue = platform.getPropertyValue(originalContext.getOwner(), OpenCLDeviceIndex());
    string precisionPropValue = platform.getPropertyValue(originalContext.getOwner(), OpenCLPrecision());
    string cpuPmePropValue = platform.getPropertyValue(originalContext.getOwner(), OpenCLUseCpuPme());
    string pmeStreamPropValue = platform.getPropertyValue(originalContext.getOwner(), OpenCLDisablePmeStream());
    int threads = reinterpret_cast<PlatformData*>(originalContext.getPlatformData())->threads.getNumThreads();
211
    context.setPlatformData(new PlatformData(context.getSystem(), &context, platformPropValue, devicePropValue, precisionPropValue, cpuPmePropValue,
212
            pmeStreamPropValue, threads, &originalContext));
213
214
215
216
217
218
219
}

void OpenCLPlatform::contextDestroyed(ContextImpl& context) const {
    PlatformData* data = reinterpret_cast<PlatformData*>(context.getPlatformData());
    delete data;
}

220
OpenCLPlatform::PlatformData::PlatformData(const System& system, ContextImpl* context, const string& platformPropValue, const string& deviceIndexProperty,
221
        const string& precisionProperty, const string& cpuPmeProperty, const string& pmeStreamProperty, int numThreads, ContextImpl* originalContext) :
222
            context(context), removeCM(false), stepCount(0), computeForceCount(0), time(0.0), hasInitializedContexts(false), threads(numThreads)  {
Robert McGibbon's avatar
Robert McGibbon committed
223
    int platformIndex = -1;
224
225
    if (platformPropValue.length() > 0)
        stringstream(platformPropValue) >> platformIndex;
226
227
    vector<string> devices;
    size_t searchPos = 0, nextPos;
228
    while ((nextPos = deviceIndexProperty.find_first_of(", ", searchPos)) != string::npos) {
229
230
231
232
        devices.push_back(deviceIndexProperty.substr(searchPos, nextPos-searchPos));
        searchPos = nextPos+1;
    }
    devices.push_back(deviceIndexProperty.substr(searchPos));
233
234
235
    PlatformData* originalData = NULL;
    if (originalContext != NULL)
        originalData = reinterpret_cast<PlatformData*>(originalContext->getPlatformData());
236
237
238
    try {
        for (int i = 0; i < (int) devices.size(); i++) {
            if (devices[i].length() > 0) {
peastman's avatar
peastman committed
239
                int deviceIndex;
240
                stringstream(devices[i]) >> deviceIndex;
241
                contexts.push_back(new OpenCLContext(system, platformIndex, deviceIndex, precisionProperty, *this, (originalData == NULL ? NULL : originalData->contexts[i])));
242
            }
243
        }
244
        if (contexts.size() == 0)
245
            contexts.push_back(new OpenCLContext(system, platformIndex, -1, precisionProperty, *this, (originalData == NULL ? NULL : originalData->contexts[0])));
246
247
248
249
250
251
252
    }
    catch (...) {
        // If an exception was thrown, do our best to clean up memory.
        
        for (int i = 0; i < (int) contexts.size(); i++)
            delete contexts[i];
        throw;
253
    }
254
    stringstream deviceIndex, deviceName;
255
    for (int i = 0; i < (int) contexts.size(); i++) {
256
257
258
259
260
261
        if (i > 0) {
            deviceIndex << ',';
            deviceName << ',';
        }
        deviceIndex << contexts[i]->getDeviceIndex();
        deviceName << contexts[i]->getDevice().getInfo<CL_DEVICE_NAME>();
262
    }
Robert McGibbon's avatar
Robert McGibbon committed
263
264
    platformIndex = contexts[0]->getPlatformIndex();

265
    useCpuPme = (cpuPmeProperty == "true" && !contexts[0]->getUseDoublePrecision());
266
    disablePmeStream = (pmeStreamProperty == "true");
267
268
    propertyValues[OpenCLPlatform::OpenCLDeviceIndex()] = deviceIndex.str();
    propertyValues[OpenCLPlatform::OpenCLDeviceName()] = deviceName.str();
269
    propertyValues[OpenCLPlatform::OpenCLPlatformIndex()] = contexts[0]->intToString(platformIndex);
270
271
272
    std::vector<cl::Platform> platforms;
    cl::Platform::get(&platforms);
    propertyValues[OpenCLPlatform::OpenCLPlatformName()] = platforms[platformIndex].getInfo<CL_PLATFORM_NAME>();
273
    propertyValues[OpenCLPlatform::OpenCLPrecision()] = precisionProperty;
274
    propertyValues[OpenCLPlatform::OpenCLUseCpuPme()] = useCpuPme ? "true" : "false";
275
    propertyValues[OpenCLPlatform::OpenCLDisablePmeStream()] = disablePmeStream ? "true" : "false";
276
    contextEnergy.resize(contexts.size());
277
}
278
279

OpenCLPlatform::PlatformData::~PlatformData() {
280
281
282
283
284
    for (int i = 0; i < (int) contexts.size(); i++)
        delete contexts[i];
}

void OpenCLPlatform::PlatformData::initializeContexts(const System& system) {
285
286
    if (hasInitializedContexts)
        return;
287
    for (int i = 0; i < (int) contexts.size(); i++)
288
        contexts[i]->initialize();
289
    hasInitializedContexts = true;
290
}
291
292
293
294
295

void OpenCLPlatform::PlatformData::syncContexts() {
    for (int i = 0; i < (int) contexts.size(); i++)
        contexts[i]->getWorkThread().flush();
}