Dynamics: Optimization and Molecular Dynamics#

The dynamics module provides a unified framework for running geometry optimizations and molecular dynamics simulations on GPU. All simulation types share a common execution loop — hooks, model evaluation, convergence checking — so you learn the pattern once and apply it to any integrator.

Tip

It is important to keep in mind that nvalchemi follows a batch-first principle: users should think and reason about dynamics workflows with multiple structures simultaneously, as opposed to individual structures being processed sequentially.

Tip

AI coding assistant? Load the nvalchemi-dynamics-api and nvalchemi-dynamics-implementation agent skills for concise instructions on configuring simulations and implementing custom integrators.

The execution loop#

Every simulation is driven by BaseDynamics, which defines a single step() that all integrators and optimizers follow. The loop is broken into discrete stages, enumerated by DynamicsStage:

Stage

When it fires

ON_ADMISSION

Once when a batch enters the engine, before force priming and the first step

BEFORE_STEP

At the very beginning of a step, before any operations

BEFORE_PRE_UPDATE

Just before the integrator’s first half-step

AFTER_PRE_UPDATE

After the first half-step completes

BEFORE_COMPUTE

Just before the model forward pass

AFTER_COMPUTE

After the model forward pass completes

BEFORE_POST_UPDATE

Just before the integrator’s second half-step

AFTER_POST_UPDATE

After the second half-step completes

AFTER_STEP

At the very end of a step, after all operations

ON_CONVERGE

After convergence evaluation; for fused sub-stages, runs at the hook’s configured interval

ON_GRADUATE

After ON_CONVERGE; ctx.graduated_mask marks the systems whose status reached exit_status this step. Dispatched whenever a hook listens and the batch carries a status column, so the mask may be all False

When a batch is newly admitted, ON_ADMISSION hooks fire before force priming and before the first step. Admission is reset for every new run() and for managed membership changes such as inflight refill or pipeline communication. Repeated step() calls do not re-fire admission until it is reset. Because admission is an event rather than a recurring step stage, it ignores a hook’s frequency; for a multi-stage hook, the frequency still applies at its other stages.

After initial force priming, inflight refill in BaseDynamics and FusedStage lets existing graphs continue updating normally. Newly added graphs skip both integrator updates for one iteration while the regular model evaluation computes their initial forces. This avoids an extra whole-batch model evaluation. Newly added graphs begin integrator updates on the following step. In FusedStage, their stage step counters do not advance during the iteration that computes their initial forces. If no graphs remain before a refill, the refilled batch is primed as a fresh batch instead.

Each step then proceeds through these stages in order:

  1. BEFORE_STEP hooks fire.

  2. pre_update(batch) — the integrator’s first half-step (e.g. update velocities by half a timestep), bracketed by BEFORE/AFTER_PRE_UPDATE hooks.

  3. compute(batch) — the wrapped ML model evaluates forces (and stress, if needed), bracketed by BEFORE/AFTER_COMPUTE hooks.

  4. post_update(batch) — the integrator’s second half-step (e.g. complete the velocity update with the new forces), bracketed by BEFORE/AFTER_POST_UPDATE hooks.

  5. AFTER_STEP hooks fire (convergence checks, logging, …).

  6. Convergence is evaluated. Standard dynamics fire ON_CONVERGE hooks only when systems converge. Fused sub-stages evaluate convergence every step; registered hooks run when allowed by hook.frequency, receive that sub-stage’s convergence mask as ctx.converged_mask, and must inspect it to determine which systems converged. Converged systems in a multi-stage pipeline then migrate to the next stage.

  7. ON_GRADUATE hooks fire, when any are registered and the batch carries a status column. A system graduates on the step its status reaches exit_status, whatever changed it, and ctx.graduated_mask marks the systems that graduated during this step.

run(batch, n_steps) calls step() in a loop until all systems converge or n_steps is reached. Every hook declares which DynamicsStage stage it should fire at and at what frequency, so you have fine-grained control over when callbacks execute.

Declarative dynamics strategies#

DynamicsStrategy stores engine configuration and reconstructible hook specs. For a workflow using one engine, set engine and pass additional constructor arguments in engine_kwargs:

from nvalchemi.dynamics import DynamicsStrategy, NVTLangevin

strategy = DynamicsStrategy(
    model=model,
    engine=NVTLangevin,
    engine_kwargs={"dt": 1.0, "temperature": 300.0, "friction": 0.01},
    n_steps=100,
    cache_engine=True,
)
batch = strategy.run(batch)
batch = strategy.run(batch, n_steps=200)

The default build_engine() supplies model, n_steps, and build_hooks() to the engine. Keep those three keys out of engine_kwargs. build_hooks() returns a new list of extra_hooks. Subclasses can override it to add their own hooks, or override build_engine() for workflows with multiple stages, such as NEB. Without an engine or a build_engine() override, construction raises NotImplementedError when the builder is called.

