GO-Diff 1.1.0__tar.gz → 1.3.0__tar.gz

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.
Files changed (85) hide show
  1. {go_diff-1.1.0 → go_diff-1.3.0}/.gitignore +3 -0
  2. {go_diff-1.1.0 → go_diff-1.3.0}/PKG-INFO +71 -3
  3. {go_diff-1.1.0 → go_diff-1.3.0}/README.md +66 -0
  4. go_diff-1.3.0/VERSION +1 -0
  5. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/concepts.rst +45 -0
  6. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/overview.rst +5 -0
  7. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/references.rst +23 -0
  8. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/troubleshooting.rst +45 -0
  9. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/tutorial/quickstart.rst +36 -0
  10. go_diff-1.3.0/go_diff/__init__.py +14 -0
  11. go_diff-1.3.0/go_diff/controllers/__init__.py +15 -0
  12. go_diff-1.3.0/go_diff/controllers/archive.py +156 -0
  13. {go_diff-1.1.0 → go_diff-1.3.0}/go_diff/controllers/buffer.py +5 -0
  14. go_diff-1.3.0/go_diff/controllers/forcefield.py +137 -0
  15. go_diff-1.3.0/go_diff/controllers/geometry.py +166 -0
  16. go_diff-1.3.0/go_diff/controllers/novelty.py +268 -0
  17. {go_diff-1.1.0 → go_diff-1.3.0}/go_diff/controllers/sample.py +15 -4
  18. go_diff-1.3.0/go_diff/controllers/selection.py +480 -0
  19. go_diff-1.3.0/go_diff/controllers/temperature.py +229 -0
  20. {go_diff-1.1.0 → go_diff-1.3.0}/go_diff/controllers/training.py +247 -4
  21. go_diff-1.3.0/go_diff/controllers/weighting.py +544 -0
  22. go_diff-1.3.0/go_diff/filter.py +368 -0
  23. go_diff-1.3.0/go_diff/go_diff.py +2757 -0
  24. go_diff-1.3.0/go_diff/gpu_memory.py +86 -0
  25. {go_diff-1.1.0 → go_diff-1.3.0}/go_diff/logger.py +204 -9
  26. go_diff-1.3.0/go_diff/noisers/__init__.py +6 -0
  27. go_diff-1.3.0/go_diff/noisers/weighted_pos.py +231 -0
  28. go_diff-1.3.0/go_diff/reporter.py +172 -0
  29. go_diff-1.3.0/go_diff/run_report.py +220 -0
  30. {go_diff-1.1.0 → go_diff-1.3.0}/pyproject.toml +3 -1
  31. {go_diff-1.1.0 → go_diff-1.3.0}/scripts/heptamer.py +1 -1
  32. {go_diff-1.1.0 → go_diff-1.3.0}/scripts/stepped_pt.py +1 -1
  33. {go_diff-1.1.0 → go_diff-1.3.0}/tests/conftest.py +32 -0
  34. go_diff-1.3.0/tests/test_bandwidth.py +113 -0
  35. go_diff-1.3.0/tests/test_buffer_eviction_schedule.py +171 -0
  36. go_diff-1.3.0/tests/test_buffer_eviction_schedule_wiring.py +239 -0
  37. go_diff-1.3.0/tests/test_buffer_weighting.py +347 -0
  38. go_diff-1.3.0/tests/test_buffer_weighting_schedule.py +153 -0
  39. go_diff-1.3.0/tests/test_buffer_weighting_schedule_wiring.py +237 -0
  40. go_diff-1.3.0/tests/test_calculator_relax.py +185 -0
  41. go_diff-1.3.0/tests/test_checkpoint_stride.py +194 -0
  42. go_diff-1.3.0/tests/test_energy_window.py +279 -0
  43. go_diff-1.3.0/tests/test_featurise_fully_connected.py +86 -0
  44. go_diff-1.3.0/tests/test_forcefield_guidance_schedule.py +108 -0
  45. go_diff-1.3.0/tests/test_forcefield_guidance_schedule_wiring.py +239 -0
  46. {go_diff-1.1.0 → go_diff-1.3.0}/tests/test_godiff.py +91 -1
  47. go_diff-1.3.0/tests/test_inpaint_wiring.py +385 -0
  48. go_diff-1.3.0/tests/test_logger_schema.py +107 -0
  49. go_diff-1.3.0/tests/test_nan_guard.py +441 -0
  50. go_diff-1.3.0/tests/test_novelty_archive.py +144 -0
  51. go_diff-1.3.0/tests/test_novelty_schedule.py +270 -0
  52. go_diff-1.3.0/tests/test_novelty_selection.py +402 -0
  53. go_diff-1.3.0/tests/test_novelty_wiring.py +323 -0
  54. go_diff-1.3.0/tests/test_periodic_filters.py +77 -0
  55. go_diff-1.3.0/tests/test_relax_wiring.py +205 -0
  56. go_diff-1.3.0/tests/test_reporter.py +118 -0
  57. go_diff-1.3.0/tests/test_run_layout.py +192 -0
  58. go_diff-1.3.0/tests/test_sampling_crash_recovery.py +186 -0
  59. go_diff-1.3.0/tests/test_selection_wiring.py +447 -0
  60. go_diff-1.3.0/tests/test_temperature.py +186 -0
  61. {go_diff-1.1.0 → go_diff-1.3.0}/uv.lock +8 -4
  62. go_diff-1.1.0/VERSION +0 -1
  63. go_diff-1.1.0/go_diff/__init__.py +0 -3
  64. go_diff-1.1.0/go_diff/controllers/__init__.py +0 -4
  65. go_diff-1.1.0/go_diff/controllers/temperature.py +0 -116
  66. go_diff-1.1.0/go_diff/filter.py +0 -102
  67. go_diff-1.1.0/go_diff/go_diff.py +0 -784
  68. go_diff-1.1.0/go_diff/noisers/__init__.py +0 -1
  69. go_diff-1.1.0/go_diff/noisers/weighted_pos.py +0 -59
  70. go_diff-1.1.0/tests/test_temperature.py +0 -81
  71. {go_diff-1.1.0 → go_diff-1.3.0}/.github/workflows/auto-tag.yml +0 -0
  72. {go_diff-1.1.0 → go_diff-1.3.0}/.github/workflows/publish.yml +0 -0
  73. {go_diff-1.1.0 → go_diff-1.3.0}/.github/workflows/tests.yml +0 -0
  74. {go_diff-1.1.0 → go_diff-1.3.0}/.readthedocs.yaml +0 -0
  75. {go_diff-1.1.0 → go_diff-1.3.0}/LICENSE +0 -0
  76. {go_diff-1.1.0 → go_diff-1.3.0}/docs/Makefile +0 -0
  77. {go_diff-1.1.0 → go_diff-1.3.0}/docs/make.bat +0 -0
  78. {go_diff-1.1.0 → go_diff-1.3.0}/docs/requirements.txt +0 -0
  79. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/conf.py +0 -0
  80. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/index.rst +0 -0
  81. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/installation.rst +0 -0
  82. {go_diff-1.1.0 → go_diff-1.3.0}/docs/source/tutorial/tutorial.rst +0 -0
  83. {go_diff-1.1.0 → go_diff-1.3.0}/go_diff/utils.py +0 -0
  84. {go_diff-1.1.0 → go_diff-1.3.0}/tests/__init__.py +0 -0
  85. {go_diff-1.1.0 → go_diff-1.3.0}/tests/test_sample_controller.py +0 -0
