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.
ConservativeBiasinheritsnn.Module, which already definesstate_dict/load_state_dictfor 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__raisesTypeErroron the wrong order rather than letting a checkpoint quietly lose data.- frequency#
Dynamics steps between
update()calls;1means every step. TheHookattribute, with the meaning it has everywhere else.- Type:
int
- stage#
Which
DynamicsStagethe frame handed toupdate()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 whilebatch.forcesstill holds the unbiased physical forces, before any bias contribution is added. What ABF requires; observing biased forces would feed the estimator its own output.
- 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
updaterather than__call__ A
Hookis dispatched through__call__(ctx, stage), but a bias is also annn.Modulewhose__call__is the model forward thatBaseDynamicsandPipelineModelWrapperboth invoke. One name cannot be both. The house resolution is the oneTrainingUpdateHookalready 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 hookEnhancedSamplinginstalls, which readsfrequencyandstageand dispatchesupdate()andcommit().- State version
bump_state_version()records that the bias changed. The runner readsstate_versionto decide whether forces in the batch are stale and need re-priming, andstamp_state_version()publishes it per graph as thestate_versionentry of the bias’sModelOutputs. 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 insideupdate()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
StatefulHooksynchronisation 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_rangethat decides what its bins mean is configuration. Restoring the first without the second silently reinterprets every bin — bin 5 stops meaningr = 1.55and starts meaningr = 3.1, with the same numbers in it.Include configuration held as a buffer too.
nn.Modulerestores 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
ConservativeBiasthis calls that class’sforwardand addsstate_versionto what it returned. A bias with no conservative half defines its ownforwardand callsstamp_state_version()directly.- Parameters:
data (AtomicData | Batch) – The live batch.
**kwargs (Any) – Forwarded to the next
forwardin the MRO.
- Returns:
The contribution, with
state_versionadded.- 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_dictdoes not reject them as unexpected under its defaultstrict=True. A recordedconfig_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_dictin the MRO, if any.**kwargs (Any) – Forwarded to the next
load_state_dictin the MRO, if any.
- Returns:
Whatever the next
load_state_dictreturns, orNone.- 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_graphsand device.
- Returns:
outputs, with a
state_versionentry 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.Modulebias this callsnn.Module.state_dictfirst, 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, callssuper().state_dict(), and adds its own entries.- Parameters:
*args (Any) – Forwarded to the next
state_dictin the MRO, if any.**kwargs (Any) – Forwarded to the next
state_dictin the MRO, if any.
- Returns:
Zarr-representable state, always including
state_versionand, whenconfig_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 == 0andstage 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.batchis the observed frame, stamped by the runner withwalker_id,thermodynamic_state_idandsampling_step;ctx.contributionis 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