By default, every run() builds a fresh engine. With cache_engine=True, the first run builds the engine and later runs reuse its original configuration and runtime state, including the step counter. A subclass can opt in by declaring cache_engine: bool = True. Calling build_engine() directly always constructs a fresh engine.

to_spec_dict() serializes the engine class as an importable dotted path and hooks as constructor specs. Restore it with DynamicsStrategy.from_spec_dict(spec, model=model). The live model and cached engine state are excluded, so a restored strategy starts with an empty cache.

Using dynamics as a context manager#

All dynamics objects (optimizers, integrators, fused stages) support Python’s context manager protocol. The with block manages a dedicated Stream for the simulation and ensures hooks are properly opened and closed:

from nvalchemi.dynamics import FIRE2, ConvergenceHook

with FIRE2(
    model=model,
    dt=0.05,
    n_steps=500,
    convergence_hook=ConvergenceHook.from_fmax(0.05),
) as opt:
    relaxed = opt.run(batch)

When you call run() without a with block, hook setup and teardown happen automatically inside run(). The context manager form is useful when you need to call step() manually or interleave dynamics with other operations while keeping hook state (e.g. open log files) alive.

Multi-stage pipelines with FusedStage#

Real workflows often chain multiple simulation phases: relax a structure, then run MD at increasing temperatures, then relax again. The FusedStage abstraction lets you compose stages with the + operator:

from nvalchemi.dynamics import FIRE2, NVTLangevin, ConvergenceHook

relax = FIRE2(
    model=model, dt=0.05, n_steps=200, convergence_hook=ConvergenceHook.from_fmax(0.05)
)
md = NVTLangevin(model=model, dt=1.0, temperature=300.0, friction=0.01, n_steps=5000)

pipeline = relax + md
with pipeline:
  pipeline.run(batch)

Systems start in the first stage (relaxation). As each system converges, it automatically migrates to the next stage (MD). Different systems can be in different stages simultaneously — the batch is partitioned internally, and a single model forward pass is shared across all active systems regardless of which stage they belong to.

Compiling with torch.compile#

FusedStage can compile its entire step function with torch.compile to reduce Python overhead and enable kernel fusion. Call compile() after composing stages:

fused = (relax + md).compile(fullgraph=True)
with fused:
    fused.run(batch)

compile() wraps the internal _step_impl method — which includes hook dispatch, masked sub-stage updates, and the shared model forward pass — in a single compiled graph. It returns the same instance, so you can chain it fluently.

You can also defer compilation by passing compile_step=True at construction time. In that case, torch.compile is invoked lazily when the context manager is entered:

fused = relax + md  # compile_step inherited from sub-stages or set explicitly
with fused:         # compilation happens here
    fused.run(batch)

Any keyword arguments accepted by torch.compile (e.g. fullgraph, mode, backend) can be passed to .compile() or stored via compile_kwargs at construction.

Note

Per-step hooks run inside the compiled _step_impl and must be compatible with torch.compile. Hooks that perform Python-side or data-dependent control flow (e.g. logging, I/O, or NaNDetectorHook) introduce graph breaks. NeighborListHook separately calls compiler-disabled helpers. Consequently, these hooks are not compatible with fullgraph=True. Use only torch-compatible per-step hooks when an unbroken graph is required.

Use DynamicsStage.ON_ADMISSION for one-time validation, shape-dependent tensor allocation, and Python-side setup. FusedStage dispatches admission before force priming and outside compiled _step_impl, so this setup does not enter the steady-state graph.

Distributed pipelines#

When a workflow needs more than one GPU — for example, relaxing structures on one device and running MD on another — the DistributedPipeline distributes stages across ranks. Where + fuses stages onto a single GPU, the | operator (or a stages dictionary) assigns one stage per rank and wires up inter-rank communication automatically.

Configuring a pipeline#

Each rank owns a BaseDynamics (or FusedStage) instance. Stages are collected in a dictionary keyed by global rank and handed to DistributedPipeline:

from nvalchemi.dynamics import FIRE2, NVTLangevin, DistributedPipeline
from nvalchemi.dynamics.base import BufferConfig

buffer_cfg = BufferConfig(num_systems=4, num_nodes=50, num_edges=0)

stages = {
    0: FIRE2(model=model, buffer_config=buffer_cfg, ...),        # upstream — relaxation
    1: NVTLangevin(model=model, buffer_config=buffer_cfg, ...),  # downstream — MD
}

pipeline = DistributedPipeline(stages=stages, backend="nccl")
with pipeline:
    pipeline.run()