@@ -9,3 +9,6 @@ docs/_build
9
9
  logs/
10
10
  wandb/
11
11
  .coverage-html/
12
+
13
+ # Claude Code worktrees and local settings
14
+ .claude/
@@ -1,15 +1,17 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: GO-Diff
3
- Version: 1.1.0
3
+ Version: 1.3.0
4
4
  Summary: GO-Diff
5
5
  License-File: LICENSE
6
6
  Requires-Python: >=3.12
7
- Requires-Dist: agedi[full]>=1.0.0
7
+ Requires-Dist: agedi[full]>=1.5.0
8
8
  Requires-Dist: ase
9
9
  Requires-Dist: lightning
10
10
  Requires-Dist: matplotlib
11
11
  Requires-Dist: numpy
12
12
  Requires-Dist: pandas
13
+ Requires-Dist: pyyaml
14
+ Requires-Dist: rich
13
15
  Requires-Dist: rich-click
14
16
  Requires-Dist: seaborn
15
17
  Requires-Dist: tensorboard
@@ -101,6 +103,28 @@ godiff = GODiff(
101
103
  trainer_config={
102
104
  "name": name
103
105
  },
106
+ # Opt-in: relax each sample with the diffusion model's own force-field
107
+ # regressor (requires AGeDi >= 1.5.0 and force_field=True above) before
108
+ # it reaches the real calculator. None (the default) leaves this off;
109
+ # an empty dict turns it on with fmax=0.05, steps=200. batch_size
110
+ # mirrors the sampling batch size unless set here explicitly.
111
+ # relax_config={
112
+ # "fmax": 0.05,
113
+ # "steps": 200,
114
+ # },
115
+ # Opt-in: source roughly half of each sampling call's structures from
116
+ # agedi.inpaint (requires AGeDi >= 1.5.0) by regenerating a small
117
+ # contiguous patch of a replay-buffer structure, instead of always
118
+ # generating de novo from noise. None (the default) leaves this off;
119
+ # an empty dict turns it on with portion=0.5, fraction=0.20,
120
+ # contiguous=True, and a random t_start in (0.4, 0.8) per call. Falls
121
+ # back to pure de-novo sampling whenever the buffer is empty (e.g.
122
+ # iteration 0) or has no eligible parent.
123
+ # inpaint_config={
124
+ # "portion": 0.5,
125
+ # "fraction": 0.20,
126
+ # "contiguous": True,
127
+ # },
104
128
  min_E=min_E,
105
129
  valid_structure_filters=[MinEnergyFilter(-200)],
106
130
  )
