-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathex19_atomic_forces.py
More file actions
500 lines (435 loc) · 18.2 KB
/
ex19_atomic_forces.py
File metadata and controls
500 lines (435 loc) · 18.2 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
import os
from ase.io import read
import mala
from mala import printout
import numpy as np
import torch
from mala.datahandling.data_repo import data_repo_path
data_path = os.path.join(data_repo_path, "Be2")
"""
ex19_at.py: Show how a prediction can be made using MALA.
Using nothing more then the trained network and atomic configurations,
predictions can be made.
"""
# Uses a network to make a prediction.
assert os.path.exists("Be_model.zip"), "Be model missing, run ex01 first."
def run_prediction(backprop=False):
"""
This just runs a regular MALA prediction for a two-atom Beryllium model.
"""
parameters, network, data_handler, predictor = mala.Predictor.load_run(
"Be_model"
)
parameters.targets.target_type = "LDOS"
parameters.targets.ldos_gridsize = 11
parameters.targets.ldos_gridspacing_ev = 2.5
parameters.targets.ldos_gridoffset_ev = -5
parameters.descriptors.descriptor_type = "Bispectrum"
parameters.descriptors.bispectrum_twojmax = 10
parameters.descriptors.bispectrum_cutoff = 4.67637
parameters.targets.pseudopotential_path = data_path
atoms = read(os.path.join(data_path, "Be_snapshot3.out"))
ldos = predictor.predict_for_atoms(atoms, save_grads=backprop)
ldos_calculator: mala.LDOS = predictor.target_calculator
ldos_calculator.read_from_array(ldos)
return ldos, ldos_calculator, parameters, predictor
def band_energy_contribution():
"""
Test the band energy contribution to the forces by calculating it
via finite differences and analytically. This should return arrays of 1s.
Note that the LDOS is only shifted at one point in space, but since the
band energy is a not a spatially resolved quantity, the forces should
be the same for all grid points.
"""
ldos, ldos_calculator, parameters, predictor = run_prediction()
# Only compute a specific part of the forces.
ldos_calculator.debug_forces_flag = "band_energy"
mala_forces = ldos_calculator.atomic_forces.copy()
delta_numerical = 1e-6
numerical_forces = []
for i in range(0, parameters.targets.ldos_gridsize):
ldos_plus = ldos.copy()
ldos_plus[0, i] += delta_numerical * 0.5
ldos_calculator.read_from_array(ldos_plus)
derivative_plus = ldos_calculator.band_energy
ldos_minus = ldos.copy()
ldos_minus[0, i] -= delta_numerical * 0.5
ldos_calculator.read_from_array(ldos_minus)
derivative_minus = ldos_calculator.band_energy
numerical_forces.append(
(derivative_plus - derivative_minus) / delta_numerical
)
print("FORCE TEST: Band energy contribution.")
print(mala_forces[0, :] / np.array(numerical_forces))
print(mala_forces[2000, :] / np.array(numerical_forces))
print(mala_forces[4000, :] / np.array(numerical_forces))
def entropy_contribution():
"""
Test the entropy contribution to the forces by calculating it
via finite differences and analytically. This should return arrays of 1s,
it will most likely not for many test settings due to the fact that the
entropy contribution is VERY small.
Note that the LDOS is only shifted at one point in space, but since the
entropy is a not a spatially resolved quantity, the forces should
be the same for all grid points.
"""
ldos, ldos_calculator, parameters, predictor = run_prediction()
# Only compute a specific part of the forces.
ldos_calculator.debug_forces_flag = "entropy_contribution"
mala_forces = ldos_calculator.atomic_forces.copy()
delta_numerical = 1e-8
numerical_forces = []
for i in range(0, parameters.targets.ldos_gridsize):
ldos_plus = ldos.copy()
ldos_plus[0, i] += delta_numerical * 0.5
ldos_calculator.read_from_array(ldos_plus)
derivative_plus = ldos_calculator.entropy_contribution
ldos_minus = ldos.copy()
ldos_minus[0, i] -= delta_numerical * 0.5
ldos_calculator.read_from_array(ldos_minus)
derivative_minus = ldos_calculator.entropy_contribution
numerical_forces.append(
(derivative_plus - derivative_minus) / delta_numerical
)
print("FORCE TEST: Entropy contribution.")
print(mala_forces[0, :] / np.array(numerical_forces))
print(mala_forces[2000, :] / np.array(numerical_forces))
print(mala_forces[4000, :] / np.array(numerical_forces))
def hartree_contribution():
"""
Test the Hartree contribution to the forces by calculating it
via finite differences and analytically. This should return arrays of 1s.
Since the Hartree energy is dependent on the electronic density, the
derivative will vary across space, and we have to compute the forces
at multiple points.
"""
ldos, ldos_calculator, parameters, predictor = run_prediction()
# Only compute a specific part of the forces.
ldos_calculator.debug_forces_flag = "hartree"
mala_forces = ldos_calculator.atomic_forces.copy()
delta_numerical = 1e-6
points = [0, 2000, 4000]
print("FORCE TEST: Hartree contribution.")
for point in points:
numerical_forces = []
for i in range(0, parameters.targets.ldos_gridsize):
ldos_plus = ldos.copy()
ldos_plus[point, i] += delta_numerical * 0.5
ldos_calculator.read_from_array(ldos_plus)
_, derivative_plus = ldos_calculator.get_total_energy(
return_energy_contributions=True
)
derivative_plus = derivative_plus["e_hartree"]
ldos_minus = ldos.copy()
ldos_minus[point, i] -= delta_numerical * 0.5
ldos_calculator.read_from_array(ldos_minus)
_, derivative_minus = ldos_calculator.get_total_energy(
return_energy_contributions=True
)
derivative_minus = derivative_minus["e_hartree"]
numerical_forces.append(
(derivative_plus - derivative_minus) / delta_numerical
)
print(mala_forces[point, :] / np.array(numerical_forces))
def check_input_gradient_scaling():
# Load a model, set paramters.
predictor: mala.Predictor
parameters: mala.Parameters
parameters, network, data_handler, predictor = mala.Predictor.load_run(
"Be_ACE_model_FULLSCALING"
)
parameters.targets.target_type = "LDOS"
parameters.targets.ldos_gridsize = 11
parameters.targets.ldos_gridspacing_ev = 2.5
parameters.targets.ldos_gridoffset_ev = -5
parameters.targets.restrict_targets = None
parameters.descriptors.descriptors_contain_xyz = False
parameters.descriptors.descriptor_type = "ACE"
# Compute descriptors, only do further computations for one point.
atoms1 = read("/home/fiedlerl/data/mala_data_repo/Be2/Be_snapshot1.out")
descriptors, ngrid = (
predictor.data.descriptor_calculator.calculate_from_atoms(
atoms1, [18, 18, 27]
)
)
snap_descriptors = torch.from_numpy(np.array([descriptors[0, 0, 0]]))
snap_descriptors_work = snap_descriptors.clone()
snap_descriptors = predictor.data.input_data_scaler.transform(
snap_descriptors
)
snap_descriptors.requires_grad = True
# Forward pass through the network.
ldos = network(snap_descriptors)
d_d_d_B = []
# Compute "gradient". This is ACTUALLY the Jacobian matrix, i.e., the one
# we can compare with finite differences.
for i in range(0, 11):
if snap_descriptors.grad is not None:
snap_descriptors.grad.zero_()
ldos[0, i].backward(retain_graph=True)
# d_d_d_B = snap_descriptors.grad.clone()
d_d_d_B.append(
predictor.data.input_data_scaler.inverse_transform_backpropagation(
snap_descriptors.grad.clone()
)
)
# Just for debugging purposes, not part of the actual test.
# if False:
# # This would be the direct application of the autograd.
# # Autograd computes the vector Jacobian product, see
# # https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html
# # Here: compare same_as_sum with d_d_d_B_sum.
# ldos = network(snap_descriptors)
# snap_descriptors.grad.zero_()
# # print(ldos / ldos)
# ldos.backward(ldos / ldos, retain_graph=True)
# same_as_sum = (
# predictor.data.input_data_scaler.inverse_transform_backpropagation(
# snap_descriptors.grad.clone()
# )
# )
# d_d_d_B_sum = d_d_d_B[0]
# for i in range(1, 11):
# d_d_d_B_sum += d_d_d_B[i]
with torch.no_grad():
# In case we want to compare different levels of finite differences.
for diff in [
# 5.0e-1,
# 5.0e-2,
# 5.0e-3,
5.0e-4,
# 5.0e-5,
# 5.0e-6,
]:
# Compute finite differences. j theoretically goes up to
# 36, but for a simple check this is completely enough.
for j in range(0, 5):
snap_descriptors_work[0, j] += diff
descriptors_scaled1 = snap_descriptors_work.clone()
ldos_1 = network(
predictor.data.input_data_scaler.transform(
descriptors_scaled1
)
).clone()
snap_descriptors_work[0, j] -= 2.0 * diff
descriptors_scaled2 = snap_descriptors_work.clone()
ldos_2 = network(
predictor.data.input_data_scaler.transform(
descriptors_scaled2
)
).clone()
# Comparison - we only compare the first component of the
# LDOS for brevity, but this works for all components.
snap_descriptors_work[0, j] += diff
force = -1.0 * ((ldos_2[0, 0] - ldos_1[0, 0]) / (2 * diff))
print(
diff,
force.double().numpy(),
d_d_d_B[0][0, j],
force.double().numpy() / d_d_d_B[0][0, j],
)
def check_output_gradient_scaling():
# Load a model, set paramters.
predictor: mala.Predictor
parameters: mala.Parameters
parameters, network, data_handler, predictor = mala.Predictor.load_run(
"Be_ACE_model_FULLSCALING"
)
parameters.targets.target_type = "LDOS"
parameters.targets.ldos_gridsize = 11
parameters.targets.ldos_gridspacing_ev = 2.5
parameters.targets.ldos_gridoffset_ev = -5
parameters.targets.restrict_targets = None
parameters.descriptors.descriptors_contain_xyz = False
parameters.descriptors.descriptor_type = "ACE"
# Compute descriptors, only do further computations for one point.
atoms1 = read("/home/fiedlerl/data/mala_data_repo/Be2/Be_snapshot1.out")
descriptors, ngrid = (
predictor.data.descriptor_calculator.calculate_from_atoms(
atoms1, [18, 18, 27]
)
)
snap_descriptors = torch.from_numpy(np.array([descriptors[0, 0, 0]]))
snap_descriptors_work = snap_descriptors.clone()
snap_descriptors = predictor.data.input_data_scaler.transform(
snap_descriptors
)
snap_descriptors.requires_grad = True
# Forward pass through the network.
# ldos = network(snap_descriptors)
# d_d_d_B = []
# Compute "gradient". This is ACTUALLY the Jacobian matrix, i.e., the one
# we can compare with finite differences.
# for i in range(0, 11):
# if snap_descriptors.grad is not None:
# snap_descriptors.grad.zero_()
#
# ldos[0, i].backward(retain_graph=True)
# # d_d_d_B = snap_descriptors.grad.clone()
# d_d_d_B.append(
# predictor.data.input_data_scaler.inverse_transform_backpropagation(
# snap_descriptors.grad.clone()
# )
# )
if True:
# This would be the direct application of the autograd.
# Autograd computes the vector Jacobian product, see
# https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html
ldos = network(snap_descriptors)
ldos_unscaled = predictor.data.output_data_scaler.inverse_transform(
ldos, copy=True
)
if snap_descriptors.grad is not None:
snap_descriptors.grad.zero_()
ldos.backward(
predictor.data.output_data_scaler.transform_backpropagation(
2 * ldos_unscaled
),
retain_graph=True,
)
d_d_d_B = (
predictor.data.input_data_scaler.inverse_transform_backpropagation(
snap_descriptors.grad.clone()
)
)
with torch.no_grad():
# In case we want to compare different levels of finite differences.
for diff in [
# 5.0e-1,
# 5.0e-2,
# 5.0e-3,
5.0e-4,
# 5.0e-5,
# 5.0e-6,
]:
# Compute finite differences. j theoretically goes up to
# 36, but for a simple check this is completely enough.
for j in range(0, 5):
snap_descriptors_work[0, j] += diff
descriptors_scaled1 = snap_descriptors_work.clone()
ldos_1 = predictor.data.output_data_scaler.inverse_transform(
network(
predictor.data.input_data_scaler.transform(
descriptors_scaled1
)
).clone()
)
energy_1 = 0
for i in range(0, 11):
energy_1 += ldos_1[0, i] * ldos_1[0, i]
snap_descriptors_work[0, j] -= 2.0 * diff
descriptors_scaled2 = snap_descriptors_work.clone()
ldos_2 = predictor.data.output_data_scaler.inverse_transform(
network(
predictor.data.input_data_scaler.transform(
descriptors_scaled2
)
).clone()
)
energy_2 = 0
for i in range(0, 11):
energy_2 += ldos_2[0, i] * ldos_2[0, i]
# Comparison - we only compare the first component of the
# LDOS for brevity, but this works for all components.
snap_descriptors_work[0, j] += diff
force = -1.0 * ((energy_2 - energy_1) / (2 * diff))
print(
diff,
force.double().numpy(),
d_d_d_B[0, j],
force.double().numpy() / d_d_d_B[0, j],
)
def check_backpropagation():
predictor: mala.Predictor
parameters: mala.Parameters
parameters, network, data_handler, predictor = mala.Predictor.load_run(
"Be_ACE_model_FULLSCALING"
)
parameters.targets.target_type = "LDOS"
parameters.targets.ldos_gridsize = 11
parameters.targets.ldos_gridspacing_ev = 2.5
parameters.targets.ldos_gridoffset_ev = -5
parameters.targets.restrict_targets = None
parameters.descriptors.descriptors_contain_xyz = False
parameters.descriptors.descriptor_type = "ACE"
# Compute descriptors, only do further computations for one point.
atoms1 = read("/home/fiedlerl/data/mala_data_repo/Be2/Be_snapshot1.out")
descriptors, ngrid = (
predictor.data.descriptor_calculator.calculate_from_atoms(
atoms1, [18, 18, 27]
)
)
snap_descriptors = torch.from_numpy(
descriptors.reshape([ngrid, descriptors.shape[-1]])
)
snap_descriptors_work = snap_descriptors.clone()
ldos = predictor.predict_for_atoms(
atoms1,
save_grads=True,
pass_descriptors=[
descriptors,
ngrid,
descriptors.shape[-1],
parameters.descriptors.descriptors_contain_xyz,
],
)
ldos_calculator: mala.LDOS = predictor.target_calculator
ldos_calculator.read_from_array(ldos)
ldos_calculator.read_additional_calculation_data(
os.path.join(data_path, "Be_snapshot1.out")
)
ldos_calculator.debug_forces_flag = "band_energy"
ldos_calculator.setup_for_forces(predictor)
mala_forces = ldos_calculator.atomic_forces.copy()
for point in [0, 2000, 4000]:
for diff in [
# 5.0e-1,
# 5.0e-2,
# 5.0e-3,
5.0e-4,
# 5.0e-5,
# 5.0e-6,
]:
# Compute finite differences. j theoretically goes up to
# 36, but for a simple check this is completely enough.
for j in range(0, 5):
snap_descriptors_work[point, j] += diff
descriptors_scaled1 = snap_descriptors_work.clone()
ldos_1 = predictor.data.output_data_scaler.inverse_transform(
network(
predictor.data.input_data_scaler.transform(
descriptors_scaled1
)
),
as_numpy=True,
).copy()
ldos_calculator.read_from_array(ldos_1)
energy_1 = ldos_calculator.band_energy
snap_descriptors_work[point, j] -= 2.0 * diff
descriptors_scaled2 = snap_descriptors_work.clone()
ldos_2 = predictor.data.output_data_scaler.inverse_transform(
network(
predictor.data.input_data_scaler.transform(
descriptors_scaled2
)
),
as_numpy=True,
).copy()
ldos_calculator.read_from_array(ldos_2)
energy_2 = ldos_calculator.band_energy
# Comparison - we only compare the first component of the
# LDOS for brevity, but this works for all components.
snap_descriptors_work[point, j] += diff
force = -1.0 * ((energy_2 - energy_1) / (2 * diff))
print(
diff,
force,
mala_forces[point, j],
force / mala_forces[point, j],
)
# check_input_gradient_scaling()
# check_output_gradient_scaling()
check_backpropagation()
# band_energy_contribution()
# entropy_contribution()
# hartree_contribution()