nvalchemi.dynamics.hooks.LoggingHook#
- class nvalchemi.dynamics.hooks.LoggingHook(backend, frequency=1, log_path=None, custom_scalars=None, writer_fn=None, stage=DynamicsStage.AFTER_STEP, *, by_group=False)[source]#
Log scalar observables with one row per graph or group.
At each firing step, this hook writes one row per graph by default. Graph rows include:
step — the current
dynamics.step_count.graph_idx — the graph’s index within the batch.
status — the sample’s status code (from
batch.status), indicating which pipeline stage it belongs to. Always0for single-stage dynamics.energy — per-graph potential energy (from
batch.energy).fmax — per-graph maximum atomic force norm.
temperature — per-graph instantaneous kinetic temperature (from
batch.velocitiesandbatch.atomic_massesvia the equipartition theorem), if velocities are present.
With
by_group=True, the batch must have aGroupLayout. Group rows containstep,group_idx, and the status of the first graph in each group. Graph-level energy, force, and temperature are not reduced automatically because their group-level meanings are application dependent.Users can extend or replace the logged scalars by providing a
custom_scalarsmapping of{name: callable}pairs. Each callable has signature(ctx) -> Tensorand returns one value per row, or returns a plainfloatthat is broadcast to every row.Asynchronous I/O. Scalar computation and the GPU-to-CPU transfer run on a dedicated CUDA side stream (set up in
__enter__()) so they do not stall the default compute stream. The D2H copy usesnon_blocking=True; the single-workerThreadPoolExecutorsynchronizes the stream before reading the CPU tensor and writing to the backend.Context manager. Use
withto guarantee the CUDA stream is created, all pending writes are flushed, and file handles are closed on exit:with LoggingHook(backend="csv", log_path="out.csv") as hook: dynamics.register_hook(hook) dynamics.run(batch)
This hook is non-blocking: scalar computation and the D2H transfer run on a dedicated CUDA side stream (when available), and all
.item()calls and I/O happen in a backgroundThreadPoolExecutorworker, so the GPU pipeline is not stalled.- Parameters:
backend ({"csv", "tensorboard", "custom"}) – Logging backend to use.
frequency (int, optional) – Log every
frequencysteps. Default1.log_path (str | Path | None, optional) – File path for file-based backends (
"csv","tensorboard"). DefaultNone.custom_scalars (dict[str, Callable] | None, optional) – Additional named scalars to compute and log. Each callable receives
(ctx,)— aDynamicsContext— and returns one tensor value per selected row, shape(B,)for graph rows or(G,)for group rows. Afloatis broadcast to every row. Name collisions override defaults. DefaultNone.writer_fn (Callable[[int, list[dict[str, float]]], None] | None, optional) – Custom writer function, required when
backend="custom". Receives(step_count, rows). DefaultNone.stage (enum.Enum, optional) – Dynamics stage at which to log. Default
AFTER_STEP. Logging atON_GRADUATEstill respectsfrequency.by_group (bool, optional) – Write one row per group instead of one row per graph. Group logging requires the batch to have a group layout and expects tensor-valued custom scalars with shape
(num_groups,). DefaultFalse.
Examples
>>> from nvalchemi.dynamics.hooks import LoggingHook >>> with LoggingHook(backend="csv", log_path="md_log.csv", frequency=100) as hook: ... dynamics = DemoDynamics(model=model, n_steps=10_000, dt=0.5, hooks=[hook]) ... dynamics.run(batch)
Using custom scalars:
>>> def pressure(ctx): ... return compute_pressure(ctx.batch.stress, ctx.batch.cell) >>> hook = LoggingHook( ... backend="csv", ... log_path="md_log.csv", ... frequency=50, ... custom_scalars={"pressure": pressure}, ... )
Notes
The default temperature calculation assumes an NVT-like system with
3Ndegrees of freedom (no constraint correction). Override viacustom_scalarsif constraints remove DOFs.For distributed pipelines, each rank logs independently. Use
log_pathwith rank-specific filenames to avoid file contention.