nvalchemi.enhanced_sampling.ConservativeBias#
- class nvalchemi.enhanced_sampling.ConservativeBias(name, *, compute_stress=True)[source]#
A bias defined by a differentiable energy.
Subclass and override
energy()to return a per-graph bias energy[B, 1];forward()derives atomic forces and tensile-positive Cauchy stress from it and returns detachedModelOutputs.Composed as
nn.Module, BaseModelMixin— the house multiple-inheritance idiom (LennardJonesModelWrapper(nn.Module, BaseModelMixin),TrainingStrategy(BaseModel, HookRegistryMixin)).BaseModelMixin.__init_subclass__is cooperative, so it composes withAdaptivePotentialMixinfor a bias that is adaptive as well as conservative. The cost of the abstraction is the twoBaseModelMixinabstract methods (embedding_shapesandcompute_embeddings()), stubbed here exactly asLennardJonesModelWrapperandDFTD3ModelWrapperstub them.Note
Subclasses must call
super().__init__(name=...). That is thenn.Modulerequirement (attribute assignment beforeModule.__init__raises), andBaseModelMixin.__init_subclass__additionally verifiesself.model_configis set afterwards.Notes
How the derivatives are taken — the symmetric strain leaf, the substitute-and-restore, the detachment — is
isolated_energy_derivatives()and is documented there. It is deliberately not restated here: one mechanism described in two places is one that can drift. What follows is what is true of this class and not of that function.- Stress rather than virial
forward()emits"stress", never"virial". That is a policy choice, not a consequence of the maths: both are documented toolkit conventions, and tensile-positive Cauchy stress is the one the rest of the toolkit speaks — every model wrapper emits it,sum_outputs()treats it as additive, and the NPT/NPH integrators readbatch.stress. So a bias contribution sums with model output with no volume conversion at the boundary."virial"stays available for a hand-written bias that produces one directly.- What gates stress here
The helper computes stress for any periodic batch with a non-zero cell. This class adds one gate on top:
"stress"must be inmodel_config.active_outputs. Passcompute_stress=Falseto drop it at construction, or flipactive_outputsat runtime as on any model wrapper.torch.compilecompatibilityforward()is eager, because the helper it delegates to callsrequires_grad_(). Compileenergy()— the hot path — instead;EnhancedSampling(compile_biases=True)does exactly that. Keep data-dependent Python branches out ofenergy()for the same reason; put them in aforward()override, which is eager by construction, asHarmonicUmbrellaBiasdoes for its bounds check.
- Parameters:
name (str)
compute_stress (bool)
- compute_embeddings(data, **kwargs)[source]#
Computing embeddings is not meaningful for a bias potential.
- Parameters:
data (AtomicData | Batch)
kwargs (Any)
- Return type:
- distribution_spec(strategy=None)[source]#
Return
None: a bias does not claim domain-decomposition support.Noneis not an oversight, and it is not “unsupported forever” — it makesDistributedModelraiseDistributionErrorrather than shard a bias whose cross-rank semantics are unverified (an explicitDistributedModel(bias, cfg, spec=...)remains the escape hatch for a caller who knows better).The default cannot be a halo preset, because a bias is not necessarily local the way a cutoff potential is. A CV can couple atoms in different domains by construction:
pair_distanceover two atoms on opposite sides of the cell has no cutoff, and an RMSD bias reads every atom.SPEC_LJ_HALOis correct for LJ precisely because a halo exchange covers its interaction range; nothing guarantees that for an arbitrary CV.A bias that is local should override this and declare its outputs, e.g.:
def distribution_spec(self, strategy=None): return MLIPSpec( distribution=DistributionSpec(policy=HaloStoragePolicy()), outputs={ "energy": OutputSpec(OutputKind.PER_GRAPH, Reduce.ALL_REDUCE), "forces": OutputSpec(OutputKind.PER_NODE, Reduce.OWNED_ONLY), "stress": OutputSpec(OutputKind.PER_GRAPH, Reduce.ALL_REDUCE), }, )
- Parameters:
strategy (StrategyKind | None) – Accepted for the framework contract; ignored by the default.
- Returns:
Always
Noneunless a subclass overrides.- Return type:
MLIPSpec | None
- property embedding_shapes: dict[str, tuple[int, ...]]#
a bias potential is a closed-form energy term.
- Type:
No embeddings
- energy(current)[source]#
Return bias energy
[B, 1](eV).Must be differentiable w.r.t.
current.positionsand/orcurrent.cell. Depending on only one of the two is allowed: a position-independent term (a volume restraint, say) yields zero forces rather than an error.- Parameters:
current (Batch) – A read-only view of the live batch whose
positionsandcellhave been replaced by their strained counterparts fromprepare_strain(). Do not assign to any batch field inside this method.- Returns:
Shape
[B, 1].- Return type:
Tensor
- Raises:
NotImplementedError – If the subclass does not override.
- export_model(path, as_state_dict=False)[source]#
Not implemented — a bias has no underlying model to export.
- Parameters:
path (Path)
as_state_dict (bool)
- Return type:
None
- extra_repr()#
Format the model config for
nn.Module.__repr__.- Parameters:
self (Any)
- Return type:
str
- forward(data, **kwargs)[source]#
Return the bias contribution for data, fully detached.
Read-only with respect to the bias: it deposits nothing, writes no storage, and communicates with no other worker, so it is safe to call repeatedly on the same batch. An adaptive bias changes its state in
update()instead, which the runner delivers once per due step after the integrator has finished.data is treated as read-only: every field
isolated_energy_derivatives()substitutes is restored before this returns, including on an exception.- Parameters:
data (AtomicData | Batch) – The live batch from the dynamics step.
**kwargs (Any) – Unused; accepted for interface compatibility with model wrappers.
- Returns:
energy,forces, and — when"stress"is active and the batch is periodic —stress, restricted tomodel_config.active_outputs. Every tensor satisfiesrequires_grad=Falseandgrad_fn is None.Not validated here:
validate_contribution()runs where the contribution is consumed — that is where an unchecked value does damage, by being added into a batch buffer, retained in a history, or written to a checkpoint — soEnhancedSamplingcalls it on every bias it applies. Call it directly to self-check a bias used outside the runner.- Return type:
ModelOutputs
Notes
Called with
allow_unused=True, soenergy()need not depend on both positions and strain — see that parameter onisolated_energy_derivatives()for what a partial dependence yields.