Dynamics default to reprime_on_entry=False: received graphs use the upstream stage’s forces for their first update when they carry every model output the receiving dynamics needs. Graphs missing any of those outputs are primed locally, as with True: they skip one update while the stage’s next model evaluation supplies them. This assumes the stages use compatible models and force modifications. To refresh forces under the receiving stage’s model and hooks before updating, opt in explicitly on the receiving stage’s dynamics:

coarse = FIRE2(model=fast_model, buffer_config=buffer_cfg, ...)
fine = FIRE2(model=accurate_model, buffer_config=buffer_cfg, ..., reprime_on_entry=True)
pipeline = coarse | fine

With this option, received graphs skip one update while the stage’s next regular model evaluation gives them forces. Residents keep their forces and keep updating, so graphs arriving at different steps add no extra model evaluations. Sending, final-stage removal, and sampler refill do not refresh residents’ forces.

With either setting, initial sampler batches are primed locally. When received graphs need local forces, an empty or unprimed receiving stage primes the whole batch instead of skipping their update.

Inside a FusedStage, the flag works the same way for sub-stage transitions. Set it on a sub-stage’s dynamics, and graphs whose status changes into that sub-stage skip one update while their forces are refreshed.

A DomainParallel stage reads the flag from the dynamics it wraps. It holds one system at a time, so a received system that needs local forces is primed as a whole before its first update.

By default, setup() (called automatically by the context manager) sorts stages by rank and wires prior_rank / next_rank between adjacent stages as a simple linear chain. For more sophisticated topologies — such as multiple independent sub-pipelines running in the same job — set prior_rank and next_rank explicitly on each stage:

stages = {
    # Sub-pipeline A: rank 0 → rank 1
    0: FIRE2(model=model, buffer_config=buffer_cfg, prior_rank=None, next_rank=1, ...),
    1: NVTLangevin(model=model, buffer_config=buffer_cfg, prior_rank=0, next_rank=None, ...),
    # Sub-pipeline B: rank 2 → rank 3
    2: FIRE2(model=model, buffer_config=buffer_cfg, prior_rank=None, next_rank=3, ...),
    3: NVTLangevin(model=model, buffer_config=buffer_cfg, prior_rank=2, next_rank=None, ...),
}

The first stage in each sub-pipeline typically owns a sampler that feeds new structures into the chain; the last stage owns one or more data sinks that collect converged results.

Note

Each rank currently communicates with at most one upstream and one downstream neighbour (one-to-one topology). Fan-out (one-to-many) and fan-in (many-to-one) patterns are planned for a future release.

Sizing the buffer#

NCCL point-to-point transfers require fixed-size tensors, so each communicating stage pre-allocates a send buffer and a receive buffer whose dimensions are set by BufferConfig. The three fields control how much data a single transfer can carry:

Field

What it controls

num_systems

Maximum number of graphs (structures) per transfer. Determines throughput per step — higher values move more data but consume more GPU memory.

num_nodes

Total atom capacity across all graphs in the buffer. Must be large enough for the worst-case combination of systems. For example, transferring up to 4 structures of at most 50 atoms each requires num_nodes=200.

num_edges

Total edge capacity. Set to 0 when the downstream model recomputes edges via its neighbor list (the common case). Edges are omitted from transport, and arriving graphs have no edges until the neighbor-list hook rebuilds them. Only set a non-zero value if pre-computed edge attributes must be transferred.

from nvalchemi.dynamics.base import BufferConfig

# 4 structures, up to 200 atoms total, edges recomputed downstream
buffer_cfg = BufferConfig(num_systems=4, num_nodes=200, num_edges=0)

When the upstream stage has more converged samples than num_systems allows in a single transfer, the excess stays in the active batch as a no-op until the next step — this is the back-pressure mechanism described below.

Important

Every pair of communicating stages must share an identical BufferConfig. DistributedPipeline.setup() validates this and raises an error on mismatch.

Buffer synchronization#

The diagram below shows how two adjacent ranks exchange data through pre-allocated send and receive buffers during a single step. The upstream rank pushes converged samples; the downstream rank pulls them into its active batch.

digraph buffer_sync { rankdir=LR compound=true subgraph cluster_upstream { label="Rank 0 (upstream)" style=rounded color="#76b900" fontcolor="#eeeeee" u_batch [label="active_batch"] u_send [label="send_buffer" fillcolor="#4a3315"] u_sinks [label="sinks\n(overflow)" style=dashed] u_batch -> u_send [label="converged\nsamples" style=bold] u_batch -> u_sinks [label="excess\n(back-pressure)" style=dotted] } subgraph cluster_downstream { label="Rank 1 (downstream)" style=rounded color="#76b900" fontcolor="#eeeeee" d_recv [label="recv_buffer" fillcolor="#4a3315"] d_batch [label="active_batch"] d_sinks [label="sinks\n(results)" style=dashed] d_recv -> d_batch [label="incoming\nsamples" style=bold] d_batch -> d_sinks [label="converged\nresults" style=bold] d_sinks -> d_batch [label="drain when\ncapacity available" style=dotted] } u_send -> d_recv [ label="isend / irecv\n(NCCL)"; style=bold; color="#ee9040"; fontcolor="#eeeeee"; penwidth=2; ] }

