Source code for nvalchemi.dynamics.base

# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Base classes and protocols for molecular dynamics simulations.

This module provides the foundational abstractions for running dynamics
simulations, including hook protocols for extensibility, the base
dynamics class that coordinates model evaluation with integrator updates,
and the ``FusedStage`` class for fusing multiple dynamics stages on a
single GPU with shared batch and forward pass.

Inheritance structure:

.. graphviz::

   digraph dynamics_inheritance {
       rankdir=BT
       fontname="Helvetica"
       node [fontname="Helvetica" fontsize=11 shape=box style="rounded,filled" fillcolor="#dce6f1"]
       edge [fontname="Helvetica" fontsize=10]

       object [label="object" fillcolor="#eeeeee"]
       comm   [label="_CommunicationMixin\n(inter-rank communication)"]
       base   [label="BaseDynamics"]
       fused  [label="FusedStage"]

       comm  -> object [style=bold]
       base  -> comm   [style=bold]
       fused -> base   [style=bold]
   }

``BaseDynamics`` inherits from ``_CommunicationMixin``, so all dynamics
subclasses automatically have communication capabilities for pipeline
execution without needing explicit multiple inheritance.
"""

from __future__ import annotations

import sys
import warnings
from collections import OrderedDict
from collections.abc import Callable, Iterator, Mapping, Sequence
from contextlib import ExitStack, contextmanager, nullcontext
from enum import Enum
from typing import (
    TYPE_CHECKING,
    Annotated,
    Any,
    ClassVar,
    Literal,
    TypeAlias,
)

import torch
import warp as wp
from jaxtyping import Bool
from loguru import logger
from pydantic import BaseModel, ConfigDict, Field
from torch import distributed as dist

from nvalchemi._typing import AtomsLike, ModelOutputs
from nvalchemi.data import Batch
from nvalchemi.data.level_storage import SegmentedLevelStorage
from nvalchemi.hooks._context import DynamicsContext
from nvalchemi.hooks._protocol import Hook
from nvalchemi.hooks._registry import HookRegistryMixin
from nvalchemi.models.base import BaseModelMixin

if TYPE_CHECKING:
    from nvalchemi.dynamics.sampler import SizeAwareSampler
    from nvalchemi.dynamics.sinks import DataSink


__all__ = [
    "Hook",
    "DynamicsStage",
    "ConvergenceHook",
    "DistributedPipeline",
    "BufferConfig",
    "requires_grad_ctx",
]


@contextmanager
def requires_grad_ctx(
    *tensors: torch.Tensor,
    requires_grad: bool = True,
) -> Iterator[None]:
    """Temporarily set ``requires_grad`` on leaf tensors.

    Tensor states are restored on exit, including when an exception is raised.
    Duplicate tensor arguments are handled once, so nested or aliased inputs
    preserve the state observed when this context was entered.

    Parameters
    ----------
    *tensors : torch.Tensor
        Leaf tensors whose autograd state should be changed temporarily.
    requires_grad : bool, optional
        State to apply inside the context. Default is ``True``.

    Yields
    ------
    None
        Control while the requested autograd state is active.

    Raises
    ------
    TypeError
        If an argument is not a tensor.
    ValueError
        If a tensor is not a leaf, or if gradients are requested for a tensor
        that is neither floating-point nor complex.
    """
    unique: list[torch.Tensor] = []
    seen: set[int] = set()
    # perform some intial validation of the data
    for tensor in tensors:
        if not isinstance(tensor, torch.Tensor):
            raise TypeError(f"Expected a tensor, got {type(tensor).__name__}")
        if not tensor.is_leaf:
            raise ValueError("requires_grad_ctx requires leaf tensors")
        if requires_grad and not (tensor.is_floating_point() or tensor.is_complex()):
            raise ValueError(
                "requires_grad=True requires floating-point or complex tensors"
            )
        if id(tensor) not in seen:
            seen.add(id(tensor))
            unique.append(tensor)

    original = [(tensor, tensor.requires_grad) for tensor in unique]
    # set gradient tracking, release control flow back, and when it
    # wraps up, rest to the original tracking state
    try:
        for tensor, state in original:
            if state != requires_grad:
                tensor.requires_grad_(requires_grad)
        yield
    finally:
        for tensor, state in reversed(original):
            if tensor.requires_grad != state:
                tensor.requires_grad_(state)


[docs] class BufferConfig(BaseModel): """Pre-allocated send/receive buffer capacities for pipeline communication. A ``BufferConfig`` declares the maximum size of the ``Batch`` that a distributed dynamics stage may exchange with a neighbouring rank. The three capacities size the flattened graph tensors independently: ``num_systems`` bounds how many graphs fit in the buffer, ``num_nodes`` bounds the combined atom count across those graphs, and ``num_edges`` bounds the combined edge count. Because the buffers are fixed-size, they must be large enough to hold the biggest batch that will ever cross the rank boundary; batches that exceed any capacity cannot be communicated. You supply a ``BufferConfig`` when a stage participates in inter-rank communication, i.e. it is wired into a :class:`DistributedPipeline` with a ``prior_rank`` and/or ``next_rank``. The buffers themselves are created lazily via ``Batch.empty()`` on the first simulation step, once a concrete batch is available to act as a dtype/device template, so only the capacities are needed up front. Set a capacity to ``0`` for a dimension the batch does not carry (for example ``num_edges=0`` when edges are recomputed downstream rather than communicated). With ``num_edges=0`` the buffers leave the edges level out entirely, and arriving graphs have no edges until a neighbor-list hook rebuilds them. Examples -------- Size a buffer for up to four graphs totalling 50 atoms, with no edges sent across the boundary:: from nvalchemi.dynamics.base import BufferConfig buffer_cfg = BufferConfig(num_systems=4, num_nodes=50, num_edges=0) A buffer that also carries edge connectivity:: buffer_cfg = BufferConfig(num_systems=10, num_nodes=500, num_edges=2000) Notes ----- All three fields are constrained to be ``>= 0``. Choose the capacities from the worst-case batch you expect to communicate: undersizing any dimension fails at runtime, while oversizing wastes pre-allocated memory. """ num_systems: Annotated[ int, Field(ge=0, description="Maximum number of graphs the buffer can hold.") ] num_nodes: Annotated[ int, Field(ge=0, description="Total node (atom) capacity across all graphs.") ] num_edges: Annotated[ int, Field(ge=0, description="Total edge capacity across all graphs.") ]
[docs] class DynamicsStage(Enum): """ Enumeration of lifecycle stages where dynamics hooks can fire. Each stage corresponds to a specific point in batch admission or a step, allowing hooks to be triggered before or after key operations. Attributes ---------- ON_ADMISSION : int Fired once when a batch enters the dynamics engine, before the first step. Fired again after a new run or managed batch replacement. BEFORE_STEP : int Fired at the beginning of a step, after any one-time model-output priming. BEFORE_PRE_UPDATE : int Fired before the pre_update (first half of integrator) is called. AFTER_PRE_UPDATE : int Fired after the pre_update completes. BEFORE_COMPUTE : int Fired before the model forward pass (force/energy computation). AFTER_COMPUTE : int Fired after the model forward pass completes. BEFORE_POST_UPDATE : int Fired before the post_update (second half of integrator) is called. AFTER_POST_UPDATE : int Fired after the post_update completes. AFTER_STEP : int Fired at the very end of a step, after all operations. ON_CONVERGE : int Fired when a convergence criterion is met (e.g., for optimizers). ON_GRADUATE : int Fired after ``ON_CONVERGE`` to report the graphs that graduated during this step. A graph graduates on the step its ``status`` reaches ``exit_status``, whether a convergence criterion, a step budget, or another hook changed it, at whichever stage of the step the change was made: the mask compares the status at step start with the status at dispatch. ``ctx.graduated_mask`` marks those graphs. The stage is dispatched on every step on which a hook is registered for it and the batch carries a ``status`` column, regardless of the hook's ``frequency``, because checking the mask first would synchronize with the host. The mask may therefore be all ``False``, so a hook must read it rather than assume a graph graduated. Both :class:`BaseDynamics` and :class:`FusedStage` dispatch it. A :class:`FusedStage` dispatches it on each sub-stage first, for the graphs that sub-stage owned, and then at the fused level. """ ON_ADMISSION = -1 BEFORE_STEP = 0 BEFORE_PRE_UPDATE = 1 AFTER_PRE_UPDATE = 2 BEFORE_COMPUTE = 3 AFTER_COMPUTE = 4 BEFORE_POST_UPDATE = 5 AFTER_POST_UPDATE = 6 AFTER_STEP = 7 ON_CONVERGE = 8 ON_GRADUATE = 9
class _ConvergenceCriterion(BaseModel): r"""A single convergence criterion evaluated against a tensor key on ``Batch``. This is an internal model and should not be instantiated directly by users. Instead, pass ``dict`` mappings to :class:`ConvergenceHook`, which will validate and construct ``_ConvergenceCriterion`` instances automatically. The evaluation pipeline is: 1. Retrieve ``getattr(batch, key)``; raise ``KeyError`` if absent. 2. If ``custom_op`` is provided, delegate entirely to it and return. 3. If the tensor is node-level (its first dimension matches ``batch.num_nodes``), scatter-reduce it to graph-level using ``batch.batch_idx`` as the group index. 4. Otherwise the tensor is assumed to be graph-level and is squeezed to 1-D ``(B,)`` if it has a trailing singleton dimension. 5. If ``reduce_op`` is not ``None``, apply the requested reduction along ``reduce_dims`` **before** step 3/4 (i.e. within each node / graph entry). 6. Compare the resulting ``(B,)`` tensor against ``threshold``. Attributes ---------- key : str Tensor key to measure convergence against (e.g. ``"forces"``). threshold : float Convergence threshold; values :math:`\le` this are considered converged. reduce_dims : int | list[int] Dimension(s) to reduce over when ``reduce_op`` is not ``None``. Defaults to ``-1``. reduce_op : {``"min"``, ``"max"``, ``"norm"``, ``"mean"``, ``"sum"``} or ``None`` Reduction applied to the raw tensor before the graph-level aggregation. ``None`` (default) skips this step and expects the key to already be at graph-level or to be a node-level vector that will be scatter-reduced. custom_op : Callable[[torch.Tensor], Bool[Tensor, " B"]] | None Custom callable that receives the raw tensor and must return a boolean ``(B,)`` mask. When provided, ``reduce_op``, ``reduce_dims``, and ``threshold`` are ignored. """ model_config = ConfigDict(arbitrary_types_allowed=True) key: Annotated[str, Field(description="Tensor key to measure convergence against.")] threshold: Annotated[ float, Field( description="Threshold for convergence; values" " smaller than or equal to `threshold` are considered converged." ), ] reduce_dims: Annotated[ int | list[int], Field(description="Dimension(s) to reduce over.") ] = -1 reduce_op: Annotated[ Literal["min", "max", "norm", "mean", "sum"] | None, Field( description="Operation used to reduce non-scalar criteria." " None skips reductions and expects the key to already be" " graph-level or a node-level vector suitable for" " scatter-reduce." ), ] = None custom_op: Annotated[ Callable[[torch.Tensor], Bool[torch.Tensor, " B"]] | None, # noqa: F722, F821 Field( description="Custom operation that wraps the convergence" " logic and returns a bool tensor indicating which samples" " have converged." ), ] = None def __repr__(self) -> str: """Return a human-readable summary of this criterion.""" if self.custom_op is not None: op_name = getattr(self.custom_op, "__name__", repr(self.custom_op)) return f"_ConvergenceCriterion(key={self.key!r}, custom_op={op_name})" parts = [f"key={self.key!r}", f"threshold={self.threshold}"] if self.reduce_op is not None: parts.append(f"reduce_op={self.reduce_op!r}") parts.append(f"reduce_dims={self.reduce_dims!r}") return f"_ConvergenceCriterion({', '.join(parts)})" def _reduce_within_entry(self, target: torch.Tensor) -> torch.Tensor: """Apply ``reduce_op`` along ``reduce_dims`` within each entry. Parameters ---------- target : torch.Tensor The raw tensor retrieved from the batch. Returns ------- torch.Tensor The reduced tensor. If ``reduce_op`` is ``None``, the input is returned unchanged. """ if self.reduce_op is None: return target match self.reduce_op: case "min": return torch.amin(target, self.reduce_dims) case "max": return torch.amax(target, self.reduce_dims) case "norm": return torch.linalg.vector_norm(target, dim=self.reduce_dims) case "mean": return torch.mean(target, dim=self.reduce_dims) case "sum": return torch.sum(target, dim=self.reduce_dims) # Unreachable because of the Literal type, but satisfies the # type checker and gives a clear error for bad runtime values. raise ValueError(f"Unknown reduce_op: {self.reduce_op!r}") @staticmethod def _scatter_reduce_to_graph( values: torch.Tensor, batch_idx: torch.Tensor, num_graphs: int, ) -> torch.Tensor: """Scatter-reduce a 1-D node-level tensor to graph-level via max. Parameters ---------- values : torch.Tensor 1-D tensor of shape ``(V,)`` with per-node values. batch_idx : torch.Tensor Integer tensor mapping each node to its graph index. num_graphs : int Number of graphs in the batch. Returns ------- torch.Tensor 1-D tensor of shape ``(B,)`` with per-graph reduced values (using ``max`` as the scatter operation). """ out = torch.full( (num_graphs,), float("-inf"), dtype=values.dtype, device=values.device ) out.scatter_reduce_(0, batch_idx, values, reduce="amax", include_self=False) return out def __call__(self, batch: Batch) -> Bool[torch.Tensor, " B"]: # noqa: F722, F821 """Evaluate this criterion against a batch. Parameters ---------- batch : Batch The current batch of atomic data. Returns ------- Bool[Tensor, " B"] Per-sample boolean mask where ``True`` indicates that the sample satisfies this convergence criterion. Raises ------ KeyError If ``self.key`` is not present on ``batch``. """ target: torch.Tensor | None = getattr(batch, self.key, None) if target is None: available = list(batch.model_dump(exclude_none=True)) raise KeyError( "Key for convergence check not found;" f" expected={self.key!r}, available={available}" ) if self.custom_op is not None: return self.custom_op(target) target = self._reduce_within_entry(target) is_node_level = ( target.shape[0] == batch.num_nodes and batch.num_nodes != batch.num_graphs ) if is_node_level: if target.dim() > 1: target = target.view(target.shape[0], -1).amax(dim=-1) reduced = self._scatter_reduce_to_graph( target, batch.batch_idx, batch.num_graphs ) else: reduced = target.squeeze(-1) if target.dim() == 2 else target return reduced <= self.threshold CommMode: TypeAlias = Literal["sync", "async_recv", "fully_async"] class _CommunicationMixin: """Base class providing inter-rank communication and buffer management. ``BaseDynamics`` inherits from this class, so all dynamics subclasses automatically have communication capabilities for pipeline execution. This class manages active batch buffers, overflow sinks, and inter-rank communication for distributed pipeline execution. Parameters ---------- prior_rank : int | None Rank to receive data from. ``None`` marks this stage as the first in its sub-pipeline (no upstream). Defaults to ``-1`` (unset), which tells :meth:`DistributedPipeline.setup` to auto-assign based on stage ordering. Set explicitly to ``None`` or a rank integer to prevent auto-assignment. next_rank : int | None Rank to send graduated samples to. ``None`` marks this stage as the last in its sub-pipeline (no downstream). Defaults to ``-1`` (unset), with the same auto-assignment semantics as ``prior_rank``. sinks : list[DataSink] | None Priority-ordered overflow sinks. active_batch : Batch | None The currently active working batch. max_batch_size : int Maximum samples in the active batch. done : bool Whether this stage has no more work. device_type : str Device type string (e.g., ``"cuda"``, ``"cpu"``). comm_mode : CommMode Communication mode for inter-rank buffer synchronization. One of ``"sync"``, ``"async_recv"``, or ``"fully_async"``. Default ``"sync"``. buffer_config : BufferConfig Pre-allocation capacities for send/recv communication buffers. **Required** when ``prior_rank`` or ``next_rank`` is set to a valid rank. A ``ValueError`` is raised at construction if omitted for a stage that has neighbors. **kwargs Forwarded to the next class in the MRO (cooperative init). Attributes ---------- prior_rank : int | None Rank of the previous pipeline stage. ``-1`` means unset (will be auto-assigned by :meth:`DistributedPipeline.setup`), ``None`` means no upstream, and a non-negative integer is the explicit source rank. next_rank : int | None Rank of the next pipeline stage, with the same conventions as ``prior_rank``. sinks : list[DataSink] Overflow sinks in priority order. active_batch : Batch | None Current working batch. max_batch_size : int Maximum active batch capacity. done : bool Whether this stage is finished. sampler : SizeAwareSampler | None Size-aware sampler for inflight batching, or ``None`` for external batch handling (i.e. the typical looping over dataloader approach). Defaults to ``None``. refill_frequency : int How often to check and refill graduated samples from the sampler; no-op if ``sampler`` is not provided. device_type : str Device type string (e.g., ``"cuda"``, ``"cpu"``). comm_mode : CommMode Communication mode for inter-rank buffer synchronization. buffer_config : BufferConfig | None Buffer capacities, or ``None`` for isolated stages. _pending_recv_handle : Any Stored ``irecv`` handle when receive is deferred (non-sync modes). ``None`` when no receive is pending. _pending_send_handle : Any Stored ``isend`` handle when send is deferred (``"fully_async"``). ``None`` when no send is pending. _stream : torch.cuda.Stream | None The torch CUDA stream created when entering the context manager (see :attr:`torch_stream`). ``None`` when outside a ``with`` block or on non-CUDA devices. _wp_stream : wp.Stream | None The warp view of ``_stream`` (see :attr:`warp_stream`). ``None`` when outside a ``with`` block or on non-CUDA devices. _stream_ctx : contextlib.ExitStack | None The active joint stream context entering ``_stream`` on both the torch and warp sides (see :attr:`stream`). ``None`` when outside a ``with`` block or on non-CUDA devices. Examples -------- >>> from nvalchemi.dynamics.base import BaseDynamics, BufferConfig >>> cfg = BufferConfig(num_systems=10, num_nodes=500, num_edges=2000) >>> dyn = BaseDynamics(model=model, prior_rank=0, buffer_config=cfg, max_batch_size=50) >>> dyn.is_first_stage False """ def __init__( self, *, prior_rank: int | None = -1, next_rank: int | None = -1, sinks: Sequence[DataSink] | None = None, active_batch: Batch | None = None, max_batch_size: int = 100, done: bool = False, sampler: SizeAwareSampler | None = None, refill_frequency: int = 1, device_type: str | None = None, comm_mode: CommMode = "async_recv", buffer_config: BufferConfig | None = None, debug_mode: bool = False, **kwargs: Any, ) -> None: """Initialize the communication mixin. Parameters ---------- prior_rank : int | None, optional Rank to receive data from (previous stage). Default None. next_rank : int | None, optional Rank to send graduated samples to (next stage). Default None. sinks : Sequence[DataSink] | None, optional Priority-ordered overflow sinks. Default None (empty list). active_batch : Batch | None, optional The currently active working batch. Default None. max_batch_size : int, optional Maximum samples in the active batch. Default 100. done : bool, optional Whether this stage has no more work. Default False. sampler : SizeAwareSampler | None, optional Size-aware sampler for inflight batching. When provided, enables inflight batching where graduated (converged/finished) samples are automatically replaced with fresh ones from the dataset. Default ``None``, which expects batches to come from dataloaders. refill_frequency : int, optional How often (in steps) to check for graduated samples and request replacements from the sampler. Only used when ``sampler`` is not None. Default 1. device_type : str, optional Device type string (e.g., ``"cuda"``, ``"cpu"``). Defaults to ``None``, which will perform auto placement. comm_mode : CommMode, optional Communication mode controlling blocking behavior of inter-rank buffer synchronization. ``"sync"`` (default) blocks on receive immediately. ``"async_recv"`` defers the receive wait until ``_complete_pending_recv`` is called. ``"fully_async"`` additionally stores the send handle and drains it at the start of the next ``_prestep_sync_buffers`` call. buffer_config : BufferConfig | None, optional Pre-allocation capacities for send/recv buffers. Buffers are created lazily via ``Batch.empty()`` on the first step using the first concrete batch as a template. **Required** when ``prior_rank`` or ``next_rank`` is a valid rank; raises ``ValueError`` otherwise. Default ``None`` (only valid for isolated stages with no neighbors). debug_mode : bool, optional When ``True``, emit detailed ``loguru.debug`` diagnostics for inter-rank communication. Default ``False``. **kwargs : Any Forwarded to the next class in the MRO (cooperative init). """ super().__init__(**kwargs) self.prior_rank = prior_rank self.next_rank = next_rank self.sinks: list[DataSink] = list(sinks) if sinks is not None else [] self.active_batch = active_batch self.max_batch_size = max_batch_size self.done = done self.sampler = sampler self.refill_frequency = refill_frequency self._admission_initialized: bool = False self._forces_primed: bool = False # Host-side mirror of ``reprime_pending.any()`` after refill or admission. self._refill_pending: bool = False if not device_type: device_type = "cuda" if torch.cuda.is_available() else "cpu" self.device_type = device_type if comm_mode not in ("sync", "async_recv", "fully_async"): raise ValueError( f"Invalid comm_mode={comm_mode!r}. " f"Expected one of: 'sync', 'async_recv', 'fully_async'." ) self.comm_mode: CommMode = comm_mode self._pending_recv_handle: Any = None self._pending_send_handle: Any = None self._stream: torch.cuda.Stream | None = None self._wp_stream: wp.Stream | None = None self._stream_ctx: ExitStack | None = None # warp wrappers cached per torch stream: re-wrapping the same CUDA # stream makes a new warp Stream object and invalidates graph capture. self._wp_stream_cache: dict[int, wp.Stream] = {} if isinstance(buffer_config, dict): buffer_config = BufferConfig(**buffer_config) if buffer_config is not None and not isinstance(buffer_config, BufferConfig): raise TypeError( f"Buffer configuration invalid; got a {type(buffer_config)} object." ) self.buffer_config = buffer_config if self.has_neighbor and self.buffer_config is None: raise ValueError( "buffer_config is required when prior_rank or next_rank is set. " "Pre-allocated buffers are mandatory for inter-rank communication." ) self.send_buffer: Batch | None = None self.recv_buffer: Batch | None = None self._recv_template: Batch | None = None self.debug_mode = debug_mode @property def has_neighbor(self) -> bool: """Convenient property to see if rank is isolated""" next_rank = self.next_rank is not None and self.next_rank != -1 prior_rank = self.prior_rank is not None and self.prior_rank != -1 return next_rank or prior_rank def _ensure_buffers(self, template: Batch) -> None: """Lazily create send/recv buffers from the first concrete batch. Called automatically at the start of the first communication step when ``buffer_config`` is set. Uses *template* (the first real batch) to determine attribute keys, dtypes, and trailing shapes for ``Batch.empty()``. Parameters ---------- template : Batch A concrete batch to use as a template for buffer creation. """ if self.buffer_config is None: return cfg = self.buffer_config need_send = self.send_buffer is None and self.next_rank is not None need_recv = self.recv_buffer is None and self.prior_rank is not None if not (need_send or need_recv): return template = self._transport_template(template) if need_send: self.send_buffer = Batch.empty( num_systems=cfg.num_systems, num_nodes=cfg.num_nodes, num_edges=cfg.num_edges, template=template, device=self.device, ) if need_recv: self.recv_buffer = Batch.empty( num_systems=cfg.num_systems, num_nodes=cfg.num_nodes, num_edges=cfg.num_edges, template=template, device=self.device, ) def _transport_template(self, template: Batch) -> Batch: """Return *template* without its edges level when buffers carry no edges. ``BufferConfig(num_edges=0)`` means edges are rebuilt downstream rather than communicated. Both ends of a link must then leave the edges level out entirely: ``Batch.irecv`` expects exactly the levels the sender transmits, and a zero-capacity edges level would reject every graph that has edges. Parameters ---------- template : Batch Batch whose schema defines a buffer or receive layout. Returns ------- Batch *template* itself, or a zero-capacity copy of its schema without the edges level. """ if ( self.buffer_config is None or self.buffer_config.num_edges > 0 or "edges" not in template._storage.groups ): return template # Only field names, dtypes, and trailing shapes matter, so build an # empty schema copy instead of cloning the template's data. stripped = Batch.empty( num_systems=0, num_nodes=0, num_edges=0, template=template, device=template.device, attr_map=template._storage.attr_map, level_capacities={ name: 0 for name, group in template._storage.groups.items() if name not in ("atoms", "edges", "system") and isinstance(group, SegmentedLevelStorage) }, ) stripped.drop_level("edges") return stripped @property def is_final_stage(self) -> bool: """Return whether this is the last stage in the pipeline. Returns ------- bool ``True`` if ``next_rank`` is ``None``. """ return self.next_rank is None @property def is_first_stage(self) -> bool: """Return whether this is the first stage in the pipeline. Returns ------- bool ``True`` if ``prior_rank`` is ``None``. """ return self.prior_rank is None @property def inflight_mode(self) -> bool: """Return whether inflight batching is enabled. Inflight batching is enabled when a sampler is configured. In this mode, graduated samples are automatically replaced with fresh ones from the dataset. Returns ------- bool ``True`` if ``sampler`` is not ``None``. """ return self.sampler is not None @property def local_rank(self) -> int: """Get the node-local rank for this process. Returns ``0`` when ``torch.distributed`` is not initialized. Returns ------- int The local rank on this node. """ if dist.is_initialized(): # ``fallback_rank=0`` for single-node / single-device contexts where # ``LOCAL_RANK`` isn't exported (e.g. a bare gloo group): without it # ``get_node_local_rank`` raises. torchrun/multi-GPU set ``LOCAL_RANK`` # so the real local rank is returned there. return dist.get_node_local_rank(fallback_rank=0) return 0 @property def device(self) -> torch.device: """Compute the torch device for this rank. For CUDA-like devices (``"cuda"``, ``"xpu"``, etc.), returns ``torch.device(f"{device_type}:{local_rank}")``. For CPU, returns ``torch.device("cpu")`` because PyTorch CPU devices do not use ordinal indices — all ranks share a single CPU device. Returns ------- torch.device Device for this rank. """ match self.device_type: case "cuda": if not torch.cuda.is_available(): raise RuntimeError( "Requested CUDA device type, but not available to PyTorch." ) return torch.device(f"cuda:{self.local_rank}") case "cpu": return torch.device("cpu") case _: try: device = torch.device(f"{self.device_type}:{self.local_rank}") return device except Exception as e: raise RuntimeError( f"Unable to create device={self.device_type}:{self.local_rank}" f" with exception: {e}" ) @property def stream(self) -> ExitStack | None: """Return the active joint torch+warp stream context, if any. The joint context is an :class:`contextlib.ExitStack` that entered the dedicated stream on both the torch side (``torch.cuda.stream``) and the warp side (``wp.ScopedStream``). Use :attr:`torch_stream` / :attr:`warp_stream` for the underlying stream objects. Returns ``None`` when outside a ``with`` block or on non-CUDA devices. Returns ------- contextlib.ExitStack | None The active joint stream context, or ``None``. """ return self._stream_ctx @property def torch_stream(self) -> torch.cuda.Stream | None: """Return the dedicated torch CUDA stream, if any. Returns ------- torch.cuda.Stream | None The stream created by ``__enter__``, or ``None``. """ return self._stream @property def warp_stream(self) -> wp.Stream | None: """Return the warp view of the dedicated CUDA stream, if any. Returns ------- wp.Stream | None The converted warp stream, or ``None``. """ return self._wp_stream @staticmethod def _enter_joint_stream_context( torch_stream: torch.cuda.Stream, warp_stream: wp.Stream ) -> ExitStack: """Enter one CUDA stream jointly on the torch and warp sides. The single mechanism behind both the engine context manager (``__enter__``, dedicated stream) and the per-step scope for bare ``run()`` calls (``_stream_scope``, caller's current stream): both sides of the same stream are entered on an :class:`contextlib.ExitStack`, which the caller later unwinds with one ``__exit__``/``close``. Parameters ---------- torch_stream : torch.cuda.Stream The torch stream to make current. warp_stream : wp.Stream The warp view of the same stream. Returns ------- contextlib.ExitStack The entered joint context. """ stack = ExitStack() stack.enter_context(torch.cuda.stream(torch_stream)) stack.enter_context(wp.ScopedStream(warp_stream)) return stack def __enter__(self) -> _CommunicationMixin: """Enter the stream context manager. On CUDA devices, creates a new ``torch.cuda.Stream`` and enters it jointly on the torch side (``torch.cuda.StreamContext``) and the warp side (``wp.ScopedStream`` over the converted stream), so all subsequent GPU operations — including warp-backed custom ops — execute on the one dedicated stream. The dedicated stream first waits for work already submitted to the caller's current torch stream. When ``_stream`` is pre-set at entry — the convention pipeline sessions use to share their stream — creation is skipped and the pre-set stream is used. On non-CUDA devices this is a no-op. See the **CUDA stream semantics** notes on :class:`BaseDynamics` for how this differs from calling ``run()`` without the context manager. Returns ------- _CommunicationMixin This instance. """ if self.device_type == "cuda" and torch.cuda.is_available(): if self._stream is None: caller_stream = torch.cuda.current_stream(self.device) self._stream = torch.cuda.Stream(device=self.device) self._stream.wait_stream(caller_stream) self._wp_stream = wp.stream_from_torch(self._stream) self._stream_ctx = self._enter_joint_stream_context( self._stream, self._wp_stream ) return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any, ) -> None: """Exit the stream context manager. Exits the warp and torch stream contexts (if entered) and clears the stored stream references. Exiting does **not** synchronize the dedicated stream: enqueue a ``wait_stream``/``synchronize`` before consuming results from a different stream. Parameters ---------- exc_type : type[BaseException] | None Exception type, if any. exc_val : BaseException | None Exception value, if any. exc_tb : Any Exception traceback, if any. """ if self._stream_ctx is not None: self._stream_ctx.__exit__(exc_type, exc_val, exc_tb) self._stream = None self._wp_stream = None self._stream_ctx = None @property def active_batch_size(self) -> int: """Return the number of samples currently in the active batch. Returns ------- int Number of graphs in the active batch, or 0 if no batch. """ if self.active_batch is None: return 0 return self.active_batch.num_graphs or 0 def _stream_scope(self, device: torch.device): """Bind warp launches to the torch stream the step runs on. Inside the engine's context manager the joint torch+warp stream from ``__enter__`` is already active and this is a no-op. Outside it, the current torch stream is converted once (cached) and entered on the warp side only, so warp-backed custom ops stop launching on warp's default per-device stream — which serializes against torch work and invalidates CUDA-graph capture. Parameters ---------- device : torch.device Device the batch lives on. Returns ------- ContextManager The entered joint stream context (see ``_enter_joint_stream_context``), or a null context. """ if device.type != "cuda" or self._stream_ctx is not None: return nullcontext() torch_stream = torch.cuda.current_stream(device) key = torch_stream.cuda_stream wp_stream = self._wp_stream_cache.get(key) if wp_stream is None: wp_stream = wp.stream_from_torch(torch_stream) self._wp_stream_cache[key] = wp_stream return self._enter_joint_stream_context(torch_stream, wp_stream) @property def active_batch_has_room(self) -> bool: """Return whether the active batch can accept more samples. Returns ------- bool ``True`` if the active batch is below ``max_batch_size``. """ return self.active_batch_size < self.max_batch_size @property def room_in_active_batch(self) -> int: """Return the number of additional samples the active batch can hold. Returns ------- int Remaining capacity. """ return max(0, self.max_batch_size - self.active_batch_size) @property def _send_buffer_capacity(self) -> int: """Return the number of additional graphs the send buffer can accept. When ``send_buffer`` is ``None`` (no pre-allocated buffer), returns ``sys.maxsize`` to indicate no capacity constraint—the system sends live batches directly without a fixed-size buffer. Returns ------- int Remaining capacity in the send buffer, or ``sys.maxsize`` when there is no pre-allocated send buffer. """ if self.send_buffer is None: return sys.maxsize return self.send_buffer.system_capacity - self.send_buffer.num_graphs def _buffer_to_batch(self, incoming_batch: Batch) -> None: """Route received data into the active batch or overflow sinks. If the active batch has room, samples are appended directly. Otherwise, excess samples are written to overflow sinks in priority order. Parameters ---------- incoming_batch : Batch Batch of samples received from the prior stage. """ if incoming_batch.num_graphs == 0: return ensure_bookkeeping = getattr(self, "_ensure_bookkeeping_fields", None) if callable(ensure_bookkeeping): ensure_bookkeeping(incoming_batch) n_existing = self.active_batch_size room = self.room_in_active_batch if room <= 0: self._overflow_to_sinks(incoming_batch) return n_incoming = incoming_batch.num_graphs n_admitted = min(room, n_incoming) # index_select copies, which matters because callers such as # _recv_to_batch zero the incoming buffer right after this call. arrivals = incoming_batch.index_select(list(range(n_admitted))) self._admission_initialized = False # Reuse upstream outputs only when this stage has not opted into # reprime and arrivals carry every output it needs. Otherwise this # stage computes them before their first update. reuse_forces = ( not getattr(self, "reprime_on_entry", False) and getattr(self, "_supports_per_graph_priming", False) and all( getattr(self, "_OUTPUT_KEY_TO_BATCH_ATTR", {}).get(key, key) in arrivals for key in getattr(self, "__needs_keys__", set()) | {"forces"} ) ) if n_existing == 0: self.active_batch = arrivals self._forces_primed = reuse_forces else: if callable(ensure_bookkeeping): ensure_bookkeeping(self.active_batch) if arrivals.device != self.active_batch.device: arrivals = arrivals.to(self.active_batch.device) bookkeeping = getattr(self, "_bookkeeping_keys", {}) # Append only fills fields residents carry, so create them first. for key, default_fn in bookkeeping.items(): if key not in self.active_batch: self.active_batch[key] = default_fn( n_existing, self.active_batch.device ) # "fill" keeps resident fields the arrivals lack, such as edges a # BufferConfig(num_edges=0) leaves out, and fills the new rows. self.active_batch.append( arrivals, missing_fields="fill", field_defaults=bookkeeping ) if not reuse_forces: self._prime_arrivals(n_existing) if n_admitted < n_incoming: self._overflow_to_sinks( incoming_batch.index_select(list(range(n_admitted, n_incoming))) ) # Received graphs extend the active-batch layout. Preserve state for # resident graphs and append freshly initialized state for arrivals. sync_state = getattr(self, "_sync_state_to_batch", None) if callable(sync_state): existing_indices = torch.arange( n_existing, dtype=torch.long, device=self.active_batch.device ) sync_state(existing_indices, n_admitted, self.active_batch) def _on_receive(self, incoming: Batch) -> None: """Normalize freshly received samples before they join the active batch. Called on every non-empty batch received from the prior rank. The default is a no-op; subclasses that carry per-sample bookkeeping (e.g. :class:`FusedStage` status codes) override it. Parameters ---------- incoming : Batch Batch received from the prior stage. May be modified in place. """ def _prime_arrivals(self, n_existing: int) -> None: """Initialize forces for graphs admitted after the first *n_existing*. Arrivals skip one update while the next regular compute gives them forces, and residents keep theirs. Without per-graph priming support or primed residents, the whole batch is primed before the next update. Parameters ---------- n_existing : int Number of resident graphs ahead of the arrivals. """ if ( n_existing > 0 and getattr(self, "_supports_per_graph_priming", False) and self._forces_primed ): self.active_batch.reprime_pending.view(-1)[n_existing:] = True self._refill_pending = True else: self._forces_primed = False def _recv_to_batch(self, incoming: Batch) -> None: """Stage incoming data through the recv buffer into the active batch. When ``recv_buffer`` is available, copies *incoming* data into the pre-allocated receive buffer via :meth:`Batch.put`, then routes the buffer contents into the active batch via :meth:`_buffer_to_batch`. When ``recv_buffer`` is ``None``, falls back to routing *incoming* directly. Parameters ---------- incoming : Batch Batch received from the prior stage (via ``irecv`` / ``wait``). """ if incoming.num_graphs > 0 and self._recv_template is None: self._recv_template = incoming if incoming.num_graphs > 0: self._on_receive(incoming) if self.recv_buffer is not None and incoming.num_graphs > 0: mask = torch.ones(incoming.num_graphs, dtype=torch.bool, device=self.device) self.recv_buffer.put(incoming, mask=mask) self._buffer_to_batch(self.recv_buffer) self.recv_buffer.zero() else: self._buffer_to_batch(incoming) def _overflow_to_sinks( self, batch: Batch, mask: torch.Tensor | None = None ) -> None: """Write overflow samples to the first sink with available capacity. Parameters ---------- batch : Batch Overflow samples to store. mask : torch.Tensor | None, optional Boolean mask for selective writing. Forwarded to sink.write(). Raises ------ RuntimeError If no sink has capacity for the overflow. """ for sink in self.sinks: if not sink.is_full: sink.write(batch, mask=mask) return raise RuntimeError( f"All sinks are full. Cannot store {batch.num_graphs} overflow samples." ) def _batch_to_buffer(self, mask: torch.Tensor) -> None: """Move graduated samples from the active batch into the send buffer. Uses ``send_buffer.put`` to copy samples where *mask* is ``True`` into the pre-allocated send buffer, then trims the active batch to a new tight :class:`~nvalchemi.data.Batch` without the graduated samples (or *None* if all were graduated). Parameters ---------- mask : torch.Tensor Boolean mask of shape ``(active_batch.num_graphs,)`` where ``True`` marks a graduated (converged) sample. Raises ------ RuntimeError If ``active_batch`` or ``send_buffer`` is ``None``. """ if self.active_batch is None: raise RuntimeError("No active batch to extract from.") if self.send_buffer is None: raise RuntimeError("No send buffer to write to.") previous_batch = self.active_batch remaining_indices = torch.where(~mask)[0] self.send_buffer.put(previous_batch, mask=mask) self.active_batch = previous_batch.trim(copied_mask=mask) self._admission_initialized = False # Graph-indexed metadata and integrator state refer to the old batch # layout. Keep only state for retained graphs and prevent the next hook # context from applying stale convergence indices to the smaller batch. sync_state = getattr(self, "_sync_state_to_batch", None) if callable(sync_state): template = ( self.active_batch if self.active_batch is not None else previous_batch ) sync_state(remaining_indices, 0, template) if hasattr(self, "_last_converged"): self._last_converged = None def _drain_sinks_to_batch(self) -> None: """Pull samples from overflow sinks into the active batch. Iterates through sinks in priority order. For each non-empty sink, drains its contents and routes them into the active batch via :meth:`_buffer_to_batch`. Stops early when the active batch has no more room. If the drained batch is larger than the remaining room, ``_buffer_to_batch`` handles the partial-fit logic (accepts what fits, overflows the rest back to sinks). Notes ----- Called by ``_prestep_sync_buffers`` after processing incoming data from the prior rank, to backfill any remaining capacity with previously overflowed samples. """ for sink in self.sinks: if self.room_in_active_batch <= 0: break if len(sink) == 0: continue overflow = sink.drain() self._buffer_to_batch(overflow) def _prestep_sync_buffers(self) -> None: """Synchronize buffers before a dynamics step. If this stage has a prior rank, zeros the send buffer and receive buffer, then receives data from the prior stage via ``Batch.irecv``. In ``"sync"`` mode the receive completes inline and incoming data is staged through the receive buffer (if present) into the active batch via :meth:`_recv_to_batch`. In ``"async_recv"`` and ``"fully_async"`` modes the receive handle is stored in ``_pending_recv_handle`` and the caller must invoke ``_complete_pending_recv`` before accessing ``active_batch``. In ``"fully_async"`` mode, any pending send handle from the previous iteration is drained (awaited) at the top of this method before posting the new receive. After processing incoming data (or when there is no prior rank), any remaining capacity in the active batch is backfilled from overflow sinks via :meth:`_drain_sinks_to_batch`. Notes ----- This method should be called before ``dynamics.step()`` in the pipeline loop. When using a non-sync ``comm_mode``, call ``_complete_pending_recv`` between this method and ``step()``. """ if self.comm_mode == "fully_async" and self._pending_send_handle is not None: if self.debug_mode: logger.debug("[rank {}] draining pending async send", self.global_rank) self._pending_send_handle.wait() self._pending_send_handle = None if self.prior_rank is not None: if self.send_buffer is not None: self.send_buffer.zero() if self.recv_buffer is not None: self.recv_buffer.zero() if self._recv_template is not None: # Match the sender's send buffer, which omits edges the same way. self._recv_template = self._transport_template(self._recv_template) # Receive with _recv_template, which matches what the sender transmits. # The receive buffer is built from this stage's own batch, so it can hold # bookkeeping fields the sender never sends. template = self._recv_template if self.debug_mode: logger.debug( "[rank {}] posting irecv from rank {} (template={})", self.global_rank, self.prior_rank, template is not None, ) handle = Batch.irecv( src=self.prior_rank, device=self.device, template=template ) if self.comm_mode == "sync": incoming = handle.wait() if self.debug_mode: logger.debug( "[rank {}] sync recv complete, {} graphs from rank {}", self.global_rank, incoming.num_graphs, self.prior_rank, ) self._recv_to_batch(incoming) else: self._pending_recv_handle = handle # In async modes, drain happens in _complete_pending_recv after recv. if self.comm_mode == "sync" or self.prior_rank is None: self._drain_sinks_to_batch() def _complete_pending_recv(self) -> None: """Finalize any deferred receive before compute needs the data. In ``"sync"`` mode this is a no-op because ``_prestep_sync_buffers`` already completed the receive inline. In ``"async_recv"`` and ``"fully_async"`` modes, this method calls ``wait()`` on the stored receive handle and stages the incoming batch through the receive buffer (if present) into the active batch via :meth:`_recv_to_batch`. After processing incoming data, any remaining capacity in the active batch is backfilled from overflow sinks via :meth:`_drain_sinks_to_batch`. Notes ----- Must be called after ``_prestep_sync_buffers`` and before any method that reads ``active_batch`` (e.g., ``step()``). """ if self._pending_recv_handle is not None: if self.debug_mode: logger.debug( "[rank {}] waiting on pending async recv", self.global_rank ) incoming = self._pending_recv_handle.wait() if self.debug_mode: logger.debug( "[rank {}] async recv complete, {} graphs", self.global_rank, incoming.num_graphs, ) self._recv_to_batch(incoming) self._pending_recv_handle = None self._drain_sinks_to_batch() def _manage_send_handle(self, handle: Any) -> None: """Store or wait on a send handle based on communication mode. Parameters ---------- handle The send handle returned by ``Batch.isend``. """ if self.comm_mode == "fully_async": self._pending_send_handle = handle else: handle.wait() def _populate_send_buffer(self, converged_indices: torch.Tensor) -> None: """Populate the send buffer with converged graphs. Creates a boolean mask from the converged indices and copies those graphs into the send buffer. Does NOT send — the caller is responsible for issuing the ``isend``. Parameters ---------- converged_indices : torch.Tensor Integer indices of converged samples (already truncated to capacity). """ mask = torch.zeros( self.active_batch.num_graphs, dtype=torch.bool, device=self.device, ) mask[converged_indices] = True self._batch_to_buffer(mask) if self.debug_mode: logger.debug( "[rank {}] populated send buffer with {} converged graphs", self.global_rank, converged_indices.numel(), ) def _remove_converged_final_stage(self, converged_indices: torch.Tensor) -> None: """Remove converged graphs on the final stage and route to sinks. Extracts converged graphs, removes them from the active batch, and writes them to configured sinks if available. Parameters ---------- converged_indices : torch.Tensor Integer indices of converged samples. """ previous_batch = self.active_batch graduated = previous_batch.index_select(converged_indices) all_indices = set(range(previous_batch.num_graphs)) remaining = sorted(all_indices - set(converged_indices.tolist())) if remaining: self.active_batch = previous_batch.index_select(remaining) else: self.active_batch = None self._admission_initialized = False sync_state = getattr(self, "_sync_state_to_batch", None) if callable(sync_state): remaining_indices = torch.tensor( remaining, dtype=torch.long, device=previous_batch.device ) template = ( self.active_batch if self.active_batch is not None else previous_batch ) sync_state(remaining_indices, 0, template) if hasattr(self, "_last_converged"): self._last_converged = None if self.debug_mode: logger.debug( "[rank {}] final stage, {} converged graphs removed", self.global_rank, converged_indices.numel(), ) if self.sinks: self._overflow_to_sinks(graduated) def _poststep_sync_buffers( self, converged_indices: torch.Tensor | None = None ) -> None: """Synchronize buffers after a dynamics step. If ``converged_indices`` is provided and a next rank exists with available capacity, the converged samples are copied into ``send_buffer`` via :meth:`_populate_send_buffer`. The send buffer is then unconditionally sent to the next rank — even if empty (``num_graphs == 0`` after zeroing) — so the downstream ``irecv`` always completes without deadlock. On the final stage, converged samples are extracted via ``index_select`` and written to the first available sink. Back-pressure behavior ---------------------- Only as many converged samples as fit in the remaining buffer capacity are copied and sent. Excess converged samples remain in the active batch and become no-ops until the next step when buffer capacity may be available. Parameters ---------- converged_indices : torch.Tensor | None, optional Integer indices of converged samples in the active batch. Typically obtained from ``BaseDynamics._check_convergence()``. If ``None``, no samples are graduated. """ if self.next_rank is not None: # The send buffer is reused every iteration. A fully asynchronous # send must finish before its storage is cleared and repopulated. if self._pending_send_handle is not None: self._pending_send_handle.wait() self._pending_send_handle = None self.send_buffer.zero() has_converged = converged_indices is not None and converged_indices.numel() > 0 if has_converged: if self.next_rank is not None: send_capacity = self._send_buffer_capacity if send_capacity > 0: if converged_indices.numel() > send_capacity: converged_indices = converged_indices[:send_capacity] self._populate_send_buffer(converged_indices) if self.is_final_stage: self._remove_converged_final_stage(converged_indices) if self.next_rank is not None: handle = self.send_buffer.isend(dst=self.next_rank) self._manage_send_handle(handle) @property def global_rank(self) -> int: """Get the global rank for this process. Returns ------- int Global rank across all nodes, or 0 if distributed is not initialized. """ rank = 0 if dist.is_initialized(): rank = dist.get_rank() return rank def __or__(self, other: BaseDynamics) -> DistributedPipeline: """Compose two stages into a ``DistributedPipeline`` via ``stage_a | stage_b``. Chaining is supported:: a | b | c → (a | b) | c The first ``|`` creates a two-stage pipeline via this method. Subsequent ``|`` calls hit ``DistributedPipeline.__or__``, which appends stages and re-wires source/sink dependencies. Parameters ---------- other : BaseDynamics The next stage to chain after this one. Returns ------- DistributedPipeline A pipeline containing both stages mapped to sequential ranks. Source/sink dependencies (``prior_rank`` / ``next_rank``) are wired when ``DistributedPipeline.setup()`` is called (e.g. via the context manager or ``run()``). """ if not isinstance(other, _CommunicationMixin): raise TypeError( f"Cannot chain {type(self).__name__} | {type(other).__name__}: " "dynamics | builds a DistributedPipeline of dynamics stages. " "To drive generation into dynamics, compose the other way: " "generator | engine (a GenerationPipeline)." ) return DistributedPipeline(stages={0: self, 1: other}) def __add__(self, other: BaseDynamics) -> FusedStage: """Fuse two dynamics into a ``FusedStage`` via ``dyn_a + dyn_b``. Creates a ``FusedStage`` where both dynamics share a single batch and forward pass. Each dynamics applies masked updates to samples based on their status code. Parameters ---------- other : BaseDynamics The dynamics to fuse with this one. Returns ------- FusedStage A fused stage containing both dynamics with status codes 0 and 1. Raises ------ TypeError If either ``self`` or ``other`` is not a ``BaseDynamics`` instance. Notes ----- **Known limitation — retained composition.** ``self`` and ``other`` become the new ``FusedStage``'s sub-stages by reference, and their ``_enclosing_hooks`` is repointed at that stage's ``hooks``. If you keep ``self`` or ``other`` around and run them standalone afterward, their hook-dependent behavior reads the fused stage's hooks instead of their own — see :meth:`FusedStage.__add__` for the full explanation. Not fixed here; tracked separately. """ # FusedStage is defined later in this file if not isinstance(self, BaseDynamics): raise TypeError( "Both operands of + must be BaseDynamics instances. " f"self is {type(self).__name__}, not BaseDynamics." ) if not isinstance(other, BaseDynamics): raise TypeError( "Both operands of + must be BaseDynamics instances. " f"other is {type(other).__name__}, not BaseDynamics." ) return FusedStage( sub_stages=[(0, self), (1, other)], by_group=self.by_group, ) def _level_mask( state: Batch, level: str, graph_mask: Bool[torch.Tensor, "B"] ) -> torch.Tensor: """Broadcast a per-graph mask to the rows of one materialized state level.""" group = state._storage.groups.get(level) if group is None: raise KeyError(f"state level {level!r} is not materialized") if isinstance(group, SegmentedLevelStorage): return graph_mask[group.batch_idx.long()] return graph_mask
[docs] class BaseDynamics(HookRegistryMixin, _CommunicationMixin): """Base class for all dynamics simulations. This class coordinates a ``BaseModelMixin`` model with a numerical integrator to evolve a ``Batch`` of atomic systems over time. It manages the step loop, hook execution at stage boundaries, and model evaluation. ``BaseDynamics`` inherits from ``HookRegistryMixin`` for hook storage and from ``_CommunicationMixin`` for 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 calls ``step()`` for ``n_steps`` iterations and is the only method most users need. ``n_steps`` can be set at construction time or passed to ``run()``. ``step(batch)`` executes a single simulation step, orchestrating the full hook-wrapped sequence ``pre_update → compute → post_update``, with hooks fired at each stage boundary, followed by convergence checking. Subclasses should generally NOT override ``step``. ``compute(batch)`` performs the model forward pass: it calls ``model(batch)`` which must return a fully adapted ``ModelOutputs`` dict, validates outputs against ``__needs_keys__``, and writes results (forces, energies, stresses) back to the batch in-place. Subclasses should generally NOT override ``compute``. Attributes ---------- model : BaseModelMixin The neural network potential model. step_count : int The current step number, starting from 0. hooks : list[Hook] Flat list of registered hooks. model_is_conservative : bool Indicates that the model uses automatic differentiation to obtain forces. convergence_hook : ConvergenceHook Hook that evaluates composable convergence criteria. Defaults to a single forces-based criterion with threshold ``0.05``. n_steps : int | None Total number of simulation steps for ``run()``. ``None`` means the step count must be supplied when calling ``run()``. exit_status : int Status code threshold for graduated samples. Samples with ``status >= exit_status`` are treated as no-ops during ``step()`` — their positions and velocities are preserved through the integrator. Default is 1. by_group : bool Whether dynamics update units are graph groups rather than individual graphs. Grouped batches must provide a valid group layout. reprime_on_entry : bool Whether graphs entering from another stage get forces from this dynamics before their first update instead of reusing carried forces. samples_equilibrium : ClassVar[bool] 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. ``True`` here and on the integrators; ``False`` on the relaxation optimizers, which descend. A distribution-matching objective reads it to tell the two apart. __needs_keys__ : set[str] 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. __provides_keys__ : set[str] 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. 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)`` and ``post_update(batch)`` to implement the integration scheme. These are called around ``compute()`` — ``pre_update`` before, ``post_update`` after. For example, Velocity Verlet updates positions in ``pre_update`` and velocities in ``post_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. ``FusedStage`` applies masked ``pre_update`` calls before one shared ``compute`` call and masked ``post_update`` calls afterward. Models must be ``BaseModelMixin`` instances — plain ``nn.Module`` is not accepted. Examples -------- >>> model = MyPotentialModel() >>> dynamics = BaseDynamics(model, n_steps=1000) >>> dynamics.run(batch) """ _stage_type = DynamicsStage __needs_keys__: set[str] = set() __provides_keys__: set[str] = set() samples_equilibrium: ClassVar[bool] = True _mutable_fields: tuple[str, ...] = ("positions", "velocities", "cell") # Hooks of the enclosing FusedStage, if any; set (live) by FusedStage. _enclosing_hooks: Sequence[Hook] = () #: Set ``True`` on a subclass whose ``post_update`` is unconditionally a #: no-op (reads nothing, writes nothing) to let #: :meth:`_masked_post_update` skip its save/blend-back of every mutable #: field and state tensor — work whose only purpose is undoing changes #: ``post_update`` never makes. A subclass that sets this to ``True`` #: while giving ``post_update`` a real body silently applies that body #: to every graph instead of only the masked ones; the flag is a #: correctness promise, not something inferred automatically. _post_update_is_noop: bool = False # Engines with a separate step implementation can retain whole-batch priming. _supports_per_graph_priming: bool = True _bookkeeping_keys: dict[str, Callable[[int, torch.device], torch.Tensor]] = { "status": lambda n, dev: torch.zeros(n, 1, dtype=torch.long, device=dev), "reprime_pending": lambda n, dev: torch.zeros( n, 1, dtype=torch.bool, device=dev ), "system_id": lambda n, dev: torch.full( (n, 1), -1, dtype=torch.long, device=dev ), } @staticmethod def _validate_n_steps(n_steps: int | None) -> None: """Validate that a step count is a positive integer or None.""" if n_steps is not None and ( not isinstance(n_steps, int) or isinstance(n_steps, bool) ): raise TypeError("n_steps must be an integer or None.") if n_steps is not None and n_steps < 1: raise ValueError("n_steps must be positive.")
[docs] @classmethod def register_bookkeeping_key( cls, key: str, init_fn: Callable[[int, torch.device], torch.Tensor], ) -> None: """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. """ cls._bookkeeping_keys = {**cls._bookkeeping_keys, key: init_fn}
def __init__( self, model: BaseModelMixin, hooks: list[Hook] | None = None, convergence_hook: Any = None, n_steps: int | None = None, exit_status: int = 1, by_group: bool = False, reprime_on_entry: bool = False, **kwargs: Any, ) -> None: """ Initialize the dynamics engine. Parameters ---------- model : BaseModelMixin The neural network potential model. hooks : list[Hook] | None, optional Initial list of hooks to register. Each hook will be organized by its `stage` attribute. convergence_hook : ConvergenceHook | dict | None, optional Hook that evaluates composable convergence criteria. n_steps : int | None, optional Total number of simulation steps. If provided, ``run()`` will use this value when called without an explicit ``n_steps`` argument. Default is ``None``. If a dict is provided, it is unpacked as ``ConvergenceHook(**convergence_hook)``. If ``None``, no convergence will be assessed. exit_status : int, optional Status code threshold for graduated samples. Samples with ``status >= exit_status`` are treated as no-ops during ``step()`` — their positions and velocities are preserved through the integrator. Default is 1. Subclasses like ``FusedStage`` may compute this dynamically. by_group : bool, optional Whether graph groups are treated as dynamics update units. Requires a valid group layout. Default is False. reprime_on_entry : bool, optional If ``True``, graphs entering this dynamics from another stage get forces from its own model and hooks before their first update, instead of reusing the forces they carry. Applies when this dynamics is a ``DistributedPipeline`` stage receiving from the previous rank, or a ``FusedStage`` sub-stage that graphs enter by status change. Has no effect on a standalone run, where initial and refilled graphs are always primed locally. Default ``False``. **kwargs : Any Additional keyword arguments forwarded to the next class in the MRO (for cooperative multiple inheritance). """ self._validate_n_steps(n_steps) if not isinstance(reprime_on_entry, bool): raise TypeError("reprime_on_entry must be a bool.") super().__init__(**kwargs) self.by_group = by_group self.reprime_on_entry = reprime_on_entry if self.by_group and self.sampler is not None: raise NotImplementedError( "Sampling and refill are not implemented for by_group=True." ) if not isinstance(model, BaseModelMixin): raise TypeError( f"Expected a `BaseModelMixin` instance, got {type(model).__name__}." " Please wrap your model with a `BaseModelMixin` subclass." ) self.model = model self.step_count: int = 0 if isinstance(convergence_hook, dict): convergence_hook = ConvergenceHook(**convergence_hook) if callable(getattr(convergence_hook, "on_register", None)): convergence_hook.on_register(self) self.convergence_hook = convergence_hook self.n_steps = n_steps self.exit_status = exit_status self.model_config = model.model_config self.current_hook_stage: DynamicsStage | None = None self._init_hooks(hooks) self._last_converged: torch.Tensor | None = None @property def model_is_conservative(self) -> bool: """Returns whether or not the model uses conservative forces.""" return "forces" in self.model_config.autograd_outputs def __repr__(self) -> str: """Return a human-readable summary of the dynamics engine.""" cls = type(self).__name__ model_cls = type(self.model).__name__ conservative = self.model_is_conservative n_hooks = len(self.hooks) return ( f"{cls}(" f"model={model_cls}, " f"n_steps={self.n_steps}, " f"step_count={self.step_count}, " f"conservative={conservative}, " f"by_group={self.by_group}, " f"convergence_hook={self.convergence_hook!r}, " f"hooks={n_hooks})" )
[docs] @staticmethod def active_graph_mask( batch: Batch, exit_status: int ) -> Bool[torch.Tensor, " G"] | None: # noqa: F722, F821 """Return the active graphs of *batch*, read from its current ``status``. A graph is active while its ``status`` is below *exit_status*; the integrator treats every other graph as a no-op. This method reads the ``status`` column as it is at the time of the call. ``ctx.active_graph_mask`` differs: 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 a :class:`ConvergenceHook`, sees the change in this method's result but not in ``ctx.active_graph_mask``. Parameters ---------- batch : Batch Batch whose ``status`` column is read. An inflight batch may keep rows beyond the graphs it holds, so only the first ``num_graphs`` rows are read. exit_status : int Status at which a graph stops being active, usually the engine's ``exit_status``. Returns ------- Bool[torch.Tensor, " G"] | None ``True`` where ``status < exit_status``, or ``None`` when *batch* carries no ``status`` column. """ status = getattr(batch, "status", None) if status is None: return None status = status.squeeze(-1) if status.dim() == 2 else status return status[: batch.num_graphs] < exit_status
def _call_hooks( self, stage: DynamicsStage, batch: Batch, active_graph_mask: torch.Tensor | None = None, *, ignore_frequency: bool = False, graduated_mask: torch.Tensor | None = None, ) -> None: """Execute hooks for the given stage with dynamics-specific tracking.""" self.current_hook_stage = stage super()._call_hooks( stage, batch, ignore_frequency=ignore_frequency, active_graph_mask=active_graph_mask, graduated_mask=graduated_mask, ) def _ensure_admission_initialized(self, batch: Batch) -> None: """Dispatch admission hooks once until admission is reset. Admission is deliberately kept outside the per-step sequence so validation, shape-dependent allocation, and hook-owned Python state do not enter a compiled steady-state step. Controlled batch replacement approaches can reset admission explicitly. """ if self._admission_initialized: return self._call_hooks( DynamicsStage.ON_ADMISSION, batch, self.active_graph_mask(batch, self.exit_status), ignore_frequency=True, ) self._admission_initialized = True def _build_context( self, batch: Batch, *, active_graph_mask: torch.Tensor | None = None, graduated_mask: torch.Tensor | None = None, ) -> DynamicsContext: """Build a dynamics-specific hook context.""" if self._last_converged is None: _mask = None elif self._last_converged.dtype == torch.bool: # Fused path stores a mask: index extraction breaks the graph. _mask = self._last_converged else: _mask = torch.zeros( batch.num_graphs, dtype=torch.bool, device=batch.positions.device ) _mask[self._last_converged] = True return DynamicsContext( batch=batch, step_count=self.step_count, model=self.model, active_graph_mask=active_graph_mask, converged_mask=_mask, graduated_mask=graduated_mask, global_rank=self.global_rank, workflow=self, ) def _open_hooks(self) -> None: """Enter context-manager hooks registered on this stage. Calls ``__enter__`` on every hook that supports the context-manager protocol. A ``seen`` set prevents double-entering hooks. Called automatically at the start of :meth:`run`. """ seen: set[int] = set() for hook in self.hooks: hook_id = id(hook) if hook_id not in seen and hasattr(hook, "__enter__"): seen.add(hook_id) hook.__enter__() def _close_hooks(self) -> None: """Exit context-manager hooks, falling back to ``close()`` otherwise. For hooks that support the context-manager protocol, calls ``__exit__(None, None, None)``. For hooks that only expose a ``close()`` method (e.g. ``TorchProfilerHook``), calls ``close()`` directly. A ``seen`` set prevents double-closing hooks. Called automatically at the end of :meth:`run`. """ seen: set[int] = set() for hook in self.hooks: hook_id = id(hook) if hook_id in seen: continue seen.add(hook_id) if hasattr(hook, "__exit__"): hook.__exit__(None, None, None) elif hasattr(hook, "close"): hook.close() def _check_convergence(self, batch: Batch) -> torch.Tensor | None: """Return indices of converged samples, or None if none converged. Delegates to ``self.convergence_hook.evaluate(batch)`` if a convergence hook is configured. Parameters ---------- batch : Batch The current batch of atomic data. Returns ------- torch.Tensor | None Integer tensor of converged sample indices, or ``None``. """ if self.convergence_hook is None: return None return self.convergence_hook.evaluate(batch) def _validate_model_outputs(self, outputs: ModelOutputs) -> None: """Validate that model outputs satisfy the dynamics requirements. Iterates over ``__needs_keys__`` and checks that each declared key is present and not ``None`` in the model outputs. Parameters ---------- outputs : ModelOutputs The model outputs to validate. Raises ------ RuntimeError If a required output key is missing or ``None``. """ for key in self.__needs_keys__: if outputs.get(key) is None: raise RuntimeError( f"{type(self).__name__} requires '{key}' " f"(declared in __needs_keys__), but the model did not " f"produce it. Check your model's ModelConfig and " f"ModelConfig to ensure '{key}' is supported and enabled," " or that no hooks are missing." ) def _validate_batch_keys(self, batch: Batch) -> None: """Validate that the batch contains all keys declared in ``__provides_keys__``. This is a diagnostic helper — not wired into the hot path. It can be called after ``step()`` to verify that the dynamics produced the keys it claims to provide. Parameters ---------- batch : Batch The batch to validate. Raises ------ RuntimeError If a declared provides-key is ``None`` on the batch. """ for key in self.__provides_keys__: val = getattr(batch, key, None) if val is None: raise RuntimeError( f"{type(self).__name__} declares '{key}' in " f"__provides_keys__, but batch.{key} is None after " f"compute. This may indicate a misconfigured model or " f"dynamics." )
[docs] def required_input_keys(self) -> frozenset[str]: """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 first ``pre_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 than ``positions``, plus ``atomic_masses`` when those include ``velocities``. Returns ------- frozenset[str] Batch field names an initial batch must carry. """ fields = set(self.__provides_keys__) - {"positions"} if "velocities" in fields: fields.add("atomic_masses") return frozenset(fields)
[docs] def check_initial_batch(self, batch: Batch) -> None: """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 :meth:`required_input_keys`. """ missing = [ key for key in sorted(self.required_input_keys()) if key not in batch ] if not missing: return raise ValueError( f"The initial batch lacks {missing!r}, which {type(self).__name__} " "updates in place from its first step. The model outputs in " f"__needs_keys__={sorted(self.__needs_keys__)!r} are primed before " "that step and need not be present, but every field in " f"__provides_keys__={sorted(self.__provides_keys__)!r} other than " "positions, and atomic_masses alongside velocities, has to arrive on " "the batch. AtomicData fills velocities and atomic_masses in unless " "a store dropped them; a cell has to be carried explicitly, because " "nothing fills one in for an aperiodic structure." )
def _composed_stages(self) -> Iterator[BaseDynamics]: """Yield this dynamics and every stage it composes, each exactly once. A :class:`FusedStage` keeps its integrators in ``sub_stages``, and a composition keyed by rank keeps its stages in a ``stages`` mapping. Stages are compared by identity, so one integrator reached through two sub-stages is yielded once. """ seen: list[BaseDynamics] = [] pending: list[BaseDynamics] = [self] while pending: stage = pending.pop() if any(stage is visited for visited in seen): continue seen.append(stage) yield stage pending.extend(sub for _, sub in getattr(stage, "sub_stages", ())) stages = getattr(stage, "stages", ()) pending.extend(stages.values() if isinstance(stages, Mapping) else stages)
[docs] def bookkeeping_keys(self) -> frozenset[str]: """Return the bookkeeping fields this dynamics and its sub-stages keep on a batch. Every stage carries its class's registry, grown by :meth:`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 ------- frozenset[str] Batch field names that carry propagator bookkeeping, such as ``status`` and ``system_id``, and mean nothing outside the run that wrote them. Examples -------- >>> from nvalchemi.dynamics import BaseDynamics >>> sorted(BaseDynamics(model=model).bookkeeping_keys()) # doctest: +SKIP ['status', 'system_id'] """ keys: set[str] = set() for stage in self._composed_stages(): keys.update(stage._bookkeeping_keys) return frozenset(keys)
[docs] def seed_offset(self, offset: int) -> tuple[str, ...]: """Add *offset* to every ``random_seed`` in this dynamics and its sub-stages. A stochastic integrator such as :class:`~nvalchemi.dynamics.NVTLangevin` exposes its seed as an integer ``random_seed`` property. Every stage reached through :class:`FusedStage` sub-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 ------- tuple[str, ...] Class names of the stages that hold randomness this call could not offset: a stage whose ``random_seed`` has no setter, or one that holds a :class:`torch.Generator` and exposes no integer ``random_seed``. A stage exposing neither is taken as deterministic and is not reported. Examples -------- >>> from nvalchemi.dynamics import NVTLangevin >>> dynamics = NVTLangevin(model, dt=1.0, temperature=300.0, friction=0.01, random_seed=7) # doctest: +SKIP >>> dynamics.seed_offset(1_000) # doctest: +SKIP () >>> dynamics.random_seed # doctest: +SKIP 1007 """ unmoved: list[str] = [] for stage in self._composed_stages(): seed = getattr(stage, "random_seed", None) if isinstance(seed, int) and not isinstance(seed, bool): try: stage.random_seed = seed + offset except AttributeError: unmoved.append(type(stage).__name__) elif any( isinstance(value, torch.Generator) for value in vars(stage).values() ): unmoved.append(type(stage).__name__) return tuple(unmoved)
# ------------------------------------------------------------------ # Per-system integrator state management # ------------------------------------------------------------------ def _num_update_units(self, batch: Batch) -> int: """Return the number of independent dynamics update units.""" if self.by_group: return batch.group_layout.num_groups return batch.num_graphs def _update_idx(self, batch: Batch) -> torch.Tensor: """Return the contiguous per-node int32 update-unit index.""" if self.by_group: return batch.group_layout.node_to_group.to(dtype=torch.int32).contiguous() return batch.batch_idx.to(dtype=torch.int32).contiguous() def _save_state_fields(self) -> dict[str, torch.Tensor]: """Clone all integrator state fields, preserving each field's shape.""" state = getattr(self, "_state", None) if state is None: return {} return {key: value.clone() for key, value in state} def _restore_unmasked_state( self, batch: Batch, saved: dict[str, torch.Tensor], graph_mask: Bool[torch.Tensor, "B"], ) -> None: """Restore inactive update-unit state after a masked fused-stage update. :class:`FusedStage` calls each sub-stage's ``pre_update`` or ``post_update`` on the full batch to preserve static shapes. State changes are retained for update units selected by ``graph_mask``. A grouped state row is retained when at least one graph in its group is selected; other rows are restored from ``saved``. Segmented state levels expand that same (possibly group-reduced) mask through their own ``batch_idx`` — but ``self._state`` need not be a full ``Batch``; the minimal state contract (``num_graphs`` plus iteration, see ``_TestState`` in ``test_state_management.py``) has no levels at all, so a state without ``level_keys`` falls back to one flat mask over every saved field. """ if not saved: return state_mask = ( batch.group_layout.reduce_any(graph_mask) if self.by_group else graph_mask ) if self._state.num_graphs != state_mask.shape[0]: raise RuntimeError( "Integrator state cardinality does not match the dynamics " f"update units: state={self._state.num_graphs}, " f"updates={state_mask.shape[0]}." ) level_keys = getattr(self._state, "level_keys", None) if level_keys is None: for key, previous in saved.items(): value = getattr(self._state, key) mask = state_mask.view(state_mask.shape[0], *([1] * (value.dim() - 1))) torch.where(mask, value, previous, out=value) return for level, keys in level_keys.items(): keys = keys & saved.keys() if not keys: continue level_mask = _level_mask(self._state, level, state_mask) for key in keys: value = getattr(self._state, key) mask = level_mask.view(level_mask.shape[0], *([1] * (value.dim() - 1))) torch.where(mask, value, saved[key], out=value) def _warm_state_levels(self) -> None: """Build lazy segmented-level topology outside a compiled step. No-op for a state without ``_storage`` — the minimal state contract (``num_graphs`` plus iteration) has no levels to warm. """ state = getattr(self, "_state", None) storage = getattr(state, "_storage", None) if storage is None: return for group in storage.groups.values(): if isinstance(group, SegmentedLevelStorage): _ = group.batch_idx, group.batch_ptr def _init_state(self, batch: Batch) -> None: """Allocate per-system integrator state from the first concrete batch. No-op in the base class. Subclasses that require per-system state (e.g. all warp-kernel integrators) override this to build a system-only :class:`~nvalchemi.data.Batch` and assign it to ``self._state``. Parameters ---------- batch : Batch The first concrete batch; used to determine M, device, and dtype. """ def _make_new_state(self, n: int, template_batch: Batch) -> "Batch | None": """Return default state for *n* newly admitted systems. No-op in the base class (returns ``None``). Subclasses override to produce a system-only :class:`~nvalchemi.data.Batch` with default/reset state for *n* replacement systems. Parameters ---------- n : int Number of new systems to create state for. template_batch : Batch The updated active batch; provides device and dtype. Returns ------- Batch | None A system-only batch with *n* rows, or ``None`` if this dynamics does not maintain per-system state. """ return None
[docs] def state_dict(self) -> dict[str, Any]: """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 ------- dict[str, Any] ``step_count``, ``random_seed`` (when the integrator has one), and a ``state`` submapping of per-system tensors. ``state`` is empty for an integrator that keeps none, and for one whose lazy initialisation has not run yet. Notes ----- Reproducibility of stochastic integrators ``NVTLangevin`` derives its noise from ``random_seed + step_count`` rather than advancing a stateful generator, so restoring those two integers reproduces the identical noise sequence. There is no generator object to serialise. """ state: dict[str, torch.Tensor] = {} internal = getattr(self, "_state", None) if internal is not None: # Batch yields (name, value) pairs from __iter__; it has no .items(). for key, value in internal: if isinstance(value, torch.Tensor): state[key] = value.detach().clone() out: dict[str, Any] = { "step_count": int(self.step_count), "state": state, } seed = getattr(self, "_random_seed", None) if seed is not None: out["random_seed"] = int(seed) return out
[docs] def load_state_dict(self, state: Mapping[str, Any]) -> None: """Restore integrator state produced by :meth:`state_dict`. Parameters ---------- state: The mapping previously returned by :meth:`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. """ self.step_count = int(state.get("step_count", 0)) if "random_seed" in state and hasattr(self, "_random_seed"): self._random_seed = int(state["random_seed"]) saved: Mapping[str, torch.Tensor] = state.get("state", {}) or {} if not saved: return internal = getattr(self, "_state", None) if internal is None: raise RuntimeError( f"{type(self).__name__}.load_state_dict: the checkpoint holds " f"per-system integrator state ({sorted(saved)}) but this " "instance has not initialised its own yet. Prime the dynamics " "against the restored batch before loading, so the shapes are " "known." ) for key, value in saved.items(): target = getattr(internal, key, None) if target is None: raise KeyError( f"{type(self).__name__}.load_state_dict: checkpoint key " f"{key!r} has no counterpart in the live integrator state " f"({sorted(k for k, _ in internal)}). The " "checkpoint was written by a differently-configured " "integrator." ) with torch.no_grad(): target.copy_(value.reshape(target.shape).to(target.device))
[docs] def redistribute_state(self, walker_ids: torch.Tensor) -> None: """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. """ internal = getattr(self, "_state", None) if internal is None: raise RuntimeError( f"{type(self).__name__}.redistribute_state: no per-system " "state to reorder." ) # Index on the state's own device: ``self.device`` reports the # process compute device, which is CUDA whenever a GPU is visible even # for state that was never moved off the CPU. index = walker_ids.reshape(-1).to(dtype=torch.long) for key, value in list(internal): if isinstance(value, torch.Tensor) and value.shape[0] == index.numel(): internal[key] = value[index.to(value.device)].contiguous()
[docs] def apply_per_system_params( self, params: Mapping[str, torch.Tensor], batch: Batch ) -> None: """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. """ raise NotImplementedError( f"{type(self).__name__} does not support per-system parameter " "rebinding. Methods that permute per-system state across walkers " "require an integrator that can rescale velocities and transform " "its thermostat state; NVTLangevin and NVTNoseHoover implement " "this." )
def _validated_temperature( self, params: Mapping[str, torch.Tensor], reference: torch.Tensor ) -> torch.Tensor: """Check *params* and return the new per-graph temperature in Kelvin. Shared by every integrator whose rebindable parameter set is exactly ``{"temperature"}``, so the two checks cannot drift apart between them. Both run **before** any state is touched, which is what ``apply_per_system_params`` promises: a rebinding it refuses leaves the integrator and the batch as they were, and callers that permute per-system state build their own atomicity on that. Temperature is rejected unless strictly positive and finite. It is not merely out of range — it propagates: * a negative target makes the velocity scale ``sqrt(T_new / T_old)`` imaginary, so velocities come back ``nan``; * zero scales a Nosé-Hoover chain's masses ``Q ∝ kT`` to zero — a massless thermostat — and ``eta_dot ∝ 1/sqrt(kT)`` to infinity; * infinity reaches velocities and chain masses directly. None of those raise on their own. The run continues with ``nan`` coordinates a few steps later, pointing at the integrator rather than at the caller that asked for the temperature. Parameters ---------- params : Mapping[str, torch.Tensor] Parameter name to its new per-graph value. reference : torch.Tensor Existing per-system temperature, for device and dtype. Returns ------- torch.Tensor The new temperature in Kelvin, shape ``[B]``. Raises ------ KeyError If *params* names anything other than ``"temperature"``. ValueError If any temperature is non-positive or not finite. """ name = type(self).__name__ unknown = sorted(set(params) - {"temperature"}) if unknown: raise KeyError( f"{name}.apply_per_system_params: cannot rebind {unknown}; " "this integrator rebinds 'temperature' only. Silently " "ignoring a parameter would leave the walker sampling the " "state it was supposed to leave." ) temperature = ( params["temperature"] .reshape(-1) .to(device=reference.device, dtype=reference.dtype) ) if not bool(temperature.isfinite().all()) or bool((temperature <= 0).any()): raise ValueError( f"{name}.apply_per_system_params: temperature must be " f"positive and finite, got {temperature.tolist()}. A " "non-positive or infinite target does not fail here on its " "own — it makes the velocity rescale imaginary or infinite " "and, for a thermostat chain, its masses zero or infinite, " "so the run continues and surfaces as nan coordinates later." ) return temperature def _rescale_velocities(self, scale_per_graph: torch.Tensor, batch: Batch) -> None: """Scale each graph's velocities by a per-graph factor, in place. Parameters ---------- scale_per_graph : torch.Tensor Multiplicative factor per graph, shape ``[B]``. batch : Batch The live batch; ``velocities`` is modified in place. """ velocities = getattr(batch, "velocities", None) if velocities is None: return with torch.no_grad(): velocities.mul_(scale_per_graph[batch.batch_idx].unsqueeze(-1)) def _autograd_input_tensors( self, batch: Batch | AtomsLike ) -> tuple[torch.Tensor, ...]: """Return tensor inputs that require gradients for model evaluation. Parameters ---------- batch : Batch | AtomsLike Model input containing configured autograd fields. Returns ------- tuple[torch.Tensor, ...] Present tensor fields requiring gradients. Conservative models include ``positions`` even when a wrapper omits it from ``autograd_inputs``. """ cfg = self.model_config grad_keys = set(cfg.gradient_keys) if cfg.autograd_outputs & cfg.active_outputs: grad_keys |= cfg.autograd_inputs grad_keys.add("positions") tensors: list[torch.Tensor] = [] for key in grad_keys: value = getattr(batch, key, None) if isinstance(value, torch.Tensor): tensors.append(value) return tuple(tensors) @contextmanager def _defer_autograd_input_cleanup(self) -> Iterator[None]: """Defer ``compute`` gradient restoration to an outer context.""" previous = getattr(self, "_autograd_cleanup_deferred", False) self._autograd_cleanup_deferred = True try: yield finally: self._autograd_cleanup_deferred = previous def _ensure_state_initialized(self, batch: Batch) -> None: """Lazily initialize per-system integrator state on the first call. Calls :meth:`_init_state` the first time this method is invoked (i.e. when ``self._state`` does not yet exist). Subsequent calls are no-ops. This is invoked automatically at the start of :meth:`step`, :meth:`_masked_pre_update`, and :meth:`_masked_post_update` so that concrete subclasses never need to call it explicitly. Parameters ---------- batch : Batch The current batch; forwarded to ``_init_state`` if needed. """ if self.by_group: _ = batch.group_layout if not hasattr(self, "_state"): self._init_state(batch) def _sync_state_to_batch( self, remaining_indices: "torch.Tensor", n_new: int, template_batch: Batch, ) -> None: """Synchronize ``self._state`` after active-batch membership changes. Called after graduated systems have been removed, with optional replacement systems appended. Removes state rows for graduated systems and appends fresh default state for the new ones. If this dynamics has no ``_state`` (e.g. :class:`DemoDynamics`), this method is a no-op. Parameters ---------- remaining_indices : torch.Tensor Integer indices of systems that remain in the new batch, in order. Used to slice ``self._state`` via ``index_select``. n_new : int Number of newly admitted replacement systems appended after the remaining ones. State for these is produced by :meth:`_make_new_state`. template_batch : Batch The updated batch (remaining + replacements); provides device and dtype for :meth:`_make_new_state`. """ if not hasattr(self, "_state"): return if remaining_indices.numel() > 0: remaining_state: "Batch | None" = self._state.index_select( remaining_indices ) else: remaining_state = None new_state: "Batch | None" = None if n_new > 0: new_state = self._make_new_state(n_new, template_batch) if remaining_state is not None and new_state is not None: remaining_state.append(new_state) self._state = remaining_state elif remaining_state is not None: self._state = remaining_state elif new_state is not None: self._state = new_state else: del self._state def _check_hook_compatibility(self) -> None: """Run-start checks for hooks incompatible with this dynamics' algorithm. No-op in the base class; a subclass overrides this to warn (or raise) when a hook registered on ``self.hooks`` or ``self._enclosing_hooks`` would corrupt its per-step state. Called every step — standalone from :meth:`step`, and per sub-stage from :meth:`FusedStage.step` — rather than once at admission, so hooks registered *after* the first step (directly, or on an enclosing ``FusedStage``) are still caught. Deliberately called from the uncompiled driver, not from :meth:`pre_update`/:meth:`post_update` themselves, which may run inside a compiled ``FusedStage`` step. """
[docs] def pre_update(self, batch: Batch) -> None: """ 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. """ pass
[docs] def post_update(self, batch: Batch) -> None: """ 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. """ pass
# Class-level mapping from model output keys to batch attribute names. # Override in subclasses to handle non-standard batch attribute names. _OUTPUT_KEY_TO_BATCH_ATTR: dict[str, str] = { "energy": "energy", "forces": "forces", "stress": "stress", }
[docs] def compute( self, batch: Batch | AtomsLike, active_graph_mask: Bool[torch.Tensor, "B"] | None = None, ) -> ModelOutputs: """ Perform the model forward pass to compute forces and energies. This method: 1. Runs the model forward pass, which should enable gradients 2. Adapts outputs to the standard format 3. Validates outputs against dynamics requirements 4. Allocates missing output buffers and writes known keys back to the batch via :attr:`_OUTPUT_KEY_TO_BATCH_ATTR` 5. Detaches all output tensors from the computation graph and exposes them as ``_last_outputs`` for custom dynamics subclasses that need charges, embeddings, or other non-standard outputs. 6. Restores the original ``requires_grad`` state 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 call ``model(batch)`` directly instead of ``compute()``. 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 ------- ModelOutputs OrderedDict containing the model outputs (energies, forces, and any other computed properties). All tensors are detached from the computation graph. Raises ------ RuntimeError If the model outputs do not satisfy the dynamics requirements specified by ``__needs_keys__``. """ if getattr(self, "_autograd_cleanup_deferred", False): return self._compute(batch, active_graph_mask) with requires_grad_ctx(*self._autograd_input_tensors(batch)): return self._compute(batch, active_graph_mask)
@staticmethod def _infer_output_group( batch: Batch | AtomsLike, key: str, tensor: torch.Tensor ) -> str: """The level *tensor*'s own length says an unregistered output belongs to. Checks every materialized segmented group (``"atoms"``, ``"edges"``) whose element count matches *tensor*'s leading dimension. A total match alone is not decisive — two groups can have the same total while differing per graph — but it is also not necessarily *ambiguous*: masking only ever applies ``active_graph_mask`` expanded through a group's own per-graph ``segment_lengths``, so two matching groups with identical ``segment_lengths`` would be masked identically regardless of which is picked. Only raise when matching groups disagree on a graph; otherwise prefer ``"atoms"`` (the common case: a per-atom extra output like an energy decomposition) over ``"edges"``. Falls back to ``"system"`` — the same default ``MultiLevelStorage`` uses for a key with no schema entry — when no segmented group matches at all. """ n = tensor.shape[0] candidates = [ group_name for group_name, count in ( ("atoms", batch.num_nodes), ("edges", batch.num_edges), ) if group_name in batch._storage.groups and n == count ] if len(candidates) > 1: lengths = [batch._storage.groups[g].segment_lengths for g in candidates] if any(not torch.equal(lengths[0], length) for length in lengths[1:]): raise RuntimeError( f"Cannot determine the storage level for unregistered " f"model output {key!r} of length {n}: it matches more " f"than one of {candidates} by total element count, and " "their per-graph counts disagree. Register this key's " "level explicitly rather than relying on shape inference." ) return candidates[0] if candidates else "system" def _publish_model_output( self, batch: Batch | AtomsLike, batch_attr: str, target: torch.Tensor, value: torch.Tensor, active_graph_mask: Bool[torch.Tensor, "B"] | None, ) -> None: """Publish one detached model output while preserving inactive rows.""" source = value.view(target.shape).to(dtype=target.dtype) if active_graph_mask is None: target.copy_(source) return group_name = batch._storage._group_name_from_attr(batch_attr) if group_name == "system": output_mask = active_graph_mask elif group_name == "atoms": output_mask = active_graph_mask[batch.batch_idx] elif group_name == "edges": edge_graph_idx = batch.batch_idx[batch.neighbor_list[:, 0]] output_mask = active_graph_mask[edge_graph_idx] else: raise RuntimeError( f"Cannot apply a graph activity mask to model output {batch_attr!r} " f"stored at level {group_name!r}." ) output_mask = output_mask.view( output_mask.shape[0], *([1] * (target.dim() - 1)) ) torch.where(output_mask, source, target, out=target) def _publish_unmapped_outputs( self, batch: Batch | AtomsLike, outputs: ModelOutputs, active_graph_mask: Bool[torch.Tensor, "B"] | None, ) -> None: """Publish every model output *compute* didn't already know how to. Allocating a never-seen key calls :meth:`_infer_output_group`, which branches on tensor *values* (``torch.equal`` on ``segment_lengths``) rather than shapes alone, so it cannot run inside a ``torch.compile(fullgraph=True)`` graph. This must therefore only be reached for keys the batch has already seen once — callers compiling the step (:class:`FusedStage`'s ``_prime_forces``) call it eagerly on the first, uncompiled step so every key is allocated before any compiled call needs to publish it. Allocation goes through :meth:`Batch.add_key` — the same public route model wrappers use for extra outputs (see ``neb_force.py``'s ``set_batch_field``) — rather than a raw storage write, so the key stays visible to schema-driven consumers (e.g. the Zarr writer, which enumerates ``attr_map``) and masked-out rows hold this priming compute's real values instead of uninitialized memory. """ for key, tensor in outputs.items(): if key not in self._OUTPUT_KEY_TO_BATCH_ATTR and tensor is not None: target = getattr(batch, key, None) if target is None: # add_key, not a raw storage write -- see docstring. group_name = self._infer_output_group(batch, key, tensor) if group_name == "system": values = list(tensor.split(1)) else: # Eager-only (see docstring): .tolist() forces a # host sync that would break under torch.compile. counts = batch._storage.groups[ group_name ].segment_lengths.tolist() values = list(tensor.split(counts)) batch.add_key(key, values, level=group_name) target = getattr(batch, key) self._publish_model_output( batch, key, target, tensor, active_graph_mask ) def _compute( self, batch: Batch | AtomsLike, active_graph_mask: Bool[torch.Tensor, "B"] | None = None, ) -> ModelOutputs: """Execute model evaluation while autograd input state is managed.""" self._last_outputs = None # model.forward() is responsible for returning a fully adapted ModelOutputs dict. # adapt_output() must NOT be called again here; each wrapper handles adaptation # internally and returns canonical keys directly from forward(). outputs: ModelOutputs = self.model(batch) self._validate_model_outputs(outputs) # Write known keys to batch via copy_, then detach all tensors from the # computation graph. Models like MACE return energies still attached to # the graph after internal autograd; without detaching, _last_outputs # would keep the entire forward graph alive until the next compute(). detached: ModelOutputs = OrderedDict() for key, value in outputs.items(): if isinstance(value, torch.Tensor): detached[key] = value.detach() else: detached[key] = value # Explicitly break all references to graph-attached tensors before # any further work. Without this, the local `outputs` dict and its # values keep the autograd graph alive for the remainder of compute(). del outputs for out_key, batch_attr in self._OUTPUT_KEY_TO_BATCH_ATTR.items(): value = detached.get(out_key) if value is not None: target = getattr(batch, batch_attr, None) if target is None: # Fresh or refilled batches may contain only model inputs, so # allocate storage for model outputs lazily. setattr(batch, batch_attr, torch.empty_like(value)) target = getattr(batch, batch_attr) self._publish_model_output( batch, batch_attr, target, value, active_graph_mask, ) self._last_outputs = detached return detached
[docs] def step(self, batch: Batch) -> tuple[Batch, torch.Tensor | None]: """ 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 before ``step_count`` advances, and the normal step evaluates it again. Consequently, both compute-hook dispatches receive ``step_count == 0``. Samples with ``status >= exit_status`` are 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 ------- tuple[Batch, torch.Tensor | None] The updated batch after the step, and a 1-D integer tensor of converged sample indices (or ``None`` if nothing converged). """ self._ensure_state_initialized(batch) self._ensure_admission_initialized(batch) self._check_hook_compatibility() # Prepare status-based active-graph filtering for this step. active_graph_mask = self.active_graph_mask(batch, self.exit_status) saved: dict[str, torch.Tensor] = {} if active_graph_mask is not None: node_mask_occupied = torch.repeat_interleave( active_graph_mask, batch.num_nodes_per_graph ) node_mask = torch.zeros( batch.num_nodes, dtype=torch.bool, device=batch.device ) node_mask[: len(node_mask_occupied)] = node_mask_occupied sys_mask = ~active_graph_mask for field in self._mutable_fields: val = getattr(batch, field, None) if val is None: continue if val.shape[0] == batch.num_nodes: saved[field] = val[~node_mask].clone() elif val.shape[0] == batch.num_graphs: saved[field] = val[sys_mask].clone() # Prime once before the hook-wrapped step so the optimizer's first # pre_update sees the same valid forces/stress as subsequent steps. if not self._forces_primed: self._prime_forces(batch, active_graph_mask) self._forces_primed = True # Only the step after a refill needs masked updates; other steps skip # the masking cost even when the batch carries all-False flags. pending = ( getattr(batch, "reprime_pending", None) if self._refill_pending else None ) update_mask = active_graph_mask if pending is not None: # Snapshot before compute clears the flags: refilled graphs must # skip both update phases of this iteration. update_mask = ~pending.view(-1)[: batch.num_graphs] if active_graph_mask is not None: update_mask = update_mask & active_graph_mask self._call_hooks(DynamicsStage.BEFORE_STEP, batch, active_graph_mask) with self._stream_scope(batch.device): self._call_hooks( DynamicsStage.BEFORE_PRE_UPDATE, batch, update_mask, ) if pending is None: self.pre_update(batch) else: self._masked_pre_update(batch, update_mask) self._call_hooks( DynamicsStage.AFTER_PRE_UPDATE, batch, update_mask, ) self._call_hooks(DynamicsStage.BEFORE_COMPUTE, batch, active_graph_mask) self.compute(batch, active_graph_mask) self._call_hooks(DynamicsStage.AFTER_COMPUTE, batch, active_graph_mask) if pending is not None: pending.zero_() self._refill_pending = False self._call_hooks( DynamicsStage.BEFORE_POST_UPDATE, batch, update_mask, ) if pending is None: self.post_update(batch) else: self._masked_post_update(batch, update_mask) self._call_hooks( DynamicsStage.AFTER_POST_UPDATE, batch, update_mask, ) if active_graph_mask is not None: with torch.no_grad(): for field, sv in saved.items(): val = getattr(batch, field) if val.shape[0] == batch.num_nodes: val[~node_mask] = sv else: val[sys_mask] = sv self._call_hooks(DynamicsStage.AFTER_STEP, batch, active_graph_mask) converged = self._check_convergence(batch) self._last_converged = converged if converged is not None: self._call_hooks(DynamicsStage.ON_CONVERGE, batch, active_graph_mask) # Dispatched whenever a hook listens: gating on the mask would host-sync. if active_graph_mask is not None and self._has_hooks_for_stage( DynamicsStage.ON_GRADUATE ): still_active = self.active_graph_mask(batch, self.exit_status) self._call_hooks( DynamicsStage.ON_GRADUATE, batch, active_graph_mask, ignore_frequency=True, graduated_mask=active_graph_mask & ~still_active, ) self.step_count += 1 return batch, converged
def _prime_forces( self, batch: Batch, active_graph_mask: torch.Tensor | None, ) -> None: """Run the compute hook lifecycle before the first integration step. Executes ``BEFORE_COMPUTE`` hooks, :meth:`compute`, and ``AFTER_COMPUTE`` hooks once to initialize the batch's model outputs. Parameters ---------- batch : Batch Batch whose model outputs are initialized in-place. active_graph_mask : torch.Tensor | None Boolean mask selecting active graphs, or ``None`` when the batch does not use status-based filtering. """ self._ensure_state_initialized(batch) with self._stream_scope(batch.device): self._call_hooks( DynamicsStage.BEFORE_COMPUTE, batch, active_graph_mask, ) self.compute(batch, active_graph_mask) self._call_hooks( DynamicsStage.AFTER_COMPUTE, batch, active_graph_mask, ) pending = getattr(batch, "reprime_pending", None) if pending is not None: pending.zero_() self._refill_pending = False
[docs] def run(self, batch: Batch, n_steps: int | None = None) -> Batch: """ 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 the ``n_steps`` parameter, 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 :class:`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 to ``self.n_steps``. If both are ``None``, raises ``ValueError``. Returns ------- Batch The batch after all steps have been executed. Raises ------ ValueError If no step count is available (both the argument and ``self.n_steps`` are ``None``). """ resolved = n_steps if n_steps is not None else self.n_steps if resolved is None: raise ValueError( "No step count provided. Either pass `n_steps` to run() " "or set it at construction time via " f"`{type(self).__name__}(..., n_steps=N)`." ) self._validate_n_steps(resolved) self._open_hooks() try: # A run is a fresh admission even when the caller deliberately # reuses the same Batch object from an earlier run. self._admission_initialized = False self._forces_primed = False for _ in range(resolved): batch, _converged = self.step(batch) # Early exit when every system has satisfied the convergence # criteria (sampler-free / Mode 1 only). if ( self.sampler is None and _converged is not None and _converged.numel() == batch.num_graphs ): break finally: self._close_hooks() return batch
[docs] def refill_check(self, batch: Batch, exit_status: int) -> Batch | None: """Replace graduated samples via index-select and append. Graduated graphs (``status >= exit_status``) are written to sinks, then removed via :meth:`Batch.index_select` on the remaining indices. Replacement samples from the sampler are appended via :meth:`Batch.append`. Dynamics-specific bookkeeping fields are written into the result batch via the ``_bookkeeping_keys`` registry. 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 ``status`` field. exit_status : int Status code indicating graduation. Returns ------- Batch | None A new batch with graduated graphs replaced by fresh samples, or ``None`` if no active samples remain (sampler exhausted and all graduated) — in which case ``self.done`` is set to ``True``. Raises ------ RuntimeError If ``self.sampler`` is ``None``. """ if self.sampler is None: raise RuntimeError("refill_check requires a sampler to be configured.") status = batch.status if status.dim() == 2: status = status.squeeze(-1) graduated_mask = status >= exit_status if not graduated_mask.any(): return batch # Batch composition changes here; drop stale converged indices so the # next _build_context mask doesn't over-index the resized batch. self._last_converged = None self._admission_initialized = False remaining_indices = torch.where(~graduated_mask)[0] n_remaining = remaining_indices.numel() # With no survivors there are no forces to preserve, so treat the # refill as a fresh batch and prime it fully before its first update. use_per_graph_priming = ( self._supports_per_graph_priming and self._forces_primed and n_remaining > 0 ) self._forces_primed = False if self.sinks and graduated_mask.any(): self._overflow_to_sinks(batch, mask=graduated_mask) if remaining_indices.numel() > 0: result = batch.index_select(remaining_indices) else: result = None # Budget-based replacement: compute total atom/edge headroom # from the remaining systems and the sampler's constraints. remaining_atoms = ( int(batch.num_nodes_per_graph[remaining_indices].sum()) if n_remaining > 0 else 0 ) atom_budget = ( self.sampler.max_atoms - remaining_atoms if self.sampler.max_atoms is not None else None ) edges_per_graph = batch.num_edges_per_graph remaining_edges = ( int(edges_per_graph[remaining_indices].sum()) if n_remaining > 0 and edges_per_graph.numel() > 0 else 0 ) edge_budget = ( self.sampler.max_edges - remaining_edges if self.sampler.max_edges is not None else None ) max_new = ( self.sampler.max_batch_size - n_remaining if self.sampler.max_batch_size is not None else None ) replacements = self.sampler.request_replacements_budget( atom_budget=atom_budget, edge_budget=edge_budget, max_count=max_new, ) if replacements: repl_batch = Batch.from_data_list(replacements, device=batch.device) if result is None: result = repl_batch else: # Append only fills fields survivors carry, so create them first # and match the registered column-shaped defaults. for key, default_fn in self._bookkeeping_keys.items(): value = getattr(result, key, None) if value is None: result[key] = default_fn(result.num_graphs, result.device) elif value.dim() == 1: result[key] = value.unsqueeze(-1) result.append( repl_batch, missing_fields="fill", field_defaults=self._bookkeeping_keys, ) if result is not None: # Fresh batches and survivors without replacements bypass append. for key, default_fn in self._bookkeeping_keys.items(): value = getattr(result, key, None) if value is None: result[key] = default_fn(result.num_graphs, result.device) elif value.dim() == 1: result[key] = value.unsqueeze(-1) if use_per_graph_priming: # Newly added graphs skip updates for one iteration while the # regular model evaluation computes their initial forces. # Preserve existing graphs' pending flags. result.reprime_pending.view(-1)[n_remaining:] = True self._forces_primed = True self._refill_pending = True self._sync_state_to_batch(remaining_indices, len(replacements), result) return result if self.sampler.exhausted: self.done = True self._sync_state_to_batch(remaining_indices, 0, batch) return None
[docs] def masked_update( self, batch: Batch, mask: Bool[torch.Tensor, "B"], # noqa: F722, F821 ) -> None: """ 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. 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. """ # lazy init — FusedStage sub-stages never have step() called on them directly self._ensure_state_initialized(batch) node_mask_occupied = torch.repeat_interleave(mask, batch.num_nodes_per_graph) node_mask = torch.zeros(batch.num_nodes, dtype=torch.bool, device=batch.device) node_mask[: len(node_mask_occupied)] = node_mask_occupied sys_mask = ~mask saved: dict[str, torch.Tensor] = {} for field in self._mutable_fields: val = getattr(batch, field, None) if val is None: continue if val.shape[0] == batch.num_nodes: saved[field] = val[~node_mask].clone() elif val.shape[0] == batch.num_graphs: saved[field] = val[sys_mask].clone() self.pre_update(batch) self.post_update(batch) with torch.no_grad(): for field, sv in saved.items(): val = getattr(batch, field) if val.shape[0] == batch.num_nodes: val[~node_mask] = sv else: val[sys_mask] = sv
def _masked_pre_update( self, batch: Batch, mask: Bool[torch.Tensor, "B"], # noqa: F722, F821 ) -> None: """Run only pre_update for masked samples, restoring non-masked state. Used by :class:`FusedStage` to interleave pre_update across all sub-stages before the shared compute, so that forces are evaluated at the post-pre_update positions (required for BAOAB Langevin and velocity-Verlet-based integrators). The save/restore uses full-tensor clones blended back with ``torch.where`` rather than boolean-mask fancy indexing: mask indexing lowers to data-dependent ``nonzero`` (dynamic shapes, graph breaks), while the blend is static-shaped, safe for all-False masks, and CUDA-graph friendly. The whole body runs under ``no_grad``: the integrator is pure kinematics, and in-place updates of a grad-requiring ``positions`` leaf are only legal without grad. """ self._ensure_state_initialized(batch) with torch.no_grad(): node_mask = mask[batch.batch_idx] saved = self._save_mutable_fields(batch) saved_state = self._save_state_fields() self.pre_update(batch) self._restore_unmasked_fields(batch, saved, mask, node_mask) self._restore_unmasked_state(batch, saved_state, mask) def _masked_post_update( self, batch: Batch, mask: Bool[torch.Tensor, "B"], # noqa: F722, F821 ) -> None: """Run only post_update for masked samples, restoring non-masked state. Called by :class:`FusedStage` after the shared compute so that post_update (e.g. the final BAOAB velocity half-kick) uses forces at the new positions. Uses the same static-shape save/blend strategy as :meth:`_masked_pre_update` — see that method for the rationale. When :attr:`_post_update_is_noop` is set, the save/blend-back is skipped entirely: ``post_update`` is still called (so a subclass that violates the flag's contract is still *invoked*, just not correctly masked), but there is nothing to restore because nothing is expected to change. This only affects ``_masked_post_update``; :meth:`_masked_pre_update` always does the full save/restore. """ if self._post_update_is_noop: with torch.no_grad(): self.post_update(batch) return with torch.no_grad(): node_mask = mask[batch.batch_idx] saved = self._save_mutable_fields(batch) saved_state = self._save_state_fields() self.post_update(batch) self._restore_unmasked_fields(batch, saved, mask, node_mask) self._restore_unmasked_state(batch, saved_state, mask) def _save_mutable_fields(self, batch: Batch) -> dict[str, torch.Tensor]: """Clone every mutable field in full (static shapes, no mask indexing).""" saved: dict[str, torch.Tensor] = {} for field in self._mutable_fields: val = getattr(batch, field, None) if val is not None: saved[field] = val.clone() return saved def _restore_unmasked_fields( self, batch: Batch, saved: dict[str, torch.Tensor], mask: torch.Tensor, node_mask: torch.Tensor, ) -> None: """Blend pre-update values back into unmasked rows via ``torch.where``.""" for field, sv in saved.items(): val = getattr(batch, field) m = node_mask if val.shape[0] == batch.num_nodes else mask m = m.view(m.shape[0], *([1] * (val.dim() - 1))) torch.where(m, val, sv, out=val)
[docs] class ConvergenceHook: """Hook that evaluates composable convergence criteria and optionally migrates converged samples between pipeline stages. Wraps one or more :class:`_ConvergenceCriterion` instances and combines their results with AND semantics: a sample is converged only when **every** criterion is satisfied. When ``source_status`` and ``target_status`` are both provided, the hook also performs status migration — updating ``batch.status`` for converged samples that match ``source_status``. This enables the single-loop execution strategy used by :class:`FusedStage`. When used as a standalone convergence detector (both ``source_status`` and ``target_status`` are ``None``), call :meth:`evaluate` directly or let :class:`BaseDynamics` use it via ``_check_convergence``. Attributes ---------- criteria : list[_ConvergenceCriterion] The individual convergence criteria. frequency : int Execute every N steps. stage : DynamicsStage The stage at which this hook fires (``AFTER_STEP``). source_status : int | None Status code of samples to check for convergence. ``None`` disables status migration. target_status : int | None Status code to assign to converged samples. ``None`` disables status migration. by_group : bool If ``True``, mark a group as converged only when every updatable graph in that group has converged. Requires ``batch.group_layout`` to be configured. Examples -------- >>> # Backward-compatible fmax-only hook >>> hook = ConvergenceHook.from_fmax(0.05) >>> converged = hook.evaluate(batch) >>> # Multi-criteria hook for FusedStage with status migration >>> hook = ConvergenceHook( ... criteria=[ ... {"key": "forces", "threshold": 0.05, "reduce_op": "norm", "reduce_dims": -1}, ... {"key": "energy_change", "threshold": 1e-6}, ... ], ... source_status=0, ... target_status=1, ... ) """ def __init__( self, criteria: ( _ConvergenceCriterion | list[_ConvergenceCriterion] | dict | list[dict] | None ) = None, source_status: int | None = None, target_status: int | None = None, frequency: int = 1, by_group: bool = False, ) -> None: """Initialize the convergence hook. Parameters ---------- criteria : _ConvergenceCriterion | list[...] | dict | list[dict] | None Convergence criterion specification(s). Dicts are validated and converted to ``_ConvergenceCriterion`` instances. If ``None``, defaults to a single forces-based criterion (max per-atom force norm) with threshold ``0.05``. source_status : int | None, optional Status code to check. ``None`` disables status migration. target_status : int | None, optional Status code to assign on convergence. ``None`` disables status migration. frequency : int, optional Execute every N steps. Default 1. by_group : bool, optional Whether convergence is reduced across graph groups. Default ``False``. """ self.frequency = frequency self.stage = DynamicsStage.AFTER_STEP self.source_status = source_status self.target_status = target_status self.by_group = by_group if criteria is None: self.criteria: list[_ConvergenceCriterion] = [ _ConvergenceCriterion( key="forces", threshold=0.05, reduce_op="norm", reduce_dims=-1 ) ] elif isinstance(criteria, _ConvergenceCriterion): self.criteria = [criteria] elif isinstance(criteria, dict): self.criteria = [_ConvergenceCriterion(**criteria)] elif isinstance(criteria, (list, tuple)): normalized: list[_ConvergenceCriterion] = [] for item in criteria: if isinstance(item, dict): normalized.append(_ConvergenceCriterion(**item)) elif isinstance(item, _ConvergenceCriterion): normalized.append(item) else: raise TypeError( "Each criterion must be a dict or" f" _ConvergenceCriterion, got {type(item).__name__}" ) self.criteria = normalized else: raise TypeError( "criteria must be a dict, _ConvergenceCriterion, or list" f" thereof, got {type(criteria).__name__}" ) def __repr__(self) -> str: """Return a human-readable summary of the convergence hook.""" inner = ", ".join(repr(c) for c in self.criteria) parts = [f"criteria=[{inner}]"] if self.source_status is not None: parts.append(f"source_status={self.source_status}") if self.target_status is not None: parts.append(f"target_status={self.target_status}") parts.append(f"frequency={self.frequency}") if self.by_group: parts.append("by_group=True") return f"{type(self).__name__}({', '.join(parts)})"
[docs] def on_register(self, workflow: object) -> None: """Require convergence and dynamics to use the same grouping mode. Parameters ---------- workflow : object Workflow on which this hook is being registered. Raises ------ ValueError If convergence and the workflow use different grouping modes. """ workflow_by_group = getattr(workflow, "by_group", False) if self.by_group != workflow_by_group: raise ValueError( "ConvergenceHook and dynamics must use the same by_group setting" )
[docs] @classmethod def from_fmax( cls, threshold: float = 0.05, source_status: int | None = None, target_status: int | None = None, frequency: int = 1, by_group: bool = False, ) -> ConvergenceHook: """Create a forces-based convergence hook (fmax-compatible). This is a convenience constructor for backward compatibility with the original ``convergence_fmax`` parameter. Parameters ---------- threshold : float, optional Maximum force threshold. Default ``0.05``. source_status : int | None, optional Status code to check. ``None`` disables status migration. target_status : int | None, optional Status code to assign on convergence. ``None`` disables status migration. frequency : int, optional Execute every N steps. Default 1. by_group : bool, optional Whether convergence is reduced across graph groups. Default ``False``. Returns ------- ConvergenceHook Hook with a single forces-based (max force norm) criterion. """ return cls.from_forces( threshold=threshold, frequency=frequency, source_status=source_status, target_status=target_status, by_group=by_group, )
[docs] @classmethod def from_forces( cls, threshold: float, frequency: int = 1, source_status: int | None = None, target_status: int | None = None, by_group: bool = False, ) -> ConvergenceHook: """Construct from force-norm threshold (reads 'forces' key, norm reduction). Parameters ---------- threshold : float Force threshold; systems with max force norm <= threshold are converged. frequency : int, optional Evaluate every N steps. Default 1. source_status : int | None, optional Status code that eligible systems must have. Default None (any status). target_status : int | None, optional Status code to assign to converged systems. Default None (no status change). by_group : bool, optional Whether convergence is reduced across graph groups. Default ``False``. Returns ------- ConvergenceHook Hook that evaluates max per-atom force norm against ``threshold``. """ return cls( criteria=[ { "key": "forces", "threshold": threshold, "reduce_op": "norm", "reduce_dims": -1, } ], frequency=frequency, source_status=source_status, target_status=target_status, by_group=by_group, )
@property def num_criteria(self) -> int: """Return the number of individual criteria.""" return len(self.criteria)
[docs] def evaluate(self, batch: Batch) -> torch.Tensor | None: """Evaluate all criteria and return indices of converged samples. Pre-allocates a ``(N_criteria, B)`` boolean tensor, evaluates each criterion to fill one row, then AND-reduces across criteria. Returns the integer indices of converged samples, or ``None`` if no samples have converged. Parameters ---------- batch : Batch The current batch of atomic data. Returns ------- torch.Tensor | None 1-D integer tensor of converged sample indices, or ``None`` if no samples satisfy all criteria. """ converged_mask = self.evaluate_mask(batch) if not converged_mask.any(): return None return torch.where(converged_mask)[0]
[docs] def evaluate_mask(self, batch: Batch) -> torch.Tensor: """Evaluate all criteria and return a boolean converged mask. Branchless, static-shape core of :meth:`evaluate`: no host sync and no data-dependent index extraction, so it can run inside a compiled step (:meth:`FusedStage._step_impl`) without breaking the graph. Parameters ---------- batch : Batch The current batch of atomic data. Returns ------- torch.Tensor Boolean tensor of shape ``(B,)``; ``True`` where every criterion is satisfied. """ n_criteria = len(self.criteria) n_graphs = batch.num_graphs results = torch.ones( n_criteria, n_graphs, dtype=torch.bool, device=batch.positions.device, ) for i, criterion in enumerate(self.criteria): results[i] = criterion(batch) converged_mask = torch.all(results, dim=0) if self.by_group: # A group converges only when every graph in the group has converged. layout = batch.group_layout converged_mask = layout.broadcast(layout.reduce_all(converged_mask)) return converged_mask
def __call__(self, ctx: DynamicsContext, stage: Enum) -> None: """Evaluate convergence and optionally migrate sample status. When ``source_status`` and ``target_status`` are both set, converged samples whose ``batch.status`` matches ``source_status`` are migrated to ``target_status``. If ``batch`` lacks ``status`` when status migration is configured, the migration step is silently skipped. Parameters ---------- ctx : DynamicsContext The hook context containing the current batch. stage : Enum The stage being dispatched. """ batch = ctx.batch if self.source_status is not None and self.target_status is not None: if not hasattr(batch, "status") or batch.status is None: return # Blend via torch.where: mask indexing and .any() gating would # host-sync and break the compiled graph. converged_mask = self.evaluate_mask(batch) status = batch.status if status.dim() == 2: status = status.squeeze(-1) migrate = converged_mask & (status == self.source_status) if getattr(batch, "reprime_pending", None) is not None: # Prevent same-step migration through a stage that requires fresh model outputs migrate &= ~batch.reprime_pending.view(-1)[: batch.num_graphs] flat_status = ( batch.status.view(-1) if batch.status.dim() == 2 else batch.status ) flat_status.copy_( torch.where( migrate, torch.full_like(flat_status, self.target_status), flat_status, ) )
[docs] class FusedStage(BaseDynamics): """Composite dynamics engine fusing multiple sub-stages on a single GPU. ``FusedStage`` composes multiple ``BaseDynamics`` sub-stages to share one ``Batch`` and one model forward pass per step, avoiding redundant forward passes when multiple simulation phases (e.g., relaxation then MD) operate on the same batch. Unlike ``BaseDynamics``, **``step(batch)``** is overridden. Instead of the standard ``pre_update → compute → post_update`` loop, ``FusedStage`` performs: (1) iterates over sub-stages, applying masked ``pre_update`` on each sub-stage's dynamics, (2) a single ``compute()`` call on the full batch, then (3) iterates over sub-stages, applying masked ``post_update``. Each update applies only to samples whose ``batch.status`` matches that sub-stage's status code. Only ONE forward pass happens per step regardless of the number of sub-stages. **``run(batch)``** is also overridden — the ``n_steps`` attribute (inherited from ``BaseDynamics``) and any ``n_steps`` argument passed to ``run()`` are both the **maximum** number of steps; the loop runs until all samples have migrated to the ``exit_status``, the sampler is exhausted, or ``n_steps`` is reached. Convergence-driven migration is handled by ``ConvergenceHook`` instances auto-registered between adjacent sub-stages: when samples converge in sub-stage *i*, their ``batch.status`` is updated to sub-stage *i+1*'s code, causing them to be processed by the next dynamics on the following step. The ``+`` operator composes sub-stages: ``dyn_a + dyn_b`` creates a ``FusedStage``, and ``fused + dyn_c`` appends a third sub-stage. The ``|`` operator (inherited from ``BaseDynamics`` via ``_CommunicationMixin``) creates a ``DistributedPipeline`` for multi-rank execution instead. Developers generally do NOT subclass ``FusedStage``. Instead, create ``BaseDynamics`` subclasses (integrators) and compose them using ``+``. ``FusedStage`` handles orchestration, including masking, automatically. The batch must have a ``status`` tensor. Hook Firing Semantics ~~~~~~~~~~~~~~~~~~~~~ Because ``FusedStage`` shares a single forward pass across all sub-stages, hooks can be registered both on the fused stage and on its sub-stages. All step, compute, and integrator update boundaries fire at both levels. Fused-stage hooks receive the full batch and overall active mask. Sub-stage hooks at step and compute boundaries receive that sub-stage's status mask. This includes reprime-pending graphs so the shared compute can refresh their forces. Hooks around ``pre_update`` and ``post_update`` instead exclude those graphs from both updates until the next fused step. The fused stage acts as the outer lifecycle boundary: - At shared ``BEFORE_*`` boundaries, fused-stage hooks fire once before sub-stage hooks fire in sub-stage order. - At shared ``AFTER_*`` boundaries, sub-stage hooks fire in sub-stage order before fused-stage hooks fire once. - ``ON_CONVERGE`` is sub-stage-only because convergence is evaluated and represented independently for each sub-stage. - ``ON_GRADUATE`` fires after the step-budget migration and the ``ON_CONVERGE`` dispatch. ``ctx.graduated_mask`` marks the graphs whose status reached ``exit_status`` at any stage of the step. Sub-stage hooks fire first, each with the mask limited to the graphs its sub-stage owned, and fused-stage hooks fire last with the full mask. Initial force priming uses the same nested ordering for ``BEFORE_COMPUTE`` and ``AFTER_COMPUTE``. Graphs that change into a sub-stage created with ``reprime_on_entry=True`` skip one update while the shared model compute and that sub-stage's compute hooks refresh their forces. The entry sub-stage's flag also applies to graphs received from a previous pipeline rank. **Step count semantics:** Each sub-stage's ``step_count`` is incremented alongside the ``FusedStage``'s own ``step_count`` after every fused step, ensuring that hook frequency (e.g., ``every_n_steps``) is respected correctly across all sub-stages. Parameters ---------- sub_stages : list[tuple[int, BaseDynamics]] Ordered ``(status_code, dynamics)`` pairs. Status codes are auto-assigned starting from 0 when using the ``+`` operator. entry_status : int Status code assigned to incoming samples (default: 0). exit_status : int Status code that triggers graduation to the next pipeline stage. Auto-set to ``len(sub_stages)`` (one past the last sub-stage code). compile_step : bool If ``True``, replace ``self.step`` with ``torch.compile(self.step, **compile_kwargs)``. compile_kwargs : dict Keyword arguments forwarded to ``torch.compile``. **kwargs Additional keyword arguments forwarded to ``BaseDynamics``. Attributes ---------- sub_stages : list[tuple[int, BaseDynamics]] Ordered ``(status_code, dynamics)`` pairs. entry_status : int Status code for incoming samples. exit_status : int Status code that triggers graduation. compile_step : bool Whether the step method is compiled. compile_kwargs : dict Arguments passed to ``torch.compile``. __needs_keys__ : set[str] Union of all sub-stage ``__needs_keys__`` sets. Populated automatically during ``__init__``. __provides_keys__ : set[str] Union of all sub-stage ``__provides_keys__`` sets. Populated automatically during ``__init__``. Examples -------- >>> from nvalchemi.dynamics import FusedStage, BaseDynamics >>> dynamics0 = BaseDynamics(model=model) >>> dynamics1 = BaseDynamics(model=model) >>> fused = FusedStage(sub_stages=[(0, dynamics0), (1, dynamics1)]) >>> fused.exit_status 2 """ def __init__( self, sub_stages: list[tuple[int, BaseDynamics]], *, entry_status: int = 0, exit_status: int = -1, compile_step: bool = False, compile_kwargs: dict[str, Any] | None = None, init_fn: Callable[[Batch], None] | None = None, **kwargs: Any, ) -> None: """Initialize the fused stage. Parameters ---------- sub_stages : list[tuple[int, BaseDynamics]] Ordered ``(status_code, dynamics)`` pairs. entry_status : int, optional Status code assigned to incoming samples. Default 0. exit_status : int, optional Status code that triggers graduation. Auto-set to ``len(sub_stages)`` if -1. Default -1. compile_step : bool, optional If ``True``, compile the step method with ``torch.compile``. Default ``False``. compile_kwargs : dict[str, Any] | None, optional Keyword arguments for ``torch.compile``. Default ``None``. init_fn : Callable[[Batch], None] | None, optional Optional callback invoked on the initial batch immediately after ``sampler.build_initial_batch()`` returns, before the first step. Use this to populate fields that the sampler does not set, such as ``velocities`` or ``forces``. Only called in Mode 2 (inflight batching with ``batch=None``). Default ``None``. **kwargs : Any Additional keyword arguments forwarded to ``BaseDynamics``. Raises ------ TypeError If ``reprime_on_entry`` is passed. Set it on the sub-stage dynamics instead. ValueError If sub-stages have different ``device_type`` or ``by_group`` values. """ if "reprime_on_entry" in kwargs: raise TypeError( "FusedStage does not accept reprime_on_entry; set " "reprime_on_entry on the sub-stage dynamics instead." ) first_dynamics = sub_stages[0][1] model = first_dynamics.model device_types = {dyn.device_type for _, dyn in sub_stages} if len(device_types) > 1: per_stage = {code: dyn.device_type for code, dyn in sub_stages} raise ValueError( f"All sub-stages in a FusedStage must share the same " f"device_type, but got: {per_stage}. A FusedStage runs " f"on a single device with a shared batch and forward pass." ) group_modes = {dynamics.by_group for _, dynamics in sub_stages} if len(group_modes) > 1: raise ValueError( "All FusedStage sub-stages must agree on whether updates are " "group-aware." ) super().__init__(model=model, **kwargs) self.sub_stages = sub_stages # Live back-pointer onto the shared sub-stage objects, not copies — # see the "retained composition" limitation in FusedStage.__add__. for _, dynamics in sub_stages: dynamics._enclosing_hooks = self.hooks self._reprime_status_codes = frozenset( code for code, dynamics in sub_stages if dynamics.reprime_on_entry ) # Pipeline arrivals enter the entry sub-stage, so they follow its flag. self.reprime_on_entry = entry_status in self._reprime_status_codes self.__needs_keys__ = set().union( *(dyn.__needs_keys__ for _, dyn in sub_stages) ) self.__provides_keys__ = set().union( *(dyn.__provides_keys__ for _, dyn in sub_stages) ) self.entry_status = entry_status self.compile_kwargs: dict[str, Any] = ( compile_kwargs if compile_kwargs is not None else {} ) self.compile_step = compile_step self._compiled_step: ( Callable[[Batch], tuple[Batch, torch.Tensor | None]] | None ) = None if exit_status == -1: self.exit_status = len(self.sub_stages) else: self.exit_status = exit_status self.convergence_check_frequency: int = 1 self.init_fn = init_fn for i in range(len(self.sub_stages)): source_code, source_dynamics = self.sub_stages[i] if i + 1 < len(self.sub_stages): target_code, _ = self.sub_stages[i + 1] else: # The last stage graduates directly to exit_status when it # declares a convergence criterion. if source_dynamics.convergence_hook is None: continue target_code = self.exit_status # Remove duplicate migration hooks with the same (source_status, target_status) # to prevent double-fire after __add__ reconstruction. source_dynamics.hooks = [ h for h in source_dynamics.hooks if not ( isinstance(h, ConvergenceHook) and hasattr(h, "source_status") and h.source_status == source_code and hasattr(h, "target_status") and h.target_status == target_code ) ] criteria = None by_group = source_dynamics.by_group if source_dynamics.convergence_hook is not None: criteria = source_dynamics.convergence_hook.criteria by_group = source_dynamics.convergence_hook.by_group hook = ConvergenceHook( criteria=criteria, source_status=source_code, target_status=target_code, by_group=by_group, ) source_dynamics.register_hook(hook) for status_code, dynamics in self.sub_stages: if dynamics.n_steps is not None: counter_key = f"n_steps_counter_{status_code}" BaseDynamics.register_bookkeeping_key( counter_key, lambda n, dev: torch.zeros(n, 1, dtype=torch.long, device=dev), ) if self.compile_step: self.compile() def __repr__(self) -> str: """Return a human-readable summary of the fused stage.""" stages_repr = ", ".join( f"{code}:{type(dyn).__name__}" for code, dyn in self.sub_stages ) compiled = self._compiled_step is not None return ( f"FusedStage(" f"sub_stages=[{stages_repr}], " f"entry_status={self.entry_status}, " f"exit_status={self.exit_status}, " f"reprime_status_codes={set(self._reprime_status_codes)}, " f"compiled={compiled}, " f"step_count={self.step_count})" )
[docs] def compile(self, **kwargs: Any) -> FusedStage: """Compile the fused step with ``torch.compile``. Merges *kwargs* with any ``compile_kwargs`` stored at construction time (values passed here take precedence), then wraps ``_step_impl`` with ``torch.compile``. Calling this method also sets ``compile_step = True`` so that the ``step`` dispatch path uses the compiled callable. This method is idempotent in intent but **will** re-compile if called again (e.g. with different kwargs). Parameters ---------- **kwargs : Any Keyword arguments forwarded to ``torch.compile``. Merged with ``compile_kwargs`` from ``__init__``; values here win. Returns ------- FusedStage This instance, enabling fluent chaining such as ``fused.compile(fullgraph=True).run(batch)``. """ merged = {**self.compile_kwargs, **kwargs} self.compile_kwargs = merged self.compile_step = True self._compiled_step = torch.compile(self._step_impl, **merged) return self
def _mark_cudagraph_static_inputs(self, batch: Batch) -> None: """Mark CUDA batch and sub-stage state tensors for graph replay. ``_step_impl`` mutates batch and optimizer-state tensors in place. Inductor permits those mutations in CUDA graphs when their inputs have stable addresses. The default unguarded marking lets CUDA graphs re-record if a refill or another batch operation replaces a tensor with a different address. Parameters ---------- batch : Batch Batch whose current tensor fields will enter the compiled step. """ if batch.device.type != "cuda": return for _, tensor in batch: torch._dynamo.mark_static_address(tensor) for _, dynamics in self.sub_stages: state = getattr(dynamics, "_state", None) if state is not None: for _, tensor in state: torch._dynamo.mark_static_address(tensor) def __enter__(self) -> FusedStage: """Enter the stream context and propagate to all sub-stages. Calls the parent ``__enter__`` to create and enter a CUDA stream context, then sets every sub-stage's ``_stream`` reference to the same stream so that all computation runs on a single dedicated stream. If ``compile_step`` is ``True`` but compilation has not yet been performed (e.g. because the stage was created via ``__add__``), compilation is triggered here automatically. Returns ------- FusedStage This instance. """ super().__enter__() for _, dynamics in self.sub_stages: dynamics._stream = self._stream dynamics._wp_stream = self._wp_stream if self.compile_step and self._compiled_step is None: self.compile() return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any, ) -> None: """Exit the stream context and clear sub-stage stream references. Clears every sub-stage's ``_stream`` reference, then delegates to the parent ``__exit__`` to exit the ``StreamContext`` and clean up. Parameters ---------- exc_type : type[BaseException] | None Exception type, if any. exc_val : BaseException | None Exception value, if any. exc_tb : Any Exception traceback, if any. """ for _, dynamics in self.sub_stages: dynamics._stream = None dynamics._wp_stream = None super().__exit__(exc_type, exc_val, exc_tb) def _sync_state_to_batch( self, remaining_indices: "torch.Tensor", n_new: int, template_batch: Batch, ) -> None: """Fan out state sync to all sub-stages. ``FusedStage`` itself holds no ``_state``; each sub-stage does. This override delegates to every sub-stage so that active-batch membership changes keep each sub-stage's ``_state`` aligned with the new batch composition. Parameters ---------- remaining_indices : torch.Tensor Integer indices of systems that remain after graduation. n_new : int Number of newly admitted replacement systems. template_batch : Batch The updated batch; provides device/dtype for new-state init. """ for _, sub_stage in self.sub_stages: sub_stage._sync_state_to_batch(remaining_indices, n_new, template_batch) def _ensure_bookkeeping_fields(self, batch: Batch) -> None: """Auto-initialize status and registered bookkeeping fields if absent. Parameters ---------- batch : Batch The batch to check and initialize fields on. """ for key, default_fn in self._bookkeeping_keys.items(): if getattr(batch, key, None) is None: batch[key] = default_fn(batch.num_graphs, batch.device) def _on_receive(self, incoming: Batch) -> None: """Admit samples from the prior rank at ``entry_status``. The sender's ``status`` is its own ``exit_status``, which would read as already graduated here; reset it to ``entry_status`` and clear the per-stage step counters. Parameters ---------- incoming : Batch Batch received from the prior stage, modified in place. """ status = getattr(incoming, "status", None) if status is not None: status.fill_(self.entry_status) for status_code, _ in self.sub_stages: counter = getattr(incoming, f"n_steps_counter_{status_code}", None) if counter is not None: counter.zero_()
[docs] def register_hook(self, hook: Hook, stage: Enum | None = None) -> None: """Register a hook and warn about sub-stage-only lifecycle stages. Hooks targeting an unsupported fused-stage boundary remain registered for backward compatibility, but those boundaries are never dispatched by :class:`FusedStage`. Parameters ---------- hook : Hook Hook to register. stage : Enum | None, optional Stage override forwarded to the base hook registry. Warns ----- UserWarning If the hook targets a stage dispatched only on sub-stages. """ super().register_hook(hook, stage) sub_stage_only_stages = (DynamicsStage.ON_CONVERGE,) runs_on_stage = getattr(hook, "_runs_on_stage", None) if runs_on_stage is None: unsupported_stages = ( [hook.stage] if hook.stage in sub_stage_only_stages else [] ) else: unsupported_stages = [ candidate for candidate in sub_stage_only_stages if runs_on_stage(candidate) ] if unsupported_stages: stage_names = ", ".join(stage.name for stage in unsupported_stages) warnings.warn( f"Hook {type(hook).__name__} is registered on FusedStage for " f"sub-stage-only stage(s): {stage_names}. These stages are not " "called on FusedStage; register the hook on the relevant " "sub-stage instead.", UserWarning, stacklevel=2, )
[docs] def register_fused_hook(self, hook: Hook) -> None: """Register a hook on the full fused batch. .. deprecated:: 0.3.0 Use :meth:`register_hook` instead. ``FusedStage``'s inherited hook registry already observes the complete batch. Parameters ---------- hook : Hook The hook to register. Warns ----- DeprecationWarning Always emitted because this method is deprecated. """ warnings.warn( "FusedStage.register_fused_hook() is deprecated; use " "FusedStage.register_hook() instead.", DeprecationWarning, stacklevel=2, ) self.register_hook(hook)
def _mark_reprime_entries( self, batch: Batch, previous_status: torch.Tensor, ) -> torch.Tensor: """Mark graphs newly entering a sub-stage requiring force repriming.""" current_status = batch.status.view(-1)[: batch.num_graphs] entered = torch.zeros_like(current_status, dtype=torch.bool) for status_code in self._reprime_status_codes: entered.logical_or_( (previous_status != status_code) & (current_status == status_code) ) batch.reprime_pending.view(-1)[: batch.num_graphs].logical_or_(entered) return current_status.clone() def _ensure_admission_initialized(self, batch: Batch) -> None: """Prepare fused-level and sub-stage hooks for an admitted batch.""" if self._admission_initialized: return status = batch.status if status.dim() == 2: status = status.squeeze(-1) status = status[: batch.num_graphs] self._call_hooks( DynamicsStage.ON_ADMISSION, batch, status < self.exit_status, ignore_frequency=True, ) for status_code, dynamics in self.sub_stages: dynamics._call_hooks( DynamicsStage.ON_ADMISSION, batch, status == status_code, ignore_frequency=True, ) dynamics._admission_initialized = True self._admission_initialized = True def _step_impl(self, batch: Batch) -> tuple[Batch, torch.Tensor | None]: """Internal step implementation (may be compiled). Performs the following sequence: 1. Fire fused-stage BEFORE_STEP hooks, then each sub-stage's BEFORE_STEP hooks in sub-stage order, before any updates. 2. Fire fused-stage BEFORE_PRE_UPDATE hooks, then for each sub-stage, fire BEFORE_PRE_UPDATE hooks, run its masked pre_update, and fire AFTER_PRE_UPDATE hooks (positions advance to r(t+dt)). Finally, fire fused-stage AFTER_PRE_UPDATE hooks. 3. Fire fused-stage BEFORE_COMPUTE hooks, then each sub-stage's BEFORE_COMPUTE hooks (for example, NeighborListHook sees the new positions). Run one shared model forward, then fire each sub-stage's AFTER_COMPUTE hooks followed by the fused-stage AFTER_COMPUTE hooks. 4. Fire fused-stage BEFORE_POST_UPDATE hooks, then for each sub-stage, fire BEFORE_POST_UPDATE hooks, run its masked post_update (the final velocity kick using forces at r(t+dt)), and fire AFTER_POST_UPDATE hooks. Finally, fire fused-stage AFTER_POST_UPDATE hooks. 5. Snapshot status, then fire sub-stage and fused-stage AFTER_STEP hooks (ConvergenceHook migrates during the sub-stage hooks) and apply counter migration. 6. Check convergence independently for each sub-stage and fire its ON_CONVERGE hooks with the sub-stage-specific convergence mask. 7. Compare the status against the step-start snapshot to find the samples that graduated at any stage of this step, then fire ON_GRADUATE hooks with that mask: on each sub-stage for the graphs it owned, then on the fused stage. 8. Increment step_count for FusedStage and all sub-stages. Parameters ---------- batch : Batch The batch with a ``status`` field. Returns ------- tuple[Batch, torch.Tensor] The updated batch, and a boolean mask over graphs of samples that newly graduated (reached ``exit_status``) during this step. The mask (rather than an index tensor) keeps the return value static-shaped so the whole method can be captured in a single dynamo graph; :meth:`step` converts it to the index contract. """ # Prepare status-based active-graph filtering for this step. status = batch.status if status.dim() == 2: status = status.squeeze(-1) status = status[: batch.num_graphs] overall_active_graph_mask: torch.Tensor = status < self.exit_status # Snapshot each sub-stage's ownership. stage_active_masks: list[torch.Tensor] = [ status == status_code for status_code, _ in self.sub_stages ] # Reprime-pending graphs remain active for shared BEFORE_COMPUTE and # AFTER_COMPUTE hooks and target-stage AFTER_COMPUTE hooks. They are # masked out of the BEFORE/AFTER_PRE_UPDATE and BEFORE/AFTER_POST_UPDATE # hook and integrator phases for this iteration. reprime_pending = batch.reprime_pending.view(-1)[: batch.num_graphs] overall_update_graph_mask = overall_active_graph_mask & ~reprime_pending stage_update_masks: list[torch.Tensor] = [ active_mask & overall_update_graph_mask for active_mask in stage_active_masks ] # Phase 0 - before step self._call_hooks( DynamicsStage.BEFORE_STEP, batch, overall_active_graph_mask, ) for (_, dynamics), active_graph_mask in zip( self.sub_stages, stage_active_masks, strict=True ): dynamics._call_hooks( DynamicsStage.BEFORE_STEP, batch, active_graph_mask, ) # Phase 1 — pre_update for each sub-stage. # This moves positions to r(t+dt) so that the shared compute can # evaluate forces at the correct (updated) positions. self._call_hooks( DynamicsStage.BEFORE_PRE_UPDATE, batch, overall_update_graph_mask, ) for (_, dynamics), update_graph_mask in zip( self.sub_stages, stage_update_masks, strict=True ): dynamics._call_hooks( DynamicsStage.BEFORE_PRE_UPDATE, batch, update_graph_mask, ) # Unconditional: `if active_graph_mask.any():` would be a # graph-breaking host sync, and the masked update is a no-op for # all-False masks. dynamics._masked_pre_update(batch, update_graph_mask) dynamics._call_hooks( DynamicsStage.AFTER_PRE_UPDATE, batch, update_graph_mask, ) self._call_hooks( DynamicsStage.AFTER_PRE_UPDATE, batch, overall_update_graph_mask, ) # Phase 2 — shared forward pass at the updated positions. self._call_hooks( DynamicsStage.BEFORE_COMPUTE, batch, overall_active_graph_mask, ) for (_, dynamics), active_graph_mask in zip( self.sub_stages, stage_active_masks, strict=True ): dynamics._call_hooks( DynamicsStage.BEFORE_COMPUTE, batch, active_graph_mask, ) outputs: ModelOutputs = self.compute(batch, overall_active_graph_mask) self._publish_unmapped_outputs(batch, outputs, overall_active_graph_mask) for (_, dynamics), active_graph_mask in zip( self.sub_stages, stage_active_masks, strict=True ): dynamics._call_hooks( DynamicsStage.AFTER_COMPUTE, batch, active_graph_mask, ) self._call_hooks( DynamicsStage.AFTER_COMPUTE, batch, overall_active_graph_mask, ) batch.reprime_pending.zero_() # Phase 3 — post_update for each sub-stage, now with forces at r(t+dt). self._call_hooks( DynamicsStage.BEFORE_POST_UPDATE, batch, overall_update_graph_mask, ) for (_, dynamics), update_graph_mask in zip( self.sub_stages, stage_update_masks, strict=True ): dynamics._call_hooks( DynamicsStage.BEFORE_POST_UPDATE, batch, update_graph_mask, ) dynamics._masked_post_update(batch, update_graph_mask) dynamics._call_hooks( DynamicsStage.AFTER_POST_UPDATE, batch, update_graph_mask, ) self._call_hooks( DynamicsStage.AFTER_POST_UPDATE, batch, overall_update_graph_mask, ) # Snapshot before hook and counter migration so both are reported # in exit_converged. pre_migration_status = batch.status.clone() if pre_migration_status.dim() == 2: pre_migration_status = pre_migration_status.squeeze(-1) migration_status = pre_migration_status.clone() for (_, dynamics), active_graph_mask in zip( self.sub_stages, stage_active_masks, strict=True ): dynamics._call_hooks( DynamicsStage.AFTER_STEP, batch, active_graph_mask, ) # Mark reprime entries before the next sub-stage's convergence hook runs. migration_status = self._mark_reprime_entries(batch, migration_status) self._call_hooks( DynamicsStage.AFTER_STEP, batch, overall_active_graph_mask, ) for i, (status_code, dynamics) in enumerate(self.sub_stages): if dynamics.n_steps is None: continue counter_key = f"n_steps_counter_{status_code}" if getattr(batch, counter_key, None) is None: batch[counter_key] = torch.zeros( batch.num_graphs, 1, dtype=torch.long, device=batch.device ) counter = getattr(batch, counter_key) # Advance a stage counter only when the graph was eligible for a dynamics # update at the start of this iteration. Force priming clears # reprime_pending after compute, but must not count as a stage update. active = ( stage_update_masks[i] & ~batch.reprime_pending.view(-1)[: batch.num_graphs] & (migration_status == status_code) ) # Branchless: mask-indexed writes and `migrate.any()` break capture. counter.add_(active.to(counter.dtype).unsqueeze(-1)) next_status = ( self.sub_stages[i + 1][0] if i + 1 < len(self.sub_stages) else self.exit_status ) migrate = active & (counter.squeeze(-1) >= dynamics.n_steps) status_flat = batch.status.view(-1) status_flat.copy_( torch.where( migrate, torch.full_like(status_flat, next_status), status_flat, ) ) # Track counter-driven status transitions and mark entries requiring force reprime. migration_status = self._mark_reprime_entries(batch, migration_status) counter.copy_( torch.where(migrate.unsqueeze(-1), torch.zeros_like(counter), counter) ) for (_, dynamics), active_mask in zip( self.sub_stages, stage_active_masks, strict=True ): hook = dynamics.convergence_hook if hook is None: dynamics._last_converged = None continue # Gating on `stage_converged.any()` would host-sync every step, # so registered ON_CONVERGE hooks always fire and must consult # ctx.converged_mask themselves. stage_converged = hook.evaluate_mask(batch) & active_mask dynamics._last_converged = stage_converged if dynamics._has_hooks_for_stage(DynamicsStage.ON_CONVERGE): dynamics._call_hooks( DynamicsStage.ON_CONVERGE, batch, active_mask, ) post_status = batch.status if post_status.dim() == 2: post_status = post_status.squeeze(-1) newly_graduated = (pre_migration_status < self.exit_status) & ( post_status >= self.exit_status ) # Reported against the step-start status so a hook migration at any # stage counts. Dispatched whenever a hook listens: gating would host-sync. graduated = overall_active_graph_mask & ( post_status[: batch.num_graphs] >= self.exit_status ) for (_, dynamics), active_mask in zip( self.sub_stages, stage_active_masks, strict=True ): if dynamics._has_hooks_for_stage(DynamicsStage.ON_GRADUATE): dynamics._call_hooks( DynamicsStage.ON_GRADUATE, batch, active_mask, ignore_frequency=True, graduated_mask=graduated & active_mask, ) if self._has_hooks_for_stage(DynamicsStage.ON_GRADUATE): self._call_hooks( DynamicsStage.ON_GRADUATE, batch, overall_active_graph_mask, ignore_frequency=True, graduated_mask=graduated, ) self.step_count += 1 for _, dynamics in self.sub_stages: dynamics.step_count += 1 return batch, newly_graduated
[docs] def step(self, batch: Batch) -> tuple[Batch, torch.Tensor | None]: """Execute one fused step: single forward pass + masked updates. If ``compile_step=True`` was set, this delegates to the compiled step implementation. As in :class:`BaseDynamics`, initial force priming causes two compute-hook dispatches at ``step_count == 0``. Transition repriming instead occurs within the normal shared compute, so hooks are dispatched once and ``step_count`` advances at the end of that fused iteration. Transitioning graphs skip their dynamics update, so their per-system stage counters do not advance. Parameters ---------- batch : Batch The batch with a ``status`` field. Returns ------- tuple[Batch, torch.Tensor | None] The updated batch, and a 1-D integer tensor of sample indices that newly graduated (reached ``exit_status``) during this step, or ``None`` if no samples graduated. """ # Lazy state must be created outside the compiled step: in-graph # allocations break CUDA-graph replay and fullgraph shape reasoning. self._ensure_bookkeeping_fields(batch) # Refill creates a new batch whose lazy pointer cache must be built eagerly. _ = batch.batch_ptr for _, dynamics in self.sub_stages: dynamics._ensure_state_initialized(batch) dynamics._warm_state_levels() # Every step, not just admission: a hook (e.g. on this # FusedStage) registered after the sub-stage's first step must # still be caught, and this loop already runs outside the # compiled step. dynamics._check_hook_compatibility() # Admission hooks remain outside of the compiled step self._ensure_admission_initialized(batch) active_graph_mask = self.active_graph_mask(batch, self.exit_status) if not self._forces_primed: self._prime_forces(batch, active_graph_mask) self._forces_primed = True if self._compiled_step is not None: self._mark_cudagraph_static_inputs(batch) step_fn = ( self._compiled_step if self._compiled_step is not None else self._step_impl ) autograd_inputs = self._autograd_input_tensors(batch) with ( # TODO ideally we unify the API for both fused and single stage dynamics # so that the `_defer_autograd_input_cleanup` is not needed as a shim self._defer_autograd_input_cleanup(), requires_grad_ctx(*autograd_inputs), self._stream_scope(batch.device), ): batch, newly_graduated = step_fn(batch) # Mask -> index conversion here, where a host sync is acceptable. if newly_graduated is None or not newly_graduated.any(): return batch, None return batch, torch.where(newly_graduated)[0]
def __call__(self, batch: Batch) -> tuple[Batch, torch.Tensor | None]: """Call the ``step`` method on a batch.""" return self.step(batch)
[docs] @staticmethod def all_complete(batch: Batch, exit_status: int) -> bool: """Check if all samples have reached the exit status. Parameters ---------- batch : Batch The current batch. exit_status : int The status code that indicates completion. Returns ------- bool ``True`` if every sample has ``status == exit_status``. """ if not hasattr(batch, "status") or batch.status is None: return False status = batch.status if status.dim() == 2: status = status.squeeze(-1) return bool((status == exit_status).all())
def _open_hooks(self) -> None: """Enter context-manager hooks on this stage and its sub-stages.""" super()._open_hooks() for _, dynamics in self.sub_stages: dynamics._open_hooks() def _close_hooks(self) -> None: """Exit context-manager hooks on this stage and its sub-stages.""" super()._close_hooks() for _, dynamics in self.sub_stages: dynamics._close_hooks() def _prime_forces( self, batch: Batch, active_graph_mask: torch.Tensor | None, ) -> None: """Prime shared forces with the nested compute-hook lifecycle. Parameters ---------- batch : Batch Shared batch whose model outputs are initialized in-place. active_graph_mask : torch.Tensor | None Boolean mask selecting all active graphs. """ self._ensure_state_initialized(batch) status = batch.status if status.dim() == 2: status = status.squeeze(-1) status = status[: batch.num_graphs] stage_active_masks = [ status == status_code for status_code, _ in self.sub_stages ] with self._stream_scope(batch.device): self._call_hooks( DynamicsStage.BEFORE_COMPUTE, batch, active_graph_mask, ) for (_, dynamics), stage_active_mask in zip( self.sub_stages, stage_active_masks, strict=True ): dynamics._call_hooks( DynamicsStage.BEFORE_COMPUTE, batch, stage_active_mask, ) outputs = self.compute(batch, active_graph_mask) # Allocate every unmapped output's storage here, eagerly: this # is the one call to _publish_unmapped_outputs that runs before # any compiled step, so a key _step_impl sees for the first # time is never new to a compiled call — see that method's # docstring for why a never-seen key cannot be allocated there. self._publish_unmapped_outputs(batch, outputs, active_graph_mask) for (_, dynamics), stage_active_mask in zip( self.sub_stages, stage_active_masks, strict=True ): dynamics._call_hooks( DynamicsStage.AFTER_COMPUTE, batch, stage_active_mask, ) self._call_hooks( DynamicsStage.AFTER_COMPUTE, batch, active_graph_mask, ) # Clear reprime flags for graphs whose forces were just primed. pending = batch.reprime_pending.view(-1)[: batch.num_graphs] if active_graph_mask is None: pending.zero_() else: pending.logical_and_(~active_graph_mask)
[docs] def run( self, batch: Batch | None = None, n_steps: int | None = None ) -> Batch | None: """Run the fused stage until all samples converge or the sampler is exhausted. Supports two modes of execution: **Mode 1 (external batch loop):** When ``batch`` is provided, runs the dynamics until ``all_complete`` or until ``n_steps`` have been executed (whichever comes first). **Mode 2 (inflight batching):** When ``batch is None`` and a sampler is configured, builds the initial batch from the sampler and replaces graduated samples every ``refill_frequency`` steps. .. note:: In Mode 2, ``refill_check`` replaces graduated samples by extracting remaining graphs via :meth:`Batch.index_select`, requesting replacements from the sampler, and appending them via :meth:`Batch.append`. This produces a **new** ``Batch`` object; the ``batch = result`` reassignment in the loop body updates the local reference. ``None`` is returned when the sampler is exhausted and no active samples remain, which triggers termination. Parameters ---------- batch : Batch | None, optional The initial batch. If ``None``, uses the sampler to build one. n_steps : int | None, optional Maximum number of steps to run. When ``None``, falls back to ``self.n_steps``. When both are ``None``, the loop runs until ``all_complete`` (Mode 1) or sampler exhaustion (Mode 2). Sub-stages that have no exit criterion (e.g. a plain MD stage) will loop forever without a step limit, so always pass ``n_steps`` when such a stage is the final sub-stage. Note: sub-stages with ``n_steps`` set use that value as a per-system step budget for automatic migration to the next stage. Returns ------- Batch | None The batch after all steps, or ``None`` if the sampler was exhausted and all samples graduated. Raises ------ ValueError If ``batch is None`` and no sampler is configured. """ if batch is None: if self.sampler is None: raise ValueError("No batch provided and no sampler configured.") batch = self.sampler.build_initial_batch() if self.init_fn is not None: self.init_fn(batch) self.active_batch = batch # Ensure bookkeeping fields are present before the loop begins. self._ensure_bookkeeping_fields(batch) resolved_steps = n_steps if n_steps is not None else self.n_steps self._validate_n_steps(resolved_steps) self._open_hooks() try: # A run is a fresh admission even when the caller deliberately # reuses the same Batch object from an earlier run. self._admission_initialized = False for _, dynamics in self.sub_stages: dynamics._admission_initialized = False self._forces_primed = False step_num = 0 while True: batch, _converged = self.step(batch) if ( self.sampler is not None and (step_num + 1) % self.refill_frequency == 0 ): result = self.refill_check(batch, self.exit_status) if result is None: self.active_batch = None return None batch = result self.active_batch = batch elif ( self.sampler is None and (step_num + 1) % self.convergence_check_frequency == 0 and self.all_complete(batch, self.exit_status) ): break step_num += 1 if resolved_steps is not None and step_num >= resolved_steps: break return batch finally: self._close_hooks()
[docs] def refill_check(self, batch: Batch, exit_status: int) -> Batch | None: """Replace graduated samples and clear stale convergence indices. Delegates to the parent :meth:`BaseDynamics.refill_check` to remove graduated graphs and append replacements from the sampler. When the batch composition changes, ``_last_converged`` is cleared on this ``FusedStage`` and all its sub-stages so that subsequent hooks do not receive an invalid ``converged_mask``. In an already-primed stage, newly added graphs skip integrator updates for one iteration while the regular model evaluation computes their initial forces. Parameters ---------- batch : Batch The current batch with a ``status`` field. exit_status : int Status code indicating graduation. Returns ------- Batch | None A new batch with graduated graphs replaced by fresh samples, or ``None`` if no active samples remain. """ result = super().refill_check(batch, exit_status) # Clear stale convergence indices since the batch configuration has changed self._last_converged = None for _, dynamics in self.sub_stages: dynamics._last_converged = None return result
def __add__(self, other: BaseDynamics) -> FusedStage: """Append a sub-stage to this fused stage via ``fused + dyn``. Parameters ---------- other : BaseDynamics The dynamics to append to this fused stage. Returns ------- FusedStage A new fused stage with the additional sub-stage appended. Raises ------ TypeError If ``other`` is not a ``BaseDynamics`` instance. Notes ----- Compilation is deferred when composing via ``+``. If the source ``FusedStage`` had ``compile_step=True``, the returned stage preserves that intent but does **not** compile eagerly. Call ``.compile()`` explicitly or enter the context manager to trigger compilation. **Known limitation — retained composition.** This reuses ``self``'s existing sub-stage objects rather than copying them, and the returned ``FusedStage`` repoints every one of those sub-stages' ``_enclosing_hooks`` at its own ``hooks`` (see ``FusedStage.__init__``). If you keep running ``self`` *after* deriving a new stage from it, ``self``'s own hook-dependent behavior can silently change — e.g. a sub-stage's ``AlignCellHook``-on-``self`` detection now sees the derived stage's (possibly empty) hook list instead. Treat a ``FusedStage`` as consumed once you have composed a new stage from it; this is a known gap tracked for a future fix alongside stage nesting and hook/optimizer-state ownership, not something resolved here. """ if not isinstance(other, BaseDynamics): raise TypeError( "Cannot append stage: other must be a BaseDynamics instance. " f"Got {type(other).__name__} instead." ) next_code = len(self.sub_stages) new_sub_stages = list(self.sub_stages) + [(next_code, other)] new_fused = FusedStage( sub_stages=new_sub_stages, entry_status=self.entry_status, compile_step=False, compile_kwargs=self.compile_kwargs, by_group=self.by_group, ) # Defer compilation to __enter__ or an explicit .compile() call. new_fused.compile_step = self.compile_step return new_fused
[docs] class DistributedPipeline: """Orchestrates multi-rank pipeline execution. Maps GPU ranks to pipeline stages and coordinates the distributed step loop. Each rank executes only its assigned stage. Parameters ---------- stages : dict[int, BaseDynamics] Mapping from rank to its assigned pipeline stage. synchronized : bool If ``True``, insert a global ``dist.barrier()`` across **all** pipeline ranks after every ``step()`` call, forcing every rank to complete its current step before any rank proceeds to the next one. This is primarily useful for debugging ordering or deadlock issues because it eliminates all inter-rank timing skew. .. note:: This is distinct from the per-stage ``comm_mode`` parameter on ``_CommunicationMixin``, which controls the blocking behavior of *pairwise* ``isend``/``irecv`` between adjacent stages. ``synchronized`` enforces a *global* synchronization point across the entire pipeline and will significantly reduce throughput; it should be disabled (``False``) in production. Attributes ---------- stages : dict[int, BaseDynamics] Rank-to-stage mapping. synchronized : bool Whether a global ``dist.barrier()`` is inserted after every step. _dist_initialized : bool Whether this DistributedPipeline instance initialized the distributed process group (used to determine cleanup responsibility). Examples -------- >>> # Context manager usage (recommended): >>> pipeline = DistributedPipeline(stages={0: opt_stage, 1: md_stage}) >>> with pipeline: ... pipeline.run() ... >>> # Manual usage: >>> pipeline = DistributedPipeline(stages={0: opt_stage, 1: md_stage}) >>> pipeline.init_distributed() >>> pipeline.setup() >>> pipeline.run() >>> pipeline.cleanup() >>> # Composing multiple pipelines together >>> full_pipeline = pipe1 | pipe2 | pipe3 >>> with full_pipeline: ... pipeline.run() ... """ def __init__( self, stages: dict[int, BaseDynamics], synchronized: bool = False, debug_mode: bool = False, mesh: Any = None, **dist_kwargs: Any, ) -> None: """Initialize the pipeline. Parameters ---------- stages : dict[int, BaseDynamics] Mapping from **stage key** to pipeline stage. Without ``mesh`` the key is the global rank (one rank per stage — the classic streaming pipeline). With ``mesh`` the key is the **pipeline index** and each rank supplies only its own stage (a :class:`DomainParallel` bound to its domain sub-mesh); see ``mesh``. synchronized : bool, optional If ``True``, insert a global ``dist.barrier()`` across all pipeline ranks after every step, preventing any rank from advancing until all ranks have completed the current step. Useful for debugging but significantly reduces throughput. See the class-level docstring for how this differs from the per-stage ``comm_mode``. Default ``False``. debug_mode : bool, optional When ``True``, emit detailed ``loguru.debug`` diagnostics for inter-rank communication and pipeline orchestration. Propagated to all stages during ``setup()``. Default ``False``. mesh : DeviceMesh, optional A 2-D ``(pipeline, domain)`` mesh for **2-D-parallel dynamics**: each pipeline index is a *stage-group* — a whole domain sub-mesh row running one :class:`DomainParallel` stage. When given, the pipeline resolves ``local_stage`` by this rank's pipeline index, sizes completion by the number of pipeline stages, and wires each stage's ``prior``/``next`` to the adjacent stage-groups' **lead** ranks (domain-rank 0). ``None`` (default) keeps the classic one-rank-per-stage behavior unchanged. **dist_kwargs : Any Additional keyword arguments for ``torch.distributed.init_process_group``. """ dist_kwargs.setdefault( "backend", "nccl" if dist.is_nccl_available() else "gloo" ) self.stages = stages self.synchronized = synchronized self.mesh = mesh self._dist_initialized: bool = False self._dist_kwargs = dist_kwargs self._done_tensor: torch.Tensor | None = None self.debug_mode = debug_mode self._templates_shared: bool = False def __or__(self, other: BaseDynamics | DistributedPipeline) -> DistributedPipeline: """Append a stage or merge another pipeline via the ``|`` operator. Supports three composition patterns:: pipeline | dynamics # append one stage pipeline | pipeline # merge two pipelines dyn1 | dyn2 | dyn3 | ... # left-associative chaining Ranks in the resulting pipeline are renumbered to form a contiguous sequence. Source/sink dependencies (``prior_rank`` / ``next_rank``) are wired when ``setup()`` is called (e.g. via the context manager or ``run()``). Parameters ---------- other : BaseDynamics | DistributedPipeline A single dynamics stage to append, or another pipeline whose stages will be absorbed (renumbered) after this pipeline's stages. Returns ------- DistributedPipeline A new pipeline containing all stages with stages mapped to contiguous ranks. Raises ------ TypeError If ``other`` is not a ``BaseDynamics`` or ``DistributedPipeline`` instance. RuntimeError If ``torch.distributed`` is already initialized. Pipeline composition must occur before entering the pipeline context or calling ``run()``. """ if dist.is_initialized(): raise RuntimeError( "Cannot compose pipelines after torch.distributed has been " "initialized. Build the full pipeline topology before " "entering the pipeline context or calling run()." ) if isinstance(other, DistributedPipeline): base_rank = max(self.stages.keys()) + 1 new_stages = {**self.stages} for i, rank in enumerate(sorted(other.stages.keys())): new_stages[base_rank + i] = other.stages[rank] pipeline = DistributedPipeline( stages=new_stages, synchronized=self.synchronized or other.synchronized, **self._dist_kwargs, ) elif isinstance(other, BaseDynamics): next_rank = max(self.stages.keys()) + 1 new_stages = {**self.stages, next_rank: other} pipeline = DistributedPipeline( stages=new_stages, synchronized=self.synchronized, **self._dist_kwargs, ) else: raise TypeError( f"Right operand of | must be a BaseDynamics or " f"DistributedPipeline instance, got {type(other).__name__}." ) return pipeline def _validate_world_size(self) -> None: """Validate that the distributed world size matches the expected ranks. Compares ``torch.distributed.get_world_size()`` against the number of configured pipeline stages. A mismatch indicates that the ``torchrun`` launch configuration does not match the pipeline topology. This method is a no-op if ``torch.distributed`` is not initialized (e.g., during local testing). Raises ------ RuntimeError If the world size does not match the number of configured pipeline stages. """ if not dist.is_initialized(): return world_size = dist.get_world_size() if self._grouped: # 2-D: world == n_pipeline × domain_size (the whole mesh). expected = int(self.mesh.mesh.numel()) if world_size != expected: raise RuntimeError( f"DistributedPipeline(mesh=...) expects {expected} ranks " f"(pipeline={self._n_stages} × domain=" f"{int(self.mesh['domain'].size())}), but torch.distributed " f"world_size is {world_size}." ) return expected = len(self.stages) if world_size != expected: raise RuntimeError( f"DistributedPipeline expects {expected} ranks (stages configured " f"for ranks {sorted(self.stages.keys())}), but " f"torch.distributed world_size is {world_size}. " )
[docs] def setup(self) -> None: """Wire up ``prior_rank`` / ``next_rank`` between adjacent stages. Sorts stages by rank and connects each stage to its predecessor and successor. Raises ------ ValueError If fewer than 2 stages are provided, or if adjacent stages have mismatched buffer configurations. RuntimeError If the world size does not match the number of configured pipeline stages. """ if self._grouped: self._setup_grouped() return sorted_ranks = sorted(self.stages.keys()) if len(sorted_ranks) < 2: raise ValueError("Pipeline requires at least 2 stages.") self._validate_world_size() for i, rank in enumerate(sorted_ranks): stage = self.stages[rank] if stage.prior_rank == -1: stage.prior_rank = sorted_ranks[i - 1] if i > 0 else None if stage.next_rank == -1: stage.next_rank = ( sorted_ranks[i + 1] if i < len(sorted_ranks) - 1 else None ) for i in range(len(sorted_ranks) - 1): rank = sorted_ranks[i] next_rank = sorted_ranks[i + 1] sender = self.stages[rank] receiver = self.stages[next_rank] s_cfg = getattr(sender, "buffer_config", None) r_cfg = getattr(receiver, "buffer_config", None) if s_cfg is None or r_cfg is None: raise ValueError( "All stages in a DistributedPipeline must have buffer_config set. " f"Stage on rank {rank} has buffer_config={s_cfg}, " f"stage on rank {next_rank} has buffer_config={r_cfg}." ) if s_cfg != r_cfg: raise ValueError( f"Buffer configuration mismatch between rank {rank} " f"and rank {next_rank}: sender has " f"BufferConfig(num_systems={s_cfg.num_systems}, " f"num_nodes={s_cfg.num_nodes}, num_edges={s_cfg.num_edges}), " f"receiver has " f"BufferConfig(num_systems={r_cfg.num_systems}, " f"num_nodes={r_cfg.num_nodes}, num_edges={r_cfg.num_edges}). " f"Adjacent stages must use identical buffer configurations." ) n_stages = len(sorted_ranks) device = self.local_stage.device self._done_tensor = torch.zeros(n_stages, dtype=torch.int32, device=device) # move model to device if it isn't there already model = self.local_stage.model if not callable(getattr(model, "to", None)): raise RuntimeError( "Model expected to possess `to()` method for device" f" and casting behavior. Passed model is type {type(model)}" " so ensure class contains this method." ) else: self.local_stage.model = model.to(device) for stage in self.stages.values(): stage.debug_mode = self.debug_mode local_stage = self.local_stage local_n_steps = getattr(local_stage, "n_steps", None) if local_n_steps is not None and not isinstance(local_stage, FusedStage): warnings.warn( f"{type(local_stage).__name__}(n_steps={local_n_steps}) is a " "plain DistributedPipeline stage. Its n_steps value is used by " "run(), but pipeline execution calls step() and graduates systems " "only through convergence. Wrap fixed-duration stages in a " "FusedStage to apply a per-system step budget.", UserWarning, stacklevel=2, )
def _setup_grouped(self) -> None: """Wire a 2-D ``(pipeline, domain)`` pipeline: each rank runs the one stage for its pipeline index (a :class:`DomainParallel` over its domain sub-mesh), and its ``prior``/``next`` point at the adjacent stage-groups' **lead** global ranks (domain-rank 0). Only the lead transmits cross-stage; non-lead ranks need the endpoints non-``None``/``None`` merely to select the right branch (``DomainParallel`` gates the actual send/recv on the lead). ``_done_tensor`` is sized by the number of pipeline stages and indexed by pipeline index.""" if self._n_stages < 2: raise ValueError("Pipeline requires at least 2 stages.") self._validate_world_size() from nvalchemi.distributed._core.gather_primitives import mesh_group pidx = self._pipeline_index stage = self.local_stage last = self._n_stages - 1 if stage.prior_rank == -1: stage.prior_rank = None if pidx == 0 else self._lead_global_rank(pidx - 1) if stage.next_rank == -1: stage.next_rank = None if pidx == last else self._lead_global_rank(pidx + 1) # Cross-stage hand-offs ride the PIPELINE-dim group (the leads' group), never # the world group: under NCCL, ops on a communicator must be issued in the # same order on every member, so a 2-rank lead↔lead P2P on the world group # would interleave inconsistently with the 4-rank done-sync all-reduce and # deadlock. Confining it to the pipeline group also routes it over IB # between paired leads on multi-node (proposal §0). The world group is then # used only by _sync_done_flags (symmetric across all ranks). stage._pipeline_group = mesh_group(self.mesh["pipeline"]) device = stage.device self._done_tensor = torch.zeros( self._n_stages, dtype=torch.int32, device=device ) model = stage.model if callable(getattr(model, "to", None)): stage.model = model.to(device) stage.debug_mode = self.debug_mode def _share_templates(self) -> None: """Compute batch schema templates for all stages via local iteration. Since ``DistributedPipeline`` has all stages in ``self.stages`` on every rank, templates can be computed locally without inter-rank communication. Inflight (first) stages build their initial batch from the sampler and cache an ``empty_like`` template. Downstream stages derive their template from the upstream stage's cached template. This method is idempotent; repeated calls are no-ops once templates have been computed. """ if self._templates_shared: return self._templates_shared = True if self._grouped: self._share_templates_grouped() return for rank in sorted(self.stages.keys()): stage = self.stages[rank] if stage.is_first_stage and stage.inflight_mode: if stage.active_batch is None: stage.active_batch = stage.sampler.build_initial_batch() if stage.active_batch is not None: if stage.active_batch.device != stage.device: stage.active_batch = stage.active_batch.to(stage.device) stage._recv_template = Batch.empty_like( stage.active_batch, device=stage.device ) if self.debug_mode: logger.debug( "[rank {}] computed template from inflight sampler", rank, ) elif stage.prior_rank is not None: upstream = self.stages[stage.prior_rank] if upstream._recv_template is not None: stage._recv_template = Batch.empty_like( upstream._recv_template, device=stage.device ) if self.debug_mode: logger.debug( "[rank {}] computed template from upstream rank {}", rank, stage.prior_rank, ) def _share_templates_grouped(self) -> None: """Establish each stage-group's handoff receive template (2-D mode). Grouped stages are not co-located (each rank holds only its own stage), so templates can't be derived locally as in :meth:`_share_templates`. Instead: * The first stage partitions its seed **now** (reused as its initial owned batch — not thrown away) and gathers once to derive the exact handoff schema, then builds an empty CPU template (``Batch.irecv`` uses a template only for field names/dtypes/shapes; the receive buffers are allocated on the receiver's device, so a CPU template is correct and cheap to ship). * That empty template is passed **lead → lead** along the pipeline dim (each stage's dynamics preserves the batch schema), so every downstream stage's lead gets its ``_recv_template`` before the first real handoff. Only leads (domain-rank 0) participate in the cross-stage object transfer; the domain-group partition/gather of the first stage is collective over its row. Downstream stage-groups do **not** partition at setup (they partition on receipt), so there is no redundant re-partition on a receiver. """ from nvalchemi.data import Batch from nvalchemi.distributed._core.gather_primitives import mesh_group pidx = self._pipeline_index stage = self.local_stage is_lead = int(self.mesh["domain"].get_local_rank()) == 0 last = self._n_stages - 1 # Template propagation rides the pipeline-dim (leads') group, same as the # hand-off — never the world group (see _setup_grouped). pipe_group = mesh_group(self.mesh["pipeline"]) tmpl: Batch | None = None if pidx == 0: seed = getattr(stage, "_pending_input", None) stage.active_batch = stage.partition(seed if is_lead else None) if hasattr(stage, "_first_stage_seeded"): stage._first_stage_seeded = True stage._pending_input = None full = stage.gather(stage.active_batch, dst=0) if is_lead and full is not None: tmpl = Batch.empty_like(full, device="cpu") if is_lead: if pidx > 0: box: list[Any] = [None] dist.recv_object_list( box, src=self._lead_global_rank(pidx - 1), group=pipe_group ) tmpl = box[0] stage._recv_template = tmpl if pidx < last: dist.send_object_list( [tmpl], dst=self._lead_global_rank(pidx + 1), group=pipe_group ) @property def local_rank(self) -> int: """Get the local rank for this process.""" rank = 0 if dist.is_initialized(): rank = dist.get_node_local_rank() return rank @property def global_rank(self) -> int: """Get the global rank for this process.""" rank = 0 if dist.is_initialized(): rank = dist.get_rank() return rank # ------------------------------------------------------------------ # 2-D-parallel (pipeline × domain) resolution. All grouped-mode logic is # gated on ``self.mesh``; without it every property below reduces to the # classic one-rank-per-stage behavior. # ------------------------------------------------------------------ @property def _grouped(self) -> bool: """Whether this pipeline runs 2-D-parallel (stage = domain sub-mesh).""" return self.mesh is not None @property def _pipeline_index(self) -> int: """This rank's pipeline stage index (grouped mode).""" return int(self.mesh["pipeline"].get_local_rank()) @property def _n_stages(self) -> int: """Number of pipeline stages: pipeline-dim size (grouped) or #stages.""" return int(self.mesh["pipeline"].size()) if self._grouped else len(self.stages) def _lead_global_rank(self, pipeline_index: int) -> int: """Global rank of a stage-group's lead (domain-rank 0). ``mesh.mesh`` is the ``(n_pipeline, domain_size)`` global-rank layout; column 0 is the leads.""" return int(self.mesh.mesh[pipeline_index, 0]) @property def _stage_slot(self) -> int: """Index into ``_done_tensor`` for this rank: pipeline index (grouped) or global rank (classic).""" return self._pipeline_index if self._grouped else self.global_rank @property def local_stage(self) -> BaseDynamics: """Get the stage associated with the rank this is executed on.""" return self.stages[self._pipeline_index if self._grouped else self.global_rank]
[docs] def step(self) -> None: """Execute one timestep for the local rank's stage. The stage (a ``BaseDynamics`` subclass) handles both the dynamics step and buffer synchronization. Supports two modes for the first stage: **Mode 1 (external batch loop):** Standard flow where the first stage receives from ``_prestep_sync_buffers`` like other stages. **Mode 2 (inflight batching):** When the first stage has ``inflight_mode=True`` (i.e., a sampler is configured), it builds the initial batch from the sampler and refills graduated samples instead of receiving from a prior stage. When ``self.synchronized`` is ``True``, a global ``dist.barrier()`` is issued at the end of each step so that no rank advances until every rank in the pipeline has finished the current step. Raises ------ RuntimeError If ``torch.distributed`` is not initialized, or if the world size does not match the number of configured pipeline stages. KeyError If the current rank is not in the global rank stage mapping. """ if not dist.is_initialized(): raise RuntimeError( "torch.distributed is not initialized. " "Call torch.distributed.init_process_group() first." ) rank = self.global_rank slot = self._stage_slot if slot not in self.stages: raise KeyError( f"{'Pipeline index' if self._grouped else 'Rank'} {slot} is not " "assigned to any pipeline stage." ) stage = self.local_stage stage_type = type(stage).__name__ if stage.is_first_stage and stage.inflight_mode: n_graphs = stage.active_batch.num_graphs if stage.active_batch else 0 if self.debug_mode: logger.debug( "[rank {}] inflight step begin | stage={} batch_size={}", rank, stage_type, n_graphs, ) if stage.active_batch is None and not stage.done: try: stage.active_batch = stage.sampler.build_initial_batch() except RuntimeError: stage.active_batch = None if stage.active_batch is not None: if stage.active_batch.device != stage.device: stage.active_batch = stage.active_batch.to(stage.device) stage._admission_initialized = False stage._forces_primed = False if self.debug_mode: logger.debug( "[rank {}] built initial batch, {} graphs", rank, stage.active_batch.num_graphs, ) else: if self.debug_mode: logger.debug( "[rank {}] sampler exhausted at build, marking done", rank ) stage.done = True if stage.active_batch is not None: stage._ensure_buffers(stage.active_batch) elif stage._recv_template is not None: stage._ensure_buffers(stage._recv_template) if stage.active_batch is not None: stage.active_batch, converged_indices = stage.step(stage.active_batch) n_conv = ( converged_indices.numel() if converged_indices is not None else 0 ) if self.debug_mode: logger.debug( "[rank {}] step done | converged={} remaining={}", rank, n_conv, stage.active_batch.num_graphs if stage.active_batch else 0, ) stage._poststep_sync_buffers(converged_indices) if hasattr(stage, "exit_status"): exit_status = stage.exit_status else: exit_status = 1 if stage.active_batch is not None: result = stage.refill_check(stage.active_batch, exit_status) stage.active_batch = result if result is None: if self.debug_mode: logger.debug( "[rank {}] sampler exhausted, marking done", rank ) stage.done = True else: if self.debug_mode: logger.debug( "[rank {}] active_batch is None after poststep, " "rebuilding from sampler", rank, ) try: stage.active_batch = stage.sampler.build_initial_batch() except RuntimeError: stage.active_batch = None if stage.active_batch is not None: if stage.active_batch.device != stage.device: stage.active_batch = stage.active_batch.to(stage.device) # Run one-time admission and force priming for the new batch. stage._admission_initialized = False stage._forces_primed = False else: if self.debug_mode: logger.debug( "[rank {}] sampler exhausted, marking done", rank ) stage.done = True elif stage.next_rank is not None: if self.debug_mode: logger.debug( "[rank {}] done, sending empty buffer to rank {}", rank, stage.next_rank, ) stage._poststep_sync_buffers(None) else: n_graphs = stage.active_batch.num_graphs if stage.active_batch else 0 if self.debug_mode: logger.debug( "[rank {}] downstream step begin | stage={} batch_size={}", rank, stage_type, n_graphs, ) if stage.active_batch is not None: stage._ensure_buffers(stage.active_batch) stage._prestep_sync_buffers() stage._complete_pending_recv() converged_indices = None if stage.active_batch is not None and stage.active_batch.num_graphs > 0: stage.active_batch, converged_indices = stage.step(stage.active_batch) n_conv = ( converged_indices.numel() if converged_indices is not None else 0 ) if self.debug_mode: logger.debug( "[rank {}] step done | converged={} remaining={}", rank, n_conv, stage.active_batch.num_graphs if stage.active_batch else 0, ) elif stage.active_batch is not None: if self.debug_mode: logger.debug( "[rank {}] skipping step, active_batch has 0 graphs", rank ) stage._poststep_sync_buffers(converged_indices) # Auto-terminate downstream stages: if the upstream is done # and this stage has no remaining work, mark it as done. n_active = ( stage.active_batch.num_graphs if stage.active_batch is not None else 0 ) # ``_done_tensor`` is indexed by stage slot (pipeline index in grouped # mode, global rank classically); the upstream slot is the prior # pipeline index (grouped) or the prior global rank (``prior_rank``). upstream_slot = ( self._pipeline_index - 1 if self._grouped else stage.prior_rank ) upstream_done = ( self._done_tensor is not None and stage.prior_rank is not None and upstream_slot is not None and upstream_slot >= 0 and bool(self._done_tensor[upstream_slot]) ) if upstream_done and n_active == 0 and not stage.done: if self.debug_mode: logger.debug( "[rank {}] upstream rank {} done and no active work, marking done", rank, stage.prior_rank, ) stage.done = True if self.synchronized: if self.debug_mode: logger.debug("[rank {}] waiting at barrier", rank) dist.barrier()
def _sync_done_flags(self) -> bool: """Synchronize ``done`` flags across all ranks via ``all_reduce``. Each rank writes its local stage's ``done`` status into the shared ``_done_tensor`` at its position, then an ``all_reduce`` (``MAX``) broadcasts the flags so every rank sees the global state. Returns ------- bool ``True`` if **all** stages report ``done``. """ if self._done_tensor is None: raise RuntimeError("_done_tensor is not initialized. Call setup() first.") stage = self.local_stage # Slot = pipeline index (grouped) or global rank (classic). In grouped mode # every rank of a stage-group writes the same slot; the group's ``done`` is # kept consistent across its ranks (sentinel broadcast / seed exhaustion), # so the MAX all-reduce yields the correct per-stage completion. self._done_tensor[self._stage_slot] = int(stage.done) if dist.is_initialized(): dist.all_reduce(self._done_tensor, op=dist.ReduceOp.MAX) all_done = bool(self._done_tensor.all()) if self.debug_mode: logger.debug( "[rank {}] done_flags={} all_done={}", self.global_rank, self._done_tensor.tolist(), all_done, ) return all_done
[docs] def run(self) -> None: """Run the pipeline loop until all stages report done. After each ``step()``, an ``all_reduce`` synchronizes the ``done`` flags across all ranks so that every process can observe the global termination state. """ self.setup() self._share_templates() if self._grouped: self._run_grouped() return iteration = 0 while True: if self.debug_mode: logger.debug( "[rank {}] === pipeline iteration {} ===", self.global_rank, iteration, ) self.step() if self._sync_done_flags(): if self.debug_mode: logger.debug("[rank {}] all stages done, exiting", self.global_rank) break iteration += 1
def _run_grouped(self) -> None: r"""Run a 2-D (pipeline :math:`\times` domain) pipeline until each stage-group is done. Unlike the streaming pipeline, a grouped stage does **not** step in global lockstep: a downstream stage blocks in its ``_prestep`` hand-off until the upstream produces a whole system, so a per-iteration world all-reduce (``_sync_done_flags``) would deadlock (the upstream calls it while the downstream is still blocked on the hand-off). Instead each rank loops its own stage until that stage is locally ``done`` — termination flows down the pipeline via the sentinel chain (on the pipeline-dim group), and the only world-group op is a single closing ``barrier`` so no rank tears down the process group while another is mid-collective. Every per-step collective is confined to the stage's domain group or the pipeline-dim hand-off group, so the groups run at independent paces and synchronize only at hand-offs. """ stage = self.local_stage while not stage.done: self.step() if dist.is_initialized(): dist.barrier()
[docs] def init_distributed(self) -> None: """Initialize the ``torch.distributed`` process group. If ``torch.distributed`` is already initialized, this method is a no-op. Otherwise, it calls ``torch.distributed.init_process_group(**self._dist_kwargs)``. The backend and other distributed options are configured via the constructor's ``**dist_kwargs`` parameter. Notes ----- When launching with ``torchrun``, the process group is typically already initialized. This method provides a convenient fallback for scripts that do not use ``torchrun``. """ if dist.is_initialized(): return dist.init_process_group(**self._dist_kwargs) self._dist_initialized = True
[docs] def cleanup(self, *, error: bool = False) -> None: """Destroy the ``torch.distributed`` process group. Only destroys the process group if it was initialized by this ``DistributedPipeline`` instance (via :meth:`init_distributed`). If the process group was externally initialized (e.g., by ``torchrun``), this method is a no-op. Parameters ---------- error : bool, optional Set when unwinding an exception. The process group is then left alone: tearing it down blocks while peer ranks are still inside a collective, which would swallow the exception and hang the job. Letting the exception propagate lets the launcher terminate the peers instead. Default ``False``. """ if error: return if self._dist_initialized and dist.is_initialized(): dist.destroy_process_group() self._dist_initialized = False
def __enter__(self) -> DistributedPipeline: """Enter the pipeline context manager. Calls :meth:`init_distributed` and :meth:`setup` in sequence. The ``setup()`` call also initializes the distributed ``_done_tensor`` used for coordinated termination. Returns ------- DistributedPipeline This pipeline instance. """ self.init_distributed() self.setup() self._share_templates() return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any, ) -> None: """Exit the pipeline context manager. Calls :meth:`cleanup` to destroy the process group if it was initialized by this pipeline. When the block exits with an exception, the process group is not torn down (see :meth:`cleanup`) and the exception propagates. Parameters ---------- exc_type : type[BaseException] | None Exception type, if any. exc_val : BaseException | None Exception value, if any. exc_tb : Any Exception traceback, if any. """ self.cleanup(error=exc_type is not None)