nvalchemi.models.base.BaseModelMixin#

class nvalchemi.models.base.BaseModelMixin[source]#

Abstract mixin providing a standardized interface for model wrappers.

All external MLIP wrappers should inherit from this mixin (alongside nn.Module) to ensure a consistent interface for dynamics engines, composition pipelines, and downstream tooling.

Concrete implementations must provide:

  • model_config attribute — a ModelConfig instance set in __init__.

  • embedding_shapes property — expected shapes of computed embeddings.

  • compute_embeddings() — compute and attach embeddings to the input data structure.

The mixin provides default implementations of:

  • input_data() — set of required input keys derived from the model config.

  • output_data() — set of active outputs intersected with supported outputs (warns on unsupported requests).

  • adapt_input() — enable gradients on required tensors and collect input dict.

  • adapt_output() — map raw model output to ModelOutputs ordered dict.

  • narrowed_outputs() — narrow active_outputs for the duration of a block and restore it afterwards.

  • requires_autograd — whether the active outputs include one the model differentiates for, so its forward needs autograd enabled.

adapt_input(data, **kwargs)[source]#

Adapt framework batch data to external model input format.

The base implementation enables requires_grad on tensors that need gradients (determined by model_config.autograd_inputs and model_config.gradient_keys), then collects all keys declared by input_data() into a dict.

Subclasses should call super().adapt_input(data) and then add or transform entries as needed for their underlying model.

Parameters:
  • data (AtomicData | Batch | AtomsLike) – Framework data structure.

  • kwargs (Any)

Returns:

Input in the format expected by the external model.

Return type:

dict[str, Any]

adapt_output(model_output, data)[source]#

Adapt external model output to ModelOutputs format.

Returns an OrderedDict keyed by output_data() entries, populated from model_output where keys match.

Note

Returned tensors may still be attached to the autograd computation graph (e.g. energies from autograd-force models like MACE). This is intentional — the model does not know whether the caller needs the graph (e.g. pipeline shared-autograd groups). Callers that do not need the graph are responsible for detaching.

Parameters:
  • model_output (Any) – Raw output from the external model.

  • data (AtomicData | Batch) – Original input data (may be needed for context/metadata).

Returns:

OrderedDict with expected output keys and their values (or None if not present). Tensors may be graph-attached.

Return type:

ModelOutputs

add_output_head(prefix)[source]#

Add an output head to the model.

Parameters:

prefix (str) – Prefix for the output head

Return type:

None

abstractmethod compute_embeddings(data, **kwargs)[source]#

Compute embeddings at different levels of a batch of atomic graphs.

Parameters:
  • data (AtomicData | Batch) – Input atomic data containing positions, atomic numbers, etc.

  • kwargs (Any)

Returns:

Data structure with embeddings attached in-place.

Return type:

AtomicData | Batch

Raises:

NotImplementedError – If the model does not support embeddings computation

compute_hessian(batch, *, strategy='vmap', row_chunk_size=None)[source]#

Materialize the dense Hessian on a batch in place.

The model evaluates an independent snapshot, then attaches or replaces batch["hessian"] on the atoms x atoms product level. To keep a simulation batch unchanged, supply a separate analysis batch with its required neighbor data already prepared. For system i, the logical field shape is [N_i, N_i, 3, 3] with axes [atom_out, atom_in, xyz_out, xyz_in]; the packed batch shape is [sum(N_i**2), 3, 3]. The detached result is d^2 E / dR^2, so the directional force Jacobian is -H @ v.

Neighbor membership is held fixed at the topology supplied by batch. The method does not run neighbor-list hooks or differentiate the discrete neighbor-selection operation.

Parameters:
  • batch (Batch) – Caller-owned batch to update after successful materialization.

  • strategy ({"vmap", "loop"}, optional) – Whether each row chunk uses batched vector-Jacobian products or evaluates one row at a time. Defaults to "vmap".

  • row_chunk_size (int, optional) – Maximum number of flattened Cartesian rows per chunk, within each system. None uses one chunk per system. "vmap" evaluates the chunk together; "loop" evaluates its rows individually.

