nvalchemi.enhanced_sampling.AdaptivePotentialMixin#

class nvalchemi.enhanced_sampling.AdaptivePotentialMixin[source]#

Mixin for a bias whose state changes as sampling proceeds.

Mix in alongside whatever else applies, this mixin first:

class WellTemperedMetaDynamicsBias(AdaptivePotentialMixin, ConservativeBias):
    ...   # conservative and adaptive

class AdaptiveBiasingForce(AdaptivePotentialMixin, nn.Module, BaseModelMixin):
    ...   # adaptive, but no energy to differentiate

Order matters and is enforced. ConservativeBias inherits nn.Module, which already defines state_dict / load_state_dict for buffers; putting this mixin second would let those shadow the ones here and silently drop the bias history from every checkpoint. With the mixin first, state_dict() calls up the MRO and merges both. __init_subclass__ raises TypeError on the wrong order rather than letting a checkpoint quietly lose data.

frequency#

Dynamics steps between update() calls; 1 means every step. The Hook attribute, with the meaning it has everywhere else.

Type:

int

stage#

Which DynamicsStage the frame handed to update() is captured at.

  • AFTER_STEP (default) — post-step coordinates. What metadynamics wants: a hill is deposited at the configuration the system actually reached.

  • AFTER_COMPUTE — captured while batch.forces still holds the unbiased physical forces, before any bias contribution is added. What ABF requires; observing biased forces would feed the estimator its own output.

Type:

nvalchemi.dynamics.base.DynamicsStage

read_only#

False: update() mutates bias state, so the runner delivers it exactly once per due step and never during force priming or a speculative re-evaluation.

Type:

bool

Notes

Why update rather than __call__

A Hook is dispatched through __call__(ctx, stage), but a bias is also an nn.Module whose __call__ is the model forward that BaseDynamics and PipelineModelWrapper both invoke. One name cannot be both. The house resolution is the one TrainingUpdateHook already uses: a domain hook family keeps the signature its semantics need, and an orchestrator owns protocol compliance on its behalf. Here that orchestrator is the single composite hook EnhancedSampling installs, which reads frequency and stage and dispatches update() and commit().

State version

bump_state_version() records that the bias changed. The runner reads state_version to decide whether forces in the batch are stale and need re-priming, and stamp_state_version() publishes it per graph as the state_version entry of the bias’s ModelOutputs. It is also checkpointed per bias, ready for validating that an accepted replica-exchange state assignment is coherent — which the exchange does not consume yet. A bias that mutates state inside update() must call it.

bump_state_version()[source]#

Record that the bias state changed.

Call from update() whenever the change affects the energy the next forward pass will return. An update that only accumulates statistics without changing the applied bias (an ABF bin below its minimum-sample threshold, say) should not bump — bumping forces the runner to re-prime forces for no reason.

Return type:

None

commit()[source]#

Synchronise pending state at a consistency-epoch boundary.

The StatefulHook synchronisation boundary. Default is a no-op: a bias whose history is local to one walker needs no synchronisation. Multi-walker shared-history biases override this to publish and merge. Called only at epoch boundaries, never on the hot path, and at most once per boundary.

Return type:

None

config_fingerprint()[source]#

Return the constructor configuration the saved state depends on.

Default is empty, which disables the check. A bias whose persisted state is only meaningful under the settings that produced it should override this and list them.

The distinction is between state and configuration. An ABF histogram is state; the cv_range that decides what its bins mean is configuration. Restoring the first without the second silently reinterprets every bin — bin 5 stops meaning r = 1.55 and starts meaning r = 3.1, with the same numbers in it.

Include configuration held as a buffer too. nn.Module restores buffers by overwriting, so without the check a mismatched setting is not merely unvalidated: the caller’s value is silently replaced by the checkpoint’s, which is the opposite of what asking for it meant.

Returns:

Zarr-representable scalars, strings, None, or flat sequences of those. Tensors must be converted to lists.

Return type:

Mapping[str, Any]

forward(data, **kwargs)[source]#

Stamp the state version onto the contribution from further up the MRO.

Cooperative: mixed in before ConservativeBias this calls that class’s forward and adds state_version to what it returned. A bias with no conservative half defines its own forward and calls stamp_state_version() directly.

Parameters:
  • data (AtomicData | Batch) – The live batch.

  • **kwargs (Any) – Forwarded to the next forward in the MRO.

Returns:

The contribution, with state_version added.

Return type:

ModelOutputs

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

Restore bias state produced by state_dict().

Strips the mixin’s own keys before delegating, so that nn.Module.load_state_dict does not reject them as unexpected under its default strict=True. A recorded config_fingerprint() is checked before delegating, since the delegate overwrites buffers and a check afterwards would come too late to stop the caller’s configuration being replaced.

Parameters:
  • state (Mapping[str, Any]) – The mapping previously returned by state_dict().

  • *args (Any) – Forwarded to the next load_state_dict in the MRO, if any.

  • **kwargs (Any) – Forwarded to the next load_state_dict in the MRO, if any.

Returns:

Whatever the next load_state_dict returns, or None.

Return type:

Any

Raises:

ValueError – If the state was written under a different config_fingerprint().

stamp_state_version(outputs, data)[source]#

Add this bias’s state revision to outputs, one entry per graph.

Parameters:
  • outputs (ModelOutputs) – The contribution to stamp; mutated in place and returned.

  • data (AtomicData | Batch) – The batch the contribution was computed for, read for num_graphs and device.

Returns:

outputs, with a state_version entry of shape [B].

Return type:

ModelOutputs

state_dict(*args, **kwargs)[source]#

Return the bias state for checkpointing, merged up the MRO.

Cooperative: when mixed into an nn.Module bias this calls nn.Module.state_dict first, so buffers (umbrella centers, wall thresholds) and bias history land in one mapping. A bias with real history (hills, reference frames, ABF bins) overrides this, calls super().state_dict(), and adds its own entries.

Parameters:
  • *args (Any) – Forwarded to the next state_dict in the MRO, if any.

  • **kwargs (Any) – Forwarded to the next state_dict in the MRO, if any.

Returns:

Zarr-representable state, always including state_version and, when config_fingerprint() is overridden, the configuration that state is only meaningful under.

Return type:

dict[str, Any]

property state_version: int#

Monotonic counter of state-changing updates applied to this bias.

update(ctx, stage)[source]#

Consume a captured frame, once per due step.

Called by the runner’s composite hook when step % frequency == 0 and stage is self.stage. Free to mutate state, allocate, grow storage, and communicate — none of this is on the compiled path.

Parameters:
  • ctx (BiasContext) – The capture. ctx.batch is the observed frame, stamped by the runner with walker_id, thermodynamic_state_id and sampling_step; ctx.contribution is what this bias returned during the preceding force evaluation.

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

Raises:

NotImplementedError – If the subclass does not override.

Return type:

None