nvalchemi.enhanced_sampling.WellTemperedMetaDynamicsBias#

class nvalchemi.enhanced_sampling.WellTemperedMetaDynamicsBias(cv, height, sigma, temperature, *, bias_factor=None, name='metadynamics', frequency=500, storage='preallocated', max_hills=None, history='shared', periods=None, ramp_depositions=0, compute_stress=True)[source]#

Gaussian hills deposited along a CV, with well-tempered damping.

\[V(s, t) = \sum_i h_i \exp\!\left( -\sum_d \frac{(s_d - c_{i,d})^2}{2\sigma_d^2}\right)\]

Each deposition adds one hill per walker at that walker’s current CV value. In the well-tempered scheme the height decays where the bias has already accumulated,

\[h_t = h_0 \exp\!\left(-\frac{V(s_t)}{k_B T (\gamma - 1)}\right)\]

which makes the sum converge instead of filling forever. At convergence the free energy is recovered as \(F(s) = -\frac{\gamma}{\gamma - 1} V(s)\) (Barducci, Bussi & Parrinello 2008), available from free_energy().

Passing bias_factor=None gives standard metadynamics — the \(\gamma \to \infty\) limit, where every hill has height h_0 and \(F(s) = -V(s)\).

Parameters:
  • cv (Callable[[Batch], Tensor]) – Differentiable cv(batch) -> Tensor[B, D].

  • height (float) – Initial hill height h_0 in eV.

  • sigma (Tensor | float) – Hill width, either a scalar shared by every CV component or shape [D]. Any other length is rejected on the first evaluation rather than broadcast into the hill table.

  • temperature (float) – Simulation temperature in Kelvin, used for the well-tempered damping.

  • bias_factor (float | None) – gamma > 1, or None for standard metadynamics.

  • name (str) – Unique bias identifier.

  • frequency (int) – Dynamics steps between depositions (the deposition pace). The Hook attribute, with the meaning it has everywhere else.

  • storage (str) – "preallocated", "grow", or "fifo" — see Notes.

  • max_hills (int | None) – Capacity. Required for "preallocated" and "fifo"; the initial chunk for "grow".

  • history (str) –

    "shared" (every walker sees every hill), "state" (hills belong to the thermodynamic state that deposited them), or "walker" (each walker sees only its own).

    "state" and "walker" require the batch to carry thermodynamic_state_id / walker_id respectively, and raise if it does not. EnhancedSampling stamps both on every step, so a runner-driven bias never sees this; a bias evaluated directly must supply the field itself.

  • periods (Tensor | None) – Period per CV component, 0 for non-periodic, shape [D]. Applied to the s - c difference so a hill near a branch cut still repels from both sides. Unlike sigma a scalar is not accepted for a multi-component CV: the entries carry per-component meaning, so broadcasting one across all of them would quietly make every component periodic.

  • ramp_depositions (int) – Number of deposition events over which a freshly added hill ramps from zero to full height. 0 activates immediately. Counted in depositions rather than dynamics steps because energy() sees the hill table, not the step counter.

  • compute_stress (bool) – Passed through to ConservativeBias.

Raises:

ValueError – For an invalid storage policy, history mode, non-positive height or width, bias_factor <= 1, or a missing capacity. A sigma or periods length that disagrees with the CV is raised on first evaluation, since the CV dimension is not knowable at construction from a plain callable.

Notes

Storage policies

preallocated keeps tensor shapes fixed for the whole run and raises when capacity is exhausted, rather than silently changing the physics. It is the compile-stable choice.

grow allocates in chunks of max_hills; each growth changes the hill-tensor shape, which forces a recompile if energy() is compiled. Under torch’s default of static parameter shapes, Dynamo caps retraces per code object at torch._dynamo.config.recompile_limit (8), so a compiled run hard-fails once past it — mid-trajectory, after the run is already underway.

Both settings are process-global and other code changes them: DistributedModel raises the limit to 64 and sets force_parameter_static_shapes = False. The second matters more than the first — with dynamic parameter shapes the hill-table dimension is traced symbolically, growth stops triggering a retrace, and the limit is never reached. So the three ways out are: size max_hills so growths stay under the limit, enable dynamic parameter shapes, or use preallocated, which holds one trace for the whole run regardless.

