nvalchemi.enhanced_sampling.BiasHook#
- class nvalchemi.enhanced_sampling.BiasHook(biases=None, *, prime_after_update=True, compile_biases=False)[source]#
Evaluate every bias against one unmodified model output, then apply.
The single hook the bias family needs. It defines
_runs_on_stageso the registry lets one object serve bothAFTER_COMPUTE(evaluate and apply) andAFTER_STEP(observe, deliverupdate(), re-prime), which keeps the ordering guarantees in one place rather than spread across separately-registered hooks whose relative order would then depend on registration sequence.It is also the orchestrator for the biases, in the sense
TrainingUpdateHookestablishes: an adaptive bias carries theStatefulHookattributes (frequency,stage,read_only,commit) but dispatches throughupdaterather than__call__, because a bias is also annn.Modulewhose__call__is its model forward. This object owns protocol compliance on their behalf: it is the thing the registry sees, and it reads those attributes to decide when each bias is due.- Parameters:
biases (Mapping[str, BaseModelMixin] | None) – Mapping of unique name to bias. May be empty, which reduces this hook to a no-op — what pure temperature replica exchange needs.
prime_after_update (bool) – When
True(default), re-evaluate the 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.compile_biases (bool) – When
True,torch.compileeach conservative bias’senergy().
- last_outputs#
Diagnostics from the most recent force evaluation —
physical/*(model only),bias/<name>/*(one bias’s contribution),bias_total/*(the sum across biases) andtotal/*(physical plus bias, read back from the batch).
Notes
Bias state is not part of
state_dict(). A checkpoint writes each bias into its ownbiases/<name>group so the pieces can be inspected and restored individually; what this hook owns is the per-bias delivery bookkeeping that keepsupdate()exactly-once across a restart.- adaptive_biases()[source]#
Return the biases that implement the stateful-hook
update.Detection is structural (
hasattr), so a bias satisfies the adaptive contract without inheritingAdaptivePotentialMixin.- Returns:
Name to bias, for adaptive biases only.
- Return type:
dict[str, BaseModelMixin]
- bias_energy(batch, state_ids)[source]#
Return the total bias energy per walker under state_ids.
Umbrella acceptance needs the bias evaluated under both the current and the proposed labels, so the assignment is swapped in, the biases re-evaluated, and the original restored in a
finally.Raw energy, not reduced: multiplying by
betais thermodynamics and belongs to whatever ladder is asking, which is also what keeps this hook free of any temperature table.Contributions are checked here as well as on the force path, and for a reason specific to this one: it is the only place a bias is evaluated under an assignment the run is not in. A window bias can be perfectly finite with every walker at home and overflow the moment one is scored against another’s window — which is precisely what umbrella acceptance asks it to do — so the force path never sees it. An unchecked non-finite energy here does not raise either: it makes the acceptance exponent
nan, andnancompares false, so the swap is silently rejected and the run looks like a ladder with poor overlap. Theisfinitesync this costs is per exchange attempt, not per step.Only the energy is checked, because only the energy is read. The forces and stress computed alongside it are discarded, and a bias can be finite under a foreign window while its derivative is singular there — a square-root restraint scored at its own centre. Refusing that would stop the run over a value nothing applies; the force path checks the derivatives the integrator actually uses.
- Parameters:
batch (Batch) – The live batch.
state_ids (torch.Tensor) – Assignment to evaluate under, shape
[B].
- Returns:
E_biasper walker in eV, shape[B].- Return type:
- Raises:
ValueError – If any bias returns an energy violating the
ModelOutputsconventions under state_ids, naming the bias.
- commit()[source]#
Publish every adaptive bias’s pending state.
The
StatefulHooksynchronisation point, fanned out to the biases. Called byEpochCommitHookat a consistency epoch boundary, never on the hot path.- Return type:
None
- evaluate_and_apply(batch)[source]#
Evaluate every bias against the unmodified batch, then apply the sum.
Implements steps 1-7 of the documented force-step ordering. The ordering is the whole point: every bias sees the same physical outputs, so no bias can observe another’s contribution and the result does not depend on registration order.
- Parameters:
batch (Batch) – The live batch, immediately after the model forward pass.
- Return type:
None
- load_state_dict(state)[source]#
Restore the delivery bookkeeping.
Does not re-baseline the seen-version cache: the biases’ own states are loaded separately, and the cache is only meaningful once they have been. Call
sync_seen_versions()after that.- Parameters:
state (Mapping[str, Any]) – A mapping produced by
state_dict().- Return type:
None
- observe_and_update(batch)[source]#
Capture post-step frames, deliver
update(), then re-prime.Implements steps 10-12 of the force-step ordering.
- Parameters:
batch (Batch) – The live batch, after the integrator has finished.
- Return type:
None
- on_register(workflow)[source]#
Remember the engine this hook was registered on.
The engine is the authority on the current step, supplies the model a bias’s
updatecontext names, and is whatreprime_from_scratch()drives through a fresh force evaluation.- Parameters:
workflow (Any) – The
BaseDynamicsdoing the registering.- Return type:
None
- replay(frames)[source]#
Deliver each frame in frames to every adaptive bias, in order.
The mechanism behind a warm start: it reconstructs bias history from prior frames, one graph at a time, without any dynamics behind it. The per-step exactly-once bookkeeping is deliberately bypassed — these are replayed frames, not steps of this run — and the frame index stands in for the step count.
- Parameters:
frames (Batch) – Prior frames in chronological order, one graph per frame.
- Return type:
None
- reprime_from_scratch(batch)[source]#
Recompute the model and reapply the bias at fixed coordinates.
Unlike
_reprime(), which reuses the cached physical outputs, this repeats the model forward pass — the caller has changed something the model itself responds to. An accepted replica-exchange swap is that case: the forces in the batch were produced under the previous labels, and the integrator reads them in its next half-step before any model call.Reproduces the prefix of
BaseDynamics.stepup to the model call, including theBEFORE_COMPUTEhooks. Those are not optional: a cutoff model reachesadapt_inputexpecting a neighbor list thatNeighborListHookbuilds at exactly that stage, so callingcompute()bare would fail.- Parameters:
batch (Batch) – The live batch.
- Return type:
None
- state_dict()[source]#
Return the delivery bookkeeping that must survive a restart.
- Returns:
The step at which each bias last received
update(), which is what keeps delivery exactly-once across the boundary.- Return type:
Mapping[str, Any]
- sync_seen_versions()[source]#
Re-baseline the cached per-bias state versions from the live biases.
The cache answers “has this bias changed since the hook last looked”, which is what decides whether forces need re-priming. It must be re-baselined after anything that changes a bias’s version without the hook observing it — construction, and a restore, which loads a saved version straight onto the bias.
Called from both, rather than inlined, so the two cannot drift: a restore that skipped this would leave the cache at
0against a restored version ofN, and the first post-restoreupdate()would re-prime on a change that never happened.- Return type:
None