@@ -125,6 +149,50 @@ See `scripts/*.py` for the full scripts.
125
149
  | `AdaptiveRefinementStop` | Stop criterion based on split-batch gradient agreement EMA |
126
150
  | `WeightedPositions` | Boltzmann-weighted position noiser for the diffusion model |
127
151
  | `GODiffLogger` | TensorBoard logger (energies, ESS, timing, analysis figures) |
152
+ | `Reporter` | Console output sink every controller and `GODiff.run()` write through |
153
+
154
+ ---
155
+
156
+ ## Run output
157
+
158
+ `GODiff.run()` writes into the trainer's log directory (`logs/<name>/version_<N>`
159
+ by default; see `trainer_config={"name": ...}` above):
160
+
161
+ ```
162
+ logs/<name>/version_N/
163
+ progress.md # markdown table, one row per iteration -- tail this
164
+ metrics.jsonl # one JSON object per iteration, for scripted analysis
165
+ config.yaml # resolved run configuration, written once at start
166
+ best.traj # global-best structure, one frame per iteration
167
+ all_data.traj # every evaluated structure, unchanged from before
168
+ last_good_state.pt # NaN-guard rollback anchor, unchanged from before
169
+ final_model.ckpt # final checkpoint, unchanged from before
170
+ checkpoints/ # AGeDi's own best_model.ckpt / last_model.ckpt
171
+ iter_0000/
172
+ samples.traj # this iteration's newly evaluated structures
173
+ buffer.traj # the replay buffer after this iteration
174
+ model.ckpt # written every `checkpoint_every` iterations (default 3)
175
+ summary.txt # plain-text twin of the console's end-of-iteration panel
176
+ iter_0001/ ...
177
+ ```
178
+
179
+ `checkpoint_every` (constructor arg, default `3`) keeps a checkpoint on a
180
+ stride rather than only the most recent few, so you can reload the model at
181
+ any earlier temperature for transferability checks — `metrics.jsonl` records
182
+ each iteration's temperature and a `"checkpoint": true/false` flag, so a kept
183
+ checkpoint's temperature never needs to be decoded from its filename. Pass
184
+ `checkpoint_every=0` or `None` to disable the per-iteration checkpoint
185
+ entirely (AGeDi's own `checkpoints/best_model.ckpt` / `last_model.ckpt` and
186
+ `final_model.ckpt` still cover "the best" and "the last" model).
187
+
188
+ Console output goes through a single `Reporter` (`go_diff.Reporter`); pass
189
+ `GODiff(..., reporter=Reporter(quiet=True))` to silence it. All output is
190
+ flushed immediately, so it survives a SLURM job being killed mid-iteration.
191
+
192
+ > **Note:** this per-iteration-directory layout replaced an earlier flat one
193
+ > (`iteration_data_T*.traj`, `buffer_T*.traj`, `diffusion_model_T*.ckpt` directly
194
+ > under the run directory). A script reading those paths from an older run needs
195
+ > updating to the layout above.
128
196
 
129
197
  ---
130
198
 
@@ -79,6 +79,28 @@ godiff = GODiff(
79
79
  trainer_config={
80
80
  "name": name
81
81
  },
82
+ # Opt-in: relax each sample with the diffusion model's own force-field
83
+ # regressor (requires AGeDi >= 1.5.0 and force_field=True above) before
84
+ # it reaches the real calculator. None (the default) leaves this off;
85
+ # an empty dict turns it on with fmax=0.05, steps=200. batch_size
86
+ # mirrors the sampling batch size unless set here explicitly.
87
+ # relax_config={
88
+ # "fmax": 0.05,
89
+ # "steps": 200,
90
+ # },
91
+ # Opt-in: source roughly half of each sampling call's structures from
92
+ # agedi.inpaint (requires AGeDi >= 1.5.0) by regenerating a small
93
+ # contiguous patch of a replay-buffer structure, instead of always
94
+ # generating de novo from noise. None (the default) leaves this off;
95
+ # an empty dict turns it on with portion=0.5, fraction=0.20,
96
+ # contiguous=True, and a random t_start in (0.4, 0.8) per call. Falls
97
+ # back to pure de-novo sampling whenever the buffer is empty (e.g.
98
+ # iteration 0) or has no eligible parent.
99
+ # inpaint_config={
100
+ # "portion": 0.5,
101
+ # "fraction": 0.20,
102
+ # "contiguous": True,
103
+ # },
82
104
  min_E=min_E,
83
105
  valid_structure_filters=[MinEnergyFilter(-200)],
84
106
  )
