nvalchemi.hooks.BiasedPotentialHook#
- class nvalchemi.hooks.BiasedPotentialHook(bias_fn, stage=None, frequency=1, inplace=True)[source]#
Add an external bias potential to forces and energy after the forward pass.
Deprecated since version 0.3.0: Superseded by
nvalchemi.enhanced_sampling. Constructing this hook emits aDeprecationWarning. It remains functional so existing code keeps working, and no removal date is set — but new biases should be written againstConservativeBiasand run throughEnhancedSampling, which together cover everything this hook does.Three limitations of the
bias_fncontract motivated the replacement:No cell response.
bias_fnreturns only(energy, forces), so a bias contributes no stress or virial. Under NPT/NPH the barostat readsbatch.stress, which the bias never touches, so the cell evolves as if the bias were absent — silently, with no error.Forces are hand-written. Nothing checks that
bias_forcesis-dE/drfor the returnedbias_energy, so a bias can be non-conservative by accident.ConservativeBiasderives forces and stress from one energy definition by autograd.Sequential in-place composition. Each hook mutates
batch.forcesin turn, so a second bias that readsbatch.forcesobserves the first one’s contribution.aggregate_contributions()sums every bias against the same unmodified model output instead.
This hook enables enhanced sampling techniques by composing an arbitrary bias potential on top of the ML potential without modifying the model itself. The bias is applied in-place to
batch.forcesandbatch.energyatAFTER_COMPUTE, keeping the model output pure and the bias fully composable.The bias is specified via a callable
bias_fnwith signature:bias_fn(batch: Batch) -> tuple[Tensor, Tensor] Returns (bias_energy, bias_forces) where: - bias_energy: Float[Tensor, "B 1"] — per-graph energy bias - bias_forces: Float[Tensor, "V 3"] — per-atom force biasThe hook adds the bias terms to the existing batch values:
batch.energy += bias_energy batch.forces += bias_forces
This design supports a wide range of enhanced sampling methods:
Harmonic restraints — bias that penalizes deviation from a reference geometry (e.g. collective variable restraints).
Umbrella sampling — harmonic bias along a reaction coordinate, with the umbrella window center parameterizing
bias_fn.Metadynamics — time-dependent Gaussian bias deposited along collective variables.
bias_fnwould maintain internal state (deposited Gaussians) and compute the accumulated bias.Steered MD — time-dependent bias that pulls the system along a path.
bias_fncan readdynamics.step_countto vary the bias over time.Wall potentials — repulsive bias that confines atoms to a region of space (e.g. preventing evaporation from a surface).
- Parameters:
bias_fn (Callable[[Batch], tuple[Tensor, Tensor]]) – A callable that computes the bias energy and forces given the current batch. Must return a tuple of
(bias_energy, bias_forces)with shapes(B, 1)and(V, 3)respectively, on the same device as the batch.stage (Enum | None, optional) – The stage at which to run this hook. Default is
None(stage-agnostic until registered with a specific engine).frequency (int, optional) – Apply the bias every
frequencysteps. Default1(every step).inplace (bool, optional) – If True, will modify energy and forces in the batch in-place. Otherwise, replaces the existing tensors.
- bias_fn#
The bias potential function.
- Type:
Callable
- frequency#
Bias application frequency in steps.
- Type:
int
- stage#
The stage at which this hook fires.
- Type:
Enum | None
Examples
Harmonic restraint on center of mass:
>>> import torch >>> from nvalchemi.hooks import BiasedPotentialHook >>> def harmonic_restraint(batch): ... # Restrain center of mass to origin with k=10 eV/A^2 ... k = 10.0 ... com = batch.positions.mean(dim=0, keepdim=True) ... bias_energy = 0.5 * k * (com ** 2).sum().unsqueeze(0).unsqueeze(0) ... bias_forces = -k * com.expand_as(batch.positions) / batch.num_nodes ... return bias_energy, bias_forces >>> hook = BiasedPotentialHook(bias_fn=harmonic_restraint)
Notes
The
bias_fnis called after the model forward pass, so it has access to the model-computed forces and energy via the batch if needed (e.g. for force-matching penalties).When only some graphs are active,
bias_fnis still called with the entire batch and must return energies and forces for the entire batch. The hook adds those values only to the active graphs and their atoms, while inactive graphs remain unchanged.Because the bias modifies forces in-place, it interacts correctly with
MaxForceClampHook— register the clamp hook after the bias hook to clamp the total (model + bias) forces.For metadynamics, the
bias_fnclosure should hold a reference to a mutable state object (e.g. a list of deposited Gaussians) that is updated externally or within the callable.The bias does not contribute to the autograd graph. If the model uses conservative forces (
forces_via_autograd=True), the bias forces are added aftertorch.autograd.gradhas already computed the model forces.