Dynamics Hooks — Stages & Usage#
This page covers hook behaviour specific to dynamics simulations. For the general hook protocol, context, and registry see Hooks — Core Framework.
See also
User guide: Hooks — conceptual overview, writing custom hooks, and composing hook pipelines.
Core framework: Hooks — Core Framework — the
Hookprotocol,HookContext/DynamicsContext, andHookRegistryMixin.
DynamicsStage#
DynamicsStage enumerates eleven lifecycle
hook-firing points: ON_ADMISSION for batch setup, followed by ten stages
within each dynamics step:
DynamicsStage lifecycle hook firing points.#
Stage |
Value |
When it fires |
|---|---|---|
|
-1 |
Once when a batch enters the engine, before force priming and the first step. |
|
0 |
Very start of each step, before any operations. |
|
1 |
Before the first integrator half-step (positions). |
|
2 |
After positions are updated, before the forward pass. |
|
3 |
Before the model forward pass. |
|
4 |
After forces/energy are written to the batch. |
|
5 |
Before the second integrator half-step (velocities). |
|
6 |
After velocities are updated. |
|
7 |
Very end of the step, after all operations. |
|
8 |
After convergence evaluation. |
|
9 |
After |
ON_ADMISSION fires once per run or managed batch replacement, before force
priming. It ignores a hook’s step-based frequency; for a multi-stage hook,
the frequency continues to gate all other stages. In
FusedStage, it runs outside the compiled
_step_impl, making it suitable for validation and shape-dependent setup.
ON_GRADUATE reports graduation. A graph is active while its status is
below the engine’s exit_status, and it graduates on the step its status
reaches exit_status, whether a convergence criterion, a step budget, or
another hook changed it, at any stage of the step: the mask compares the status
at step start with the status at dispatch. Without a status column nothing
can graduate, so the stage is not dispatched; with one, it is not gated on the
mask, because checking the mask first would synchronize with the host. A hook
must therefore read ctx.graduated_mask rather than assume a graph graduated.
Built-in dynamics hooks#
The nvalchemi.dynamics.hooks package ships production-ready hooks in three
categories. NeighborListHook,
BiasedPotentialHook, and
WrapPeriodicHook are general-purpose hooks documented
in Hooks — Core Framework.
Observer hooks#
Observer hooks fire at AFTER_STEP and do not modify the batch.
LoggingHook#
LoggingHook writes per-step scalar
observables to a backend. The default scalars are energy (per atom), fmax
(maximum force component across all atoms), temperature (derived from kinetic
energy when velocities are present), and converged_fraction (fraction of
samples that have met the convergence criterion).
backend is a required argument that selects the output destination. It must
be one of "csv", "tensorboard", or "custom":
"csv"— writes one row per step tolog_path. Use when you need per-step data for post-run analysis in Python or a spreadsheet."tensorboard"— writes scalar events tolog_pathas a TensorBoard event file. Use when comparing scalar trends across experiments."custom"— routes each snapshot to a custom writer callable passed via the separatewriter_fnparameter (signaturefn(step_count, rows) -> None), such as a W&B or MLflow sink.
frequency throttles writes to every N steps. For long runs,
frequency=10 or higher keeps output manageable without losing trends.
SnapshotHook#
SnapshotHook writes the full batch state
— positions, velocities, forces, energy, cell, and atom types — to a
DataSink at a specified frequency.
sink accepts one of three DataSink types:
GPUBuffer— stores batches in GPU memory. Fastest write path; capacity bounded by GPU memory.HostMemory— stores in pinned CPU memory. Slightly slower; larger capacity and works without GPU.ZarrData— streams to disk in Zarr format. Unbounded capacity; suitable for long trajectories and persistent storage.
After the run, call sink.read() to retrieve the accumulated trajectory as a
Batch. Use this hook when you need full atomic-detail
trajectories for analysis, visualization, or continuation from a specific frame.
ConvergedSnapshotHook#
ConvergedSnapshotHook writes only
newly-converged samples at ON_CONVERGE — once per sample, exactly when
convergence is detected — rather than periodically. The same DataSink types
apply as for SnapshotHook.
This hook is designed for FusedStage pipelines
where samples converge at different steps. A periodic snapshot would produce
ragged data or miss samples; this hook captures each sample exactly once. Call
sink.read() after the run to collect all converged structures.
EnergyDriftMonitorHook#
EnergyDriftMonitorHook tracks cumulative
energy drift in NVE (constant-energy) simulations and takes a configurable
action when drift exceeds a threshold.
Key arguments:
threshold— allowed drift, in the model’s energy output units.metric— how drift is measured."per_atom_per_step"normalises by system size and simulation length, making the threshold transferable across systems and time steps.action—"raise"(default) halts the run;"warn"logs and continues. Use"warn"in production,"raise"during model validation.frequency— check every N steps. Checking every step is accurate but adds overhead for large batches;frequency=100is typical.
StabilityMonitor#
StabilityMonitor is the offline counterpart
of the drift monitor. Instead of comparing one live value against a threshold,
it records the total energy and momentum of every graph at each firing, as
float64 on the host, and reports the whole series once the run is over through
metrics(). The result is a
StabilityMetrics record: the endpoint drift
per atom, a least-squares drift rate per nanosecond when a timestep_fs is
given, the RMS fluctuation about that fit, the largest excursion, and the
largest deviation of any graph’s total momentum, each for the worst graph or as
the mean over graphs under aggregate="mean".
Key arguments:
warmup_steps— firings before this step count are discarded, so a structure that is not an equilibrium of the propagated potential relaxes before the series starts. Without it, the relaxation is reported as drift.divergence— a predicate flagging diverged graphs, evaluated at every firing. The first firing that flags any graph ends the series and is recorded asfirst_divergence_step. It defaults tononfinite_graph_mask().stop_on_composition_change— recording always stops when the graph count or the per-graph atom counts change; this flag also stops it when asystem_idin a slot changes, which is what an inflight refill of an equal-size system looks like.
total_momentum(), the per-graph mass-weighted
velocity sum the monitor records, is exported alongside it. A batch that
carries status brings an active_graph_mask to every dispatch, and the
monitor records as long as that mask keeps every graph active. Like the drift
monitor, it does not yet support a dispatch in which some graphs are inactive.
StageTimingHook and TorchProfilerHook are described in Hooks — Core Framework.
Post-compute hooks#
Post-compute hooks fire at AFTER_COMPUTE, after forces and energy are
written to the batch but before the velocity update. They may modify the batch.
NaNDetectorHook#
NaNDetectorHook checks energy and forces for
NaN or Inf values after the model forward pass. On detection it raises a
RuntimeError that includes the affected graph indices and the current step
count so the offending sample can be identified.
extra_keys extends the check to additional batch fields beyond energy and
forces. For models that output stress tensors, pass
extra_keys=["stress"].
When used with MaxForceClampHook, register
the clamping hook first so the detector sees the clamped values and only catches
what clamping did not prevent.
MaxForceClampHook#
MaxForceClampHook rescales per-atom forces
whose magnitude exceeds max_force back to the threshold, preserving
direction. Energy is not modified.
max_force is in the same units as the model’s force output (typically
eV/Å). Clamping is applied in-place to any per-atom force whose magnitude
exceeds the threshold. Frequent clamping during model development is a signal to
identify problem configurations.
Clamping prevents numerical blow-up from large forces in high-energy or poorly-sampled configurations. It is a safety net, not a model fix: if clamping fires frequently, the model has accuracy problems for those structures.
nonfinite_graph_mask#
nonfinite_graph_mask() is a standalone
per-graph finiteness check for a hook or workflow to call directly; the two
guards above keep element-level checks of their own. It returns one boolean per
graph, True where any value under the inspected keys (positions and
forces by default) is NaN or infinite, and it does not synchronize with the
host. It takes no action itself. The caller decides what to do with a diverged
graph, meaning one holding a non-finite value: freeze it, drop it, or keep it
out of a capture.
Constraint hooks#
Constraint hooks enforce geometric constraints across integration steps. They can span the pre-update, compute, and post-update boundaries to prevent frozen state from influencing either half of the integrator while still presenting a constrained geometry to the model.
FreezeAtomsHook#
FreezeAtomsHook keeps selected atoms fixed:
it fires at five stages. At BEFORE_PRE_UPDATE it snapshots positions and
clears prior forces and velocities; at AFTER_PRE_UPDATE it restores the
constrained geometry before compute preparation; at AFTER_COMPUTE it clears
new model forces when zero_forces=True; at BEFORE_POST_UPDATE it always
clears frozen-atom forces; and at AFTER_POST_UPDATE it restores positions
and zeroes velocities.
freeze_category is the integer batch.atom_categories value that marks
frozen atoms. It defaults to SPECIAL.
Only atoms matching that value are frozen; all others evolve freely.
Set zero_forces=False to expose raw frozen-atom model forces to
AFTER_COMPUTE observers. Those forces are still cleared at
BEFORE_POST_UPDATE, before the second integrator update, so they cannot
move the frozen atoms.
Use this hook for partial-system relaxations (freeze the substrate, relax the adsorbate), slab calculations (freeze bottom layers), or any configuration where part of the system must remain rigid.
Usage examples#
Logging to CSV every 100 steps#
from nvalchemi.dynamics.hooks import LoggingHook
hook = LoggingHook(frequency=100, backend="csv", log_path="md_log.csv")
dynamics = DemoDynamics(model=model, n_steps=10_000, dt=0.5, hooks=[hook])
dynamics.run(batch)
Recording trajectories to a data sink#
from nvalchemi.dynamics.hooks import SnapshotHook
from nvalchemi.dynamics import HostMemory
sink = HostMemory(capacity=10_000)
hook = SnapshotHook(sink=sink, frequency=10)
dynamics = DemoDynamics(model=model, n_steps=1_000, dt=0.5, hooks=[hook])
dynamics.run(batch) # 100 snapshots
trajectory = sink.read()
Safety: NaN detection and force clamping#
Registration order determines execution order at the same stage. Clamp before checking so the detector sees the corrected forces:
from nvalchemi.dynamics.hooks import MaxForceClampHook, NaNDetectorHook
dynamics = DemoDynamics(
model=model,
dt=0.5,
hooks=[
MaxForceClampHook(max_force=50.0),
NaNDetectorHook(extra_keys=["stress"]),
],
)
Hooks inside FusedStage#
Hooks may be registered directly on a
FusedStage or on any of its sub-stages. Step,
compute, and integrator update boundaries all fire at both levels. Every hook
receives the full batch and an active mask for the graphs participating at that
boundary. Fused-stage masks span all participating sub-stages; sub-stage masks
are restricted to that sub-stage’s status. Every mask is fixed at the start of
the step. A hook that must see a status change made earlier in the same step
reads the current status through
BaseDynamics.active_graph_mask(ctx.batch, exit_status).
During force repriming, graphs remain
active for step and compute hooks but are excluded from pre-update and
post-update hooks because their integrator updates are skipped. At admission,
the fused-stage ON_ADMISSION hooks fire first, followed by each sub-stage’s
admission hooks in sub-stage order.
At every BEFORE_* boundary, the fused-stage hooks fire before the sub-stage
hooks. At every AFTER_* boundary, the sub-stage hooks fire before the
fused-stage hooks. Only ON_CONVERGE remains sub-stage-only because
convergence is evaluated independently for each sub-stage. Registered
ON_CONVERGE hooks on a fused sub-stage run every step interval configured by
hook.frequency and must inspect ctx.converged_mask to determine which
samples, if any, converged.
BaseDynamics.step() calls these hooks only when convergence is detected.
ON_GRADUATE fires at both levels, after the step-budget migration and the
ON_CONVERGE dispatch. Sub-stage hooks fire first, each with
ctx.graduated_mask limited to the graphs its sub-stage owned. Fused-stage
hooks fire last, with every graph that graduated during the step. The dispatch
is not gated on the mask, so the mask may be all False and a hook must read
it.
Register a cross-stage constraint once on the fused stage when it should apply to every active system, regardless of its current sub-stage:
from nvalchemi.dynamics.hooks import FreezeAtomsHook
fused = optimizer + md
fused.register_hook(FreezeAtomsHook())
fused.run(batch)
Register the hook on an individual sub-stage instead when the constraint should apply only during that phase.
Hook ordering inside a fused step:
Hook ordering inside a single FusedStage.step().#
Initial force priming follows the same nested BEFORE_COMPUTE and
AFTER_COMPUTE ordering. Safety hooks (NaNDetectorHook,
MaxForceClampHook) and observer hooks (LoggingHook, SnapshotHook)
therefore behave consistently whether they are registered on the fused stage
or on a specific sub-stage.
API reference#
Log scalar observables with one row per graph or group. |
|
Save a snapshot of the active batch to a |
|
Write only newly converged samples to a |
|
Track energy drift and warn or stop if it exceeds a threshold. |
|
Dynamics hook recording energy and momentum along a trajectory. |
|
Conservation diagnostics of one trajectory. |
|
Return the total linear momentum of each graph. |
|
Detect NaN or Inf values in model outputs and raise immediately. |
|
Clamp per-atom force vectors to a maximum magnitude. |
|
Flag the graphs of batch holding a NaN or infinite value under any of keys. |
|
Freeze selected atoms during molecular dynamics simulation. |
|
Propose and accept pairwise swaps of per-system state. |
The module-level kinetic-energy helper the temperature-reading hooks are built on is exported alongside them:
Compute |
The general-purpose profiling hooks
StageTimingHook and
TorchProfilerHook also work with dynamics and are
documented in Hooks — Core Framework.