@@ -103,6 +125,50 @@ See `scripts/*.py` for the full scripts.
103
125
  | `AdaptiveRefinementStop` | Stop criterion based on split-batch gradient agreement EMA |
104
126
  | `WeightedPositions` | Boltzmann-weighted position noiser for the diffusion model |
105
127
  | `GODiffLogger` | TensorBoard logger (energies, ESS, timing, analysis figures) |
128
+ | `Reporter` | Console output sink every controller and `GODiff.run()` write through |
129
+
130
+ ---
131
+
132
+ ## Run output
133
+
134
+ `GODiff.run()` writes into the trainer's log directory (`logs/<name>/version_<N>`
135
+ by default; see `trainer_config={"name": ...}` above):
136
+
137
+ ```
138
+ logs/<name>/version_N/
139
+ progress.md # markdown table, one row per iteration -- tail this
140
+ metrics.jsonl # one JSON object per iteration, for scripted analysis
141
+ config.yaml # resolved run configuration, written once at start
142
+ best.traj # global-best structure, one frame per iteration
143
+ all_data.traj # every evaluated structure, unchanged from before
144
+ last_good_state.pt # NaN-guard rollback anchor, unchanged from before
145
+ final_model.ckpt # final checkpoint, unchanged from before
146
+ checkpoints/ # AGeDi's own best_model.ckpt / last_model.ckpt
147
+ iter_0000/
148
+ samples.traj # this iteration's newly evaluated structures
149
+ buffer.traj # the replay buffer after this iteration
150
+ model.ckpt # written every `checkpoint_every` iterations (default 3)
151
+ summary.txt # plain-text twin of the console's end-of-iteration panel
152
+ iter_0001/ ...
153
+ ```
154
+
155
+ `checkpoint_every` (constructor arg, default `3`) keeps a checkpoint on a
156
+ stride rather than only the most recent few, so you can reload the model at
157
+ any earlier temperature for transferability checks — `metrics.jsonl` records
158
+ each iteration's temperature and a `"checkpoint": true/false` flag, so a kept
159
+ checkpoint's temperature never needs to be decoded from its filename. Pass
160
+ `checkpoint_every=0` or `None` to disable the per-iteration checkpoint
161
+ entirely (AGeDi's own `checkpoints/best_model.ckpt` / `last_model.ckpt` and
162
+ `final_model.ckpt` still cover "the best" and "the last" model).
163
+
164
+ Console output goes through a single `Reporter` (`go_diff.Reporter`); pass
165
+ `GODiff(..., reporter=Reporter(quiet=True))` to silence it. All output is
166
+ flushed immediately, so it survives a SLURM job being killed mid-iteration.
167
+
168
+ > **Note:** this per-iteration-directory layout replaced an earlier flat one
169
+ > (`iteration_data_T*.traj`, `buffer_T*.traj`, `diffusion_model_T*.ckpt` directly
170
+ > under the run directory). A script reading those paths from an older run needs
171
+ > updating to the layout above.
106
172
 
107
173
  ---
108
174
 
go_diff-1.3.0/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.3.0
@@ -70,6 +70,51 @@ An ESS equal to *N* means all structures contribute equally; an ESS of 1
70
70
  means a single structure dominates. The :class:`~go_diff.controllers.SampleController`
71
71
  continues sampling until the ESS exceeds a configurable target.
72
72
 