Returns:

The same object supplied as batch, with a detached canonical hessian field.

Return type:

Batch

Raises:
  • TypeError – If batch or an argument has the wrong type.

  • ValueError – If tensor layout, storage declarations, strategy, or chunk size is incompatible with dense Hessian materialization.

  • DerivativeNotSupported – If this wrapper or execution context does not support the requested dense strategy.

  • RuntimeError – If energy does not satisfy the connected derivative contract.

direct_derivative_keys()[source]#

Return output keys this model computes analytically in forward().

When this model participates in a pipeline autograd group, the pipeline strips "forces" and "stress" from sub-model active_outputs so it can compute them via autograd on the summed energy. Keys returned by this method are kept in active_outputs — the pipeline collects them from the model output and sums them with the autograd-derived derivatives.

Override this in models that produce analytical forces or stress alongside an energy that carries autograd information (e.g. Ewald/PME with hybrid_forces=True).

Returns:

Keys (e.g. {"forces", "stress"}) that the model produces analytically and should be summed with autograd derivatives. Default: empty set (all derivatives come from autograd).

Return type:

set[str]

distributed_setup(ctx)[source]#

Called once by DistributedModel when entering a distributed scope, after the spec’s adapters have been installed. ctx is the DistributedContext that the framework will mutate per-step (ctx.halo_meta / ctx.gather_meta); the wrapper should stash a reference to ctx (commonly as self._dist_ctx) so its adapt_input() can read the live values at forward time.

Override to also build per-rank closures (e.g. distributed helper replacements that close over ctx.gather_meta) at scope-entry time.

Default: no-op. Simple halo-mode models (MACE, LJ) don’t override beyond stashing the ctx reference, which the default implementation handles for them — see _dist_ctx.

Parameters:

ctx (Any)

Return type:

None

distributed_teardown()[source]#

Restore anything distributed_setup() mutated. Default clears the ctx reference; override to also restore monkey-patches the framework’s adapter registry doesn’t manage.

Return type:

None

distribution_spec(strategy=None)[source]#

Return the MLIPSpec describing the primitives this model needs under domain parallelism for the given parallelization strategy.

Parameters:

strategy (StrategyKind | None) – The StrategyKind the scope runs under (HALO / GRAPH_PARTITION); None is treated as HALO. The framework passes the config-selected strategy — models must not sniff the environment. The spec content is a joint \((\mathrm{model} \times \mathrm{strategy})\) product, so a model that supports graph parallel returns a different (policy, adapters, shard_fields, consolidation) bundle per strategy.

Returns:

Default None = model doesn’t declare distributed support. DomainParallel raises if asked to shard a model whose spec is None. Per-model wrappers override to return a preset (SPEC_MPNN_HALO / SPEC_UMA_HALO) or a custom spec.

Return type:

MLIPSpec | None

abstract property embedding_shapes: dict[str, tuple[int, ...]]#

Retrieves the expected shapes of the node, edge, and graph embeddings.

export_model(path, as_state_dict=False)[source]#

Export the current model without the BaseModelMixin interface.

Parameters:
  • path (Path)

  • as_state_dict (bool)

Return type:

None

hessian_vector_product(batch, vectors, *, create_graph=False)[source]#

Compute a Hessian-vector product from one energy-only forward.

This evaluates (d^2 E / dR^2) @ vectors for the supplied, fixed neighbor topology. It does not rebuild neighbors or differentiate neighbor membership. The force directional derivative has the opposite sign.

Parameters:
  • batch (Batch) – Caller-owned batch to evaluate without mutation.

  • vectors (torch.Tensor) – One vector with the same shape, dtype, and device as batch.positions.

  • create_graph (bool, optional) – Keep the product attached to the graph of the forward this method runs, so a loss can backpropagate through it to the model parameters. Default False returns a detached product.

Returns:

Hessian-vector product aligned with batch.positions.

Return type:

torch.Tensor

Raises:
  • TypeError – If batch is not a Batch or vectors is not a floating-point tensor.

  • ValueError – If vector shape, dtype, or device does not match positions.

  • DerivativeNotSupported – If this wrapper or execution context does not support HVPs.

