Skip to content

Commit 978a857

Browse files
Bug fixes in MD, cell optimizers, Ewald stress and elastic tensors (#626)
1 parent 2630479 commit 978a857

18 files changed

Lines changed: 462 additions & 71 deletions

‎docs/user/reproducibility.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ One of the main reasons for seeding the global states is to control the determin
4141

4242
## Seeding TorchSim SimStates
4343

44-
In PyTorch, `torch.manual_seed()` only seeds the default global generator, i.e. the generator used in `torch.rand(..., generator=None)` if the generator isn't specified. An explicit `torch.Generator()` is independent and is initialized at the time of calling from the OS entropy source. Since TorchSim internally uses a `torch.Generator()` in the form of `SimState.rng` for all algorithmic randomness in core code setting the global seed is insufficient to ensure determinism within TorchSim. **You must explicitly seed your SimStates to ensure determinism**.
44+
In PyTorch, `torch.manual_seed()` only seeds the default global generator, i.e. the generator used in `torch.rand(..., generator=None)` if the generator isn't specified. TorchSim internally uses a `torch.Generator()` in the form of `SimState.rng` for all algorithmic randomness in core code. An unseeded state seeds it from the global generator when `rng` is first used. After `torch.manual_seed()` a fixed script is therefore reproducible, but its random streams shift whenever other code draws from the global generator first, for example a model initializing its weights. **You must explicitly seed your SimStates to ensure determinism**.
4545

4646
```python
4747
sim_state = ts.initialize_state(atoms, device, dtype)
48-
sim_state.rng = 42 # needed for reproducibility: torch.manual_seed() has no effect
48+
sim_state.rng = 42 # fixes the stream, whatever else uses the global generator
4949
```
5050

5151
### Deterministic vs stochastic integrators in TorchSim
@@ -54,15 +54,17 @@ sim_state.rng = 42 # needed for reproducibility: torch.manual_seed() has no eff
5454
terms by design. When seeded via `state.rng`, they produce identical trajectories.
5555
The `rng` generator controls **both** the initial momenta sampling **and** all per-step stochastic noise (Langevin OU noise, V-Rescale draws, C-Rescale barostat noise, etc.). It is stored on the state and automatically advances on every step, so running the same seed twice produces identical trajectories.
5656
- `ts.Integrator.nvt_nose_hoover` and `ts.Integrator.nve` are deterministic at the
57-
algorithmic level and require no seeding.
57+
algorithmic level, but they still draw their starting momenta from `state.rng`.
5858

59-
For the simplest path to reproducibility, use a deterministic integrator such as Nosé-Hoover:
59+
For the simplest path to reproducibility, seed the state and use a deterministic integrator such as Nosé-Hoover:
6060

6161
```python
6262
import torch_sim as ts
6363

64+
state = ts.initialize_state(atoms, device, dtype)
65+
state.rng = 42
6466
state = ts.integrate(
65-
system=atoms,
67+
system=state,
6668
model=model,
6769
n_steps=500,
6870
timestep=0.001,
@@ -77,6 +79,8 @@ In practice, exact reproducibility also depends on hardware, driver/library vers
7779

7880
Because TorchSim runs batched simulations, all systems in a batch share a single `torch.Generator`. Random numbers are drawn in a fixed order each step, so **identical batch composition** is required for exact reproducibility. Changing which systems are in a batch (or their order) will consume random numbers differently and cause trajectories to diverge.
7981

82+
A `BinningAutoBatcher` gives each batch after the first its own seed drawn from the state's generator, so replicas in different batches get independent noise.
83+
8084
If strict reproducibility is required, keep your batching setup fixed.
8185

8286
### Serialising state for reproducible restarts

‎tests/conftest.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,12 @@ def si_phonopy_atoms() -> Any:
128128
)
129129

130130

131+
@pytest.fixture(autouse=True)
132+
def _seed_torch() -> None:
133+
"""Seed torch per test, so unseeded states don't depend on test order."""
134+
torch.manual_seed(0)
135+
136+
131137
@pytest.fixture
132138
def cu_supercell_sim_state() -> ts.SimState:
133139
"""Create a 4x4x4 FCC Copper supercell with small random displacements."""

‎tests/models/test_electrostatics.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,21 @@ def test_ewald_pme_energy_agreement() -> None:
196196
ewald(state)["energy"], pme(state)["energy"], atol=1e-3, rtol=1e-3
197197
)
198198

199+
# A primitive cell batched with a large supercell keeps its single-system stress
200+
small = _add_partial_charges(
201+
ts.io.atoms_to_state(bulk("MgO", "rocksalt", a=4.21), DEVICE, DTYPE)
202+
)
203+
large = _add_partial_charges(
204+
ts.io.atoms_to_state(
205+
bulk("NaCl", "rocksalt", a=5.64, cubic=True).repeat(2), DEVICE, DTYPE
206+
)
207+
)
208+
batch = ts.concatenate_states([small, large])
209+
for model in (ewald, pme):
210+
torch.testing.assert_close(
211+
model(batch)["stress"][:1], model(small)["stress"], rtol=1e-4, atol=1e-6
212+
)
213+
199214

200215
def _slab_reference_energy_forces(
201216
positions: torch.Tensor, charges: torch.Tensor, box: float, n_max: int = 100

‎tests/test_elastic.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
import pytest
44
import torch
5+
from ase.build import bulk
6+
from ase.spacegroup import crystal
57

68
import torch_sim as ts
7-
from tests.conftest import DEVICE
9+
from tests.conftest import DEVICE, DTYPE
810
from torch_sim.elastic import (
911
calculate_elastic_moduli,
1012
calculate_elastic_tensor,
@@ -268,12 +270,22 @@ def mace_model() -> MaceModel:
268270
)
269271

270272

273+
@pytest.fixture
274+
def sb_hexagonal_sim_state() -> ts.SimState:
275+
"""R-3m antimony in the hexagonal setting."""
276+
atoms = crystal(
277+
"Sb", [(0, 0, 0.2336)], spacegroup=166, cellpar=[4.31, 4.31, 11.27, 90, 90, 120]
278+
)
279+
return ts.io.atoms_to_state(atoms, DEVICE, DTYPE)
280+
281+
271282
@pytest.mark.parametrize(
272283
("sim_state_name", "expected_bravais_type", "atol"),
273284
[
274285
("cu_sim_state", BravaisType.CUBIC, 2e-1),
275286
("mg_sim_state", BravaisType.HEXAGONAL, 5e-1),
276287
("sb_sim_state", BravaisType.TRIGONAL, 5e-1),
288+
("sb_hexagonal_sim_state", BravaisType.TRIGONAL, 5e-1),
277289
("tio2_sim_state", BravaisType.TETRAGONAL, 5e-1),
278290
("ga_sim_state", BravaisType.ORTHORHOMBIC, 5e-1),
279291
("niti_sim_state", BravaisType.MONOCLINIC, 5e-1),
@@ -356,6 +368,9 @@ def test_copper_elastic_properties(
356368
mace_model: MaceModel, cu_sim_state: ts.SimState
357369
) -> None:
358370
"""Test calculation of elastic properties for copper."""
371+
# The primitive cell's 3-fold axis isn't along z
372+
primitive = ts.io.atoms_to_state(bulk("Cu", "fcc", a=3.58), DEVICE, DTYPE)
373+
assert get_bravais_type(primitive) == BravaisType.TRICLINIC
359374

360375
# Relax positions and cell
361376
state = ts.fire_init(

‎tests/test_fix_symmetry.py‎

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ class NoisyModelWrapper(ModelInterface):
8383
Uses Weibull noise (heavy-tailed) rather than Gaussian so that occasional
8484
large perturbations can break symmetry in negative-control tests. This
8585
also better mimics real ML potential errors, which have heavy tails.
86+
87+
With ``symmetry_breaking_only`` the symmetric part of the noise is removed, so
88+
FixSymmetry cancels it exactly.
8689
"""
8790

8891
model: LennardJonesModel
@@ -94,6 +97,8 @@ def __init__(
9497
model: LennardJonesModel,
9598
noise_scale: float = 1e-1,
9699
concentration: float = 1.0,
100+
*,
101+
symmetry_breaking_only: bool = False,
97102
) -> None:
98103
super().__init__()
99104
self.model = model
@@ -103,6 +108,7 @@ def __init__(
103108
self._dtype = model.dtype
104109
self._compute_stress = model.compute_stress
105110
self._compute_forces = model.compute_forces
111+
self.symmetry_breaking_only = symmetry_breaking_only
106112

107113
def forward(self, state: ts.SimState, **kwargs: object) -> dict[str, torch.Tensor]:
108114
"""Forward pass with added Weibull noise."""
@@ -124,6 +130,15 @@ def forward(self, state: ts.SimState, **kwargs: object) -> dict[str, torch.Tenso
124130
noise = magnitudes.unsqueeze(-1) * direction
125131
else:
126132
noise = magnitudes.view(-1, 1, 1) * direction
133+
if self.symmetry_breaking_only:
134+
symmetric = noise.to(results[key].dtype, copy=True)
135+
for constraint in state.constraints:
136+
if isinstance(constraint, FixSymmetry):
137+
if key == "forces":
138+
constraint.adjust_forces(state, symmetric)
139+
else:
140+
constraint.adjust_stress(state, symmetric)
141+
noise = noise - symmetric
127142
results[key] = results[key] + noise
128143
return results
129144

@@ -134,6 +149,19 @@ def noisy_lj_model(model: LennardJonesModel) -> NoisyModelWrapper:
134149
return NoisyModelWrapper(model, noise_scale=5e-1, concentration=1.0)
135150

136151

152+
@pytest.fixture
153+
def symmetry_breaking_lj_model() -> NoisyModelWrapper:
154+
"""LJ model with sigma near the hcp neighbor distance, so the strained cells feel
155+
real forces, and large noise that FixSymmetry removes exactly.
156+
"""
157+
model = LennardJonesModel(
158+
sigma=2.5, epsilon=0.05, cutoff=6.0, compute_stress=True, dtype=DTYPE
159+
)
160+
return NoisyModelWrapper(
161+
model, noise_scale=5e-1, concentration=1.0, symmetry_breaking_only=True
162+
)
163+
164+
137165
@pytest.fixture
138166
def p6bar_both_constraints() -> tuple[ts.SimState, FixSymmetry, Atoms, ASEFixSymmetry]:
139167
"""P-6 structure with both TorchSim and ASE constraints (shared setup)."""
@@ -605,22 +633,28 @@ def test_cell_filter_preserves_symmetry(
605633
final = get_symmetry_datasets(final_state, symprec=SYMPREC)
606634
assert initial[0].number == final[0].number
607635

636+
@pytest.mark.parametrize(
637+
("optimizer", "structure"),
638+
[(ts.Optimizer.lbfgs, "bcc"), (ts.Optimizer.bfgs, "hcp")],
639+
)
608640
@pytest.mark.parametrize("cell_filter", [ts.CellFilter.frechet, ts.CellFilter.unit])
609-
def test_lbfgs_preserves_symmetry(
641+
def test_quasi_newton_preserves_symmetry(
610642
self,
611643
noisy_lj_model: NoisyModelWrapper,
612644
cell_filter: ts.CellFilter,
645+
optimizer: ts.Optimizer,
646+
structure: str,
613647
) -> None:
614-
"""Regression: LBFGS must use set_constrained_cell for FixSymmetry support."""
615-
state = ts.io.atoms_to_state(make_structure("bcc"), DEVICE, DTYPE)
648+
"""Regression: L-BFGS and BFGS must use set_constrained_cell for FixSymmetry."""
649+
state = ts.io.atoms_to_state(make_structure(structure), DEVICE, DTYPE)
616650
constraint = FixSymmetry.from_state(state, symprec=SYMPREC)
617651
state.constraints = [constraint]
618652
state.cell = state.cell * 0.95
619653
state.positions = state.positions * 0.95
620654
final_state = ts.optimize(
621655
system=state,
622656
model=noisy_lj_model,
623-
optimizer=ts.Optimizer.lbfgs,
657+
optimizer=optimizer,
624658
convergence_fn=ts.generate_force_convergence_fn(
625659
force_tol=0.01,
626660
include_cell_forces=True,
@@ -629,7 +663,7 @@ def test_lbfgs_preserves_symmetry(
629663
max_steps=MAX_STEPS,
630664
)
631665
final = get_symmetry_datasets(final_state, symprec=SYMPREC)
632-
assert final[0].number == SPACEGROUPS["bcc"]
666+
assert final[0].number == SPACEGROUPS[structure]
633667

634668
def test_noisy_model_loses_symmetry_without_constraint(
635669
self,
@@ -767,14 +801,15 @@ def test_optimizer_sym_batch1_matches_batch_n(
767801
)
768802
def test_optimizer_sym_converges(
769803
self,
770-
noisy_lj_model: NoisyModelWrapper,
804+
symmetry_breaking_lj_model: NoisyModelWrapper,
771805
optimizer: ts.Optimizer,
772806
) -> None:
773807
"""Optimizer with FixSymmetry + Frechet converges on anisotropically strained HCP.
774808
775809
Uses HCP with anisotropic strain (a-axis compressed, c-axis stretched)
776810
so the cell actively wants to change shape under symmetry constraints.
777-
Asserts the optimizer converges within MAX_STEPS (not just preserves symmetry).
811+
Asserts the optimizer converges within 2 * MAX_STEPS (not just preserves
812+
symmetry).
778813
"""
779814
state = ts.io.atoms_to_state(make_structure("hcp"), DEVICE, DTYPE)
780815
constraint = FixSymmetry.from_state(state, symprec=SYMPREC)
@@ -793,11 +828,11 @@ def test_optimizer_sym_converges(
793828
)
794829
final_state = ts.optimize(
795830
system=state,
796-
model=noisy_lj_model,
831+
model=symmetry_breaking_lj_model,
797832
optimizer=optimizer,
798833
convergence_fn=convergence_fn,
799834
init_kwargs={"cell_filter": ts.CellFilter.frechet},
800-
max_steps=MAX_STEPS,
835+
max_steps=2 * MAX_STEPS,
801836
steps_between_swaps=1,
802837
)
803838
fmax = ts.system_wise_max_force(final_state).item()

‎tests/test_integrators.py‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,12 @@ def test_nvt_nose_hoover_multi_equivalent_to_single(
497497

498498
assert torch.allclose(final_temperatures, temp / MetalUnits.temperature)
499499

500+
# Slicing, splitting and .to() keep each system's own chain
501+
torch.testing.assert_close(state[1].chain.momenta, state.chain.momenta[1:])
502+
rejoined = ts.concatenate_states(state.split())
503+
torch.testing.assert_close(rejoined.chain.momenta, state.chain.momenta)
504+
assert state.to(dtype=torch.float32).chain.momenta.dtype == torch.float32
505+
500506

501507
def test_nvt_nose_hoover_multi_kt(
502508
ar_double_sim_state: ts.SimState, lj_model: LennardJonesModel
@@ -784,7 +790,7 @@ def test_npt_crescale_init_accepts_per_system_coupling(
784790
)
785791

786792

787-
def test_npt_crescale_triclinic_shear(
793+
def test_npt_crescale_triclinic_shear( # noqa: PLR0915
788794
ar_double_sim_state: ts.SimState, lj_model: LennardJonesModel
789795
) -> None:
790796
"""Test anisotropic crescale with off-diagonal (shear) external stress."""
@@ -852,6 +858,78 @@ def test_npt_crescale_triclinic_shear(
852858
for mean_temp in mean_temps:
853859
assert abs(mean_temp - kT.item() / MetalUnits.temperature) < 150.0
854860

861+
# With no forces or noise and tiny momenta, atoms must move with the cell
862+
free_model = LennardJonesModel(
863+
sigma=3.405, epsilon=0.0, device=DEVICE, dtype=DTYPE, compute_stress=True
864+
)
865+
zero_kT = torch.tensor(0.0, dtype=DTYPE)
866+
free_state = ts.npt_crescale_init(
867+
state=ar_double_sim_state,
868+
model=free_model,
869+
dt=dt,
870+
kT=zero_kT,
871+
tau_p=10 * dt,
872+
isothermal_compressibility=torch.tensor(1.0, dtype=DTYPE),
873+
)
874+
free_state.momenta = torch.full_like(free_state.momenta, 1e-9)
875+
876+
def frac_positions(state: ts.SimState) -> torch.Tensor:
877+
cells = state.cell[state.system_idx]
878+
return torch.linalg.solve(cells, state.positions.unsqueeze(-1)).squeeze(-1)
879+
880+
frac_before = frac_positions(free_state)
881+
free_state = ts.npt_crescale_triclinic_step(
882+
state=free_state,
883+
model=free_model,
884+
dt=dt,
885+
kT=zero_kT,
886+
external_pressure=1e4 * external_pressure,
887+
)
888+
torch.testing.assert_close(
889+
frac_positions(free_state), frac_before, atol=1e-10, rtol=0
890+
)
891+
# The rotation-free update keeps the upper-triangular cells upper-triangular
892+
assert torch.all(free_state.cell.tril(-1) == 0)
893+
894+
# The same crystal in another lattice basis must deform the same way
895+
basis_change = torch.tensor(
896+
[[1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=DTYPE
897+
)
898+
shear_strain = torch.tensor(
899+
[[1.0, 0.05, 0.0], [0.0, 1.0, 0.02], [0.0, 0.0, 0.97]], dtype=DTYPE
900+
)
901+
deviatoric_pressure = MetalUnits.pressure * torch.diag(
902+
torch.tensor([1e4, 0.0, -1e4], dtype=DTYPE)
903+
)
904+
deformations = []
905+
for basis in (torch.eye(3, dtype=DTYPE), basis_change):
906+
crystal = ts.io.atoms_to_state(
907+
bulk("Ar", "fcc", a=5.26, cubic=True), DEVICE, DTYPE
908+
)
909+
crystal.cell = crystal.cell @ basis
910+
crystal = ts.npt_crescale_init(
911+
state=crystal,
912+
model=free_model,
913+
dt=dt,
914+
kT=zero_kT,
915+
tau_p=10 * dt,
916+
isothermal_compressibility=torch.tensor(1e-2, dtype=DTYPE),
917+
)
918+
crystal.momenta = torch.full_like(crystal.momenta, 1e-9)
919+
# Shear away from the reference cell, moving the atoms with it
920+
crystal.cell = shear_strain @ crystal.cell
921+
crystal.positions = crystal.positions @ shear_strain.T
922+
cell_before = crystal.cell.clone()
923+
crystal = ts.npt_crescale_triclinic_step(
924+
state=crystal,
925+
model=free_model,
926+
dt=dt,
927+
kT=zero_kT,
928+
external_pressure=deviatoric_pressure,
929+
)
930+
deformations.append(crystal.cell @ torch.linalg.inv(cell_before))
931+
torch.testing.assert_close(deformations[0], deformations[1], atol=1e-12, rtol=0)
932+
855933
# Check energy is stable
856934
for traj in energies_tensor.T:
857935
energy_std = traj.std()
@@ -1118,6 +1196,16 @@ def test_npt_nose_hoover_multi_equivalent_to_single(
11181196

11191197
assert torch.allclose(final_temperatures, temp / MetalUnits.temperature)
11201198

1199+
# Slicing, splitting and .to() keep each system's own chains
1200+
for chain_name in ("thermostat", "barostat"):
1201+
chain = getattr(state, chain_name)
1202+
torch.testing.assert_close(
1203+
getattr(state[1], chain_name).momenta, chain.momenta[1:]
1204+
)
1205+
rejoined = getattr(ts.concatenate_states(state.split()), chain_name)
1206+
torch.testing.assert_close(rejoined.momenta, chain.momenta)
1207+
assert state.to(dtype=torch.float32).thermostat.momenta.dtype == torch.float32
1208+
11211209

11221210
def test_npt_nose_hoover_multi_kt(
11231211
ar_double_sim_state: ts.SimState, lj_model: LennardJonesModel

0 commit comments

Comments
 (0)