nvalchemi.enhanced_sampling.EnhancedSampling#
- class nvalchemi.enhanced_sampling.EnhancedSampling(*, model, engine=None, engine_kwargs=<factory>, n_steps=None, extra_hooks=<factory>, cache_engine=True, biases=<factory>, steps_per_epoch=10000, compile_biases=False, prime_after_update=True, replica_exchange=None)[source]#
Declarative recipe for biased dynamics on a
BaseDynamicsengine.A sibling of any other
DynamicsStrategy: construction validates the configuration,build_hooks()contributes the enhanced-sampling hook family, andDynamicsStrategy.rundrives the engine. The model, the integrator, the thermostat, and every other hook behave exactly as they would unbiased.- biases#
Mapping of unique name to bias. A bias is any
BaseModelMixinthat maps aBatchtoModelOutputsand carries aname— there is no separate bias protocol. May be empty, which reduces the strategy to identity stamping — what pure temperature replica exchange needs, since the ladder alone drives the sampling.- Type:
dict[str, Any]
- steps_per_epoch#
Steps per consistency epoch, the
StatefulHooksynchronisation boundary at whichAdaptivePotentialMixin.commit()fires.- Type:
int
- compile_biases#
When
True,torch.compileeach conservative bias’senergy(). Notforward()— that path callsrequires_grad_(), whichtorch.compilecannot trace; see theConservativeBiasdocstring.- Type:
bool
- prime_after_update#
When
True(default), re-evaluate biases and rewrite the batch’s total forces after anupdate()bumps a bias’s state version, so that anything readingbatch.forcesbetween steps sees the current bias rather than the previous one.- Type:
bool
- replica_exchange#
Optional ladder. When given, the strategy also contributes the
PairSwapHookthe ladder configures. A runtime object rather than a declarative knob, so it is excluded fromto_spec_dict()the waybiasesandextra_hooksare.- Type:
ReplicaExchange | None
- cache_engine#
Always
True; see One strategy, one trajectory below.- Type:
bool
- Raises:
TypeError – If any value in biases is not a
BaseModelMixin, or if replica_exchange is given for an engine that cannot rebind a thermodynamic state.ValueError – If
steps_per_epochis below 1, a bias’snamedisagrees with its key in biases, noengineis given, orcache_engineisFalse.
- Parameters:
model (BaseModelMixin)
engine (Annotated[type | None, BeforeValidator(func=~nvalchemi._serialization._validate_type, json_schema_input_type=PydanticUndefined), PlainSerializer(func=~nvalchemi._serialization._serialize_type, return_type=PydanticUndefined, when_used=always)])
engine_kwargs (dict[str, Any])
n_steps (Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Strict(strict=True), Gt(gt=0)])] | None)
extra_hooks (list[Hook])
cache_engine (bool)
biases (dict[str, Any])
steps_per_epoch (int)
compile_biases (bool)
prime_after_update (bool)
replica_exchange (ReplicaExchange | None)
Examples
>>> sampling = EnhancedSampling( ... model=model, ... engine=NVTLangevin, ... engine_kwargs={"dt": 0.5, "temperature": 300.0, "friction": 0.01}, ... biases={"umbrella": umbrella, "wall": lower_wall}, ... ) >>> batch = sampling.run(batch, n_steps=1000)
Notes
- Hook ordering
build_hooks()returns the strategy’s own hooks beforeextra_hooks, so atAFTER_COMPUTEthe bias contribution is applied before any caller-supplied hook runs. A safety hook such asMaxForceClampHooktherefore clamps the total force, which is the physically meaningful quantity, rather than the model force alone. Bias observations that need unbiased physical forces are captured insideBiasHookbefore the contribution is applied, so they are unaffected.Among the strategy’s own hooks the order is identity, bias, exchange, commit. Exchange precedes commit because the commit publishes shared history, and doing it before the swap would publish under labels that are about to change — the same order
checkpoint()drains in.- One strategy, one trajectory
The hook family is built once, at construction, because it holds the run’s bookkeeping: the walker counter, the committed epoch, the attempted segment, and each bias’s delivery record. That is also what a checkpoint saves and
restore()writes back. So the engine is cached —cache_enginedefaults toTrueandFalseis refused — anddynamics()returns it. Callingbuild_engine()again would hand a second engine the first one’s bookkeeping; construct a second strategy instead.
- build_hooks()[source]#
Return the enhanced-sampling hooks, then
extra_hooks.- Returns:
Identity, bias, exchange (when configured) and epoch-commit hooks, followed by whatever the base contributes.
- Return type:
list[Hook]
- checkpoint(path, batch=None)[source]#
Write a transactional checkpoint at a consistency-epoch boundary.
The boundary is not a convention — it is the only point where there are no pending
update()calls and no in-flight epoch commit, so a checkpoint taken anywhere else could capture a bias mid-mutation.- Parameters:
path (str | Path) – Destination Zarr store.
batch (Batch | None) – The batch to save. Defaults to the one last seen by the identity hook.
- Raises:
RuntimeError – If no engine has been built or no batch is available, meaning nothing has been run or primed.
ValueError – If the current step is not an epoch boundary; the message names the next valid step.
- Return type:
None
- dynamics()[source]#
Return the engine this strategy drives, building it on first use.
The same slot
DynamicsStrategy.runcaches into, so this,run(),prime_forces()andrestore()all reach one engine.- Returns:
The cached engine. Stable across calls, so step counters and thermostat state persist.
- Return type:
- classmethod from_spec_dict(spec, *, model, biases=None, replica_exchange=None, extra_hooks=None)[source]#
Rebuild a strategy from
to_spec_dict()output.biasesandreplica_exchangeare excluded from the spec — they are live objects with state, likemodel— so they are supplied here the same way. Without this override the base would rebuild a strategy with neither, and the restored run would be unbiased with nothing to say so.- Parameters:
spec (Mapping[str, Any]) – JSON-decoded strategy configuration.
model (BaseModelMixin) – The potential the engine calls.
biases (Mapping[str, BaseModelMixin] | None) – Name to bias, as passed at construction.
replica_exchange (ReplicaExchange | None) – The ladder, as passed at construction.
extra_hooks (Sequence[Hook] | None) – Runtime hooks appended after hooks rebuilt from the spec.
- Returns:
A freshly validated strategy.
- Return type:
- Raises:
ValueError – If spec already carries
biasesorreplica_exchange.
- property last_outputs: dict[str, Tensor]#
Diagnostics from the most recent force evaluation.
physical/<field>is the model alone,bias/<name>/<field>one bias’s contribution,bias_total/<field>the sum across biases, andtotal/<field>physical plus bias as read back from the batch.
- model_config = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'revalidate_instances': 'never', 'validate_assignment': False}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self (BaseModel) – The BaseModel instance.
context (Any) – The context.
- Return type:
None
- prime_forces(batch)[source]#
Run one force evaluation without advancing dynamics.
Populates
batch.energy/forces/stresswith the total (physical plus bias) values at the current coordinates. Needed before the first step of a warm-started run, where a consumer may read forces before any step has happened.- Parameters:
batch (Batch) – The batch to prime.
- Returns:
The same batch, primed in place.
- Return type:
- Raises:
ValueError – If the batch has no
forcesfield to write into.
Notes
Does not advance sampling state. Identity is stamped directly rather than by dispatching
BEFORE_STEP, so no exchange is attempted and no epoch is committed from here — priming after a restore leaves the run exactly where the checkpoint left it.compute()writes its outputs back withcopy_into fields that must already exist — a model output whose batch field is absent is silently discarded rather than created. That is the toolkit’s contract (AtomicData(..., forces=torch.zeros(n, 3))), so the check below turns a silent no-op into a named error.
- restore(path, device=None)[source]#
Restore a checkpoint exactly, and prime forces before returning.
The caller must have reconstructed the same model, engine and biases first; this validates that they match what was saved. Model weights are not restored — load them through the model’s own API before calling here. The compatibility metadata proves the architecture agrees, not that the weights do.
- Parameters:
path (str | Path) – Source Zarr store.
device (torch.device | str | None) – Device for the restored batch. Defaults to the model’s own.
- Returns:
The restored batch, force-primed and ready to run.
- Return type:
- Raises:
ValueError – If the checkpoint is uncommitted, fails a checksum, or was written by a different model, engine, or bias set.
- run(batch, n_steps=None, *, prime=True)[source]#
Run biased dynamics.
Primes forces first by default. A velocity-Verlet-style integrator reads
batch.forcesin its first half-step, before any model call — so without priming, step 0 integrates against whatever the buffer happened to hold (zeros, for a freshly built batch), making it the one step in the run that ignores the bias.
- state_dict()[source]#
Return sampling counters plus each adaptive bias’s state.
- Returns:
Nested mapping; bias state lives under
biases/<name>.- Return type:
Mapping[str, Any]