73
+ Oversampling and novelty selection
74
+ ----------------------------------
75
+
76
+ Diffusion sampling is cheap next to a DFT-quality calculator, so there is no
77
+ reason to evaluate every structure the model proposes. Passing a
78
+ :class:`~go_diff.controllers.NoveltySelector` switches each iteration to
79
+ *oversample-then-select*: generate a large candidate pool (1000 structures by
80
+ default, in batches of 256), then hand the calculator only the candidates worth
81
+ the call. The ESS target is unchanged — this decides *which* structures are
82
+ evaluated, not how many.
83
+
84
+ Each candidate is scored by an acquisition written entirely in energy units:
85
+
86
+ .. code-block:: text
87
+
88
+ cost_i = Ê_i + λ · Φ_i, Φ_i = Σ_r exp(-‖f_i - f_r‖² / 2σ²)
89
+
90
+ where ``Ê`` is the energy predicted by the model's force-field regressor, ``f``
91
+ are unit-norm feature vectors from the score model's backbone — the same
92
+ feature space AGeDi's novelty *guidance* repels in — and ``r`` runs over the
93
+ replay buffer *and* over the picks already made this round. The cheapest
94
+ candidate is picked, its own Gaussian penalty is added to ``Φ``, and the ranking
95
+ is redone. This greedy **local penalization** is what keeps a batch from
96
+ collapsing onto one basin: plain top-``k`` ranking would happily return ten
97
+ copies of the same minimum.
98
+
99
+ Writing the trade-off in eV is deliberate. The annealing temperature falls by
100
+ orders of magnitude over a run, so an acquisition of the form ``-E/T - λΦ``
101
+ would silently hand the whole decision to the energy term as the run cools —
102
+ switching novelty off exactly when re-proposal of known minima becomes the
103
+ dominant failure mode. In the form above the temperature cancels out of the
104
+ ``argmax``, and ``λ`` states once, for the whole run, how many eV of excess
105
+ energy a coincident duplicate is worth. Left at ``None`` it is calibrated per
106
+ pool to the interquartile spread of the predicted energies.
107
+
108
+ Selection is skipped on iteration 0, where the score model is untrained and its
109
+ features say nothing about structural similarity, and it degrades to pure
110
+ farthest-point selection when the model has no regressor to predict energies
111
+ with.
112
+
113
+ This complements novelty guidance rather than replacing it: guidance pushes
114
+ samples apart while they are being generated, selection discards the duplicates
115
+ guidance failed to separate. See refs. 4–6 for the batch-selection literature
116
+ this follows.
117
+
73
118
  Adaptive buffer size
74
119
  --------------------
75
120
 
@@ -34,6 +34,11 @@ High-level package layout
34
34
  dimensionless heat capacity C(T) = Var(E) / T²
35
35
  - ``SampleController``: stops sampling when the Effective Sample Size (ESS)
36
36
  reaches a target threshold
37
+ - ``NoveltySelector``: oversamples a large candidate pool and evaluates only
38
+ the candidates that are low in predicted energy and dissimilar to both the
39
+ buffer and each other
40
+ - ``NoveltySchedule``: ramps AGeDi's novelty guidance up as the temperature
41
+ anneals
37
42
  - ``MomentumConsensusStop``: stops training when gradient–momentum cosine
38
43
  similarity drops below a fraction of its peak value
39
44
  - ``AdaptiveRefinementStop``: alternative stop criterion based on split-batch
@@ -19,6 +19,24 @@ Primary publications
19
19
  **Physical Review B** **110**, 235427 (2024).
20
20
  DOI: https://doi.org/10.1103/PhysRevB.110.235427
21
21
 
22
+ Methods adopted from other work
23
+ -------------------------------
24
+
25
+ 4. J. González, Z. Dai, P. Hennig and N. D. Lawrence,
26
+ *Batch Bayesian Optimization via Local Penalization*,
27
+ **AISTATS 2016**, PMLR **51**, 648–657.
28
+ URL: https://proceedings.mlr.press/v51/gonzalez16a.html
29
+
30
+ 5. M. K. Bisbo and B. Hammer,
31
+ *Global optimization of atomistic structure enhanced by machine learning*
32
+ (GOFEE), **Physical Review B** **105**, 245404 (2022).
33
+ DOI: https://doi.org/10.1103/PhysRevB.105.245404
34
+
35
+ 6. G. Corso, Y. Xu, V. De Bortoli, R. Barzilay and T. Jaakkola,
36
+ *Particle Guidance: non-I.I.D. Diverse Sampling with Diffusion Models*,
37
+ **ICLR 2024**.
38
+ URL: https://arxiv.org/abs/2310.13102
39
+
22
40
  How this documentation maps to the papers
23
41
  ------------------------------------------
24
42
 
@@ -28,6 +46,11 @@ How this documentation maps to the papers
28
46
  model in GO-Diff is presented in ref. 2
29
47
  - The surface supported diffusion model including its confinement and
30
48
  correspond methodology is introduced in ref. 3.
49
+ - The greedy quality-diversity rule behind
50
+ :class:`~go_diff.controllers.NoveltySelector` is the local penalization of
51
+ ref. 4, applied in the learned feature space of ref. 6 rather than to a
52
+ Gaussian-process acquisition. Enforcing feature-space diversity among the
53
+ candidates a global-optimisation loop evaluates follows ref. 5.
31
54
 
32
55
 
33
56
  Suggested citation
@@ -17,6 +17,28 @@ Sampling pitfalls
17
17
  *Fix*: Change ``valid_structure_filters`` to fit the system you are
18
18
  investigating.
19
19
 