Notes

The forward pass runs on this wrapper directly, so a DDP wrapper around it does not see it and gradients from an attached product are not reduced across ranks. For that case, take the energy from the training forward and use HessianOperator.from_energy.

input_data()[source]#

Return the set of required input keys.

Base implementation derives keys from the model config: {positions, atomic_numbers} plus neighbor-list keys (from neighbor_config), pbc (if needs_pbc), and any extra keys in model_config.required_inputs.

Optional inputs (model_config.optional_inputs) are handled separately in adapt_input() and are NOT included here.

Returns:

Set of required input keys.

Return type:

set[str]

make_neighbor_hooks(max_neighbors=None, neighbor_list_method=None)[source]#

Return a list of NeighborListHook instances for this model’s neighbor configuration.

Returns an empty list if the model does not require a neighbor list. Defers the import to avoid circular imports.

Parameters:
  • max_neighbors (int | None, optional) – Maximum neighbors per atom for MATRIX format. When None (default), auto-estimated from the cutoff at first use.

  • neighbor_list_method (str | None, optional) – Explicit nvalchemiops neighbor-list method to use. When None (default), the hook selects an appropriate method.

Return type:

list

narrowed_outputs(outputs)[source]#

Compute only outputs for the duration of a block.

active_outputs is set to outputs on entry and restored on exit, whether the block returns or raises. A caller that needs one output of a model configured for several, such as an energy to differentiate twice while the forces stay off, narrows the pass this way and hands the model back as it found it.

Parameters:

outputs (Iterable[str]) – Output keys to leave active inside the block.

Yields:

None – Control while the narrowed active_outputs is in force.

Return type:

Iterator[None]

Examples

>>> with model.narrowed_outputs({"energy"}):
...     energy = model(batch)["energy"]
>>> "forces" in model.model_config.active_outputs
True
output_data()[source]#

Return the set of keys the model will compute this run.

Intersects active_outputs with outputs. Warns if any active keys are not supported by the model.

Returns:

Set of output keys that are both active and supported.

Return type:

set[str]

prepare_hessian(batch)[source]#

Prepare an immediately active matrix-free Hessian.

The operator represents the second derivative of total energy with respect to Cartesian positions, d^2 E / dR^2, at the supplied geometry. It copies the batch inputs and retains a derivative graph evaluated with the current model. Keep model parameters, buffers, execution mode, and pipeline wiring unchanged while using it. Close the operator explicitly or use it as a context manager.

Parameters:

batch (Batch) – Caller-owned batch to snapshot for repeated Hessian-vector products.

Returns:

Operator retaining one private derivative graph. Close it explicitly or use it as a context manager.

Return type:

HessianOperator

Raises:
  • TypeError – If batch is not a Batch.

  • DerivativeNotSupported – If this wrapper or execution context does not support HVPs.

  • RuntimeError – If energy does not satisfy the connected derivative contract.

property requires_autograd: bool#

Whether the model’s forward pass needs autograd enabled around it.

True when at least one of model_config.active_outputs is in model_config.autograd_outputs, meaning the model produces it by differentiating its forward. adapt_input() marks the autograd_inputs requires_grad under the same condition, so a caller that runs the model under torch.no_grad() reads this first. A model that only publishes direct outputs reports False.

Returns:

Whether an active output is computed by autograd.

Return type:

bool

Examples

>>> from nvalchemi.models.demo import DemoModel, DemoModelWrapper
>>> model = DemoModelWrapper(DemoModel())
>>> model.requires_autograd
True
>>> with model.narrowed_outputs({"energy"}):
...     model.requires_autograd
False
set_config(key, value)[source]#

Set a mutable field on model_config.

Convenience method equivalent to self.model_config.<key> = value with validation that the field exists and is mutable.

Parameters:
  • key (str) – Name of a mutable ModelConfig field (e.g. "active_outputs", "gradient_keys").

  • value (Any) – New value for the field.

Raises:

AttributeError – If key is not a field on ModelConfig.

Return type:

None