-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_energy.py
More file actions
461 lines (392 loc) · 13.5 KB
/
test_energy.py
File metadata and controls
461 lines (392 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import math
import openmm
import os
import pytest
import sire as sr
from loch import GCMCSampler, SoftcoreForm
@pytest.mark.skipif(
"CUDA_VISIBLE_DEVICES" not in os.environ,
reason="Requires CUDA enabled GPU.",
)
@pytest.mark.parametrize("platform", ["cuda", "opencl"])
@pytest.mark.parametrize(
"fixture,softcore_form",
[
("water_box", "zacharias"),
("bpti", "zacharias"),
("sd12", "zacharias"),
("sd12", "taylor"),
],
)
def test_energy(fixture, softcore_form, platform, request):
"""
Test that the RF energy difference agrees with OpenMM.
"""
# Get the fixture.
mols, reference = request.getfixturevalue(fixture)
# Standard lambda schedule.
schedule = sr.cas.LambdaSchedule.standard_morph()
# Set the lambda value.
lambda_value = 0.5
# Create a GCMC sampler.
sampler = GCMCSampler(
mols,
cutoff_type="rf",
cutoff="10 A",
reference=reference,
lambda_schedule=schedule,
lambda_value=lambda_value,
softcore_form=softcore_form,
log_level="debug",
ghost_file=None,
log_file=None,
test=True,
platform=platform,
)
# Build map of extra options for the dynamics object.
dyn_map = {}
if sampler._softcore_form == SoftcoreForm.TAYLOR:
dyn_map["use_taylor_softening"] = True
# Create a dynamics object using the modified GCMC system.
d = sampler.system().dynamics(
cutoff_type="rf",
cutoff="10 A",
temperature="298 K",
pressure=None,
constraint="h_bonds",
timestep="2 fs",
schedule=schedule,
lambda_value=lambda_value,
coulomb_power=sampler._coulomb_power,
shift_coulomb=str(sampler._shift_coulomb),
shift_delta=str(sampler._shift_delta),
platform=platform,
map=dyn_map,
)
# Loop until we accept an insertion move.
is_accepted = False
while not is_accepted:
# Store the initial energy in kcal/mol.
initial_energy = (
d.context()
.getState(getEnergy=True)
.getPotentialEnergy()
.value_in_unit(openmm.unit.kilocalories_per_mole)
)
# Perform a GCMC move.
moves = sampler.move(d.context())
# No moves were made.
if len(moves) == 0:
is_accepted = False
else:
# Deletion move.
if moves[0] != 0:
is_accepted = False
# Insertion move.
else:
is_accepted = True
# Store the final energy in kcal/mol.
final_energy = (
d.context()
.getState(getEnergy=True)
.getPotentialEnergy()
.value_in_unit(openmm.unit.kilocalories_per_mole)
)
# Get the debugging information.
sampler_energy = sampler._debug["energy_coul"] + sampler._debug["energy_lj"]
# Calculate the energy difference.
energy_difference = final_energy - initial_energy
# Check that the energy difference is close to the calculated energy change.
assert math.isclose(energy_difference, sampler_energy, abs_tol=1e-2)
# Loop until we accept a deletion move.
is_accepted = False
while not is_accepted:
# Store the initial energy in kcal/mol.
initial_energy = (
d.context()
.getState(getEnergy=True)
.getPotentialEnergy()
.value_in_unit(openmm.unit.kilocalories_per_mole)
)
# Perform a GCMC move.
moves = sampler.move(d.context())
# No moves were made.
if len(moves) == 0:
is_accepted = False
else:
# Insertion move.
if moves[0] != 1:
is_accepted = False
# Deletion move.
else:
is_accepted = True
# Store the final energy in kcal/mol.
final_energy = (
d.context()
.getState(getEnergy=True)
.getPotentialEnergy()
.value_in_unit(openmm.unit.kilocalories_per_mole)
)
# Get the debugging information.
sampler_energy = sampler._debug["energy_coul"] + sampler._debug["energy_lj"]
# Calculate the energy difference.
energy_difference = final_energy - initial_energy
# Check that the energy difference is close to the calculated energy change.
assert math.isclose(energy_difference, sampler_energy, abs_tol=1e-2)
@pytest.mark.skipif(
"CUDA_VISIBLE_DEVICES" not in os.environ,
reason="Requires CUDA enabled GPU.",
)
@pytest.mark.parametrize("fixture", ["water_box", "bpti", "sd12"])
def test_platform_consistency(fixture, request):
"""
Test that CUDA and OpenCL platforms produce consistent energy calculations.
"""
# Get the fixture.
mols, reference = request.getfixturevalue(fixture)
# Standard lambda schedule.
schedule = sr.cas.LambdaSchedule.standard_morph()
# Set the lambda value.
lambda_value = 0.5
# Use a fixed seed for reproducibility
seed = 42
# Create CUDA sampler.
cuda_sampler = GCMCSampler(
mols,
cutoff_type="rf",
cutoff="10 A",
reference=reference,
lambda_schedule=schedule,
lambda_value=lambda_value,
log_level="debug",
ghost_file=None,
log_file=None,
test=True,
platform="cuda",
seed=seed,
)
# Create OpenCL sampler with same configuration.
opencl_sampler = GCMCSampler(
mols,
cutoff_type="rf",
cutoff="10 A",
reference=reference,
lambda_schedule=schedule,
lambda_value=lambda_value,
log_level="debug",
ghost_file=None,
log_file=None,
test=True,
platform="opencl",
seed=seed,
)
# Perform insertion moves on both samplers.
# With same seed, both platforms should generate identical random numbers
# and thus identical water positions, allowing direct energy comparison.
# Create dynamics objects for both.
cuda_d = cuda_sampler.system().dynamics(
cutoff_type="rf",
cutoff="10 A",
temperature="298 K",
pressure=None,
constraint="h_bonds",
timestep="2 fs",
schedule=schedule,
lambda_value=lambda_value,
coulomb_power=cuda_sampler._coulomb_power,
shift_coulomb=str(cuda_sampler._shift_coulomb),
shift_delta=str(cuda_sampler._shift_delta),
platform="cuda",
)
opencl_d = opencl_sampler.system().dynamics(
cutoff_type="rf",
cutoff="10 A",
temperature="298 K",
pressure=None,
constraint="h_bonds",
timestep="2 fs",
schedule=schedule,
lambda_value=lambda_value,
coulomb_power=opencl_sampler._coulomb_power,
shift_coulomb=str(opencl_sampler._shift_coulomb),
shift_delta=str(opencl_sampler._shift_delta),
platform="opencl",
)
# Perform moves until we get an accepted insertion on CUDA.
is_accepted = False
while not is_accepted:
moves = cuda_sampler.move(cuda_d.context())
if len(moves) > 0 and moves[0] == 0:
is_accepted = True
# Get CUDA energy calculation.
cuda_energy = cuda_sampler._debug["energy_coul"] + cuda_sampler._debug["energy_lj"]
# Perform moves until we get an accepted insertion on OpenCL.
is_accepted = False
while not is_accepted:
moves = opencl_sampler.move(opencl_d.context())
if len(moves) > 0 and moves[0] == 0:
is_accepted = True
# Get OpenCL energy calculation.
opencl_energy = (
opencl_sampler._debug["energy_coul"] + opencl_sampler._debug["energy_lj"]
)
# With same seed, the water positions should be identical, so energies
# should match closely. Allow small tolerance for floating point differences.
assert math.isfinite(cuda_energy), "CUDA energy is not finite"
assert math.isfinite(opencl_energy), "OpenCL energy is not finite"
# Energy calculations should be very close (within 0.1%)
relative_diff = abs(cuda_energy - opencl_energy) / max(
abs(cuda_energy), abs(opencl_energy), 1.0
)
assert relative_diff < 0.001, (
f"Platform energies differ: CUDA={cuda_energy:.6f}, OpenCL={opencl_energy:.6f}, relative_diff={relative_diff:.6f}"
)
# Reference energy values captured with seed=42 on the original kernel implementation.
# These anchor the kernel output to exact values so that refactors (e.g. moving from
# __device__ static arrays to buffer arguments) can be validated.
_REFERENCE_ENERGIES = {
"water_box": {
"energy_coul": -9.45853172201302,
"energy_lj": 3.2191088,
},
"bpti": {
"energy_coul": -15.377882774621897,
"energy_lj": -0.58867246,
},
}
@pytest.mark.skipif(
"CUDA_VISIBLE_DEVICES" not in os.environ,
reason="Requires CUDA enabled GPU.",
)
@pytest.mark.parametrize("platform", ["cuda", "opencl"])
@pytest.mark.parametrize("fixture", ["water_box", "bpti"])
def test_energy_regression(fixture, platform, request):
"""
Test that kernel energy values are unchanged for a fixed random seed.
This catches silent numerical changes introduced by kernel refactors.
"""
# Get the fixture.
mols, reference = request.getfixturevalue(fixture)
# Standard lambda schedule.
schedule = sr.cas.LambdaSchedule.standard_morph()
# Set the lambda value.
lambda_value = 0.5
# Create a GCMC sampler with a fixed seed.
sampler = GCMCSampler(
mols,
cutoff_type="rf",
cutoff="10 A",
reference=reference,
lambda_schedule=schedule,
lambda_value=lambda_value,
log_level="debug",
ghost_file=None,
log_file=None,
test=True,
platform=platform,
seed=42,
)
# Create a dynamics object.
d = sampler.system().dynamics(
cutoff_type="rf",
cutoff="10 A",
temperature="298 K",
pressure=None,
constraint="h_bonds",
timestep="2 fs",
schedule=schedule,
lambda_value=lambda_value,
coulomb_power=sampler._coulomb_power,
shift_coulomb=str(sampler._shift_coulomb),
shift_delta=str(sampler._shift_delta),
platform=platform,
)
# Loop until we get an accepted insertion move.
is_accepted = False
while not is_accepted:
moves = sampler.move(d.context())
if len(moves) > 0 and moves[0] == 0:
is_accepted = True
# Get the energy components.
energy_coul = sampler._debug["energy_coul"]
energy_lj = sampler._debug["energy_lj"]
# Check against reference values.
ref = _REFERENCE_ENERGIES[fixture]
assert math.isclose(energy_coul, ref["energy_coul"], abs_tol=1e-4), (
f"Coulomb energy changed: {energy_coul!r} != {ref['energy_coul']!r}"
)
assert math.isclose(energy_lj, ref["energy_lj"], abs_tol=1e-4), (
f"LJ energy changed: {energy_lj!r} != {ref['energy_lj']!r}"
)
@pytest.mark.skipif(
"CUDA_VISIBLE_DEVICES" not in os.environ,
reason="Requires CUDA enabled GPU.",
)
@pytest.mark.parametrize("platform", ["cuda", "opencl"])
def test_cached_kernel_correctness(platform, water_box):
"""
A second sampler using cached kernels must produce the same energies
as the first.
"""
mols, reference = water_box
schedule = sr.cas.LambdaSchedule.standard_morph()
def _create_and_run(seed):
sampler = GCMCSampler(
mols,
cutoff_type="rf",
cutoff="10 A",
reference=reference,
lambda_schedule=schedule,
lambda_value=0.5,
log_level="debug",
ghost_file=None,
log_file=None,
test=True,
platform=platform,
seed=seed,
)
d = sampler.system().dynamics(
cutoff_type="rf",
cutoff="10 A",
temperature="298 K",
pressure=None,
constraint="h_bonds",
timestep="2 fs",
schedule=schedule,
lambda_value=0.5,
coulomb_power=sampler._coulomb_power,
shift_coulomb=str(sampler._shift_coulomb),
shift_delta=str(sampler._shift_delta),
platform=platform,
)
is_accepted = False
while not is_accepted:
moves = sampler.move(d.context())
if len(moves) > 0 and moves[0] == 0:
is_accepted = True
return sampler
# Clear the cache so the first sampler compiles from source.
if platform == "cuda":
from loch._platforms._cuda import CUDAPlatform
CUDAPlatform.clear_cache()
else:
from loch._platforms._opencl import OpenCLPlatform
OpenCLPlatform.clear_cache()
# First sampler compiles kernels, second uses the cache.
# Both use the same seed so random water positions are identical.
sampler1 = _create_and_run(seed=42)
sampler2 = _create_and_run(seed=42)
# Verify cache behaviour.
assert not sampler1._kernel_cache_hit, "First sampler should compile from source"
assert sampler2._kernel_cache_hit, "Second sampler should use cached kernels"
# Verify energy consistency.
energy1_coul = sampler1._debug["energy_coul"]
energy1_lj = sampler1._debug["energy_lj"]
energy2_coul = sampler2._debug["energy_coul"]
energy2_lj = sampler2._debug["energy_lj"]
assert math.isclose(energy1_coul, energy2_coul, abs_tol=1e-4), (
f"Coulomb energy mismatch: {energy1_coul!r} vs {energy2_coul!r}"
)
assert math.isclose(energy1_lj, energy2_lj, abs_tol=1e-4), (
f"LJ energy mismatch: {energy1_lj!r} vs {energy2_lj!r}"
)