20
+ - **High-energy structures pollute the dataset**
21
+
22
+ ``all_data`` is not just an archive: it sets the annealing temperature
23
+ through ``std(E)``, it is what the ESS is measured on, and — when
24
+ ``dataset_config`` requests ``regressor_data`` — it is what the force-field
25
+ regressor trains on. A handful of blown-up structures skew all three. Note
26
+ that ``buffer_filters`` gate only *buffer* membership, so they do not help
27
+ here.
28
+
29
+ *Fix*: ``GODiff`` discards anything more than ``energy_window`` eV above the
30
+ best energy found so far, 50 eV by default, before it can reach
31
+ ``all_data``. "Best so far" means the best energy that was *kept*: the
32
+ window is applied after ``after_potential_filters``, so a spuriously deep
33
+ false minimum that ``MinEnergyFilter`` rejects does not become the reference
34
+ point either. That ordering matters — a false minimum allowed to set the
35
+ reference would drop the threshold thousands of eV below anything physical
36
+ and discard every real structure from then on. Narrow the window for a tightly-bound system, widen it if the
37
+ guard is trimming structures you want to keep, or pass ``energy_window=None``
38
+ to switch it off. Watch ``iteration/n_discarded_energy_window`` in
39
+ TensorBoard: a persistently high count means the model is spending calculator
40
+ calls on structures the run then throws away.
41
+
20
42
  - **ESS target never reached**
21
43
 
22
44
  If ``SampleController`` keeps sampling until ``max_N`` is hit without
@@ -69,6 +91,29 @@ Training pitfalls
69
91
  *Fix*: set ``min_steps`` to at least 50–100 steps. A larger ``patience``
70
92
  value also helps.
71
93
 
94
+ - **Training produces NaN and the run never recovers**
95
+
96
+ Once the loss goes ``nan`` nothing in the default stack notices.
97
+ ``MomentumConsensusStop`` compares against a ``nan`` agreement, and *every*
98
+ comparison against ``nan`` is ``False``, so its stopping condition cannot
99
+ fire. ``ReduceLROnPlateau`` sees a ``val_loss`` that never improves and
100
+ merely decays the learning rate. The run trains on garbage until its
101
+ wall-clock limit expires.
102
+
103
+ *Fix*: ``GODiff`` installs a ``NaNGuard`` callback by default. It trips on
104
+ the first non-finite loss, gradient or parameter, stops the stage, and makes
105
+ :meth:`~go_diff.GODiff.run` restore the model from ``last_good_state.pt`` in
106
+ the log directory and retry the same iteration — re-annealing from where the
107
+ failed iteration started. Evaluated structures are kept across a rollback;
108
+ only the model and the schedules are rewound. After ``max_nan_retries``
109
+ consecutive failures (3 by default) the run restores the last good model and
110
+ stops cleanly. ``iteration/nan_rollbacks`` in TensorBoard marks the affected
111
+ iterations. Pass ``nan_guard=False`` to disable.
112
+
113
+ A recurring NaN usually means the learning rate is too high or the buffer
114
+ contains a structure with an extreme energy; lowering ``lr`` in
115
+ ``create_diffusion`` and narrowing ``energy_window`` both help.
116
+
72
117
  - **AdaptiveRefinementStop requires batch size ≥ 4**
73
118
 
74
119
  The split-batch gradient agreement cannot be computed when the mini-batch
@@ -114,6 +114,40 @@ z-coordinate range within which new atoms are generated. Setting
114
114
  – waits at least 100 training steps then stops when gradient–momentum
115
115
  agreement has been below 90 % of its peak for 250 steps.
116
116
 
117
+ **Spending fewer calculator calls (optional)**
118
+
119
+ When the calculator is the bottleneck — DFT, or a slow MLIP — add a
120
+ :class:`~go_diff.controllers.NoveltySelector`:
121
+
122
+ .. code-block:: python
123
+
124
+ from go_diff.controllers import NoveltySelector
125
+
126
+ godiff = GODiff(
127
+ ...,
128
+ novelty_selector=NoveltySelector(),
129
+ )
130
+
131
+ Each iteration then generates 1000 candidates in batches of 256 and evaluates
132
+ only those that are low in predicted energy and unlike anything already in the
133
+ buffer, until the same ESS target is met. The ESS target and ``max_N`` are
134
+ unchanged, so the calculator budget per iteration does not grow — the pool just
135
+ gives the selector something to choose from.
136
+
137
+ Two knobs matter in practice:
138
+
139
+ * ``sigma`` (default ``0.5``) – the feature distance below which two structures
140
+ count as duplicates. Match it to the ``sigma`` of any
141
+ ``NoveltyGuidanceConfig`` you pass in ``sample_config``.
142
+ * ``energy_penalty`` – how many eV of excess energy a duplicate is worth.
143
+ Leave it at ``None`` to calibrate it per iteration from the spread of
144
+ predicted energies, or pin it (e.g. ``0.5``) once you know your system's
145
+ energy scale.
146
+
147
+ Predicted energies need a model trained with a force-field regressor (see
148
+ ``regressor_data`` in ``dataset_config``); without one the selector still runs,
149
+ picking on novelty alone.
150
+
117
151
  **GODiff.run**
118
152
 
119
153
  Calling ``godiff.run(max_iterations=20)`` starts the outer loop. Output is