Buffer synchronization between two adjacent ranks in a DistributedPipeline.#

A step proceeds as follows:

  1. Pre-step — The downstream rank zeros its receive buffer and posts an asynchronous irecv from its prior_rank. In async_recv mode (the default), the wait is deferred until later in the step; in sync mode it blocks immediately.

  2. Complete receive — The downstream rank waits on the pending receive, then routes incoming samples into its active batch (or overflow sinks if the batch is full).

  3. Step — Both ranks execute their respective integrator or optimizer on their active batches.

  4. Post-step — The upstream rank identifies converged samples, copies them into its send buffer (up to BufferConfig capacity), and issues an isend. An empty buffer is always sent to prevent deadlocks. The final stage routes converged samples to its sinks instead.

Tip

Back-pressure: when the send buffer is full, excess converged samples remain in the upstream active batch as no-ops until buffer capacity opens up. This naturally throttles fast producers without dropping data.

Communication modes#

The comm_mode parameter controls how aggressively communication overlaps with computation:

Mode

Behavior

sync

Blocks on irecv immediately in the pre-step. Simplest to debug.

async_recv (default)

Posts irecv early, waits only when the data is needed. Overlaps receive with computation.

fully_async

Also defers isend completion to the next step’s pre-step. Maximum overlap, highest throughput.

Launching#

Distributed pipelines are launched with torchrun (or any torch.distributed launcher):

torchrun --nproc_per_node=2 my_pipeline.py

DistributedPipeline calls init_distributed() on entry and coordinates termination across ranks via an all_reduce on per-rank done flags.

See also

The Distributed Examples gallery contains end-to-end examples, including multi-pipeline topologies and monitoring with persistent storage.

Structure sources#

A run that graduates structures needs fresh ones to take their place, and a run that starts many trajectories needs them dealt out once. OrderedStructureSampler is that supply: a dataset served in row order from one position, next_row. The initial batch, and every later backfill (the structures drawn to replace the ones that finished) read from that position. A structure is therefore propagated once per pass over the rows, and a sampler restored from its state_dict() (next_row, wraps, next_system_id, rank, and world_size) picks up where it stopped rather than at row zero. shard() resets the position, so a caller that re-shards at start-up, as the distillation segment loop does, begins at the first row of the shard unless it restores the state afterwards.

An unbudgeted sampler serves every row it owns as one batch, so that batch is the set of systems the run generates from. A budget — max_atoms, max_batch_size, or max_edges — packs the initial batch first-fit in row order instead. Packing stops at the first structure that does not fit and leaves the remainder, in row order, for the backfill. The initial packing and each backfill are one draw() call under a WithinBudget policy: the initial batch with on_miss="stop", and a backfill with on_miss="skip", which passes over a row that does not fit rather than stalling on it. When you drive draw yourself, fits= takes any FitPolicy, a callable over the running atom and edge totals of the batch being drawn. max_edges counts the edges a store saved, not the neighbor list a propagator’s hook rebuilds each step, so set it only when the stored count is the one that matters.

shard() narrows the sampler to the rows one rank owns, dealt strided and unpadded through distributed_shard(): rank r takes every world_size-th row from offset r, so the shards are disjoint and cover the dataset. recycle=True wraps the position to the front of the shard when it reaches the end instead of reporting the sampler exhausted; wraps counts how often that happened, and the system_ids keep climbing across a wrap. One draw reaches every row at most once, so a single call never serves two copies of one structure.

Every batch the sampler hands over is stamped with the bookkeeping an in-flight run maintains: status zeros and consecutive system_ids. A store written by an earlier run, whose exit statuses a propagator would otherwise read as finished, can therefore be propagated again without a manual cleanup pass. Any object satisfying the StructureSource protocol can stand in for the sampler; API Reference lists its members.

What’s next#

  • Optimization and Integrators — FIRE2, NVE, NVT, NPT and their configuration.

  • Reaction Paths and NEB — batched nudged elastic band, using either the high-level NEB strategy or hooks attached directly to an optimizer.

  • Hooks — the hook protocol, built-in hooks, and writing custom hooks.

  • Data Sinks — recording trajectories and simulation results.

See also#

  • Examples: basic/02_geometry_optimization.py demonstrates a complete relaxation workflow.

  • API: See the nvalchemi.dynamics module for the full reference, including the hook protocol and distributed pipeline documentation.

  • Data guide: The AtomicData and Batch guide covers the input data structures consumed by dynamics.