fifo bounds memory by discarding the oldest hill. This is scientifically meaningful, not merely a cache eviction: the accumulated bias is no longer the integral of everything deposited, so the well-tempered convergence argument no longer applies and free_energy() is not a valid estimator. Chosen deliberately for exploration, and the natural policy for the RMSD variant.

Multi-walker history

shared is the multiple-walker scheme: every walker feels every hill, so B walkers fill a basin roughly B times faster. state keeps a separate history per thermodynamic state, which is what a replica-exchange ladder needs. walker runs B independent metadynamics simulations in one batch.

Examples

>>> import torch
>>> from nvalchemi.enhanced_sampling import (
...     WellTemperedMetaDynamicsBias, pair_distance,
... )
>>> idx = torch.tensor([0, 5])
>>> bias = WellTemperedMetaDynamicsBias(
...     cv=lambda b: pair_distance(b, idx),
...     height=0.01, sigma=0.1, temperature=300.0, bias_factor=10.0,
...     max_hills=1000,
... )
>>> bias.hill_count.item()
0
config_fingerprint()[source]#

Return the settings the deposited hills are only valid under.

sigma and periods are held as buffers, so without this check nn.Module.load_state_dict would replace the caller’s values with the checkpoint’s rather than reject the mismatch. bias_factor and temperature set the well-tempered damping the stored heights were computed under, and the ratio free_energy applies to them. storage and history decide retention and ownership.

max_hills is deliberately absent: grow legitimately reaches a capacity the constructor never had, and load_state_dict() already resizes to match.

Returns:

The checked configuration.

Return type:

dict[str, Any]

energy(current)[source]#

Return the accumulated metadynamics bias, shape [B, 1].

Parameters:

current (Batch) – Batch with strained positions supplied by ConservativeBias.evaluate().

Returns:

Shape [B, 1] in eV.

Return type:

Tensor

extra_repr()#

Format the model config for nn.Module.__repr__.

Parameters:

self (Any)

Return type:

str

free_energy(values, owner_key=None)[source]#

Return the free-energy estimate at values.

F(s) = -(gamma / (gamma - 1)) V(s) for well-tempered, or F(s) = -V(s) for standard metadynamics.

Parameters:
  • values (Tensor) – CV values, shape [B, D].

  • owner_key (Tensor | None) – History key per graph. Defaults to the shared history.

Returns:

Free energy in eV, shape [B], up to an additive constant.

Return type:

Tensor

Raises:
  • ValueError – If values does not match the deposited hills’ dimension, or disagrees with sigma or periods.

  • RuntimeError – Under storage="fifo", where discarded hills mean the accumulated bias is no longer the integral of everything deposited and the well-tempered relation does not hold.

gaussian_sum(values, owner_key)[source]#

Return the accumulated bias at values, shape [B].

Contains no data-dependent Python branch, so it compiles with fullgraph=True: the live-hill mask comes from comparing an arange against the count tensor rather than slicing by an int.

Parameters:
  • values (Tensor) – CV values, shape [B, D].

  • owner_key (Tensor) – History key per graph, shape [B].

Returns:

Bias energy per graph, shape [B].

Return type:

Tensor

Raises:

ValueError – If values does not agree with sigma and periods; see _validate_cv().

load_state_dict(state, *args, **kwargs)[source]#

Restore state, resizing the hill buffers to match the checkpoint.

storage="grow" means the saved capacity is whatever the run had reached, which is almost never the constructor’s initial chunk — nn.Module.load_state_dict would reject the size mismatch.

Parameters:
  • state (Mapping[str, Any]) – Mapping from state_dict().

  • *args (Any) – Forwarded up the MRO.

  • **kwargs (Any) – Forwarded up the MRO.

Returns:

Whatever the next load_state_dict returns.

Return type:

Any

update(ctx, stage)[source]#

Deposit one hill per walker at its current CV value.

Parameters:
  • ctx (BiasContext) – The capture. ctx.batch is the post-step frame; the bias’s own preceding contribution is on ctx.contribution.

  • stage (DynamicsStage) – The stage being dispatched, always stage.

Raises:
  • ValueError – If the CV output disagrees with sigma or periods.

  • RuntimeError – If the CV changes dimension part-way through a run, which would silently invalidate every hill already deposited.

Return type:

None