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.
@@ -0,0 +1,407 @@
1
+ """Lightning callbacks that control training duration in GO-Diff."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any
7
+
8
+ import torch
9
+ from lightning.pytorch.callbacks import Callback
10
+ from torch.nn.functional import cosine_similarity
11
+ from torch_geometric.data import Batch
12
+
13
+
14
+ class MomentumConsensusStop(Callback):
15
+ """Stop training when gradient momentum and current gradient diverge.
16
+
17
+ After an initial warm-up phase (*min_steps*) the callback computes the
18
+ cosine similarity between the current gradient and the first-moment
19
+ estimate stored by the Adam/AdamW optimiser. Training is halted when
20
+ agreement has been below ``drop_factor × peak_agreement`` for *patience*
21
+ consecutive steps.
22
+
23
+ Parameters
24
+ ----------
25
+ min_steps : int
26
+ Minimum number of training steps before the stopping criterion is
27
+ evaluated. Default: 50.
28
+ patience : int
29
+ Number of consecutive steps below the drop threshold before training
30
+ is stopped. Default: 100.
31
+ drop_factor : float
32
+ Fraction of the peak agreement that the current agreement must fall
33
+ below (for *patience* steps) to trigger early stopping. Default: 0.5.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ min_steps: int = 50,
39
+ patience: int = 100,
40
+ drop_factor: float = 0.5,
41
+ ) -> None:
42
+ super().__init__()
43
+ self.min_steps = min_steps
44
+ self.patience = patience
45
+ self.drop_factor = drop_factor
46
+
47
+ self.max_agreement: float = -1.0
48
+ self.patience_counter: int = 0
49
+ self.current_step: int = 0
50
+
51
+ # Optional GODiffLogger for TensorBoard logging
52
+ self._godiff_logger = None
53
+
54
+ def set_logger(self, logger: Any) -> None:
55
+ """Attach a GODiffLogger so agreement metrics are written to TensorBoard.
56
+
57
+ Parameters
58
+ ----------
59
+ logger : GODiffLogger
60
+ Logger instance to receive per-step metrics.
61
+ """
62
+ self._godiff_logger = logger
63
+
64
+ def on_after_backward(self, trainer: Any, pl_module: Any) -> None:
65
+ """Evaluate momentum–gradient agreement after each backward pass.
66
+
67
+ Gradients are available in ``pl_module.parameters()`` at this point.
68
+ Computes the cosine similarity between the current gradient vector and
69
+ the Adam first-moment (momentum) vector and triggers early stopping
70
+ when the agreement has been low for *patience* steps.
71
+ """
72
+ self.current_step += 1
73
+ if self.current_step < self.min_steps:
74
+ return
75
+
76
+ # 1. Pull the optimizer (to access momentum states)
77
+ # In manual optimization, you might have multiple; we'll take the first.
78
+ opt = trainer.optimizers[0]
79
+
80
+ grads = []
81
+ momentums = []
82
+
83
+ for p in pl_module.parameters():
84
+ if p.grad is not None:
85
+ # 'exp_avg' is the first moment (moving average) in Adam/AdamW
86
+ state = opt.state[p]
87
+ if 'exp_avg' in state:
88
+ grads.append(p.grad.detach().view(-1))
89
+ momentums.append(state['exp_avg'].detach().view(-1))
90
+
91
+ if not grads or not momentums:
92
+ return
93
+
94
+ # 2. Vectorized Consensus Calculation
95
+ g = torch.cat(grads)
96
+ m = torch.cat(momentums)
97
+
98
+ # Cosine similarity measures if the new gradient aligns with the trend
99
+ agreement = torch.nn.functional.cosine_similarity(g, m, dim=0).item()
100
+
101
+ # 3. Peak-to-Drop Logic
102
+ if agreement > self.max_agreement:
103
+ self.max_agreement = agreement
104
+ self.patience_counter = 0
105
+ else:
106
+ self.patience_counter += 1
107
+
108
+ # 4. Stopping logic
109
+ if (self.patience_counter >= self.patience and
110
+ agreement < (self.drop_factor * self.max_agreement)):
111
+
112
+ print(f"\n[Adaptive Stop] Consensus reached. "
113
+ f"Peak Agreement: {self.max_agreement:.3f} | Current: {agreement:.3f}")
114
+ trainer.should_stop = True
115
+
116
+ if self._godiff_logger is not None:
117
+ self._godiff_logger.log_training_step(
118
+ trainer.global_step,
119
+ agreement_current=agreement,
120
+ agreement_max=self.max_agreement,
121
+ patience_counter=self.patience_counter,
122
+ )
123
+
124
+
125
+ def on_train_start(self, trainer: Any, pl_module: Any) -> None:
126
+ """Reset internal state at the start of each GO-Diff training stage."""
127
+ self.max_agreement = -1.0
128
+ self.patience_counter = 0
129
+ self.current_step = 0
130
+
131
+
132
+ class AdaptiveRefinementStop(Callback):
133
+ """Stop training when the gradient-agreement EMA has significantly dropped.
134
+
135
+ Computes gradient agreement by splitting each mini-batch into two halves,
136
+ running independent backward passes, and measuring the cosine similarity of
137
+ the resulting gradient vectors. Training stops when the exponential moving
138
+ average (EMA) of the agreement has peaked and then fallen to less than half
139
+ its peak value for *patience* consecutive check-points.
140
+
141
+ Parameters
142
+ ----------
143
+ min_steps : int
144
+ Global training step at which checking begins. Default: 100.
145
+ patience : int
146
+ Number of consecutive low-agreement check-points before stopping.
147
+ Default: 50.
148
+ smooth_factor : float
149
+ EMA smoothing coefficient (between 0 and 1). Higher values give a
150
+ smoother but more lagging estimate. Default: 0.75.
151
+ check_interval : int
152
+ Interval in training steps between agreement evaluations. Default: 1.
153
+ """
154
+
155
+ def __init__(
156
+ self,
157
+ min_steps: int = 100,
158
+ patience: int = 50,
159
+ smooth_factor: float = 0.75,
160
+ check_interval: int = 1,
161
+ ) -> None:
162
+ super().__init__()
163
+ self._min_steps = min_steps
164
+ self.min_steps = min_steps
165
+ self.patience = patience
166
+ self.smooth_factor = smooth_factor
167
+ self.check_interval = check_interval
168
+
169
+ self.ema_agreement: float = 0.0
170
+ self.max_agreement: float = -1.0
171
+ self.patience_counter: int = 0
172
+
173
+ # Optional GODiffLogger for TensorBoard logging
174
+ self._godiff_logger = None
175
+
176
+ def set_logger(self, logger: Any) -> None:
177
+ """Attach a GODiffLogger so agreement metrics are written to TensorBoard.
178
+
179
+ Parameters
180
+ ----------
181
+ logger : GODiffLogger
182
+ Logger instance to receive per-step metrics.
183
+ """
184
+ self._godiff_logger = logger
185
+
186
+ def on_train_batch_start(
187
+ self,
188
+ trainer: Any,
189
+ pl_module: Any,
190
+ batch: Any,
191
+ batch_idx: int,
192
+ ) -> None:
193
+ """Evaluate gradient agreement and optionally stop training."""
194
+ if trainer.global_step < self.min_steps or trainer.global_step % self.check_interval != 0:
195
+ return
196
+
197
+ if len(batch) < 4:
198
+ return
199
+
200
+ # 1. Calculate current agreement (using the split logic from before)
201
+ current_agreement = self._calculate_split_agreement(trainer, pl_module, batch, batch_idx)
202
+
203
+ # 2. Apply Exponential Moving Average (EMA) to smooth the noise
204
+ self.ema_agreement = (self.smooth_factor * self.ema_agreement) + \
205
+ ((1 - self.smooth_factor) * current_agreement)
206
+
207
+ # 3. Track the peak agreement reached in this iteration
208
+ if self.ema_agreement > self.max_agreement:
209
+ self.max_agreement = self.ema_agreement
210
+ self.patience_counter = 0
211
+ else:
212
+ self.patience_counter += 1
213
+
214
+ # 4. Log gradient-agreement metrics to TensorBoard
215
+ if self._godiff_logger is not None:
216
+ self._godiff_logger.log_training_step(
217
+ trainer.global_step,
218
+ agreement_current=current_agreement,
219
+ agreement_ema=self.ema_agreement,
220
+ agreement_max=self.max_agreement,
221
+ patience_counter=self.patience_counter,
222
+ )
223
+
224
+ # 5. Logic: If agreement has significantly dropped from its peak, stop.
225
+ # This means the model has finished learning the "consensus" and is now over-fitting.
226
+ if self.patience_counter >= self.patience and self.ema_agreement < (0.5 * self.max_agreement):
227
+ print(f"\n[Adaptive Stop] Agreement peaked at {self.max_agreement:.4f} "
228
+ f"and dropped to {self.ema_agreement:.4f}. Stopping.")
229
+ trainer.should_stop = True
230
+
231
+ def _calculate_split_agreement(
232
+ self,
233
+ trainer: Any,
234
+ pl_module: Any,
235
+ batch: Any,
236
+ batch_idx: int,
237
+ ) -> float:
238
+ """Compute gradient cosine similarity by splitting the batch in two.
239
+
240
+ Parameters
241
+ ----------
242
+ trainer : lightning.Trainer
243
+ pl_module : lightning.LightningModule
244
+ batch : list
245
+ Current mini-batch (list of graph data objects).
246
+ batch_idx : int
247
+
248
+ Returns
249
+ -------
250
+ float
251
+ Cosine similarity between the two half-batch gradients.
252
+ """
253
+ # 1. Split the batch into two independent halves
254
+ half = len(batch) // 2
255
+
256
+ opt = trainer.optimizers[0]
257
+ # 2. Calculate Gradient A (First Half)
258
+ pl_module.zero_grad()
259
+ loss_a = pl_module.loss(Batch.from_data_list(batch[:half]), batch_idx)
260
+ trainer.strategy.backward(loss_a["loss"], optimizer=opt)
261
+ grad_a = self._get_flat_grad(pl_module)
262
+
263
+ # 3. Calculate Gradient B (Second Half)
264
+ pl_module.zero_grad()
265
+ loss_b = pl_module.loss(Batch.from_data_list(batch[half:]), batch_idx)
266
+ trainer.strategy.backward(loss_b["loss"], optimizer=opt)
267
+ grad_b = self._get_flat_grad(pl_module)
268
+
269
+ # 4. Compute Agreement (Cosine Similarity)
270
+ grad_a /= torch.norm(grad_a)
271
+ grad_b /= torch.norm(grad_b)
272
+ agreement = cosine_similarity(grad_a.unsqueeze(0), grad_b.unsqueeze(0)).item()
273
+ pl_module.zero_grad()
274
+
275
+ return agreement
276
+
277
+
278
+
279
+ def _get_flat_grad(self, pl_module: Any) -> torch.Tensor:
280
+ """Flatten all model gradients into a single 1-D tensor."""
281
+ grads = []
282
+ for param in pl_module.parameters():
283
+ if param.grad is not None:
284
+ grads.append(param.grad.view(-1))
285
+ return torch.cat(grads) if grads else torch.tensor([])
286
+
287
+
288
+ def on_train_start(self, trainer: Any, pl_module: Any) -> None:
289
+ """Reset internal state at the start of each GO-Diff training stage.
290
+
291
+ *min_steps* is offset by the current global step so the warm-up
292
+ period is restarted relative to the current Lightning global step.
293
+ """
294
+ self.ema_agreement = 0.0
295
+ self.max_agreement = -1.0
296
+ self.patience_counter = 0
297
+ self.min_steps = trainer.global_step + self._min_steps
298
+
299
+ def reset(self, trainer: Any) -> None:
300
+ """Reset internal state; *min_steps* is offset by the current global step.
301
+
302
+ .. deprecated::
303
+ Call :meth:`on_train_start` or rely on the Lightning callback
304
+ mechanism instead. This method is kept for backwards compatibility
305
+ but will be removed in a future release.
306
+ """
307
+ self.on_train_start(trainer, None)
308
+
309
+ class FlopsAndTimingCallback(Callback):
310
+ """Lightning callback that tracks per-training-step wall-time and estimates
311
+ FLOPs via ``torch.profiler`` for the first ``profile_steps`` steps of each
312
+ GO-Diff iteration.
313
+
314
+ For each iteration, ``torch.profiler`` actively captures FLOPs for the first
315
+ ``profile_steps`` training steps. After that window the running-mean
316
+ FLOPs/step estimate is reused for all remaining steps, keeping the profiling
317
+ overhead negligible. Calling :py:meth:`reset` at the start of a new
318
+ iteration restarts the profiling window so the estimate stays up-to-date as
319
+ the model evolves.
320
+
321
+ Parameters
322
+ ----------
323
+ profile_steps : int
324
+ Number of steps to actively profile with ``torch.profiler`` per
325
+ iteration (default: 5).
326
+ """
327
+
328
+ def __init__(self, profile_steps: int = 5):
329
+ super().__init__()
330
+ self.profile_steps = profile_steps
331
+ self._step_start: float = 0.0
332
+ self._profiling_steps_done: int = 0
333
+ self._flops_estimates: list = []
334
+ self._flops_per_step: float = 0.0
335
+ self._cumulative_flops: float = 0.0
336
+ self._profiler = None
337
+ self._profiler_available: bool = True
338
+ self._godiff_logger = None
339
+
340
+ def set_logger(self, logger) -> None:
341
+ """Attach a GODiffLogger for TensorBoard logging."""
342
+ self._godiff_logger = logger
343
+
344
+ def reset(self) -> None:
345
+ """Reset per-iteration profiling counters.
346
+
347
+ Called at the start of each new GO-Diff iteration so the FLOPs
348
+ estimate is refreshed for the new model state.
349
+ """
350
+ self._profiling_steps_done = 0
351
+ self._flops_estimates = []
352
+
353
+ def on_train_batch_start(self, trainer, pl_module, batch, batch_idx):
354
+ self._step_start = time.perf_counter()
355
+ # Profile only the first `profile_steps` steps per iteration.
356
+ # This callback is placed *after* AdaptiveRefinementStop in the
357
+ # callbacks list so the gradient-agreement extra backward passes are
358
+ # not included in the FLOPs estimate.
359
+ if self._profiler_available and self._profiling_steps_done < self.profile_steps:
360
+ activities = [torch.profiler.ProfilerActivity.CPU]
361
+ if torch.cuda.is_available():
362
+ activities.append(torch.profiler.ProfilerActivity.CUDA)
363
+ try:
364
+ self._profiler = torch.profiler.profile(
365
+ activities=activities,
366
+ with_flops=True,
367
+ record_shapes=True,
368
+ )
369
+ self._profiler.__enter__()
370
+ except Exception:
371
+ self._profiler_available = False
372
+ self._profiler = None
373
+
374
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
375
+ step_wall_s = time.perf_counter() - self._step_start
376
+ step_flops = None
377
+
378
+ if self._profiler is not None:
379
+ try:
380
+ self._profiler.__exit__(None, None, None)
381
+ raw_flops = float(
382
+ sum(e.flops for e in self._profiler.key_averages() if e.flops > 0)
383
+ )
384
+ self._flops_estimates.append(raw_flops)
385
+ self._profiling_steps_done += 1
386
+ self._flops_per_step = (
387
+ sum(self._flops_estimates) / len(self._flops_estimates)
388
+ )
389
+ step_flops = raw_flops
390
+ except Exception:
391
+ self._profiler_available = False
392
+ finally:
393
+ self._profiler = None
394
+ elif self._flops_per_step > 0:
395
+ step_flops = self._flops_per_step
396
+
397
+ if step_flops is not None:
398
+ self._cumulative_flops += step_flops
399
+
400
+ if self._godiff_logger is not None:
401
+ self._godiff_logger.log_training_step(
402
+ trainer.global_step,
403
+ step_wall_s=step_wall_s,
404
+ step_flops=step_flops,
405
+ cumulative_flops=self._cumulative_flops if step_flops is not None else None,
406
+ )
407
+
go_diff/filter.py ADDED
@@ -0,0 +1,70 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Protocol, runtime_checkable
4
+
5
+ import numpy as np
6
+ from ase import Atoms
7
+
8
+ @runtime_checkable
9
+ class Filter(Protocol):
10
+ """Protocol for structure filter callables.
11
+
12
+ A filter is any callable that accepts an :class:`ase.Atoms` object and
13
+ returns ``True`` if the structure should be **kept**.
14
+
15
+ Any function or object implementing ``__call__(atoms: Atoms) -> bool``
16
+ satisfies this protocol.
17
+
18
+ Examples
19
+ --------
20
+ Use the built-in filter classes::
21
+
22
+ from go_diff.controllers import MinEnergyFilter, MaxEnergyFilter
23
+ valid_structure_filters = [MinEnergyFilter(-500.0)]
24
+ buffer_filters = [MaxEnergyFilter(0.0)]
25
+
26
+ Or write your own::
27
+
28
+ def my_filter(atoms):
29
+ return atoms.get_potential_energy() > -10.0
30
+ """
31
+
32
+ def __call__(self, atoms: Atoms) -> bool: ...
33
+
34
+
35
+ class MinEnergyFilter:
36
+ """Keep only structures whose potential energy is strictly above a threshold.
37
+
38
+ Parameters
39
+ ----------
40
+ threshold : float
41
+ Structures with ``get_potential_energy() <= threshold`` are removed.
42
+ Pass ``-500.0`` to replicate the former ``GODiff(min_E=-500.0)``
43
+ behaviour and discard clearly unphysical structures.
44
+ """
45
+
46
+ def __init__(self, threshold: float = 0.0) -> None:
47
+ self.threshold = threshold
48
+
49
+ def __call__(self, atoms: Atoms) -> bool:
50
+ return atoms.get_potential_energy() > self.threshold
51
+
52
+
53
+ class MaxEnergyFilter:
54
+ """Keep only structures whose potential energy is strictly below a threshold.
55
+
56
+ Parameters
57
+ ----------
58
+ threshold : float
59
+ Structures with ``get_potential_energy() >= threshold`` are removed.
60
+ The default ``0.0`` reproduces the historical silent ``e < 0.0``
61
+ buffer filter, keeping only negative-energy structures.
62
+ """
63
+
64
+ def __init__(self, threshold: float = 0.0) -> None:
65
+ self.threshold = threshold
66
+
67
+ def __call__(self, atoms: Atoms) -> bool:
68
+ return atoms.get_potential_energy() < self.threshold
69
+
70
+