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 detached ModelOutputs.

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 with AdaptivePotentialMixin for a bias that is adaptive as well as conservative. The cost of the abstraction is the two BaseModelMixin abstract methods (embedding_shapes and compute_embeddings()), stubbed here exactly as LennardJonesModelWrapper and DFTD3ModelWrapper stub them.

Note

Subclasses must call super().__init__(name=...). That is the nn.Module requirement (attribute assignment before Module.__init__ raises), and BaseModelMixin.__init_subclass__ additionally verifies self.model_config is 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 read batch.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 in model_config.active_outputs. Pass compute_stress=False to drop it at construction, or flip active_outputs at runtime as on any model wrapper.

torch.compile compatibility

forward() is eager, because the helper it delegates to calls requires_grad_(). Compile energy() — the hot path — instead; EnhancedSampling(compile_biases=True) does exactly that. Keep data-dependent Python branches out of energy() for the same reason; put them in a forward() override, which is eager by construction, as HarmonicUmbrellaBias does 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:
Return type:

AtomicData | Batch

distribution_spec(strategy=None)[source]#

Return None: a bias does not claim domain-decomposition support.

None is not an oversight, and it is not “unsupported forever” — it makes DistributedModel raise DistributionError rather than shard a bias whose cross-rank semantics are unverified (an explicit DistributedModel(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_distance over two atoms on opposite sides of the cell has no cutoff, and an RMSD bias reads every atom. SPEC_LJ_HALO is 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 None unless 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.positions and/or current.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 positions and cell have been replaced by their strained counterparts from prepare_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 to model_config.active_outputs. Every tensor satisfies requires_grad=False and grad_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 — so EnhancedSampling calls 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, so energy() need not depend on both positions and strain — see that parameter on isolated_energy_derivatives() for what a partial dependence yields.