Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 119 additions & 4 deletions deepmd/dpmodel/atomic_model/base_atomic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,14 +535,22 @@ def _prepare_graph_inputs(
self,
graph: "NeighborGraph",
atype: Array,
node_mask: Array | None = None,
) -> tuple["NeighborGraph", Array, Array]:
"""Apply graph masks shared by standard and fused atomic forwards."""
"""Apply graph masks shared by the standard, fused and embedding forwards.

``node_mask`` is the flat mask of the nodes an enclosing model counts;
it is combined with the output mask of this model, and ``None``
imposes nothing further.
"""
atype_clamped, output_mask = self._prepare_graph_nodes(
graph.n_node,
graph.n_local,
atype,
graph.edge_vec,
)
if node_mask is not None:
output_mask = output_mask & node_mask
self._assert_graph_pair_excluded(graph, atype_clamped)
return graph, atype_clamped, output_mask

Expand Down Expand Up @@ -607,9 +615,9 @@ def forward_common_atomic_graph(
the result dict on the flat node axis, defined by the `FittingOutputDef`.

"""
graph, atype_clamped, output_mask = self._prepare_graph_inputs(graph, atype)
if node_mask is not None:
output_mask = output_mask & node_mask
graph, atype_clamped, output_mask = self._prepare_graph_inputs(
graph, atype, node_mask
)
ret_dict = self.forward_atomic_graph(
graph,
atype_clamped,
Expand All @@ -623,6 +631,113 @@ def forward_common_atomic_graph(
)
return self._finalize_atomic_ret(ret_dict, output_mask, atype)

def forward_common_embedding_graph(
self,
graph: "NeighborGraph",
atype: Array,
fparam: Array | None = None,
aparam: Array | None = None,
charge_spin: Array | None = None,
node_mask: Array | None = None,
) -> dict[str, Array]:
"""Embeddings on the flat node axis, from a forward without derivatives.

The embedding analogue of :meth:`forward_common_atomic_graph`: the
same masks select the counted nodes, and
:meth:`forward_embedding_graph` evaluates the embeddings. The per-node
embeddings of a virtual atom (type < 0) read zero, while an excluded
atom keeps them and is left out of the structural feature only.

Parameters
----------
graph
neighbor graph for the local atoms (ghost-free)
atype
flat local atom types. N
fparam
frame parameter. nf x ndf
aparam
atomic parameter. N x nda
charge_spin
frame-level charge/spin conditioning, forwarded to the descriptor
as on :meth:`forward_common_atomic_graph`.
node_mask
flat mask of the nodes an enclosing model counts (real, owned and
not excluded there), combined with this model's own; ``None``
imposes nothing further.

Returns
-------
dict[str, Array]
``descriptor`` with shape (N, d); ``atomic_feature``, the
activation after the last hidden layer of the fitting network,
with shape (N, h); and ``structural_feature``, the sum of
``atomic_feature`` over the counted nodes of every frame, with
shape (nf, h).
"""
xp = array_api_compat.array_namespace(graph.edge_vec)
graph, atype_clamped, output_mask = self._prepare_graph_inputs(
graph, atype, node_mask
)
ret = self.forward_embedding_graph(
graph,
atype_clamped,
output_mask,
fparam=fparam,
aparam=aparam,
charge_spin=charge_spin,
)
real = self.make_atom_mask(atype)[:, None]
for key in ("descriptor", "atomic_feature"):
ret[key] = xp.where(real, ret[key], xp.zeros_like(ret[key]))
return ret

def forward_embedding_graph(
self,
graph: "NeighborGraph",
atype: Array,
node_mask: Array,
fparam: Array | None = None,
aparam: Array | None = None,
charge_spin: Array | None = None,
) -> dict[str, Array]:
"""Evaluate the embeddings of :meth:`forward_common_embedding_graph`.

Only an atomic model with a learned descriptor and fitting network has
embeddings; such a model overrides this method.

Parameters
----------
graph
neighbor graph for the local atoms (ghost-free)
atype
flat local atom types, clamped to valid types. N
node_mask
flat mask of the counted nodes, over which the structural feature
sums. N
fparam
frame parameter. nf x ndf
aparam
atomic parameter. N x nda
charge_spin
frame-level charge/spin conditioning.

Returns
-------
dict[str, Array]
The embeddings of :meth:`forward_common_embedding_graph`.

Raises
------
NotImplementedError
For an atomic model without a learned descriptor and fitting
network.
"""
raise NotImplementedError(
f"{type(self).__name__} has no learned descriptor and fitting "
"network, so it provides no embedding."
)

def _assert_nlist_pair_excluded(self, nlist: Array, extended_atype: Array) -> None:
"""Fail-safe: assert the nlist reaching the dense seam is pre-excluded.

Expand Down
75 changes: 74 additions & 1 deletion deepmd/dpmodel/atomic_model/dp_atomic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,7 @@ def forward_atomic_graph(
comm_dict: dict | None = None,
topologies: dict[str, Any] | None = None,
node_mask: Array | None = None,
return_atomic_feature: bool = False,
) -> dict[str, Array]:
"""Graph analogue of :meth:`forward_atomic` on the flat node axis.

Expand Down Expand Up @@ -709,11 +710,18 @@ def forward_atomic_graph(
node_mask
flat mask of the real and owned nodes, which carry the fields of
the long-range module.
return_atomic_feature
whether the forward stops after the fitting network and returns
the embeddings of the nodes instead of the fitting output; the
long-range module is then not evaluated.

Returns
-------
result_dict
the result dict on the flat node axis, defined by the `FittingOutputDef`.
the result dict on the flat node axis, defined by the `FittingOutputDef`;
with ``return_atomic_feature``, the ``descriptor`` (N, d) and the
``atomic_feature`` (N, h), the activation after the last hidden
layer of the fitting network.

"""
from deepmd.dpmodel.utils.neighbor_graph import (
Expand Down Expand Up @@ -804,6 +812,7 @@ def forward_atomic_graph(
# its type, so along the closing of a pair the learned energy follows
# the switch linearly while the analytical pair term takes over.
gate_kwargs = {} if node_gate is None else {"node_gate": node_gate}
middle_kwargs = {"return_middle_output": True} if return_atomic_feature else {}
ret = self.fitting_net.call_graph(
gg,
atype,
Expand All @@ -814,7 +823,12 @@ def forward_atomic_graph(
aparam=aparam_node,
**vacuum_kwargs,
**gate_kwargs,
**middle_kwargs,
)
# The embeddings are the descriptor and the last hidden activation of
# the fitting network, which the long-range module does not change.
if return_atomic_feature:
return {"descriptor": gg, "atomic_feature": ret["middle_output"]}
# === Step 5. Long-range module ===
# The module reads the descriptor of the real nodes; the reference
# nodes appended above take no part in it.
Expand All @@ -837,6 +851,65 @@ def forward_atomic_graph(
)
return ret

def forward_embedding_graph(
self,
graph: "NeighborGraph",
atype: Array,
node_mask: Array,
fparam: Array | None = None,
aparam: Array | None = None,
charge_spin: Array | None = None,
) -> dict[str, Array]:
"""Descriptor, atomic feature and structural feature of the nodes.

The forward of :meth:`forward_atomic_graph` stops after the fitting
network, and the structural feature sums the atomic feature over the
counted nodes of every frame.

Parameters
----------
graph
neighbor graph for the local atoms (ghost-free)
atype
flat local atom types, clamped to valid types. N
node_mask
flat mask of the counted nodes, over which the structural feature
sums. N
fparam
frame parameter. nf x ndf
aparam
atomic parameter. N x nda
charge_spin
frame-level charge/spin conditioning.

Returns
-------
dict[str, Array]
``descriptor`` (N, d), ``atomic_feature`` (N, h) and
``structural_feature`` (nf, h).
"""
from deepmd.dpmodel.utils.neighbor_graph import (
frame_id_from_n_node,
segment_sum,
)

xp = array_api_compat.array_namespace(graph.edge_vec)
ret = self.forward_atomic_graph(
graph,
atype,
fparam=fparam,
aparam=aparam,
charge_spin=charge_spin,
return_atomic_feature=True,
)
atomic_feature = ret["atomic_feature"]
ret["structural_feature"] = segment_sum(
xp.where(node_mask[:, None], atomic_feature, xp.zeros_like(atomic_feature)),
frame_id_from_n_node(graph.n_node, n_total=atype.shape[0]),
graph.n_node.shape[0],
)
return ret

def _frame_conditions(
self,
fparam: Array | None,
Expand Down
94 changes: 84 additions & 10 deletions deepmd/dpmodel/atomic_model/linear_atomic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,11 +526,7 @@ def forward_atomic_graph(
"""
import array_api_compat

if not self._graph_mapping_is_identity:
raise NotImplementedError(
"the graph route supports children sharing the parent "
"type_map only (no atype remapping)"
)
self._check_graph_mapping()
nmodels = len(self.models)
if self.weights == "sum":
weights = [1.0] * nmodels
Expand Down Expand Up @@ -562,6 +558,80 @@ def forward_atomic_graph(
energy = contrib if energy is None else energy + contrib
return {"energy": xp.astype(energy, graph.edge_vec.dtype)}

def forward_embedding_graph(
self,
graph: Any,
atype: Array,
node_mask: Array,
fparam: Array | None = None,
aparam: Array | None = None,
charge_spin: Array | None = None,
) -> dict[str, Array]:
"""Embeddings of the first descriptor-fitting child of the composition.

A composition such as a bridged DPA4 or DPA4C model holds one learned
descriptor-fitting child beside analytical terms. Its embeddings are
those of that child, which evaluates them on the same graph and counts
the nodes under the masks of both the composition and the child.

Parameters
----------
graph
neighbor graph for the local atoms (ghost-free).
atype
flat local atom types, clamped to valid types. N
node_mask
flat mask of the nodes the composition counts. N
fparam
frame parameter. nf x ndf
aparam
atomic parameter. N x nda
charge_spin
frame-level conditioning, forwarded to the child.

Returns
-------
dict[str, Array]
The embeddings of the child, see
:meth:`~deepmd.dpmodel.atomic_model.base_atomic_model.BaseAtomicModel.forward_common_embedding_graph`.

Raises
------
NotImplementedError
For children with remapped type maps, or when no child is a
descriptor-fitting model.
"""
self._check_graph_mapping()
for model in self.models:
if isinstance(model, DPAtomicModel):
return model.forward_common_embedding_graph(
Comment thread
OutisLi marked this conversation as resolved.
Resolved
graph,
atype,
fparam=fparam,
aparam=aparam,
charge_spin=charge_spin,
node_mask=node_mask,
)
raise NotImplementedError(
"this linear model has no descriptor-fitting child, so it provides "
"no embedding."
)

def _check_graph_mapping(self) -> None:
"""Require the children to share the type map of the composition.

Raises
------
NotImplementedError
If a child remaps the atom types, which the graph route does not
support.
"""
if not self._graph_mapping_is_identity:
raise NotImplementedError(
"the graph route supports children sharing the parent "
"type_map only (no atype remapping)"
)

def forward_atomic(
self,
extended_coord: Array,
Expand Down Expand Up @@ -852,9 +922,9 @@ def _agreed_default(
stay omitted, letting each child apply its own default, rather than
silently broadcasting one child's value to the others.

Children that do not consume the input (dimension 0, e.g. an
analytical bridging term) are excluded by the caller, so a learned
model composed with ZBL still inherits the learned default.
Children without the conditioning (e.g. an analytical bridging term)
are excluded by the caller, so a learned model composed with ZBL still
inherits the learned default.
"""
if not actives or not all(has(m) for m in actives):
return False, None
Expand All @@ -865,8 +935,12 @@ def _agreed_default(
return True, get(actives[0])

def _chg_spin_consumers(self) -> list:
"""Children that actually consume ``charge_spin``."""
return [m for m in self.models if m.get_dim_chg_spin() > 0]
"""Children conditioned on ``charge_spin``.

A compressed child carries its condition folded into frozen tables and
reads no input, yet it keeps the default that those tables hold.
"""
return [m for m in self.models if m.has_chg_spin_ebd()]
Comment thread
OutisLi marked this conversation as resolved.
Resolved

def _fparam_consumers(self) -> list:
"""Children that actually consume ``fparam``."""
Expand Down
Loading
Loading