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_configattribute — aModelConfiginstance set in__init__.embedding_shapesproperty — 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 toModelOutputsordered dict.narrowed_outputs()— narrowactive_outputsfor 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_gradon tensors that need gradients (determined bymodel_config.autograd_inputsandmodel_config.gradient_keys), then collects all keys declared byinput_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
ModelOutputsformat.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
Noneif 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:
- 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 theatoms x atomsproduct level. To keep a simulation batch unchanged, supply a separate analysis batch with its required neighbor data already prepared. For systemi, 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 isd^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.
Noneuses 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
hessianfield.- Return type:
- 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-modelactive_outputsso it can compute them via autograd on the summed energy. Keys returned by this method are kept inactive_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
DistributedModelwhen entering a distributed scope, after the spec’s adapters have been installed.ctxis theDistributedContextthat the framework will mutate per-step (ctx.halo_meta/ctx.gather_meta); the wrapper should stash a reference toctx(commonly asself._dist_ctx) so itsadapt_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
MLIPSpecdescribing the primitives this model needs under domain parallelism for the given parallelization strategy.- Parameters:
strategy (StrategyKind | None) – The
StrategyKindthe scope runs under (HALO/GRAPH_PARTITION);Noneis treated asHALO. 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.DomainParallelraises if asked to shard a model whose spec isNone. 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
BaseModelMixininterface.- 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) @ vectorsfor 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
Falsereturns a detached product.
- Returns:
Hessian-vector product aligned with
batch.positions.- Return type:
- Raises:
TypeError – If
batchis not aBatchorvectorsis 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 (fromneighbor_config),pbc(ifneeds_pbc), and any extra keys inmodel_config.required_inputs.Optional inputs (
model_config.optional_inputs) are handled separately inadapt_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
NeighborListHookinstances 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
nvalchemiopsneighbor-list method to use. WhenNone(default), the hook selects an appropriate method.
- Return type:
list
- narrowed_outputs(outputs)[source]#
Compute only outputs for the duration of a block.
active_outputsis 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_outputsis 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_outputswithoutputs. 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:
- Raises:
TypeError – If
batchis not aBatch.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.
Truewhen at least one ofmodel_config.active_outputsis inmodel_config.autograd_outputs, meaning the model produces it by differentiating its forward.adapt_input()marks theautograd_inputsrequires_gradunder the same condition, so a caller that runs the model undertorch.no_grad()reads this first. A model that only publishes direct outputs reportsFalse.- 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> = valuewith validation that the field exists and is mutable.- Parameters:
key (str) – Name of a mutable
ModelConfigfield (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