GO-Diff 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- go_diff/__init__.py +3 -0
- go_diff/controllers/__init__.py +4 -0
- go_diff/controllers/buffer.py +89 -0
- go_diff/controllers/sample.py +98 -0
- go_diff/controllers/temperature.py +116 -0
- go_diff/controllers/training.py +407 -0
- go_diff/filter.py +70 -0
- go_diff/go_diff.py +751 -0
- go_diff/logger.py +453 -0
- go_diff/noisers/__init__.py +1 -0
- go_diff/noisers/weighted_pos.py +59 -0
- go_diff/utils.py +50 -0
- go_diff-1.0.0.dist-info/METADATA +153 -0
- go_diff-1.0.0.dist-info/RECORD +16 -0
- go_diff-1.0.0.dist-info/WHEEL +4 -0
- go_diff-1.0.0.dist-info/licenses/LICENSE +674 -0
go_diff/logger.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from collections import defaultdict
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import matplotlib
|
|
7
|
+
matplotlib.use("Agg")
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import seaborn as sns
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GODiffLogger:
|
|
13
|
+
"""
|
|
14
|
+
TensorBoard logger for GO-Diff run metrics.
|
|
15
|
+
|
|
16
|
+
Logs metrics at two granularities:
|
|
17
|
+
|
|
18
|
+
* **Iteration level** – one entry per GO-Diff outer loop iteration
|
|
19
|
+
(temperature, energy statistics, buffer/data sizes, ESS, heat capacity).
|
|
20
|
+
* **Training-step level** – one entry per Lightning training step for
|
|
21
|
+
gradient-agreement tracking (written from the training controller
|
|
22
|
+
callback via :py:meth:`log_training_step`).
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
----------
|
|
26
|
+
writer : torch.utils.tensorboard.SummaryWriter
|
|
27
|
+
The underlying TensorBoard writer, typically obtained from a
|
|
28
|
+
Lightning ``TensorBoardLogger`` via ``trainer.logger.experiment``.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(self, writer):
|
|
32
|
+
self.writer = writer
|
|
33
|
+
self._cumulative_wall_s = 0.0
|
|
34
|
+
# History for cumulative analysis plots
|
|
35
|
+
self._best_energy_history = [] # list of (n_total, best_energy)
|
|
36
|
+
self._buffer_history = [] # list of (temperature, buffer_energies ndarray)
|
|
37
|
+
self._landscape_history = [] # list of (step, min, mean, std)
|
|
38
|
+
|
|
39
|
+
# ------------------------------------------------------------------
|
|
40
|
+
# Internal helpers
|
|
41
|
+
# ------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def _max_force_norm(forces, idx):
|
|
45
|
+
"""Return the maximum per-atom force norm for structure at *idx*.
|
|
46
|
+
|
|
47
|
+
Returns ``None`` when *forces* is empty or does not contain the index.
|
|
48
|
+
"""
|
|
49
|
+
if len(forces) > idx and forces[idx] is not None:
|
|
50
|
+
return float(np.max(np.linalg.norm(forces[idx], axis=-1)))
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
# ------------------------------------------------------------------
|
|
54
|
+
# Iteration-level logging
|
|
55
|
+
# ------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
def log_iteration(
|
|
58
|
+
self,
|
|
59
|
+
step,
|
|
60
|
+
*,
|
|
61
|
+
temperature,
|
|
62
|
+
new_energies,
|
|
63
|
+
new_forces,
|
|
64
|
+
all_energies,
|
|
65
|
+
all_forces,
|
|
66
|
+
buffer_energies,
|
|
67
|
+
buffer_forces,
|
|
68
|
+
ess=None,
|
|
69
|
+
ess_ratio=None,
|
|
70
|
+
heat_capacity=None,
|
|
71
|
+
iteration_wall_s=None,
|
|
72
|
+
sampling_wall_s=None,
|
|
73
|
+
evaluation_wall_s=None,
|
|
74
|
+
training_wall_s=None,
|
|
75
|
+
):
|
|
76
|
+
"""Log all important metrics for a single GO-Diff iteration.
|
|
77
|
+
|
|
78
|
+
Parameters
|
|
79
|
+
----------
|
|
80
|
+
step : int
|
|
81
|
+
Iteration index (used as the TensorBoard global step).
|
|
82
|
+
temperature : float
|
|
83
|
+
Current annealing temperature.
|
|
84
|
+
new_energies : array-like
|
|
85
|
+
Energies of structures sampled in this iteration.
|
|
86
|
+
new_forces : list of np.ndarray
|
|
87
|
+
Forces on each structure sampled in this iteration.
|
|
88
|
+
all_energies : array-like
|
|
89
|
+
Energies of all structures accumulated so far.
|
|
90
|
+
all_forces : list of np.ndarray
|
|
91
|
+
Forces on all accumulated structures.
|
|
92
|
+
buffer_energies : array-like
|
|
93
|
+
Energies of structures selected into the replay buffer.
|
|
94
|
+
buffer_forces : list of np.ndarray
|
|
95
|
+
Forces on buffer structures.
|
|
96
|
+
ess : float or None
|
|
97
|
+
Effective Sample Size computed over the new samples.
|
|
98
|
+
ess_ratio : float or None
|
|
99
|
+
ESS / n_new_samples ratio.
|
|
100
|
+
heat_capacity : float or None
|
|
101
|
+
Dimensionless heat capacity C(T) = Var(E) / T^2.
|
|
102
|
+
iteration_wall_s : float or None
|
|
103
|
+
Total wall-clock time (seconds) for the full iteration
|
|
104
|
+
(sampling + evaluation + training).
|
|
105
|
+
sampling_wall_s : float or None
|
|
106
|
+
Wall-clock time (seconds) spent in diffusion model inference.
|
|
107
|
+
evaluation_wall_s : float or None
|
|
108
|
+
Wall-clock time (seconds) spent calling the energy/force calculator.
|
|
109
|
+
training_wall_s : float or None
|
|
110
|
+
Wall-clock time (seconds) spent in model training.
|
|
111
|
+
"""
|
|
112
|
+
w = self.writer
|
|
113
|
+
|
|
114
|
+
# --- temperature ---
|
|
115
|
+
w.add_scalar("iteration/temperature", temperature, step)
|
|
116
|
+
|
|
117
|
+
# --- new samples this iteration ---
|
|
118
|
+
new_energies = np.asarray(new_energies) if len(new_energies) > 0 else np.array([])
|
|
119
|
+
n_new = len(new_energies)
|
|
120
|
+
w.add_scalar("iteration/n_new_samples", n_new, step)
|
|
121
|
+
if n_new > 0:
|
|
122
|
+
w.add_scalar("iteration/new_min_energy", float(np.min(new_energies)), step)
|
|
123
|
+
w.add_scalar("iteration/new_mean_energy", float(np.mean(new_energies)), step)
|
|
124
|
+
w.add_scalar("iteration/new_energy_std", float(np.std(new_energies)), step)
|
|
125
|
+
|
|
126
|
+
# Max force norm of best new structure (proxy for relaxation quality)
|
|
127
|
+
best_new_idx = int(np.argmin(new_energies))
|
|
128
|
+
best_new_max_force = self._max_force_norm(new_forces, best_new_idx)
|
|
129
|
+
if best_new_max_force is not None:
|
|
130
|
+
w.add_scalar(
|
|
131
|
+
"iteration/new_best_energy_max_force", best_new_max_force, step
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
# --- accumulated / total data ---
|
|
135
|
+
all_energies = np.asarray(all_energies) if len(all_energies) > 0 else np.array([])
|
|
136
|
+
n_total = len(all_energies)
|
|
137
|
+
w.add_scalar("iteration/total_data", n_total, step)
|
|
138
|
+
if n_total > 0:
|
|
139
|
+
best_idx = int(np.argmin(all_energies))
|
|
140
|
+
best_energy = float(all_energies[best_idx])
|
|
141
|
+
w.add_scalar("iteration/best_energy", best_energy, step)
|
|
142
|
+
w.add_scalar("iteration/mean_energy", float(np.mean(all_energies)), step)
|
|
143
|
+
w.add_scalar(
|
|
144
|
+
"iteration/energy_std", float(np.std(all_energies)), step
|
|
145
|
+
)
|
|
146
|
+
w.add_scalar(
|
|
147
|
+
"iteration/energy_variance", float(np.var(all_energies)), step
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# Max force norm of the globally best structure
|
|
151
|
+
best_max_force = self._max_force_norm(all_forces, best_idx)
|
|
152
|
+
if best_max_force is not None:
|
|
153
|
+
w.add_scalar(
|
|
154
|
+
"iteration/best_energy_max_force", best_max_force, step
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# --- buffer ---
|
|
158
|
+
buffer_energies = (
|
|
159
|
+
np.asarray(buffer_energies) if len(buffer_energies) > 0 else np.array([])
|
|
160
|
+
)
|
|
161
|
+
w.add_scalar("iteration/buffer_size", len(buffer_energies), step)
|
|
162
|
+
if len(buffer_energies) > 0:
|
|
163
|
+
w.add_scalar(
|
|
164
|
+
"iteration/buffer_best_energy", float(np.min(buffer_energies)), step
|
|
165
|
+
)
|
|
166
|
+
w.add_scalar(
|
|
167
|
+
"iteration/buffer_mean_energy", float(np.mean(buffer_energies)), step
|
|
168
|
+
)
|
|
169
|
+
w.add_scalar(
|
|
170
|
+
"iteration/buffer_energy_std", float(np.std(buffer_energies)), step
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# Max force norm of buffer's best structure
|
|
174
|
+
if len(buffer_forces) > 0:
|
|
175
|
+
buf_best_idx = int(np.argmin(buffer_energies))
|
|
176
|
+
buf_best_max_force = self._max_force_norm(buffer_forces, buf_best_idx)
|
|
177
|
+
if buf_best_max_force is not None:
|
|
178
|
+
w.add_scalar(
|
|
179
|
+
"iteration/buffer_best_energy_max_force",
|
|
180
|
+
buf_best_max_force,
|
|
181
|
+
step,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# --- ESS ---
|
|
185
|
+
if ess is not None:
|
|
186
|
+
w.add_scalar("iteration/ess", float(ess), step)
|
|
187
|
+
if ess_ratio is not None:
|
|
188
|
+
w.add_scalar("iteration/ess_ratio", float(ess_ratio), step)
|
|
189
|
+
|
|
190
|
+
# --- heat capacity ---
|
|
191
|
+
if heat_capacity is not None:
|
|
192
|
+
w.add_scalar("iteration/heat_capacity", float(heat_capacity), step)
|
|
193
|
+
|
|
194
|
+
# --- wall time ---
|
|
195
|
+
if iteration_wall_s is not None:
|
|
196
|
+
self._cumulative_wall_s += iteration_wall_s
|
|
197
|
+
w.add_scalar("timing/iteration_wall_s", float(iteration_wall_s), step)
|
|
198
|
+
w.add_scalar("timing/cumulative_wall_s", self._cumulative_wall_s, step)
|
|
199
|
+
if sampling_wall_s is not None:
|
|
200
|
+
w.add_scalar("timing/sampling_wall_s", float(sampling_wall_s), step)
|
|
201
|
+
if evaluation_wall_s is not None:
|
|
202
|
+
w.add_scalar("timing/evaluation_wall_s", float(evaluation_wall_s), step)
|
|
203
|
+
if training_wall_s is not None:
|
|
204
|
+
w.add_scalar("timing/training_wall_s", float(training_wall_s), step)
|
|
205
|
+
|
|
206
|
+
# --- custom analysis figures ---
|
|
207
|
+
self.log_analysis(
|
|
208
|
+
step,
|
|
209
|
+
temperature=temperature,
|
|
210
|
+
buffer_energies=buffer_energies,
|
|
211
|
+
all_energies=all_energies,
|
|
212
|
+
new_energies=new_energies,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
# ------------------------------------------------------------------
|
|
216
|
+
# Analysis plots
|
|
217
|
+
# ------------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
def log_analysis(self, step, *, temperature, buffer_energies, all_energies, new_energies):
|
|
220
|
+
"""Log custom matplotlib figures under the ``analysis/`` tag group.
|
|
221
|
+
|
|
222
|
+
Four figures are produced each iteration:
|
|
223
|
+
|
|
224
|
+
* **best_energy_vs_total_data** – running line plot of the global
|
|
225
|
+
best energy against cumulative dataset size.
|
|
226
|
+
* **buffer_energies_vs_temperature** – cumulative scatter plot of
|
|
227
|
+
buffer energies for every temperature seen so far (log x-axis),
|
|
228
|
+
with the per-temperature mean marked as a horizontal tick.
|
|
229
|
+
* **new_sample_energy_distribution** – histogram of the energies
|
|
230
|
+
sampled in the current iteration, with min and mean annotated.
|
|
231
|
+
* **energy_landscape_overview** – running plot of min, mean and a
|
|
232
|
+
±1-std band of the full accumulated energy set vs. iteration.
|
|
233
|
+
|
|
234
|
+
Parameters
|
|
235
|
+
----------
|
|
236
|
+
step : int
|
|
237
|
+
Current iteration index (TensorBoard global step).
|
|
238
|
+
temperature : float or None
|
|
239
|
+
Temperature at the current iteration.
|
|
240
|
+
buffer_energies : array-like
|
|
241
|
+
Energies of structures in the replay buffer.
|
|
242
|
+
all_energies : array-like
|
|
243
|
+
Energies of all accumulated structures.
|
|
244
|
+
new_energies : array-like
|
|
245
|
+
Energies of structures sampled this iteration.
|
|
246
|
+
"""
|
|
247
|
+
w = self.writer
|
|
248
|
+
|
|
249
|
+
all_energies = np.asarray(all_energies) if len(all_energies) > 0 else np.array([])
|
|
250
|
+
buffer_energies = (
|
|
251
|
+
np.asarray(buffer_energies) if len(buffer_energies) > 0 else np.array([])
|
|
252
|
+
)
|
|
253
|
+
new_energies = (
|
|
254
|
+
np.asarray(new_energies) if len(new_energies) > 0 else np.array([])
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# --- update running histories ---
|
|
258
|
+
if len(all_energies) > 0:
|
|
259
|
+
self._best_energy_history.append((len(all_energies), float(np.min(all_energies))))
|
|
260
|
+
|
|
261
|
+
if temperature is not None and len(buffer_energies) > 0:
|
|
262
|
+
self._buffer_history.append((float(temperature), buffer_energies.copy()))
|
|
263
|
+
|
|
264
|
+
# -----------------------------------------------------------------
|
|
265
|
+
# Plot 1: best energy as a function of total data
|
|
266
|
+
# -----------------------------------------------------------------
|
|
267
|
+
if len(self._best_energy_history) >= 1:
|
|
268
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
269
|
+
ns, bests = zip(*self._best_energy_history)
|
|
270
|
+
ax.plot(ns, bests, "o-", color="steelblue", markersize=4, linewidth=1.5)
|
|
271
|
+
ax.set_xlabel("Total data (structures)")
|
|
272
|
+
ax.set_ylabel("Best energy [eV]")
|
|
273
|
+
ax.set_title("Best energy vs. total data")
|
|
274
|
+
ax.grid(True, alpha=0.3)
|
|
275
|
+
fig.tight_layout()
|
|
276
|
+
w.add_figure("analysis/best_energy_vs_total_data", fig, global_step=step)
|
|
277
|
+
plt.close(fig)
|
|
278
|
+
|
|
279
|
+
# -----------------------------------------------------------------
|
|
280
|
+
# Plot 2: buffer energies violin vs temperature (seaborn-style)
|
|
281
|
+
# -----------------------------------------------------------------
|
|
282
|
+
if len(self._buffer_history) >= 1:
|
|
283
|
+
# Group energies per temperature across all iterations
|
|
284
|
+
grouped = defaultdict(list)
|
|
285
|
+
for t, e in self._buffer_history:
|
|
286
|
+
grouped[t].extend(e.tolist())
|
|
287
|
+
|
|
288
|
+
temps_sorted = sorted(grouped.keys(), reverse=True) # high → low
|
|
289
|
+
|
|
290
|
+
# Normalise to global min so y-axis starts near 0
|
|
291
|
+
# global_min = min(min(v) for v in grouped.values())
|
|
292
|
+
|
|
293
|
+
# Colour map: RdYlBu_r → index 0 = red (high T), index 1 = blue (low T)
|
|
294
|
+
n_temps = max(len(temps_sorted) - 1, 1)
|
|
295
|
+
cmap = plt.cm.RdYlBu
|
|
296
|
+
colors = {
|
|
297
|
+
t: cmap(i / n_temps)
|
|
298
|
+
for i, t in enumerate(temps_sorted)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
302
|
+
|
|
303
|
+
for t in temps_sorted:
|
|
304
|
+
energies_t = np.asarray(grouped[t])# - global_min
|
|
305
|
+
if len(energies_t) < 2:
|
|
306
|
+
# Not enough data for KDE – fall back to a single point
|
|
307
|
+
ax.scatter([t], [float(np.mean(energies_t))],
|
|
308
|
+
color=colors[t], s=40, zorder=5)
|
|
309
|
+
continue
|
|
310
|
+
x_col = np.full(len(energies_t), t)
|
|
311
|
+
_df = pd.DataFrame({"temperature": x_col, "energy": energies_t})
|
|
312
|
+
sns.violinplot(
|
|
313
|
+
data=_df,
|
|
314
|
+
x="temperature",
|
|
315
|
+
y="energy",
|
|
316
|
+
ax=ax,
|
|
317
|
+
color=colors[t],
|
|
318
|
+
inner="point",
|
|
319
|
+
cut=0,
|
|
320
|
+
bw_adjust=0.5,
|
|
321
|
+
linewidth=0.5,
|
|
322
|
+
density_norm="width",
|
|
323
|
+
split=True,
|
|
324
|
+
common_norm=True,
|
|
325
|
+
native_scale=True,
|
|
326
|
+
width=0.2,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
ax.set_xscale("log")
|
|
330
|
+
ax.invert_xaxis()
|
|
331
|
+
ax.set_xlabel("Temperature")
|
|
332
|
+
ax.set_ylabel("Energy [eV]")
|
|
333
|
+
# ax.set_ylim(-0.05, 5)
|
|
334
|
+
ax.set_title("Buffer energies vs. temperature")
|
|
335
|
+
ax.grid(True, alpha=0.3, which="both")
|
|
336
|
+
fig.tight_layout()
|
|
337
|
+
w.add_figure("analysis/buffer_energies_vs_temperature", fig, global_step=step)
|
|
338
|
+
plt.close(fig)
|
|
339
|
+
|
|
340
|
+
# -----------------------------------------------------------------
|
|
341
|
+
# Plot 3: new-sample energy distribution (histogram)
|
|
342
|
+
# -----------------------------------------------------------------
|
|
343
|
+
if len(new_energies) > 0:
|
|
344
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
345
|
+
ax.hist(new_energies, bins=max(1, min(20, len(new_energies))), color="steelblue",
|
|
346
|
+
edgecolor="white", alpha=0.75)
|
|
347
|
+
ax.axvline(float(np.min(new_energies)), color="red", linestyle="--",
|
|
348
|
+
linewidth=1.5, label=f"min = {np.min(new_energies):.3f}")
|
|
349
|
+
ax.axvline(float(np.mean(new_energies)), color="orange", linestyle="--",
|
|
350
|
+
linewidth=1.5, label=f"mean = {np.mean(new_energies):.3f}")
|
|
351
|
+
ax.set_xlabel("Energy [eV]")
|
|
352
|
+
ax.set_ylabel("Count")
|
|
353
|
+
t_str = f"{temperature:.4f}" if temperature is not None else "initial"
|
|
354
|
+
ax.set_title(f"New-sample energy distribution (T = {t_str})")
|
|
355
|
+
ax.legend(fontsize=8)
|
|
356
|
+
ax.grid(True, alpha=0.3)
|
|
357
|
+
fig.tight_layout()
|
|
358
|
+
w.add_figure("analysis/new_sample_energy_distribution", fig, global_step=step)
|
|
359
|
+
plt.close(fig)
|
|
360
|
+
|
|
361
|
+
# -----------------------------------------------------------------
|
|
362
|
+
# Plot 4: energy landscape overview (min / mean ± std vs iteration)
|
|
363
|
+
# -----------------------------------------------------------------
|
|
364
|
+
if len(self._best_energy_history) >= 1 and len(all_energies) > 0:
|
|
365
|
+
self._landscape_history.append(
|
|
366
|
+
(step, float(np.min(all_energies)),
|
|
367
|
+
float(np.mean(all_energies)), float(np.std(all_energies)))
|
|
368
|
+
)
|
|
369
|
+
steps_l, mins_l, means_l, stds_l = zip(*self._landscape_history)
|
|
370
|
+
steps_l = np.array(steps_l)
|
|
371
|
+
mins_l = np.array(mins_l)
|
|
372
|
+
means_l = np.array(means_l)
|
|
373
|
+
stds_l = np.array(stds_l)
|
|
374
|
+
|
|
375
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
376
|
+
ax.fill_between(
|
|
377
|
+
steps_l, means_l - stds_l, means_l + stds_l,
|
|
378
|
+
alpha=0.25, color="steelblue", label="mean ± std"
|
|
379
|
+
)
|
|
380
|
+
ax.plot(steps_l, means_l, "-", color="steelblue", linewidth=1.5)
|
|
381
|
+
ax.plot(steps_l, mins_l, "o-", color="crimson", markersize=4,
|
|
382
|
+
linewidth=1.5, label="best")
|
|
383
|
+
ax.set_xlabel("Iteration")
|
|
384
|
+
ax.set_ylabel("Energy [eV]")
|
|
385
|
+
ax.set_title("Energy landscape overview")
|
|
386
|
+
ax.legend(fontsize=8)
|
|
387
|
+
ax.grid(True, alpha=0.3)
|
|
388
|
+
fig.tight_layout()
|
|
389
|
+
w.add_figure("analysis/energy_landscape_overview", fig, global_step=step)
|
|
390
|
+
plt.close(fig)
|
|
391
|
+
|
|
392
|
+
# ------------------------------------------------------------------
|
|
393
|
+
# Training-step level logging
|
|
394
|
+
# ------------------------------------------------------------------
|
|
395
|
+
|
|
396
|
+
def log_training_step(
|
|
397
|
+
self,
|
|
398
|
+
global_step,
|
|
399
|
+
*,
|
|
400
|
+
agreement_current=None,
|
|
401
|
+
agreement_ema=None,
|
|
402
|
+
agreement_max=None,
|
|
403
|
+
patience_counter=None,
|
|
404
|
+
step_wall_s=None,
|
|
405
|
+
step_flops=None,
|
|
406
|
+
cumulative_flops=None,
|
|
407
|
+
):
|
|
408
|
+
"""Log gradient-agreement metrics at the training-step level.
|
|
409
|
+
|
|
410
|
+
Parameters
|
|
411
|
+
----------
|
|
412
|
+
global_step : int
|
|
413
|
+
Lightning global step counter.
|
|
414
|
+
agreement_current : float or None
|
|
415
|
+
Cosine similarity between the two gradient halves for this step.
|
|
416
|
+
agreement_ema : float or None
|
|
417
|
+
Exponential moving average of the gradient agreement.
|
|
418
|
+
agreement_max : float or None
|
|
419
|
+
Peak gradient agreement reached so far in this iteration.
|
|
420
|
+
patience_counter : int or None
|
|
421
|
+
Number of steps since the peak agreement was last updated.
|
|
422
|
+
step_wall_s : float or None
|
|
423
|
+
Wall-clock time (seconds) for this training step.
|
|
424
|
+
step_flops : float or None
|
|
425
|
+
Estimated FLOPs for this training step (profiled via
|
|
426
|
+
``torch.profiler`` for the first few steps per iteration; the
|
|
427
|
+
running mean is used as an estimate for subsequent steps).
|
|
428
|
+
cumulative_flops : float or None
|
|
429
|
+
Running total of training FLOPs across all steps so far.
|
|
430
|
+
"""
|
|
431
|
+
w = self.writer
|
|
432
|
+
if agreement_current is not None:
|
|
433
|
+
w.add_scalar(
|
|
434
|
+
"train/gradient_agreement_current", float(agreement_current), global_step
|
|
435
|
+
)
|
|
436
|
+
if agreement_ema is not None:
|
|
437
|
+
w.add_scalar(
|
|
438
|
+
"train/gradient_agreement_ema", float(agreement_ema), global_step
|
|
439
|
+
)
|
|
440
|
+
if agreement_max is not None:
|
|
441
|
+
w.add_scalar(
|
|
442
|
+
"train/gradient_agreement_max", float(agreement_max), global_step
|
|
443
|
+
)
|
|
444
|
+
if patience_counter is not None:
|
|
445
|
+
w.add_scalar(
|
|
446
|
+
"train/patience_counter", int(patience_counter), global_step
|
|
447
|
+
)
|
|
448
|
+
if step_wall_s is not None:
|
|
449
|
+
w.add_scalar("train/step_wall_s", float(step_wall_s), global_step)
|
|
450
|
+
if step_flops is not None:
|
|
451
|
+
w.add_scalar("train/step_flops", float(step_flops), global_step)
|
|
452
|
+
if cumulative_flops is not None:
|
|
453
|
+
w.add_scalar("train/cumulative_flops", float(cumulative_flops), global_step)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .weighted_pos import WeightedPositions, WeightedConfinedCellPositions
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from agedi.diffusion.noisers import ConfinedCellPositions, Positions
|
|
3
|
+
from agedi.data import AtomsGraph
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class _WeightedLossMixin:
|
|
7
|
+
"""Mixin that replaces the standard position-score loss with a
|
|
8
|
+
Boltzmann-weighted variant.
|
|
9
|
+
|
|
10
|
+
Expects the batch to carry a ``weight`` attribute (one scalar weight per
|
|
11
|
+
structure) that is broadcast to the per-atom level before computing the
|
|
12
|
+
mean squared error between the predicted and target score.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def _loss(self, batch: AtomsGraph) -> torch.Tensor:
|
|
16
|
+
"""Compute the Boltzmann-weighted denoising score-matching loss.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
batch : AtomsGraph
|
|
21
|
+
The atomistic structure (or batch hereof) to be noised.
|
|
22
|
+
|
|
23
|
+
Returns
|
|
24
|
+
-------
|
|
25
|
+
torch.Tensor
|
|
26
|
+
Scalar loss value.
|
|
27
|
+
"""
|
|
28
|
+
t = batch.time
|
|
29
|
+
r_score = batch[self.key + "_score"]
|
|
30
|
+
r_noise = batch[self.key + "_noise"]
|
|
31
|
+
|
|
32
|
+
weights = batch.weight
|
|
33
|
+
weights = weights.repeat_interleave(batch.n_atoms.view(-1), dim=0)
|
|
34
|
+
|
|
35
|
+
var = self.sde.var(t)
|
|
36
|
+
|
|
37
|
+
r_score = batch.apply_mask(r_score)
|
|
38
|
+
|
|
39
|
+
return torch.mean(
|
|
40
|
+
weights * torch.sum((r_noise + r_score * var) ** 2, dim=-1)
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class WeightedConfinedCellPositions(_WeightedLossMixin, ConfinedCellPositions):
|
|
45
|
+
"""Boltzmann-weighted variant of :class:`agedi.diffusion.noisers.ConfinedCellPositions`.
|
|
46
|
+
|
|
47
|
+
Assumes that the batch has a ``weight`` attribute.
|
|
48
|
+
"""
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class WeightedPositions(_WeightedLossMixin, Positions):
|
|
53
|
+
"""Boltzmann-weighted variant of :class:`agedi.diffusion.noisers.Positions`.
|
|
54
|
+
|
|
55
|
+
Assumes that the batch has a ``weight`` attribute.
|
|
56
|
+
"""
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
go_diff/utils.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Shared utility functions for GO-Diff."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy.typing import ArrayLike
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def boltzmann_weights(energies: ArrayLike, temperature: float) -> np.ndarray:
|
|
10
|
+
"""Compute Boltzmann importance weights for a set of energies.
|
|
11
|
+
|
|
12
|
+
Weights are normalised so that their sum equals ``len(energies)``.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
energies : array-like of float
|
|
17
|
+
Scalar potential energies (eV).
|
|
18
|
+
temperature : float
|
|
19
|
+
Current annealing temperature.
|
|
20
|
+
|
|
21
|
+
Returns
|
|
22
|
+
-------
|
|
23
|
+
np.ndarray of float, shape ``(len(energies),)``
|
|
24
|
+
Boltzmann importance weights, summing to ``len(energies)``.
|
|
25
|
+
"""
|
|
26
|
+
energies = np.asarray(energies, dtype=float)
|
|
27
|
+
Es_scaled = -energies / temperature
|
|
28
|
+
Es_shifted = Es_scaled - np.max(Es_scaled)
|
|
29
|
+
exp_Es = np.exp(Es_shifted)
|
|
30
|
+
return exp_Es / np.sum(exp_Es) * len(energies)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def effective_sample_size(energies: ArrayLike, temperature: float) -> float:
|
|
34
|
+
"""Compute the Effective Sample Size (ESS) for a set of energies.
|
|
35
|
+
|
|
36
|
+
Parameters
|
|
37
|
+
----------
|
|
38
|
+
energies : array-like of float
|
|
39
|
+
Scalar potential energies (eV).
|
|
40
|
+
temperature : float
|
|
41
|
+
Current annealing temperature.
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
float
|
|
46
|
+
The ESS (between 1 and ``len(energies)``).
|
|
47
|
+
"""
|
|
48
|
+
w = boltzmann_weights(energies, temperature)
|
|
49
|
+
w_norm = w / np.sum(w)
|
|
50
|
+
return float(1.0 / np.sum(w_norm ** 2))
|