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=Nonegives standard metadynamics — the \(\gamma \to \infty\) limit, where every hill has heighth_0and \(F(s) = -V(s)\).- Parameters:
cv (Callable[[Batch], Tensor]) – Differentiable
cv(batch) -> Tensor[B, D].height (float) – Initial hill height
h_0in 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, orNonefor standard metadynamics.name (str) – Unique bias identifier.
frequency (int) – Dynamics steps between depositions (the deposition pace). The
Hookattribute, 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 carrythermodynamic_state_id/walker_idrespectively, and raise if it does not.EnhancedSamplingstamps 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,
0for non-periodic, shape[D]. Applied to thes - cdifference so a hill near a branch cut still repels from both sides. Unlikesigmaa 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.
0activates immediately. Counted in depositions rather than dynamics steps becauseenergy()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. Asigmaorperiodslength 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
preallocatedkeeps 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.growallocates in chunks ofmax_hills; each growth changes the hill-tensor shape, which forces a recompile ifenergy()is compiled. Under torch’s default of static parameter shapes, Dynamo caps retraces per code object attorch._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:
DistributedModelraises the limit to 64 and setsforce_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: sizemax_hillsso growths stay under the limit, enable dynamic parameter shapes, or usepreallocated, which holds one trace for the whole run regardless.fifobounds 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 andfree_energy()is not a valid estimator. Chosen deliberately for exploration, and the natural policy for the RMSD variant.- Multi-walker history
sharedis the multiple-walker scheme: every walker feels every hill, soBwalkers fill a basin roughlyBtimes faster.statekeeps a separate history per thermodynamic state, which is what a replica-exchange ladder needs.walkerrunsBindependent 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.
sigmaandperiodsare held as buffers, so without this checknn.Module.load_state_dictwould replace the caller’s values with the checkpoint’s rather than reject the mismatch.bias_factorandtemperatureset the well-tempered damping the stored heights were computed under, and the ratiofree_energyapplies to them.storageandhistorydecide retention and ownership.max_hillsis deliberately absent:growlegitimately reaches a capacity the constructor never had, andload_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, orF(s) = -V(s)for standard metadynamics.- Parameters:
- 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
sigmaorperiods.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 anarangeagainst the count tensor rather than slicing by an int.
- 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_dictwould 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_dictreturns.- Return type:
Any
- update(ctx, stage)[source]#
Deposit one hill per walker at its current CV value.
- Parameters:
ctx (BiasContext) – The capture.
ctx.batchis the post-step frame; the bias’s own preceding contribution is onctx.contribution.stage (DynamicsStage) – The stage being dispatched, always
stage.
- Raises:
ValueError – If the CV output disagrees with
sigmaorperiods.RuntimeError – If the CV changes dimension part-way through a run, which would silently invalidate every hill already deposited.
- Return type:
None