nvalchemi.dynamics.BaseDynamics#
- class nvalchemi.dynamics.BaseDynamics(model, hooks=None, convergence_hook=None, n_steps=None, exit_status=1, by_group=False, reprime_on_entry=False, **kwargs)[source]#
Base class for all dynamics simulations.
This class coordinates a
BaseModelMixinmodel with a numerical integrator to evolve aBatchof atomic systems over time. It manages the step loop, hook execution at stage boundaries, and model evaluation.BaseDynamicsinherits fromHookRegistryMixinfor hook storage and from_CommunicationMixinfor inter-rank communication and buffer management for pipeline execution. All dynamics subclasses automatically have communication capabilities.The public interface centers on three methods.
run(batch)is the top-level entry point: it repeatedly callsstep()forn_stepsiterations and is the only method most users need.n_stepscan be set at construction time or passed torun().step(batch)executes a single simulation step, orchestrating the full hook-wrapped sequencepre_update → compute → post_update, with hooks fired at each stage boundary, followed by convergence checking. Subclasses should generally NOT overridestep.compute(batch)performs the model forward pass: it callsmodel(batch)which must return a fully adaptedModelOutputsdict, validates outputs against__needs_keys__, and writes results (forces, energies, stresses) back to the batch in-place. Subclasses should generally NOT overridecompute.- Parameters:
model (BaseModelMixin)
hooks (list[Hook])
convergence_hook (Any)
n_steps (int | None)
exit_status (int)
by_group (bool)
reprime_on_entry (bool)
kwargs (Any)
- model#
The neural network potential model.
- Type:
- step_count#
The current step number, starting from 0.
- Type:
int
- model_is_conservative#
Indicates that the model uses automatic differentiation to obtain forces.
- Type:
bool
- convergence_hook#
Hook that evaluates composable convergence criteria. Defaults to a single forces-based criterion with threshold
0.05.- Type:
- n_steps#
Total number of simulation steps for
run().Nonemeans the step count must be supplied when callingrun().- Type:
int | None
- exit_status#
Status code threshold for graduated samples. Samples with
status >= exit_statusare treated as no-ops duringstep()— their positions and velocities are preserved through the integrator. Default is 1.- Type:
int
- by_group#
Whether dynamics update units are graph groups rather than individual graphs. Grouped batches must provide a valid group layout.
- Type:
bool
- reprime_on_entry#
Whether graphs entering from another stage get forces from this dynamics before their first update instead of reusing carried forces.
- Type:
bool
- samples_equilibrium#
Whether stepping samples an equilibrium ensemble, so that a frame along a trajectory is a draw from a distribution rather than a point on a path to a minimum.
Truehere and on the integrators;Falseon the relaxation optimizers, which descend. A distribution-matching objective reads it to tell the two apart.- Type:
ClassVar[bool]
- __needs_keys__#
Set of output keys that this dynamics requires from the model. Empty by default on
BaseDynamics. Subclasses declare their own requirements (e.g., typically forces for optimization and MD). Checked in_validate_model_outputs()after each forward pass.- Type:
set[str]
- __provides_keys__#
Set of keys that this dynamics produces or updates on the batch beyond model outputs. Empty by default. Subclasses declare what additional state they provide (e.g.,
{"velocities", "positions"}for velocity verlet). Used for validation and buffer preallocation.- Type:
set[str]
Notes
CUDA streams. Used as a context manager, dynamics creates a dedicated stream shared by torch and warp. This supports overlapping GPU work, multi-stage pipelines, and CUDA-graph capture. Entry waits for prior work, but exit is asynchronous; synchronize before consuming results on another stream.
Without the context manager (i.e. when you just call run() directly), dynamics uses the caller’s current torch stream and binds warp operations to it for each step. Callers using custom streams are responsible for cross-stream ordering.
Developers implementing a new integrator should override
pre_update(batch)andpost_update(batch)to implement the integration scheme. These are called aroundcompute()—pre_updatebefore,post_updateafter. For example, Velocity Verlet updates positions inpre_updateand velocities inpost_update. The class-level sets__needs_keys__and__provides_keys__declare what outputs the dynamics requires from the model and what additional state it produces; requirements are checked in_validate_model_outputs()after each forward pass.FusedStageapplies maskedpre_updatecalls before one sharedcomputecall and maskedpost_updatecalls afterward. Models must beBaseModelMixininstances — plainnn.Moduleis not accepted.Examples
>>> model = MyPotentialModel() >>> dynamics = BaseDynamics(model, n_steps=1000) >>> dynamics.run(batch)
- static active_graph_mask(batch, exit_status)[source]#
Return the active graphs of batch, read from its current
status.A graph is active while its
statusis below exit_status; the integrator treats every other graph as a no-op. This method reads thestatuscolumn as it is at the time of the call.ctx.active_graph_maskdiffers: every hook dispatch of a step receives the mask computed at the start of that step. A hook that runs after a status change on the same step, such as one registered after aConvergenceHook, sees the change in this method’s result but not inctx.active_graph_mask.- Parameters:
batch (Batch) – Batch whose
statuscolumn is read. An inflight batch may keep rows beyond the graphs it holds, so only the firstnum_graphsrows are read.exit_status (int) – Status at which a graph stops being active, usually the engine’s
exit_status.
- Returns:
Truewherestatus < exit_status, orNonewhen batch carries nostatuscolumn.- Return type:
Bool[torch.Tensor, “ G”] | None
- apply_per_system_params(params, batch)[source]#
Rebind per-system parameters — temperature, timestep, and so on.
The reusable half of any method that permutes per-system state across walkers: replica exchange over a temperature ladder, basin hopping with swaps, a population or evolutionary structure search, any annealing schedule. What they share is “walker b is now running under these parameters”; what differs is the rule that decided it.
Implementations must transform dependent private state — thermostat chain masses, velocity scaling — as one indivisible change. An integrator that accepted the new target while leaving its velocities and thermostat at the old one would keep sampling the ensemble the walker just left, with no symptom the run would show. That is why batch is a parameter rather than a follow-up call: the velocity rescale needs the live batch, and a caller who forgot the second call would get exactly the silent failure this method exists to prevent.
- Parameters:
params (Mapping[str, torch.Tensor]) – Parameter name to its new per-graph value, shape
[B]."temperature"is in Kelvin.batch (Batch) – The live batch, so dependent fields — velocities — move with the parameters.
- Raises:
NotImplementedError – Always, on the base class. An integrator that cannot rebind must fail rather than silently accept a label-only change.
- Return type:
None
- bookkeeping_keys()[source]#
Return the bookkeeping fields this dynamics and its sub-stages keep on a batch.
Every stage carries its class’s registry, grown by
register_bookkeeping_key(). A subclass may register keys on its own class that the base registry never sees, so the union is taken over the whole composition. Read it at call time: registration happens as stages are built.- Returns:
Batch field names that carry propagator bookkeeping, such as
statusandsystem_id, and mean nothing outside the run that wrote them.- Return type:
frozenset[str]
Examples
>>> from nvalchemi.dynamics import BaseDynamics >>> sorted(BaseDynamics(model=model).bookkeeping_keys()) ['status', 'system_id']
- check_initial_batch(batch)[source]#
Reject an initial batch this dynamics cannot take its first step from.
- Parameters:
batch (Batch) – Batch the first step would propagate from, or a one-graph sample that stands in for it.
- Raises:
ValueError – If batch lacks a field named by
required_input_keys().- Return type:
None
- compute(batch, active_graph_mask=None)[source]#
Perform the model forward pass to compute forces and energies.
This method:
Runs the model forward pass, which should enable gradients
Adapts outputs to the standard format
Validates outputs against dynamics requirements
Allocates missing output buffers and writes known keys back to the batch via
_OUTPUT_KEY_TO_BATCH_ATTRDetaches all output tensors from the computation graph and exposes them as
_last_outputsfor custom dynamics subclasses that need charges, embeddings, or other non-standard outputs.Restores the original
requires_gradstate of model autograd inputs, so downstream hooks can safely perform in-place operations.
The detach in step 5 is deliberate: model wrappers may return tensors that are still attached to the autograd graph (e.g. MACE returns energies on the graph even after computing forces internally). Since
compute()is a terminal consumer — values have already been copied into the batch — holding the graph would cause memory to grow without bound across dynamics steps. Callers that need the live graph (e.g. training loops computing a loss) should callmodel(batch)directly instead ofcompute().- Parameters:
batch (Batch) – The current batch of atomic data. Will have forces and energies updated in-place.
active_graph_mask (torch.Tensor | None, optional) – Boolean mask selecting graph rows whose model outputs may be published to the batch. Node-level outputs use the corresponding broadcast node mask. Inactive rows retain their existing values. When None, publish every output row.
- Returns:
OrderedDict containing the model outputs (energies, forces, and any other computed properties). All tensors are detached from the computation graph.
- Return type:
ModelOutputs
- Raises:
RuntimeError – If the model outputs do not satisfy the dynamics requirements specified by
__needs_keys__.
- load_state_dict(state)[source]#
Restore integrator state produced by
state_dict().- Parameters:
state (Mapping[str, Any]) – The mapping previously returned by
state_dict().- Raises:
RuntimeError – If the checkpoint carries per-system state but this integrator has not initialised its own — restoring into an uninitialised integrator would leave the two silently out of step. Prime the dynamics once (or run a step) before restoring.
KeyError – If a restored key is absent from the live state, which means the checkpoint came from a differently-configured integrator.
- Return type:
None
- masked_update(batch, mask)[source]#
Apply pre_update and post_update only to selected samples in the batch.
This method allows selective updates where only some graphs in the batch are modified. Unmasked samples retain their original positions and velocities.
The mask is a boolean tensor of shape (B,) where B is the number of graphs. True values indicate samples that should be updated.
- Parameters:
batch (Batch) – The current batch of atomic data, modified in-place.
mask (Bool[Tensor, "B"]) – Boolean mask selecting which graphs to update. Shape (B,) where B is the number of graphs in the batch.
- Return type:
None
Notes
This method expands the graph-level mask to node-level using batch.batch_idx to correctly index per-node tensors like positions and velocities.
- property model_is_conservative: bool#
Returns whether or not the model uses conservative forces.
- post_update(batch)[source]#
Perform the second half of the integration step.
This method is a no-op in the base class and should be overridden by integrator subclasses (e.g., Velocity Verlet would update velocities here).
- Parameters:
batch (Batch) – The current batch of atomic data, modified in-place.
- Return type:
None
- pre_update(batch)[source]#
Perform the first half of the integration step.
This method is a no-op in the base class and should be overridden by integrator subclasses (e.g., Velocity Verlet would update positions here).
- Parameters:
batch (Batch) – The current batch of atomic data, modified in-place.
- Return type:
None
- redistribute_state(walker_ids)[source]#
Reorder per-system state to match a new walker layout.
Needed only when a checkpoint is restored into a batch whose rows are ordered differently from the one it was written from. Batch position is not an identity, so the caller supplies the permutation.
- Parameters:
walker_ids (torch.Tensor) – Row permutation, shape
[B]: entry i is the index in the current state that should become row i.- Raises:
RuntimeError – If the integrator has no per-system state to reorder.
- Return type:
None
- refill_check(batch, exit_status)[source]#
Replace graduated samples via index-select and append.
Graduated graphs (
status >= exit_status) are written to sinks, then removed viaBatch.index_select()on the remaining indices. Replacement samples from the sampler are appended viaBatch.append(). Dynamics-specific bookkeeping fields are written into the result batch via the_bookkeeping_keysregistry. After initial force priming, engines supporting per-graph priming let existing graphs continue updating normally. Newly added graphs skip integrator updates for one iteration while the model computes their initial forces.- Parameters:
batch (Batch) – The current batch with a
statusfield.exit_status (int) – Status code indicating graduation.
- Returns:
A new batch with graduated graphs replaced by fresh samples, or
Noneif no active samples remain (sampler exhausted and all graduated) — in which caseself.doneis set toTrue.- Return type:
Batch | None
- Raises:
RuntimeError – If
self.samplerisNone.
- classmethod register_bookkeeping_key(key, init_fn)[source]#
Register a graph-level bookkeeping field to survive refill_check.
- Parameters:
key (str) – Field name on Batch.
init_fn (Callable[[int, torch.device], torch.Tensor]) – Factory that creates a zero-initialized tensor of shape (n, 1) for n systems on the given device.
- Return type:
None
- required_input_keys()[source]#
Return the batch fields this dynamics updates in place from its first step.
A dynamics computes its model outputs (
BEFORE_COMPUTE,compute,AFTER_COMPUTE) before its firstpre_update. The fields its__needs_keys__outputs are written to therefore need not be on the initial batch. The fields it updates in place must be there: its__provides_keys__other thanpositions, plusatomic_masseswhen those includevelocities.- Returns:
Batch field names an initial batch must carry.
- Return type:
frozenset[str]
- run(batch, n_steps=None)[source]#
Run the dynamics simulation for a specified number of steps.
This is a convenience method that repeatedly calls
step(). The step count can be set at construction time via then_stepsparameter, or passed directly to this method. A value passed here takes precedence over the instance attribute.May be called bare or inside the engine’s context manager; the two differ in CUDA stream behavior — see the CUDA stream semantics notes on
BaseDynamics.- Parameters:
batch (Batch) – The initial batch of atomic data.
n_steps (int | None, optional) – The number of steps to run. If
None, falls back toself.n_steps. If both areNone, raisesValueError.
- Returns:
The batch after all steps have been executed.
- Return type:
- Raises:
ValueError – If no step count is available (both the argument and
self.n_stepsareNone).
- seed_offset(offset)[source]#
Add offset to every
random_seedin this dynamics and its sub-stages.A stochastic integrator such as
NVTLangevinexposes its seed as an integerrandom_seedproperty. Every stage reached throughFusedStagesub-stages is offset on its own, so a composition whose root holds no seed still moves the thermostat that draws its noise. Data-parallel drivers call this with a rank-keyed offset so ranks stepping in lockstep apply different noise, and call it again with the negated offset to put the seeds back.- Parameters:
offset (int) – Amount added to every seed found. Zero leaves every seed as it is and still reports the stages that could not be offset.
- Returns:
Class names of the stages that hold randomness this call could not offset: a stage whose
random_seedhas no setter, or one that holds atorch.Generatorand exposes no integerrandom_seed. A stage exposing neither is taken as deterministic and is not reported.- Return type:
tuple[str, …]
Examples
>>> from nvalchemi.dynamics import NVTLangevin >>> dynamics = NVTLangevin(model, dt=1.0, temperature=300.0, friction=0.01, random_seed=7) >>> dynamics.seed_offset(1_000) () >>> dynamics.random_seed 1007
- state_dict()[source]#
Return the integrator state needed to resume this run exactly.
Covers the step counter, the RNG seed, and every per-system tensor in
self._state— thermostat chain variables, per-system timesteps, barostat auxiliaries, whatever the subclass put there.Nothing here is a Python object graph: values are tensors and scalars, so the result is directly representable in Zarr without a pickle payload.
- Returns:
step_count,random_seed(when the integrator has one), and astatesubmapping of per-system tensors.stateis empty for an integrator that keeps none, and for one whose lazy initialisation has not run yet.- Return type:
dict[str, Any]
Notes
- Reproducibility of stochastic integrators
NVTLangevinderives its noise fromrandom_seed + step_countrather than advancing a stateful generator, so restoring those two integers reproduces the identical noise sequence. There is no generator object to serialise.
- step(batch)[source]#
Execute a single dynamics step with the full hook-wrapped sequence.
The step proceeds as follows: 1. Fire ON_ADMISSION hooks once for a newly admitted batch 2. Prime required model outputs once, before the first integration step 3. BEFORE_STEP hooks 4. BEFORE_PRE_UPDATE hooks -> pre_update() -> AFTER_PRE_UPDATE hooks 5. BEFORE_COMPUTE hooks -> compute() -> AFTER_COMPUTE hooks 6. BEFORE_POST_UPDATE hooks -> post_update() -> AFTER_POST_UPDATE hooks 7. AFTER_STEP hooks 8. Check convergence and fire ON_CONVERGE hooks if any samples converged 9. Fire ON_GRADUATE hooks with the graphs that reached exit_status this step 10. Increment step_count
Compute hooks run for every model evaluation. On the first call to
step(), initial force priming evaluates the model beforestep_countadvances, and the normal step evaluates it again. Consequently, both compute-hook dispatches receivestep_count == 0.Samples with
status >= exit_statusare treated as no-ops for the integrator (pre_update/post_update). Their positions and velocities are preserved through the step. This enables back-pressure handling in pipeline mode where converged samples may remain in the active batch when the send buffer is full.- Parameters:
batch (Batch) – The current batch of atomic data.
- Returns:
The updated batch after the step, and a 1-D integer tensor of converged sample indices (or
Noneif nothing converged).- Return type:
tuple[Batch, torch.Tensor | None]