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/go_diff.py ADDED
@@ -0,0 +1,751 @@
1
+ """Core GO-Diff optimisation loop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from pathlib import Path
7
+ from typing import Protocol, runtime_checkable
8
+ from copy import deepcopy
9
+
10
+ import numpy as np
11
+ from numpy.typing import ArrayLike
12
+
13
+ from ase import Atoms
14
+ from ase.constraints import FixAtoms
15
+ from ase.calculators.singlepoint import SinglePointCalculator as SPC
16
+ from ase.io import write, Trajectory
17
+
18
+ # AGeDi
19
+ from agedi import create_dataset, create_trainer, train, sample
20
+
21
+ # GO-Diff
22
+ from .filter import (
23
+ Filter,
24
+ MinEnergyFilter,
25
+ MaxEnergyFilter,
26
+ )
27
+ from go_diff.controllers import (
28
+ TemperatureSchedule,
29
+ SampleController,
30
+ BufferController,
31
+ MomentumConsensusStop,
32
+ FlopsAndTimingCallback,
33
+ )
34
+ from go_diff.utils import boltzmann_weights, effective_sample_size
35
+ from .logger import GODiffLogger
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Protocol definitions
40
+ # ---------------------------------------------------------------------------
41
+
42
+ @runtime_checkable
43
+ class Calculator(Protocol):
44
+ """Minimal interface expected of an ASE-compatible energy/force calculator."""
45
+
46
+ def get_potential_energy(self) -> float: ...
47
+ def get_forces(self) -> np.ndarray: ...
48
+
49
+
50
+ @runtime_checkable
51
+ class DiffusionModel(Protocol):
52
+ """Minimal interface expected of an AGeDi diffusion model."""
53
+
54
+ def to(self, device: str) -> "DiffusionModel": ...
55
+
56
+
57
+ @runtime_checkable
58
+ class TrainingController(Protocol):
59
+ """Minimal interface expected of a Lightning training-stop callback."""
60
+
61
+ def set_logger(self, logger: object) -> None: ...
62
+
63
+
64
+ class GODiff:
65
+ """Gradient-Optimised Diffusion model for atomic structure search.
66
+
67
+ Implements an iterative training procedure with adaptive temperature
68
+ annealing. At each iteration:
69
+
70
+ 1. **Sample** candidate structures from the current diffusion model.
71
+ 2. **Evaluate** their energies and forces with the provided calculator.
72
+ 3. **Build a replay buffer** using Boltzmann-weighted prioritised sampling.
73
+ 4. **Retrain** the diffusion model on the buffer until the training
74
+ controller signals convergence.
75
+ 5. **Update the temperature** schedule for the next iteration.
76
+
77
+ Parameters
78
+ ----------
79
+ calculator : Calculator
80
+ ASE-compatible calculator used to evaluate potential energies and
81
+ forces (must implement :class:`Calculator`).
82
+ diffusion : DiffusionModel
83
+ Diffusion model created with :func:`agedi.create_diffusion` (must
84
+ implement :class:`DiffusionModel`).
85
+ temperature_schedule : TemperatureSchedule
86
+ Controls the annealing temperature. Defaults to
87
+ ``TemperatureSchedule()``.
88
+ sample_controller : SampleController
89
+ Decides when enough structures have been collected per iteration.
90
+ Defaults to ``SampleController()``.
91
+ buffer_controller : BufferController
92
+ Controls the replay buffer size. Defaults to ``BufferController()``.
93
+ training_controller : TrainingController
94
+ Decides when to stop training each iteration (must implement
95
+ :class:`TrainingController`). Defaults to
96
+ ``MomentumConsensusStop()``.
97
+ sample_config : dict
98
+ Keyword arguments forwarded to :func:`agedi.sample`. Common keys:
99
+ ``template``, ``atomic_numbers``, ``ForceFieldGuidanceConfig``.
100
+ dataset_config : dict
101
+ Keyword arguments forwarded to :func:`agedi.create_dataset`. Common
102
+ keys: ``mask``, ``confinement``, ``regressor_data``.
103
+ batch_size : int
104
+ Mini-batch size used to estimate the number of training epochs per
105
+ iteration. Default: 32.
106
+ max_steps_per_loop : int
107
+ Maximum number of training steps per GO-Diff iteration. Default: 500.
108
+ valid_structure_filters : list of Filter or None, optional
109
+ Sequence of callables ``(atoms: Atoms) -> bool`` applied right after
110
+ energy/force evaluation to discard physically unreasonable structures.
111
+ Discarded structures are never added to ``all_data`` or the buffer.
112
+ Defaults to ``None`` (no filtering). Pass
113
+ ``[MinEnergyFilter(-500.0)]`` to replicate the former
114
+ ``GODiff(min_E=-500.0)`` behaviour.
115
+ buffer_filters : list of Filter, optional
116
+ Sequence of callables ``(atoms: Atoms) -> bool`` applied when
117
+ rebuilding the buffer from ``all_data``. A structure from
118
+ ``all_data`` is included in the buffer candidate pool only when
119
+ **all** filters return ``True``. Defaults to
120
+ ``[MaxEnergyFilter(0.0)]``, which restricts the buffer to structures
121
+ with negative energy — reproducing the historical silent ``e < 0.0``
122
+ filter. Use an empty list (``[]``) to disable buffer-level filtering.
123
+ device : str
124
+ Device passed to the trainer / sampler. Default: ``"cuda"``.
125
+ """
126
+
127
+ def __init__(
128
+ self,
129
+ calculator: Calculator,
130
+ diffusion: DiffusionModel,
131
+ temperature_schedule: TemperatureSchedule | None = None,
132
+ sample_controller: SampleController | None = None,
133
+ buffer_controller: BufferController | None = None,
134
+ training_controller: TrainingController | None = None,
135
+ sample_config: dict | None = None,
136
+ dataset_config: dict | None = None,
137
+ trainer_config: dict | None = None,
138
+ batch_size: int = 32,
139
+ sample_batch_size: int = 16,
140
+ max_steps_per_loop: int = 500,
141
+ valid_structure_filters: list[Filter] | None = None,
142
+ buffer_filters: list[Filter] | None = None,
143
+ device: str = "cuda",
144
+ ) -> None:
145
+ self.calculator = calculator
146
+ self.diffusion = diffusion
147
+ self.temperature_schedule = temperature_schedule or TemperatureSchedule()
148
+ self.sample_controller = sample_controller or SampleController()
149
+ self.training_controller = training_controller or MomentumConsensusStop()
150
+ self.buffer_controller = buffer_controller or BufferController()
151
+
152
+ self.sample_config: dict = sample_config or {}
153
+ self.dataset_config: dict = dataset_config or {}
154
+ self.trainer_config: dict = trainer_config or {}
155
+
156
+ self.batch_size: int = batch_size
157
+ self.sample_batch_size: int = sample_batch_size
158
+ self.max_steps_per_loop: int = max_steps_per_loop
159
+ self.valid_structure_filters: list[Filter] | None = valid_structure_filters
160
+ self.buffer_filters: list[Filter] = (
161
+ buffer_filters if buffer_filters is not None else [MaxEnergyFilter(0.0)]
162
+ )
163
+ self.device: str = device
164
+
165
+ self._godiff_logger: GODiffLogger | None = None
166
+ self._flops_timing_cb: FlopsAndTimingCallback | None = None
167
+ self.trainer: object | None = None
168
+
169
+ self.buffer: list[Atoms] = []
170
+ self.all_data: list[Atoms] = []
171
+
172
+ # ------------------------------------------------------------------
173
+ # Trainer setup
174
+ # ------------------------------------------------------------------
175
+
176
+ def _get_trainer(self, max_time_hours: float = 64) -> None:
177
+ """Create and store a PyTorch Lightning trainer.
178
+
179
+ Parameters
180
+ ----------
181
+ max_time_hours : float
182
+ Maximum wall-clock training time in hours passed to
183
+ :func:`agedi.create_trainer`. Default: 64.
184
+ """
185
+ self._flops_timing_cb = FlopsAndTimingCallback()
186
+
187
+ callbacks = [
188
+ self.training_controller,
189
+ self._flops_timing_cb,
190
+ ]
191
+
192
+ self.trainer = create_trainer(
193
+ max_time={"hours": max_time_hours},
194
+ extra_callbacks=callbacks,
195
+ **self.trainer_config,
196
+ )
197
+
198
+ # ------------------------------------------------------------------
199
+ # Sampling & evaluation
200
+ # ------------------------------------------------------------------
201
+
202
+ def sample(self, exclude_keys: set[str] | None = None) -> list[Atoms]:
203
+ """Sample structures from the current diffusion model.
204
+
205
+ Uses :attr:`sample_config` as keyword arguments forwarded to
206
+ :func:`agedi.sample`. When a ``"template"`` is present the template
207
+ atoms are frozen via :class:`ase.constraints.FixAtoms`.
208
+
209
+ Parameters
210
+ ----------
211
+ exclude_keys : set of str or None
212
+ Keys to temporarily omit from :attr:`sample_config` for this call.
213
+ Useful for suppressing optional guidance on the first iteration.
214
+
215
+ Returns
216
+ -------
217
+ list of ase.Atoms
218
+ Sampled structures.
219
+ """
220
+ config = dict(self.sample_config)
221
+ if exclude_keys:
222
+ for key in exclude_keys:
223
+ config.pop(key, None)
224
+ n_samples = config.pop("n_samples", self.sample_batch_size)
225
+
226
+ atoms_list = sample(self.diffusion, n_samples=n_samples, **config)
227
+
228
+ template = config.get("template")
229
+ if template is not None:
230
+ template_len = len(template)
231
+ for atoms in atoms_list:
232
+ atoms.set_constraint(
233
+ FixAtoms(
234
+ mask=[atom.index < template_len for atom in atoms]
235
+ )
236
+ )
237
+
238
+ return atoms_list
239
+
240
+ def evaluate(
241
+ self,
242
+ atoms_list: list[Atoms],
243
+ iteration: int | None = None,
244
+ ) -> list[Atoms]:
245
+ """Evaluate energies and forces for a list of structures in-place.
246
+
247
+ Each structure's calculator is replaced with a
248
+ :class:`~ase.calculators.singlepoint.SinglePointCalculator` that
249
+ stores the computed energy and forces so they can be retrieved later
250
+ without re-running the (potentially expensive) calculator.
251
+
252
+ Parameters
253
+ ----------
254
+ atoms_list : list of ase.Atoms
255
+ Structures to evaluate.
256
+ iteration : int or None
257
+ If provided, stored as the calculator name for bookkeeping.
258
+
259
+ Returns
260
+ -------
261
+ list of ase.Atoms
262
+ The same structures with updated calculators.
263
+ """
264
+ for atoms in atoms_list:
265
+ atoms.calc = self.calculator
266
+ e = atoms.get_potential_energy()
267
+ f = atoms.get_forces(apply_constraint=False)
268
+ atoms.calc = SPC(atoms, energy=e, forces=f)
269
+ if iteration is not None:
270
+ atoms.calc.name = f"Iteration{iteration}"
271
+
272
+ return atoms_list
273
+
274
+ def check_min_dist(
275
+ self,
276
+ atoms_list: list[Atoms],
277
+ min_dist: float = 1.0,
278
+ ) -> list[Atoms]:
279
+ """Filter structures with interatomic distances below *min_dist*.
280
+
281
+ Parameters
282
+ ----------
283
+ atoms_list : list of ase.Atoms
284
+ Structures to filter.
285
+ min_dist : float
286
+ Minimum allowed distance (Å) between any pair of atoms.
287
+ Default: 1.0.
288
+
289
+ Returns
290
+ -------
291
+ list of ase.Atoms
292
+ Structures in which all pairwise distances are ≥ *min_dist*.
293
+ """
294
+ filtered: list[Atoms] = []
295
+ for atoms in atoms_list:
296
+ positions = atoms.get_positions()
297
+ dists = np.linalg.norm(
298
+ positions[:, np.newaxis] - positions, axis=-1
299
+ )
300
+ np.fill_diagonal(dists, np.inf)
301
+ if float(np.min(dists)) >= min_dist:
302
+ filtered.append(atoms)
303
+ return filtered
304
+
305
+ # ------------------------------------------------------------------
306
+ # Boltzmann weighting helpers
307
+ # ------------------------------------------------------------------
308
+
309
+ def compute_weights(self, data: list[Atoms]) -> np.ndarray:
310
+ """Compute Boltzmann importance weights for a set of structures.
311
+
312
+ Weights are normalised so that their sum equals ``len(data)``.
313
+ Uses the current temperature from :attr:`temperature_schedule`.
314
+
315
+ Parameters
316
+ ----------
317
+ data : list of ase.Atoms
318
+ Structures with energies already attached.
319
+
320
+ Returns
321
+ -------
322
+ np.ndarray of float, shape ``(len(data),)``
323
+ Boltzmann importance weights, summing to ``len(data)``.
324
+ """
325
+ temperature = self.temperature_schedule.get_temperature()
326
+ energies = np.array([atoms.get_potential_energy() for atoms in data])
327
+ return boltzmann_weights(energies, temperature)
328
+
329
+ def compute_ess(self, data: list[Atoms]) -> float:
330
+ """Compute the Effective Sample Size (ESS) for a set of structures.
331
+
332
+ Parameters
333
+ ----------
334
+ data : list of ase.Atoms
335
+ Structures with energies attached.
336
+
337
+ Returns
338
+ -------
339
+ float
340
+ The ESS (between 1 and len(data)).
341
+ """
342
+ temperature = self.temperature_schedule.get_temperature()
343
+ energies = np.array([atoms.get_potential_energy() for atoms in data])
344
+ return effective_sample_size(energies, temperature)
345
+
346
+ def get_properties(
347
+ self,
348
+ atoms_list: list[Atoms],
349
+ ) -> list[dict]:
350
+ """Compute Boltzmann weights, energies, and forces for each structure.
351
+
352
+ Parameters
353
+ ----------
354
+ atoms_list : list of ase.Atoms
355
+ Structures with energies and forces already computed.
356
+
357
+ Returns
358
+ -------
359
+ list of dict
360
+ Each dict contains ``'weight'`` (float), ``'energy'`` (float),
361
+ and ``'forces'`` (np.ndarray).
362
+ """
363
+ energies = np.array(
364
+ [atoms.get_potential_energy() for atoms in atoms_list]
365
+ )
366
+ forces = [
367
+ atoms.get_forces(apply_constraint=False) for atoms in atoms_list
368
+ ]
369
+ weights = self.compute_weights(atoms_list)
370
+
371
+ return [
372
+ {"weight": float(w), "energy": float(e), "forces": f}
373
+ for w, e, f in zip(weights, energies, forces)
374
+ ]
375
+
376
+ # ------------------------------------------------------------------
377
+ # Trajectory I/O
378
+ # ------------------------------------------------------------------
379
+
380
+ def save_trajectory(
381
+ self,
382
+ atoms_list: list[Atoms],
383
+ path: str | Path | None = None,
384
+ writer: object | None = None,
385
+ ) -> None:
386
+ """Save structures (sorted by energy) to a trajectory file.
387
+
388
+ At least one of *path* or *writer* must be provided.
389
+
390
+ Parameters
391
+ ----------
392
+ atoms_list : list of ase.Atoms
393
+ Structures to save.
394
+ path : str or Path or None
395
+ If provided, write the trajectory to this file path using
396
+ :func:`ase.io.write`.
397
+ writer : ase.io.Trajectory or None
398
+ If provided, append each structure to this open trajectory writer.
399
+ """
400
+ if path is None and writer is None:
401
+ raise ValueError("Either path or writer must be provided.")
402
+
403
+
404
+ energies = [atoms.get_potential_energy() for atoms in atoms_list]
405
+ traj = [deepcopy(atoms) for atoms in atoms_list]
406
+ argsort = np.argsort(energies)
407
+ traj = [traj[i] for i in argsort]
408
+
409
+ if writer is not None:
410
+ for atoms in traj:
411
+ writer.write(atoms)
412
+
413
+ if path is not None:
414
+ write(str(path), traj)
415
+
416
+ # ------------------------------------------------------------------
417
+ # Buffer management
418
+ # ------------------------------------------------------------------
419
+
420
+ def _apply_valid_structure_filters(self, data: list[Atoms]) -> list[Atoms]:
421
+ """Apply :attr:`valid_structure_filters` to *data* and return survivors.
422
+
423
+ When :attr:`valid_structure_filters` is ``None`` (the default), all
424
+ structures are returned unchanged. Otherwise a structure is kept only
425
+ when **every** filter returns ``True``.
426
+
427
+ Parameters
428
+ ----------
429
+ data : list of ase.Atoms
430
+
431
+ Returns
432
+ -------
433
+ list of ase.Atoms
434
+ """
435
+ if not self.valid_structure_filters:
436
+ return data
437
+ return [
438
+ atoms for atoms in data
439
+ if all(f(atoms) for f in self.valid_structure_filters)
440
+ ]
441
+
442
+ def update_buffer(self) -> None:
443
+ """Rebuild :attr:`buffer` via Boltzmann-weighted prioritised sampling.
444
+
445
+ :attr:`buffer_filters` are applied to :attr:`all_data` to obtain the
446
+ candidate pool; structures rejected by any filter are excluded. When
447
+ fewer candidates than the current buffer size are available, all
448
+ candidates are used. Otherwise a stochastic prioritised subset is
449
+ selected via reservoir-style key-based sorting.
450
+ """
451
+ # Apply buffer-level filters to the full accumulated dataset
452
+ if self.buffer_filters:
453
+ valid_data = [
454
+ atoms for atoms in self.all_data
455
+ if all(f(atoms) for f in self.buffer_filters)
456
+ ]
457
+ else:
458
+ valid_data = self.all_data
459
+
460
+ if not valid_data:
461
+ print(
462
+ "No valid structures at "
463
+ f"T={self.temperature_schedule.temperature}"
464
+ )
465
+ self.buffer = []
466
+ return
467
+
468
+ if len(valid_data) <= self.buffer_controller.get_buffer_size():
469
+ print(
470
+ f"Not enough data, using all {len(valid_data)} valid structures."
471
+ )
472
+ self.buffer = valid_data
473
+ return
474
+
475
+ weights = self.compute_weights(valid_data)
476
+ # Stochastic prioritised sampling: reservoir key trick
477
+ keys = np.random.uniform(size=len(valid_data)) ** (1.0 / weights)
478
+ sorter = np.argsort(keys)[::-1]
479
+ self.buffer = [valid_data[i] for i in sorter[: self.buffer_controller.get_buffer_size()]]
480
+
481
+ # ------------------------------------------------------------------
482
+ # Stage methods
483
+ # ------------------------------------------------------------------
484
+
485
+ def sample_stage(
486
+ self,
487
+ iteration: int,
488
+ data_writer: object,
489
+ logdir: Path,
490
+ exclude_sample_keys: set[str] | None = None,
491
+ ) -> dict:
492
+ """Run one sampling-and-evaluation stage.
493
+
494
+ Samples structures until :attr:`sample_controller` is satisfied,
495
+ evaluates them, filters unphysical structures, updates the temperature,
496
+ and rebuilds the replay buffer.
497
+
498
+ Parameters
499
+ ----------
500
+ iteration : int
501
+ Current outer-loop iteration index (used for logging and file
502
+ naming).
503
+ data_writer : ase.io.Trajectory
504
+ Open trajectory writer for all accumulated structures.
505
+ logdir : pathlib.Path
506
+ Directory for per-iteration trajectory files.
507
+ exclude_sample_keys : set of str or None
508
+ Keys to omit from :attr:`sample_config` for this stage (passed
509
+ through to :meth:`sample`).
510
+
511
+ Returns
512
+ -------
513
+ dict
514
+ Keys: ``temperature``, ``new_energies``, ``new_forces``,
515
+ ``all_energies``, ``all_forces``, ``buffer_energies``,
516
+ ``buffer_forces``, ``ess``, ``sampling_wall_s``,
517
+ ``evaluation_wall_s``.
518
+ """
519
+ current_temperature = self.temperature_schedule.temperature
520
+
521
+ sampling_wall_s = 0.0
522
+ evaluation_wall_s = 0.0
523
+ iteration_data: list[Atoms] = []
524
+
525
+ while self.sample_controller.continue_sampling(
526
+ [a.get_potential_energy() for a in iteration_data],
527
+ current_temperature,
528
+ ):
529
+ t0 = time.perf_counter()
530
+ new_samples = self.sample(exclude_keys=exclude_sample_keys)
531
+ new_samples = self.check_min_dist(new_samples, min_dist=1.0)
532
+ sampling_wall_s += time.perf_counter() - t0
533
+
534
+ t0 = time.perf_counter()
535
+ new_samples = self.evaluate(new_samples, iteration=iteration)
536
+ evaluation_wall_s += time.perf_counter() - t0
537
+
538
+ new_samples = self._apply_valid_structure_filters(new_samples)
539
+ iteration_data.extend(new_samples)
540
+
541
+ # Save this iteration's structures
542
+ name = f"{current_temperature:.3f}" if current_temperature is not None else "initial"
543
+ self.save_trajectory(
544
+ iteration_data,
545
+ path=str(logdir / f"iteration_data_T{name}.traj"),
546
+ writer=data_writer,
547
+ )
548
+
549
+ # Compute ESS *before* updating the temperature
550
+ ess: float | None = None
551
+ if current_temperature is not None and len(iteration_data) > 0:
552
+ ess = self.compute_ess(iteration_data)
553
+
554
+ # Update temperature based on this iteration's energies
555
+ if iteration_data:
556
+ self.temperature_schedule.next(
557
+ [a.get_potential_energy() for a in iteration_data]
558
+ )
559
+
560
+ # Accumulate global dataset
561
+ self.all_data.extend(iteration_data)
562
+
563
+ # Adapt buffer size and rebuild buffer
564
+ if self.all_data:
565
+ # Only call update_adaptive_buffer_size after temperature is set
566
+ if self.temperature_schedule.temperature is not None:
567
+ self.buffer_controller.update_buffer_size(
568
+ [a.get_potential_energy() for a in self.all_data],
569
+ self.temperature_schedule.temperature
570
+ )
571
+ self.update_buffer()
572
+
573
+ # Save buffer
574
+ if self.buffer:
575
+ t_str = f"{self.temperature_schedule.temperature:.2f}"
576
+ self.save_trajectory(
577
+ self.buffer,
578
+ path=str(logdir / f"buffer_T{t_str}.traj"),
579
+ )
580
+
581
+ # Extract arrays for the stage_info dict
582
+ new_energies = (
583
+ np.array([a.get_potential_energy() for a in iteration_data])
584
+ if iteration_data else np.array([])
585
+ )
586
+ new_forces = (
587
+ [a.get_forces(apply_constraint=False) for a in iteration_data]
588
+ if iteration_data else []
589
+ )
590
+ all_energies = (
591
+ np.array([a.get_potential_energy() for a in self.all_data])
592
+ if self.all_data else np.array([])
593
+ )
594
+ all_forces = (
595
+ [a.get_forces(apply_constraint=False) for a in self.all_data]
596
+ if self.all_data else []
597
+ )
598
+ buffer_energies = (
599
+ np.array([a.get_potential_energy() for a in self.buffer])
600
+ if self.buffer else np.array([])
601
+ )
602
+ buffer_forces = (
603
+ [a.get_forces(apply_constraint=False) for a in self.buffer]
604
+ if self.buffer else []
605
+ )
606
+
607
+ stage_info = dict(
608
+ temperature=self.temperature_schedule.temperature,
609
+ new_energies=new_energies,
610
+ new_forces=new_forces,
611
+ all_energies=all_energies,
612
+ all_forces=all_forces,
613
+ buffer_energies=buffer_energies,
614
+ buffer_forces=buffer_forces,
615
+ ess=ess,
616
+ sampling_wall_s=sampling_wall_s,
617
+ evaluation_wall_s=evaluation_wall_s,
618
+ )
619
+ return stage_info
620
+
621
+ def train_diffusion_stage(self) -> None:
622
+ """Train the diffusion model on the current replay buffer.
623
+
624
+ The number of additional epochs is computed from :attr:`batch_size` and
625
+ :attr:`max_steps_per_loop` so that training runs for at most
626
+ *max_steps_per_loop* gradient steps. The training controller callback
627
+ may stop training earlier.
628
+ """
629
+ temperature = self.temperature_schedule.get_temperature()
630
+ print(f"\n=== Training Diffusion Model at T={temperature:.4f} ===")
631
+
632
+ steps_per_epoch = max(1, len(self.buffer) // self.batch_size)
633
+ epochs_to_add = max(1, self.max_steps_per_loop // steps_per_epoch)
634
+
635
+ current_epoch = self.trainer.current_epoch
636
+ self.trainer.fit_loop.max_epochs = current_epoch + epochs_to_add
637
+
638
+ buffer_props = self.get_properties(self.buffer)
639
+
640
+ dataset_config = dict(self.dataset_config)
641
+ # Inject live all_data reference for regressor training if requested.
642
+ if "regressor_data" in dataset_config:
643
+ dataset_config["regressor_data"] = self.all_data
644
+
645
+ dataset = create_dataset(
646
+ self.buffer, properties=buffer_props, **dataset_config
647
+ )
648
+ train(self.diffusion, dataset, self.trainer)
649
+
650
+ # Save checkpoint
651
+ ckpt_path = str(
652
+ Path(self.trainer.log_dir) / f"diffusion_model_T{temperature:.2f}.ckpt"
653
+ )
654
+ self.trainer.save_checkpoint(ckpt_path)
655
+ print(f"Saved diffusion model checkpoint to {ckpt_path}")
656
+
657
+ #ensure diffusion model stays on the correct device after training
658
+ self.diffusion.to(self.device)
659
+
660
+ # ------------------------------------------------------------------
661
+ # Main entry point
662
+ # ------------------------------------------------------------------
663
+
664
+ def run(
665
+ self,
666
+ max_time_hours: float = 64,
667
+ max_iterations: int = 100,
668
+ ) -> str:
669
+ """Run the complete GO-Diff training procedure.
670
+
671
+ Iterates over sampling and training stages, annealing the temperature
672
+ after each iteration, until *max_iterations* is reached or the
673
+ wall-clock limit is hit.
674
+
675
+ Parameters
676
+ ----------
677
+ max_time_hours : float
678
+ Maximum total wall-clock time (hours) for the trainer. Default: 64.
679
+ max_iterations : int
680
+ Maximum number of outer-loop iterations. Default: 100.
681
+
682
+ Returns
683
+ -------
684
+ str
685
+ Path to the final saved model checkpoint.
686
+ """
687
+ self._get_trainer(max_time_hours)
688
+
689
+ logdir = Path(self.trainer.log_dir)
690
+ logdir.mkdir(parents=True, exist_ok=True)
691
+
692
+ self._godiff_logger = GODiffLogger(self.trainer.logger.experiment)
693
+ self.training_controller.set_logger(self._godiff_logger)
694
+ self._flops_timing_cb.set_logger(self._godiff_logger)
695
+
696
+ data_writer = Trajectory(str(logdir / "all_data.traj"), mode="w")
697
+
698
+ # Disable force-field guidance on the first iteration (cold start)
699
+ # by passing a temporary config without ForceFieldGuidanceConfig.
700
+ ffg_config = self.sample_config.get("ForceFieldGuidanceConfig")
701
+
702
+ i = 0
703
+ while i < max_iterations:
704
+ print(f"\n{'='*50}\nSTAGE {i}\n{'='*50}")
705
+
706
+ t_iter_start = time.perf_counter()
707
+ # Suppress force-field guidance on the first (cold-start) iteration.
708
+ exclude = {"ForceFieldGuidanceConfig"} if i == 0 and ffg_config is not None else None
709
+ stage_info = self.sample_stage(i, data_writer, logdir, exclude_sample_keys=exclude)
710
+
711
+ temperature = self.temperature_schedule.temperature
712
+ print(
713
+ f"Current temperature: {temperature}, "
714
+ f"Buffer size: {len(self.buffer)}, "
715
+ f"Total data size: {len(self.all_data)}"
716
+ )
717
+
718
+ if len(self.buffer) == 0:
719
+ print(f"Warning: Empty buffer at T={temperature}, skipping training.")
720
+ if self._godiff_logger is not None:
721
+ self._godiff_logger.log_iteration(
722
+ i,
723
+ **stage_info,
724
+ iteration_wall_s=time.perf_counter() - t_iter_start,
725
+ )
726
+ i += 1
727
+ continue
728
+
729
+ t_train_start = time.perf_counter()
730
+ self._flops_timing_cb.reset()
731
+ self.train_diffusion_stage()
732
+ training_wall_s = time.perf_counter() - t_train_start
733
+ iteration_wall_s = time.perf_counter() - t_iter_start
734
+
735
+ if self._godiff_logger is not None:
736
+ self._godiff_logger.log_iteration(
737
+ i,
738
+ **stage_info,
739
+ training_wall_s=training_wall_s,
740
+ iteration_wall_s=iteration_wall_s,
741
+ )
742
+
743
+ i += 1
744
+
745
+ print("\nTraining completed.")
746
+
747
+ final_ckpt = str(logdir / "final_model.ckpt")
748
+ self.trainer.save_checkpoint(final_ckpt)
749
+ print(f"Final model saved to: {final_ckpt}")
750
+
751
+ return final_ckpt