@@ -133,6 +167,8 @@ Monitoring with TensorBoard
133
167
  Key scalars to watch:
134
168
 
135
169
  * ``iteration/best_energy`` – global minimum energy found so far.
170
+ * ``selection/accept_fraction`` – with a ``NoveltySelector``, the share of
171
+ generated candidates that reached the calculator.
136
172
  * ``iteration/ess`` – effective sample size per iteration.
137
173
  * ``iteration/temperature`` – annealing temperature.
138
174
  * ``train/gradient_agreement_current`` – gradient–momentum cosine similarity.
@@ -0,0 +1,14 @@
1
+ from .go_diff import GODiff
2
+ from .logger import GODiffLogger
3
+ from .reporter import Reporter
4
+ from .filter import (
5
+ Filter,
6
+ MinEnergyFilter,
7
+ MaxEnergyFilter,
8
+ MinDistFilter,
9
+ PeriodicMinDistFilter,
10
+ ConfinementFilter,
11
+ ConnectivityFilter,
12
+ FiniteFilter,
13
+ EnergyWindowFilter,
14
+ )
@@ -0,0 +1,15 @@
1
+ from .training import (
2
+ MomentumConsensusStop,
3
+ AdaptiveRefinementStop,
4
+ FlopsAndTimingCallback,
5
+ NaNGuard,
6
+ model_is_finite,
7
+ )
8
+ from .sample import SampleController
9
+ from .temperature import TemperatureSchedule
10
+ from .buffer import BufferController
11
+ from .novelty import NoveltySchedule, NoveltyGuidanceSchedule
12
+ from .archive import NoveltyArchive
13
+ from .selection import NoveltySelector
14
+ from .weighting import NoveltyWeighting, BufferWeightingSchedule, BufferEvictionSchedule
15
+ from .forcefield import ForcefieldGuidanceSchedule
@@ -0,0 +1,156 @@
1
+ """A persistent, deduplicated reference set for feature-space novelty guidance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, List, Optional
6
+
7
+ import numpy as np
8
+ from ase import Atoms
9
+
10
+
11
+ class NoveltyArchive:
12
+ """A monotonically-growing, deduplicated reference set for novelty guidance.
13
+
14
+ ``novelty_guidance``'s default reference set is the live buffer, which is
15
+ rebuilt by weighted reservoir sampling every iteration (see
16
+ :meth:`~go_diff.GODiff.update_buffer`) and can lose track of a region it
17
+ already explored once that region's structures age out of the buffer.
18
+ This archive instead keeps every sufficiently-distinct structure GO-Diff
19
+ has ever accepted, in the score model's own feature space, and never
20
+ forgets one -- so repulsion always sees the *complete* set of
21
+ already-found structural families, not just whatever the buffer
22
+ currently happens to hold.
23
+
24
+ A structure is added when its nearest-neighbour distance, in the
25
+ **current** model generation's feature space, to every existing archive
26
+ member exceeds ``dedup_sigma``. Because features are only comparable
27
+ within one model generation (they live in the backbone's activation
28
+ space and are meaningless across retrainings -- the same reasoning
29
+ behind :meth:`~go_diff.GODiff.featurise` never caching), the whole
30
+ archive is re-featurised and re-deduplicated from scratch on every
31
+ :meth:`update` call, using whatever score model :meth:`update` is called
32
+ with at that moment.
33
+
34
+ Parameters
35
+ ----------
36
+ dedup_sigma : float or None
37
+ Feature-space distance (unit-normalised features lie in ``[0, 2]``)
38
+ below which a candidate counts as a duplicate of an existing member
39
+ and is not added. ``None`` (default) resolves it the same way
40
+ ``NoveltyGuidanceConfig``'s own ``sigma`` does: the
41
+ ``dedup_sigma_quantile`` quantile of the pool's own pairwise
42
+ distances, recomputed on every call -- a fixed number in a feature
43
+ space rebuilt every retraining is a guess.
44
+ dedup_sigma_quantile : float
45
+ Quantile used when ``dedup_sigma`` is ``None``. Default ``0.05``,
46
+ matching ``NoveltyGuidanceConfig``'s own default.
47
+ max_size : int or None
48
+ Optional cap on the archive size. When adding structures would
49
+ exceed it, the most *redundant* members (smallest nearest-neighbour
50
+ distance to the rest of the archive) are dropped first, so the
51
+ archive stays maximally spread out in feature space rather than
52
+ shrinking by recency. ``None`` (default) never prunes.
53
+
54
+ Examples
55
+ --------
56
+ ::
57
+
58
+ from go_diff.controllers import NoveltyArchive
59
+
60
+ GODiff(..., novelty_archive=NoveltyArchive(max_size=256))
61
+ """
62
+
63
+ def __init__(
64
+ self,
65
+ dedup_sigma: Optional[float] = None,
66
+ dedup_sigma_quantile: float = 0.05,
67
+ max_size: Optional[int] = None,
68
+ ) -> None:
69
+ if dedup_sigma is not None and dedup_sigma <= 0.0:
70
+ raise ValueError(f"dedup_sigma must be positive, got {dedup_sigma}")
71
+ if not 0.0 < dedup_sigma_quantile < 1.0:
72
+ raise ValueError(
73
+ f"dedup_sigma_quantile must lie in (0, 1), got {dedup_sigma_quantile}"
74
+ )
75
+ if max_size is not None and max_size < 1:
76
+ raise ValueError(f"max_size must be >= 1, got {max_size}")
77
+
78
+ self.dedup_sigma = dedup_sigma
79
+ self.dedup_sigma_quantile = dedup_sigma_quantile
80
+ self.max_size = max_size
81
+
82
+ self.structures: List[Atoms] = []
83
+
84
+ def update(
85
+ self,
86
+ candidates: List[Atoms],
87
+ featurise: Callable[[List[Atoms]], Optional[np.ndarray]],
88
+ ) -> None:
89
+ """Add sufficiently-distinct structures from *candidates* to the archive.
90
+
91
+ Parameters
92
+ ----------
93
+ candidates : list of ase.Atoms
94
+ Newly accepted structures to consider adding. Structures already
95
+ in the archive are always kept regardless of *candidates*.
96
+ featurise : callable
97
+ ``GODiff.featurise``-compatible: ``list[Atoms] -> np.ndarray | None``.
98
+ Called with the archive's current members plus *candidates*
99
+ together, so distances are measured in a single consistent
100
+ feature space.
101
+ """
102
+ if not candidates:
103
+ return
104
+
105
+ pool = self.structures + list(candidates)
106
+ features = featurise(pool)
107
+
108
+ if features is None:
109
+ # No features available (e.g. an AGeDi build without
110
+ # agedi.diffusion.novelty) -- keep everything rather than
111
+ # silently discarding candidates, the same escape hatch
112
+ # GODiff.draw_weights falls back to.
113
+ self.structures = pool
114
+ return
115
+
116
+ n_old = len(self.structures)
117
+ dist = np.linalg.norm(features[:, None, :] - features[None, :, :], axis=-1)
118
+ np.fill_diagonal(dist, np.inf)
119
+
120
+ sigma = self.dedup_sigma
121
+ if sigma is None:
122
+ finite = dist[np.isfinite(dist)]
123
+ sigma = (
124
+ float(np.quantile(finite, self.dedup_sigma_quantile))
125
+ if finite.size
126
+ else 1.0
127
+ )
128
+
129
+ keep = list(range(n_old)) # existing members are always kept
130
+ for i in range(n_old, len(pool)):
131
+ nearest = dist[i, keep].min() if keep else np.inf
132
+ if nearest >= sigma:
133
+ keep.append(i)
134
+
135
+ self.structures = [pool[i] for i in keep]
136
+
137
+ if self.max_size is not None and len(self.structures) > self.max_size:
138
+ kept_features = features[keep]
139
+ kd = np.linalg.norm(
140
+ kept_features[:, None, :] - kept_features[None, :, :], axis=-1
141
+ )
142
+ np.fill_diagonal(kd, np.inf)
143
+ nn_dist = kd.min(axis=1)
144
+ # Largest nearest-neighbour distance first = most distinct =
145
+ # kept; smallest = most redundant = dropped first.
146
+ order = np.argsort(-nn_dist)
147
+ self.structures = [
148
+ self.structures[i] for i in order[: self.max_size]
149
+ ]
150
+
151
+ def get_reference(self) -> List[Atoms]:
152
+ """Return the current archive as a ``novelty_reference`` list."""
153
+ return self.structures
154
+
155
+ def __len__(self) -> int:
156
+ return len(self.structures)
@@ -34,6 +34,10 @@ class BufferController:
34
34
 
35
35
  self.current_buffer_size = initial_buffer_size
36
36
 
37
+ # Target size from the most recent update_buffer_size() call, before
38
+ # exponential smoothing -- explains *why* the buffer resized.
39
+ self.last_target_size: int | None = None
40
+
37
41
  # ------------------------------------------------------------------
38
42
  # Public API
39
43
  # ------------------------------------------------------------------
@@ -70,6 +74,7 @@ class BufferController:
70
74
 
71
75
  ess = self.compute_ess(energies, temperature)
72
76
  target_B = int(ess)
77
+ self.last_target_size = target_B
73
78
 
74
79
  new_B = (1.0 - self.adaptation_rate) * self.current_buffer_size + self.adaptation_rate * target_B
75
80
  self.current_buffer_size = int(np.clip(new_B, self.min_buffer_size, self.max_buffer_size))